Skip to content

Self-improving AI Employees for everyone

feat(nodes): add gcloud node wrapping the Google Cloud CLI

trohitg3f7a543c7025
diff --git a/CLAUDE.md b/CLAUDE.md
index 197fbcec..01feda41 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -31,6 +31,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[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 OpenCompany, 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`. |
| **[Cloudflare Service](./docs-internal/cloudflare_service.md)** | Cloudflare CLI integration — `cloudflareAction` (whoami / zones_list / dns_records CRUD / `graphql_query` / `custom` passthrough; AI tool `cloudflare`) wrapping the official `cf` CLI (npm `[email protected]`, technical preview — "the next version of Wrangler"). **Two cf-specific variants of the CLI-managed-auth pattern**: (1) the CLI opens the browser ITSELF (loopback PKCE callback on fixed port 8877) so the login handler proxies nothing — single-flight guard (concurrent logins collide on the fixed port) + never-kill-the-shim invariant (killing the npm `.cmd` wrapper orphans the node child holding 8877); success gate = `cf auth whoami` JSON (`authenticated: true` — cf exits 0 in BOTH auth states). (2) **Fixed 86-scope OAuth grant with no `--scopes` flag** — only `dns_analytics:read` for analytics; no RUM/zone-analytics OAuth scope exists anywhere, so the optional `cloudflare_api_token` field (injected as `CLOUDFLARE_API_TOKEN`, cf's documented first-priority credential) is the only path to Web Analytics/RUM + the GraphQL Analytics API. `graphql_query` op POSTs the official `client/v4/graphql` endpoint directly (outside the OpenAPI schema cf/SDKs are generated from) — the replacement for the sunsetted Zone Analytics REST API; needs `Account > Account Analytics > Read`. Pinned npm install into the shared packages tree, system cf never consulted (preview argv surface drifts across versions). Palette group `deployment`. |
+| **[Google Cloud Service](./docs-internal/gcloud_service.md)** | Google Cloud CLI integration — `gcloudAction` (auth/config/projects + set_project / Compute Engine instances list-start-stop-describe / Cloud Run deploy-list-describe / Cloud Storage ls-cp-rm / `custom` passthrough; AI tool `gcloud`) wrapping the official gcloud CLI (pinned versioned archive via pooch into `package_dir("gcloud")` — NOT npm; the Windows bundled-python zip keeps the legacy `google-cloud-sdk-` filename prefix, the `-cli-` spelling 404s, locked by test). Cloudflare login variant (CLI opens the browser itself, random loopback port — no fixed-port hazard) + the gh marker-token pattern; success gate = `gcloud auth list --filter=status:ACTIVE --format=json` non-empty (exit codes never trusted). **Config isolation divergence from gh**: every invocation pins `CLOUDSDK_CONFIG=<DATA_DIR>/gcloud/`, so terminal logins against the operator's global gcloud are deliberately NOT visible to the node. ADC note: node login mints gcloud USER creds only (CLI commands never read ADC); client-library code gets ADC via the `custom` op `auth application-default login` (lands isolated in the pinned dir). Cold install ~100 MB → login answers `pending: True` within the 22 s WS budget. Provider id `gcloud` is orthogonal to the Workspace `google` OAuth2 provider. Palette group `deployment`. |
| **[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, 21.5 s cold post-`company clean` — was 71 s before the 2026-07-14 boot-delay fixes; first WS connect 8.29 s) + warm and cold per-phase timelines + optimisation history (lazy LangChain imports, lazy LLM-SDK exception refs, esbuild sidecar bundle, bytecode-at-build, PartySocket reconnect, TanStack Query auth bootstrap, `manualChunks`, Vite dep-cache preservation, off-loop Temporal build-id hash) + bottleneck inventory + reproduction commands + anti-patterns to never reintroduce (incl. eager SDK import at LLM provider registration, unconditional `.vite` wipe, synchronous `Worker()` on the event loop). 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), bytecode pre-compile in two halves — `[tool.uv] compile-bytecode = true` (uv sync compiles `.venv/` site-packages) + `python -m compileall` for project source (plain `.pyc`, **no `-O`** — per PEP 488 the non-`-O` runtimes never load `.opt-1.pyc`; excludes `.venv/`, `tests/`). Single source of truth for the bytecode-compile path list: `cli.commands.build.COMPILEALL_SOURCE_DIRS`. |
@@ -495,7 +496,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 / github / cloudflare.
+- **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 / cloudflare / gcloud.
- **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`.
@@ -617,7 +618,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, github (palette group `vcs`), cloudflare (palette group `deployment`). 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`), cloudflare and gcloud (palette group `deployment`). See [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) for the card index.
## Backend Services
diff --git a/docs-internal/gcloud_service.md b/docs-internal/gcloud_service.md
new file mode 100644
index 00000000..81f09dbf
--- /dev/null
+++ b/docs-internal/gcloud_service.md
@@ -0,0 +1,147 @@
+# Google Cloud Service
+
+Self-contained plugin at [`server/nodes/gcloud/`](../server/nodes/gcloud/)
+wrapping the official **Google Cloud CLI** (`gcloud`, pinned versioned
+archive in `_install.py`). One dual-purpose node — `gcloudAction`
+(workflow node + AI tool `gcloud`) — with typed core operations across
+four surfaces (account/config, Compute Engine, Cloud Run, Cloud
+Storage) plus a `custom` passthrough covering the entire gcloud surface
+(IAM, Cloud SQL, Functions, GKE, logging, `services enable`, ...).
+
+**Auth model: the gcloud CLI owns its own auth** — the Stripe/gh
+pattern, with the cloudflare login variant (the CLI opens the browser
+itself). OpenCompany never stores, reads, or injects a credential:
+
+- `gcloud auth login --quiet` runs Google's OAuth flow with a loopback
+ callback on a **random port** and opens the default browser itself —
+ the handler never parses or proxies the authorize URL (no custom
+ login UI; cf precedent, minus cf's fixed-port collision hazard).
+- Credentials land in **gcloud's own store under the pinned config
+ dir** (see isolation below), not the operator's global gcloud state.
+- The credentials modal's connected badge is a synthetic `cli-managed`
+ **marker OAuth row** (`store_oauth_tokens(provider="gcloud", ...)`),
+ written only after the `gcloud auth list --filter=status:ACTIVE
+ --format=json` probe confirms a live session (gcloud exits 0 in both
+ auth states — exit codes are never trusted) and removed on logout.
+- There is **no auth pre-flight** in the node: gcloud's own "You do
+ not currently have an active account selected" error surfaces
+ verbatim through the `NodeUserError` wrap (plus a Login-button hint).
+
+**Config isolation — the load-bearing divergence from gh.** Every
+invocation (ops AND auth) pins `CLOUDSDK_CONFIG=<DATA_DIR>/gcloud/`
+(the vercel `--global-config` / `CLAUDE_CONFIG_DIR` idiom), so node
+auth state never collides with the operator's own `~/.config/gcloud` /
+`%APPDATA%\gcloud`. Consequence: a terminal `gcloud auth login` against
+the operator's global config is **NOT visible to this node** — by
+design (gh shares terminal sessions; gcloud deliberately does not,
+because gcloud config also carries mutable project/region defaults the
+node must own).
+
+**ADC vs user credentials.** The node login mints gcloud USER
+credentials only — gcloud CLI commands never read Application Default
+Credentials, so nothing more is needed for any node op. Code using
+Google client libraries will NOT see this session via ADC; the
+documented escape hatch is the `custom` op running `auth
+application-default login` (ADC then lands isolated at
+`<DATA_DIR>/gcloud/application_default_credentials.json`).
+
+## File map
+
+| File | Role |
+|---|---|
+| `__init__.py` | `register_ws_handlers(WS_HANDLERS)` + `register_output_schema("gcloudAction", …)`; node auto-registers on import |
+| `gcloud_action.py` | `GCloudActionNode(ActionNode)`, `usable_as_tool=True`, `tool_name="gcloud"`, multi-`@Operation` dispatch; `_run` = `ensure_gcloud_cli()` → `run_cli_command(env=gcloud_env(), cwd=…)` → non-zero exit → `NodeUserError` (stderr tail + Login hint). `ui_hints = {"outputMode": "terminal"}`; `_shape` omits empty keys and never ships raw stdout alongside a parsed `result` |
+| `_handlers.py` | `gcloud_login` / `gcloud_logout` / `gcloud_status`; single-flight guard, 22 s response-budget shield with `pending` fallback (the cold install is ~100 MB), never-kill completion watcher, probe-gated marker + broadcast |
+| `_service.py` | `gcloud_env()` (pinned `CLOUDSDK_CONFIG` + automation baseline: `CLOUDSDK_CORE_DISABLE_PROMPTS=1`, update-check + usage-reporting off, `NO_COLOR=1`), `login_env()` (strips `GOOGLE_APPLICATION_CREDENTIALS` / `CLOUDSDK_AUTH_ACCESS_TOKEN` / account+project overrides), `resolve_gcloud_light()` (no-download binary probe), `active_account()` (the session probe, 30 s — first call pays Python startup), `resolve_workdir()` (workspace-relative cwd) |
+| `_install.py` | `ensure_gcloud_cli()` — **project-local, pooch-driven** (gh idiom): pinned versioned archive extracted under `package_dir("gcloud")`. The system-global gcloud is never consulted. Constant inner root `google-cloud-sdk/`, entry point `bin/gcloud(.cmd)`; `install.sh` deliberately not run (PATH/completion setup only); `gcloud storage` is native core — no `components install` |
+| `_credentials.py` | `GCloudCredential` thin marker (`auth="custom"`, `resolve()` → `{}`); provider id `gcloud` deliberately separate from the Google Workspace `google` OAuth2 provider (different auth model, no storage-key overlap) |
+| `meta.json` | Node color `#4285F4`. No co-located `icon.svg` — icon via `visuals.json: {"gcloudAction": {"icon": "lobehub:googlecloud", "skill": "gcloud-skill"}}` plus the lowercase `"gcloud"` alias (icon + color) required because the skill's `allowed-tools` token is the tool name, not the node type's snake_case |
+
+Paired skill: [`server/skills/gcloud/gcloud-skill/SKILL.md`](../server/skills/gcloud/gcloud-skill/SKILL.md).
+Palette group: `deployment` (shared with vercel/cloudflare — no
+`groups.py` edit). Catalogue entry: fieldless github shape in
+`credential_providers.json` (`kind: "oauth"`, `ws` block, no `fields`)
+— zero frontend edits.
+
+## Install matrix (verified against dl.google.com, v577.0.0)
+
+Base URL `https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/`.
+**Naming quirk locked by test:** the Windows bundled-python zip uses
+the legacy `google-cloud-sdk-` filename prefix; every other versioned
+asset uses `google-cloud-cli-` — the "normalized" Windows `-cli-`
+spelling 404s. Do not fix it on a version bump.
+
+| (system, machine) | Asset | Python |
+|---|---|---|
+| Windows/AMD64 + ARM64 | `google-cloud-sdk-<V>-windows-x86_64-bundled-python.zip` (~111 MB) | bundled (ARM64 runs the x86_64 zip under emulation — no ARM asset exists) |
+| Linux/x86_64 | `google-cloud-cli-<V>-linux-x86_64.tar.gz` (~88 MB) | bundled |
+| Linux/aarch64+arm64 | `google-cloud-cli-<V>-linux-arm.tar.gz` (~61 MB) | system python3 3.9–3.13 (`CLOUDSDK_PYTHON` override) |
+| Darwin/x86_64 + arm64 | `google-cloud-cli-<V>-darwin-{x86_64,arm}.tar.gz` (~61 MB) | system python3 3.9–3.13 |
+
+Cold-install budget: ~700 MB disk under `packages/gcloud/` (pooch
+keeps the archive beside the ~15k-file extraction), 1–4 min wall —
+far past the 22 s WS budget, hence the `pending: True` login response.
+Per-call latency: every op is a fresh Python interpreter (~2–6 s on
+Windows) — noted in `tool_description` so agents don't retry slow
+calls.
+
+## The login flow
+
+`gcloud_login` spawns `gcloud auth login --quiet` with `login_env()`
+and returns `{success, message}` — no url/verification_code (the CLI
+opens the browser itself). Fast path: if `active_account()` is already
+truthy the handler marks + returns without spawning. Hazards handled
+(cf precedent): single-flight guard (repeat clicks return "already in
+progress" instead of a second browser tab), pipes drained for the
+process lifetime, and the completion watcher **never kills the
+process** — on Windows `gcloud.cmd` is a cmd.exe shim around the
+bundled Python; killing the wrapper orphans the child holding the
+loopback callback socket. Background completion: `proc.wait()` ≤ 600 s
+→ gate on `active_account()` → `mark_logged_in("gcloud",
+email=account)` + `credential.oauth.connected` broadcast (shared
+`services/cli_agent/_cli_auth.py` plumbing).
+
+`gcloud_logout`: `gcloud auth revoke --all --quiet` (best-effort —
+hits Google's revocation endpoint; offline failure downgrades to
+success so the marker is still removed) → `credential.oauth.disconnected`.
+`gcloud_status`: `{connected, logged_in, email}` from the probe — no
+side effects.
+
+## Operations
+
+All JSON-capable ops run with `--format=json` (parsed into `result`);
+`project` / `zone` / `region` fields map to `--project` / `--zone` /
+`--region`, appended only when set.
+
+| Op | argv shape | Notes |
+|---|---|---|
+| `auth_list` | `auth list --format=json` | |
+| `config_list` | `config list --format=json` | |
+| `projects_list` | `projects list --format=json --limit N` | |
+| `set_project` | `config set project <id>` | Text output → `stdout` |
+| `compute_instances_list` | `compute instances list --format=json [--zones Z] [--project P]` | |
+| `compute_instance_start/stop` | `compute instances start\|stop <vm> --zone Z --format=json [--project P]` | zone+instance required; 300 s |
+| `compute_instance_describe` | `compute instances describe <vm> --zone Z --format=json [--project P]` | |
+| `run_deploy` | `run deploy <svc> --region R --quiet --format=json (--source D \| --image I) [--allow-unauthenticated] [--project P]` | exactly one of source/image; source cwd = workspace; 900 s (Cloud Build) |
+| `run_services_list` | `run services list --format=json [--region R] [--project P]` | |
+| `run_service_describe` | `run services describe <svc> --region R --format=json [--project P]` | region required |
+| `storage_ls` | `storage ls [gs://url] --format=json [--project P]` | omit url → buckets |
+| `storage_cp` | `storage cp [--recursive] <src> <dst>` | text/progress → `stdout`; cwd = workspace; 600 s |
+| `storage_rm` | `storage rm [--recursive] <gs://url>` | `gs://` prefix enforced |
+| `custom` | verbatim after `gcloud ` (shlex-split) | no `--format` injection; 600 s; cwd = `path`/workspace |
+
+## Tests
+
+[`server/tests/test_gcloud_plugin.py`](../server/tests/test_gcloud_plugin.py):
+env builders (pinned config + hygiene vars; login stripping), install
+resolution (7-key asset map, the Windows `google-cloud-sdk-` prefix
+lock, constant inner root, no `shutil.which`, cached
+`ensure_gcloud_cli`), op argv builders (required-field
+`NodeUserError`s, exactly-one source/image, `gs://` enforcement,
+per-op timeouts, `--project` only-when-set),
+gcloud-error-surfaces-verbatim + `test_node_has_no_auth_preflight`,
+login budget/single-flight/never-kill/no-url-proxying, marker +
+broadcast introspection, fieldless catalogue shape, folder assets +
+skill. Plus the generic `test_plugin_contract.py` /
+`test_plugin_self_containment.py` suites (`gcloud` is in
+`_MIGRATED_PLUGINS` + `_PLUGINS_WITH_HANDLERS`).
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index 762cd104..5dbfdb96 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -580,6 +580,21 @@
}
],
"instructions": "Two independent auth paths: click 'Login with Cloudflare' — the cf CLI (auto-installed via npm) opens your default browser itself and completes via a localhost callback (browser must run on this machine; the badge flips when the CLI finishes; token stored by cf, never by OpenCompany) — or paste an API token above for full-scope and headless use."
+ },
+
+ "gcloud": {
+ "name": "Google Cloud",
+ "category": "deployment",
+ "category_label": "Deployment",
+ "color": "dracula.cyan",
+ "kind": "oauth",
+ "icon_ref": "lobehub:googlecloud",
+ "ws": {
+ "login": "gcloud_login",
+ "logout": "gcloud_logout",
+ "status": "gcloud_status"
+ },
+ "instructions": "Click 'Login with Google Cloud' — the gcloud CLI (auto-installed, ~100 MB on first use) opens your default browser itself for Google sign-in and completes via a localhost callback (browser must run on this machine; the badge flips when the CLI finishes). Credentials are stored by gcloud under OpenCompany's data directory — isolated from any gcloud you may have installed yourself — and OpenCompany never keeps them."
}
}
}
diff --git a/server/nodes/README.md b/server/nodes/README.md
index 30ec7917..b7f48728 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -131,6 +131,7 @@ 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")
cloudflare/ — Cloudflare (cf CLI: zones / DNS / GraphQL analytics / custom; palette group "deployment")
+gcloud/ — Google Cloud (gcloud CLI: projects / Compute Engine / Cloud Run / Cloud Storage / custom; palette group "deployment")
```
---
diff --git a/server/nodes/gcloud/__init__.py b/server/nodes/gcloud/__init__.py
new file mode 100644
index 00000000..d8040be3
--- /dev/null
+++ b/server/nodes/gcloud/__init__.py
@@ -0,0 +1,30 @@
+"""Plugin for the 'deployment' palette group — Google Cloud via the
+gcloud CLI.
+
+Self-contained CLI-managed-auth plugin (gh/Stripe pattern): the gcloud
+CLI owns its auth end-to-end — ``gcloud auth login`` driven from the
+credentials modal opens the browser itself, credentials land in
+gcloud's own store under the pinned ``CLOUDSDK_CONFIG`` dir
+(``<DATA_DIR>/gcloud/``), and a synthetic ``cli-managed`` marker OAuth
+row drives the catalogue badge. OpenCompany never stores or injects a
+token. The SDK itself is project-local and version-pinned under
+``<DATA_DIR>/packages/gcloud/`` — the system gcloud is never consulted.
+"""
+
+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 GCloudCredential
+from ._handlers import WS_HANDLERS
+from .gcloud_action import GCloudActionNode, GCloudActionOutput
+
+register_ws_handlers(WS_HANDLERS)
+register_output_schema("gcloudAction", GCloudActionOutput)
+
+__all__ = [
+ "GCloudCredential",
+ "GCloudActionNode",
+ "WS_HANDLERS",
+]
diff --git a/server/nodes/gcloud/_credentials.py b/server/nodes/gcloud/_credentials.py
new file mode 100644
index 00000000..5bd8aeec
--- /dev/null
+++ b/server/nodes/gcloud/_credentials.py
@@ -0,0 +1,35 @@
+"""Google Cloud credential — thin marker (gh/Stripe idiom).
+
+The gcloud CLI manages its own auth state (credential store under the
+pinned ``CLOUDSDK_CONFIG`` dir, populated by ``gcloud auth login`` and
+cleared by ``gcloud auth revoke``). OpenCompany 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.
+
+Deliberately a SEPARATE provider from the Google Workspace ``google``
+OAuth2 credential: that one holds OpenCompany-managed tokens minted
+with our own OAuth client for the Workspace APIs, while this row is
+only a badge for the gcloud CLI's self-managed session. Different id,
+different auth model, no storage-key overlap.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from services.plugin.credential import Credential
+
+
+class GCloudCredential(Credential):
+ id = "gcloud"
+ display_name = "Google Cloud"
+ category = "Deployment"
+ auth = "custom"
+ docs_url = "https://cloud.google.com/sdk/gcloud"
+
+ @classmethod
+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
+ """Nothing to resolve — auth lives in the gcloud CLI's own
+ credential store under the pinned config dir."""
+ return {}
diff --git a/server/nodes/gcloud/_handlers.py b/server/nodes/gcloud/_handlers.py
new file mode 100644
index 00000000..8c9cd51d
--- /dev/null
+++ b/server/nodes/gcloud/_handlers.py
@@ -0,0 +1,284 @@
+"""Google Cloud WebSocket handlers — the gcloud CLI owns its own auth
+(gh / Stripe / cloudflare pattern), including the browser interaction.
+
+``gcloud_login`` spawns gcloud's official login and lets the CLI drive
+the whole flow itself::
+
+ gcloud auth login --quiet
+
+gcloud runs Google's OAuth flow with a loopback callback server on a
+RANDOM port and OPENS THE DEFAULT BROWSER ITSELF. The handler
+deliberately does NOT parse or proxy the authorize URL to the frontend
+— no custom login UI; the modal just gets ``{success, message}`` and
+the connected badge flips when the background completion broadcasts.
+
+Hazards guarded against (both inherited from the cloudflare plugin):
+
+* **Duplicate flows** — a module-level single-flight guard makes repeat
+ Login clicks return "already in progress" instead of spawning a
+ second browser tab + competing loopback server.
+* **Windows shim orphaning** — ``gcloud.cmd`` is a cmd.exe wrapper
+ around the bundled Python; killing it terminates only the wrapper and
+ orphans the python child holding the loopback callback socket. The
+ completion watcher therefore NEVER kills the process — gcloud exits
+ by itself when the flow completes or the user abandons it.
+
+Success gate: ``gcloud auth list --filter=status:ACTIVE`` returning a
+non-empty account list under the pinned config dir (gcloud exits 0 in
+both auth states, so exit codes are never trusted). On success we write
+the synthetic ``cli-managed`` marker OAuth row (flips the catalogue's
+``stored`` badge, with the account email as the label) and broadcast
+the generic catalogue-invalidation event. Marker + broadcast plumbing
+is the shared :mod:`services.cli_agent._cli_auth` module
+(claude/codex/github/cloudflare all use it).
+
+OpenCompany never stores or reads the actual credentials — they stay in
+gcloud's own store under ``<DATA_DIR>/gcloud/``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any, Dict, List, Optional
+
+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_gcloud_cli
+from ._service import active_account, login_env
+
+logger = get_logger(__name__)
+
+# --quiet suppresses the "You are about to log in..." Y/n confirmation;
+# gcloud still opens the browser and serves the loopback callback.
+_LOGIN_ARGS = ["auth", "login", "--quiet"]
+_LOGIN_TIMEOUT_SECONDS = 600
+# The frontend drops WS requests after 30s. A first-ever login pays the
+# cold SDK install (~100 MB download + large extraction) inside this
+# handler — answer within this budget no matter what and let the flow
+# continue in the background.
+_RESPONSE_BUDGET_SECONDS = 22
+# Retained head of the CLI's output, used only for the failure log line.
+_OUTPUT_CAP_BYTES = 8192
+
+
+# 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()
+
+# Single-flight state: at most one login flow at a time. `task` covers
+# the pre-spawn window (install + session probe), `proc` covers the
+# browser-flow window until gcloud exits on its own.
+_active_login: Dict[str, Any] = {"task": None, "proc": None}
+
+
+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 _login_in_progress() -> bool:
+ task = _active_login["task"]
+ if task is not None and not task.done():
+ return True
+ proc = _active_login["proc"]
+ return proc is not None and proc.returncode is None
+
+
+async def _mark_connected(email: Optional[str]) -> None:
+ await mark_logged_in("gcloud", email=email)
+ logger.info("[GCloud] connected as %s — catalogue marker persisted", email or "<unknown>")
+ await broadcast_credential_event("credential.oauth.connected", provider="gcloud")
+
+
+async def _start_login_flow() -> Dict[str, Any]:
+ """Install (if needed) + spawn gcloud's own browser login. Never
+ raises — returns the WS response dict. The CLI owns the interaction
+ from here: it opens the browser, serves the loopback callback, and
+ exits when done; we only watch for the exit in the background."""
+ try:
+ try:
+ binary = str(await ensure_gcloud_cli())
+ except Exception as e:
+ logger.warning("[GCloud] Google Cloud CLI install failed: %s", e)
+ return {
+ "success": False,
+ "error": f"Google Cloud CLI install failed ({e}). Manual install: https://cloud.google.com/sdk/docs/install",
+ }
+
+ # Fast path: a live session already exists under the pinned
+ # config dir (a previous flow completed after the modal closed).
+ info = await active_account()
+ if info:
+ email = info.get("account")
+ await _mark_connected(email)
+ return {"success": True, "message": f"Already logged in{f' as {email}' if email else ''}."}
+
+ # stdin=PIPE left un-written: prompts are disabled via --quiet +
+ # CLOUDSDK_CORE_DISABLE_PROMPTS, and 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(),
+ )
+ _active_login["proc"] = proc
+
+ # Drain both pipes for the process lifetime so gcloud never
+ # blocks on a full pipe buffer while its callback server waits.
+ # Only a small head is retained — solely for the failure log.
+ output: List[str] = []
+
+ async def drain(stream: Optional[asyncio.StreamReader]) -> None:
+ if stream is None:
+ return
+ kept = 0
+ while True:
+ chunk = await stream.read(4096)
+ if not chunk:
+ break
+ if kept < _OUTPUT_CAP_BYTES:
+ text = chunk.decode(errors="replace")
+ output.append(text)
+ kept += len(text)
+
+ _spawn_background(drain(proc.stdout))
+ _spawn_background(drain(proc.stderr))
+ _spawn_background(_complete_login(proc, output))
+
+ logger.info(
+ "[GCloud] gcloud auth login spawned (pid=%s) — gcloud opens the browser itself; awaiting completion in background (timeout=%ss)",
+ proc.pid,
+ _LOGIN_TIMEOUT_SECONDS,
+ )
+ return {
+ "success": True,
+ "message": "gcloud is opening your default browser — complete the Google sign-in there.",
+ }
+ except Exception as e:
+ logger.exception("[GCloud] login flow raised unexpectedly: %s", e)
+ return {"success": False, "error": f"Google Cloud login failed: {e}"}
+
+
+async def handle_gcloud_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Single-flight + answer within the frontend's request window no
+ matter what (vercel's cold-install pending pattern)."""
+ if _login_in_progress():
+ logger.info("[GCloud] login request ignored — a flow is already in progress")
+ return {
+ "success": True,
+ "pending": True,
+ "message": (
+ "A Google Cloud login is already in progress — complete it in the browser "
+ "window gcloud opened (it may still be preparing)."
+ ),
+ }
+
+ logger.info("[GCloud] login flow starting (gcloud auth login)")
+ flow = _spawn_background(_start_login_flow())
+ _active_login["task"] = flow
+ try:
+ return await asyncio.wait_for(asyncio.shield(flow), timeout=_RESPONSE_BUDGET_SECONDS)
+ except asyncio.TimeoutError:
+ logger.info(
+ "[GCloud] login still preparing after %ss (cold SDK install) — continuing in background",
+ _RESPONSE_BUDGET_SECONDS,
+ )
+ return {
+ "success": True,
+ "pending": True,
+ "message": (
+ "The Google Cloud CLI is being installed (~100 MB on first use) — "
+ "the browser will open automatically when it is ready."
+ ),
+ }
+
+
+async def _complete_login(proc: asyncio.subprocess.Process, output: List[str]) -> None:
+ """Await gcloud's loopback-callback flow; gate success on the
+ ``auth list`` probe (exit codes are not trusted — gcloud exits 0
+ either way); then the marker + broadcast.
+
+ Never kills the process: on Windows the entry point is a
+ ``gcloud.cmd`` shim, and killing the wrapper orphans the python
+ child holding the loopback callback socket. gcloud exits by itself
+ when the flow completes or is abandoned.
+ """
+ try:
+ try:
+ returncode = await asyncio.wait_for(proc.wait(), timeout=_LOGIN_TIMEOUT_SECONDS)
+ except asyncio.TimeoutError:
+ logger.warning(
+ "[GCloud] login still running after %ss — leaving it to finish on its own (killing the shim would orphan the callback server)",
+ _LOGIN_TIMEOUT_SECONDS,
+ )
+ return
+
+ info = await active_account()
+ if not info:
+ tail = "".join(output).strip().splitlines()
+ banner = " | ".join(ln.strip() for ln in tail[-5:] if ln.strip()) or "(no output)"
+ logger.warning(
+ "[GCloud] login exited (code=%s) but 'gcloud auth list' reports no active account. CLI said: %s",
+ returncode,
+ banner,
+ )
+ return
+
+ await _mark_connected(info.get("account"))
+ except Exception as e:
+ logger.exception("[GCloud] login completion raised unexpectedly: %s", e)
+ finally:
+ if _active_login["proc"] is proc:
+ _active_login["proc"] = None
+
+
+async def handle_gcloud_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """``gcloud auth revoke --all`` (best-effort — hits Google's
+ revocation endpoint, and exits non-zero when nothing is stored),
+ drop the catalogue marker, broadcast so the modal flips
+ immediately."""
+ logger.info("[GCloud] logout starting")
+ from ._service import resolve_gcloud_light
+
+ binary = resolve_gcloud_light()
+ result: Dict[str, Any] = {"success": True}
+ if binary:
+ result = await run_cli_command(
+ binary=binary,
+ argv=["auth", "revoke", "--all", "--quiet"],
+ timeout=30.0,
+ env=login_env(),
+ )
+ if not result.get("success"):
+ logger.warning("[GCloud] 'gcloud auth revoke' failed (marker still removed): %s", result.get("error"))
+ result = {"success": True, "message": "gcloud reported no stored session; catalogue marker removed"}
+ await mark_logged_out("gcloud")
+ await broadcast_credential_event("credential.oauth.disconnected", provider="gcloud")
+ logger.info("[GCloud] logout complete: marker removed + catalogue broadcast sent")
+ return result
+
+
+async def handle_gcloud_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Session snapshot straight from the CLI — no side effects."""
+ info = await active_account()
+ connected = info is not None
+ status: Dict[str, Any] = {"connected": connected, "logged_in": connected}
+ if info and info.get("account"):
+ status["email"] = info["account"]
+ return {"success": True, "status": status}
+
+
+WS_HANDLERS = {
+ "gcloud_login": handle_gcloud_login,
+ "gcloud_logout": handle_gcloud_logout,
+ "gcloud_status": handle_gcloud_status,
+}
diff --git a/server/nodes/gcloud/_install.py b/server/nodes/gcloud/_install.py
new file mode 100644
index 00000000..affc7434
--- /dev/null
+++ b/server/nodes/gcloud/_install.py
@@ -0,0 +1,180 @@
+"""Google Cloud CLI (`gcloud`) downloader — pooch-driven, project-local.
+
+Mirrors :mod:`server.nodes.github._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 versioned URL and
+the per-platform asset map.
+
+The SDK lands under ``<DATA_DIR>/packages/gcloud/`` — the same
+:func:`core.paths.package_dir` root that holds the gh / Stripe /
+Temporal binaries. The system-global gcloud is deliberately never
+consulted, so node behavior doesn't depend on whatever version is on
+the operator's PATH. Auth state is fully isolated too: every
+invocation pins ``CLOUDSDK_CONFIG`` under the data dir (see
+``_service.gcloud_env``), so this install never reads or writes the
+operator's own ``~/.config/gcloud`` / ``%APPDATA%\\gcloud``.
+
+Asset matrix notes (verified against dl.google.com):
+
+- The Windows bundled-python zip uses the legacy ``google-cloud-sdk-``
+ filename prefix; every other versioned asset uses
+ ``google-cloud-cli-``. Do NOT "normalize" the Windows name on a
+ version bump — the ``-cli-`` spelling 404s.
+- Windows has no ARM64 asset; ARM64 maps to the x86_64 bundled-python
+ zip (runs under x64 emulation).
+- linux-x86_64 and the Windows zip bundle their own Python; darwin and
+ linux-arm archives do NOT — they need a system python3 (3.9-3.13),
+ overridable via ``CLOUDSDK_PYTHON``.
+- The archives are directly runnable after extraction: ``install.sh`` /
+ ``install.bat`` only do PATH/completion setup and are deliberately
+ not run. ``gcloud storage`` is native core — no ``components
+ install`` step either.
+"""
+
+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 = "577.0.0"
+_DL_BASE = "https://dl.google.com/dl/cloudsdk/channels/rapid/downloads"
+
+_WINDOWS_ASSET = f"google-cloud-sdk-{_VERSION}-windows-x86_64-bundled-python.zip"
+
+# (system, machine) -> (asset filename, binary name inside google-cloud-sdk/bin/).
+_ASSETS: dict[Tuple[str, str], Tuple[str, str]] = {
+ ("Windows", "AMD64"): (_WINDOWS_ASSET, "gcloud.cmd"),
+ ("Windows", "ARM64"): (_WINDOWS_ASSET, "gcloud.cmd"),
+ ("Linux", "x86_64"): (f"google-cloud-cli-{_VERSION}-linux-x86_64.tar.gz", "gcloud"),
+ ("Linux", "aarch64"): (f"google-cloud-cli-{_VERSION}-linux-arm.tar.gz", "gcloud"),
+ ("Linux", "arm64"): (f"google-cloud-cli-{_VERSION}-linux-arm.tar.gz", "gcloud"),
+ ("Darwin", "x86_64"): (f"google-cloud-cli-{_VERSION}-darwin-x86_64.tar.gz", "gcloud"),
+ ("Darwin", "arm64"): (f"google-cloud-cli-{_VERSION}-darwin-arm.tar.gz", "gcloud"),
+}
+
+_cached_path: Optional[Path] = None
+_install_lock = asyncio.Lock()
+
+
+def _package_root() -> Path:
+ from core.paths import package_dir
+
+ p = package_dir("gcloud")
+ 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 Google Cloud CLI for {key}. Supported: {sorted(_ASSETS)}. "
+ "See https://cloud.google.com/sdk/docs/install"
+ )
+ 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``. Unlike gh's version-suffixed inner dir, every
+ Google Cloud CLI archive extracts to the constant inner root
+ ``google-cloud-sdk/``."""
+ asset_name, binary_name = _platform_asset()
+ suffix = ".unzip" if asset_name.endswith(".zip") else ".untar"
+ return _package_root() / f"{asset_name}{suffix}" / "google-cloud-sdk" / "bin" / binary_name
+
+
+def gcloud_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_gcloud_cli() -> Path:
+ """Return absolute path to the project-local gcloud entry point,
+ downloading the pinned release on miss. Idempotent + concurrent-safe.
+
+ Cold path is heavy: 61-111 MB download plus a large extraction
+ (~15k files). Runs in a worker thread under the install lock, so
+ nothing blocks the event loop — callers on the WS path use the
+ pending-response pattern to stay inside the frontend's budget.
+ """
+ global _cached_path
+ existing = gcloud_cli_path()
+ if existing:
+ return existing
+
+ async with _install_lock:
+ existing = gcloud_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 Google Cloud CLI release via pooch.
+
+ ``known_hash=None``: the URL is version-pinned and served over TLS
+ from Google's CDN (temporal/gh precedent — transport integrity
+ without hand-maintaining per-platform hashes).
+ """
+ asset_name, _ = _platform_asset()
+ url = f"{_DL_BASE}/{asset_name}"
+ logger.info("[GCloud] downloading Google Cloud CLI v%s from %s", _VERSION, url)
+
+ processor = pooch.Unzip() if asset_name.endswith(".zip") else pooch.Untar()
+ try:
+ 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),
+ )
+ except Exception as e:
+ raise RuntimeError(
+ f"Google Cloud CLI download failed: {e}. "
+ "Note: darwin/linux-arm archives need a system python3 3.9-3.13 at "
+ "runtime (override with CLOUDSDK_PYTHON)."
+ ) from e
+
+ # The archive is huge (~15k files) — resolve the entry point
+ # directly instead of scanning pooch's extracted-files list.
+ binary = _extracted_binary_path()
+ if not binary.exists():
+ raise RuntimeError(f"[GCloud] gcloud entry point not found at {binary} after extracting {asset_name}")
+ if platform.system() != "Windows":
+ # Untar preserves modes; belt-and-suspenders on the bin/ tree so
+ # gcloud and its sibling launchers are always executable.
+ for item in binary.parent.iterdir():
+ if item.is_file():
+ item.chmod(item.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+ logger.info("[GCloud] Google Cloud CLI installed at %s", binary)
+ return binary
+
+
+__all__ = ["ensure_gcloud_cli", "gcloud_cli_path"]
diff --git a/server/nodes/gcloud/_service.py b/server/nodes/gcloud/_service.py
new file mode 100644
index 00000000..1c8ad08c
--- /dev/null
+++ b/server/nodes/gcloud/_service.py
@@ -0,0 +1,138 @@
+"""Shared Google Cloud plugin helpers — subprocess env builders and the
+gcloud session probe.
+
+Auth model — **the gcloud CLI owns its own auth end-to-end** (gh/Stripe
+pattern): ``gcloud auth login`` (driven by the modal's Login button)
+runs Google's OAuth flow with a loopback callback on a RANDOM port and
+opens the default browser itself — the handlers never parse or proxy
+its output. Credentials land in gcloud's own credential store under the
+pinned config dir. OpenCompany never stores or reads a token — a
+synthetic ``cli-managed`` marker OAuth row flips the catalogue's
+``stored`` badge, exactly like gh/cloudflare.
+
+Config isolation — every invocation (ops AND auth) pins
+``CLOUDSDK_CONFIG`` to ``<DATA_DIR>/gcloud/`` (the vercel
+``--global-config`` / ``CLAUDE_CONFIG_DIR`` idiom), so node auth state
+never collides with the operator's own ``~/.config/gcloud`` /
+``%APPDATA%\\gcloud``. A terminal session against the operator's global
+config is therefore NOT visible to this node — by design.
+
+ADC note: ``gcloud auth login`` mints gcloud USER credentials only.
+gcloud CLI commands never read Application Default Credentials, so the
+node needs nothing more; code using Google client libraries won't see
+this session via ADC. The documented escape hatch is the node's
+``custom`` op running ``auth application-default login`` (ADC then
+lands isolated at ``<DATA_DIR>/gcloud/application_default_credentials.json``).
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any, Dict, Optional
+
+# Ambient credential/config env vars that would mask the pinned-config
+# session probe or short-circuit login (gcloud resolves
+# CLOUDSDK_AUTH_ACCESS_TOKEN and account/project overrides env-first).
+_AMBIENT_CREDENTIAL_VARS = (
+ "GOOGLE_APPLICATION_CREDENTIALS",
+ "CLOUDSDK_AUTH_ACCESS_TOKEN",
+ "CLOUDSDK_CORE_ACCOUNT",
+ "CLOUDSDK_CORE_PROJECT",
+ "GOOGLE_CLOUD_PROJECT",
+)
+
+
+def _config_dir() -> str:
+ from core.paths import data_path
+
+ p = data_path("gcloud")
+ p.mkdir(parents=True, exist_ok=True)
+ return str(p)
+
+
+def gcloud_env() -> Dict[str, str]:
+ """Child env for every gcloud invocation — pinned isolated config
+ dir plus the documented automation baseline (no interactive
+ prompts, no update nags, no usage reporting, no ANSI)."""
+ env = os.environ.copy()
+ env["CLOUDSDK_CONFIG"] = _config_dir()
+ env["CLOUDSDK_CORE_DISABLE_PROMPTS"] = "1"
+ env["CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK"] = "1"
+ env["CLOUDSDK_CORE_DISABLE_USAGE_REPORTING"] = "1"
+ env["NO_COLOR"] = "1"
+ return env
+
+
+def login_env() -> Dict[str, str]:
+ """Env for ``gcloud auth login`` / ``auth list`` / ``auth revoke``
+ — the CLI must consult its OWN credential store under the pinned
+ config dir, so ambient credential/account overrides are stripped:
+ with ``CLOUDSDK_AUTH_ACCESS_TOKEN`` (or an account override) set,
+ the session probe would report the ambient identity instead of the
+ stored login."""
+ env = gcloud_env()
+ for var in _AMBIENT_CREDENTIAL_VARS:
+ env.pop(var, None)
+ return env
+
+
+def resolve_gcloud_light() -> Optional[str]:
+ """The project-local gcloud entry point WITHOUT triggering the
+ (heavy) install. ``None`` when it has never been installed (status
+ then reports disconnected; login / ops install on demand). The
+ system-global gcloud is deliberately never consulted."""
+ from ._install import gcloud_cli_path
+
+ cached = gcloud_cli_path()
+ return str(cached) if cached else None
+
+
+def resolve_workdir(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 (github ``resolve_repo_path`` idiom)."""
+ from pathlib import Path
+
+ from services.plugin.base import NodeUserError
+
+ 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)
+
+
+async def active_account() -> Optional[Dict[str, Any]]:
+ """The ACTIVE credentialed account from ``gcloud auth list`` (under
+ the pinned config dir), else ``None``. gcloud exits 0 with an empty
+ JSON array when logged out — the non-empty array is the only
+ signal, so exit codes are never consulted. Best-effort: ``None``
+ when gcloud isn't installed.
+
+ 30s timeout (vs the usual 15s probes): the first-ever gcloud call
+ pays Python interpreter startup plus config-dir creation, which is
+ slow on Windows.
+ """
+ from services.events import run_cli_command
+
+ binary = resolve_gcloud_light()
+ if not binary:
+ return None
+ result = await run_cli_command(
+ binary=binary,
+ argv=["auth", "list", "--filter=status:ACTIVE", "--format=json"],
+ timeout=30.0,
+ env=login_env(),
+ )
+ accounts = result.get("result")
+ if not isinstance(accounts, list) or not accounts:
+ return None
+ first = accounts[0]
+ return first if isinstance(first, dict) else None
diff --git a/server/nodes/gcloud/gcloud_action.py b/server/nodes/gcloud/gcloud_action.py
new file mode 100644
index 00000000..68f9891c
--- /dev/null
+++ b/server/nodes/gcloud/gcloud_action.py
@@ -0,0 +1,429 @@
+"""Google Cloud Action — typed core operations over the gcloud CLI,
+plus a raw-command passthrough.
+
+The gcloud CLI owns its own auth (gh/Stripe pattern): no pre-flight
+check and no token injection here — gcloud reads its own credential
+store under the pinned ``CLOUDSDK_CONFIG`` dir (populated by ``gcloud
+auth login`` from the credentials modal), and its own "no active
+account" error surfaces through the ``NodeUserError`` wrap. JSON-capable
+operations use ``--format=json`` for machine-readable results.
+"""
+
+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 GCloudCredential
+
+_PROJECT_OPS = [
+ "projects_list",
+ "compute_instances_list", "compute_instance_start", "compute_instance_stop", "compute_instance_describe",
+ "run_deploy", "run_services_list", "run_service_describe",
+ "storage_ls", "storage_cp", "storage_rm",
+]
+_SET_PROJECT = {"displayOptions": {"show": {"operation": ["set_project"]}}}
+_COMPUTE = {"displayOptions": {"show": {"operation": ["compute_instances_list", "compute_instance_start", "compute_instance_stop", "compute_instance_describe"]}}}
+_COMPUTE_INSTANCE = {"displayOptions": {"show": {"operation": ["compute_instance_start", "compute_instance_stop", "compute_instance_describe"]}}}
+_RUN_REGION = {"displayOptions": {"show": {"operation": ["run_deploy", "run_service_describe", "run_services_list"]}}}
+_RUN_SERVICE = {"displayOptions": {"show": {"operation": ["run_deploy", "run_service_describe"]}}}
+_RUN_DEPLOY = {"displayOptions": {"show": {"operation": ["run_deploy"]}}}
+_STORAGE_URL = {"displayOptions": {"show": {"operation": ["storage_ls", "storage_rm"]}}}
+_STORAGE_CP = {"displayOptions": {"show": {"operation": ["storage_cp"]}}}
+_STORAGE_RECURSIVE = {"displayOptions": {"show": {"operation": ["storage_cp", "storage_rm"]}}}
+_PROJECTS_LIST = {"displayOptions": {"show": {"operation": ["projects_list"]}}}
+_PATH_OPS = {"displayOptions": {"show": {"operation": ["run_deploy", "storage_cp", "custom"]}}}
+_CUSTOM = {"displayOptions": {"show": {"operation": ["custom"]}}}
+
+_ONESHOT_TIMEOUT = 120.0
+_MUTATION_TIMEOUT = 300.0
+_TRANSFER_TIMEOUT = 600.0
+_DEPLOY_TIMEOUT = 900.0
+_STDERR_TAIL_CHARS = 2000
+
+
+class GCloudActionParams(BaseModel):
+ operation: Literal[
+ "auth_list", "config_list", "projects_list", "set_project",
+ "compute_instances_list", "compute_instance_start", "compute_instance_stop", "compute_instance_describe",
+ "run_deploy", "run_services_list", "run_service_describe",
+ "storage_ls", "storage_cp", "storage_rm",
+ "custom",
+ ] = "config_list"
+
+ # Shared: gcloud falls back to the configured default project when
+ # unset (config set project); set explicitly to operate elsewhere.
+ project: str = Field(
+ default="",
+ description="Target project id (optional — defaults to the configured project)",
+ json_schema_extra={
+ "placeholder": "my-project-123",
+ "displayOptions": {"show": {"operation": _PROJECT_OPS}},
+ },
+ )
+
+ # set_project
+ project_id: str = Field(
+ default="",
+ description="Project id to set as the configuration default",
+ json_schema_extra={"placeholder": "my-project-123", **_SET_PROJECT},
+ )
+
+ # compute
+ zone: str = Field(
+ default="",
+ description="Compute zone (required for instance start/stop/describe; optional --zones filter for list)",
+ json_schema_extra={"placeholder": "us-central1-a", **_COMPUTE},
+ )
+ instance: str = Field(
+ default="",
+ description="Compute Engine instance name",
+ json_schema_extra={"placeholder": "my-vm", **_COMPUTE_INSTANCE},
+ )
+
+ # cloud run
+ region: str = Field(
+ default="",
+ description="Cloud Run region (required for deploy/describe; optional filter for list)",
+ json_schema_extra={"placeholder": "us-central1", **_RUN_REGION},
+ )
+ service: str = Field(
+ default="",
+ description="Cloud Run service name",
+ json_schema_extra={"placeholder": "my-service", **_RUN_SERVICE},
+ )
+ source: str = Field(
+ default="",
+ description="Deploy from source directory (mutually exclusive with image)",
+ json_schema_extra={"placeholder": ". or ./app (relative to the workspace)", **_RUN_DEPLOY},
+ )
+ image: str = Field(
+ default="",
+ description="Deploy a container image (mutually exclusive with source)",
+ json_schema_extra={"placeholder": "gcr.io/my-project/my-image", **_RUN_DEPLOY},
+ )
+ allow_unauthenticated: bool = Field(default=False, json_schema_extra=_RUN_DEPLOY)
+
+ # storage
+ url: str = Field(
+ default="",
+ description="Cloud Storage URL (optional for ls; required for rm)",
+ json_schema_extra={"placeholder": "gs://my-bucket/path", **_STORAGE_URL},
+ )
+ src: str = Field(
+ default="",
+ description="Copy source — local path or gs:// URL",
+ json_schema_extra={"placeholder": "./file.txt or gs://bucket/file.txt", **_STORAGE_CP},
+ )
+ dst: str = Field(
+ default="",
+ description="Copy destination — local path or gs:// URL",
+ json_schema_extra={"placeholder": "gs://bucket/dir/ or ./downloads/", **_STORAGE_CP},
+ )
+ recursive: bool = Field(default=False, json_schema_extra=_STORAGE_RECURSIVE)
+
+ # projects_list
+ limit: int = Field(default=50, ge=1, le=500, json_schema_extra=_PROJECTS_LIST)
+
+ # Working directory (relative → workflow workspace).
+ path: str = Field(
+ default="",
+ json_schema_extra={
+ "placeholder": "Working directory (defaults to the workflow workspace)",
+ **_PATH_OPS,
+ },
+ )
+
+ # custom
+ command: str = Field(
+ default="",
+ description="gcloud CLI command, exactly as typed after 'gcloud '",
+ json_schema_extra={
+ "placeholder": "iam service-accounts list | sql instances list | functions deploy ...",
+ **_CUSTOM,
+ },
+ )
+
+ model_config = ConfigDict(extra="ignore")
+
+
+class GCloudActionOutput(BaseModel):
+ operation: Optional[str] = None
+ success: Optional[bool] = None
+ result: Optional[Any] = None
+ stdout: Optional[str] = None
+ stderr_tail: Optional[str] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class GCloudActionNode(ActionNode):
+ type = "gcloudAction"
+ display_name = "Google Cloud"
+ subtitle = "gcloud CLI"
+ group = ("deployment", "tool")
+ description = (
+ "Google Cloud via the gcloud CLI — projects, Compute Engine instances, "
+ "Cloud Run deploys, Cloud Storage, or any gcloud command"
+ )
+ component_kind = "square"
+ tool_name = "gcloud"
+ tool_description = (
+ "Interact with Google Cloud via the gcloud CLI. Operations: auth_list / config_list "
+ "(session + config snapshot), projects_list, set_project (sets the default project — "
+ "run this first if commands complain about a missing project), compute_instances_list / "
+ "compute_instance_start / compute_instance_stop / compute_instance_describe (zone required "
+ "for the last three), run_deploy (Cloud Run — exactly one of source/image, region required; "
+ "builds can take minutes), run_services_list / run_service_describe, storage_ls / storage_cp "
+ "/ storage_rm (gs:// URLs), custom (any other gcloud command — pass 'command' exactly as "
+ "typed after 'gcloud ', e.g. 'iam service-accounts list', 'sql instances list', "
+ "'functions deploy my-fn --runtime python312 --trigger-http', 'auth application-default "
+ "login' to mint ADC for client libraries). The project/zone/region fields map to "
+ "--project/--zone/--region flags. Auth is managed by the gcloud CLI itself — connect via "
+ "Credentials -> Google Cloud (Login button). Each call starts a fresh gcloud process "
+ "(a few seconds of startup latency is normal). "
+ "Reference: https://cloud.google.com/sdk/gcloud/reference"
+ )
+ handles = (
+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
+ )
+ # start/stop/deploy/rm mutate cloud state.
+ annotations = {"destructive": True, "readonly": False, "open_world": True}
+ # OutputPanel renders textual output preformatted (gcloud tables /
+ # copy progress are terminal text, not markdown).
+ ui_hints = {"outputMode": "terminal"}
+ credentials = (GCloudCredential,)
+ task_queue = TaskQueue.REST_API
+ usable_as_tool = True
+
+ Params = GCloudActionParams
+ Output = GCloudActionOutput
+
+ # ---- shared plumbing -------------------------------------------------
+
+ async def _run(
+ self,
+ argv: List[str],
+ *,
+ cwd: Optional[str] = None,
+ timeout: float = _ONESHOT_TIMEOUT,
+ ) -> Dict[str, Any]:
+ """No auth pre-flight (gh/Stripe pattern) — gcloud authenticates
+ from its own credential store under the pinned config dir, and
+ its error (including "You do not currently have an active
+ account selected") surfaces via the NodeUserError wrap below."""
+ from ._install import ensure_gcloud_cli
+ from ._service import gcloud_env
+
+ try:
+ binary = str(await ensure_gcloud_cli())
+ except Exception as e:
+ raise RuntimeError(f"Google Cloud CLI install failed: {e}") from e
+
+ result = await run_cli_command(
+ binary=binary,
+ argv=argv,
+ timeout=timeout,
+ env=gcloud_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 "gcloud invocation failed")
+ raise NodeUserError(
+ f"gcloud {argv[0]} failed: {detail} "
+ "(if this is an auth error, connect via Credentials -> Google Cloud -> Login)"
+ )
+ return result
+
+ def _cwd(self, ctx: NodeContext, path: str, *, required: bool = False) -> Optional[str]:
+ from ._service import resolve_workdir
+
+ if not path and not required and not ctx.workspace_dir:
+ return None
+ return resolve_workdir(ctx.workspace_dir, path.strip())
+
+ @staticmethod
+ def _project_flag(params: "GCloudActionParams") -> List[str]:
+ return ["--project", params.project.strip()] if params.project.strip() else []
+
+ @staticmethod
+ def _shape(operation: str, result: Dict[str, Any]) -> Dict[str, Any]:
+ """Output-panel shaping: when gcloud returned JSON
+ (--format=json ops), 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}
+ 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
+
+ # ---- core account / project ops --------------------------------------
+
+ @Operation("auth_list", cost={"service": "gcloud", "action": "auth_list", "count": 1})
+ async def auth_list(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ result = await self._run(["auth", "list", "--format=json"])
+ return self._shape("auth_list", result)
+
+ @Operation("config_list", cost={"service": "gcloud", "action": "config_list", "count": 1})
+ async def config_list(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ result = await self._run(["config", "list", "--format=json"])
+ return self._shape("config_list", result)
+
+ @Operation("projects_list", cost={"service": "gcloud", "action": "projects_list", "count": 1})
+ async def projects_list(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ argv = ["projects", "list", "--format=json", "--limit", str(params.limit)]
+ result = await self._run(argv)
+ return self._shape("projects_list", result)
+
+ @Operation("set_project", cost={"service": "gcloud", "action": "set_project", "count": 1})
+ async def set_project(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ project_id = params.project_id.strip()
+ if not project_id:
+ raise NodeUserError("project_id is required (e.g. 'my-project-123')")
+ result = await self._run(["config", "set", "project", project_id])
+ return self._shape("set_project", result)
+
+ # ---- compute engine ---------------------------------------------------
+
+ @Operation("compute_instances_list", cost={"service": "gcloud", "action": "compute_instances_list", "count": 1})
+ async def compute_instances_list(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ argv = ["compute", "instances", "list", "--format=json"]
+ if params.zone.strip():
+ argv += ["--zones", params.zone.strip()]
+ argv += self._project_flag(params)
+ result = await self._run(argv)
+ return self._shape("compute_instances_list", result)
+
+ def _compute_instance_argv(self, verb: str, params: GCloudActionParams) -> List[str]:
+ instance = params.instance.strip()
+ if not instance:
+ raise NodeUserError(f"instance is required for compute_instance_{verb}")
+ zone = params.zone.strip()
+ if not zone:
+ raise NodeUserError(f"zone is required for compute_instance_{verb} (e.g. 'us-central1-a')")
+ return ["compute", "instances", verb, instance, "--zone", zone, "--format=json", *self._project_flag(params)]
+
+ @Operation("compute_instance_start", cost={"service": "gcloud", "action": "compute_instance_start", "count": 1})
+ async def compute_instance_start(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ result = await self._run(self._compute_instance_argv("start", params), timeout=_MUTATION_TIMEOUT)
+ return self._shape("compute_instance_start", result)
+
+ @Operation("compute_instance_stop", cost={"service": "gcloud", "action": "compute_instance_stop", "count": 1})
+ async def compute_instance_stop(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ result = await self._run(self._compute_instance_argv("stop", params), timeout=_MUTATION_TIMEOUT)
+ return self._shape("compute_instance_stop", result)
+
+ @Operation("compute_instance_describe", cost={"service": "gcloud", "action": "compute_instance_describe", "count": 1})
+ async def compute_instance_describe(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ result = await self._run(self._compute_instance_argv("describe", params))
+ return self._shape("compute_instance_describe", result)
+
+ # ---- cloud run ----------------------------------------------------------
+
+ @Operation("run_deploy", cost={"service": "gcloud", "action": "run_deploy", "count": 1})
+ async def run_deploy(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ service = params.service.strip()
+ if not service:
+ raise NodeUserError("service is required (the Cloud Run service name)")
+ region = params.region.strip()
+ if not region:
+ raise NodeUserError("region is required for run_deploy (e.g. 'us-central1')")
+ source = params.source.strip()
+ image = params.image.strip()
+ if bool(source) == bool(image):
+ raise NodeUserError("Set exactly one of source (deploy from directory) or image (deploy a container image)")
+ argv = ["run", "deploy", service, "--region", region, "--quiet", "--format=json"]
+ if source:
+ argv += ["--source", source]
+ else:
+ argv += ["--image", image]
+ if params.allow_unauthenticated:
+ argv.append("--allow-unauthenticated")
+ argv += self._project_flag(params)
+ cwd = self._cwd(ctx, params.path, required=bool(source))
+ result = await self._run(argv, cwd=cwd, timeout=_DEPLOY_TIMEOUT)
+ return self._shape("run_deploy", result)
+
+ @Operation("run_services_list", cost={"service": "gcloud", "action": "run_services_list", "count": 1})
+ async def run_services_list(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ argv = ["run", "services", "list", "--format=json"]
+ if params.region.strip():
+ argv += ["--region", params.region.strip()]
+ argv += self._project_flag(params)
+ result = await self._run(argv)
+ return self._shape("run_services_list", result)
+
+ @Operation("run_service_describe", cost={"service": "gcloud", "action": "run_service_describe", "count": 1})
+ async def run_service_describe(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ service = params.service.strip()
+ if not service:
+ raise NodeUserError("service is required (the Cloud Run service name)")
+ region = params.region.strip()
+ if not region:
+ raise NodeUserError("region is required for run_service_describe (e.g. 'us-central1')")
+ argv = ["run", "services", "describe", service, "--region", region, "--format=json", *self._project_flag(params)]
+ result = await self._run(argv)
+ return self._shape("run_service_describe", result)
+
+ # ---- cloud storage ------------------------------------------------------
+
+ @Operation("storage_ls", cost={"service": "gcloud", "action": "storage_ls", "count": 1})
+ async def storage_ls(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ argv = ["storage", "ls"]
+ if params.url.strip():
+ argv.append(params.url.strip())
+ argv += ["--format=json", *self._project_flag(params)]
+ result = await self._run(argv)
+ return self._shape("storage_ls", result)
+
+ @Operation("storage_cp", cost={"service": "gcloud", "action": "storage_cp", "count": 1})
+ async def storage_cp(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ src = params.src.strip()
+ dst = params.dst.strip()
+ if not src or not dst:
+ raise NodeUserError("src and dst are both required (local path or gs:// URL)")
+ argv = ["storage", "cp"]
+ if params.recursive:
+ argv.append("--recursive")
+ argv += [src, dst]
+ result = await self._run(argv, cwd=self._cwd(ctx, params.path), timeout=_TRANSFER_TIMEOUT)
+ return self._shape("storage_cp", result)
+
+ @Operation("storage_rm", cost={"service": "gcloud", "action": "storage_rm", "count": 1})
+ async def storage_rm(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ url = params.url.strip()
+ if not url.startswith("gs://"):
+ raise NodeUserError("url is required and must be a gs:// URL (e.g. 'gs://my-bucket/path')")
+ argv = ["storage", "rm"]
+ if params.recursive:
+ argv.append("--recursive")
+ argv.append(url)
+ result = await self._run(argv)
+ return self._shape("storage_rm", result)
+
+ # ---- passthrough ---------------------------------------------------------
+
+ @Operation("custom", cost={"service": "gcloud", "action": "custom", "count": 1})
+ async def custom(self, ctx: NodeContext, params: GCloudActionParams) -> Any:
+ cmd = params.command.strip()
+ if not cmd:
+ raise NodeUserError("command is required (e.g. 'iam service-accounts list', 'sql instances list')")
+ argv = shlex.split(cmd)
+ result = await self._run(argv, cwd=self._cwd(ctx, params.path), timeout=_TRANSFER_TIMEOUT)
+ return self._shape("custom", result)
diff --git a/server/nodes/gcloud/meta.json b/server/nodes/gcloud/meta.json
new file mode 100644
index 00000000..c95f000b
--- /dev/null
+++ b/server/nodes/gcloud/meta.json
@@ -0,0 +1 @@
+{"color": "#4285F4"}
diff --git a/server/nodes/visuals.json b/server/nodes/visuals.json
index a2c83e1f..a3e88f6b 100644
--- a/server/nodes/visuals.json
+++ b/server/nodes/visuals.json
@@ -140,6 +140,14 @@
"geminiChatModel": {
"icon": "lobehub:gemini"
},
+ "gcloud": {
+ "icon": "lobehub:googlecloud",
+ "color": "#4285F4"
+ },
+ "gcloudAction": {
+ "icon": "lobehub:googlecloud",
+ "skill": "gcloud-skill"
+ },
"github": {
"icon": "lobehub:Github",
"color": "#8250df"
diff --git a/server/skills/gcloud/gcloud-skill/SKILL.md b/server/skills/gcloud/gcloud-skill/SKILL.md
new file mode 100644
index 00000000..080ea013
--- /dev/null
+++ b/server/skills/gcloud/gcloud-skill/SKILL.md
@@ -0,0 +1,159 @@
+---
+name: gcloud-skill
+description: Work with Google Cloud via the official gcloud CLI — check auth/config, list and switch projects, manage Compute Engine instances, deploy and inspect Cloud Run services, work with Cloud Storage, and run any other gcloud command. Output is parsed JSON.
+allowed-tools: "gcloud"
+metadata:
+ author: opencompany
+ version: "1.0"
+ category: deployment
+
+---
+
+# Google Cloud Skill
+
+Wrapper over the official [Google Cloud CLI](https://cloud.google.com/sdk/gcloud/reference)
+(`gcloud`). Typed operations for the core flows plus a `custom`
+passthrough that covers the entire gcloud surface. JSON-capable
+operations run with `--format=json`, so results come back parsed in
+`result`.
+
+Each call starts a fresh gcloud process — a few seconds of startup
+latency per call is normal; don't retry a slow call.
+
+## Tool: gcloud
+
+### Operations
+
+| Operation | Purpose | Key fields |
+|---|---|---|
+| `auth_list` | Credentialed accounts + which is active | — |
+| `config_list` | Current configuration (account, project, region defaults) | — |
+| `projects_list` | Projects the account can access (parsed JSON) | `limit` (default 50) |
+| `set_project` | Set the configuration's default project | `project_id` (required) |
+| `compute_instances_list` | Compute Engine instances (parsed JSON) | `zone` (optional filter), `project` |
+| `compute_instance_start` | Start an instance | `instance`, `zone` (both required), `project` |
+| `compute_instance_stop` | Stop an instance | `instance`, `zone` (both required), `project` |
+| `compute_instance_describe` | Full instance details | `instance`, `zone` (both required), `project` |
+| `run_deploy` | Deploy a Cloud Run service | `service`, `region` (required), exactly one of `source` / `image`, `allow_unauthenticated`, `project` |
+| `run_services_list` | Cloud Run services (all regions unless filtered) | `region` (optional), `project` |
+| `run_service_describe` | Cloud Run service details (URL, revisions) | `service`, `region` (both required), `project` |
+| `storage_ls` | List buckets or objects | `url` (optional `gs://` URL; omit to list buckets), `project` |
+| `storage_cp` | Copy files local <-> `gs://` | `src`, `dst` (required), `recursive`, `path` (working dir) |
+| `storage_rm` | Delete objects | `url` (required `gs://` URL), `recursive` |
+| `custom` | Any other gcloud command | `command` — exactly what you would type after `gcloud ` |
+
+The `project` / `zone` / `region` fields map to `--project` /
+`--zone` / `--region`. When `project` is empty, gcloud falls back to
+the configured default — run `set_project` once instead of repeating
+`project` on every call.
+
+### Response
+
+```json
+{
+ "operation": "projects_list",
+ "success": true,
+ "result": [{ "projectId": "my-project-123", "name": "My Project", "lifecycleState": "ACTIVE" }]
+}
+```
+
+Parsed JSON lands in `result`; plain text (`set_project`, `storage_cp`
+progress) lands in `stdout`. On failure the tool raises an error
+carrying gcloud's own message — surface it verbatim; gcloud's errors
+are precise (including "You do not currently have an active account
+selected", which means the user needs to log in via Credentials ->
+Google Cloud).
+
+## Typical flows
+
+Orient first when state is unknown:
+
+```json
+{ "operation": "auth_list" }
+{ "operation": "config_list" }
+{ "operation": "projects_list" }
+{ "operation": "set_project", "project_id": "my-project-123" }
+```
+
+Compute Engine — zone is required for single-instance operations (get
+it from the list output's `zone` field):
+
+```json
+{ "operation": "compute_instances_list" }
+{ "operation": "compute_instance_stop", "instance": "my-vm", "zone": "us-central1-a" }
+```
+
+Cloud Run — deploy from a container image, or from source (source
+deploys run Cloud Build and can take minutes; the 15-minute timeout
+accommodates that):
+
+```json
+{ "operation": "run_deploy", "service": "my-api", "region": "us-central1", "image": "gcr.io/my-project/my-api:latest", "allow_unauthenticated": true }
+{ "operation": "run_deploy", "service": "my-api", "region": "us-central1", "source": ".", "path": "app" }
+{ "operation": "run_service_describe", "service": "my-api", "region": "us-central1" }
+```
+
+The deployed URL is in the describe/deploy result under
+`status.url`.
+
+Cloud Storage — local paths resolve against the workflow workspace:
+
+```json
+{ "operation": "storage_ls", "url": "gs://my-bucket/reports/" }
+{ "operation": "storage_cp", "src": "gs://my-bucket/reports/latest.csv", "dst": "./downloads/" }
+{ "operation": "storage_cp", "src": "./build", "dst": "gs://my-bucket/site/", "recursive": true }
+```
+
+## The full gcloud surface via custom
+
+```json
+{ "operation": "custom", "command": "iam service-accounts list" }
+{ "operation": "custom", "command": "sql instances list" }
+{ "operation": "custom", "command": "functions deploy my-fn --runtime python312 --trigger-http --region us-central1" }
+{ "operation": "custom", "command": "container clusters list" }
+{ "operation": "custom", "command": "logging read \"severity>=ERROR\" --limit 20 --format=json" }
+{ "operation": "custom", "command": "services enable run.googleapis.com" }
+```
+
+Notes for `custom`:
+
+- Add `--format=json` yourself when you want parsed output — it is not
+ injected for you.
+- `command` is parsed with `shlex.split` — wrap filter expressions and
+ JSON in quotes as you would in a shell.
+- Long-running commands get a 10-minute timeout; for very long
+ operations prefer the `--async` flag and poll.
+- `auth application-default login` mints Application Default
+ Credentials for client-library code (stored isolated under
+ OpenCompany's data directory). gcloud CLI commands themselves never
+ need ADC.
+
+## Authentication
+
+Auth is owned by the gcloud CLI itself, isolated under OpenCompany's
+data directory (a login you did in your own terminal is NOT visible
+here):
+
+- **Credentials Modal -> Google Cloud -> Login** — gcloud opens the
+ browser itself for Google sign-in (localhost callback, so the
+ browser must be on the server's machine). First use auto-installs
+ the CLI (~100 MB; allow a few minutes).
+
+If a command fails with an auth error, point the user at the Login
+button; don't ask them to paste credentials in chat. If it fails with
+"API not enabled", enable it via
+`{ "operation": "custom", "command": "services enable <api>.googleapis.com" }`.
+
+## Best practices
+
+1. **Run `config_list` first** when state is unknown — it shows the
+ active account and default project without side effects.
+2. **Set the project once** (`set_project`) instead of repeating the
+ `project` field.
+3. **Destructive operations** (instance stop, `storage_rm`, deletes
+ via `custom`) — confirm with the user before running unless they
+ explicitly asked.
+4. **Surface gcloud error messages verbatim** — don't paraphrase; they
+ name the exact flag, permission, or API to fix.
+5. **Costs are real** — starting instances and deploying services
+ incurs billing; mention it when the user's intent is exploratory.
diff --git a/server/tests/test_gcloud_plugin.py b/server/tests/test_gcloud_plugin.py
new file mode 100644
index 00000000..1c76ff33
--- /dev/null
+++ b/server/tests/test_gcloud_plugin.py
@@ -0,0 +1,570 @@
+"""Google Cloud plugin contract tests.
+
+Locks the plugin's load-bearing seams under the CLI-owns-auth (Stripe /
+gh / cloudflare) pattern: env builders (pinned ``CLOUDSDK_CONFIG``
+isolation; login env strips ambient credential vars so the session
+probe reflects the stored login), install resolution (pinned versioned
+archive into ``package_dir("gcloud")``; system gcloud never consulted;
+the Windows bundled-python asset's legacy ``google-cloud-sdk-`` filename
+prefix), the marker-token + CloudEvents broadcast contract
+(``inspect.getsource`` introspection, ``test_credential_broadcasts``
+style), op argv building, and the catalogue entry shape (fieldless —
+gcloud owns the credentials).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import json
+from pathlib import Path
+
+import pytest
+
+import nodes.gcloud._handlers as gcloud_handlers
+import nodes.gcloud._install as gcloud_install
+import nodes.gcloud._service as gcloud_service
+import nodes.gcloud.gcloud_action as gcloud_action_mod
+from nodes.gcloud import WS_HANDLERS
+from nodes.gcloud._credentials import GCloudCredential
+from nodes.gcloud.gcloud_action import GCloudActionNode, GCloudActionParams
+from services.plugin import NodeContext
+from services.plugin.base import NodeUserError
+
+PLUGIN_DIR = Path(gcloud_service.__file__).parent
+CONFIG_PATH = Path(gcloud_service.__file__).parents[2] / "config" / "credential_providers.json"
+
+
+# --- _service env builders ----------------------------------------------------
+
+
+def _pin_config_dir(monkeypatch, tmp_path):
+ monkeypatch.setattr(gcloud_service, "_config_dir", lambda: str(tmp_path / "gcloud-config"))
+
+
+def test_gcloud_env_pins_isolated_config_and_hygiene_vars(monkeypatch, tmp_path):
+ _pin_config_dir(monkeypatch, tmp_path)
+ env = gcloud_service.gcloud_env()
+ assert env["CLOUDSDK_CONFIG"] == str(tmp_path / "gcloud-config")
+ assert env["CLOUDSDK_CORE_DISABLE_PROMPTS"] == "1"
+ assert env["CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK"] == "1"
+ assert env["CLOUDSDK_CORE_DISABLE_USAGE_REPORTING"] == "1"
+ assert env["NO_COLOR"] == "1"
+
+
+def test_login_env_strips_ambient_credential_vars(monkeypatch, tmp_path):
+ """With CLOUDSDK_AUTH_ACCESS_TOKEN (or an account/project override)
+ set, the session probe would report the ambient identity instead of
+ the stored login — auth paths must consult gcloud's OWN store under
+ the pinned config dir."""
+ _pin_config_dir(monkeypatch, tmp_path)
+ for var in gcloud_service._AMBIENT_CREDENTIAL_VARS:
+ monkeypatch.setenv(var, "ambient")
+ env = gcloud_service.login_env()
+ for var in gcloud_service._AMBIENT_CREDENTIAL_VARS:
+ assert var not in env
+ assert env["CLOUDSDK_CONFIG"] == str(tmp_path / "gcloud-config")
+
+
+def test_ops_env_keeps_ambient_vars(monkeypatch, tmp_path):
+ # Ops leave ambient credential vars alone (headless path — gcloud
+ # documents env-first resolution), unlike the auth paths.
+ _pin_config_dir(monkeypatch, tmp_path)
+ monkeypatch.setenv("CLOUDSDK_AUTH_ACCESS_TOKEN", "ambient")
+ env = gcloud_service.gcloud_env()
+ assert env["CLOUDSDK_AUTH_ACCESS_TOKEN"] == "ambient"
+
+
+# --- _install resolution --------------------------------------------------------
+
+
+def test_version_is_pinned():
+ assert gcloud_install._VERSION.count(".") == 2
+ assert "latest" not in gcloud_install._VERSION
+
+
+def test_asset_map_covers_all_platforms():
+ assert set(gcloud_install._ASSETS) == {
+ ("Windows", "AMD64"),
+ ("Windows", "ARM64"),
+ ("Linux", "x86_64"),
+ ("Linux", "aarch64"),
+ ("Linux", "arm64"),
+ ("Darwin", "x86_64"),
+ ("Darwin", "arm64"),
+ }
+
+
+def test_windows_asset_keeps_legacy_sdk_prefix():
+ """dl.google.com naming quirk: the Windows bundled-python zip uses
+ the legacy ``google-cloud-sdk-`` prefix — the ``google-cloud-cli-``
+ spelling 404s. A version bump must not "normalize" it."""
+ for key in (("Windows", "AMD64"), ("Windows", "ARM64")):
+ asset, binary = gcloud_install._ASSETS[key]
+ assert asset.startswith("google-cloud-sdk-")
+ assert asset.endswith("-windows-x86_64-bundled-python.zip")
+ assert binary == "gcloud.cmd"
+ # Every non-Windows asset uses the modern google-cloud-cli- prefix.
+ for key, (asset, binary) in gcloud_install._ASSETS.items():
+ if key[0] != "Windows":
+ assert asset.startswith("google-cloud-cli-")
+ assert binary == "gcloud"
+
+
+def test_extracted_binary_path_uses_constant_inner_root(monkeypatch, tmp_path):
+ monkeypatch.setattr(gcloud_install, "_package_root", lambda: tmp_path)
+ target = gcloud_install._extracted_binary_path()
+ assert target.parts[-3:-1] == ("google-cloud-sdk", "bin")
+ assert target.name in ("gcloud", "gcloud.cmd")
+ assert str(target).startswith(str(tmp_path))
+
+
+def test_gcloud_binary_never_resolved_from_system_path():
+ # Project-local contract: the system gcloud is never consulted.
+ assert "which(" not in inspect.getsource(gcloud_install)
+ assert "which(" not in inspect.getsource(gcloud_service)
+
+
+async def test_ensure_gcloud_cli_installs_into_package_dir(monkeypatch, tmp_path):
+ monkeypatch.setattr(gcloud_install, "_cached_path", None)
+ monkeypatch.setattr(gcloud_install, "_package_root", lambda: tmp_path)
+ target = gcloud_install._extracted_binary_path()
+
+ calls = {"installs": 0}
+
+ def fake_fetch():
+ calls["installs"] += 1
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text("", encoding="utf-8")
+ return target
+
+ monkeypatch.setattr(gcloud_install, "_fetch_cli_sync", fake_fetch)
+
+ resolved = await gcloud_install.ensure_gcloud_cli()
+ assert resolved == target
+ assert calls["installs"] == 1
+ # cached for subsequent calls without re-installing
+ assert await gcloud_install.ensure_gcloud_cli() == target
+ assert calls["installs"] == 1
+
+
+# --- operations (no auth pre-flight — Stripe pattern) ---------------------------
+
+
+def _wire(monkeypatch, tmp_path, run_impl):
+ async def fake_ensure():
+ return tmp_path / "gcloud"
+
+ monkeypatch.setattr(gcloud_install, "ensure_gcloud_cli", fake_ensure)
+ monkeypatch.setattr(gcloud_action_mod, "run_cli_command", run_impl)
+ _pin_config_dir(monkeypatch, tmp_path)
+
+
+def _ctx(tmp_path) -> NodeContext:
+ return NodeContext(node_id="gc1", node_type="gcloudAction", workspace_dir=str(tmp_path))
+
+
+def _capturing_run(captured, payload=None):
+ async def fake_run(**kwargs):
+ captured.update(kwargs)
+ return {"success": True, "result": payload, "stdout": "" if payload is not None else "done", "stderr": "", "error": None}
+
+ return fake_run
+
+
+async def test_auth_list_argv_and_pinned_env(monkeypatch, tmp_path):
+ captured = {}
+ _wire(monkeypatch, tmp_path, _capturing_run(captured, payload=[{"account": "[email protected]", "status": "ACTIVE"}]))
+ node = GCloudActionNode()
+ out = await node.auth_list(_ctx(tmp_path), GCloudActionParams(operation="auth_list"))
+ assert captured["argv"] == ["auth", "list", "--format=json"]
+ assert captured["env"]["CLOUDSDK_CONFIG"] == str(tmp_path / "gcloud-config")
+ assert out["result"] == [{"account": "[email protected]", "status": "ACTIVE"}]
+
+
+async def test_projects_list_carries_limit(monkeypatch, tmp_path):
+ captured = {}
+ _wire(monkeypatch, tmp_path, _capturing_run(captured, payload=[]))
+ node = GCloudActionNode()
+ await node.projects_list(_ctx(tmp_path), GCloudActionParams(operation="projects_list", limit=7))
+ assert captured["argv"] == ["projects", "list", "--format=json", "--limit", "7"]
+
+
+async def test_set_project_requires_id_and_is_textual(monkeypatch, tmp_path):
+ captured = {}
+ _wire(monkeypatch, tmp_path, _capturing_run(captured))
+ node = GCloudActionNode()
+
+ with pytest.raises(NodeUserError, match="project_id"):
+ await node.set_project(_ctx(tmp_path), GCloudActionParams(operation="set_project"))
+
+ out = await node.set_project(_ctx(tmp_path), GCloudActionParams(operation="set_project", project_id="proj-1"))
+ assert captured["argv"] == ["config", "set", "project", "proj-1"]
+ assert "--format=json" not in captured["argv"]
+ assert out["stdout"] == "done"
+
+
+async def test_compute_instances_list_optional_zone_and_project(monkeypatch, tmp_path):
+ captured = {}
+ _wire(monkeypatch, tmp_path, _capturing_run(captured, payload=[]))
+ node = GCloudActionNode()
+
+ await node.compute_instances_list(_ctx(tmp_path), GCloudActionParams(operation="compute_instances_list"))
+ assert captured["argv"] == ["compute", "instances", "list", "--format=json"]
+
+ await node.compute_instances_list(
+ _ctx(tmp_path),
+ GCloudActionParams(operation="compute_instances_list", zone="us-central1-a", project="proj-1"),
+ )
+ assert captured["argv"] == [
+ "compute", "instances", "list", "--format=json",
+ "--zones", "us-central1-a", "--project", "proj-1",
+ ]
+
+
+async def test_compute_instance_ops_require_instance_and_zone(monkeypatch, tmp_path):
+ captured = {}
+ _wire(monkeypatch, tmp_path, _capturing_run(captured, payload={}))
+ node = GCloudActionNode()
+
+ with pytest.raises(NodeUserError, match="instance"):
+ await node.compute_instance_start(_ctx(tmp_path), GCloudActionParams(operation="compute_instance_start"))
+ with pytest.raises(NodeUserError, match="zone"):
+ await node.compute_instance_stop(
+ _ctx(tmp_path), GCloudActionParams(operation="compute_instance_stop", instance="vm1")
+ )
+
+ await node.compute_instance_start(
+ _ctx(tmp_path),
+ GCloudActionParams(operation="compute_instance_start", instance="vm1", zone="us-central1-a"),
+ )
+ assert captured["argv"] == ["compute", "instances", "start", "vm1", "--zone", "us-central1-a", "--format=json"]
+ assert captured["timeout"] == gcloud_action_mod._MUTATION_TIMEOUT
+
+ await node.compute_instance_describe(
+ _ctx(tmp_path),
+ GCloudActionParams(operation="compute_instance_describe", instance="vm1", zone="us-central1-a", project="p"),
+ )
+ assert captured["argv"] == [
+ "compute", "instances", "describe", "vm1", "--zone", "us-central1-a", "--format=json", "--project", "p",
+ ]
+
+
+async def test_run_deploy_validates_and_builds_argv(monkeypatch, tmp_path):
+ captured = {}
+ _wire(monkeypatch, tmp_path, _capturing_run(captured, payload={}))
+ node = GCloudActionNode()
+
+ with pytest.raises(NodeUserError, match="service"):
+ await node.run_deploy(_ctx(tmp_path), GCloudActionParams(operation="run_deploy"))
+ with pytest.raises(NodeUserError, match="region"):
+ await node.run_deploy(_ctx(tmp_path), GCloudActionParams(operation="run_deploy", service="svc"))
+ # exactly one of source/image — neither and both must fail
+ with pytest.raises(NodeUserError, match="exactly one"):
+ await node.run_deploy(
+ _ctx(tmp_path), GCloudActionParams(operation="run_deploy", service="svc", region="us-central1")
+ )
+ with pytest.raises(NodeUserError, match="exactly one"):
+ await node.run_deploy(
+ _ctx(tmp_path),
+ GCloudActionParams(operation="run_deploy", service="svc", region="us-central1", source=".", image="img"),
+ )
+
+ await node.run_deploy(
+ _ctx(tmp_path),
+ GCloudActionParams(
+ operation="run_deploy", service="svc", region="us-central1",
+ image="gcr.io/p/i", allow_unauthenticated=True, project="p",
+ ),
+ )
+ assert captured["argv"] == [
+ "run", "deploy", "svc", "--region", "us-central1", "--quiet", "--format=json",
+ "--image", "gcr.io/p/i", "--allow-unauthenticated", "--project", "p",
+ ]
+ assert captured["timeout"] == gcloud_action_mod._DEPLOY_TIMEOUT
+
+ # --source deploys run from the workspace (cwd resolved).
+ await node.run_deploy(
+ _ctx(tmp_path),
+ GCloudActionParams(operation="run_deploy", service="svc", region="us-central1", source="."),
+ )
+ assert captured["cwd"] == str(tmp_path)
+ argv = captured["argv"]
+ assert argv[argv.index("--source") + 1] == "."
+
+
+async def test_run_services_list_and_describe(monkeypatch, tmp_path):
+ captured = {}
+ _wire(monkeypatch, tmp_path, _capturing_run(captured, payload=[]))
+ node = GCloudActionNode()
+
+ await node.run_services_list(_ctx(tmp_path), GCloudActionParams(operation="run_services_list"))
+ assert captured["argv"] == ["run", "services", "list", "--format=json"]
+
+ with pytest.raises(NodeUserError, match="region"):
+ await node.run_service_describe(
+ _ctx(tmp_path), GCloudActionParams(operation="run_service_describe", service="svc")
+ )
+
+ await node.run_service_describe(
+ _ctx(tmp_path),
+ GCloudActionParams(operation="run_service_describe", service="svc", region="us-central1"),
+ )
+ assert captured["argv"] == ["run", "services", "describe", "svc", "--region", "us-central1", "--format=json"]
+
+
+async def test_storage_ops(monkeypatch, tmp_path):
+ captured = {}
+ _wire(monkeypatch, tmp_path, _capturing_run(captured, payload=[]))
+ node = GCloudActionNode()
+
+ await node.storage_ls(_ctx(tmp_path), GCloudActionParams(operation="storage_ls"))
+ assert captured["argv"] == ["storage", "ls", "--format=json"]
+ await node.storage_ls(_ctx(tmp_path), GCloudActionParams(operation="storage_ls", url="gs://b/x"))
+ assert captured["argv"] == ["storage", "ls", "gs://b/x", "--format=json"]
+
+ with pytest.raises(NodeUserError, match="src and dst"):
+ await node.storage_cp(_ctx(tmp_path), GCloudActionParams(operation="storage_cp", src="a.txt"))
+ await node.storage_cp(
+ _ctx(tmp_path),
+ GCloudActionParams(operation="storage_cp", src="./dir", dst="gs://b/dir/", recursive=True),
+ )
+ assert captured["argv"] == ["storage", "cp", "--recursive", "./dir", "gs://b/dir/"]
+ assert "--format=json" not in captured["argv"]
+ assert captured["timeout"] == gcloud_action_mod._TRANSFER_TIMEOUT
+
+ with pytest.raises(NodeUserError, match="gs://"):
+ await node.storage_rm(_ctx(tmp_path), GCloudActionParams(operation="storage_rm", url="my-bucket"))
+ await node.storage_rm(_ctx(tmp_path), GCloudActionParams(operation="storage_rm", url="gs://b/x", recursive=True))
+ assert captured["argv"] == ["storage", "rm", "--recursive", "gs://b/x"]
+
+
+async def test_custom_requires_command_and_shlex_splits(monkeypatch, tmp_path):
+ captured = {}
+ _wire(monkeypatch, tmp_path, _capturing_run(captured, payload={"ok": True}))
+ node = GCloudActionNode()
+
+ with pytest.raises(NodeUserError):
+ await node.custom(_ctx(tmp_path), GCloudActionParams(operation="custom", command=" "))
+
+ await node.custom(
+ _ctx(tmp_path),
+ GCloudActionParams(operation="custom", command="iam service-accounts list --format=json --filter 'displayName:CI Bot'"),
+ )
+ assert captured["argv"] == ["iam", "service-accounts", "list", "--format=json", "--filter", "displayName:CI Bot"]
+ assert captured["timeout"] == gcloud_action_mod._TRANSFER_TIMEOUT
+
+
+async def test_gcloud_auth_error_surfaces_as_node_user_error(monkeypatch, tmp_path):
+ """No pre-flight: gcloud's own 'no active account' error IS the
+ auth error, plus the Login-button hint."""
+
+ async def fake_run(**kwargs):
+ return {
+ "success": False,
+ "stdout": "",
+ "stderr": "ERROR: (gcloud.projects.list) You do not currently have an active account selected.",
+ "error": "exit 1",
+ }
+
+ _wire(monkeypatch, tmp_path, fake_run)
+ node = GCloudActionNode()
+ with pytest.raises(NodeUserError, match="active account"):
+ await node.projects_list(_ctx(tmp_path), GCloudActionParams(operation="projects_list"))
+
+
+def test_shape_prefers_parsed_result_over_stdout():
+ shaped = GCloudActionNode._shape("op", {"result": [{"a": 1}], "stdout": '[{"a": 1}]', "stderr": ""})
+ assert shaped["result"] == [{"a": 1}]
+ assert "stdout" not in shaped
+
+ shaped = GCloudActionNode._shape("op", {"result": None, "stdout": "Updated property [core/project].", "stderr": "warn"})
+ assert shaped["stdout"] == "Updated property [core/project]."
+ assert "result" not in shaped
+ assert shaped["stderr_tail"] == "warn"
+
+
+def test_node_has_no_auth_preflight():
+ # Stripe-strict: the CLI owns auth; the node must not pre-check it.
+ assert not hasattr(GCloudActionNode, "_preflight")
+ src = inspect.getsource(gcloud_action_mod)
+ assert "PermissionError" not in src
+
+
+# --- login handler --------------------------------------------------------------
+
+
+def _reset_login_state(monkeypatch):
+ monkeypatch.setattr(gcloud_handlers, "_active_login", {"task": None, "proc": None})
+
+
+async def test_login_answers_within_budget_when_flow_stalls(monkeypatch):
+ _reset_login_state(monkeypatch)
+
+ async def stalled_flow():
+ await asyncio.sleep(30)
+ return {"success": True, "message": "done"}
+
+ monkeypatch.setattr(gcloud_handlers, "_start_login_flow", stalled_flow)
+ monkeypatch.setattr(gcloud_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)
+ res = await gcloud_handlers.handle_gcloud_login({}, websocket=None)
+ assert res["success"] is True
+ assert res.get("pending") is True
+
+
+def test_response_budget_fits_frontend_window():
+ assert gcloud_handlers._RESPONSE_BUDGET_SECONDS <= 25
+
+
+async def test_login_response_never_proxies_a_url(monkeypatch):
+ # The CLI owns the whole interaction — it opens the browser itself.
+ _reset_login_state(monkeypatch)
+
+ async def instant_flow():
+ return {"success": True, "message": "gcloud is opening your default browser."}
+
+ monkeypatch.setattr(gcloud_handlers, "_start_login_flow", instant_flow)
+ res = await gcloud_handlers.handle_gcloud_login({}, websocket=None)
+ assert res["success"] is True
+ assert "url" not in res
+ assert "verification_code" not in res
+ src = inspect.getsource(gcloud_handlers._start_login_flow)
+ assert '"url"' not in src
+
+
+async def test_login_is_single_flight(monkeypatch):
+ # A repeat Login click while a flow is live must not spawn a second
+ # browser tab + competing loopback callback server.
+ _reset_login_state(monkeypatch)
+
+ started = asyncio.Event()
+ release = asyncio.Event()
+
+ async def slow_flow():
+ started.set()
+ await release.wait()
+ return {"success": True, "message": "done"}
+
+ monkeypatch.setattr(gcloud_handlers, "_start_login_flow", slow_flow)
+ monkeypatch.setattr(gcloud_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)
+
+ first = await gcloud_handlers.handle_gcloud_login({}, websocket=None)
+ assert first.get("pending") is True
+ await started.wait()
+
+ def boom():
+ raise AssertionError("second click must not spawn a second flow")
+
+ monkeypatch.setattr(gcloud_handlers, "_start_login_flow", boom)
+ second = await gcloud_handlers.handle_gcloud_login({}, websocket=None)
+ assert second["success"] is True
+ assert second.get("pending") is True
+ assert "already in progress" in second["message"].lower()
+
+ release.set()
+
+
+def test_login_flow_short_circuits_when_already_logged_in():
+ src = inspect.getsource(gcloud_handlers._start_login_flow)
+ assert "active_account" in src
+ assert "Already logged in" in src
+
+
+def test_completion_never_kills_the_login_process():
+ # gcloud.cmd is a cmd.exe shim around the bundled Python on Windows:
+ # killing the wrapper orphans the python child holding the loopback
+ # callback socket.
+ src = inspect.getsource(gcloud_handlers._complete_login)
+ assert ".kill(" not in src
+ assert ".terminate(" not in src
+
+
+# --- marker-token + broadcast contract (source introspection) -------------------
+
+
+def test_login_success_gates_on_probe_then_marks_and_broadcasts():
+ # Marker + broadcast plumbing is the SHARED module (claude/codex/github/cloudflare/gcloud).
+ assert gcloud_handlers.mark_logged_in.__module__ == "services.cli_agent._cli_auth"
+ complete = inspect.getsource(gcloud_handlers._complete_login)
+ # exit code alone is never trusted — gcloud exits 0 logged-in AND
+ # logged-out; the `auth list` probe is the gate (and the
+ # account-label email source).
+ assert "active_account" in complete
+ assert "_mark_connected" in complete
+ marked = inspect.getsource(gcloud_handlers._mark_connected)
+ assert 'mark_logged_in("gcloud"' in marked
+ assert "credential.oauth.connected" in marked
+ probe = inspect.getsource(gcloud_service.active_account)
+ assert '"auth", "list"' in probe
+ assert "status:ACTIVE" in probe
+
+
+def test_logout_removes_marker_and_broadcasts():
+ assert gcloud_handlers.mark_logged_out.__module__ == "services.cli_agent._cli_auth"
+ src = inspect.getsource(gcloud_handlers.handle_gcloud_logout)
+ assert 'mark_logged_out("gcloud")' in src
+ assert "credential.oauth.disconnected" in src
+ # revoke is best-effort — offline failure must not block marker removal
+ assert '"revoke"' in src or '"auth", "revoke"' in src
+
+
+def test_login_uses_stripped_env():
+ for fn in (gcloud_handlers._start_login_flow, gcloud_handlers.handle_gcloud_logout):
+ assert "login_env" in inspect.getsource(fn)
+ assert "login_env" in inspect.getsource(gcloud_service.active_account)
+
+
+def test_ws_handlers_registered():
+ assert set(WS_HANDLERS) == {"gcloud_login", "gcloud_logout", "gcloud_status"}
+
+
+# --- catalogue + assets ----------------------------------------------------------
+
+
+def test_catalogue_entry_is_github_fieldless_shape():
+ config = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
+ assert "deployment" in config["categories"]
+ gcloud = config["providers"]["gcloud"]
+ assert gcloud["kind"] == "oauth"
+ assert gcloud["category"] == "deployment"
+ assert gcloud["icon_ref"] == "lobehub:googlecloud"
+ assert gcloud["ws"] == {
+ "login": "gcloud_login",
+ "logout": "gcloud_logout",
+ "status": "gcloud_status",
+ }
+ # Fieldless (github shape): pure CLI login — no token field, so the
+ # Login button is always enabled (OAuthConnect gates on required
+ # fields only) and OpenCompany never stores a credential.
+ assert "fields" not in gcloud
+
+
+def test_credential_class_shape():
+ assert GCloudCredential.id == "gcloud"
+ assert GCloudCredential.auth == "custom"
+
+
+async def test_credential_resolve_is_empty_marker():
+ # gh pattern: nothing to resolve — auth lives in gcloud's own store.
+ assert await GCloudCredential.resolve() == {}
+
+
+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"] == "#4285F4"
+
+ visuals = json.loads((PLUGIN_DIR.parent / "visuals.json").read_text(encoding="utf-8"))
+ entry = visuals["gcloudAction"]
+ assert entry["icon"] == "lobehub:googlecloud"
+ assert entry["skill"] == "gcloud-skill"
+ # tool_name ("gcloud") != snake_case(node type) — the lowercase
+ # alias carries icon + color for the Master Skill row.
+ alias = visuals["gcloud"]
+ assert alias["icon"] == "lobehub:googlecloud"
+ assert alias["color"].startswith("#")
+
+ skill_md = PLUGIN_DIR.parents[1] / "skills" / "gcloud" / "gcloud-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 da988fbb..31114f93 100644
--- a/server/tests/test_plugin_self_containment.py
+++ b/server/tests/test_plugin_self_containment.py
@@ -62,6 +62,7 @@ _MIGRATED_PLUGINS = (
"cloudflare",
"code",
"email",
+ "gcloud",
"github",
"google",
"stripe",
@@ -76,6 +77,7 @@ _MIGRATED_PLUGINS = (
_PLUGINS_WITH_HANDLERS = (
"android",
"cloudflare",
+ "gcloud",
"github",
"google",
"stripe",