Skip to content

The agent that grows with you

refactor(hermes_cli/web): compact git router (module-level imports, _probe_gh_auth), urllib_security, verify_cmd (_readiness_status), vercel_auth (_present inlined), seam docstrings

Tekniumad50496b758c
diff --git a/hermes_cli/urllib_security.py b/hermes_cli/urllib_security.py
index f9dac6e4292..ab48af84d67 100644
--- a/hermes_cli/urllib_security.py
+++ b/hermes_cli/urllib_security.py
@@ -19,26 +19,17 @@ logger = logging.getLogger(__name__)
# custom provider headers routinely carry credentials under arbitrary names.
_CROSS_ORIGIN_SAFE_HEADERS = frozenset({"accept", "user-agent"})
_DEFAULT_PORTS = {"http": 80, "https": 443}
-_CA_BUNDLE_ENV_VARS = (
- "HERMES_CA_BUNDLE",
- "SSL_CERT_FILE",
- "REQUESTS_CA_BUNDLE",
- "CURL_CA_BUNDLE",
-)
+_CA_BUNDLE_ENV_VARS = ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE")
def url_origin(url: str) -> tuple[str, str, int | None]:
"""Return a normalized (scheme, hostname, effective port) origin."""
parsed = urllib.parse.urlparse(url)
scheme = (parsed.scheme or "").lower()
- # Accessing ``parsed.port`` validates malformed/non-numeric ports. Let the
- # ValueError fail the request closed instead of collapsing it to a default.
+ # ``parsed.port`` raises ValueError on malformed ports — let that fail the
+ # request closed instead of collapsing it to a default.
port = parsed.port
- return (
- scheme,
- (parsed.hostname or "").lower().rstrip("."),
- port if port is not None else _DEFAULT_PORTS.get(scheme),
- )
+ return scheme, (parsed.hostname or "").lower().rstrip("."), port if port is not None else _DEFAULT_PORTS.get(scheme)
def _strip_headers(request, keep: frozenset[str]) -> None:
@@ -52,15 +43,10 @@ class SafeCredentialRedirectHandler(urllib.request.HTTPRedirectHandler):
"""Preserve request headers only while redirects stay on one origin."""
def __init__(
- self,
- original_url: str,
- *,
- cross_origin_safe_headers: Iterable[str] = _CROSS_ORIGIN_SAFE_HEADERS,
+ self, original_url: str, *, cross_origin_safe_headers: Iterable[str] = _CROSS_ORIGIN_SAFE_HEADERS
) -> None:
self._original_origin = url_origin(original_url)
- self._cross_origin_safe_headers = frozenset(
- str(name).lower() for name in cross_origin_safe_headers
- )
+ self._cross_origin_safe_headers = frozenset(str(name).lower() for name in cross_origin_safe_headers)
def redirect_request(self, req, fp, code, msg, headers, newurl):
# Let urllib enforce status/method semantics first (notably 307/308).
@@ -68,10 +54,9 @@ class SafeCredentialRedirectHandler(urllib.request.HTTPRedirectHandler):
if redirected is None:
return None
- resolved_url = urllib.parse.urljoin(req.full_url, newurl)
- if url_origin(resolved_url) != self._original_origin:
- # Use an allowlist rather than guessing credential header names.
- # normalize_extra_headers permits arbitrary secret-bearing names.
+ # Allowlist rather than guessing credential header names: normalize_extra_headers
+ # permits arbitrary secret-bearing names.
+ if url_origin(urllib.parse.urljoin(req.full_url, newurl)) != self._original_origin:
_strip_headers(redirected, self._cross_origin_safe_headers)
return redirected
@@ -79,12 +64,10 @@ class SafeCredentialRedirectHandler(urllib.request.HTTPRedirectHandler):
class _CrossOriginRequestSanitizer(urllib.request.BaseHandler):
"""Strip headers after installed request processors have run."""
- # Request processors run in ascending order. Keep this last so an installed
- # cookie/auth/instrumentation processor cannot re-add a secret after the
- # redirect handler sanitizes the new Request.
- # Infinity is greater than every finite handler order. If an installed
- # processor also uses infinity, stable sorting keeps this appended handler
- # after it, so sanitization still owns the final request boundary.
+ # Request processors run in ascending order; infinity keeps this last so an
+ # installed cookie/auth/instrumentation processor cannot re-add a secret after
+ # the redirect handler sanitized the new Request (stable sort keeps this
+ # appended handler after another infinity-ordered one).
handler_order = float("inf") # type: ignore[assignment]
def __init__(self, original_url: str) -> None:
@@ -101,8 +84,7 @@ class _CrossOriginRequestSanitizer(urllib.request.BaseHandler):
def _resolved_https_context() -> ssl.SSLContext | None:
"""Return the explicit CA context for Hermes-owned urllib openers."""
- ca_bundle = next(
- (value for name in _CA_BUNDLE_ENV_VARS if (value := os.getenv(name, "").strip())), "")
+ ca_bundle = next((value for name in _CA_BUNDLE_ENV_VARS if (value := os.getenv(name, "").strip())), "")
if ca_bundle:
ca_path = Path(ca_bundle).expanduser()
if ca_path.is_file():
@@ -111,26 +93,20 @@ def _resolved_https_context() -> ssl.SSLContext | None:
except (OSError, ssl.SSLError) as exc:
logger.warning(
"CA bundle could not be loaded from %s: %s — falling back to default certificates",
- ca_bundle,
- exc,
+ ca_bundle, exc,
)
else:
- logger.warning(
- "CA bundle path does not exist: %s — falling back to default certificates",
- ca_bundle,
- )
+ logger.warning("CA bundle path does not exist: %s — falling back to default certificates", ca_bundle)
if sys.platform != "darwin":
return None
-
try:
import certifi
return ssl.create_default_context(cafile=certifi.where())
except (ImportError, OSError, ssl.SSLError) as exc:
logger.warning(
- "Could not load certifi for urllib HTTPS verification: %s — falling back to default certificates",
- exc,
+ "Could not load certifi for urllib HTTPS verification: %s — falling back to default certificates", exc
)
return None
@@ -138,16 +114,14 @@ def _resolved_https_context() -> ssl.SSLContext | None:
def _secure_opener_from_installed_policy(original_url: str, *, ssl_context=None):
"""Clone the installed opener's handlers, replacing redirect policy only.
- With ``ssl_context`` the cloned HTTPS handler is bound to it so per-provider TLS settings
- (``ssl_ca_cert``/``ssl_verify``) apply. With None, Hermes-owned openers get an explicit CA
- default via ``_resolved_https_context``; an application-installed opener's TLS policy is
- preserved.
+ ``ssl_context`` rebinds the cloned HTTPS handler so per-provider TLS settings
+ (``ssl_ca_cert``/``ssl_verify``) apply; with None a Hermes-owned opener gets the explicit CA
+ default from ``_resolved_https_context`` and an application-installed opener keeps its TLS.
"""
installed = getattr(urllib.request, "_opener", None)
if installed is None:
context = _resolved_https_context()
- installed = urllib.request.build_opener(
- *([] if context is None else [urllib.request.HTTPSHandler(context=context)]))
+ installed = urllib.request.build_opener(*([] if context is None else [urllib.request.HTTPSHandler(context=context)]))
_https_handler_cls = getattr(urllib.request, "HTTPSHandler", None)
replace_https = ssl_context is not None and _https_handler_cls is not None
@@ -162,9 +136,8 @@ def _secure_opener_from_installed_policy(original_url: str, *, ssl_context=None)
handlers.append(SafeCredentialRedirectHandler(original_url))
handlers.append(_CrossOriginRequestSanitizer(original_url))
secured = urllib.request.build_opener(*handlers)
- # OpenerDirector injects addheaders after request processors, which would
- # bypass the sanitizer on redirects. Carry them on the initial request
- # instead, then leave the rebuilt opener's late-injection list empty.
+ # OpenerDirector injects addheaders after request processors (bypassing the
+ # sanitizer on redirects), so carry them on the initial request instead.
secured._hermes_initial_addheaders = list(getattr(installed, "addheaders", ()))
secured.addheaders = []
return secured
@@ -179,17 +152,12 @@ def open_credentialed_url(
):
"""Open a request without forwarding credentials across origins.
- The default preserves an application-installed opener's proxy, TLS, cookies, custom protocol
- handlers, and instrumentation while replacing its redirect handler. ``opener_factory`` is an
- explicit test seam; security is never disabled based on global ``urlopen`` identity.
-
- ``ssl_context`` (an ``ssl.SSLContext``) overrides the HTTPS handler's TLS policy for this
- request only.
+ Preserves an application-installed opener's proxy/TLS/cookies/handlers while replacing its
+ redirect handler. ``opener_factory`` is an explicit test seam (security is never disabled
+ based on global ``urlopen`` identity); ``ssl_context`` overrides TLS for this request only.
"""
if opener_factory is None:
- opener = _secure_opener_from_installed_policy(
- request.full_url, ssl_context=ssl_context
- )
+ opener = _secure_opener_from_installed_policy(request.full_url, ssl_context=ssl_context)
for name, value in getattr(opener, "_hermes_initial_addheaders", ()):
if not request.has_header(name):
request.add_header(name, value)
@@ -198,8 +166,4 @@ def open_credentialed_url(
return opener.open(request, timeout=timeout)
-__all__ = [
- "SafeCredentialRedirectHandler",
- "open_credentialed_url",
- "url_origin",
-]
+__all__ = ["SafeCredentialRedirectHandler", "open_credentialed_url", "url_origin"]
diff --git a/hermes_cli/vercel_auth.py b/hermes_cli/vercel_auth.py
index 4666d516e1e..1825f2f2273 100644
--- a/hermes_cli/vercel_auth.py
+++ b/hermes_cli/vercel_auth.py
@@ -16,19 +16,12 @@ class VercelAuthStatus:
detail_lines: tuple[str, ...]
-def _present(name: str) -> bool:
- return bool(os.getenv(name))
-
-
def describe_vercel_auth() -> VercelAuthStatus:
"""Return Vercel auth status without exposing secret values."""
+ present_token_vars = tuple(name for name in _TOKEN_TUPLE_VARS if os.getenv(name))
+ missing_token_vars = tuple(name for name in _TOKEN_TUPLE_VARS if not os.getenv(name))
- has_oidc = _present("VERCEL_OIDC_TOKEN")
- token_states = {name: _present(name) for name in _TOKEN_TUPLE_VARS}
- present_token_vars = tuple(name for name, present in token_states.items() if present)
- missing_token_vars = tuple(name for name, present in token_states.items() if not present)
-
- if has_oidc:
+ if os.getenv("VERCEL_OIDC_TOKEN"):
details = [
"mode: OIDC",
"active env: VERCEL_OIDC_TOKEN",
@@ -42,10 +35,7 @@ def describe_vercel_auth() -> VercelAuthStatus:
return VercelAuthStatus(
True,
"access token + project/team via VERCEL_TOKEN, VERCEL_PROJECT_ID, VERCEL_TEAM_ID",
- (
- "mode: access token",
- "active env: VERCEL_TOKEN, VERCEL_PROJECT_ID, VERCEL_TEAM_ID",
- ),
+ ("mode: access token", "active env: VERCEL_TOKEN, VERCEL_PROJECT_ID, VERCEL_TEAM_ID"),
)
if present_token_vars:
@@ -63,8 +53,6 @@ def describe_vercel_auth() -> VercelAuthStatus:
return VercelAuthStatus(
False,
"not configured",
- (
- "recommended: set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID",
- "development-only alternative: set VERCEL_OIDC_TOKEN",
- ),
+ ("recommended: set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID",
+ "development-only alternative: set VERCEL_OIDC_TOKEN"),
)
diff --git a/hermes_cli/verify_cmd.py b/hermes_cli/verify_cmd.py
index ec7c023f61d..dc30fc0b2d5 100644
--- a/hermes_cli/verify_cmd.py
+++ b/hermes_cli/verify_cmd.py
@@ -9,12 +9,7 @@ from pathlib import Path
def run_verify_command(args) -> int:
- from agent.verify import (
- load_or_detect,
- manifest_path,
- run_verify,
- save_manifest,
- )
+ from agent.verify import load_or_detect, manifest_path, run_verify, save_manifest
root = Path(getattr(args, "path", None) or ".").resolve()
if not root.is_dir():
@@ -23,14 +18,14 @@ def run_verify_command(args) -> int:
recipe, source = load_or_detect(root)
if recipe is None:
- message = (
- f"No recognizable project found at {root}.\n"
- f"Create {manifest_path(root)} to define a recipe manually."
- )
if args.json:
print(json.dumps({"ok": False, "error": "no-recipe", "root": str(root)}))
else:
- print(message, file=sys.stderr)
+ print(
+ f"No recognizable project found at {root}.\n"
+ f"Create {manifest_path(root)} to define a recipe manually.",
+ file=sys.stderr,
+ )
return 1
if source == "detected":
@@ -45,22 +40,13 @@ def run_verify_command(args) -> int:
print(f"Saved manifest: {path}")
if args.detect_only:
- payload = {"source": source, "recipe": recipe.to_dict()}
- print(json.dumps(payload, indent=None if args.json else 2))
+ print(json.dumps({"source": source, "recipe": recipe.to_dict()}, indent=None if args.json else 2))
return 0
- phases = None
- if args.phase:
- phases = tuple(args.phase)
-
+ phases = tuple(args.phase) if args.phase else None
result = run_verify(
- root,
- recipe,
- phases=phases,
- phase_timeout=args.timeout,
- ready_timeout=args.ready_timeout,
- skip_start=args.skip_start,
- port_override=args.port,
+ root, recipe, phases=phases, phase_timeout=args.timeout, ready_timeout=args.ready_timeout,
+ skip_start=args.skip_start, port_override=args.port,
)
_record_evidence(root, recipe, result, partial=bool(phases or args.skip_start))
@@ -76,10 +62,9 @@ def run_verify_command(args) -> int:
def _merge_project_facts_commands(root: Path, recipe) -> None:
- """Fold ``detect_project_facts`` verify commands into a detected recipe.
+ """Fold ``detect_project_facts`` verify commands into a detected recipe (best-effort union).
- Never applied to a saved manifest (the user-edited manifest is the source of truth) and never
- raises: this is a best-effort union.
+ Never applied to a saved manifest — the user-edited manifest is the source of truth.
"""
try:
from agent.coding_context import detect_project_facts
@@ -98,24 +83,16 @@ def _merge_project_facts_commands(root: Path, recipe) -> None:
def _record_evidence(root: Path, recipe, result, *, partial: bool) -> None:
"""Record the completed run into the verification evidence ledger.
- Best-effort and fail-silent: a ledger problem must never change the CLI's exit code or output.
- ``partial`` (an explicit ``--phase`` subset or ``--skip-start``) downgrades the scope to
- ``targeted`` so a partial pass is never presented as a full workspace green.
+ Fail-silent: a ledger problem must never change the CLI's exit code or output. ``partial``
+ (a ``--phase`` subset or ``--skip-start``) downgrades the scope to ``targeted`` so a partial
+ pass is never presented as a full workspace green.
"""
try:
from agent.verification_evidence import record_verify_run
- tails: list[str] = []
- for p in result.phases:
- if p.output_tail:
- tails.append(f"[{p.phase}] {p.command}\n{p.output_tail}")
+ tails = [f"[{p.phase}] {p.command}\n{p.output_tail}" for p in result.phases if p.output_tail]
if result.readiness is not None:
- r = result.readiness
- readiness_line = (
- f"[start] {recipe.start} -> "
- + (f"ready (HTTP {r.status_code})" if r.ready else f"not ready ({r.error or 'timeout'})")
- )
- tails.append(readiness_line)
+ tails.append(f"[start] {recipe.start} -> {_readiness_status(result.readiness)}")
record_verify_run(
root=root,
session_id=os.environ.get("HERMES_SESSION_ID"),
@@ -128,6 +105,10 @@ def _record_evidence(root: Path, recipe, result, *, partial: bool) -> None:
pass
+def _readiness_status(r) -> str:
+ return f"ready (HTTP {r.status_code})" if r.ready else f"not ready ({r.error or 'timeout'})"
+
+
def _print_human_report(recipe, source, result) -> None:
print(f"Recipe: {recipe.name} ({recipe.kind}) — source: {source}")
print()
@@ -141,11 +122,10 @@ def _print_human_report(recipe, source, result) -> None:
if result.readiness is not None:
r = result.readiness
- status = f"ready (HTTP {r.status_code})" if r.ready else f"not ready ({r.error or 'timeout'})"
print(f" {'start'.ljust(max(5, max((len(p.phase) for p in result.phases), default=5)))} "
f"{'PASS' if r.ready else 'FAIL':<7} {r.duration:6.1f}s {recipe.start}")
print()
- print(f"Readiness: {r.url} -> {status}")
+ print(f"Readiness: {r.url} -> {_readiness_status(r)}")
failed = [p for p in result.phases if not p.ok]
print()
diff --git a/hermes_cli/web_deps.py b/hermes_cli/web_deps.py
index 274f5a53e7b..68626ba2cfb 100644
--- a/hermes_cli/web_deps.py
+++ b/hermes_cli/web_deps.py
@@ -1,14 +1,9 @@
-"""Shared late-binding dependency seam for extracted dashboard routers.
+"""Late-binding dependency seam for extracted dashboard routers.
-``hermes_cli/web_server.py`` owns all dashboard runtime state and most helper
-functions the route handlers call. Extracted ``APIRouter`` modules under
-``hermes_cli/web_routers/`` cannot import it at module import time (web_server
-imports them to mount them — a cycle) and must not copy its state (tests
-``monkeypatch.setattr(web_server, "_helper", ...)`` and expect that to win).
-
-Design: **late binding, state stays in web_server.** ``late(name)`` returns a
-proxy that resolves ``hermes_cli.web_server.<name>`` *at call time*, so
-monkeypatched replacements and module state are never frozen at import time.
+``web_server`` owns all dashboard state/helpers; routers under ``web_routers/`` cannot
+import it at import time (web_server imports them to mount them — a cycle) and must not
+copy its state (tests ``monkeypatch.setattr(web_server, ...)`` and expect that to win).
+``late(name)`` / ``LateState(name)`` resolve ``web_server.<name>`` *at call time*.
"""
from __future__ import annotations
@@ -39,12 +34,9 @@ def late(name: str):
class LateState:
"""Live proxy for module-level state owned by ``web_server``.
- Forwards every operation the extracted handlers perform — attribute access,
- item get/set/del, iteration, membership, ``len``/truthiness, ``with``-blocks
- (locks), rich comparisons (numeric limits) — to ``web_server.<name>``
- resolved at operation time. Some of that state is defined *after* the
- router's ``include_router`` point, so even a late module import would not
- see it; this proxy does.
+ Forwards attribute/item access, iteration, membership, len/truthiness, ``with`` (locks)
+ and rich comparisons to ``web_server.<name>`` resolved at operation time — some state is
+ defined *after* the router's ``include_router`` point, so a late import would miss it.
"""
__slots__ = ("_name",)
diff --git a/hermes_cli/web_routers/__init__.py b/hermes_cli/web_routers/__init__.py
index 76fe5ca2a15..f8b1e3d52a4 100644
--- a/hermes_cli/web_routers/__init__.py
+++ b/hermes_cli/web_routers/__init__.py
@@ -1,8 +1,6 @@
"""Extracted APIRouter modules for the dashboard web server.
-Each module exposes ``router = APIRouter()`` (profiles additionally exposes
-``sessions_router``) and is mounted by ``hermes_cli.web_server`` at the exact
-point in module execution where the routes were originally registered, so
-route-matching order is unchanged. Shared web_server helpers/state are
-reached through the late-binding seam in ``hermes_cli.web_deps``.
+Each exposes ``router`` (profiles also ``sessions_router``), mounted by ``web_server`` at the
+point the routes were originally registered so match order is unchanged. Shared helpers/state
+come through the late-binding seam in ``hermes_cli.web_deps``.
"""
diff --git a/hermes_cli/web_routers/_common.py b/hermes_cli/web_routers/_common.py
index 15eba005bad..a32f7c3e278 100644
--- a/hermes_cli/web_routers/_common.py
+++ b/hermes_cli/web_routers/_common.py
@@ -1,10 +1,6 @@
-"""Shared plumbing for the extracted dashboard routers.
-
-Everything here is a thin wrapper over the late-binding seam in
-:mod:`hermes_cli.web_deps`: web_server still owns the helpers and state, and
-every access resolves at call time so ``monkeypatch.setattr(web_server, ...)``
-stays authoritative.
-"""
+"""Shared plumbing for the extracted dashboard routers — thin wrappers over the
+late-binding seam in :mod:`hermes_cli.web_deps` (web_server owns helpers/state;
+every access resolves at call time so ``monkeypatch.setattr(web_server, ...)`` wins)."""
from __future__ import annotations
@@ -51,11 +47,9 @@ async def scoped_to_thread(profile: Optional[str], fn: Callable[[], Any]) -> Any
def http_failure(log_msg: str, status: int, prefix: Optional[str] = None, *, detail: Optional[str] = None):
"""Map unexpected exceptions to an ``HTTPException``.
- ``HTTPException`` passes through untouched; anything else is logged with
- ``log_msg`` (full traceback) first, then re-raised as
- ``HTTPException(status, f"{prefix}: {exc}")`` or — when ``detail`` is
- given instead — ``HTTPException(status, detail)`` (fixed message, the
- exception text is only in the log).
+ ``HTTPException`` passes through; anything else is logged with ``log_msg`` (traceback),
+ then re-raised as ``HTTPException(status, f"{prefix}: {exc}")`` — or ``detail`` when given
+ (fixed message, exception text only in the log).
"""
try:
yield
diff --git a/hermes_cli/web_routers/git.py b/hermes_cli/web_routers/git.py
index e5d0e25486c..b775cc066f4 100644
--- a/hermes_cli/web_routers/git.py
+++ b/hermes_cli/web_routers/git.py
@@ -1,40 +1,37 @@
-"""Git dashboard routes — thin executor-offloaded wrappers over ``web_git``
-(``_git_op`` / ``_git_path`` live in web_server, reached via the late seam)."""
+"""Git dashboard routes — the remote half of the desktop coding rail + review pane.
+
+The desktop runs these as Electron-local git; over a remote gateway that's the wrong
+filesystem, so they are mirrored here with the same auth gate + path hardening as
+/api/fs. Logic lives in ``hermes_cli.web_git``; these are thin executor-offloaded
+wrappers (git/gh can block).
+"""
import asyncio
+import shutil
+import subprocess
+import time
from typing import Optional
-from fastapi import APIRouter
+from fastapi import APIRouter, HTTPException
from hermes_cli import web_git as _web_git
from hermes_cli.web_deps import late
from hermes_cli.web_models import (
- GitPathBody,
- GitFileBody,
+ GitBranchSwitchBody,
GitCommitBody,
+ GitFileBody,
+ GitPathBody,
GitPrListBody,
GitWorktreeAddBody,
GitWorktreeRemoveBody,
- GitBranchSwitchBody,
)
-from fastapi import HTTPException
router = APIRouter()
-# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative.
+# web_server helper, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative.
_fs_path = late("_fs_path")
-# ---------------------------------------------------------------------------
-# Git ops — the remote half of the desktop coding rail + review pane.
-#
-# The desktop runs these as Electron-local git on the user's machine; over a
-# remote gateway that's the wrong filesystem, so we mirror them here (same auth
-# gate + path hardening as /api/fs). Logic lives in ``hermes_cli.web_git``;
-# these are thin, executor-offloaded wrappers (git/gh can block).
-# ---------------------------------------------------------------------------
-
-
async def _git_op(fn, *args):
"""Run a (blocking) git op off the event loop; map a failed mutation to 400."""
loop = asyncio.get_running_loop()
@@ -48,53 +45,44 @@ def _git_path(path: str) -> str:
return str(_fs_path(path))
-
@router.get("/api/git/status")
async def git_status_route(path: str):
return await _git_op(_web_git.repo_status, _git_path(path))
-# Cached `gh auth status` for the desktop composer's GitHub suggestion pill.
-# GitHub deliberately has NO MCP catalog entry (hosted MCP needs a per-host
-# OAuth app; the gh-CLI skills are the better integration), so the pill offers
-# the `/github-auth` skill — only to users who aren't already authenticated.
-
+# Cached `gh auth status` for the desktop composer's GitHub suggestion pill. GitHub
+# deliberately has NO MCP catalog entry (hosted MCP needs a per-host OAuth app; the
+# gh-CLI skills are the better integration), so the pill offers `/github-auth` —
+# only to users who aren't already authenticated.
_GH_AUTH_TTL_S = 300.0
_gh_auth_cache: Optional[tuple] = None # (monotonic_ts, payload)
+def _probe_gh_auth() -> dict:
+ gh = shutil.which("gh")
+ if not gh:
+ return {"available": False, "authenticated": False}
+ try:
+ # Exits 0 when at least one host is logged in; DEVNULL stdin guards against any prompt.
+ proc = subprocess.run(
+ [gh, "auth", "status"],
+ stdin=subprocess.DEVNULL,
+ capture_output=True,
+ timeout=10,
+ )
+ return {"available": True, "authenticated": proc.returncode == 0}
+ except Exception:
+ return {"available": True, "authenticated": False}
+
+
@router.get("/api/git/gh-auth")
async def gh_auth_status_route(refresh: bool = False):
"""``{"available", "authenticated"}`` for the `gh` CLI; cached 5 min
(``refresh=true`` bypasses so the pill withdraws right after a login)."""
global _gh_auth_cache
- import asyncio
- import time
-
if not refresh and _gh_auth_cache and time.monotonic() - _gh_auth_cache[0] < _GH_AUTH_TTL_S:
return _gh_auth_cache[1]
-
- def _probe() -> dict:
- import shutil
- import subprocess
-
- gh = shutil.which("gh")
- if not gh:
- return {"available": False, "authenticated": False}
- try:
- # `gh auth status` exits 0 when at least one host is logged in.
- # Never interactive; DEVNULL stdin guards against any prompt.
- proc = subprocess.run(
- [gh, "auth", "status"],
- stdin=subprocess.DEVNULL,
- capture_output=True,
- timeout=10,
- )
- return {"available": True, "authenticated": proc.returncode == 0}
- except Exception:
- return {"available": True, "authenticated": False}
-
- payload = await asyncio.to_thread(_probe)
+ payload = await asyncio.to_thread(_probe_gh_auth)
_gh_auth_cache = (time.monotonic(), payload)
return payload
@@ -185,12 +173,7 @@ async def git_create_pr_route(body: GitPathBody):
async def git_worktree_add_route(body: GitWorktreeAddBody):
options = {
key: value
- for key, value in {
- "name": body.name,
- "branch": body.branch,
- "base": body.base,
- "existingBranch": body.existingBranch,
- }.items()
+ for key, value in body.model_dump(include={"name", "branch", "base", "existingBranch"}).items()
if value
}
return await _git_op(_web_git.worktree_add, _git_path(body.path), options)