Skip to content

Self-improving AI Employees for everyone

feat(github): GitHub node — gh CLI wrapper, CLI-owned auth (Stripe pattern)

trohitg70b92efec92e
diff --git a/CLAUDE.md b/CLAUDE.md
index 04599b67..202ebd36 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -28,6 +28,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Email Service](./docs-internal/email_service.md)** | IMAP/SMTP integration via Himalaya CLI with EmailService orchestrator, provider presets, custom credential fallback, and polling triggers |
| **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. |
| **[Vercel Service](./docs-internal/vercel_service.md)** | Vercel CLI integration — `vercelAction` (deploy / inspect / list + `custom` CLI passthrough; AI tool `vercel`). Second reference for the CLI-managed-auth pattern: the **device-flow variant** (`vercel login` is one blocking process — no two-step `--complete`; direct `create_subprocess_exec` + chunk-based banner read for the code-embedding URL, pumps drain pipes for the process lifetime, success gate = auth.json mtime advance + sniff). Dual auth: optional `vercel_token` field (injected as `VERCEL_TOKEN` env, never argv) OR CLI login with marker tokens. All invocations pin `--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR` isolation idiom). npm install into the shared packages tree (pinned version). First-deploy project guard raises `NodeUserError` instead of letting Vercel derive an invalid name from the workspace dir. Shipped with the generic OAuthConnect change: Login gates on **required** fields only, so optional fields never block CLI login. |
+| **[GitHub Service](./docs-internal/github_service.md)** | GitHub CLI integration — `githubAction` (repo_clone / pr_create / pr_list / pr_merge / issue_create / issue_list + `custom` passthrough; AI tool `github`). **Strict Stripe pattern: the gh CLI owns its own auth** — no token stored/injected by MachinaOs, no auth pre-flight (gh's own error surfaces), marker OAuth row for the modal badge, fieldless catalogue entry. Login = spawned `gh auth login --hostname github.com --git-protocol https --web` — source-verified: headless takes the `isInteractive=false` branch (no Press-Enter), prints one-time code + `github.com/login/device` URL on stderr; the modal shows the code via the generic `verificationCode` plumbing (`useCredentialPanel` → `OAuthConnect`). `login_env()` strips `GH_TOKEN`/`GITHUB_TOKEN` (login aborts otherwise). Success gate = `gh auth status` exit 0, then best-effort **`gh auth setup-git`** (official bridge — the future git node needs zero auth code). gh binary: **project-local, pooch-driven** (temporal `_install.py` idiom) — pinned release under `package_dir("gh")`, system gh never consulted (auth state still shared: gh config paths are user-level). Palette group `vcs`. |
| **[CI/CD Pipeline](./docs-internal/ci_cd.md)** | GitHub Actions workflows, predeploy validation, release publishing, and composite setup action |
| **[Performance](./docs-internal/performance.md)** | Cold-start measurements (Application startup complete 2.90 s warm, first WS connect 8.29 s) + per-phase timeline + optimisation history (lazy LangChain imports, esbuild sidecar bundle, scoped `compileall`, PartySocket reconnect, TanStack Query auth bootstrap, `manualChunks`) + bottleneck inventory + reproduction commands + anti-patterns to never reintroduce. Pairs with the build-time pipeline doc below. |
| **[Release Build Pipeline](./docs-internal/release_build_pipeline.md)** | npm-distribution build pipeline: `tsgo` for type-check (5× faster than tsc), Vite `manualChunks` + `target: 'es2022'`, esbuild Node.js sidecar bundle (drops `tsx` interpreter cost), `python -O -m compileall` for project-source bytecode (excludes `.venv/`, `tests/`). Single source of truth for the bytecode-compile path list: `machina.commands.build.COMPILEALL_SOURCE_DIRS`. |
@@ -490,7 +491,7 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Python (FastAPI + Pydantic plugins) + React/TypeScript frontend + Node.js subprocess for JS/TS code execution.
-- **Backend NodeSpec is the single source of truth.** Plugins live in [`server/nodes/<group>/<name>.py`](./server/nodes/) and auto-register via `BaseNode.__init_subclass__`. Authoritative node count is whatever globs out of `server/nodes/**/*.py` (excluding `_*.py` helpers and `__init__.py`); folders cover agent / model / android / google / whatsapp / twitter / telegram / social / email / search / scraper / document / code / filesystem / proxy / location / chat / text / scheduler / trigger / tool / utility / workflow / skill / browser / stripe / vercel.
+- **Backend NodeSpec is the single source of truth.** Plugins live in [`server/nodes/<group>/<name>.py`](./server/nodes/) and auto-register via `BaseNode.__init_subclass__`. Authoritative node count is whatever globs out of `server/nodes/**/*.py` (excluding `_*.py` helpers and `__init__.py`); folders cover agent / model / android / google / whatsapp / twitter / telegram / social / email / search / scraper / document / code / filesystem / proxy / location / chat / text / scheduler / trigger / tool / utility / workflow / skill / browser / stripe / vercel / github.
- **WebSocket-first frontend-backend communication.** Authoritative handler count is the size of the `MESSAGE_HANDLERS` dict in [`server/routers/websocket.py`](./server/routers/websocket.py) plus plugin-registered handlers via `services.ws_handler_registry`. Don't hand-maintain the count in this doc — it drifts on every plugin add.
- **Plugin-first architecture (Wave 11).** One file = one node. `services/handlers/` shrank from 12.8K → 1.1K LOC across 16 → 4 files. Live invariant total via `pytest --collect-only`.
@@ -613,7 +614,7 @@ The project uses WebSocket as the primary communication method between frontend
> The authoritative, per-node reference is the backend plugin registry plus the per-node "logic-flow" cards under [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) (one card per node, grouped by category, with handles / params / outputs / side-effects / edge-cases). Live node list = the plugin registry (one folder per node under `server/nodes/<group>/`, ~118 node types today; a bare `__init__.py` glob also counts the 26 group packages); live total via `pytest --collect-only`. Do NOT maintain a per-node catalogue here — it drifts on every plugin add.
-Node groups (palette categories): agent, model, skill, tool, trigger, workflow, search, google, android, whatsapp, telegram, twitter, social, email, proxy, chat, scheduler, text, code, document, location, utility, browser, scraper, filesystem, stripe, vercel. See [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) for the card index.
+Node groups (palette categories): agent, model, skill, tool, trigger, workflow, search, google, android, whatsapp, telegram, twitter, social, email, proxy, chat, scheduler, text, code, document, location, utility, browser, scraper, filesystem, stripe, vercel, github (palette group `vcs`). See [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) for the card index.
## Backend Services
diff --git a/docs-internal/github_service.md b/docs-internal/github_service.md
new file mode 100644
index 00000000..48122782
--- /dev/null
+++ b/docs-internal/github_service.md
@@ -0,0 +1,119 @@
+# GitHub Service
+
+Self-contained plugin at [`server/nodes/github/`](../server/nodes/github/)
+wrapping the official **GitHub CLI** (`gh`, pinned release in
+`_install.py`). One dual-purpose node — `githubAction` (workflow node +
+AI tool `github`) — with typed core operations (`repo_clone`,
+`pr_create`, `pr_list`, `pr_merge`, `issue_create`, `issue_list`) plus
+a `custom` passthrough covering the entire gh surface (`gh api`, runs,
+releases, gists, repo administration).
+
+**Auth model: the gh CLI owns its own auth** — the Stripe CLI pattern,
+strictly. MachinaOs never stores, reads, or injects a token:
+
+- `gh auth login` puts the token in the **system credential store**;
+ ops read it from there (or from an ambient `GH_TOKEN` env var, per
+ gh's own documented precedence — we don't touch it).
+- The credentials modal's connected badge is a synthetic
+ `cli-managed` **marker OAuth row** (`store_oauth_tokens(provider="github", ...)`),
+ written only after `gh auth status` confirms a live session and
+ removed on logout — exactly like Stripe.
+- There is **no auth pre-flight** in the node: gh's own "To get
+ started… run: gh auth login" error surfaces verbatim through the
+ `NodeUserError` wrap.
+- The **git node (future, separate folder)** needs zero auth code:
+ login success runs the official `gh auth setup-git`, which
+ configures git to use gh as its credential helper.
+
+## File map
+
+| File | Role |
+|---|---|
+| `__init__.py` | `register_ws_handlers(WS_HANDLERS)` + `register_output_schema("githubAction", …)`; node auto-registers on import |
+| `github_action.py` | `GitHubActionNode(ActionNode)`, `usable_as_tool=True`, `tool_name="github"`, gmail-style multi-`@Operation` dispatch; `_run` = `ensure_gh_cli()` → `run_cli_command(env=gh_env(), cwd=…)` → non-zero exit → `NodeUserError` (stderr tail) |
+| `_handlers.py` | `github_login` / `github_logout` / `github_status`; login-banner parser; marker + broadcast helpers |
+| `_service.py` | `gh_env()` (automation baseline: `GH_PROMPT_DISABLED=1`, `NO_COLOR=1`, `GH_NO_UPDATE_NOTIFIER=1`, `GH_PAGER=cat`), `login_env()` (see below), `resolve_gh_light()` (no-download binary probe), `cli_logged_in()` (`gh auth status` exit 0), `resolve_repo_path()` (workspace-relative cwd, vercel idiom) |
+| `_install.py` | `ensure_gh_cli()` — **project-local, pooch-driven** (mirrors `services/temporal/_install.py`, the repo's shared binary-fetch pattern): pinned release extracted under `package_dir("gh")` via `pooch.retrieve` (caching + Unzip/Untar handled by the library). The system-global gh is never consulted; gh's user-level config/credential-store is shared either way, so terminal `gh auth login` sessions remain visible. Note gh's `macOS`-capitalized zip assets |
+| `_credentials.py` | `GitHubCredential` thin marker (`auth="custom"`, `resolve()` → `{}` — nothing to resolve) |
+| `meta.json` | Node color. No co-located `icon.svg` — the icon is the official brand glyph via `visuals.json: {"githubAction": {"icon": "lobehub:Github", "skill": "github-skill"}}` |
+
+Paired skill: [`server/skills/github/github-skill/SKILL.md`](../server/skills/github/github-skill/SKILL.md).
+Palette group: `vcs` ("Version Control", registered in `groups.py`;
+the future git node joins it from its own folder — same-group,
+different-folder is established practice, e.g. `social` spans three
+folders).
+
+## The login flow (source-verified against gh's own code)
+
+`github_login` spawns::
+
+ gh auth login --hostname github.com --git-protocol https --web
+
+Facts from `internal/authflow/flow.go` + `pkg/cmd/auth/login/login.go`
++ `cli/oauth` that the handler is built on:
+
+1. github.com always gets the **device flow** (`DetectFlow` tries it
+ first; the localhost-callback webapp flow is only an
+ unsupported-grant fallback).
+2. With **no TTY** the flow takes the `isInteractive=false` branch —
+ **no "Press Enter" block** — and prints to **stderr**:
+ `! First copy your one-time code: XXXX-XXXX` then
+ `Open this URL to continue in your web browser: https://github.com/login/device`,
+ then polls until the user authorises.
+3. `gh auth login` **aborts when `GH_TOKEN`/`GITHUB_TOKEN` is set**
+ ("The value of the … environment variable is being used for
+ authentication"). Hence `login_env()` = `gh_env()` minus both
+ token vars minus `GH_PROMPT_DISABLED` — used for login, status,
+ and logout so gh consults its OWN credential store.
+
+Handler mechanics: chunk-based banner reader (no `readline()` —
+spinner `\r` frames; pumps outlive the call so gh never blocks on a
+full pipe during its ~15-minute poll), parses the code + device URL,
+returns `{success, url, verification_code}` — the modal opens the URL
+and **displays the one-time code** (the generic `verificationCode`
+plumbing in `useCredentialPanel` / `OAuthConnect`; GitHub's device
+page cannot pre-fill the code). A response-budget shield (~22 s)
+returns a pending message if a cold gh download eats the window
+(vercel precedent). Background completion: `proc.wait()` ≤ 600 s →
+gate on `cli_logged_in()` (exit codes alone are never trusted — Stripe
+precedent) → best-effort `gh auth setup-git` → marker +
+`credential.oauth.connected` broadcast.
+
+`github_logout`: `gh auth logout --hostname github.com` (best-effort)
+→ remove marker → `credential.oauth.disconnected`.
+`github_status`: `{connected: cli_logged_in()}` — no side effects.
+Terminal logins (`gh auth login` run by the user) are first-class: ops
+and status see the same gh session; only the modal badge waits for a
+marker written via the modal's own Login.
+
+## Operations
+
+| Op | argv shape | Notes |
+|---|---|---|
+| `repo_clone` | `repo clone <repo> [dir]` | cwd required (workspace default); 600 s timeout |
+| `pr_create` | `pr create [--repo O/R] --title … --body … [--base] [--head] [--draft] \| --fill` | New PR URL from stdout → `url` |
+| `pr_list` | `pr list [--repo O/R] --state S --limit N --json <fields>` | Parsed JSON in `result` |
+| `pr_merge` | `pr merge <pr> [--repo O/R] --squash\|--merge\|--rebase [--delete-branch]` | |
+| `issue_create` | `issue create [--repo O/R] --title … --body … [--label …]…` | URL → `url` |
+| `issue_list` | `issue list [--repo O/R] --state S --limit N --json <fields>` | `merged` state coerced to `all` |
+| `custom` | verbatim after `gh ` (shlex-split) | cwd = `path`/workspace when available; `gh api` returns parsed JSON |
+
+## Tests
+
+[`server/tests/test_github_plugin.py`](../server/tests/test_github_plugin.py):
+env builders (ambient-token passthrough for ops, stripping for login),
+banner parser against the source-verified strings, pinned release
+asset map + member paths, op argv builders, gh-error-surfaces-verbatim
+(and `test_node_has_no_auth_preflight` locking the Stripe-strict
+no-pre-flight contract), login budget/fast-path, marker + broadcast +
+`setup-git` introspection, fieldless catalogue shape, assets. Plus the
+generic `test_plugin_contract.py` / `test_plugin_self_containment.py`
+suites (`github` is in `_MIGRATED_PLUGINS` + `_PLUGINS_WITH_HANDLERS`).
+
+## Runtime caveat
+
+gh issue #12925 reports that on some gh versions the `--web` flow may
+not begin polling until the browser step is acknowledged; the pinned
+version should be sanity-checked on bump (the failure mode is benign —
+login completes but the background gate logs a warning until the user
+authorises).
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index c26b061a..508108ea 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -13,7 +13,8 @@
"scrapers": { "label": "Scrapers", "order": 7 },
"services": { "label": "Services", "order": 8 },
"payments": { "label": "Payments", "order": 9 },
- "deployment": { "label": "Deployment", "order": 10 }
+ "deployment": { "label": "Deployment", "order": 10 },
+ "developer": { "label": "Developer Tools", "order": 11 }
},
"providers": {
@@ -530,6 +531,21 @@
}
],
"instructions": "Two independent auth paths: click 'Login with Vercel' for the browser device flow (the CLI is auto-installed via npm and stores its auth state under MachinaOs's data directory), or paste an access token above for headless use."
+ },
+
+ "github": {
+ "name": "GitHub",
+ "category": "developer",
+ "category_label": "Developer Tools",
+ "color": "dracula.purple",
+ "kind": "oauth",
+ "icon_ref": "lobehub:Github",
+ "ws": {
+ "login": "github_login",
+ "logout": "github_logout",
+ "status": "github_status"
+ },
+ "instructions": "Click 'Login with GitHub' — the gh CLI (auto-installed) opens github.com/login/device in your browser and the one-time code is shown here. The token is stored by gh in your system credential store; MachinaOs never keeps it. After login, 'gh auth setup-git' runs so git remotes authenticate too. Alternative: run 'gh auth login' (or pipe a Personal Access Token to 'gh auth login --with-token') in a terminal on this machine."
}
}
}
diff --git a/server/nodes/README.md b/server/nodes/README.md
index 15153901..b511be10 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -127,6 +127,7 @@ skill/ — simpleMemory / masterSkill
browser/ — browser (agent-browser CLI)
stripe/ — Stripe (CLI passthrough action + signed-webhook trigger)
vercel/ — Vercel (CLI deploy / inspect / list / custom passthrough)
+github/ — GitHub (gh CLI: clone / PRs / issues / custom; palette group "vcs")
```
---
diff --git a/server/nodes/github/__init__.py b/server/nodes/github/__init__.py
new file mode 100644
index 00000000..6ed5883e
--- /dev/null
+++ b/server/nodes/github/__init__.py
@@ -0,0 +1,28 @@
+"""Plugin for the 'vcs' palette group — GitHub via the gh CLI.
+
+Self-contained CLI-managed-auth plugin (Stripe pattern): the gh CLI
+owns its auth end-to-end — ``gh auth login --web`` driven from the
+credentials modal (or the user's own terminal), token in the system
+credential store, a synthetic ``cli-managed`` marker OAuth row for the
+catalogue badge. MachinaOs never stores or injects a token. On login
+success ``gh auth setup-git`` configures git's credential helper (the
+official bridge), so a future git node needs zero auth code.
+"""
+
+from __future__ import annotations
+
+from services.node_output_schemas import register_output_schema
+from services.ws_handler_registry import register_ws_handlers
+
+from ._credentials import GitHubCredential
+from ._handlers import WS_HANDLERS
+from .github_action import GitHubActionNode, GitHubActionOutput
+
+register_ws_handlers(WS_HANDLERS)
+register_output_schema("githubAction", GitHubActionOutput)
+
+__all__ = [
+ "GitHubCredential",
+ "GitHubActionNode",
+ "WS_HANDLERS",
+]
diff --git a/server/nodes/github/_credentials.py b/server/nodes/github/_credentials.py
new file mode 100644
index 00000000..86cd4ffa
--- /dev/null
+++ b/server/nodes/github/_credentials.py
@@ -0,0 +1,28 @@
+"""GitHub credential — thin marker (Stripe idiom).
+
+The gh CLI manages its own auth state (system credential store,
+populated by ``gh auth login`` and cleared by ``gh auth logout``).
+MachinaOs stores no token — the credentials modal's connected badge is
+driven by the synthetic ``cli-managed`` marker OAuth row written by
+``_handlers.py`` after a successful login.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from services.plugin.credential import Credential
+
+
+class GitHubCredential(Credential):
+ id = "github"
+ display_name = "GitHub"
+ category = "Developer Tools"
+ auth = "custom"
+ docs_url = "https://cli.github.com"
+
+ @classmethod
+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
+ """Nothing to resolve — auth lives in the gh CLI's own
+ credential store."""
+ return {}
diff --git a/server/nodes/github/_handlers.py b/server/nodes/github/_handlers.py
new file mode 100644
index 00000000..c59148e5
--- /dev/null
+++ b/server/nodes/github/_handlers.py
@@ -0,0 +1,304 @@
+"""GitHub WebSocket handlers — the gh CLI owns its own auth (Stripe
+CLI pattern).
+
+``github_login`` spawns gh's official browser login::
+
+ gh auth login --hostname github.com --git-protocol https --web
+
+Source-verified behavior (gh ``internal/authflow/flow.go``): with no
+TTY the flow takes the ``isInteractive=false`` branch — no "Press
+Enter" block — and prints to **stderr**::
+
+ ! First copy your one-time code: XXXX-XXXX
+ Open this URL to continue in your web browser: https://github.com/login/device
+
+then polls GitHub until the user authorises. The handler parses those
+two lines, returns ``{success, url, verification_code}`` (the modal
+opens the url and displays the code), and a background task awaits the
+poll. Success gate: ``gh auth status`` exit 0. On success we run the
+official ``gh auth setup-git`` bridge (configures git to use gh as
+credential helper — the future git node needs zero auth code), fetch
+the account identity via ``gh api user`` (so the modal shows
+"Connected as <login>" through the catalogue's ``account_label``, same
+as Claude Code), write the synthetic ``cli-managed`` marker OAuth row
+(flips the catalogue's ``stored`` badge), and broadcast the generic
+catalogue-invalidation event. Marker + broadcast plumbing is the
+shared :mod:`services.cli_agent._cli_auth` module (claude/codex/github
+all use it).
+
+MachinaOs never stores or reads the actual token — it stays in gh's
+system credential store.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import re
+from typing import Any, Dict, List, Optional, Tuple
+
+from fastapi import WebSocket
+
+from core.logging import get_logger
+from services.cli_agent._cli_auth import broadcast_credential_event, mark_logged_in, mark_logged_out
+from services.events import run_cli_command
+
+from ._install import ensure_gh_cli
+from ._service import cli_logged_in, login_env
+
+logger = get_logger(__name__)
+
+_LOGIN_ARGS = ["auth", "login", "--hostname", "github.com", "--git-protocol", "https", "--web"]
+_LOGIN_TIMEOUT_SECONDS = 600
+# How long to wait for the one-time code / device URL on the CLI's
+# output before giving up on this attempt.
+_BANNER_DEADLINE_SECONDS = 20
+# The frontend drops WS requests after 30s. A first-ever login pays a
+# cold gh download inside this handler — answer within this budget no
+# matter what and let the flow continue in the background.
+_RESPONSE_BUDGET_SECONDS = 22
+
+# Source-verified banner shapes (authflow/flow.go format strings).
+_CODE_RE = re.compile(r"one-time code:\s*([A-Z0-9]{4}-[A-Z0-9]{4})")
+_URL_RE = re.compile(r"https://\S*?/login/device\S*")
+
+
+async def _fetch_account(binary: str) -> Tuple[Optional[str], Optional[str]]:
+ """``(login, name)`` of the authenticated user via ``gh api user``
+ — feeds the catalogue's ``account_label`` ("Connected as <login>",
+ same surface Claude Code uses). Best-effort: ``(None, None)`` on
+ any failure."""
+ result = await run_cli_command(
+ binary=binary,
+ argv=["api", "user"],
+ timeout=15.0,
+ env=login_env(),
+ )
+ info = result.get("result")
+ if not (result.get("success") and isinstance(info, dict)):
+ logger.debug("[GitHub] account fetch failed (non-fatal): %s", result.get("error"))
+ return None, None
+ return info.get("login"), info.get("name")
+
+
+# Strong refs for fire-and-forget tasks — asyncio holds only weak refs
+# (the documented discard-set pattern from the asyncio docs).
+_background_tasks: set = set()
+
+
+def _spawn_background(coro) -> asyncio.Task:
+ task = asyncio.create_task(coro)
+ _background_tasks.add(task)
+ task.add_done_callback(_background_tasks.discard)
+ return task
+
+
+def parse_login_banner(text: str) -> Optional[tuple[str, Optional[str]]]:
+ """``(device_url, one_time_code)`` once the URL has appeared in the
+ accumulated output; ``None`` while still waiting. The code is
+ printed BEFORE the URL (flow.go order), so when the URL is present
+ the code — if any — is already in the buffer."""
+ url_m = _URL_RE.search(text)
+ if not url_m:
+ return None
+ code_m = _CODE_RE.search(text)
+ return url_m.group(0).rstrip(".,;)'\""), code_m.group(1) if code_m else None
+
+
+async def _read_login_banner(proc: asyncio.subprocess.Process) -> tuple[Optional[tuple[str, Optional[str]]], List[str]]:
+ """Read the login process's early output until the device URL shows
+ up (or deadline / EOF). Chunk-based, not ``readline()`` — spinner
+ frames repaint via ``\\r`` with no newline. The pumps deliberately
+ OUTLIVE this function: they keep draining both pipes for the
+ process lifetime so gh never blocks on a full pipe buffer during
+ its ~15-minute poll; only the first 32 KiB is retained for parsing."""
+ buf: List[str] = []
+ buf_len = 0
+ new_data = asyncio.Event()
+
+ async def pump(stream: Optional[asyncio.StreamReader]) -> None:
+ nonlocal buf_len
+ if stream is None:
+ new_data.set()
+ return
+ while True:
+ chunk = await stream.read(4096)
+ if not chunk:
+ break
+ if buf_len < 32768:
+ text = chunk.decode(errors="replace")
+ buf.append(text)
+ buf_len += len(text)
+ new_data.set()
+ new_data.set()
+
+ pumps = [_spawn_background(pump(proc.stdout)), _spawn_background(pump(proc.stderr))]
+
+ parsed: Optional[tuple[str, Optional[str]]] = None
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + _BANNER_DEADLINE_SECONDS
+ while True:
+ parsed = parse_login_banner("".join(buf))
+ if parsed is not None or all(t.done() for t in pumps):
+ break
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ break
+ new_data.clear()
+ try:
+ await asyncio.wait_for(new_data.wait(), timeout=remaining)
+ except asyncio.TimeoutError:
+ break
+
+ tail = [ln.strip() for ln in "".join(buf).splitlines() if ln.strip()]
+ return parsed, tail
+
+
+async def _start_login_flow() -> Dict[str, Any]:
+ """Install (if needed) + spawn gh's browser login + parse the
+ banner + schedule completion. Never raises — returns the WS
+ response dict."""
+ try:
+ try:
+ binary = str(await ensure_gh_cli())
+ except Exception as e:
+ logger.warning("[GitHub] gh CLI install failed: %s", e)
+ return {
+ "success": False,
+ "error": f"gh CLI install failed ({e}). Manual install: https://cli.github.com",
+ }
+
+ # stdin=PIPE left un-written: headless gh skips the Press-Enter
+ # prompt entirely (isInteractive=false branch), but a pipe keeps
+ # any stray stdin read from seeing instant EOF.
+ proc = await asyncio.create_subprocess_exec(
+ binary,
+ *_LOGIN_ARGS,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=login_env(),
+ )
+
+ parsed, lines = await _read_login_banner(proc)
+ if parsed is None:
+ proc.kill()
+ banner = " | ".join(lines[-5:]) or "(no output)"
+ logger.warning("[GitHub] login banner had no device URL within %ss: %s", _BANNER_DEADLINE_SECONDS, banner)
+ return {
+ "success": False,
+ "error": (
+ f"Could not start gh's browser login. CLI said: {banner} — "
+ "you can also run 'gh auth login' in a terminal on this machine."
+ ),
+ }
+
+ url, code = parsed
+ logger.info(
+ "[GitHub] device-flow URL issued (code=%s) — opening on frontend; awaiting browser confirmation in background (timeout=%ss)",
+ code,
+ _LOGIN_TIMEOUT_SECONDS,
+ )
+ _spawn_background(_complete_login(proc))
+ return {"success": True, "url": url, "verification_code": code}
+ except Exception as e:
+ logger.exception("[GitHub] login flow raised unexpectedly: %s", e)
+ return {"success": False, "error": f"GitHub login failed: {e}"}
+
+
+async def handle_github_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Answer within the frontend's request window no matter what
+ (vercel's cold-install pending pattern)."""
+ logger.info("[GitHub] login flow starting (gh auth login --web)")
+ flow = _spawn_background(_start_login_flow())
+ try:
+ return await asyncio.wait_for(asyncio.shield(flow), timeout=_RESPONSE_BUDGET_SECONDS)
+ except asyncio.TimeoutError:
+ logger.info(
+ "[GitHub] login still preparing after %ss (cold gh download) — continuing in background",
+ _RESPONSE_BUDGET_SECONDS,
+ )
+ return {
+ "success": True,
+ "pending": True,
+ "message": "gh CLI is being installed — click Login again in a few seconds.",
+ }
+
+
+async def _complete_login(proc: asyncio.subprocess.Process) -> None:
+ """Await gh's device-flow poll; gate success on ``gh auth status``
+ (exit codes are not trusted alone — Stripe precedent); then the
+ official git bridge + marker + broadcast."""
+ try:
+ try:
+ returncode = await asyncio.wait_for(proc.wait(), timeout=_LOGIN_TIMEOUT_SECONDS)
+ except asyncio.TimeoutError:
+ proc.kill()
+ logger.warning("[GitHub] login timed out after %ss — user never completed the browser flow", _LOGIN_TIMEOUT_SECONDS)
+ return
+ except Exception as e:
+ logger.exception("[GitHub] login wait raised unexpectedly: %s", e)
+ return
+
+ if not await cli_logged_in():
+ logger.warning(
+ "[GitHub] login exited (code=%s) but 'gh auth status' reports no session — user likely closed the browser before authorising",
+ returncode,
+ )
+ return
+
+ logger.info("[GitHub] auth successful — gh holds the credential; configuring git bridge + catalogue marker")
+
+ login = name = None
+ from ._service import resolve_gh_light
+
+ binary = resolve_gh_light()
+ if binary:
+ # Official one-shot: configures git to use gh as credential helper
+ # for authenticated hosts. Best-effort — github ops work without it.
+ setup = await run_cli_command(binary=binary, argv=["auth", "setup-git"], timeout=30.0, env=login_env())
+ if setup.get("success"):
+ logger.info("[GitHub] 'gh auth setup-git' configured git's credential helper")
+ else:
+ logger.warning("[GitHub] 'gh auth setup-git' failed (non-fatal): %s", setup.get("error"))
+ login, name = await _fetch_account(binary)
+
+ await mark_logged_in("github", email=login, name=name)
+ logger.info("[GitHub] connected as %s — catalogue marker persisted", login or "<unknown>")
+ await broadcast_credential_event("credential.oauth.connected", provider="github")
+
+
+async def handle_github_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """``gh auth logout`` (best-effort), drop the catalogue marker,
+ broadcast so the modal flips immediately."""
+ logger.info("[GitHub] logout starting")
+ from ._service import resolve_gh_light
+
+ binary = resolve_gh_light()
+ result: Dict[str, Any] = {"success": True}
+ if binary:
+ result = await run_cli_command(
+ binary=binary,
+ argv=["auth", "logout", "--hostname", "github.com"],
+ timeout=15.0,
+ env=login_env(),
+ )
+ if not result.get("success"):
+ logger.warning("[GitHub] 'gh auth logout' failed (marker still removed): %s", result.get("error"))
+ result = {"success": True, "message": "gh reported no stored session; catalogue marker removed"}
+ await mark_logged_out("github")
+ await broadcast_credential_event("credential.oauth.disconnected", provider="github")
+ logger.info("[GitHub] logout complete: marker removed + catalogue broadcast sent")
+ return result
+
+
+async def handle_github_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Session snapshot straight from the CLI — no side effects."""
+ connected = await cli_logged_in()
+ return {"success": True, "status": {"connected": connected, "logged_in": connected}}
+
+
+WS_HANDLERS = {
+ "github_login": handle_github_login,
+ "github_logout": handle_github_logout,
+ "github_status": handle_github_status,
+}
diff --git a/server/nodes/github/_install.py b/server/nodes/github/_install.py
new file mode 100644
index 00000000..28fe4b37
--- /dev/null
+++ b/server/nodes/github/_install.py
@@ -0,0 +1,142 @@
+"""GitHub CLI (`gh`) downloader — pooch-driven, project-local.
+
+Mirrors :mod:`services.temporal._install` (the repo's shared pattern
+for fetching official CLI binaries): ``pooch.retrieve`` handles the
+download, caching (re-runs are instant cache hits keyed by filename),
+and archive extraction; we contribute only the pinned release URL and
+the per-platform asset map.
+
+The binary lands under ``<DATA_DIR>/packages/gh/`` — the same
+:func:`core.paths.package_dir` root that holds the Stripe and Temporal
+binaries. The system-global gh is deliberately never consulted, so
+node behavior doesn't depend on whatever version is on the operator's
+PATH. Auth state is unaffected by which binary runs: gh's config +
+credential-store paths are user-level and shared, so a session created
+by the user's own ``gh auth login`` in a terminal is visible to this
+local binary too.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import platform
+import stat
+from pathlib import Path
+from typing import Optional, Tuple
+
+import pooch
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+_VERSION = "2.96.0"
+_RELEASE_BASE = f"https://github.com/cli/cli/releases/download/v{_VERSION}"
+
+# (system, machine) -> (asset filename, binary name inside the archive's bin/).
+# Note gh's release naming: linux assets are tar.gz, windows AND macOS are
+# zips, with capital-S `macOS` in the asset name.
+_ASSETS: dict[Tuple[str, str], Tuple[str, str]] = {
+ ("Windows", "AMD64"): (f"gh_{_VERSION}_windows_amd64.zip", "gh.exe"),
+ ("Windows", "ARM64"): (f"gh_{_VERSION}_windows_arm64.zip", "gh.exe"),
+ ("Linux", "x86_64"): (f"gh_{_VERSION}_linux_amd64.tar.gz", "gh"),
+ ("Linux", "aarch64"): (f"gh_{_VERSION}_linux_arm64.tar.gz", "gh"),
+ ("Linux", "arm64"): (f"gh_{_VERSION}_linux_arm64.tar.gz", "gh"),
+ ("Darwin", "x86_64"): (f"gh_{_VERSION}_macOS_amd64.zip", "gh"),
+ ("Darwin", "arm64"): (f"gh_{_VERSION}_macOS_arm64.zip", "gh"),
+}
+
+_cached_path: Optional[Path] = None
+_install_lock = asyncio.Lock()
+
+
+def _package_root() -> Path:
+ from core.paths import package_dir
+
+ p = package_dir("gh")
+ p.mkdir(parents=True, exist_ok=True)
+ return p
+
+
+def _platform_asset() -> Tuple[str, str]:
+ key = (platform.system(), platform.machine())
+ asset = _ASSETS.get(key)
+ if asset is None:
+ raise RuntimeError(f"No prebuilt gh CLI for {key}. Supported: {sorted(_ASSETS)}. See https://cli.github.com")
+ return asset
+
+
+def _extracted_binary_path() -> Path:
+ """Deterministic post-extraction location: pooch's Unzip/Untar
+ processors extract next to the archive under ``<fname>.unzip`` /
+ ``<fname>.untar``, preserving the archive's inner
+ ``gh_<V>_<os>_<arch>/bin/`` layout."""
+ asset_name, binary_name = _platform_asset()
+ suffix = ".unzip" if asset_name.endswith(".zip") else ".untar"
+ inner_root = asset_name.removesuffix(".zip").removesuffix(".tar.gz")
+ return _package_root() / f"{asset_name}{suffix}" / inner_root / "bin" / binary_name
+
+
+def gh_cli_path() -> Optional[Path]:
+ """Sync getter for the project-local binary — the already-installed
+ copy, without downloading. ``None`` when never installed."""
+ global _cached_path
+ if _cached_path and _cached_path.exists():
+ return _cached_path
+ target = _extracted_binary_path()
+ if target.exists():
+ _cached_path = target
+ return target
+ return None
+
+
+async def ensure_gh_cli() -> Path:
+ """Return absolute path to the project-local gh binary, downloading
+ the pinned release on miss. Idempotent + concurrent-safe."""
+ global _cached_path
+ existing = gh_cli_path()
+ if existing:
+ return existing
+
+ async with _install_lock:
+ existing = gh_cli_path()
+ if existing:
+ return existing
+ binary = await asyncio.to_thread(_fetch_cli_sync)
+ _cached_path = binary
+ return binary
+
+
+def _fetch_cli_sync() -> Path:
+ """Download + extract the pinned gh release via pooch.
+
+ ``known_hash=None``: the release URL is version-pinned and served
+ over TLS from GitHub's CDN (temporal precedent — transport
+ integrity without hand-maintaining per-platform hashes).
+ """
+ asset_name, binary_name = _platform_asset()
+ url = f"{_RELEASE_BASE}/{asset_name}"
+ logger.info("[GitHub] downloading gh CLI v%s from %s", _VERSION, url)
+
+ processor = pooch.Unzip() if asset_name.endswith(".zip") else pooch.Untar()
+ extracted = pooch.retrieve(
+ url=url,
+ known_hash=None,
+ path=_package_root(),
+ fname=asset_name,
+ processor=processor,
+ # requests' timeout is per-socket-read, not total download time
+ # (temporal precedent: pooch's 30s default killed slow links).
+ downloader=pooch.HTTPDownloader(timeout=300, progressbar=True),
+ )
+
+ match = next((Path(p) for p in extracted if Path(p).name == binary_name), None)
+ if match is None:
+ raise RuntimeError(f"[GitHub] gh binary {binary_name!r} not found in {asset_name}. Extracted: {[Path(p).name for p in extracted]}")
+ if platform.system() != "Windows":
+ match.chmod(match.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+ logger.info("[GitHub] gh CLI installed at %s", match)
+ return match
+
+
+__all__ = ["ensure_gh_cli", "gh_cli_path"]
diff --git a/server/nodes/github/_service.py b/server/nodes/github/_service.py
new file mode 100644
index 00000000..1c619a3a
--- /dev/null
+++ b/server/nodes/github/_service.py
@@ -0,0 +1,101 @@
+"""Shared GitHub plugin helpers — subprocess env builders, gh session
+probe, workspace path resolution.
+
+Auth model — **the gh CLI owns its own auth** (Stripe CLI pattern):
+``gh auth login`` (driven by the modal's Login button or run by the
+user in a terminal) stores the token in the system credential store;
+MachinaOs never stores or injects a token — a synthetic ``cli-managed``
+marker OAuth row flips the catalogue's ``stored`` badge, exactly like
+Stripe. Users who prefer a PAT pipe it to ``gh auth login
+--with-token`` themselves. Ambient ``GH_TOKEN`` in the server's own
+environment is left untouched for ops (gh documents env tokens as
+taking precedence over stored credentials) — but it MUST be stripped
+for ``gh auth login`` / ``status`` / ``logout`` (see
+:func:`login_env`).
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Dict, Optional
+
+from services.plugin.base import NodeUserError
+
+
+def gh_env() -> Dict[str, str]:
+ """Child env for gh op invocations — the documented automation
+ baseline from ``gh help environment``. No token handling: gh reads
+ its own credential store (or an ambient env token, per its own
+ documented precedence)."""
+ env = os.environ.copy()
+ env["GH_PROMPT_DISABLED"] = "1"
+ env["NO_COLOR"] = "1"
+ env["GH_NO_UPDATE_NOTIFIER"] = "1"
+ env["GH_PAGER"] = "cat"
+ return env
+
+
+def login_env() -> Dict[str, str]:
+ """Env for ``gh auth login`` / ``gh auth status`` / ``gh auth
+ logout`` — the CLI must consult its OWN credential store, so
+ ambient env tokens are stripped: ``gh auth login`` aborts outright
+ when ``GH_TOKEN``/``GITHUB_TOKEN`` is set ("The value of the …
+ environment variable is being used for authentication", source:
+ ``pkg/cmd/auth/login/login.go``), and ``gh auth status`` would
+ report the env token instead of the stored session. The login flow
+ must also be allowed to prompt-print, so ``GH_PROMPT_DISABLED`` is
+ dropped here too."""
+ env = gh_env()
+ env.pop("GH_TOKEN", None)
+ env.pop("GITHUB_TOKEN", None)
+ env.pop("GH_PROMPT_DISABLED", None)
+ return env
+
+
+def resolve_gh_light() -> Optional[str]:
+ """The project-local gh binary WITHOUT triggering a download.
+ ``None`` when it has never been installed (status then reports
+ disconnected; login / ops install on demand). The system-global gh
+ is deliberately never consulted."""
+ from ._install import gh_cli_path
+
+ cached = gh_cli_path()
+ return str(cached) if cached else None
+
+
+async def cli_logged_in() -> bool:
+ """True when a ``gh auth login`` session is live (whether started
+ from the modal's Login button or the user's own terminal — gh owns
+ the state either way). ``gh auth status`` exits 0 when healthy,
+ 1 on auth problems. Best-effort: False when gh isn't installed."""
+ from services.events import run_cli_command
+
+ binary = resolve_gh_light()
+ if not binary:
+ return False
+ result = await run_cli_command(
+ binary=binary,
+ argv=["auth", "status"],
+ timeout=15.0,
+ env=login_env(),
+ )
+ return bool(result.get("success"))
+
+
+def resolve_repo_path(workspace_dir: Optional[str], path: str) -> str:
+ """Working directory for an operation: explicit param (absolute,
+ or relative to the per-workflow workspace) falling back to the
+ workspace itself (vercel ``_resolve_deploy_cwd`` idiom)."""
+ if path:
+ p = Path(path)
+ if not p.is_absolute():
+ if not workspace_dir:
+ raise NodeUserError(f"Relative path {path!r} needs a workflow workspace — run inside a workflow or pass an absolute path")
+ p = Path(workspace_dir) / p
+ if not p.is_dir():
+ raise NodeUserError(f"Path does not exist or is not a directory: {p}")
+ return str(p)
+ if not workspace_dir:
+ raise NodeUserError("No path given and no workflow workspace available — set the 'path' parameter")
+ return str(workspace_dir)
diff --git a/server/nodes/github/github_action.py b/server/nodes/github/github_action.py
new file mode 100644
index 00000000..d8f4f234
--- /dev/null
+++ b/server/nodes/github/github_action.py
@@ -0,0 +1,319 @@
+"""GitHub Action — typed core operations over the `gh` CLI, plus a
+raw-command passthrough.
+
+The gh CLI owns its own auth (Stripe pattern): no pre-flight check and
+no token injection here — gh reads its system credential store
+(populated by ``gh auth login``) or an ambient env token, and its own
+"not logged in" error surfaces through the ``NodeUserError`` wrap.
+List operations use ``--json`` for machine-readable results; ``gh
+api`` (via ``custom``) returns raw JSON.
+"""
+
+from __future__ import annotations
+
+import shlex
+from typing import Any, Dict, List, Literal, Optional
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from services.events import run_cli_command
+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue
+
+from ._credentials import GitHubCredential
+
+_CLONE = {"displayOptions": {"show": {"operation": ["repo_clone"]}}}
+_PR_CREATE = {"displayOptions": {"show": {"operation": ["pr_create"]}}}
+_LISTS = {"displayOptions": {"show": {"operation": ["pr_list", "issue_list"]}}}
+_PR_MERGE = {"displayOptions": {"show": {"operation": ["pr_merge"]}}}
+_ISSUE_CREATE = {"displayOptions": {"show": {"operation": ["issue_create"]}}}
+_CUSTOM = {"displayOptions": {"show": {"operation": ["custom"]}}}
+
+_ONESHOT_TIMEOUT = 120.0
+_CLONE_TIMEOUT = 600.0
+_STDERR_TAIL_CHARS = 2000
+
+_PR_JSON_FIELDS = "number,title,state,url,author,headRefName,baseRefName,createdAt"
+_ISSUE_JSON_FIELDS = "number,title,state,url,author,labels,createdAt"
+
+
+class GitHubActionParams(BaseModel):
+ operation: Literal[
+ "repo_clone", "pr_create", "pr_list", "pr_merge", "issue_create", "issue_list", "custom"
+ ] = "pr_list"
+
+ # Shared repo target: gh infers OWNER/REPO from the cwd's git remote;
+ # set explicitly to operate outside a checkout (maps to --repo / GH_REPO).
+ repo: str = Field(
+ default="",
+ description="Target repository as OWNER/REPO (optional inside a cloned checkout)",
+ json_schema_extra={
+ "placeholder": "octocat/hello-world",
+ "displayOptions": {"show": {"operation": ["pr_create", "pr_list", "pr_merge", "issue_create", "issue_list"]}},
+ },
+ )
+ # Working directory (relative → workflow workspace).
+ path: str = Field(
+ default="",
+ json_schema_extra={
+ "placeholder": "Working directory (defaults to the workflow workspace)",
+ "displayOptions": {"show": {"operation": ["repo_clone", "pr_create", "pr_merge", "custom"]}},
+ },
+ )
+
+ # repo_clone
+ clone_repo: str = Field(
+ default="",
+ description="Repository to clone: OWNER/REPO or a full URL",
+ json_schema_extra={"placeholder": "octocat/hello-world", **_CLONE},
+ )
+ clone_dir: str = Field(default="", json_schema_extra={"placeholder": "Target directory name (optional)", **_CLONE})
+
+ # pr_create
+ title: str = Field(
+ default="",
+ json_schema_extra={"displayOptions": {"show": {"operation": ["pr_create", "issue_create"]}}},
+ )
+ body: str = Field(
+ default="",
+ json_schema_extra={
+ "rows": 4,
+ "displayOptions": {"show": {"operation": ["pr_create", "issue_create"]}},
+ },
+ )
+ base: str = Field(default="", json_schema_extra={"placeholder": "Base branch (optional)", **_PR_CREATE})
+ head: str = Field(default="", json_schema_extra={"placeholder": "Head branch (optional)", **_PR_CREATE})
+ draft: bool = Field(default=False, json_schema_extra=_PR_CREATE)
+ fill: bool = Field(
+ default=False,
+ description="Derive title/body from commits (--fill)",
+ json_schema_extra=_PR_CREATE,
+ )
+
+ # pr_list / issue_list
+ state: Literal["open", "closed", "merged", "all"] = Field(default="open", json_schema_extra=_LISTS)
+ limit: int = Field(default=30, ge=1, le=100, json_schema_extra=_LISTS)
+
+ # pr_merge
+ pr: str = Field(
+ default="",
+ description="PR number, URL, or branch",
+ json_schema_extra=_PR_MERGE,
+ )
+ merge_method: Literal["squash", "merge", "rebase"] = Field(default="squash", json_schema_extra=_PR_MERGE)
+ delete_branch: bool = Field(default=False, json_schema_extra=_PR_MERGE)
+
+ # issue_create
+ labels: str = Field(default="", json_schema_extra={"placeholder": "bug,help wanted (comma-separated, optional)", **_ISSUE_CREATE})
+
+ # custom
+ command: str = Field(
+ default="",
+ description="gh CLI command, exactly as typed after 'gh '",
+ json_schema_extra={
+ "placeholder": "api repos/{owner}/{repo} | run list | release create v1.0.0",
+ **_CUSTOM,
+ },
+ )
+
+ model_config = ConfigDict(extra="ignore")
+
+
+class GitHubActionOutput(BaseModel):
+ operation: Optional[str] = None
+ success: Optional[bool] = None
+ url: Optional[str] = None
+ result: Optional[Any] = None
+ stdout: Optional[str] = None
+ stderr_tail: Optional[str] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class GitHubActionNode(ActionNode):
+ type = "githubAction"
+ display_name = "GitHub"
+ subtitle = "gh CLI"
+ group = ("vcs", "tool")
+ description = "GitHub via the gh CLI — clone repos, create/list/merge PRs, create/list issues, or run any gh command"
+ component_kind = "square"
+ tool_name = "github"
+ tool_description = (
+ "Interact with GitHub via the gh CLI. Operations: repo_clone (clone into the workspace), "
+ "pr_create (open a pull request; returns its URL), pr_list / issue_list (JSON results), "
+ "pr_merge (squash/merge/rebase), issue_create, custom (any other gh command — pass "
+ "'command' exactly as typed after 'gh ', e.g. 'api repos/{owner}/{repo}', 'run list', "
+ "'release create v1.0.0 --notes ...', 'repo create my-repo --private'). Inside a cloned "
+ "checkout gh infers the repository; otherwise set the 'repo' field (OWNER/REPO). "
+ "Auth is managed by the gh CLI itself — connect via Credentials → GitHub (Login button) "
+ "or run 'gh auth login' in a terminal. Reference: https://cli.github.com/manual"
+ )
+ handles = (
+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
+ )
+ annotations = {"destructive": False, "readonly": False, "open_world": True}
+ # OutputPanel renders textual output preformatted (gh tables /
+ # clone progress are terminal text, not markdown).
+ ui_hints = {"outputMode": "terminal"}
+ credentials = (GitHubCredential,)
+ task_queue = TaskQueue.REST_API
+ usable_as_tool = True
+
+ Params = GitHubActionParams
+ Output = GitHubActionOutput
+
+ # ---- shared plumbing -------------------------------------------------
+
+ async def _run(
+ self,
+ argv: List[str],
+ *,
+ cwd: Optional[str] = None,
+ timeout: float = _ONESHOT_TIMEOUT,
+ ) -> Dict[str, Any]:
+ """No auth pre-flight (Stripe pattern) — gh authenticates from
+ its own credential store, and its error (including "not logged
+ in") surfaces via the NodeUserError wrap below."""
+ from ._install import ensure_gh_cli
+ from ._service import gh_env
+
+ try:
+ binary = str(await ensure_gh_cli())
+ except Exception as e:
+ raise RuntimeError(f"gh CLI install failed: {e}") from e
+
+ result = await run_cli_command(
+ binary=binary,
+ argv=argv,
+ timeout=timeout,
+ env=gh_env(),
+ cwd=cwd,
+ )
+ if not result.get("success"):
+ stderr = (result.get("stderr") or "").strip()
+ detail = stderr[-_STDERR_TAIL_CHARS:] if stderr else (result.get("error") or "gh invocation failed")
+ raise NodeUserError(f"gh {argv[0]} failed: {detail}")
+ return result
+
+ def _cwd(self, ctx: NodeContext, path: str, *, required: bool = False) -> Optional[str]:
+ from ._service import resolve_repo_path
+
+ if not path and not required and not ctx.workspace_dir:
+ return None
+ return resolve_repo_path(ctx.workspace_dir, path.strip())
+
+ @staticmethod
+ def _repo_flag(params: "GitHubActionParams") -> List[str]:
+ return ["--repo", params.repo.strip()] if params.repo.strip() else []
+
+ @staticmethod
+ def _shape(operation: str, result: Dict[str, Any], *, url: Optional[str] = None) -> Dict[str, Any]:
+ """Output-panel shaping: when gh returned JSON (pr_list /
+ issue_list / `gh api`), the parsed data IS the payload — the
+ raw stdout string would just duplicate it as an unreadable
+ blob (and pre-stringified JSON violates the output contract).
+ Keys are omitted (not None'd) when empty so the panel shows
+ only meaningful fields (`exclude_unset` preserves this)."""
+ shaped: Dict[str, Any] = {"operation": operation, "success": True}
+ if url:
+ shaped["url"] = url
+ parsed = result.get("result")
+ stdout = (result.get("stdout") or "").strip()
+ if parsed is not None:
+ shaped["result"] = parsed
+ elif stdout:
+ shaped["stdout"] = stdout
+ stderr = (result.get("stderr") or "").strip()
+ if stderr:
+ shaped["stderr_tail"] = stderr[-_STDERR_TAIL_CHARS:]
+ return shaped
+
+ # ---- operations ------------------------------------------------------
+
+ @Operation("repo_clone", cost={"service": "github", "action": "repo_clone", "count": 1})
+ async def repo_clone(self, ctx: NodeContext, params: GitHubActionParams) -> Any:
+ repo = params.clone_repo.strip()
+ if not repo:
+ raise NodeUserError("clone_repo is required (OWNER/REPO or a full URL)")
+ cwd = self._cwd(ctx, params.path, required=True)
+ argv = ["repo", "clone", repo]
+ if params.clone_dir.strip():
+ argv.append(params.clone_dir.strip())
+ result = await self._run(argv, cwd=cwd, timeout=_CLONE_TIMEOUT)
+ return self._shape("repo_clone", result)
+
+ @Operation("pr_create", cost={"service": "github", "action": "pr_create", "count": 1})
+ async def pr_create(self, ctx: NodeContext, params: GitHubActionParams) -> Any:
+ argv = ["pr", "create", *self._repo_flag(params)]
+ if params.fill:
+ argv.append("--fill")
+ else:
+ if not params.title.strip():
+ raise NodeUserError("title is required (or set fill=true to derive it from commits)")
+ argv += ["--title", params.title.strip(), "--body", params.body]
+ if params.base.strip():
+ argv += ["--base", params.base.strip()]
+ if params.head.strip():
+ argv += ["--head", params.head.strip()]
+ if params.draft:
+ argv.append("--draft")
+ result = await self._run(argv, cwd=self._cwd(ctx, params.path))
+ # gh prints the new PR's URL on stdout.
+ stdout = (result.get("stdout") or "").strip()
+ url = stdout if stdout.startswith("http") else None
+ return self._shape("pr_create", result, url=url)
+
+ @Operation("pr_list", cost={"service": "github", "action": "pr_list", "count": 1})
+ async def pr_list(self, ctx: NodeContext, params: GitHubActionParams) -> Any:
+ argv = [
+ "pr", "list", *self._repo_flag(params),
+ "--state", params.state, "--limit", str(params.limit),
+ "--json", _PR_JSON_FIELDS,
+ ]
+ result = await self._run(argv, cwd=self._cwd(ctx, ""))
+ return self._shape("pr_list", result)
+
+ @Operation("pr_merge", cost={"service": "github", "action": "pr_merge", "count": 1})
+ async def pr_merge(self, ctx: NodeContext, params: GitHubActionParams) -> Any:
+ pr = params.pr.strip()
+ if not pr:
+ raise NodeUserError("pr is required (a PR number, URL, or branch name)")
+ argv = ["pr", "merge", pr, *self._repo_flag(params), f"--{params.merge_method}"]
+ if params.delete_branch:
+ argv.append("--delete-branch")
+ result = await self._run(argv, cwd=self._cwd(ctx, params.path))
+ return self._shape("pr_merge", result)
+
+ @Operation("issue_create", cost={"service": "github", "action": "issue_create", "count": 1})
+ async def issue_create(self, ctx: NodeContext, params: GitHubActionParams) -> Any:
+ if not params.title.strip():
+ raise NodeUserError("title is required")
+ argv = ["issue", "create", *self._repo_flag(params), "--title", params.title.strip(), "--body", params.body]
+ for label in filter(None, (s.strip() for s in params.labels.split(","))):
+ argv += ["--label", label]
+ result = await self._run(argv, cwd=self._cwd(ctx, ""))
+ stdout = (result.get("stdout") or "").strip()
+ url = stdout if stdout.startswith("http") else None
+ return self._shape("issue_create", result, url=url)
+
+ @Operation("issue_list", cost={"service": "github", "action": "issue_list", "count": 1})
+ async def issue_list(self, ctx: NodeContext, params: GitHubActionParams) -> Any:
+ state = params.state if params.state != "merged" else "all"
+ argv = [
+ "issue", "list", *self._repo_flag(params),
+ "--state", state, "--limit", str(params.limit),
+ "--json", _ISSUE_JSON_FIELDS,
+ ]
+ result = await self._run(argv, cwd=self._cwd(ctx, ""))
+ return self._shape("issue_list", result)
+
+ @Operation("custom", cost={"service": "github", "action": "custom", "count": 1})
+ async def custom(self, ctx: NodeContext, params: GitHubActionParams) -> Any:
+ cmd = params.command.strip()
+ if not cmd:
+ raise NodeUserError("command is required (e.g. 'api repos/{owner}/{repo}', 'run list', 'release list')")
+ argv = shlex.split(cmd)
+ result = await self._run(argv, cwd=self._cwd(ctx, params.path), timeout=_CLONE_TIMEOUT)
+ stdout = (result.get("stdout") or "").strip()
+ url = stdout if stdout.startswith("http") and "\n" not in stdout else None
+ return self._shape("custom", result, url=url)
diff --git a/server/nodes/github/meta.json b/server/nodes/github/meta.json
new file mode 100644
index 00000000..7caf04d9
--- /dev/null
+++ b/server/nodes/github/meta.json
@@ -0,0 +1 @@
+{"color": "#8250df"}
diff --git a/server/nodes/groups.py b/server/nodes/groups.py
index b1f08144..6e86fab2 100644
--- a/server/nodes/groups.py
+++ b/server/nodes/groups.py
@@ -51,6 +51,7 @@ register_group(key="whatsapp", metadata={"label": "WhatsApp", "icon": "💬", "c
register_group(key="email", metadata={"label": "Email", "icon": "✉️", "color": "#8be9fd", "visibility": "dev"})
register_group(key="payments", metadata={"label": "Payments", "icon": "asset:stripe", "color": "#635BFF", "visibility": "dev"})
register_group(key="deployment", metadata={"label": "Deployment", "icon": "lobehub:Vercel", "color": "#666666", "visibility": "dev"})
+register_group(key="vcs", metadata={"label": "Version Control", "icon": "lobehub:Github", "color": "#F05133", "visibility": "dev"})
register_group(key="browser", metadata={"label": "Browser", "icon": "🌐", "color": "#ff79c6", "visibility": "dev"})
register_group(key="scraper", metadata={"label": "Scrapers", "icon": "🕸", "color": "#ff79c6", "visibility": "dev"})
register_group(key="filesystem", metadata={"label": "Filesystem", "icon": "📁", "color": "#8be9fd", "visibility": "dev"})
diff --git a/server/nodes/visuals.json b/server/nodes/visuals.json
index 24ce12b4..236a85dc 100644
--- a/server/nodes/visuals.json
+++ b/server/nodes/visuals.json
@@ -132,6 +132,10 @@
"geminiChatModel": {
"icon": "lobehub:gemini"
},
+ "githubAction": {
+ "icon": "lobehub:Github",
+ "skill": "github-skill"
+ },
"gmaps_create": {
"icon": "🗺️"
},
diff --git a/server/skills/github/github-skill/SKILL.md b/server/skills/github/github-skill/SKILL.md
new file mode 100644
index 00000000..e47fef76
--- /dev/null
+++ b/server/skills/github/github-skill/SKILL.md
@@ -0,0 +1,135 @@
+---
+name: github-skill
+description: Work with GitHub via the gh CLI — clone repositories, create/list/merge pull requests, create/list issues, and run any other gh command (API calls, workflow runs, releases, repo administration). List operations return parsed JSON.
+allowed-tools: "github"
+metadata:
+ author: machina
+ version: "1.0"
+ category: developer
+
+---
+
+# GitHub Skill
+
+Wrapper over the official [GitHub CLI](https://cli.github.com/manual).
+Typed operations for the core flows plus a `custom` passthrough that
+covers the entire gh surface.
+
+## Tool: github
+
+### Operations
+
+| Operation | Purpose | Key fields |
+|---|---|---|
+| `repo_clone` | Clone a repository into the workflow workspace | `clone_repo` (OWNER/REPO or URL), `clone_dir`, `path` |
+| `pr_create` | Open a pull request; returns its URL | `title`, `body`, `base`, `head`, `draft`, `fill`, `repo`, `path` |
+| `pr_list` | List pull requests (parsed JSON) | `repo`, `state`, `limit` |
+| `pr_merge` | Merge a PR | `pr` (number/URL/branch), `merge_method` (squash/merge/rebase), `delete_branch`, `repo` |
+| `issue_create` | Open an issue; returns its URL | `title`, `body`, `labels`, `repo` |
+| `issue_list` | List issues (parsed JSON) | `repo`, `state`, `limit` |
+| `custom` | Any other gh command | `command` — exactly what you would type after `gh ` |
+
+### Response
+
+```json
+{
+ "operation": "pr_list",
+ "success": true,
+ "url": null,
+ "result": [{ "number": 42, "title": "Fix login", "state": "OPEN", "url": "https://github.com/o/r/pull/42", "author": {"login": "octocat"}, "headRefName": "fix-login", "baseRefName": "main", "createdAt": "…" }],
+ "stdout": "…raw output…",
+ "stderr_tail": null
+}
+```
+
+`pr_list` / `issue_list` return parsed JSON in `result` (via gh's
+`--json`). `pr_create` / `issue_create` put the new item's URL in
+`url`. `custom` commands that emit JSON (`api …`, `… --json fields`)
+come back parsed in `result` too.
+
+On failure the tool raises an error carrying gh's own message —
+surface it verbatim; gh's errors are precise (including "not logged
+in", which tells the user exactly how to authenticate).
+
+## Repository targeting
+
+Inside a cloned checkout (after `repo_clone`, with `path` pointing at
+it) gh infers OWNER/REPO from the git remote. Everywhere else, set the
+`repo` field explicitly:
+
+```json
+{ "operation": "pr_list", "repo": "octocat/hello-world", "state": "open" }
+```
+
+## Common workflows
+
+### Clone, then work inside the checkout
+
+```json
+{ "operation": "repo_clone", "clone_repo": "octocat/hello-world" }
+{ "operation": "pr_create", "path": "hello-world", "fill": true }
+```
+
+`path` resolves relative to the workflow workspace.
+
+### Review flow
+
+```json
+{ "operation": "pr_list", "repo": "octocat/hello-world", "state": "open" }
+{ "operation": "custom", "command": "pr view 42 --repo octocat/hello-world --json title,body,files" }
+{ "operation": "pr_merge", "pr": "42", "repo": "octocat/hello-world", "merge_method": "squash", "delete_branch": true }
+```
+
+### Issues
+
+```json
+{ "operation": "issue_create", "repo": "octocat/hello-world", "title": "Crash on login", "body": "Steps…", "labels": "bug" }
+{ "operation": "issue_list", "repo": "octocat/hello-world", "state": "open", "limit": 50 }
+```
+
+### The full gh surface via custom
+
+```json
+{ "operation": "custom", "command": "api repos/{owner}/{repo}" }
+{ "operation": "custom", "command": "api user" }
+{ "operation": "custom", "command": "run list --repo octocat/hello-world --json databaseId,status,conclusion" }
+{ "operation": "custom", "command": "release create v1.0.0 --notes 'First release'" }
+{ "operation": "custom", "command": "repo create my-new-repo --private" }
+{ "operation": "custom", "command": "gist create notes.md" }
+```
+
+Prefer `--json <fields>` (list/view commands) or `gh api` when you
+need machine-readable output. `gh api` supports `{owner}/{repo}`
+placeholders inside a checkout.
+
+## Quoting and escaping
+
+`command` is parsed with `shlex.split` — quote arguments containing
+spaces with single quotes: `custom: "release create v1.0.0 --notes 'First release'"`.
+
+## Authentication
+
+The gh CLI owns its auth — MachinaOs never stores a token. Three
+equivalent ways to connect (any one is enough):
+
+1. **Credentials Modal → GitHub → Login with GitHub** — gh (auto-installed)
+ starts its browser device flow: the modal shows a one-time code and
+ opens github.com/login/device; enter the code and approve.
+2. **`gh auth login`** in a terminal on this machine.
+3. **`gh auth login --with-token`** in a terminal, piping a Personal
+ Access Token (scopes: repo, read:org, gist).
+
+If a command fails with an authentication error, tell the user to
+connect via one of these; don't ask them for a token.
+
+## Best practices
+
+1. **Set `repo` explicitly** unless you're operating inside a cloned
+ checkout.
+2. **Use `fill: true`** on pr_create when commits already carry good
+ messages.
+3. **Return created URLs to the user** (PRs, issues, releases).
+4. **Destructive administration** (repo delete, etc.) goes through
+ `custom` and gh will require its own `--yes`-style confirmation
+ flags — pass them only when the user explicitly asked.
+5. **Surface gh error messages verbatim** — don't paraphrase.
diff --git a/server/tests/test_github_plugin.py b/server/tests/test_github_plugin.py
new file mode 100644
index 00000000..f07de56d
--- /dev/null
+++ b/server/tests/test_github_plugin.py
@@ -0,0 +1,329 @@
+"""GitHub plugin contract tests.
+
+Locks the plugin's load-bearing seams under the CLI-owns-auth (Stripe)
+pattern: env builders (no token handling; login env strips ambient
+tokens — source-verified gh abort), the login-banner parser (gh's
+``authflow/flow.go`` format strings), install resolution (pinned
+release, per-platform member paths), the marker-token + CloudEvents
+broadcast contract (``inspect.getsource`` introspection,
+``test_credential_broadcasts`` style), op argv building, and the
+catalogue entry shape (fieldless — gh owns the token).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import json
+from pathlib import Path
+
+import pytest
+
+import nodes.github._handlers as gh_handlers
+import nodes.github._install as gh_install
+import nodes.github._service as gh_service
+import nodes.github.github_action as gh_action_mod
+from nodes.github import WS_HANDLERS
+from nodes.github._credentials import GitHubCredential
+from nodes.github.github_action import GitHubActionNode, GitHubActionParams
+from services.plugin import NodeContext
+from services.plugin.base import NodeUserError
+
+PLUGIN_DIR = Path(gh_service.__file__).parent
+CONFIG_PATH = Path(gh_service.__file__).parents[2] / "config" / "credential_providers.json"
+
+
+# --- _service env builders ----------------------------------------------------
+
+
+def test_gh_env_is_the_documented_automation_baseline(monkeypatch):
+ monkeypatch.setenv("GH_TOKEN", "ghp_ambient")
+ env = gh_service.gh_env()
+ assert env["GH_PROMPT_DISABLED"] == "1"
+ assert env["NO_COLOR"] == "1"
+ assert env["GH_NO_UPDATE_NOTIFIER"] == "1"
+ assert env["GH_PAGER"] == "cat"
+ # Ambient env token is left alone for ops — gh's documented precedence.
+ assert env["GH_TOKEN"] == "ghp_ambient"
+
+
+def test_login_env_strips_ambient_tokens_and_allows_prompts(monkeypatch):
+ """`gh auth login` aborts when GH_TOKEN/GITHUB_TOKEN is set
+ (login.go: 'The value of the %s environment variable is being used
+ for authentication'), and `gh auth status` would report the env
+ token instead of the stored session."""
+ monkeypatch.setenv("GH_TOKEN", "ghp_ambient")
+ monkeypatch.setenv("GITHUB_TOKEN", "ghp_ambient2")
+ env = gh_service.login_env()
+ assert "GH_TOKEN" not in env
+ assert "GITHUB_TOKEN" not in env
+ assert "GH_PROMPT_DISABLED" not in env
+
+
+# --- login banner parsing (source-verified authflow/flow.go strings) -----------
+
+
+def test_parse_login_banner_extracts_code_and_device_url():
+ banner = (
+ "! First copy your one-time code: ABCD-1234\n"
+ "Open this URL to continue in your web browser: https://github.com/login/device\n"
+ )
+ parsed = gh_handlers.parse_login_banner(banner)
+ assert parsed == ("https://github.com/login/device", "ABCD-1234")
+
+
+def test_parse_login_banner_waits_until_url_present():
+ # Code line alone (printed first) is not enough — the URL is the gate.
+ assert gh_handlers.parse_login_banner("! First copy your one-time code: ABCD-1234\n") is None
+ assert gh_handlers.parse_login_banner("") is None
+
+
+def test_parse_login_banner_tolerates_missing_code():
+ # Interactive-branch output variants may phrase the code line
+ # differently; the URL alone must still unblock the flow.
+ parsed = gh_handlers.parse_login_banner("Open this URL to continue in your web browser: https://github.com/login/device\n")
+ assert parsed == ("https://github.com/login/device", None)
+
+
+# --- _install resolution --------------------------------------------------------
+
+
+async def test_ensure_gh_cli_is_project_local_and_pooch_driven(monkeypatch, tmp_path):
+ """The system-global gh is never consulted — the binary comes from
+ the pooch-extracted copy under package_dir("gh") (temporal idiom)."""
+ fake_bin = tmp_path / "extracted" / "bin" / ("gh.exe" if gh_install.platform.system() == "Windows" else "gh")
+ fake_bin.parent.mkdir(parents=True)
+ fake_bin.write_text("", encoding="utf-8")
+
+ calls = {}
+
+ def fake_retrieve(**kwargs):
+ calls.update(kwargs)
+ return [str(fake_bin)]
+
+ monkeypatch.setattr(gh_install, "_cached_path", None)
+ monkeypatch.setattr(gh_install, "_package_root", lambda: tmp_path)
+ monkeypatch.setattr(gh_install.pooch, "retrieve", fake_retrieve)
+
+ resolved = await gh_install.ensure_gh_cli()
+ assert resolved == fake_bin
+ assert calls["url"].startswith(gh_install._RELEASE_BASE)
+ assert calls["path"] == tmp_path
+ # cached for subsequent calls without re-fetching
+ def boom(**kwargs):
+ raise AssertionError("must not re-download")
+
+ monkeypatch.setattr(gh_install.pooch, "retrieve", boom)
+ assert await gh_install.ensure_gh_cli() == fake_bin
+
+
+def test_release_assets_pinned_per_platform():
+ version = gh_install._VERSION
+ assert version and version != "latest"
+ for (system, _machine), (asset, binary_name) in gh_install._ASSETS.items():
+ assert version in asset
+ assert binary_name == ("gh.exe" if system == "Windows" else "gh")
+ assert asset.endswith(".zip" if system in ("Windows", "Darwin") else ".tar.gz")
+ # gh's release naming quirk: macOS assets are zips with capital-S "macOS".
+ assert "macOS" in gh_install._ASSETS[("Darwin", "arm64")][0]
+
+
+def test_gh_cli_path_never_touches_system_path():
+ # Project-local contract: no shutil.which anywhere in the plugin.
+ src_install = inspect.getsource(gh_install)
+ src_service = inspect.getsource(gh_service)
+ assert "which(" not in src_install
+ assert "which(" not in src_service
+
+
+# --- operations (no auth pre-flight — Stripe pattern) ---------------------------
+
+
+def _wire(monkeypatch, tmp_path, run_impl):
+ async def fake_ensure():
+ return tmp_path / "gh"
+
+ monkeypatch.setattr(gh_install, "ensure_gh_cli", fake_ensure)
+ monkeypatch.setattr(gh_action_mod, "run_cli_command", run_impl)
+
+
+async def test_pr_list_builds_json_argv(monkeypatch, tmp_path):
+ captured = {}
+
+ async def fake_run(**kwargs):
+ captured.update(kwargs)
+ return {"success": True, "result": [{"number": 1}], "stdout": "[{}]", "stderr": "", "error": None}
+
+ _wire(monkeypatch, tmp_path, fake_run)
+ node = GitHubActionNode()
+ ctx = NodeContext(node_id="g1", node_type="githubAction", workspace_dir=str(tmp_path))
+ out = await node.pr_list(ctx, GitHubActionParams(operation="pr_list", repo="octocat/hello", state="open", limit=5))
+
+ argv = captured["argv"]
+ assert argv[:2] == ["pr", "list"]
+ assert argv[argv.index("--repo") + 1] == "octocat/hello"
+ assert argv[argv.index("--limit") + 1] == "5"
+ assert argv[argv.index("--json") + 1] == gh_action_mod._PR_JSON_FIELDS
+ # env comes from gh_env() — no token was resolved or injected anywhere
+ assert captured["env"]["GH_PAGER"] == "cat"
+ assert out["result"] == [{"number": 1}]
+
+
+async def test_repo_clone_requires_workspace_and_uses_clone_timeout(monkeypatch, tmp_path):
+ captured = {}
+
+ async def fake_run(**kwargs):
+ captured.update(kwargs)
+ return {"success": True, "result": None, "stdout": "", "stderr": "Cloning...", "error": None}
+
+ _wire(monkeypatch, tmp_path, fake_run)
+ node = GitHubActionNode()
+
+ ctx = NodeContext(node_id="g1", node_type="githubAction", workspace_dir=str(tmp_path))
+ await node.repo_clone(ctx, GitHubActionParams(operation="repo_clone", clone_repo="octocat/hello"))
+ assert captured["argv"] == ["repo", "clone", "octocat/hello"]
+ assert captured["cwd"] == str(tmp_path)
+ assert captured["timeout"] == gh_action_mod._CLONE_TIMEOUT
+
+ with pytest.raises(NodeUserError):
+ await node.repo_clone(
+ NodeContext(node_id="g1", node_type="githubAction", workspace_dir=None),
+ GitHubActionParams(operation="repo_clone", clone_repo="octocat/hello"),
+ )
+
+
+async def test_gh_auth_error_surfaces_verbatim_as_node_user_error(monkeypatch, tmp_path):
+ """No pre-flight: gh's own 'not logged in' error IS the auth error."""
+
+ async def fake_run(**kwargs):
+ return {"success": False, "stdout": "", "stderr": "To get started with GitHub CLI, please run: gh auth login", "error": "exit 4"}
+
+ _wire(monkeypatch, tmp_path, fake_run)
+ node = GitHubActionNode()
+ ctx = NodeContext(node_id="g1", node_type="githubAction", workspace_dir=str(tmp_path))
+ with pytest.raises(NodeUserError, match="gh auth login"):
+ await node.issue_list(ctx, GitHubActionParams(operation="issue_list"))
+
+
+async def test_custom_requires_command_and_shlex_splits(monkeypatch, tmp_path):
+ captured = {}
+
+ async def fake_run(**kwargs):
+ captured.update(kwargs)
+ return {"success": True, "result": {"login": "octocat"}, "stdout": "{}", "stderr": "", "error": None}
+
+ _wire(monkeypatch, tmp_path, fake_run)
+ node = GitHubActionNode()
+ ctx = NodeContext(node_id="g1", node_type="githubAction", workspace_dir=str(tmp_path))
+
+ with pytest.raises(NodeUserError):
+ await node.custom(ctx, GitHubActionParams(operation="custom", command=" "))
+
+ await node.custom(ctx, GitHubActionParams(operation="custom", command="release create v1.0.0 --notes 'First release'"))
+ assert captured["argv"] == ["release", "create", "v1.0.0", "--notes", "First release"]
+
+
+def test_node_has_no_auth_preflight():
+ # Stripe-strict: the CLI owns auth; the node must not pre-check it.
+ assert not hasattr(GitHubActionNode, "_preflight")
+ src = inspect.getsource(gh_action_mod)
+ assert "PermissionError" not in src
+
+
+# --- login handler --------------------------------------------------------------
+
+
+async def test_login_answers_within_budget_when_flow_stalls(monkeypatch):
+ async def stalled_flow():
+ await asyncio.sleep(30)
+ return {"success": True, "url": "https://github.com/login/device"}
+
+ monkeypatch.setattr(gh_handlers, "_start_login_flow", stalled_flow)
+ monkeypatch.setattr(gh_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)
+ res = await gh_handlers.handle_github_login({}, websocket=None)
+ assert res["success"] is True
+ assert res.get("pending") is True
+
+
+async def test_login_fast_path_returns_device_url_and_code(monkeypatch):
+ async def instant_flow():
+ return {"success": True, "url": "https://github.com/login/device", "verification_code": "ABCD-1234"}
+
+ monkeypatch.setattr(gh_handlers, "_start_login_flow", instant_flow)
+ res = await gh_handlers.handle_github_login({}, websocket=None)
+ assert res["success"] is True
+ assert res["url"] == "https://github.com/login/device"
+ assert res["verification_code"] == "ABCD-1234"
+
+
+# --- marker-token + broadcast contract (source introspection) -------------------
+
+
+def test_login_success_gates_on_auth_status_then_marks_and_broadcasts():
+ # Marker + broadcast plumbing is the SHARED module (claude/codex/github).
+ assert gh_handlers.mark_logged_in.__module__ == "services.cli_agent._cli_auth"
+ complete = inspect.getsource(gh_handlers._complete_login)
+ # exit code alone is never trusted — `gh auth status` is the gate
+ assert "cli_logged_in" in complete
+ assert 'mark_logged_in("github"' in complete
+ assert "credential.oauth.connected" in complete
+ # the official git bridge runs on success
+ assert "setup-git" in complete
+ # account identity feeds the catalogue's account_label ("Connected as …")
+ assert "_fetch_account" in complete
+ fetch = inspect.getsource(gh_handlers._fetch_account)
+ assert '"api", "user"' in fetch
+
+
+def test_logout_removes_marker_and_broadcasts():
+ assert gh_handlers.mark_logged_out.__module__ == "services.cli_agent._cli_auth"
+ src = inspect.getsource(gh_handlers.handle_github_logout)
+ assert 'mark_logged_out("github")' in src
+ assert "credential.oauth.disconnected" in src
+
+
+def test_login_uses_stripped_env():
+ # login/status/logout must consult gh's OWN store, never env tokens.
+ for fn in (gh_handlers._start_login_flow, gh_handlers.handle_github_logout):
+ assert "login_env" in inspect.getsource(fn)
+ assert "login_env" in inspect.getsource(gh_service.cli_logged_in)
+
+
+def test_ws_handlers_registered():
+ assert set(WS_HANDLERS) == {"github_login", "github_logout", "github_status"}
+
+
+# --- catalogue + assets ----------------------------------------------------------
+
+
+def test_catalogue_entry_is_fieldless_stripe_shape():
+ config = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
+ assert "developer" in config["categories"]
+ github = config["providers"]["github"]
+ assert github["kind"] == "oauth"
+ assert github["category"] == "developer"
+ assert github["icon_ref"] == "lobehub:Github"
+ assert github["ws"] == {"login": "github_login", "logout": "github_logout", "status": "github_status"}
+ # gh owns the token — the modal stores nothing (Stripe shape).
+ assert "fields" not in github
+
+
+def test_credential_class_shape():
+ assert GitHubCredential.id == "github"
+ assert GitHubCredential.auth == "custom"
+
+
+def test_plugin_folder_assets():
+ # Icon is the official lobehub brand glyph via visuals.json — a
+ # co-located icon.svg would silently override it.
+ assert not (PLUGIN_DIR / "icon.svg").exists()
+ meta = json.loads((PLUGIN_DIR / "meta.json").read_text(encoding="utf-8"))
+ assert meta["color"].startswith("#")
+
+ visuals = json.loads((PLUGIN_DIR.parent / "visuals.json").read_text(encoding="utf-8"))
+ entry = visuals["githubAction"]
+ assert entry["icon"] == "lobehub:Github"
+ assert entry["skill"] == "github-skill"
+
+ skill_md = PLUGIN_DIR.parents[1] / "skills" / "github" / "github-skill" / "SKILL.md"
+ assert skill_md.exists()
diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.py
index 708f27fc..dfd1c9c6 100644
--- a/server/tests/test_plugin_self_containment.py
+++ b/server/tests/test_plugin_self_containment.py
@@ -61,6 +61,7 @@ _MIGRATED_PLUGINS = (
"browser",
"code",
"email",
+ "github",
"google",
"stripe",
"telegram",
@@ -73,6 +74,7 @@ _MIGRATED_PLUGINS = (
# ``register_ws_handlers`` from its package ``__init__.py``.
_PLUGINS_WITH_HANDLERS = (
"android",
+ "github",
"google",
"stripe",
"telegram",