diff --git a/README.md b/README.md index bcc0d6c..d9b21d1 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,13 @@ # hermes-gemini-api-plugin -Native Google AI Studio Gemini (**Nano Banana**) image generation and editing backend plugin for [Hermes Agent](https://github.com/NousResearch/hermes-agent). +Google AI Studio Gemini plugin (`gemini-api`) for [Hermes Agent](https://github.com/NousResearch/hermes-agent), powered end-to-end by the official [gemini-api CLI](https://github.com/google-gemini/gemini-api-cli) (Interactions API) under a single `GEMINI_API_KEY`: -Calls the Gemini REST endpoint (`POST /v1beta/models/{model}:generateContent` with `responseModalities: ["TEXT", "IMAGE"]`), decodes returned `inlineData` images into `$HERMES_HOME/cache/generated/images/`, and records token usage (including Nano Banana 2.1 and Nano Banana Pro thinking tokens) into Hermes session accounting. +1. **Image Generation (`GeminiImageGenProvider`, `image_gen.provider: gemini`)** — **Nano Banana 2.1**, **Nano Banana 2**, **Nano Banana 2 Lite**, and **Nano Banana Pro** generation and multi-reference editing via `gemini-api image` (`-i`, `--aspect-ratio`, `--image-size`, optional Google Search grounding), saving images to `$HERMES_HOME/cache/generated/images/`. +2. **Video Generation & CLI Tools (`GeminiVideoGenProvider` + 6 Tools + Skill)** — Native `video_generate` (`video_gen.provider: gemini`), Lyria music generation, Gemini 3.8 Flash single/two-speaker TTS, multimodal file & YouTube analysis, speaker-diarized transcription (`.md` / `.srt`), Gemini Deep Research interactions, and resumable Files API uploads (up to 2 GB). -## Supported Models +## Capabilities Overview + +### 1. Image Generation (`image_gen.provider: gemini`) | Model ID | Display Name | Speed | Capabilities | | :--- | :--- | :--- | :--- | @@ -13,12 +16,27 @@ Calls the Gemini REST endpoint (`POST /v1beta/models/{model}:generateContent` wi | `gemini-3.1-flash-lite-image` | **Nano Banana 2 Lite** (Gemini 3.1 Flash Lite Image) | Fastest | Lowest latency & cost; 10 aspect ratios, `1K` output resolution, up to 14 reference images | | `gemini-3-pro-image` | **Nano Banana Pro** (Gemini 3 Pro Image) | Slower | Highest fidelity & reasoning; 10 aspect ratios, `1K` / `2K` / `4K` output resolution, Google Search grounding, up to 14 reference images | +### 2. Video Generation & `gemini-api` CLI Tools + +| Surface | CLI Default Model / Agent (`v0.5.0`) | Description | +| :--- | :--- | :--- | +| `video_generate` (`video_gen.provider: gemini`) | `gemini-omni-1.2-flash` | Text-to-video and image-to-video generation (`--aspect-ratio`, `--resolution`, `-i`) saved to `$HERMES_HOME/cache/videos/` | +| `gemini_music` | `lyria-3.5` | Instrumental and vocal music generation saved to `$HERMES_HOME/cache/generated/audio/` | +| `gemini_tts` | `gemini-3.8-flash-tts` | 24 kHz WAV speech synthesis with single-speaker voices (`Kore`, `Puck`, etc.) and 2-speaker scripts | +| `gemini_analyze` | `gemini-4-hydrogen` | Multimodal Q&A over PDFs, videos, audio, images, CSVs, `files/` handles, and YouTube URLs (seamlessly auto-uploads binary media >14 MB via Files API) | +| `gemini_transcribe` | `gemini-3.5-transcribe` | Speaker-diarized and timestamped transcripts in `md`, `text`, `json`, or `srt` captions (seamlessly auto-uploads media >14 MB) | +| `gemini_deep_research` | `deep-research-preview-04-2026` | Start (`run`, async `background: true` by default), poll (`status`), or stop (`cancel`) Gemini Deep Research & Interactions API agent runs | +| `gemini_files_upload` | Gemini Files API | Resumable upload up to 2 GB (`--wait` until `ACTIVE`), returning a reusable 48-hour `files/` handle | +| Skill `gemini-api-cli` | `SKILL.md` | Read-only reference (`skill_view`) for ad-hoc `gemini-api` commands (`models`, `--dry-run`, `video --resume`, `--help`) | + ## Installation +### 1. Install the Hermes Plugin + Install from the Hermes Plugin Catalog: ```bash -hermes plugins install gemini-image +hermes plugins install gemini-api ``` Or install directly from GitHub: @@ -27,6 +45,20 @@ Or install directly from GitHub: hermes plugins install https://github.com/google-gemini/hermes-gemini-api-plugin ``` +> **Migrating from `gemini-image`:** If you previously installed the v0.1.0 `gemini-image` plugin, uninstall it first (`hermes plugins uninstall gemini-image`) before installing `gemini-api` so both do not register the `gemini` image provider concurrently. Your `image_gen.gemini.*` settings and `GEMINI_API_KEY` remain compatible. + +### 2. Install `gemini-api` CLI *(required)* + +Install [`google-gemini/gemini-api-cli`](https://github.com/google-gemini/gemini-api-cli) (`v0.5.0`+) onto your `PATH` or `~/.hermes/bin/gemini-api` (or opt into `auto_install_cli: true` in `config.yaml` below): + +```bash +# Option A: Install with Go 1.22+ +go install github.com/google-gemini/gemini-api-cli/cmd/gemini-api@v0.5.0 + +# Option B: Download a prebuilt archive from GitHub Releases and verify checksums.txt +# https://github.com/google-gemini/gemini-api-cli/releases/tag/v0.5.0 +``` + ## Configuration ### 1. API Key (`.env`) @@ -37,9 +69,7 @@ Set your Google AI Studio API key ([get one here](https://aistudio.google.com/ap GEMINI_API_KEY="your-api-key" ``` -### 2. Provider & Generation Settings (`~/.hermes/config.yaml`) - -Select `gemini` as your image generation provider (or run `hermes tools` → **Image Generation** → **Google AI Studio (direct)**): +### 2. Provider & Plugin Settings (`~/.hermes/config.yaml`) ```yaml image_gen: @@ -49,34 +79,40 @@ image_gen: image_size: 2K # 1K | 2K | 4K (or 512 on gemini-3.1-flash-image) aspect_ratio: "16:9" # exact ratio override (e.g. 1:1, 16:9, 9:16, 21:9, 1:4, 4:1, 1:8, 8:1) google_search: false # enable Google Search grounding on supported models - # Optional custom endpoint / credential routing: - # base_url: https://generativelanguage.googleapis.com/v1beta - # key_env: GEMINI_API_KEY - # provider: my-custom-gemini-endpoint + +video_gen: + provider: gemini + gemini: + model: "" # optional explicit override (empty uses gemini-api CLI's built-in default) + +plugins: + entries: + gemini-api: + settings: + cli_path: "" # optional explicit path to gemini-api binary + # timeout_seconds: 180 # optional override (when omitted: 180s TTS, 300s music/analyze/transcribe/upload, 900s video/sync research) + auto_install_cli: false # opt-in download of pinned v0.5.0 verified against hardcoded SHA-256 digests into $HERMES_HOME/bin ``` -Optional environment variable overrides for model and endpoint: +Optional environment variable overrides for image model and endpoint: - `GEMINI_IMAGE_MODEL` — Override the Gemini image model ID (strips any optional `google/` prefix). -- `GEMINI_BASE_URL` — Override the Gemini API base URL. - -## Features - -- **Multi-reference image editing**: Pass `image_url` and/or `reference_image_urls` (up to 14 reference images across HTTP(S) URLs, `data:` URIs, or local file paths) to edit, restyle, or combine images. -- **Safety & size guards**: Uses Hermes's SSRF-safe HTTP client for remote URLs, blocks local credential store reads via `raise_if_read_blocked`, sniffs magic bytes (`PNG`, `JPEG`, `WebP`, `GIF`) before upload, and enforces a 25 MB per-image cap plus an 80 MB total inline payload ceiling. -- **Session token accounting**: Reports `promptTokenCount`, `candidatesTokenCount`, `thoughtsTokenCount`, and `cachedContentTokenCount` to Hermes's `record_token_usage`. +- `GEMINI_BASE_URL` — Override the Gemini API base URL (`https://` required; `http://` allowed for localhost testing only). ## Security & Privacy Disclosure -- **External network calls**: Sends text prompts and optional inline reference images over HTTPS to `https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent` (or a custom `image_gen.gemini.base_url`) authenticated via `GEMINI_API_KEY`. Remote `http(s)://` reference image URLs passed to `image_generate` are fetched through Hermes's SSRF-safe HTTP client. -- **Filesystem access**: Reads local reference image paths explicitly passed by the caller (guarded by `agent.file_safety.raise_if_read_blocked`) and writes generated output images to `$HERMES_HOME/cache/generated/images/`. -- **No background processes or telemetry**: Spawns no shell commands or background workers and collects no telemetry. +- **External network calls**: All Gemini API requests (image, video, music, TTS, analyze, transcribe, Deep Research, and Files upload) are sent by `gemini-api` over HTTPS to `generativelanguage.googleapis.com` (or a validated `https://` `image_gen.gemini.base_url` / `GEMINI_BASE_URL` — cleartext non-loopback `http://` URLs are refused) authenticated via `GEMINI_API_KEY`. Remote `http(s)://` reference image URLs are fetched through Hermes's SSRF-safe HTTP client. If `auto_install_cli: true` is explicitly opted into by the user, downloads the pinned `gemini-api` `v0.5.0` release archive (capped at 64 MiB) from `github.com/google-gemini/gemini-api-cli/releases` and verifies it against hardcoded SHA-256 digests before atomic extraction. +- **Subprocess execution**: Invokes the local `gemini-api` binary (`--no-interactive -o json`, `stdin=DEVNULL`, `--` end-of-flags guard on positional prompts/paths) inside an allowlisted, secret-scrubbed environment carrying only the active `GEMINI_API_KEY` (never inheriting unrelated API keys or conflicting `GEMINI_*` / `GOOGLE_API_KEY` variables). +- **Filesystem access**: Validates all caller-supplied local file paths against `agent.file_safety.raise_if_read_blocked` and regular-file checks before reading or passing them to `gemini-api`, and writes generated outputs only under `$HERMES_HOME/cache/` (`generated/images/`, `generated/audio/`, `videos/`, `transcripts/`). Cached media persists until cleaned up by Hermes or the user. +- **Session token accounting**: Reports CLI `usage` token counts (Interactions API `total_*_tokens` and porcelain `thoughts_tokens`) to Hermes's session accounting. ## Development & Testing +Run tests using Hermes's virtual environment and validate the plugin manifest with the Hermes CLI: + ```bash -PYTHONPATH=/path/to/hermes-agent:. pytest tests/ -v -PYTHONPATH=/path/to/hermes-agent python -m hermes_cli.main plugins validate . +PYTHONPATH=/path/to/hermes-agent:. /path/to/hermes-agent/.venv/bin/python -m pytest tests/ -v +hermes plugins validate . ``` ## Acknowledgments diff --git a/SKILL.md b/SKILL.md new file mode 100644 index 0000000..7869344 --- /dev/null +++ b/SKILL.md @@ -0,0 +1,54 @@ +--- +name: gemini-api-cli +description: "Headless usage patterns, flags, and JSON envelopes for google-gemini/gemini-api-cli when invoking gemini-api from Hermes." +--- + +# Gemini API CLI (`gemini-api`) Reference + +Prefer the structured plugin tools (`image_generate`, `video_generate`, `gemini_music`, `gemini_tts`, `gemini_analyze`, `gemini_transcribe`, `gemini_deep_research`, `gemini_files_upload`) for standard media generation, multimodal analysis, transcription, and Deep Research tasks. Use the `gemini-api` CLI directly only when inspecting model catalogs, previewing request payloads with `--dry-run`, resuming async videos (`video --resume `), or calling advanced Interactions API, webhooks, or triggers subcommands. + +## Mandatory Headless Rules + +1. **Always disable interactive prompts and request JSON output**: pass `--no-interactive -o json` on every automated command so Cobra never opens a TUI picker on missing arguments. +2. **Disable SSE streaming when parsing JSON**: `generate`, `agent run`, and `agent status` stream SSE by default; add `--stream=false` whenever parsing a single JSON response object. +3. **Authenticate via `GEMINI_API_KEY`**: `gemini-api` reads `GEMINI_API_KEY` from the environment automatically; never pass API keys on the command line where process listings can expose them. Note that `GEMINI_ACCESS_TOKEN` takes precedence over `GEMINI_API_KEY` if set in your shell. +4. **Upload large local files when invoking the CLI directly**: `gemini_analyze` and `gemini_transcribe` plugin tools automatically upload local binary media >14 MiB, but direct `gemini-api` commands inline files up to 14 MiB only. For larger media (up to 2 GiB), run `gemini-api files upload --wait -o json --no-interactive` and pass the returned `files/` handle to `-i`. +5. **Avoid raw `--usage` and `--schema` dumps**: use `gemini-api --help` to inspect flags; raw `--usage` emits ~45 KB of KDL and raw `--schema` emits ~92 KB of JSON (pipe `--schema | jq ...` if you need specific fields). + +## Exit Codes & Structured Errors + +- `0` — Success (JSON object emitted on `stdout`; for `agent run` / `agent status`, still inspect `.status` and `.errors` because failed interactions exit `0`). +- `1` — Runtime or upstream Gemini API error. +- `2` — CLI flag or argument validation error. +- `3` — Missing or invalid `GEMINI_API_KEY` authentication. + +With `-o json` or `--agent-mode`, failures emit structured diagnostics on `stderr`: + +```json +{"error": "missing required flag --id", "exit_code": 2, "hints": ["pass --id "]} +``` + +## Common Ad-Hoc Commands + +```bash +# List available Gemini models as JSON +gemini-api models list --no-interactive -o json + +# Inspect CLI flags concisely without flooding context +gemini-api video --help +gemini-api agent run --help + +# Preview the outgoing HTTP request without sending network traffic +gemini-api generate "Summarize quantum error correction" --stream=false --dry-run --no-interactive -o json + +# Upload a large video or PDF once and reuse its 48-hour files/ handle +gemini-api files upload ./lecture.mp4 --wait --no-interactive -o json +gemini-api analyze -i files/abc123xyz "List key equations and timestamps" --no-interactive -o json + +# Resume polling an async video job +gemini-api video --resume --out ./clip.mp4 --no-interactive -o json + +# Run and poll a background Deep Research interaction +gemini-api agent run "Compare solid-state battery electrolytes" --agent deep-research-preview-04-2026 --background --stream=false --no-interactive -o json +gemini-api agent status --id --stream=false --no-interactive -o json +``` diff --git a/__init__.py b/__init__.py index 3d8dea1..3a11477 100644 --- a/__init__.py +++ b/__init__.py @@ -12,44 +12,112 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Google AI Studio Gemini image generation (Nano Banana 2.1, Nano Banana 2, Nano Banana 2 Lite, and Nano Banana Pro); -base64 inlineData → image cache. Selection: the caller's ``model`` (honoured only when it names a -catalog entry) → ``GEMINI_IMAGE_MODEL`` → ``image_gen.gemini.model`` → :data:`DEFAULT_MODEL`. The -shared top-level ``image_gen.model`` is deliberately NOT honoured: it is provider-agnostic and may -hold another backend's id. -Endpoint: ``image_gen.gemini.base_url`` → the named endpoint ``image_gen.gemini.provider`` → -``GEMINI_BASE_URL`` → :data:`BASE_URL`; key: env named by ``image_gen.gemini.key_env`` → the named -endpoint's credential → ``GEMINI_API_KEY``. -Resolution (``imageSize``), an exact aspect ratio and Google Search grounding are configured -through ``image_gen.gemini.*`` in ``config.yaml`` — the shared ``image_generate`` tool schema -carries no arguments for them. +"""Google AI Studio Gemini plugin for Hermes, backed end-to-end by ``google-gemini/gemini-api-cli``. + +Provides: +- ``GeminiImageGenProvider`` (``image_gen.provider = gemini``) via ``gemini-api image`` (Interactions API) +- ``GeminiVideoGenProvider`` (``video_gen.provider = gemini``) via ``gemini-api video`` (Interactions API) +- Six structured tools in the ``gemini_api`` toolset (``gemini_music``, ``gemini_tts``, + ``gemini_analyze``, ``gemini_transcribe``, ``gemini_deep_research``, ``gemini_files_upload``) +- Bundled ``gemini-api-cli`` skill (``SKILL.md``) + +Image model selection: caller ``model`` (honoured only when it names a Gemini catalog entry) → +``GEMINI_IMAGE_MODEL`` → ``image_gen.gemini.model`` → ``gemini-api image``'s built-in default +(:data:`DEFAULT_MODEL`). Top-level ``image_gen.model`` is deliberately NOT honoured because it is +provider-agnostic and may hold another backend's ID. """ from __future__ import annotations import base64 +import importlib +import importlib.metadata +import importlib.util +import json import logging import os +import sys from pathlib import Path -from types import SimpleNamespace -from typing import Any, Dict, List, Optional, Tuple -from urllib.parse import quote +from typing import Any, Callable, Dict, List, Optional, Tuple +import hermes_constants from agent.image_gen_provider import ( - DEFAULT_ASPECT_RATIO, resolve_aspect_ratio, save_b64_image, success_response) + DEFAULT_ASPECT_RATIO, + ImageGenProvider, + error_response, + normalize_reference_images, + resolve_aspect_ratio, + success_response, +) from agent.secret_scope import get_secret -from hermes_cli.version_info import get_version_info -from plugins.image_gen._common import ( - StaticImageGenProvider, collect_source_images, error_factory, load_image_gen_config, - post_json, prompt_required_error, record_token_usage, resolve_static_model) +from hermes_cli.config import get_compatible_custom_providers, load_config_readonly +from hermes_constants import get_hermes_home logger = logging.getLogger(__name__) BASE_URL = "https://generativelanguage.googleapis.com/v1beta" DEFAULT_MODEL = "gemini-nano-banana-2.1" -HERMES_VERSION = f"hermes-agent/{get_version_info().base_version}" -PLUGIN_VERSION = "0.1.0" -USER_AGENT = f"{HERMES_VERSION} gemini-image/{PLUGIN_VERSION}" +PLUGIN_VERSION = "0.2.0" +_FALLBACK_CLI_VERSION = "0.5.0" +_PROMPT_REQUIRED = "Prompt is required and must be a non-empty string" + + +def _load_sibling_module(module_leaf: str): + """Import a sibling plugin module across package, loader, and standalone test contexts.""" + pkg = __package__ or __name__ + parent = pkg.rpartition(".")[0] + if pkg in sys.modules and (not parent or parent in sys.modules): + try: + return importlib.import_module(f".{module_leaf}", package=pkg) + except ImportError: + pass + mod_name = f"{pkg}.{module_leaf}" + existing = sys.modules.get(mod_name) + if existing is not None: + return existing + mod_path = Path(__file__).resolve().parent / f"{module_leaf}.py" + if not mod_path.is_file(): + return None + spec = importlib.util.spec_from_file_location(mod_name, mod_path) + if spec is None or spec.loader is None: + return None + mod = importlib.util.module_from_spec(spec) + sys.modules[mod_name] = mod + spec.loader.exec_module(mod) + return mod + + +def _resolve_hermes_base_version() -> str: + """Resolve the running Hermes base version using only public package metadata and install stamps.""" + try: + hermes_root = Path(hermes_constants.__file__).resolve().parent + stamp_path = hermes_root / "install-stamp.json" + if stamp_path.is_file(): + stamp = json.loads(stamp_path.read_text(encoding="utf-8-sig")) + if isinstance(stamp, dict): + for key in ("baseVersion", "base_version", "version"): + val = str(stamp.get(key) or "").strip() + if val and val.lower() != "unknown": + return val + except Exception: # noqa: BLE001 + pass + try: + dist_ver = importlib.metadata.version("hermes-agent").strip() + if dist_ver and dist_ver != "0.0.0": + return dist_ver + except Exception: # noqa: BLE001 + pass + return "0.0.0" + + +def _pinned_cli_version() -> str: + runner_mod = _load_sibling_module("cli_runner") + return str(getattr(runner_mod, "PINNED_CLI_VERSION", _FALLBACK_CLI_VERSION)) + + +HERMES_VERSION = f"hermes-agent/{_resolve_hermes_base_version()}" +USER_AGENT = f"{HERMES_VERSION} (gemini-api-plugin/{PLUGIN_VERSION}; gemini-api-cli/{_pinned_cli_version()})" +CLI_USER_AGENT = USER_AGENT _ASPECT_RATIOS = {"landscape": "16:9", "square": "1:1", "portrait": "9:16"} _GEMINI_RATIOS_10 = ( @@ -58,17 +126,13 @@ _GEMINI_RATIOS_14 = _GEMINI_RATIOS_10 + ("1:4", "4:1", "1:8", "8:1") _MAX_REFERENCE_IMAGES = 14 _MAX_INPUT_IMAGE_BYTES = 25 * 1024 * 1024 # 25 MB per reference image -# Gemini caps an inline (non-Files-API) request at ~100 MB in total, so a per-image limit alone is -# not enough: 14 references at 25 MB would assemble ~470 MB of base64 before the server rejects it. -# Measured against the encoded payload, which runs ~4/3 of the raw bytes. -_MAX_INLINE_REQUEST_BYTES = 80 * 1024 * 1024 -_DEFAULT_TIMEOUT = (15.0, 120.0) - -# mime → cache-file extension. Local copy: a plugin should not import a private core name, and the -# set of formats Gemini can return inline is small and stable. -_MIME_TO_EXT = { - "image/png": "png", "image/jpeg": "jpg", "image/jpg": "jpg", - "image/webp": "webp", "image/gif": "gif", + +_MIME_TO_SUFFIX = { + "image/png": ".png", + "image/jpeg": ".jpg", + "image/jpg": ".jpg", + "image/webp": ".webp", + "image/gif": ".gif", } MODELS: Dict[str, Dict[str, Any]] = { @@ -115,22 +179,67 @@ } +def _read_config_cached() -> Dict[str, Any]: + """Read ``config.yaml`` using ``cli_runner``'s ``(mtime_ns, size)`` cache to avoid per-turn YAML reparsing.""" + runner_mod = _load_sibling_module("cli_runner") + if runner_mod is not None and hasattr(runner_mod, "_read_cached_config"): + cfg = runner_mod._read_cached_config() + return cfg if isinstance(cfg, dict) else {} + cfg = load_config_readonly() or {} + return cfg if isinstance(cfg, dict) else {} + + +def _load_image_gen_config(sub: Optional[str] = None) -> Dict[str, Any]: + """Read ``image_gen`` (or ``image_gen.``) via cached public ``hermes_cli.config``.""" + label = "image_gen" if sub is None else f"image_gen.{sub}" + try: + cfg = _read_config_cached() + section = cfg.get("image_gen") if isinstance(cfg, dict) else None + if sub is not None: + section = section.get(sub) if isinstance(section, dict) else None + return section if isinstance(section, dict) else {} + except Exception as exc: # noqa: BLE001 + logger.debug("Could not load %s config: %s", label, exc) + return {} + + +def _collect_source_images( + image_url: Optional[str], + reference_image_urls: Optional[List[str]], + limit: Optional[int] = None, +) -> List[str]: + sources: List[str] = [] + if isinstance(image_url, str) and image_url.strip(): + sources.append(image_url.strip()) + sources.extend(normalize_reference_images(reference_image_urls) or []) + return sources[:limit] if limit is not None else sources + + +def _error_factory( + provider: str, aspect: str, *, model: str = "", prompt: str = "" +) -> Callable[..., Dict[str, Any]]: + def fail(error: str, error_type: str, **override: Any) -> Dict[str, Any]: + kwargs: Dict[str, Any] = dict(provider=provider, model=model, prompt=prompt, aspect_ratio=aspect) + kwargs.update(override) + return error_response(error=error, error_type=error_type, **kwargs) + + return fail + + +def _prompt_required_error(provider: str, aspect: str) -> Dict[str, Any]: + return _error_factory(provider, aspect)(_PROMPT_REQUIRED, "invalid_argument") + + def _strip_google_prefix(value: Optional[str]) -> Optional[str]: if not isinstance(value, str) or not value.strip(): return None raw = value.strip() - return raw.split("/", 1)[1].strip() if raw.lower().startswith("google/") else raw + cleaned = raw.split("/", 1)[1].strip() if raw.lower().startswith("google/") else raw + return None if (not cleaned or cleaned.startswith("-")) else cleaned def _custom_model_meta(model_id: str) -> Dict[str, Any]: - """Conservative metadata for an uncatalogued Gemini id: the ratio set common to every image - model, no ``imageSize`` and no search grounding. - - A model we do not know may not accept the newer ``imageConfig``/``tools`` fields, and sending - them earns a remote 400 that reads like a Hermes bug. Omitting a capability the model happens - to support only costs the user that extra, and mirrors ``resolve_static_model`` dropping - ``quality`` on passthrough (#97928). - """ + """Conservative metadata for an uncatalogued Gemini image model ID.""" return { "display": model_id, "api_model": model_id, @@ -141,38 +250,60 @@ def _custom_model_meta(model_id: str) -> Dict[str, Any]: } -def _resolve_model(caller_model: Optional[str] = None) -> Tuple[str, Dict[str, Any]]: - """``(model_id, meta)`` — caller ``model`` (only when it names a catalog entry) → - ``GEMINI_IMAGE_MODEL`` → ``image_gen.gemini.model`` → :data:`DEFAULT_MODEL`. - - ``image_generate`` passes the shared top-level ``image_gen.model`` down as the ``model`` kwarg, - and that key is provider-agnostic: with ``image_gen: {provider: gemini, model: gpt-image-2}`` - it names an OpenAI model. Honouring it verbatim would POST to ``models/gpt-image-2`` and return - a remote 404 instead of a local fallback, so membership is checked first — the same rule the - xAI backend applies to its own caller kwarg. Every other source is resolved by - :func:`resolve_static_model`, which already refuses the shared top-level key while still - allowing a deliberately provider-scoped custom id through. +def _resolve_model_selection( + caller_model: Optional[str] = None, cfg: Optional[Dict[str, Any]] = None +) -> Tuple[str, Dict[str, Any], Optional[str]]: + """Return ``(model_id, meta, explicit_override)``. + + ``explicit_override`` is ``None`` when no caller/env/config override is active, allowing + ``gemini-api image`` to omit ``-m`` and own its built-in default across CLI upgrades. """ cleaned = _strip_google_prefix(caller_model) if cleaned and cleaned in MODELS: - return cleaned, MODELS[cleaned] + return cleaned, MODELS[cleaned], cleaned if cleaned: logger.debug( "Ignoring image model id %r: not a Gemini model. Set image_gen.gemini.model or " - "GEMINI_IMAGE_MODEL to choose one.", cleaned) - model_id, _ = resolve_static_model( - MODELS, DEFAULT_MODEL, env_var="GEMINI_IMAGE_MODEL", config_key="gemini", passthrough=True) - normalized = _strip_google_prefix(model_id) or model_id - return normalized, MODELS.get(normalized) or _custom_model_meta(normalized) + "GEMINI_IMAGE_MODEL to choose one.", + cleaned, + ) + env_override = _strip_google_prefix(os.environ.get("GEMINI_IMAGE_MODEL")) + if env_override: + return env_override, MODELS.get(env_override) or _custom_model_meta(env_override), env_override -def _named_endpoint(name: str) -> Tuple[str, str]: - """``(base_url, api_key)`` of the user-declared custom endpoint *name* (``providers:`` / - ``custom_providers:``), so image generation reuses a chat endpoint's URL and credential without - duplicating the key into Gemini variables (#83080). Unknown name → ``("", "")`` with a warning.""" - from hermes_cli.runtime_provider import _get_named_custom_provider + scoped = _load_image_gen_config("gemini") if cfg is None else cfg + cfg_model = _strip_google_prefix(scoped.get("model") if isinstance(scoped, dict) else None) + if cfg_model: + return cfg_model, MODELS.get(cfg_model) or _custom_model_meta(cfg_model), cfg_model + + return DEFAULT_MODEL, MODELS[DEFAULT_MODEL], None + + +def _resolve_model(caller_model: Optional[str] = None) -> Tuple[str, Dict[str, Any]]: + """``(model_id, meta)`` — caller catalog entry → ``GEMINI_IMAGE_MODEL`` → ``image_gen.gemini.model`` → default.""" + model_id, meta, _ = _resolve_model_selection(caller_model) + return model_id, meta - entry = _get_named_custom_provider(name) + +def _named_endpoint(name: str) -> Tuple[str, str]: + """``(base_url, api_key)`` of the user-declared custom endpoint *name* via public ``hermes_cli.config``.""" + target = name.strip().lower() + if not target: + return "", "" + try: + cfg = _read_config_cached() + providers = get_compatible_custom_providers(cfg) or [] + except Exception: # noqa: BLE001 + providers = [] + + entry = next( + ( + p for p in providers + if isinstance(p, dict) and str(p.get("name") or "").strip().lower() == target + ), + None, + ) if not entry: logger.warning("image_gen.gemini.provider %r matches no custom endpoint in providers:", name) return "", "" @@ -184,8 +315,8 @@ def _named_endpoint(name: str) -> Tuple[str, str]: def _resolve_endpoint(cfg: Optional[Dict[str, Any]] = None) -> Tuple[str, str]: """``(base_url, api_key)`` — ``image_gen.gemini.base_url`` → named endpoint → ``GEMINI_BASE_URL`` → :data:`BASE_URL`; the env var named by ``image_gen.gemini.key_env`` → named endpoint → - ``GEMINI_API_KEY``. Shared by ``is_available()`` and ``generate()``.""" - cfg = load_image_gen_config("gemini") if cfg is None else cfg + ``GEMINI_API_KEY``. Shared across image, video, and CLI tools.""" + cfg = _load_image_gen_config("gemini") if cfg is None else cfg named = str(cfg.get("provider") or "").strip() named_base, named_key = _named_endpoint(named) if named else ("", "") base_url = ( @@ -207,13 +338,12 @@ def _resolve_endpoint(cfg: Optional[Dict[str, Any]] = None) -> Tuple[str, str]: def _resolve_exact_aspect_ratio( meta: Dict[str, Any], aspect_ratio: Optional[str], cfg: Optional[Dict[str, Any]] = None ) -> Tuple[str, str]: - """``(semantic_aspect, wire_aspect)`` — an exact ratio (the ``aspect_ratio`` argument itself → - ``image_gen.gemini.aspect_ratio`` in ``config.yaml``) wins when listed in - ``meta['aspect_ratios']``; otherwise the semantic landscape/square/portrait mapping applies.""" + """``(semantic_aspect, wire_aspect)`` — an exact ratio (caller argument → ``image_gen.gemini.aspect_ratio``) + wins when supported by *meta*; otherwise the semantic landscape/square/portrait mapping applies.""" semantic = resolve_aspect_ratio(aspect_ratio) supported: Tuple[str, ...] = tuple(meta.get("aspect_ratios") or _GEMINI_RATIOS_10) raw_arg = (aspect_ratio or "").strip() - cfg = load_image_gen_config("gemini") if cfg is None else cfg + cfg = _load_image_gen_config("gemini") if cfg is None else cfg for candidate in ( raw_arg if raw_arg in supported else None, cfg.get("aspect_ratio"), @@ -222,20 +352,17 @@ def _resolve_exact_aspect_ratio( exact = candidate.strip() w, h = (int(x) for x in exact.split(":")) return ("square" if w == h else ("landscape" if w > h else "portrait")), exact - # resolve_aspect_ratio only ever returns one of the three semantic names, so the mapping hits. return semantic, _ASPECT_RATIOS[semantic] def _resolve_image_size( meta: Dict[str, Any], upscale: bool = False, cfg: Optional[Dict[str, Any]] = None ) -> Optional[str]: - """``imageConfig.imageSize`` (``"512"``/``"1K"``/``"2K"``/``"4K"``) when *meta* supports it: - ``upscale`` → ``image_gen.gemini.image_size``/``.resolution`` in ``config.yaml``. - ``None`` leaves the field off, which is also what an uncatalogued model gets.""" + """``--image-size`` (``512``/``1K``/``2K``/``4K``) when *meta* supports it.""" supported: Tuple[str, ...] = tuple(meta.get("resolutions") or ()) if not supported: return None - cfg = load_image_gen_config("gemini") if cfg is None else cfg + cfg = _load_image_gen_config("gemini") if cfg is None else cfg for candidate in ( "4K" if upscale and "4K" in supported else ("2K" if upscale and "2K" in supported else None), cfg.get("image_size") or cfg.get("resolution"), @@ -248,22 +375,15 @@ def _resolve_image_size( def _resolve_google_search(meta: Dict[str, Any], cfg: Optional[Dict[str, Any]] = None) -> bool: - """Whether ``tools: [{"googleSearch": {}}]`` grounding is enabled, when *meta* supports it: - configured via ``image_gen.gemini.google_search``/``.search_grounding`` in ``config.yaml``.""" + """Whether ``tools: [{"type": "google_search"}]`` grounding is enabled when *meta* supports it.""" if not meta.get("supports_search"): return False - cfg = load_image_gen_config("gemini") if cfg is None else cfg + cfg = _load_image_gen_config("gemini") if cfg is None else cfg return bool(cfg.get("google_search") or cfg.get("search_grounding")) def _sniff_mime(data: bytes) -> str: - """The image MIME type of *data*, read from its magic bytes. - - Magic bytes rather than the declared ``Content-Type`` or the file extension: for the formats - Gemini accepts inline those bytes are authoritative, so a payload whose label disagrees with - its content is mislabelled by definition. Raising here names the offending reference, where a - trusted label would inline an HTML error page and earn an opaque remote 400 instead. - """ + """Detect supported image MIME type from magic bytes.""" if data.startswith(b"\x89PNG\r\n\x1a\n"): return "image/png" if data.startswith(b"\xff\xd8\xff"): @@ -279,154 +399,112 @@ def _cap_message(ref: str) -> str: return f"exceeds the {_MAX_INPUT_IMAGE_BYTES // (1024 * 1024)}MB per-image cap: {ref}" +def _resolve_safe_local_image(ref: str) -> Path: + """Resolve symlinks and enforce ``raise_if_read_blocked`` plus size cap on a local image path.""" + from agent.file_safety import raise_if_read_blocked + + raise_if_read_blocked(ref) + path = Path(os.path.expanduser(ref)).resolve() + raise_if_read_blocked(str(path)) + if not path.is_file(): + raise ValueError(f"Image input path is not a regular file or does not exist: {ref}") + if path.stat().st_size > _MAX_INPUT_IMAGE_BYTES: + raise ValueError(f"Image input path {_cap_message(ref)}") + return path + + +def _sniff_local_image_mime(ref: str) -> str: + """Validate a local image path and sniff its MIME type from only the first 16 header bytes.""" + path = _resolve_safe_local_image(ref) + with path.open("rb") as fh: + header = fh.read(16) + return _sniff_mime(header) + + def _load_image_bytes(ref: str) -> Tuple[bytes, str]: - """Load ``(data, mime_type)`` from a URL, data URI or local path; raises on IO/network/security - error, on a payload that is not a supported image, or past :data:`_MAX_INPUT_IMAGE_BYTES`.""" + """Load ``(data, mime_type)`` from a URL, data URI, or local path with SSRF and file-safety guards.""" ref = ref.strip() lower = ref.lower() if lower.startswith(("http://", "https://")): - from tools.url_safety import create_ssrf_safe_client, is_safe_url - - if not is_safe_url(ref): - raise ValueError(f"Image reference URL failed the SSRF safety check: {ref}") - # Streamed so an oversized body is dropped mid-flight instead of being buffered in full and - # only then measured. Redirect hops need no further check here: the SSRF-safe client guards - # at the TCP connect layer, validating (and dialling) a vetted IP on every hop. - with create_ssrf_safe_client(timeout=60.0, follow_redirects=True) as client: + from tools.url_safety import create_ssrf_safe_client + + chunks: List[bytes] = [] + total = 0 + with create_ssrf_safe_client(timeout=30.0, follow_redirects=True) as client: with client.stream("GET", ref) as resp: resp.raise_for_status() declared = (resp.headers.get("Content-Length") or "").strip() if declared.isdigit() and int(declared) > _MAX_INPUT_IMAGE_BYTES: - raise ValueError(f"Image reference URL {_cap_message(ref)}") - chunks: List[bytes] = [] - total = 0 - for chunk in resp.iter_bytes(chunk_size=64 * 1024): + raise ValueError(f"Image URL {_cap_message(ref)}") + for chunk in resp.iter_bytes(): total += len(chunk) if total > _MAX_INPUT_IMAGE_BYTES: - raise ValueError(f"Image reference URL {_cap_message(ref)}") + raise ValueError(f"Image URL {_cap_message(ref)}") chunks.append(chunk) raw = b"".join(chunks) return raw, _sniff_mime(raw) if lower.startswith("data:"): - _, sep, b64 = ref.partition(",") - if not sep: - raise ValueError("image data URI is missing its payload") + header, sep, b64 = ref.partition(",") + if not sep or ";base64" not in header.lower(): + raise ValueError("Unsupported data URI for image input (expected base64-encoded image)") b64 = "".join(b64.split()) - # base64 inflates ~4/3, so the encoded length bounds the decode before it allocates. if len(b64) > (_MAX_INPUT_IMAGE_BYTES // 3) * 4 + 4: raise ValueError(f"Image data URI {_cap_message('data:')}") raw = base64.b64decode(b64, validate=True) if len(raw) > _MAX_INPUT_IMAGE_BYTES: raise ValueError(f"Image data URI {_cap_message('data:')}") return raw, _sniff_mime(raw) - from agent.file_safety import raise_if_read_blocked # credential-read guard before local bytes - - raise_if_read_blocked(ref) - path = Path(os.path.expanduser(ref)) - if not path.is_file(): - raise ValueError(f"Image input path is not a regular file or does not exist: {ref}") - # stat() first so an oversized file is refused without reading it into memory. - if path.stat().st_size > _MAX_INPUT_IMAGE_BYTES: - raise ValueError(f"Image input path {_cap_message(ref)}") + path = _resolve_safe_local_image(ref) raw = path.read_bytes() if len(raw) > _MAX_INPUT_IMAGE_BYTES: raise ValueError(f"Image input path {_cap_message(ref)}") return raw, _sniff_mime(raw) -def _extract_error_message(response: Any, exc: Exception) -> str: - """Extract Google AI Studio's nested ``error.message`` JSON field on HTTP errors.""" - if response is not None: - try: - body = response.json() - error = body.get("error") if isinstance(body, dict) else None - if isinstance(error, dict) and error.get("message"): - return str(error["message"]) - if isinstance(body, dict) and body.get("message"): - return str(body["message"]) - except Exception: # noqa: BLE001 - pass - text = getattr(response, "text", None) or getattr(response, "reason", None) - if text: - return str(text)[:300] - return str(exc) - - -def _extract_inline_image(body: Dict[str, Any]) -> Tuple[Optional[Tuple[str, str]], Optional[str]]: - """Return ``((b64_data, extension), text_fallback)`` from a ``generateContent`` response.""" - candidates = body.get("candidates") - if not isinstance(candidates, list) or not candidates: - block = (body.get("promptFeedback") or {}).get("blockReason") - return None, (f"Prompt blocked by safety filter ({block})" if block else None) - - texts: List[str] = [] - for candidate in candidates: - if not isinstance(candidate, dict): - continue - parts = ((candidate.get("content") or {}).get("parts")) or [] - for part in parts: - if not isinstance(part, dict) or part.get("thought") is True: - continue - inline = part.get("inlineData") or part.get("inline_data") - if isinstance(inline, dict): - b64_data = str(inline.get("data") or "").strip() - if b64_data: - mime = str(inline.get("mimeType") or inline.get("mime_type") or "").strip().lower() - ext = _MIME_TO_EXT.get(mime) - if not ext: - # No/unknown mimeType: sniff the leading bytes rather than assume PNG, so a - # WebP or JPEG still lands in the cache under its true extension. - try: - ext = _MIME_TO_EXT.get( - _sniff_mime(base64.b64decode(b64_data[:64])), "png") - except Exception: # noqa: BLE001 - ext = "png" - return (b64_data, ext), None - text = part.get("text") - if isinstance(text, str) and text.strip(): - texts.append(text.strip()) - finish_reason = candidate.get("finishReason") - if finish_reason and finish_reason not in ("STOP", "MAX_TOKENS"): - texts.append(f"finishReason={finish_reason}") - return None, ("; ".join(texts) if texts else None) - - -def _usage_from_gemini_metadata(usage_meta: Dict[str, Any]) -> SimpleNamespace: - """Gemini's camelCase ``usageMetadata`` → the snake_case shape ``record_token_usage`` reads. - - ``thoughtsTokenCount`` is folded into the completion count. Nano Banana 2.1 and Nano Banana Pro - reason before they draw, and ``totalTokenCount`` already counts those tokens, so omitting them - records a row where prompt + completion does not reconcile with the total — on a thinking image - call the shortfall is most of the billed work. Core's converter still leaves them out (upstream - #103002 / #103205 propose the same fix there); this is a deliberate, local divergence rather - than a fork of core behaviour. - """ - def count(key: str) -> int: - value = usage_meta.get(key) - return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else 0 - - return SimpleNamespace( - prompt_tokens=count("promptTokenCount"), - completion_tokens=count("candidatesTokenCount") + count("thoughtsTokenCount"), - total_tokens=count("totalTokenCount"), - prompt_tokens_details=SimpleNamespace(cached_tokens=count("cachedContentTokenCount")), - ) - +class GeminiImageGenProvider(ImageGenProvider): + """Hermes ``ImageGenProvider`` backed by ``gemini-api image`` (Interactions API).""" -class GeminiImageGenProvider(StaticImageGenProvider): - """Google AI Studio ``models/{model}:generateContent`` backend for Nano Banana image generation.""" - - provider_id = "gemini" - label = "Google AI Studio" models = MODELS - default_model_id = DEFAULT_MODEL - price = "varies" + + def __init__(self, *, runner: Any = None) -> None: + if runner is None: + runner_mod = _load_sibling_module("cli_runner") + if runner_mod is None: + raise ImportError("Unable to load sibling cli_runner module") + runner = runner_mod.GeminiCLIRunner( + endpoint_resolver=_resolve_endpoint, + user_agent=CLI_USER_AGENT, + ) + self._runner = runner + + @property + def name(self) -> str: + return "gemini" + + @property + def display_name(self) -> str: + return "Google AI Studio" + + def list_models(self) -> List[Dict[str, Any]]: + rows: List[Dict[str, Any]] = [] + for model_id, meta in MODELS.items(): + rows.append({ + "id": model_id, + "display": meta.get("display", model_id), + "speed": meta.get("speed", ""), + "strengths": meta.get("strengths", ""), + "price": "varies", + }) + return rows + + def default_model(self) -> Optional[str]: + return DEFAULT_MODEL def get_setup_schema(self) -> Dict[str, Any]: return { - "name": "Google AI Studio (direct)", + "name": "Google AI Studio (gemini-api CLI)", "badge": "paid", - "tag": "Native Gemini (Nano Banana) image generation & editing with GEMINI_API_KEY", + "tag": "Gemini (Nano Banana) image generation & editing via gemini-api CLI and GEMINI_API_KEY", "env_vars": [ { "key": "GEMINI_API_KEY", @@ -437,7 +515,7 @@ def get_setup_schema(self) -> Dict[str, Any]: } def is_available(self) -> bool: - return bool(_resolve_endpoint()[1]) + return bool(self._runner.is_available()) def capabilities(self) -> Dict[str, Any]: _, meta = _resolve_model() @@ -445,105 +523,111 @@ def capabilities(self) -> Dict[str, Any]: return { "modalities": ["text", "image"], "max_reference_images": int(meta.get("max_refs") or _MAX_REFERENCE_IMAGES), - # Advertise the knob only when this model has a rung above 1K to climb to. The lite - # model is 1K-only, so offering `upscale` there would accept the argument and quietly - # do nothing; the tool hides the parameter entirely when this is False. "supports_upscale": bool(resolutions & {"2K", "4K"}), } def generate( - self, prompt: str, aspect_ratio: str = DEFAULT_ASPECT_RATIO, *, - image_url: Optional[str] = None, reference_image_urls: Optional[List[str]] = None, + self, + prompt: str, + aspect_ratio: str = DEFAULT_ASPECT_RATIO, + *, + image_url: Optional[str] = None, + reference_image_urls: Optional[List[str]] = None, **kwargs: Any, ) -> Dict[str, Any]: prompt = (prompt or "").strip() - # One snapshot for the whole call: load_image_gen_config deep-copies on every read, and the - # resolvers below would otherwise re-read it four times and could disagree if the file - # changed underneath a long generation. - cfg = load_image_gen_config("gemini") - model_id, meta = _resolve_model(kwargs.get("model")) + cfg = _load_image_gen_config("gemini") + model_id, meta, explicit_model = _resolve_model_selection(kwargs.get("model"), cfg) aspect, wire_aspect = _resolve_exact_aspect_ratio(meta, aspect_ratio, cfg) if not prompt: - return prompt_required_error("gemini", aspect) + return _prompt_required_error("gemini", aspect) + base_url, api_key = _resolve_endpoint(cfg) if not api_key: - return error_factory("gemini", aspect)( + return _error_factory("gemini", aspect)( "GEMINI_API_KEY is not set (and image_gen.gemini.key_env is empty). " "Run `hermes tools` → Image Generation → Google AI Studio to configure.", - "auth_required") + "auth_required", + ) - max_refs = int(meta.get("max_refs") or _MAX_REFERENCE_IMAGES) - sources = collect_source_images(image_url, reference_image_urls, limit=max_refs) - is_edit = bool(sources) - fail = error_factory("gemini", aspect, model=model_id, prompt=prompt) - - parts: List[Dict[str, Any]] = [] - encoded_total = 0 - for ref in sources: + fail = _error_factory("gemini", aspect, model=model_id, prompt=prompt) + runner_mod = _load_sibling_module("cli_runner") + if runner_mod is not None and hasattr(runner_mod, "validate_base_url"): try: - img_bytes, mime = _load_image_bytes(ref) - except Exception as exc: # noqa: BLE001 - return fail(f"Could not load reference image: {exc}", "invalid_argument") - encoded = base64.b64encode(img_bytes).decode("ascii") - # Each image is individually under the per-image cap, but the request as a whole still - # has to fit Gemini's inline ceiling. Fail here, naming the reference we stopped on, - # rather than assembling hundreds of MB only for the server to refuse it. - encoded_total += len(encoded) - if encoded_total > _MAX_INLINE_REQUEST_BYTES: - limit_mb = _MAX_INLINE_REQUEST_BYTES // (1024 * 1024) - return fail( - f"Reference images exceed the {limit_mb}MB total request limit (stopped at " - f"{ref}). Use fewer or smaller references.", "invalid_argument") - parts.append({"inlineData": {"mimeType": mime, "data": encoded}}) - parts.append({"text": prompt}) - - image_config: Dict[str, Any] = {"aspectRatio": wire_aspect} + runner_mod.validate_base_url(base_url) + except ValueError as exc: + return fail(str(exc), "invalid_argument") + + out_dir = get_hermes_home() / "cache" / "generated" / "images" + out_dir.mkdir(parents=True, exist_ok=True) + + cli_args: List[str] = ["image", "--out", str(out_dir)] + if explicit_model: + cli_args.extend(["-m", explicit_model]) + cli_args.extend(["--aspect-ratio", wire_aspect]) + image_size = _resolve_image_size(meta, bool(kwargs.get("upscale")), cfg) if image_size: - image_config["imageSize"] = image_size + cli_args.extend(["--image-size", image_size]) - payload: Dict[str, Any] = { - "contents": [{"parts": parts}], - "generationConfig": {"responseModalities": ["TEXT", "IMAGE"], "imageConfig": image_config}, - } use_google_search = _resolve_google_search(meta, cfg) if use_google_search: - payload["tools"] = [{"googleSearch": {}}] + cli_args.extend(["--body", json.dumps({"tools": [{"type": "google_search"}]})]) - url = f"{base_url}/models/{quote(meta['api_model'], safe='')}:generateContent" - headers = { - "x-goog-api-key": api_key, - "Content-Type": "application/json", - "User-Agent": USER_AGENT, - } - body, failure = post_json( - url, headers=headers, payload=payload, timeout=_DEFAULT_TIMEOUT, - label="Google AI Studio", error_message=_extract_error_message, - catch_request_exception=True) - if failure is not None: - err_type = "auth_required" if failure.status in (401, 403) else failure.error_type - return fail(failure.error, err_type) - if not isinstance(body, dict): - return fail("Google AI Studio returned a non-object JSON payload", "invalid_response") - - # Gemini bills per text/image token; recorded before extraction so a billed - # HTTP 200 with a text refusal / empty image still lands in session accounting. - if isinstance(body.get("usageMetadata"), dict): - record_token_usage( - _usage_from_gemini_metadata(body["usageMetadata"]), - model=meta["api_model"], provider="gemini", base_url=base_url) - - extracted, reason = _extract_inline_image(body) - if not extracted: - detail = f": {reason}" if reason else "" - return fail(f"Google AI Studio returned no image data{detail}", "empty_response") - - b64_data, ext = extracted - try: - saved_path = save_b64_image(b64_data, prefix=f"gemini_{model_id}", extension=ext) - except Exception as exc: # noqa: BLE001 - return fail(f"Google AI Studio returned undecodable image data: {exc}", "invalid_response") + max_refs = int(meta.get("max_refs") or _MAX_REFERENCE_IMAGES) + sources = _collect_source_images(image_url, reference_image_urls, limit=max_refs) + is_edit = bool(sources) + tmp_files: List[Path] = [] + inline_used = 0 + default_timeout = int(getattr(runner_mod, "DEFAULT_CLI_TIMEOUT", 180)) if runner_mod else 180 + try: + for ref in sources: + valid_ref, ref_err, added_cost = self._runner.prepare_image_input( + ref, + image_loader=_load_image_bytes, + local_mime_sniffer=_sniff_local_image_mime, + mime_to_suffix=_MIME_TO_SUFFIX, + tmp_files=tmp_files, + tmp_prefix="hermes-image-ref-", + inline_budget_used=inline_used, + enforce_cumulative=True, + ) + if ref_err is not None or not valid_ref: + return fail( + f"Could not load reference image: {ref_err.error}" + if ref_err is not None + else "Invalid reference image input.", + (ref_err.error_type if ref_err is not None else "") or "invalid_argument", + ) + cli_args.extend(["-i", valid_ref]) + inline_used += added_cost + + res = self._runner.run( + cli_args, + positional_args=[prompt], + default_timeout=default_timeout, + default_model=meta["api_model"], + ) + finally: + for tmp_path in tmp_files: + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + + if not res.ok: + return fail(res.error or "gemini-api image failed", res.error_type or "provider_error") + + payload = res.data if isinstance(res.data, dict) else {} + saved_path = str(payload.get("path") or "").strip() + if not saved_path or not Path(saved_path).is_file(): + return fail( + "gemini-api image completed without returning a valid output image file path.", + "invalid_response", + ) + + reported_model = str(payload.get("model") or model_id).strip() extra: Dict[str, Any] = {"api": "google-ai-studio", "exact_aspect_ratio": wire_aspect} if image_size: extra["image_size"] = image_size @@ -551,11 +635,42 @@ def generate( extra["upscaled"] = True if use_google_search: extra["google_search"] = True + if payload.get("response_id"): + extra["response_id"] = payload["response_id"] + if payload.get("mime_type"): + extra["mime_type"] = payload["mime_type"] return success_response( - image=str(saved_path), model=model_id, prompt=prompt, aspect_ratio=aspect, - provider="gemini", modality="image" if is_edit else "text", extra=extra) + image=saved_path, + model=reported_model, + prompt=prompt, + aspect_ratio=aspect, + provider="gemini", + modality="image" if is_edit else "text", + extra=extra, + ) + + +def _load_cli_tools_module(): + """Import sibling ``cli_tools`` across package, loader, and standalone test contexts.""" + return _load_sibling_module("cli_tools") def register(ctx) -> None: - """Plugin entry point — wire ``GeminiImageGenProvider`` into the registry.""" - ctx.register_image_gen_provider(GeminiImageGenProvider()) + """Plugin entry point — wire CLI-backed Gemini image/video providers, tools, and skill.""" + runner_mod = _load_sibling_module("cli_runner") + shared_runner = ( + runner_mod.GeminiCLIRunner(endpoint_resolver=_resolve_endpoint, user_agent=CLI_USER_AGENT) + if runner_mod is not None + else None + ) + ctx.register_image_gen_provider(GeminiImageGenProvider(runner=shared_runner)) + cli_tools = _load_cli_tools_module() + if cli_tools is not None: + cli_tools.register_cli_integrations( + ctx, + endpoint_resolver=_resolve_endpoint, + image_loader=_load_image_bytes, + local_mime_sniffer=_sniff_local_image_mime, + user_agent=CLI_USER_AGENT, + runner=shared_runner, + ) diff --git a/cli_runner.py b/cli_runner.py new file mode 100644 index 0000000..7b579de --- /dev/null +++ b/cli_runner.py @@ -0,0 +1,962 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Subprocess runner, binary discovery, and opt-in pinned installer for ``gemini-api``. + +Wraps ``google-gemini/gemini-api-cli`` in non-interactive JSON mode (``--no-interactive -o json``) +with Hermes profile-scoped ``GEMINI_API_KEY`` isolation, PR #2 ``User-Agent`` attribution, +``agent.file_safety`` local-path checks, ``--`` positional argument flag-injection guards, and +structured error / token-usage extraction. +""" + +from __future__ import annotations + +import errno +import hashlib +import io +import json +import logging +import os +import platform +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +import threading +import time +import zipfile +from dataclasses import dataclass, field +from pathlib import Path +from types import SimpleNamespace +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple +from urllib.parse import urlsplit + +from hermes_constants import get_hermes_home + +logger = logging.getLogger(__name__) + +PINNED_CLI_VERSION = "0.5.0" +# Verified SHA-256 digests from https://github.com/google-gemini/gemini-api-cli/releases/download/v0.5.0/checksums.txt +PINNED_CLI_SHA256: Dict[str, str] = { + "gemini-api_Darwin_arm64.tar.gz": "ae31afd60148edc4b8550811d406b875c4b74164ca96a5782ff47bf60057aef7", + "gemini-api_Darwin_x86_64.tar.gz": "006c1f58e2c2711b9a7c6d537e4db4f930df49402035bcdfdefdd25384d07989", + "gemini-api_Linux_arm64.tar.gz": "cea63e70982a06f81069318049bfca6db49042649c5ae635b3433cb3a2420d20", + "gemini-api_Linux_x86_64.tar.gz": "fce229dd482ec1caff15cd147a293513ffb5a52390394e52136f85b4a497c742", + "gemini-api_Windows_arm64.zip": "a64df8f4b0ec394de4a42b8be96831942ec850463aacc77d41c6b04f07af2963", + "gemini-api_Windows_x86_64.zip": "d2bc738fb8c83f663e1fca5e3382876dcbde54880c7375cfcb49351298b264ec", +} +CLI_INLINE_LIMIT_BYTES = 14 * 1024 * 1024 # ~14 MiB single-file raw binary limit (~19 MiB base64) +CLI_CUMULATIVE_INLINE_BYTES = 19 * 1024 * 1024 # 19 MiB cumulative base64 request budget in gemini-api +CLI_MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024 # 2 GiB Gemini Files API ceiling +DEFAULT_CLI_TIMEOUT = 180 +DEFAULT_RESEARCH_TIMEOUT = 900 + +_MAX_CHECKSUMS_BYTES = 64 * 1024 # 64 KiB download ceiling for checksums.txt +_MAX_ARCHIVE_BYTES = 64 * 1024 * 1024 # 64 MiB download ceiling for gemini-api release archives +_MAX_BINARY_BYTES = 128 * 1024 * 1024 # 128 MiB extracted binary ceiling +_CLI_CACHE_TTL_SECONDS = 5.0 +_MAX_CACHE_ENTRIES = 64 + +# Safe non-secret process environment variables forwarded to the gemini-api child process. +# Unrelated secrets (OpenAI, Anthropic, GitHub, etc.), HERMES_* state, and conflicting +# GEMINI_* / GOOGLE_API_KEY variables are never inherited. +_SAFE_CHILD_ENV_KEYS = frozenset({ + "PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "COLORTERM", + "TMPDIR", "TEMP", "TMP", "LANG", "LANGUAGE", "TZ", + "SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", + "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", + "http_proxy", "https_proxy", "all_proxy", "no_proxy", + "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_RUNTIME_DIR", + "SYSTEMROOT", "COMSPEC", "WINDIR", "PATHEXT", + "APPDATA", "LOCALAPPDATA", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", +}) + +CLI_INSTALL_HINT = ( + f"gemini-api CLI binary not found. Install v{PINNED_CLI_VERSION} with " + f"`go install github.com/google-gemini/gemini-api-cli/cmd/gemini-api@v{PINNED_CLI_VERSION}` " + f"or place the release binary from https://github.com/google-gemini/gemini-api-cli/releases/tag/v{PINNED_CLI_VERSION} " + "into ~/.hermes/bin/gemini-api (or set plugins.entries.gemini-api.settings.cli_path in config.yaml)." +) + +_DEFAULT_SERVER_URL = "https://generativelanguage.googleapis.com" +_API_VERSION_SUFFIXES = ("/v1beta", "/v1alpha", "/v1") +_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"}) +_YOUTUBE_HOST_RE = re.compile(r"^(?:www\.|m\.|music\.)?(?:youtube\.com|youtu\.be)$", re.IGNORECASE) +_FILE_ID_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$") +# Extensions that gemini-api sends strictly as inline text blocks or rejects in analyze/transcribe +# (must NOT be auto-uploaded to Files API — let gemini-api report its fast local diagnostic instead). +_NON_UPLOADABLE_ANALYZE_EXTS = frozenset({ + ".txt", ".md", ".html", ".htm", ".xml", ".json", ".js", ".ts", ".py", ".go", ".css", ".yaml", ".yml", + ".amr", ".wma", ".mkv", ".rtf", +}) + +_cache_lock = threading.Lock() +_install_lock = threading.Lock() +_config_cache: Dict[str, Tuple[int, int, Dict[str, Any]]] = {} +_binary_cache: Dict[Tuple[str, str, str], Tuple[float, Optional[str]]] = {} + + +@dataclass +class CLIResult: + """Normalized result from a ``gemini-api`` subprocess invocation.""" + + ok: bool + exit_code: int + data: Any = None + stdout: str = "" + stderr: str = "" + error: str = "" + error_type: str = "" + hints: List[str] = field(default_factory=list) + + +def clear_cli_cache() -> None: + """Clear short-lived binary and config caches (primarily for unit tests).""" + with _cache_lock: + _config_cache.clear() + _binary_cache.clear() + + +def _read_cached_config() -> Dict[str, Any]: + """Read ``$HERMES_HOME/config.yaml`` keyed by ``(mtime_ns, size)`` to avoid per-turn YAML thrash.""" + home = get_hermes_home() + cfg_path = home / "config.yaml" + cache_key = str(cfg_path) + try: + st = cfg_path.stat() + except OSError: + with _cache_lock: + _config_cache.pop(cache_key, None) + return {} + with _cache_lock: + cached = _config_cache.get(cache_key) + if cached is not None and cached[0] == st.st_mtime_ns and cached[1] == st.st_size: + return cached[2] + try: + from hermes_cli.config import load_config_readonly + + cfg = load_config_readonly() or {} + except Exception: # noqa: BLE001 + return {} + normalized = cfg if isinstance(cfg, dict) else {} + with _cache_lock: + if len(_config_cache) >= _MAX_CACHE_ENTRIES: + _config_cache.clear() + _config_cache[cache_key] = (st.st_mtime_ns, st.st_size, normalized) + return normalized + + +def load_plugin_settings(plugin_ids: Sequence[str] = ("gemini-api", "gemini-image")) -> Dict[str, Any]: + """Read ``plugins.entries..settings`` (or legacy ``config``) from ``config.yaml``.""" + cfg = _read_cached_config() + entries = ((cfg.get("plugins") or {}).get("entries")) if isinstance(cfg, dict) else None + if not isinstance(entries, dict): + return {} + for pid in plugin_ids: + entry = entries.get(pid) + if not isinstance(entry, dict): + continue + for key in ("settings", "config"): + block = entry.get(key) + if isinstance(block, dict) and block: + return dict(block) + return {} + + +def _is_executable_file(path: Path) -> bool: + try: + return path.is_file() and os.access(path, os.X_OK) + except OSError: + return False + + +def _binary_filename() -> str: + return "gemini-api.exe" if sys.platform.lower() == "win32" else "gemini-api" + + +def resolve_cli_binary(cli_path: Optional[str] = None) -> Optional[str]: + """Locate an executable ``gemini-api`` binary without downloading anything. + + Order: explicit *cli_path* → ``plugins.entries.gemini-api.settings.cli_path`` → + ``$HERMES_HOME/bin/gemini-api`` → ``PATH`` → common user Go / local bin directories. + """ + settings = load_plugin_settings() if cli_path is None else {} + configured = str((cli_path if cli_path is not None else settings.get("cli_path")) or "").strip() + if configured: + candidate = Path(os.path.expanduser(configured)) + return str(candidate) if _is_executable_file(candidate) else None + + hermes_home = get_hermes_home() + path_env = os.environ.get("PATH", "") + binary_name = _binary_filename() + cache_key = (str(hermes_home), path_env, binary_name) + now = time.monotonic() + with _cache_lock: + cached = _binary_cache.get(cache_key) + if cached is not None and (now - cached[0]) < _CLI_CACHE_TTL_SECONDS: + if cached[1] is None or _is_executable_file(Path(cached[1])): + return cached[1] + + resolved: Optional[str] = None + hermes_bin = hermes_home / "bin" / binary_name + if _is_executable_file(hermes_bin): + resolved = str(hermes_bin) + else: + found_on_path = shutil.which("gemini-api") + if found_on_path: + resolved = found_on_path + else: + home = Path.home() + for fallback in ( + home / ".local" / "bin" / binary_name, + home / "go" / "bin" / binary_name, + Path("/usr/local/bin") / binary_name, + ): + if _is_executable_file(fallback): + resolved = str(fallback) + break + + with _cache_lock: + if len(_binary_cache) >= _MAX_CACHE_ENTRIES: + _binary_cache.clear() + _binary_cache[cache_key] = (now, resolved) + return resolved + + +def _platform_release_asset(version: str = PINNED_CLI_VERSION) -> Tuple[str, str]: + """Return ``(archive_filename, binary_name)`` matching GoReleaser assets on GitHub Releases.""" + del version # GitHub release assets omit version from filename (e.g. gemini-api_Linux_x86_64.tar.gz) + sys_name = sys.platform.lower() + if sys_name.startswith("linux"): + os_slug, ext, binary_name = "Linux", "tar.gz", "gemini-api" + elif sys_name == "darwin": + os_slug, ext, binary_name = "Darwin", "tar.gz", "gemini-api" + elif sys_name == "win32": + os_slug, ext, binary_name = "Windows", "zip", "gemini-api.exe" + else: + raise ValueError(f"Unsupported OS for gemini-api release archive: {sys.platform}") + + machine = platform.machine().lower() + if machine in ("x86_64", "amd64"): + arch_slug = "x86_64" + elif machine in ("aarch64", "arm64"): + arch_slug = "arm64" + else: + raise ValueError(f"Unsupported CPU architecture for gemini-api release archive: {machine}") + + return f"gemini-api_{os_slug}_{arch_slug}.{ext}", binary_name + + +def _expected_sha256_from_checksums(checksums_text: str, asset_name: str) -> str: + for raw_line in checksums_text.splitlines(): + parts = raw_line.strip().split() + if len(parts) >= 2 and parts[1].lstrip("*") == asset_name: + digest = parts[0].strip().lower() + if len(digest) == 64 and all(c in "0123456789abcdef" for c in digest): + return digest + raise ValueError(f"Asset {asset_name!r} not found in release checksums.txt") + + +def _read_bounded_archive(client: Any, archive_url: str, max_bytes: Optional[int] = None) -> bytes: + """Download *archive_url* while enforcing a hard streaming byte ceiling.""" + limit = _MAX_ARCHIVE_BYTES if max_bytes is None else max_bytes + stream_fn = getattr(client, "stream", None) + if callable(stream_fn): + chunks: List[bytes] = [] + total = 0 + with stream_fn("GET", archive_url) as resp: + resp.raise_for_status() + for chunk in resp.iter_bytes(): + total += len(chunk) + if total > limit: + raise ValueError(f"Release download exceeded {limit} byte safety limit") + chunks.append(chunk) + return b"".join(chunks) + + resp = client.get(archive_url) + resp.raise_for_status() + raw_bytes = resp.content + if len(raw_bytes) > limit: + raise ValueError(f"Release download exceeded {limit} byte safety limit") + return raw_bytes + + +def _extract_binary_from_archive(archive_bytes: bytes, asset_name: str, binary_name: str) -> bytes: + """Extract *binary_name* from a ``.tar.gz`` or ``.zip`` release archive with size caps.""" + if asset_name.endswith(".zip"): + with zipfile.ZipFile(io.BytesIO(archive_bytes)) as zf: + info = next( + (i for i in zf.infolist() if not i.is_dir() and Path(i.filename).name == binary_name), + None, + ) + if info is None: + raise ValueError(f"Binary {binary_name!r} not found in archive {asset_name}") + if info.file_size > _MAX_BINARY_BYTES: + raise ValueError( + f"Extracted {binary_name!r} exceeds {_MAX_BINARY_BYTES // (1024 * 1024)} MiB limit" + ) + with zf.open(info, "r") as extracted: + payload = extracted.read(_MAX_BINARY_BYTES + 1) + else: + with tarfile.open(fileobj=io.BytesIO(archive_bytes), mode="r:gz") as tf: + member = next( + (m for m in tf.getmembers() if m.isfile() and Path(m.name).name == binary_name), + None, + ) + if member is None: + raise ValueError(f"Binary {binary_name!r} not found in archive {asset_name}") + if member.size > _MAX_BINARY_BYTES: + raise ValueError( + f"Extracted {binary_name!r} exceeds {_MAX_BINARY_BYTES // (1024 * 1024)} MiB limit" + ) + extracted = tf.extractfile(member) + if extracted is None: + raise ValueError(f"Could not extract {binary_name!r} from archive {asset_name}") + payload = extracted.read(_MAX_BINARY_BYTES + 1) + + if len(payload) > _MAX_BINARY_BYTES: + raise ValueError(f"Extracted {binary_name!r} exceeds {_MAX_BINARY_BYTES // (1024 * 1024)} MiB limit") + if not payload: + raise ValueError(f"Extracted {binary_name!r} binary was empty") + return payload + + +def install_cli_binary( + *, + version: str = PINNED_CLI_VERSION, + target_dir: Optional[Path] = None, + expected_sha256: Optional[str] = None, +) -> Path: + """Download and SHA-256-verify a pinned ``gemini-api`` release into ``$HERMES_HOME/bin``. + + For the pinned release (:data:`PINNED_CLI_VERSION`), verification uses the hardcoded digest in + :data:`PINNED_CLI_SHA256` rather than trusting a remote ``checksums.txt``. Never called + automatically unless ``plugins.entries.gemini-api.settings.auto_install_cli`` is explicitly + set to ``true`` by the user (off by default per Hermes catalog policy). + """ + from tools.url_safety import create_ssrf_safe_client + + ver = version.lstrip("v") + asset_name, binary_name = _platform_release_asset(ver) + base = f"https://github.com/google-gemini/gemini-api-cli/releases/download/v{ver}" + checksums_url = f"{base}/checksums.txt" + archive_url = f"{base}/{asset_name}" + + pinned_sha = ( + expected_sha256.strip().lower() + if isinstance(expected_sha256, str) and expected_sha256.strip() + else (PINNED_CLI_SHA256.get(asset_name) if ver == PINNED_CLI_VERSION else None) + ) + + with _install_lock: + with create_ssrf_safe_client(timeout=60.0, follow_redirects=True) as client: + if pinned_sha: + expected_sha = pinned_sha + else: + cs_bytes = _read_bounded_archive(client, checksums_url, max_bytes=_MAX_CHECKSUMS_BYTES) + expected_sha = _expected_sha256_from_checksums( + cs_bytes.decode("utf-8", errors="replace"), asset_name + ) + archive_bytes = _read_bounded_archive(client, archive_url) + + actual_sha = hashlib.sha256(archive_bytes).hexdigest().lower() + if actual_sha != expected_sha: + raise ValueError( + f"SHA-256 mismatch for {asset_name}: expected {expected_sha}, got {actual_sha}" + ) + + payload = _extract_binary_from_archive(archive_bytes, asset_name, binary_name) + + dest_dir = Path(target_dir) if target_dir is not None else (get_hermes_home() / "bin") + dest_dir.mkdir(parents=True, exist_ok=True) + dest_path = dest_dir / binary_name + + tmp_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile( + dir=dest_dir, prefix=f".{binary_name}.tmp.", delete=False + ) as tmp_file: + tmp_path = Path(tmp_file.name) + tmp_file.write(payload) + if os.name != "nt": + tmp_path.chmod(0o755) + tmp_path.replace(dest_path) + tmp_path = None + finally: + if tmp_path is not None: + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + + clear_cli_cache() + return dest_path + + +def validate_base_url(base_url: str) -> str: + """Validate and normalize a Gemini API base URL. + + Refuses cleartext ``http://`` URLs (except loopback hosts for local testing), leading dashes, + embedded credentials, query parameters, and fragments so ``GEMINI_API_KEY`` is never sent over + unencrypted links or flag-injected values. + """ + cleaned = (base_url or "").strip().rstrip("/") + if not cleaned: + return "" + if cleaned.startswith("-"): + raise ValueError(f"Invalid Gemini base_url {base_url!r}: must be an https:// URL") + + parsed = urlsplit(cleaned) + scheme = parsed.scheme.lower() + host = (parsed.hostname or "").lower() + if not scheme or not host or host.startswith("-"): + raise ValueError(f"Invalid Gemini base_url {base_url!r}: must include scheme and hostname") + if parsed.username or parsed.password or parsed.query or parsed.fragment: + raise ValueError("Invalid Gemini base_url: embedded credentials, query parameters, and fragments are not allowed") + if scheme != "https" and not (scheme == "http" and host in _LOOPBACK_HOSTS): + raise ValueError( + f"Refusing insecure Gemini base_url {base_url!r}: use https:// (http:// is allowed only for localhost)" + ) + return cleaned + + +def server_flags_from_base_url(base_url: str) -> List[str]: + """Translate validated ``https://host/v1beta`` endpoint URLs into ``gemini-api`` flags.""" + cleaned = validate_base_url(base_url) + if not cleaned: + return [] + + api_version: Optional[str] = None + for suffix in _API_VERSION_SUFFIXES: + if cleaned.endswith(suffix): + cleaned = cleaned[: -len(suffix)].rstrip("/") + if suffix != "/v1beta": + api_version = suffix.lstrip("/") + break + flags: List[str] = [] + if cleaned and cleaned != _DEFAULT_SERVER_URL: + flags.extend(["--server-url", cleaned]) + if api_version: + flags.extend(["--api-version", api_version]) + return flags + + +def _build_child_env(binary_path: str, api_key: str) -> Dict[str, str]: + """Construct a scrubbed, allowlisted environment for ``gemini-api`` subprocesses. + + Avoids inheriting unrelated process secrets (OpenAI, Anthropic, GitHub, etc.), Hermes profile + state, or conflicting ``GEMINI_*`` / ``GOOGLE_API_KEY`` variables (such as ``GEMINI_ACCESS_TOKEN``, + which takes precedence over ``GEMINI_API_KEY`` in ``gemini-api``). + """ + env: Dict[str, str] = {} + for key, val in os.environ.items(): + if key in _SAFE_CHILD_ENV_KEYS or key.startswith("LC_"): + env[key] = val + env["GEMINI_API_KEY"] = api_key + env["NO_COLOR"] = "1" + bin_parent = str(Path(binary_path).parent) + current_path = env.get("PATH", "") + if bin_parent and bin_parent not in current_path.split(os.pathsep): + env["PATH"] = f"{bin_parent}{os.pathsep}{current_path}" if current_path else bin_parent + return env + + +def _exit_code_to_error_type(exit_code: int) -> str: + if exit_code == 3: + return "auth_required" + if exit_code == 2: + return "invalid_argument" + return "api_error" + + +def _parse_cli_error(stderr: str, stdout: str, exit_code: int) -> Tuple[str, List[str]]: + """Extract ``(message, hints)`` from ``gemini-api`` JSON stderr or fallback text.""" + for stream in (stderr, stdout): + text = (stream or "").strip() + if not text: + continue + for candidate in (text, text.splitlines()[-1]): + try: + parsed = json.loads(candidate) + except (ValueError, TypeError): + continue + if isinstance(parsed, dict) and parsed.get("error"): + raw_err = parsed["error"] + msg = str(raw_err.get("message") if isinstance(raw_err, dict) else raw_err) + hints_raw = parsed.get("hints") + hints = [str(h) for h in hints_raw if isinstance(h, str)] if isinstance(hints_raw, list) else [] + if any("files upload" in h for h in hints): + hints.append("Call gemini_files_upload first and pass the returned files/ handle.") + return msg, hints + fallback = (stderr or stdout or f"gemini-api exited with code {exit_code}").strip() + return fallback, [] + + +def _usage_namespace(usage_obj: Dict[str, Any]) -> Optional[SimpleNamespace]: + """Normalize ``gemini-api`` Interactions API, porcelain, or camelCase usage dicts for accounting.""" + def _num(*keys: str) -> int: + for k in keys: + val = usage_obj.get(k) + if isinstance(val, (int, float)) and not isinstance(val, bool): + return int(val) + return 0 + + prompt = _num("total_input_tokens", "input_tokens", "prompt_tokens", "promptTokenCount") + output = _num("total_output_tokens", "output_tokens", "completion_tokens", "candidatesTokenCount") + thoughts = _num( + "total_thought_tokens", "thoughts_tokens", "thought_tokens", "reasoning_tokens", "thoughtsTokenCount" + ) + total = _num("total_tokens", "totalTokenCount") or (prompt + output + thoughts) + cached = _num("total_cached_tokens", "cached_tokens", "cached_input_tokens", "cachedContentTokenCount") + if not (prompt or output or thoughts or total): + return None + return SimpleNamespace( + prompt_tokens=prompt, + completion_tokens=output + thoughts, + total_tokens=total, + prompt_tokens_details=SimpleNamespace(cached_tokens=cached), + ) + + +def record_gemini_token_usage(usage_ns: Any, *, model: str, base_url: str) -> None: + """Best-effort bridge to Hermes's session token accounting (sole pending public-API seam).""" + if usage_ns is None: + return + try: + from plugins.image_gen._common import record_token_usage + except ImportError: + return + record_token_usage(usage_ns, model=model, provider="gemini", base_url=base_url) + + +def maybe_record_cli_usage(data: Any, *, default_model: str, base_url: str) -> None: + """Record ``usage`` / ``usageMetadata`` from a ``gemini-api`` JSON payload when present.""" + if not isinstance(data, dict): + return + + top_model = str(data.get("model") or default_model or "gemini").strip() + usage_entries: List[Tuple[str, Dict[str, Any]]] = [] + for key in ("usage", "usageMetadata", "usage_metadata"): + if isinstance(data.get(key), dict): + usage_entries.append((top_model, data[key])) + if isinstance(data.get("results"), list): + for item in data["results"]: + if isinstance(item, dict) and isinstance(item.get("usage"), dict): + item_model = str(item.get("model") or top_model).strip() + usage_entries.append((item_model, item["usage"])) + for entry_model, raw_usage in usage_entries: + ns = _usage_namespace(raw_usage) + if ns is not None: + record_gemini_token_usage(ns, model=entry_model, base_url=base_url) + + +class GeminiCLIRunner: + """Executes ``gemini-api`` subcommands with structured JSON output and safety checks.""" + + def __init__( + self, + *, + endpoint_resolver: Callable[[], Tuple[str, str]], + user_agent: str, + cli_path: Optional[str] = None, + ) -> None: + self._resolve_endpoint = endpoint_resolver + self._user_agent = user_agent + self._cli_path = cli_path + + def is_available(self) -> bool: + """Fast availability probe shared across ``GeminiVideoGenProvider`` and all 6 CLI tools.""" + if not self._resolve_endpoint()[1]: + return False + if resolve_cli_binary(self._cli_path): + return True + return load_plugin_settings().get("auto_install_cli") is True + + def ensure_binary(self) -> Tuple[Optional[str], Optional[str]]: + """Return ``(binary_path, error_message)``; auto-installs only when opted in via settings.""" + binary = resolve_cli_binary(self._cli_path) + if binary: + return binary, None + settings = load_plugin_settings() + if settings.get("auto_install_cli") is True: + try: + installed = install_cli_binary() + return str(installed), None + except Exception as exc: # noqa: BLE001 + return None, f"Automatic gemini-api CLI install failed ({exc}). {CLI_INSTALL_HINT}" + return None, CLI_INSTALL_HINT + + def run( + self, + args: Sequence[str], + *, + positional_args: Sequence[str] = (), + timeout: Optional[int] = None, + default_timeout: int = DEFAULT_CLI_TIMEOUT, + default_model: str = "", + cwd: Optional[Path] = None, + ) -> CLIResult: + """Run ``gemini-api --no-interactive -o json -- `` and parse JSON.""" + base_url, api_key = self._resolve_endpoint() + if not api_key: + return CLIResult( + ok=False, + exit_code=3, + error="GEMINI_API_KEY is not set. Configure GEMINI_API_KEY in ~/.hermes/.env.", + error_type="auth_required", + ) + + try: + server_flags = server_flags_from_base_url(base_url) + except ValueError as exc: + return CLIResult( + ok=False, + exit_code=2, + error=str(exc), + error_type="invalid_argument", + ) + + binary, bin_err = self.ensure_binary() + if not binary: + return CLIResult( + ok=False, + exit_code=127, + error=bin_err or CLI_INSTALL_HINT, + error_type="missing_dependency", + ) + + settings = load_plugin_settings() + effective_timeout = timeout + if effective_timeout is None: + cfg_timeout = settings.get("timeout_seconds") + effective_timeout = ( + int(cfg_timeout) + if isinstance(cfg_timeout, int) and not isinstance(cfg_timeout, bool) and cfg_timeout > 0 + else default_timeout + ) + + cmd: List[str] = [ + binary, + *args, + "--no-interactive", + "-o", + "json", + "--header", + f"User-Agent: {self._user_agent}", + *server_flags, + ] + if positional_args: + cmd.append("--") + cmd.extend(positional_args) + + env = _build_child_env(binary, api_key) + try: + proc = subprocess.run( + cmd, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=effective_timeout, + cwd=str(cwd) if cwd is not None else None, + env=env, + stdin=subprocess.DEVNULL, + ) + except subprocess.TimeoutExpired: + return CLIResult( + ok=False, + exit_code=124, + error=f"gemini-api timed out after {effective_timeout}s", + error_type="timeout", + ) + except OSError as exc: + if isinstance(exc, (FileNotFoundError, PermissionError)) or exc.errno in ( + errno.ENOENT, + errno.EACCES, + errno.ENOEXEC, + ): + return CLIResult( + ok=False, + exit_code=127, + error=f"Failed to execute gemini-api ({exc}). {CLI_INSTALL_HINT}", + error_type="missing_dependency", + ) + return CLIResult( + ok=False, + exit_code=1, + error=f"Failed to execute gemini-api ({exc}).", + error_type="execution_error", + ) + + stdout = (proc.stdout or "").strip() + stderr = (proc.stderr or "").strip() + if proc.returncode != 0: + msg, hints = _parse_cli_error(stderr, stdout, proc.returncode) + if hints: + msg = f"{msg} (Hints: {'; '.join(hints)})" + return CLIResult( + ok=False, + exit_code=proc.returncode, + stdout=stdout, + stderr=stderr, + error=msg, + error_type=_exit_code_to_error_type(proc.returncode), + hints=hints, + ) + + parsed: Any = None + if stdout: + try: + parsed = json.loads(stdout) + except ValueError: + parsed = {"raw_output": stdout} + maybe_record_cli_usage(parsed, default_model=default_model, base_url=base_url) + return CLIResult(ok=True, exit_code=0, data=parsed, stdout=stdout, stderr=stderr) + + def _validate_local_file(self, raw_path: str) -> Tuple[Optional[Path], Optional[CLIResult]]: + """Check *raw_path* (and its symlink-resolved target) against ``raise_if_read_blocked``.""" + from agent.file_safety import raise_if_read_blocked + + cleaned = (raw_path or "").strip() + if not cleaned: + return None, CLIResult(ok=False, exit_code=2, error="File path is required.", error_type="invalid_argument") + try: + # Check raw string first (catches Windows NT-namespace prefixes before normalization), + # then resolve symlinks so a symlink pointing to a blocked credential file cannot bypass it. + raise_if_read_blocked(cleaned) + path = Path(os.path.expanduser(cleaned)).resolve() + raise_if_read_blocked(str(path)) + except Exception as exc: # noqa: BLE001 + return None, CLIResult(ok=False, exit_code=2, error=str(exc), error_type="invalid_argument") + + if not path.is_file(): + return None, CLIResult( + ok=False, + exit_code=2, + error=f"Input path is not a regular file or does not exist: {cleaned}", + error_type="invalid_argument", + ) + return path, None + + def upload_file( + self, + local_path: str, + *, + display_name: Optional[str] = None, + mime_type: Optional[str] = None, + wait: bool = True, + timeout: Optional[int] = None, + default_timeout: int = 300, + ) -> CLIResult: + """Validate *local_path* against ``raise_if_read_blocked`` and run ``files upload``.""" + path, err = self._validate_local_file(local_path) + if err is not None or path is None: + return err or CLIResult(ok=False, exit_code=2, error="Invalid file path.", error_type="invalid_argument") + + size = path.stat().st_size + if size <= 0: + return CLIResult( + ok=False, exit_code=2, error=f"Input file is empty: {local_path}", error_type="invalid_argument" + ) + if size > CLI_MAX_UPLOAD_BYTES: + return CLIResult( + ok=False, + exit_code=2, + error=f"Input file exceeds the 2GB Gemini Files API limit: {local_path}", + error_type="invalid_argument", + ) + + args: List[str] = ["files", "upload"] + if wait: + args.append("--wait") + if display_name and display_name.strip(): + dn = display_name.strip() + if dn.startswith("-"): + return CLIResult( + ok=False, + exit_code=2, + error="display_name cannot start with a dash.", + error_type="invalid_argument", + ) + args.extend(["--display-name", dn]) + if mime_type and mime_type.strip(): + mt = mime_type.strip() + if mt.startswith("-"): + return CLIResult( + ok=False, + exit_code=2, + error="mime_type cannot start with a dash.", + error_type="invalid_argument", + ) + args.extend(["--mime-type", mt]) + return self.run(args, positional_args=[str(path)], timeout=timeout, default_timeout=default_timeout) + + def prepare_media_input( + self, + raw_input: str, + *, + allow_youtube: bool = True, + mime_type: Optional[str] = None, + inline_budget_used: int = 0, + enforce_cumulative: bool = False, + ) -> Tuple[Optional[str], Optional[CLIResult], int]: + """Validate a local path, ``files/`` handle, or YouTube URL; seamlessly auto-upload >14 MiB binary media. + + Returns ``(resolved_ref, error_result, inline_cost_added)``. Plain-text files and unsupported container + extensions stay local so ``gemini-api`` runs its own fast local validation without wasted uploads. + """ + ref = (raw_input or "").strip() + if not ref: + return ( + None, + CLIResult( + ok=False, exit_code=2, error="Media input reference cannot be empty.", error_type="invalid_argument" + ), + 0, + ) + if ref.startswith("files/"): + file_id = ref[len("files/"):] + if not _FILE_ID_RE.fullmatch(file_id): + return ( + None, + CLIResult( + ok=False, + exit_code=2, + error=f"Invalid Gemini Files API handle {ref!r}: expected 'files/'.", + error_type="invalid_argument", + ), + 0, + ) + return ref, None, 0 + + lower = ref.lower() + if lower.startswith(("http://", "https://")): + parsed = urlsplit(ref) + host = (parsed.hostname or "").lower() + if allow_youtube and _YOUTUBE_HOST_RE.fullmatch(host): + return ref, None, 0 + return ( + None, + CLIResult( + ok=False, + exit_code=2, + error=( + f"Unsupported remote URL {ref!r}: pass a local file path, a 'files/' handle, " + + ("or a YouTube URL." if allow_youtube else "not a remote URL.") + ), + error_type="invalid_argument", + ), + 0, + ) + + path, err = self._validate_local_file(ref) + if err is not None or path is None: + return None, err, 0 + + size = path.stat().st_size + ext = path.suffix.lower() + mime_clean = (mime_type or "").strip().lower() + is_text_override = mime_clean.startswith("text/") and mime_clean != "text/csv" + can_auto_upload = not is_text_override and (bool(mime_clean) or ext not in _NON_UPLOADABLE_ANALYZE_EXTS) + + encoded_cost = ((size + 2) // 3) * 4 if can_auto_upload else size + exceeds_single = size > CLI_INLINE_LIMIT_BYTES + exceeds_cumulative = enforce_cumulative and (inline_budget_used + encoded_cost) > CLI_CUMULATIVE_INLINE_BYTES + + if can_auto_upload and (exceeds_single or exceeds_cumulative): + uploaded = self.upload_file(str(path), mime_type=mime_type, wait=True) + if not uploaded.ok: + return None, uploaded, 0 + file_name = (uploaded.data or {}).get("name") if isinstance(uploaded.data, dict) else None + if not isinstance(file_name, str) or not file_name.startswith("files/"): + return ( + None, + CLIResult( + ok=False, + exit_code=1, + error="gemini-api files upload succeeded but returned no files/ handle", + error_type="invalid_response", + ), + 0, + ) + return file_name, None, 0 + + return str(path), None, encoded_cost + + def prepare_image_input( + self, + ref: str, + *, + image_loader: Callable[[str], Tuple[bytes, str]], + local_mime_sniffer: Optional[Callable[[str], str]] = None, + mime_to_suffix: Dict[str, str], + tmp_files: List[Path], + tmp_prefix: str = "hermes-image-ref-", + inline_budget_used: int = 0, + enforce_cumulative: bool = False, + ) -> Tuple[Optional[str], Optional[CLIResult], int]: + """Resolve a ``files/``, remote URL, data URI, or local image path for ``gemini-api -i``. + + Remote URLs and data URIs are written to ``0o600`` temporary files appended to *tmp_files* + for caller cleanup. Local image paths use *local_mime_sniffer* (when provided) so only the + leading header bytes are read instead of buffering up to 25 MB in memory. + """ + cleaned = (ref or "").strip() + if cleaned.startswith("files/"): + return self.prepare_media_input( + cleaned, + allow_youtube=False, + inline_budget_used=inline_budget_used, + enforce_cumulative=enforce_cumulative, + ) + if cleaned.lower().startswith(("http://", "https://", "data:")): + try: + raw_bytes, mime = image_loader(cleaned) + except Exception as exc: # noqa: BLE001 + return ( + None, + CLIResult(ok=False, exit_code=2, error=str(exc), error_type="invalid_argument"), + 0, + ) + suffix = mime_to_suffix.get(mime, ".png") + with tempfile.NamedTemporaryFile(prefix=tmp_prefix, suffix=suffix, delete=False) as tmp_file: + tmp_path = Path(tmp_file.name) + tmp_file.write(raw_bytes) + if os.name != "nt": + tmp_path.chmod(0o600) + tmp_files.append(tmp_path) + return self.prepare_media_input( + str(tmp_path), + allow_youtube=False, + mime_type=mime, + inline_budget_used=inline_budget_used, + enforce_cumulative=enforce_cumulative, + ) + try: + mime = local_mime_sniffer(cleaned) if local_mime_sniffer is not None else image_loader(cleaned)[1] + except Exception as exc: # noqa: BLE001 + return ( + None, + CLIResult(ok=False, exit_code=2, error=str(exc), error_type="invalid_argument"), + 0, + ) + return self.prepare_media_input( + cleaned, + allow_youtube=False, + mime_type=mime, + inline_budget_used=inline_budget_used, + enforce_cumulative=enforce_cumulative, + ) diff --git a/cli_tools.py b/cli_tools.py new file mode 100644 index 0000000..f1c07d4 --- /dev/null +++ b/cli_tools.py @@ -0,0 +1,1030 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Hermes provider and tool registrations backed by ``google-gemini/gemini-api-cli``. + +Registers: +- ``GeminiVideoGenProvider`` (``video_gen.provider = gemini``) via ``gemini-api video`` +- Six structured tools in the ``gemini_api`` toolset: + ``gemini_music``, ``gemini_tts``, ``gemini_analyze``, ``gemini_transcribe``, + ``gemini_deep_research``, and ``gemini_files_upload`` +- Bundled ``gemini-api-cli`` plugin skill (``SKILL.md``) for ad-hoc terminal workflows +""" + +from __future__ import annotations + +import importlib.util +import json +import logging +import os +import sys +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Tuple + +from agent.video_gen_provider import ( + DEFAULT_ASPECT_RATIO as DEFAULT_VIDEO_ASPECT_RATIO, + DEFAULT_RESOLUTION as DEFAULT_VIDEO_RESOLUTION, + VideoGenProvider, + error_response as video_error_response, + success_response as video_success_response, +) +from hermes_constants import get_hermes_home + +logger = logging.getLogger(__name__) + + +def tool_error(message: str, **extra: Any) -> str: + return json.dumps({"error": str(message)[:2048], **extra}, ensure_ascii=False) + + +def tool_result(data: Dict[str, Any]) -> str: + return json.dumps(data, ensure_ascii=False) + + +def _load_cli_runner_module(): + pkg = __package__ or "" + if pkg and pkg in sys.modules: + parent = pkg.rpartition(".")[0] + if not parent or parent in sys.modules: + from . import cli_runner as _mod + + return _mod + mod_name = f"{pkg}.cli_runner" if pkg else "gemini_plugin_cli_runner" + existing = sys.modules.get(mod_name) + if existing is not None: + return existing + runner_path = Path(__file__).resolve().parent / "cli_runner.py" + spec = importlib.util.spec_from_file_location(mod_name, runner_path) + if spec is None or spec.loader is None: + raise ImportError(f"Unable to load cli_runner from {runner_path}") + mod = importlib.util.module_from_spec(spec) + sys.modules[mod_name] = mod + spec.loader.exec_module(mod) + return mod + + +_cli_runner = _load_cli_runner_module() +CLIResult = _cli_runner.CLIResult +CLI_INSTALL_HINT = _cli_runner.CLI_INSTALL_HINT +DEFAULT_CLI_TIMEOUT = _cli_runner.DEFAULT_CLI_TIMEOUT +DEFAULT_RESEARCH_TIMEOUT = _cli_runner.DEFAULT_RESEARCH_TIMEOUT +GeminiCLIRunner = _cli_runner.GeminiCLIRunner +_read_cached_config = _cli_runner._read_cached_config + +# Documented CLI default models for gemini-api v0.5.0 (used for Hermes picker metadata and +# accounting fallback when `-m` is omitted so `gemini-api` owns its built-in defaults across upgrades). +DEFAULT_VIDEO_MODEL = "gemini-omni-1.2-flash" +DEFAULT_MUSIC_MODEL = "lyria-3.5" +DEFAULT_TTS_MODEL = "gemini-3.8-flash-tts" +DEFAULT_ANALYZE_MODEL = "gemini-4-hydrogen" +DEFAULT_TRANSCRIBE_MODEL = "gemini-3.5-transcribe" +DEFAULT_RESEARCH_AGENT = "deep-research-preview-04-2026" + +_IMAGE_MIME_TO_SUFFIX = { + "image/png": ".png", + "image/jpeg": ".jpg", + "image/jpg": ".jpg", + "image/webp": ".webp", + "image/gif": ".gif", +} + +VIDEO_MODELS: Dict[str, Dict[str, Any]] = { + "gemini-omni-1.2-flash": { + "display": "Gemini Omni 1.2 Flash (Video)", + "speed": "~30-120s", + "strengths": "Default conversational text-to-video and image-to-video via Gemini Interactions API", + "price": "varies", + "modalities": ["text", "image"], + }, + "gemini-omni-1.1-flash": { + "display": "Gemini Omni 1.1 Flash (Video)", + "speed": "~30-120s", + "strengths": "Previous generation text-to-video and image-to-video via Gemini Interactions API", + "price": "varies", + "modalities": ["text", "image"], + }, + "gemini-omni-flash-preview": { + "display": "Gemini Omni Flash Preview (Video)", + "speed": "~30-120s", + "strengths": "Preview Gemini Omni video generation model via Interactions API", + "price": "varies", + "modalities": ["text", "image"], + }, +} + +PROVIDED_TOOL_NAMES: Tuple[str, ...] = ( + "gemini_music", + "gemini_tts", + "gemini_analyze", + "gemini_transcribe", + "gemini_deep_research", + "gemini_files_upload", +) + +_TRANSCRIBE_FORMATS = {"md", "text", "json", "srt"} +_RESEARCH_ACTIONS = {"run", "status", "cancel"} + + +def _strip_google_prefix(value: Optional[str]) -> Optional[str]: + if not isinstance(value, str) or not value.strip(): + return None + raw = value.strip() + cleaned = raw.split("/", 1)[1].strip() if raw.lower().startswith("google/") else raw + return None if (not cleaned or cleaned.startswith("-")) else cleaned + + +def _load_video_gen_gemini_config() -> Dict[str, Any]: + cfg = _read_cached_config() + video_cfg = cfg.get("video_gen") if isinstance(cfg, dict) else None + gemini_cfg = video_cfg.get("gemini") if isinstance(video_cfg, dict) else None + return dict(gemini_cfg) if isinstance(gemini_cfg, dict) else {} + + +def _resolve_explicit_video_model(caller_model: Optional[str] = None) -> Optional[str]: + """Return an explicit Gemini video model override, or ``None`` to let ``gemini-api`` use its default. + + Foreign top-level ``video_gen.model`` IDs (e.g. ``grok-imagine-video``) are ignored so switching + providers never sends a non-Gemini model ID to Google AI Studio. + """ + cleaned = _strip_google_prefix(caller_model) + if cleaned and (cleaned in VIDEO_MODELS or cleaned.startswith(("gemini-", "veo-"))): + return cleaned + cfg_model = _strip_google_prefix(_load_video_gen_gemini_config().get("model")) + return cfg_model or None + + +def _cache_subdir(*parts: str) -> Path: + target = get_hermes_home().joinpath("cache", *parts) + target.mkdir(parents=True, exist_ok=True) + return target + + +def _cli_failure_to_tool_error(res: CLIResult) -> str: + extra: Dict[str, Any] = {"error_type": res.error_type or "api_error", "exit_code": res.exit_code} + if res.hints: + extra["hints"] = res.hints + return tool_error(res.error or "gemini-api command failed", **extra) + + +def _extract_interaction_text(payload: Any) -> str: + """Pull readable model output text from an Interactions API response dict, ignoring user inputs and thoughts.""" + if not isinstance(payload, dict): + return "" + direct = payload.get("output_text") + if isinstance(direct, str) and direct.strip(): + return direct.strip() + chunks: List[str] = [] + for collection_key in ("outputs", "steps"): + items = payload.get(collection_key) + if not isinstance(items, list): + continue + for item in items: + if not isinstance(item, dict): + continue + step_type = str(item.get("type") or "").strip().lower() + step_role = str(item.get("role") or "").strip().lower() + if step_type in ("user_input", "thought") or step_role == "user": + continue + if isinstance(item.get("text"), str) and item["text"].strip(): + chunks.append(item["text"].strip()) + content = item.get("content") + if isinstance(content, list): + for block in content: + if isinstance(block, dict) and block.get("type") != "thought": + txt = block.get("text") + if isinstance(txt, str) and txt.strip(): + chunks.append(txt.strip()) + return "\n\n".join(chunks) + + +def _extract_interaction_errors(payload: Any) -> List[str]: + """Extract human-readable error messages from an Interactions API payload's ``errors`` field.""" + if not isinstance(payload, dict): + return [] + raw_errors = payload.get("errors") + if not isinstance(raw_errors, list): + return [] + messages: List[str] = [] + for entry in raw_errors: + if isinstance(entry, dict): + msg = str(entry.get("message") or entry.get("code") or "").strip() + if msg: + messages.append(msg) + elif isinstance(entry, str) and entry.strip(): + messages.append(entry.strip()) + return messages + + +class GeminiVideoGenProvider(VideoGenProvider): + """Hermes ``VideoGenProvider`` backed by ``gemini-api video``.""" + + name = "gemini" + display_name = "Google AI Studio" + + def __init__( + self, + *, + runner: GeminiCLIRunner, + endpoint_resolver: Callable[[], Tuple[str, str]], + image_loader: Callable[[str], Tuple[bytes, str]], + local_mime_sniffer: Optional[Callable[[str], str]] = None, + ) -> None: + self._runner = runner + self._resolve_endpoint = endpoint_resolver + self._load_image_bytes = image_loader + self._local_mime_sniffer = local_mime_sniffer + + def is_available(self) -> bool: + return self._runner.is_available() + + def list_models(self) -> List[Dict[str, Any]]: + return [{"id": mid, **meta} for mid, meta in VIDEO_MODELS.items()] + + def default_model(self) -> Optional[str]: + return DEFAULT_VIDEO_MODEL + + def get_setup_schema(self) -> Dict[str, Any]: + return { + "name": "Google AI Studio (gemini-api CLI)", + "badge": "paid", + "tag": "Conversational Gemini video generation via gemini-api CLI and GEMINI_API_KEY", + "env_vars": [ + { + "key": "GEMINI_API_KEY", + "prompt": "Google AI Studio Gemini API key", + "url": "https://aistudio.google.com/apikey", + }, + ], + } + + def capabilities(self) -> Dict[str, Any]: + return { + "modalities": ["text", "image"], + "aspect_ratios": ["16:9", "9:16", "1:1", "4:3", "3:4"], + "resolutions": ["720p", "1080p"], + "max_duration": 10, + "min_duration": 4, + "supports_audio": True, + "supports_negative_prompt": False, + "supports_seed": False, + "supports_upscale": False, + "max_reference_images": 0, + } + + def generate( + self, + prompt: str, + *, + model: Optional[str] = None, + image_url: Optional[str] = None, + reference_image_urls: Optional[List[str]] = None, + duration: Optional[int] = None, + aspect_ratio: str = DEFAULT_VIDEO_ASPECT_RATIO, + resolution: str = DEFAULT_VIDEO_RESOLUTION, + negative_prompt: Optional[str] = None, + audio: Optional[bool] = None, + seed: Optional[int] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + del reference_image_urls, negative_prompt, audio, seed, kwargs + cleaned_prompt = (prompt or "").strip() + explicit_model = _resolve_explicit_video_model(model) + accounting_model = explicit_model or DEFAULT_VIDEO_MODEL + if not cleaned_prompt: + return video_error_response( + error="A non-empty video prompt is required.", + error_type="invalid_argument", + provider="gemini", + model=accounting_model, + prompt="", + aspect_ratio=aspect_ratio, + ) + + _, api_key = self._resolve_endpoint() + if not api_key: + return video_error_response( + error="GEMINI_API_KEY is not set. Configure GEMINI_API_KEY in ~/.hermes/.env.", + error_type="auth_required", + provider="gemini", + model=accounting_model, + prompt=cleaned_prompt, + aspect_ratio=aspect_ratio, + ) + + out_dir = _cache_subdir("videos") + modality = "image" if (image_url and image_url.strip()) else "text" + cli_args: List[str] = ["video", "--out", str(out_dir)] + if explicit_model: + cli_args.extend(["-m", explicit_model]) + cleaned_aspect = str(aspect_ratio or "").strip() + if cleaned_aspect and not cleaned_aspect.startswith("-"): + cli_args.extend(["--aspect-ratio", cleaned_aspect]) + cleaned_resolution = str(resolution or "").strip() + if cleaned_resolution and not cleaned_resolution.startswith("-"): + cli_args.extend(["--resolution", cleaned_resolution]) + + tmp_files: List[Path] = [] + try: + if modality == "image" and image_url: + valid_ref, ref_err, _ = self._runner.prepare_image_input( + image_url, + image_loader=self._load_image_bytes, + local_mime_sniffer=self._local_mime_sniffer, + mime_to_suffix=_IMAGE_MIME_TO_SUFFIX, + tmp_files=tmp_files, + tmp_prefix="hermes-video-ref-", + ) + if ref_err is not None or not valid_ref: + return video_error_response( + error=( + f"Could not load image_url for video generation: {ref_err.error}" + if ref_err is not None + else "Invalid image_url for video generation." + ), + error_type=(ref_err.error_type if ref_err is not None else "") or "invalid_argument", + provider="gemini", + model=accounting_model, + prompt=cleaned_prompt, + aspect_ratio=aspect_ratio, + ) + cli_args.extend(["-i", valid_ref]) + + res = self._runner.run( + cli_args, + positional_args=[cleaned_prompt], + default_timeout=DEFAULT_RESEARCH_TIMEOUT, + default_model=accounting_model, + ) + finally: + for tmp_image_path in tmp_files: + try: + tmp_image_path.unlink(missing_ok=True) + except OSError: + pass + if not res.ok: + return video_error_response( + error=res.error, + error_type=res.error_type or "provider_error", + provider="gemini", + model=accounting_model, + prompt=cleaned_prompt, + aspect_ratio=aspect_ratio, + ) + + payload = res.data if isinstance(res.data, dict) else {} + saved_path = str(payload.get("path") or "").strip() + if not saved_path or not Path(saved_path).is_file(): + return video_error_response( + error="gemini-api video completed without returning a valid output video file path.", + error_type="invalid_response", + provider="gemini", + model=accounting_model, + prompt=cleaned_prompt, + aspect_ratio=aspect_ratio, + ) + + reported_model = str(payload.get("model") or explicit_model or DEFAULT_VIDEO_MODEL).strip() + extra: Dict[str, Any] = {"api": "google-ai-studio"} + if payload.get("response_id"): + extra["response_id"] = payload["response_id"] + if payload.get("mime_type"): + extra["mime_type"] = payload["mime_type"] + return video_success_response( + video=saved_path, + model=reported_model, + prompt=cleaned_prompt, + modality=modality, + aspect_ratio=aspect_ratio, + duration=int(duration) if duration else 0, + provider="gemini", + extra=extra, + ) + + +# ── Tool JSON Schemas ──────────────────────────────────────────────────────── + +GEMINI_MUSIC_SCHEMA: Dict[str, Any] = { + "name": "gemini_music", + "description": ( + "Generate instrumental or vocal music tracks using Google AI Studio's Lyria model " + "via gemini-api CLI and save the audio file to the Hermes cache." + ), + "parameters": { + "type": "object", + "properties": { + "prompt": { + "type": "string", + "description": "Musical prompt describing genre, instruments, tempo, mood, or vocals.", + }, + "model": { + "type": "string", + "description": "Optional music model override (when omitted, gemini-api uses its built-in default).", + }, + }, + "required": ["prompt"], + }, +} + +GEMINI_TTS_SCHEMA: Dict[str, Any] = { + "name": "gemini_tts", + "description": ( + "Synthesize 24kHz WAV speech from text or a two-speaker script via gemini-api CLI. " + "Supports single-speaker voices (e.g. Kore, Puck, Charon, Aoede) and " + "two-speaker dialogues (e.g. 'Host=Kore,Guest=Puck')." + ), + "parameters": { + "type": "object", + "properties": { + "text": { + "type": "string", + "description": "Text to speak. For multi-speaker mode, prefix lines with speaker names (e.g. 'Host: Hello!').", + }, + "voice": { + "type": "string", + "description": "Prebuilt voice name for single-speaker synthesis (default: Kore).", + }, + "multi_speaker": { + "type": "string", + "description": "Optional two-speaker voice map 'Speaker1=Voice1,Speaker2=Voice2' (mutually exclusive with voice).", + }, + "language": { + "type": "string", + "description": "Optional BCP-47 language hint (e.g. en-US, ja-JP, es-US).", + }, + "model": { + "type": "string", + "description": "Optional TTS model override (when omitted, gemini-api uses its built-in default).", + }, + }, + "required": ["text"], + }, +} + +GEMINI_ANALYZE_SCHEMA: Dict[str, Any] = { + "name": "gemini_analyze", + "description": ( + "Ask questions about local documents, PDFs, videos, audio files, images, CSVs, 'files/' " + "handles, or YouTube URLs via gemini-api CLI. Local media over ~14MB (up to 2GB) is seamlessly " + "uploaded via the Gemini Files API, and the resulting 'files/' handle is returned in 'inputs' " + "so follow-up questions can reuse it without re-uploading." + ), + "parameters": { + "type": "object", + "properties": { + "inputs": { + "type": "array", + "items": {"type": "string"}, + "description": "One or more local file paths, 'files/' handles, or YouTube URLs to analyze.", + }, + "question": { + "type": "string", + "description": "Question or instruction for analyzing the supplied media (defaults to a summary).", + }, + "system": { + "type": "string", + "description": "Optional system instruction to guide tone or output structure.", + }, + "mime_type": { + "type": "string", + "description": "Optional MIME type override when passing a single input with an uncommon extension.", + }, + "model": { + "type": "string", + "description": "Optional Gemini model override (when omitted, gemini-api uses its built-in default).", + }, + }, + "required": ["inputs"], + }, +} + +GEMINI_TRANSCRIBE_SCHEMA: Dict[str, Any] = { + "name": "gemini_transcribe", + "description": ( + "Transcribe local audio or video files (or 'files/' handles) with speaker diarization " + "and timestamps into Markdown, plain text, JSON, or SRT captions via gemini-api CLI. " + "Local media over ~14MB (up to 2GB) is seamlessly uploaded through the Gemini Files API." + ), + "parameters": { + "type": "object", + "properties": { + "inputs": { + "type": "array", + "items": {"type": "string"}, + "description": "One or more local audio/video paths or 'files/' handles to transcribe.", + }, + "format": { + "type": "string", + "enum": ["md", "text", "json", "srt"], + "description": "Transcript output format: 'md' (default), 'text', 'json', or 'srt' subtitles.", + }, + "speakers": { + "type": "boolean", + "description": "Include speaker attribution labels (default: true; ignored for 'srt').", + }, + "timestamps": { + "type": "boolean", + "description": "Include timestamps (default: true; always enabled for 'srt').", + }, + "model": { + "type": "string", + "description": "Optional Gemini model override (when omitted, gemini-api uses its built-in default).", + }, + }, + "required": ["inputs"], + }, +} + +GEMINI_DEEP_RESEARCH_SCHEMA: Dict[str, Any] = { + "name": "gemini_deep_research", + "description": ( + "Run, poll, or cancel multi-step Gemini Deep Research and Interactions API agent tasks " + f"(default agent: {DEFAULT_RESEARCH_AGENT}) via gemini-api CLI. Defaults to asynchronous " + "background execution so long runs return an interaction_id immediately for status polling." + ), + "parameters": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["run", "status", "cancel"], + "description": "'run' starts a research task (default), 'status' fetches an interaction by id, 'cancel' stops a background run.", + }, + "prompt": { + "type": "string", + "description": "Research prompt or question (required when action='run').", + }, + "interaction_id": { + "type": "string", + "description": "Interaction ID returned by a prior background run (required for 'status' and 'cancel').", + }, + "background": { + "type": "boolean", + "description": "Run asynchronously and return interaction_id immediately (default: true; set false to block).", + }, + "agent": { + "type": "string", + "description": f"Agent ID for action='run' (default: {DEFAULT_RESEARCH_AGENT}).", + }, + }, + "required": [], + }, +} + +GEMINI_FILES_UPLOAD_SCHEMA: Dict[str, Any] = { + "name": "gemini_files_upload", + "description": ( + "Upload a local media or document file (up to 2GB) to the Gemini Files API via gemini-api CLI " + "and wait until ACTIVE, returning a reusable 48-hour 'files/' handle." + ), + "parameters": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Local path to the file to upload.", + }, + "display_name": { + "type": "string", + "description": "Optional human-readable display name for the uploaded file.", + }, + "mime_type": { + "type": "string", + "description": "Optional explicit MIME type override (e.g. 'video/mp4', 'application/pdf').", + }, + }, + "required": ["path"], + }, +} + + +# ── Tool Handler Builders ──────────────────────────────────────────────────── + +def _string_list(raw: Any) -> List[str]: + if raw is None: + return [] + items = raw if isinstance(raw, list) else [raw] + return [str(x).strip() for x in items if isinstance(x, (str, int, float)) and str(x).strip()] + + +def build_tool_handlers(runner: GeminiCLIRunner) -> Dict[str, Callable[..., str]]: + """Create ``(args, **kw) -> json_str`` handlers bound to *runner*.""" + + def handle_music(args: dict, **_kw: Any) -> str: + prompt = str(args.get("prompt") or "").strip() + if not prompt: + return tool_error("A non-empty 'prompt' is required for gemini_music.", error_type="invalid_argument") + explicit_model = _strip_google_prefix(args.get("model")) + out_dir = _cache_subdir("generated", "audio") + cmd_args: List[str] = ["music", "--out", str(out_dir)] + if explicit_model: + cmd_args.extend(["-m", explicit_model]) + res = runner.run( + cmd_args, + positional_args=[prompt], + default_timeout=300, + default_model=explicit_model or DEFAULT_MUSIC_MODEL, + ) + if not res.ok: + return _cli_failure_to_tool_error(res) + payload = res.data if isinstance(res.data, dict) else {} + audio_path = str(payload.get("path") or "").strip() + if not audio_path or not Path(audio_path).is_file(): + return tool_error( + "gemini-api music completed without returning a valid output audio file path.", + error_type="invalid_response", + ) + return tool_result({ + "success": True, + "audio": audio_path, + "mime_type": payload.get("mime_type"), + "size_bytes": payload.get("size_bytes"), + "response_id": payload.get("response_id"), + "model": payload.get("model") or explicit_model or DEFAULT_MUSIC_MODEL, + "provider": "gemini", + }) + + def handle_tts(args: dict, **_kw: Any) -> str: + text = str(args.get("text") or "").strip() + if not text: + return tool_error("A non-empty 'text' is required for gemini_tts.", error_type="invalid_argument") + multi_speaker = str(args.get("multi_speaker") or "").strip() + voice = str(args.get("voice") or "").strip() + if multi_speaker.startswith("-") or voice.startswith("-"): + return tool_error("Voice or multi_speaker cannot start with a dash.", error_type="invalid_argument") + if multi_speaker and voice: + return tool_error( + "Pass either 'voice' (single-speaker) or 'multi_speaker' (two-speaker), not both.", + error_type="invalid_argument", + ) + explicit_model = _strip_google_prefix(args.get("model")) + out_dir = _cache_subdir("generated", "audio") + cmd_args: List[str] = ["tts", "--out", str(out_dir)] + if explicit_model: + cmd_args.extend(["-m", explicit_model]) + if multi_speaker: + cmd_args.extend(["--multi-speaker", multi_speaker]) + elif voice: + cmd_args.extend(["--voice", voice]) + language = str(args.get("language") or "").strip() + if language: + if language.startswith("-"): + return tool_error("Language cannot start with a dash.", error_type="invalid_argument") + cmd_args.extend(["--language", language]) + res = runner.run( + cmd_args, + positional_args=[text], + default_timeout=DEFAULT_CLI_TIMEOUT, + default_model=explicit_model or DEFAULT_TTS_MODEL, + ) + if not res.ok: + return _cli_failure_to_tool_error(res) + payload = res.data if isinstance(res.data, dict) else {} + audio_path = str(payload.get("path") or "").strip() + if not audio_path or not Path(audio_path).is_file(): + return tool_error( + "gemini-api tts completed without returning a valid output audio file path.", + error_type="invalid_response", + ) + return tool_result({ + "success": True, + "audio": audio_path, + "mime_type": payload.get("mime_type", "audio/wav"), + "size_bytes": payload.get("size_bytes"), + "sample_rate": payload.get("sample_rate"), + "channels": payload.get("channels"), + "model": payload.get("model") or explicit_model or DEFAULT_TTS_MODEL, + "provider": "gemini", + }) + + def handle_analyze(args: dict, **_kw: Any) -> str: + raw_inputs = _string_list(args.get("inputs")) + if not raw_inputs: + return tool_error("At least one entry in 'inputs' is required for gemini_analyze.", error_type="invalid_argument") + mime_type = str(args.get("mime_type") or "").strip() + if mime_type.startswith("-"): + return tool_error("MIME type cannot start with a dash.", error_type="invalid_argument") + if mime_type and len(raw_inputs) > 1: + return tool_error("'mime_type' can only be specified when a single input is provided.", error_type="invalid_argument") + + prepared: List[str] = [] + inline_used = 0 + for item in raw_inputs: + resolved_ref, err, added_cost = runner.prepare_media_input( + item, + allow_youtube=True, + mime_type=mime_type or None, + inline_budget_used=inline_used, + enforce_cumulative=True, + ) + if err is not None or not resolved_ref: + return _cli_failure_to_tool_error(err) if err is not None else tool_error("Invalid input reference.") + prepared.append(resolved_ref) + inline_used += added_cost + + explicit_model = _strip_google_prefix(args.get("model")) + cmd_args: List[str] = ["analyze"] + if explicit_model: + cmd_args.extend(["-m", explicit_model]) + for ref in prepared: + cmd_args.extend(["-i", ref]) + if mime_type: + cmd_args.extend(["--mime-type", mime_type]) + system = str(args.get("system") or "").strip() + if system: + cmd_args.append(f"--system={system}") + question = str(args.get("question") or "").strip() + positional = [question] if question else [] + + res = runner.run( + cmd_args, + positional_args=positional, + default_timeout=300, + default_model=explicit_model or DEFAULT_ANALYZE_MODEL, + ) + if not res.ok: + return _cli_failure_to_tool_error(res) + payload = res.data if isinstance(res.data, dict) else {} + return tool_result({ + "success": True, + "text": payload.get("text", ""), + "model": payload.get("model") or explicit_model or DEFAULT_ANALYZE_MODEL, + "inputs": prepared, + "mime_types": payload.get("mime_types"), + "provider": "gemini", + }) + + def handle_transcribe(args: dict, **_kw: Any) -> str: + raw_inputs = _string_list(args.get("inputs")) + if not raw_inputs: + return tool_error("At least one entry in 'inputs' is required for gemini_transcribe.", error_type="invalid_argument") + fmt = str(args.get("format") or "md").strip().lower() + if fmt not in _TRANSCRIBE_FORMATS: + return tool_error( + f"Unsupported format {fmt!r}: expected one of 'md', 'text', 'json', or 'srt'.", + error_type="invalid_argument", + ) + + prepared: List[str] = [] + for item in raw_inputs: + resolved_ref, err, _ = runner.prepare_media_input(item, allow_youtube=False) + if err is not None or not resolved_ref: + return _cli_failure_to_tool_error(err) if err is not None else tool_error("Invalid input reference.") + prepared.append(resolved_ref) + + explicit_model = _strip_google_prefix(args.get("model")) + out_dir = _cache_subdir("transcripts") + cmd_args: List[str] = ["transcribe", "--format", fmt, "--out", str(out_dir)] + if explicit_model: + cmd_args.extend(["-m", explicit_model]) + for ref in prepared: + cmd_args.extend(["-i", ref]) + if args.get("speakers") is False and fmt != "srt": + cmd_args.append("--no-speakers") + if args.get("timestamps") is False and fmt != "srt": + cmd_args.append("--no-timestamps") + + res = runner.run( + cmd_args, + default_timeout=300, + default_model=explicit_model or DEFAULT_TRANSCRIBE_MODEL, + ) + if not res.ok: + return _cli_failure_to_tool_error(res) + payload = res.data if isinstance(res.data, dict) else {} + results = payload.get("results") if isinstance(payload.get("results"), list) else [] + out_dir_resolved = out_dir.resolve() + transcripts: List[Dict[str, Any]] = [] + for entry in results: + if not isinstance(entry, dict): + continue + item_out = dict(entry) + out_path = entry.get("path") + if isinstance(out_path, str) and out_path.strip(): + try: + from agent.file_safety import raise_if_read_blocked + + raise_if_read_blocked(out_path) + resolved_out = Path(os.path.expanduser(out_path)).resolve() + raise_if_read_blocked(str(resolved_out)) + if resolved_out.is_relative_to(out_dir_resolved) and resolved_out.is_file(): + text_body = resolved_out.read_text(encoding="utf-8", errors="replace") + if len(text_body) <= 32768: + item_out["content"] = text_body + else: + item_out["content_omitted"] = True + except Exception: # noqa: BLE001 + pass + transcripts.append(item_out) + return tool_result({ + "success": True, + "format": payload.get("format") or fmt, + "model": payload.get("model") or explicit_model or DEFAULT_TRANSCRIBE_MODEL, + "results": transcripts, + "provider": "gemini", + }) + + def handle_deep_research(args: dict, **_kw: Any) -> str: + action = str(args.get("action") or "run").strip().lower() + if action not in _RESEARCH_ACTIONS: + return tool_error( + f"Unsupported action {action!r}: expected 'run', 'status', or 'cancel'.", + error_type="invalid_argument", + ) + if action == "run": + prompt = str(args.get("prompt") or "").strip() + if not prompt: + return tool_error("A non-empty 'prompt' is required when action='run'.", error_type="invalid_argument") + agent_id = str(args.get("agent") or "").strip() or DEFAULT_RESEARCH_AGENT + if agent_id.startswith("-"): + return tool_error(f"Invalid 'agent' {agent_id!r}.", error_type="invalid_argument") + raw_bg = args.get("background") + background = True if raw_bg is None else bool(raw_bg) + cmd_args = ["agent", "run", "--agent", agent_id, "--stream=false"] + if background: + cmd_args.append("--background") + res = runner.run( + cmd_args, + positional_args=[prompt], + default_timeout=60 if background else DEFAULT_RESEARCH_TIMEOUT, + default_model=agent_id, + ) + if not res.ok: + return _cli_failure_to_tool_error(res) + payload = res.data if isinstance(res.data, dict) else {} + status = str(payload.get("status") or "").strip() or None + errors = _extract_interaction_errors(payload) + if status == "failed" or (errors and status != "completed"): + err_msg = "; ".join(errors) if errors else f"Deep Research interaction ended with status={status!r}" + return tool_error( + err_msg, + error_type="api_error", + action="run", + interaction_id=payload.get("id"), + status=status, + errors=errors or None, + provider="gemini", + ) + return tool_result({ + "success": True, + "action": "run", + "interaction_id": payload.get("id"), + "status": status, + "agent": agent_id, + "background": background, + "output_text": _extract_interaction_text(payload), + "provider": "gemini", + }) + + interaction_id = str(args.get("interaction_id") or "").strip() + if not interaction_id: + return tool_error( + f"'interaction_id' is required when action={action!r}.", + error_type="invalid_argument", + ) + if interaction_id.startswith("-"): + return tool_error( + f"Invalid 'interaction_id' {interaction_id!r}.", + error_type="invalid_argument", + ) + if action == "status": + res = runner.run( + ["agent", "status", "--id", interaction_id, "--stream=false"], + default_timeout=60, + ) + if not res.ok: + return _cli_failure_to_tool_error(res) + payload = res.data if isinstance(res.data, dict) else {} + status = str(payload.get("status") or "").strip() or None + errors = _extract_interaction_errors(payload) + if status == "failed" or (errors and status != "completed"): + err_msg = "; ".join(errors) if errors else f"Deep Research interaction ended with status={status!r}" + return tool_error( + err_msg, + error_type="api_error", + action="status", + interaction_id=payload.get("id") or interaction_id, + status=status, + errors=errors or None, + provider="gemini", + ) + return tool_result({ + "success": True, + "action": "status", + "interaction_id": payload.get("id") or interaction_id, + "status": status, + "output_text": _extract_interaction_text(payload), + "provider": "gemini", + }) + + res = runner.run(["agent", "cancel", "--id", interaction_id], default_timeout=60) + if not res.ok: + return _cli_failure_to_tool_error(res) + payload = res.data if isinstance(res.data, dict) else {} + return tool_result({ + "success": True, + "action": "cancel", + "interaction_id": payload.get("id") or interaction_id, + "status": payload.get("status") or "cancelled", + "provider": "gemini", + }) + + def handle_files_upload(args: dict, **_kw: Any) -> str: + path = str(args.get("path") or "").strip() + if not path: + return tool_error("A non-empty 'path' is required for gemini_files_upload.", error_type="invalid_argument") + res = runner.upload_file( + path, + display_name=args.get("display_name"), + mime_type=args.get("mime_type"), + wait=True, + ) + if not res.ok: + return _cli_failure_to_tool_error(res) + payload = res.data if isinstance(res.data, dict) else {} + return tool_result({ + "success": True, + "name": payload.get("name"), + "uri": payload.get("uri"), + "mime_type": payload.get("mime_type"), + "display_name": payload.get("display_name"), + "size_bytes": payload.get("size_bytes"), + "state": payload.get("state"), + "provider": "gemini", + }) + + return { + "gemini_music": handle_music, + "gemini_tts": handle_tts, + "gemini_analyze": handle_analyze, + "gemini_transcribe": handle_transcribe, + "gemini_deep_research": handle_deep_research, + "gemini_files_upload": handle_files_upload, + } + + +def register_cli_integrations( + ctx: Any, + *, + endpoint_resolver: Callable[[], Tuple[str, str]], + image_loader: Callable[[str], Tuple[bytes, str]], + user_agent: str, + runner: Optional[GeminiCLIRunner] = None, + local_mime_sniffer: Optional[Callable[[str], str]] = None, +) -> GeminiCLIRunner: + """Register ``GeminiVideoGenProvider``, structured CLI tools, and ``SKILL.md`` on *ctx*.""" + active_runner = ( + runner + if runner is not None + else GeminiCLIRunner(endpoint_resolver=endpoint_resolver, user_agent=user_agent) + ) + + if hasattr(ctx, "register_video_gen_provider"): + ctx.register_video_gen_provider( + GeminiVideoGenProvider( + runner=active_runner, + endpoint_resolver=endpoint_resolver, + image_loader=image_loader, + local_mime_sniffer=local_mime_sniffer, + ) + ) + + handlers = build_tool_handlers(active_runner) + tool_specs = ( + ("gemini_music", GEMINI_MUSIC_SCHEMA, "🎵"), + ("gemini_tts", GEMINI_TTS_SCHEMA, "🗣️"), + ("gemini_analyze", GEMINI_ANALYZE_SCHEMA, "🔎"), + ("gemini_transcribe", GEMINI_TRANSCRIBE_SCHEMA, "📝"), + ("gemini_deep_research", GEMINI_DEEP_RESEARCH_SCHEMA, "🧠"), + ("gemini_files_upload", GEMINI_FILES_UPLOAD_SCHEMA, "📤"), + ) + for tool_name, schema, emoji in tool_specs: + ctx.register_tool( + name=tool_name, + toolset="gemini_api", + schema=schema, + handler=handlers[tool_name], + check_fn=active_runner.is_available, + requires_env=["GEMINI_API_KEY"], + description=schema["description"], + emoji=emoji, + ) + + skill_path = Path(__file__).resolve().parent / "SKILL.md" + if hasattr(ctx, "register_skill") and skill_path.is_file(): + ctx.register_skill( + "gemini-api-cli", + skill_path, + description="Non-interactive command reference for google-gemini/gemini-api-cli", + ) + return active_runner diff --git a/plugin.yaml b/plugin.yaml index 4d2e111..f4f1a41 100644 --- a/plugin.yaml +++ b/plugin.yaml @@ -12,10 +12,35 @@ # See the License for the specific language governing permissions and # limitations under the License. -name: gemini-image -version: 0.1.0 -description: "Native Google AI Studio Gemini (Nano Banana) image generation and editing using GEMINI_API_KEY. Saves generated images to $HERMES_HOME/cache/generated/images/." +name: gemini-api +version: 0.2.0 +requires_hermes: ">=0.22.0" +description: "Google AI Studio Gemini plugin for Hermes powered by gemini-api CLI (Interactions API): Nano Banana image generation/editing, Gemini Omni video generation, Lyria music, 3.8 Flash TTS, multimodal analysis, transcription, Deep Research, and Files API uploads." author: Google DeepMind kind: backend requires_env: - GEMINI_API_KEY +provides_tools: + - gemini_music + - gemini_tts + - gemini_analyze + - gemini_transcribe + - gemini_deep_research + - gemini_files_upload +external_dependencies: + - name: gemini-api + install: "go install github.com/google-gemini/gemini-api-cli/cmd/gemini-api@v0.5.0" + check: "gemini-api --version" +config_schema: + cli_path: + type: str + default: "" + description: "Optional explicit path to the gemini-api executable." + timeout_seconds: + type: int + default: 180 + description: "Optional timeout override in seconds for gemini-api CLI calls (omit to use per-command defaults)." + auto_install_cli: + type: bool + default: false + description: "When true, download and verify the pinned gemini-api v0.5.0 release (against hardcoded SHA-256 digests) into $HERMES_HOME/bin if not found on PATH." diff --git a/tests/test_gemini_cli_plugin.py b/tests/test_gemini_cli_plugin.py new file mode 100644 index 0000000..c6d2fea --- /dev/null +++ b/tests/test_gemini_cli_plugin.py @@ -0,0 +1,892 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the gemini-api CLI integration (video provider, 6 tools, skill, security, and validation).""" + +from __future__ import annotations + +import hashlib +import importlib.util +import io +import json +import os +import shutil +import subprocess +import sys +import tarfile +import zipfile +from pathlib import Path +from typing import Any, List +from unittest.mock import MagicMock, patch + +import pytest +import yaml + +_PLUGIN_ROOT = Path(__file__).resolve().parent.parent + +_PNG_HEX = ( + "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4" + "890000000d49444154789c6300010000000500010d0a2db40000000049454e44" + "ae426082" +) + + +def _load_plugin_package(): + pkg_name = "hermes_plugins_test_pkg" + spec = importlib.util.spec_from_file_location( + pkg_name, + _PLUGIN_ROOT / "__init__.py", + submodule_search_locations=[str(_PLUGIN_ROOT)], + ) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + sys.modules[pkg_name] = mod + spec.loader.exec_module(mod) + return mod + + +gemini_plugin = _load_plugin_package() +cli_tools = gemini_plugin._load_cli_tools_module() +cli_runner = cli_tools._cli_runner + + +def _make_fake_binary(tmp_path: Path) -> Path: + bin_dir = tmp_path / "bin" + bin_dir.mkdir(parents=True, exist_ok=True) + binary = bin_dir / "gemini-api" + binary.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + binary.chmod(0o755) + return binary + + +def _completed_proc( + payload: Any = None, + *, + returncode: int = 0, + stderr_payload: Any = None, + raw_stdout: str = "", + raw_stderr: str = "", +) -> subprocess.CompletedProcess[str]: + stdout = raw_stdout if raw_stdout else (json.dumps(payload) if payload is not None else "") + stderr = raw_stderr if raw_stderr else (json.dumps(stderr_payload) if stderr_payload is not None else "") + return subprocess.CompletedProcess(args=["gemini-api"], returncode=returncode, stdout=stdout, stderr=stderr) + + +@pytest.fixture(autouse=True) +def _isolated_hermes_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + cli_runner.clear_cli_cache() + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("GEMINI_API_KEY", "AQ.test-key") + monkeypatch.delenv("GEMINI_BASE_URL", raising=False) + monkeypatch.delenv("GEMINI_IMAGE_MODEL", raising=False) + yield tmp_path + cli_runner.clear_cli_cache() + + +@pytest.fixture() +def fake_cli_bin(tmp_path: Path) -> Path: + return _make_fake_binary(tmp_path) + + +@pytest.fixture() +def runner(fake_cli_bin: Path): + return cli_runner.GeminiCLIRunner( + endpoint_resolver=gemini_plugin._resolve_endpoint, + user_agent=gemini_plugin.CLI_USER_AGENT, + cli_path=str(fake_cli_bin), + ) + + +class TestBinaryResolutionAndInstaller: + def test_resolves_hermes_home_bin_before_path_with_ttl_cache(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + hermes_bin = _make_fake_binary(tmp_path) + calls = 0 + + def _counting_which(_name: str): + nonlocal calls + calls += 1 + return "/usr/bin/other-gemini-api" + + monkeypatch.setattr(shutil, "which", _counting_which) + assert cli_runner.resolve_cli_binary() == str(hermes_bin) + assert calls == 0 + + def test_settings_cli_path_override_and_missing_binary(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + custom_bin = tmp_path / "custom" / "gemini-api" + custom_bin.parent.mkdir(parents=True) + custom_bin.write_text("#!/bin/sh\n", encoding="utf-8") + custom_bin.chmod(0o755) + (tmp_path / "config.yaml").write_text( + yaml.safe_dump({"plugins": {"entries": {"gemini-api": {"settings": {"cli_path": str(custom_bin)}}}}}), + encoding="utf-8", + ) + assert cli_runner.resolve_cli_binary() == str(custom_bin) + + # Non-existent configured cli_path fails closed instead of falling back silently. + (tmp_path / "config.yaml").write_text( + yaml.safe_dump({"plugins": {"entries": {"gemini-api": {"settings": {"cli_path": str(tmp_path / "nope")}}}}}), + encoding="utf-8", + ) + assert cli_runner.resolve_cli_binary() is None + + # Without binary anywhere and auto_install_cli default false, runner returns actionable hint. + (tmp_path / "config.yaml").unlink() + cli_runner.clear_cli_cache() + monkeypatch.setattr(shutil, "which", lambda _name: None) + monkeypatch.setattr(Path, "home", lambda: tmp_path / "empty-home") + bare_runner = cli_runner.GeminiCLIRunner( + endpoint_resolver=gemini_plugin._resolve_endpoint, + user_agent=gemini_plugin.USER_AGENT, + ) + with patch.object(cli_runner, "_is_executable_file", return_value=False): + res = bare_runner.run(["models", "list"]) + assert res.ok is False + assert res.error_type == "missing_dependency" + assert "go install github.com/google-gemini/gemini-api-cli" in res.error + + def test_server_flags_strip_v1beta_and_reject_cleartext_remote_urls(self, runner, monkeypatch: pytest.MonkeyPatch): + assert cli_runner.server_flags_from_base_url("https://generativelanguage.googleapis.com/v1beta") == [] + assert cli_runner.server_flags_from_base_url("https://proxy.example.com/v1beta/") == [ + "--server-url", + "https://proxy.example.com", + ] + assert cli_runner.server_flags_from_base_url("https://proxy.example.com/v1alpha") == [ + "--server-url", + "https://proxy.example.com", + "--api-version", + "v1alpha", + ] + assert cli_runner.server_flags_from_base_url("http://127.0.0.1:8080/v1beta") == [ + "--server-url", + "http://127.0.0.1:8080", + ] + + # Cleartext non-loopback HTTP base_url is refused before spawning the CLI with GEMINI_API_KEY. + monkeypatch.setenv("GEMINI_BASE_URL", "http://evil.example.com/v1beta") + with patch("subprocess.run") as mock_run: + res = runner.run(["models", "list"]) + assert res.ok is False + assert res.error_type == "invalid_argument" + assert "https://" in res.error + mock_run.assert_not_called() + + def test_install_cli_binary_verifies_sha256_and_enforces_size_cap( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + # Verify exact GoReleaser release asset names across Linux, macOS, and Windows. + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setattr("platform.machine", lambda: "x86_64") + assert cli_runner._platform_release_asset("0.5.0") == ("gemini-api_Linux_x86_64.tar.gz", "gemini-api") + + monkeypatch.setattr(sys, "platform", "darwin") + monkeypatch.setattr("platform.machine", lambda: "arm64") + assert cli_runner._platform_release_asset("0.5.0") == ("gemini-api_Darwin_arm64.tar.gz", "gemini-api") + + monkeypatch.setattr(sys, "platform", "win32") + monkeypatch.setattr("platform.machine", lambda: "AMD64") + assert cli_runner._platform_release_asset("0.5.0") == ("gemini-api_Windows_x86_64.zip", "gemini-api.exe") + + # Back to Linux x86_64 for tar.gz verification against pinned SHA-256 table. + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setattr("platform.machine", lambda: "x86_64") + + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tf: + payload = b"#!/bin/sh\necho gemini-api 0.5.0\n" + info = tarfile.TarInfo(name="gemini-api") + info.size = len(payload) + info.mode = 0o755 + tf.addfile(info, io.BytesIO(payload)) + archive_bytes = buf.getvalue() + good_sha = hashlib.sha256(archive_bytes).hexdigest() + asset_name = "gemini-api_Linux_x86_64.tar.gz" + assert asset_name in cli_runner.PINNED_CLI_SHA256 + + def _mock_client_ctx(checksums_body: str = "", chunks: List[bytes] | None = None): + client = MagicMock() + cs_bytes = checksums_body.encode("utf-8") + + def _stream(_method: str, url: str): + resp = MagicMock() + resp.raise_for_status.return_value = None + if url.endswith("/checksums.txt"): + resp.iter_bytes.return_value = [cs_bytes] + else: + resp.iter_bytes.return_value = chunks if chunks is not None else [archive_bytes] + cm = MagicMock() + cm.__enter__.return_value = resp + cm.__exit__.return_value = False + return cm + + client.stream.side_effect = _stream + cm = MagicMock() + cm.__enter__.return_value = client + cm.__exit__.return_value = False + return cm + + # Pinned v0.5.0 uses hardcoded PINNED_CLI_SHA256 directly without trusting remote checksums.txt. + monkeypatch.setitem(cli_runner.PINNED_CLI_SHA256, asset_name, good_sha) + with patch("tools.url_safety.create_ssrf_safe_client", return_value=_mock_client_ctx()) as mock_client_factory: + installed = cli_runner.install_cli_binary(target_dir=tmp_path / "installed") + assert installed.is_file() + assert os.access(installed, os.X_OK) + stream_urls = [c.args[1] for c in mock_client_factory.return_value.__enter__.return_value.stream.call_args_list] + assert stream_urls == [f"https://github.com/google-gemini/gemini-api-cli/releases/download/v{cli_runner.PINNED_CLI_VERSION}/{asset_name}"] + + # Tampered bytes fail hardcoded SHA-256 verification. + monkeypatch.setitem(cli_runner.PINNED_CLI_SHA256, asset_name, "0" * 64) + with patch("tools.url_safety.create_ssrf_safe_client", return_value=_mock_client_ctx()): + with pytest.raises(ValueError, match="SHA-256 mismatch"): + cli_runner.install_cli_binary(target_dir=tmp_path / "tampered") + assert not (tmp_path / "tampered" / "gemini-api").exists() + + # Non-pinned custom version falls back to bounded checksums.txt verification. + with patch( + "tools.url_safety.create_ssrf_safe_client", + return_value=_mock_client_ctx(f"{good_sha} {asset_name}\n"), + ): + custom_installed = cli_runner.install_cli_binary(version="0.4.6", target_dir=tmp_path / "custom_ver") + assert custom_installed.is_file() + + # Windows .zip archive extraction works cleanly too. + zip_buf = io.BytesIO() + with zipfile.ZipFile(zip_buf, mode="w") as zf: + zf.writestr("gemini-api.exe", b"MZ-fake-pe") + zip_bytes = zip_buf.getvalue() + zip_sha = hashlib.sha256(zip_bytes).hexdigest() + monkeypatch.setattr(sys, "platform", "win32") + monkeypatch.setattr("platform.machine", lambda: "x86_64") + monkeypatch.setitem(cli_runner.PINNED_CLI_SHA256, "gemini-api_Windows_x86_64.zip", zip_sha) + with patch("tools.url_safety.create_ssrf_safe_client", return_value=_mock_client_ctx(chunks=[zip_bytes])): + win_installed = cli_runner.install_cli_binary(target_dir=tmp_path / "win_installed") + assert win_installed.name == "gemini-api.exe" + assert win_installed.read_bytes() == b"MZ-fake-pe" + + # Download size cap is enforced during streaming. + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setitem(cli_runner.PINNED_CLI_SHA256, asset_name, good_sha) + monkeypatch.setattr(cli_runner, "_MAX_ARCHIVE_BYTES", 8) + with patch("tools.url_safety.create_ssrf_safe_client", return_value=_mock_client_ctx()): + with pytest.raises(ValueError, match="safety limit"): + cli_runner.install_cli_binary(target_dir=tmp_path / "oversized") + + +class TestRunnerExecutionAndSafety: + def test_invokes_headless_json_with_pr2_user_agent_and_double_dash_guard( + self, runner, monkeypatch: pytest.MonkeyPatch + ): + from agent import aux_accounting + + # Verify unrelated secrets and conflicting GEMINI_* env vars are scrubbed from child env. + monkeypatch.setenv("OPENAI_API_KEY", "fake-openai-key-should-not-leak") + monkeypatch.setenv("ANTHROPIC_API_KEY", "fake-anthropic-key-should-not-leak") + monkeypatch.setenv("GEMINI_ACCESS_TOKEN", "fake-access-token-should-not-override") + monkeypatch.setenv("GOOGLE_API_KEY", "fake-google-key-should-not-leak") + monkeypatch.setenv("HTTPS_PROXY", "https://proxy.corp.example:8443") + + recorded: List[Any] = [] + + class _DB: + def record_auxiliary_usage(self, *args, **kwargs): + recorded.append((args, kwargs)) + + # Use real porcelain usage keys (`prompt_tokens`, `output_tokens`, `thoughts_tokens`). + proc = _completed_proc({ + "model": cli_tools.DEFAULT_ANALYZE_MODEL, + "text": "Analysis complete", + "usage": {"prompt_tokens": 120, "output_tokens": 80, "thoughts_tokens": 30, "total_tokens": 230}, + }) + token = aux_accounting.set_accounting_context(_DB(), "sess-cli-1") + try: + with patch("subprocess.run", return_value=proc) as mock_run: + res = runner.run( + ["analyze", "-i", "files/abc123"], + positional_args=["--server-url=https://evil.example - summarize this"], + default_model=cli_tools.DEFAULT_ANALYZE_MODEL, + ) + finally: + aux_accounting.reset_accounting_context(token) + + assert res.ok is True + cmd = mock_run.call_args.args[0] + assert "--no-interactive" in cmd + assert cmd[cmd.index("-o") + 1] == "json" + header_val = cmd[cmd.index("--header") + 1] + assert header_val == f"User-Agent: {gemini_plugin.CLI_USER_AGENT}" + assert gemini_plugin.HERMES_VERSION in header_val + assert f"gemini-api-plugin/{gemini_plugin.PLUGIN_VERSION}" in header_val + assert f"gemini-api-cli/{cli_runner.PINNED_CLI_VERSION}" in header_val + # Positional prompt with leading `--` sits strictly after `--` so Cobra never parses it as a flag. + dd_idx = cmd.index("--") + assert dd_idx > cmd.index("--no-interactive") + assert cmd[dd_idx + 1:] == ["--server-url=https://evil.example - summarize this"] + assert mock_run.call_args.kwargs["stdin"] == subprocess.DEVNULL + child_env = mock_run.call_args.kwargs["env"] + assert child_env["GEMINI_API_KEY"] == "AQ.test-key" + assert child_env["HTTPS_PROXY"] == "https://proxy.corp.example:8443" + assert "OPENAI_API_KEY" not in child_env + assert "ANTHROPIC_API_KEY" not in child_env + assert "GEMINI_ACCESS_TOKEN" not in child_env + assert "GOOGLE_API_KEY" not in child_env + assert len(recorded) == 1 + assert recorded[0][1]["input_tokens"] == 120 + assert recorded[0][1]["output_tokens"] == 110 # 80 output + 30 thoughts + + def test_interactions_usage_and_per_item_transcribe_model_accounting(self, runner): + from agent import aux_accounting + + recorded: List[Any] = [] + + class _DB: + def record_auxiliary_usage(self, *args, **kwargs): + recorded.append(kwargs) + + token = aux_accounting.set_accounting_context(_DB(), "sess-cli-usage") + try: + cli_runner.maybe_record_cli_usage( + { + "id": "int_1", + "usage": { + "total_input_tokens": 500, + "total_output_tokens": 200, + "total_thought_tokens": 100, + "total_cached_tokens": 50, + "total_tokens": 800, + }, + }, + default_model="deep-research-preview-04-2026", + base_url="https://generativelanguage.googleapis.com/v1beta", + ) + cli_runner.maybe_record_cli_usage( + { + "model": "gemini-3.5-transcribe", + "results": [ + { + "model": "gemini-4-hydrogen", + "usage": {"prompt_tokens": 40, "output_tokens": 60, "thoughts_tokens": 10}, + } + ], + }, + default_model="gemini-3.5-transcribe", + base_url="https://generativelanguage.googleapis.com/v1beta", + ) + finally: + aux_accounting.reset_accounting_context(token) + + assert len(recorded) == 2 + assert recorded[0]["model"] == "deep-research-preview-04-2026" + # Hermes aux_accounting splits prompt_tokens (500) into uncached input_tokens (450) + cache_read_tokens (50). + assert ( + recorded[0]["input_tokens"], + recorded[0]["cache_read_tokens"], + recorded[0]["output_tokens"], + ) == (450, 50, 300) + assert recorded[1]["model"] == "gemini-4-hydrogen" + assert (recorded[1]["input_tokens"], recorded[1]["output_tokens"]) == (40, 70) + + def test_timeout_seconds_setting_overrides_tool_defaults_and_e2big_error_type( + self, runner, tmp_path: Path + ): + handlers = cli_tools.build_tool_handlers(runner) + (tmp_path / "config.yaml").write_text( + yaml.safe_dump({"plugins": {"entries": {"gemini-api": {"settings": {"timeout_seconds": 77}}}}}), + encoding="utf-8", + ) + cli_runner.clear_cli_cache() + + music_file = tmp_path / "track.mp3" + music_file.write_bytes(b"mp3") + with patch( + "subprocess.run", + return_value=_completed_proc({"path": str(music_file), "mime_type": "audio/mpeg"}), + ) as mock_run: + res = json.loads(handlers["gemini_music"]({"prompt": "ambient piano"})) + assert res["success"] is True + assert mock_run.call_args.kwargs["timeout"] == 77 + + # OSError(E2BIG) is classified as execution_error, not missing_dependency. + with patch("subprocess.run", side_effect=OSError(7, "Argument list too long")): + e2big = runner.run(["video"], positional_args=["hi"]) + assert e2big.ok is False + assert e2big.error_type == "execution_error" + assert "go install" not in e2big.error + + @pytest.mark.parametrize( + ("code", "expected_type"), + [(1, "api_error"), (2, "invalid_argument"), (3, "auth_required")], + ) + def test_exit_codes_and_structured_stderr_hints(self, runner, code: int, expected_type: str): + proc = _completed_proc( + returncode=code, + stderr_payload={"error": "bad request", "exit_code": code, "hints": ["try --stream=false"]}, + ) + with patch("subprocess.run", return_value=proc): + res = runner.run(["generate"], positional_args=["hi"]) + assert res.ok is False + assert res.error_type == expected_type + assert "bad request" in res.error + assert "try --stream=false" in res.error + + def test_blocks_credential_store_and_seamlessly_auto_uploads_large_binary_media( + self, runner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + auth_json = tmp_path / "auth.json" + auth_json.write_text('{"secret":"value"}', encoding="utf-8") + + with patch("subprocess.run") as mock_run: + ref, err, _ = runner.prepare_media_input(str(auth_json)) + assert ref is None + assert err is not None and err.error_type == "invalid_argument" + assert "credential store" in err.error.lower() + mock_run.assert_not_called() + + # Malformed files/ traversal attempt is rejected locally. + bad_ref, bad_err, _ = runner.prepare_media_input("files/../../etc/passwd") + assert bad_ref is None and bad_err is not None and bad_err.error_type == "invalid_argument" + + # Oversized binary media automatically promotes via `files upload --wait -- `. + monkeypatch.setattr(cli_runner, "CLI_INLINE_LIMIT_BYTES", 64) + big_media = tmp_path / "lecture.mp4" + big_media.write_bytes(b"\x00" * 256) + + upload_proc = _completed_proc({"name": "files/lec999", "state": "ACTIVE"}) + with patch("subprocess.run", return_value=upload_proc) as mock_run: + ref, err, cost = runner.prepare_media_input(str(big_media)) + assert err is None + assert ref == "files/lec999" + assert cost == 0 + upload_cmd = mock_run.call_args.args[0] + assert upload_cmd[1:3] == ["files", "upload"] + assert "--wait" in upload_cmd + assert upload_cmd[upload_cmd.index("--") + 1:] == [str(big_media)] + + # Plain-text files are NOT uploaded to Files API (gemini-api sends text inline only). + big_txt = tmp_path / "notes.txt" + big_txt.write_text("x" * 256, encoding="utf-8") + with patch("subprocess.run") as mock_run: + txt_ref, txt_err, _ = runner.prepare_media_input(str(big_txt)) + assert txt_err is None + assert txt_ref == str(big_txt) + mock_run.assert_not_called() + + +class TestVideoGenProviderAndTools: + def test_video_provider_omits_default_m_flag_and_supports_explicit_override(self, runner, tmp_path: Path): + provider = cli_tools.GeminiVideoGenProvider( + runner=runner, + endpoint_resolver=gemini_plugin._resolve_endpoint, + image_loader=gemini_plugin._load_image_bytes, + ) + assert provider.default_model() == cli_tools.DEFAULT_VIDEO_MODEL + ids = {m["id"] for m in provider.list_models()} + assert ids >= {cli_tools.DEFAULT_VIDEO_MODEL, "gemini-omni-flash-preview"} + + out_mp4 = tmp_path / "cache" / "videos" / "clip.mp4" + out_mp4.parent.mkdir(parents=True, exist_ok=True) + out_mp4.write_bytes(b"fake-mp4-bytes") + + # Foreign top-level model (`grok-imagine-video`) is ignored; `-m` is omitted so CLI owns default! + proc = _completed_proc({ + "path": str(out_mp4), + "kind": "video", + "mime_type": "video/mp4", + "size_bytes": 14, + "response_id": "int_vid_1", + "status": "completed", + }) + with patch("subprocess.run", return_value=proc) as mock_run: + result = provider.generate( + "a paper boat in the rain", + model="grok-imagine-video", + aspect_ratio="9:16", + resolution="1080p", + ) + assert result["success"] is True + assert result["video"] == str(out_mp4) + assert result["model"] == cli_tools.DEFAULT_VIDEO_MODEL + assert result["modality"] == "text" + assert result["response_id"] == "int_vid_1" + cmd = mock_run.call_args.args[0] + assert cmd[1] == "video" + assert "-m" not in cmd + assert cmd[cmd.index("--aspect-ratio") + 1] == "9:16" + assert cmd[cmd.index("--resolution") + 1] == "1080p" + assert cmd[cmd.index("--") + 1:] == ["a paper boat in the rain"] + + # Explicit Gemini video model passes `-m` and image-to-video passes `-i ` (never `--body` argv). + frame = tmp_path / "frame.png" + frame.write_bytes(bytes.fromhex(_PNG_HEX)) + with patch("subprocess.run", return_value=proc) as mock_run: + i2v = provider.generate( + "animate gentle waves", + image_url=str(frame), + model="gemini-omni-flash-preview", + aspect_ratio="16:9", + resolution="720p", + ) + assert i2v["success"] is True + assert i2v["modality"] == "image" + assert i2v["model"] == "gemini-omni-flash-preview" + i2v_cmd = mock_run.call_args.args[0] + assert i2v_cmd[i2v_cmd.index("-m") + 1] == "gemini-omni-flash-preview" + assert "--body" not in i2v_cmd + assert i2v_cmd[i2v_cmd.index("-i") + 1] == str(frame) + assert i2v_cmd[i2v_cmd.index("--aspect-ratio") + 1] == "16:9" + assert i2v_cmd[i2v_cmd.index("--resolution") + 1] == "720p" + assert i2v_cmd[i2v_cmd.index("--") + 1:] == ["animate gentle waves"] + + # Data URI image-to-video writes a private temp file, passes `-i `, and cleans it up. + import base64 + + data_uri = f"data:image/png;base64,{base64.b64encode(bytes.fromhex(_PNG_HEX)).decode('ascii')}" + seen_tmp_paths: List[Path] = [] + + def _capture_tmp(argv, **_kwargs): + tmp_ref = Path(argv[argv.index("-i") + 1]) + assert tmp_ref.is_file() + seen_tmp_paths.append(tmp_ref) + return proc + + with patch("subprocess.run", side_effect=_capture_tmp): + i2v_data = provider.generate("gentle zoom", image_url=data_uri) + assert i2v_data["success"] is True + assert len(seen_tmp_paths) == 1 + assert not seen_tmp_paths[0].exists() + + def test_music_and_tts_tools_delegate_default_model_and_pass_overrides(self, runner, tmp_path: Path): + handlers = cli_tools.build_tool_handlers(runner) + + music_file = tmp_path / "track.mp3" + music_file.write_bytes(b"mp3") + with patch( + "subprocess.run", + return_value=_completed_proc({"path": str(music_file), "mime_type": "audio/mpeg", "size_bytes": 3}), + ) as mock_run: + music_res = json.loads(handlers["gemini_music"]({"prompt": "- upbeat jazz piano"})) + assert music_res["success"] is True + assert music_res["audio"] == str(music_file) + assert music_res["model"] == cli_tools.DEFAULT_MUSIC_MODEL + music_cmd = mock_run.call_args.args[0] + assert "-m" not in music_cmd + assert music_cmd[music_cmd.index("--") + 1:] == ["- upbeat jazz piano"] + + # Mutually exclusive voice + multi_speaker rejected locally. + conflict = json.loads( + handlers["gemini_tts"]({"text": "A: Hi", "voice": "Kore", "multi_speaker": "A=Kore,B=Puck"}) + ) + assert conflict["error_type"] == "invalid_argument" + + wav_file = tmp_path / "speech.wav" + wav_file.write_bytes(b"wav") + with patch( + "subprocess.run", + return_value=_completed_proc( + {"path": str(wav_file), "model": cli_tools.DEFAULT_TTS_MODEL, "sample_rate": 24000, "channels": 1} + ), + ) as mock_run: + tts_res = json.loads( + handlers["gemini_tts"]({ + "text": "Host: Welcome!\nGuest: Thanks!", + "multi_speaker": "Host=Kore,Guest=Puck", + "language": "en-US", + }) + ) + assert tts_res["success"] is True + assert tts_res["audio"] == str(wav_file) + assert tts_res["model"] == cli_tools.DEFAULT_TTS_MODEL + tts_cmd = mock_run.call_args.args[0] + assert "-m" not in tts_cmd + assert "--multi-speaker" in tts_cmd + assert "Host=Kore,Guest=Puck" in tts_cmd + assert "--language" in tts_cmd + + def test_analyze_transcribe_deep_research_and_files_upload( + self, runner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + handlers = cli_tools.build_tool_handlers(runner) + + # Cumulative multi-file inline budget promotes the second PDF seamlessly and surfaces files/. + monkeypatch.setattr(cli_runner, "CLI_CUMULATIVE_INLINE_BYTES", 32) + doc1 = tmp_path / "part1.pdf" + doc2 = tmp_path / "part2.pdf" + doc1.write_bytes(b"%PDF-1.4 one") + doc2.write_bytes(b"%PDF-1.4 two-overflow") + + upload_proc = _completed_proc({"name": "files/part2id", "state": "ACTIVE"}) + analyze_proc = _completed_proc({"model": cli_tools.DEFAULT_ANALYZE_MODEL, "text": "Key takeaway: 42%"}) + with patch("subprocess.run", side_effect=[upload_proc, analyze_proc]) as mock_run: + ana = json.loads( + handlers["gemini_analyze"]({ + "inputs": [str(doc1), str(doc2), "https://youtu.be/dQw4w9WgXcQ"], + "question": "Compare the reports and video", + "system": "Be concise", + }) + ) + assert ana["success"] is True + assert ana["text"] == "Key takeaway: 42%" + assert ana["inputs"] == [str(doc1), "files/part2id", "https://youtu.be/dQw4w9WgXcQ"] + ana_cmd = mock_run.call_args_list[1].args[0] + assert ana_cmd[1] == "analyze" + assert "-m" not in ana_cmd + assert "files/part2id" in ana_cmd + assert ana_cmd[ana_cmd.index("--") + 1:] == ["Compare the reports and video"] + + # Transcribe reads back generated SRT file content when <=32KB and inside cache/transcripts. + audio = tmp_path / "clip.mp3" + audio.write_bytes(b"audio-bytes") + transcript_dir = tmp_path / "cache" / "transcripts" + transcript_dir.mkdir(parents=True, exist_ok=True) + srt_out = transcript_dir / "clip.srt" + srt_out.write_text("1\n00:00:00,000 --> 00:00:02,000\nHello world\n", encoding="utf-8") + with patch( + "subprocess.run", + return_value=_completed_proc( + {"format": "srt", "model": cli_tools.DEFAULT_ANALYZE_MODEL, "results": [{"input": str(audio), "path": str(srt_out)}]} + ), + ): + tr = json.loads(handlers["gemini_transcribe"]({"inputs": [str(audio)], "format": "srt"})) + assert tr["success"] is True + assert "Hello world" in tr["results"][0]["content"] + + # Deep research defaults to background=True on action="run", with explicit background=False supported. + with patch( + "subprocess.run", + return_value=_completed_proc({"id": "int_res_42", "status": "in_progress"}), + ) as mock_run: + bg = json.loads(handlers["gemini_deep_research"]({"action": "run", "prompt": "Survey solid-state batteries"})) + assert bg["interaction_id"] == "int_res_42" + assert bg["background"] is True + bg_cmd = mock_run.call_args.args[0] + assert "--background" in bg_cmd and "--stream=false" in bg_cmd + assert bg_cmd[bg_cmd.index("--agent") + 1] == cli_tools.DEFAULT_RESEARCH_AGENT + + with patch( + "subprocess.run", + return_value=_completed_proc( + { + "id": "int_res_42", + "status": "completed", + "steps": [ + {"type": "user_input", "content": [{"type": "text", "text": "Prompt that must not leak"}]}, + { + "type": "model_output", + "content": [ + {"type": "thought", "text": "Internal reasoning"}, + {"type": "text", "text": "Final synthesis"}, + ], + }, + ], + } + ), + ) as mock_run: + fg = json.loads( + handlers["gemini_deep_research"]({"action": "run", "prompt": "Quick check", "background": False}) + ) + assert fg["background"] is False + assert "--background" not in mock_run.call_args.args[0] + assert fg["output_text"] == "Final synthesis" + + # Failed interactions exit 0 from CLI but must return a structured error with `.errors` details. + with patch( + "subprocess.run", + return_value=_completed_proc( + {"id": "int_res_fail", "status": "failed", "errors": [{"message": "Safety policy violation"}]} + ), + ): + failed_st = json.loads( + handlers["gemini_deep_research"]({"action": "status", "interaction_id": "int_res_fail"}) + ) + assert "error" in failed_st + assert failed_st["error_type"] == "api_error" + assert failed_st["status"] == "failed" + assert "Safety policy violation" in failed_st["error"] + + # Leading dash on agent ID is rejected locally. + bad_agent = json.loads( + handlers["gemini_deep_research"]({"action": "run", "prompt": "hi", "agent": "--evil"}) + ) + assert bad_agent["error_type"] == "invalid_argument" + + # Oversized transcript omits inline content and signals content_omitted=True. + big_srt = transcript_dir / "big.srt" + big_srt.write_text("x" * 40000, encoding="utf-8") + with patch( + "subprocess.run", + return_value=_completed_proc( + {"format": "srt", "model": cli_tools.DEFAULT_TRANSCRIBE_MODEL, "results": [{"input": str(audio), "path": str(big_srt)}]} + ), + ): + tr_big = json.loads(handlers["gemini_transcribe"]({"inputs": [str(audio)], "format": "srt"})) + assert tr_big["success"] is True + assert "content" not in tr_big["results"][0] + assert tr_big["results"][0]["content_omitted"] is True + + # Transcribe refuses to read back paths outside cache/transcripts or symlinks to blocked files. + outside_file = tmp_path / "outside.txt" + outside_file.write_text("should not be read back", encoding="utf-8") + auth_json = tmp_path / "auth.json" + auth_json.write_text('{"secret":"blocked"}', encoding="utf-8") + symlink_in_cache = transcript_dir / "escape.txt" + symlink_in_cache.symlink_to(auth_json) + with patch( + "subprocess.run", + return_value=_completed_proc( + { + "format": "text", + "model": cli_tools.DEFAULT_TRANSCRIBE_MODEL, + "results": [ + {"input": str(audio), "path": str(outside_file)}, + {"input": str(audio), "path": str(symlink_in_cache)}, + ], + } + ), + ): + tr_escape = json.loads(handlers["gemini_transcribe"]({"inputs": [str(audio)], "format": "text"})) + assert tr_escape["success"] is True + assert "content" not in tr_escape["results"][0] + assert "content" not in tr_escape["results"][1] + + # Missing audio output file from music/tts returns invalid_response instead of success. + with patch("subprocess.run", return_value=_completed_proc({"path": str(tmp_path / "missing.mp3")})): + missing_music = json.loads(handlers["gemini_music"]({"prompt": "piano"})) + assert missing_music["error_type"] == "invalid_response" + + with patch( + "subprocess.run", + return_value=_completed_proc( + {"id": "int_res_42", "status": "completed", "steps": [{"content": [{"type": "text", "text": "Final synthesis"}]}]} + ), + ): + st = json.loads(handlers["gemini_deep_research"]({"action": "status", "interaction_id": "int_res_42"})) + assert st["status"] == "completed" + assert st["output_text"] == "Final synthesis" + + with patch("subprocess.run", return_value=_completed_proc({"id": "int_res_42", "status": "cancelled"})): + cn = json.loads(handlers["gemini_deep_research"]({"action": "cancel", "interaction_id": "int_res_42"})) + assert cn["status"] == "cancelled" + + # Explicit files_upload tool returns reusable files/ handle. + sample = tmp_path / "deck.pdf" + sample.write_bytes(b"%PDF-1.4 deck") + with patch( + "subprocess.run", + return_value=_completed_proc({"name": "files/deck77", "uri": "https://x/files/deck77", "state": "ACTIVE"}), + ): + up = json.loads(handlers["gemini_files_upload"]({"path": str(sample), "display_name": "Q4 Deck"})) + assert up["success"] is True + assert up["name"] == "files/deck77" + + def test_security_hardening_symlinks_and_flag_injection_guards(self, runner, tmp_path): + handlers = cli_tools.build_tool_handlers(runner) + + # Symlink pointing to blocked credential file must be rejected by _validate_local_file / prepare_media_input. + auth_json = tmp_path / "auth.json" + auth_json.write_text('{"api_key":"blocked"}', encoding="utf-8") + link = tmp_path / "harmless.pdf" + link.symlink_to(auth_json) + ref, err, _ = runner.prepare_media_input(str(link)) + assert ref is None + assert err is not None and err.error_type == "invalid_argument" + assert "credential store" in err.error.lower() + + # Leading-dash display_name / mime_type / voice / multi_speaker / language rejected locally. + sample = tmp_path / "doc.pdf" + sample.write_bytes(b"%PDF-1.4") + with patch("subprocess.run") as mock_run: + bad_dn = json.loads(handlers["gemini_files_upload"]({"path": str(sample), "display_name": "--evil"})) + bad_mt = json.loads(handlers["gemini_files_upload"]({"path": str(sample), "mime_type": "--evil"})) + bad_voice = json.loads(handlers["gemini_tts"]({"text": "hi", "voice": "--evil"})) + bad_ms = json.loads(handlers["gemini_tts"]({"text": "hi", "multi_speaker": "--evil"})) + bad_lang = json.loads(handlers["gemini_tts"]({"text": "hi", "language": "--evil"})) + bad_ana_mt = json.loads(handlers["gemini_analyze"]({"inputs": [str(sample)], "mime_type": "--evil"})) + for res in (bad_dn, bad_mt, bad_voice, bad_ms, bad_lang, bad_ana_mt): + assert res["error_type"] == "invalid_argument" + mock_run.assert_not_called() + + # _strip_google_prefix drops leading-dash model IDs so they cannot inject CLI flags. + assert cli_tools._strip_google_prefix("--evil") is None + assert cli_tools._strip_google_prefix("google/--evil") is None + assert cli_tools._strip_google_prefix("google/") is None + + # Leading-dash system instructions use --system= so markdown bullets work safely. + with patch("subprocess.run", return_value=_completed_proc({"text": "ok"})) as mock_run: + ana = json.loads( + handlers["gemini_analyze"]({"inputs": [str(sample)], "system": "- Be concise", "model": "--ignored"}) + ) + assert ana["success"] is True + cmd = mock_run.call_args.args[0] + assert "-m" not in cmd + assert "--system=- Be concise" in cmd + + +class TestPluginManifestAndValidatorParity: + def test_plugin_registers_video_provider_tools_and_skill(self, tmp_path: Path, fake_cli_bin: Path): + from agent.video_gen_registry import get_provider as get_video_provider + from hermes_cli.plugins import get_plugin_manager + from tools.registry import registry + + user_plugin_dir = tmp_path / "plugins" / "gemini-api" + user_plugin_dir.mkdir(parents=True) + for fname in ("plugin.yaml", "__init__.py", "cli_runner.py", "cli_tools.py", "SKILL.md"): + shutil.copy2(_PLUGIN_ROOT / fname, user_plugin_dir / fname) + (tmp_path / "config.yaml").write_text( + yaml.safe_dump({ + "plugins": { + "enabled": ["gemini-api"], + "entries": {"gemini-api": {"settings": {"cli_path": str(fake_cli_bin)}}}, + } + }), + encoding="utf-8", + ) + + mgr = get_plugin_manager() + mgr.discover_and_load() + assert "gemini-api" in mgr._plugins + assert mgr._plugins["gemini-api"].enabled is True + + vid_provider = get_video_provider("gemini") + assert vid_provider is not None + assert vid_provider.is_available() is True + + registered_names = set(registry.get_all_tool_names()) + for tool_name in cli_tools.PROVIDED_TOOL_NAMES: + assert tool_name in registered_names + + assert mgr.list_plugin_skills("gemini-api") == ["gemini-api-cli"] + skill_path = mgr.find_plugin_skill("gemini-api:gemini-api-cli") + assert skill_path is not None and skill_path.exists() + + def test_hermes_plugin_validator_and_security_scanner_pass(self): + from hermes_cli.plugin_validate import validate_plugin_dir + try: + from hermes_cli.plugins_install_scan import scan_plugin + except ImportError: + from tools.plugin_guard import scan_plugin + + report = validate_plugin_dir(_PLUGIN_ROOT) + assert report.ok, f"Validation failed: {report.failures}" + # Only the single documented session-accounting seam (plugins.image_gen._common.record_token_usage) + # may emit a Rule 9 private-import warning until Hermes exposes a public token-accounting API. + unexpected_warnings = [ + w for w in report.warnings + if not ( + w.startswith("private core imports") + and "plugins.image_gen._common.record_token_usage" in w + and "; " not in w.split("): ", 1)[-1].split(". Use ctx.*", 1)[0] + ) + ] + assert not unexpected_warnings, f"Unexpected validation warnings: {unexpected_warnings}" + + scan = scan_plugin(_PLUGIN_ROOT, source="unit-test") + assert scan.verdict == "safe", f"Unexpected findings: {scan.findings}" diff --git a/tests/test_gemini_provider.py b/tests/test_gemini_provider.py index 018041d..40a9e4c 100644 --- a/tests/test_gemini_provider.py +++ b/tests/test_gemini_provider.py @@ -12,16 +12,19 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Tests for the Google AI Studio (Gemini / Nano Banana) image_gen plugin.""" +"""Tests for the Google AI Studio (Gemini / Nano Banana) image_gen provider backed by ``gemini-api image``.""" from __future__ import annotations +import base64 import importlib.util +import json import shutil +import subprocess import sys from pathlib import Path -from typing import Any, Dict -from unittest.mock import MagicMock, patch +from typing import Any, Dict, List +from unittest.mock import patch import pytest import yaml @@ -29,17 +32,17 @@ _PLUGIN_ROOT = Path(__file__).resolve().parent.parent _INIT_PATH = _PLUGIN_ROOT / "__init__.py" _SPEC = importlib.util.spec_from_file_location( - "hermes_plugins.gemini_image", + "hermes_plugins.gemini_api_img_test", _INIT_PATH, submodule_search_locations=[str(_PLUGIN_ROOT)], ) assert _SPEC is not None and _SPEC.loader is not None gemini_plugin = importlib.util.module_from_spec(_SPEC) -sys.modules["hermes_plugins.gemini_image"] = gemini_plugin +sys.modules["hermes_plugins.gemini_api_img_test"] = gemini_plugin _SPEC.loader.exec_module(gemini_plugin) +cli_runner = gemini_plugin._load_sibling_module("cli_runner") - -# 1×1 transparent PNG — valid bytes for save_b64_image() +# 1×1 transparent PNG — valid image bytes for magic-byte sniffing _PNG_HEX = ( "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4" "890000000d49444154789c6300010000000500010d0a2db40000000049454e44" @@ -48,37 +51,39 @@ def _b64_png() -> str: - import base64 + return base64.b64encode(bytes.fromhex(_PNG_HEX)).decode("ascii") - return base64.b64encode(bytes.fromhex(_PNG_HEX)).decode() +def _make_fake_binary(tmp_path: Path) -> Path: + bin_dir = tmp_path / "bin" + bin_dir.mkdir(parents=True, exist_ok=True) + binary = bin_dir / "gemini-api" + binary.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + binary.chmod(0o755) + return binary -def _fake_http_response(payload: Dict[str, Any], *, status_code: int = 200) -> MagicMock: - resp = MagicMock() - resp.status_code = status_code - resp.json.return_value = payload - if status_code >= 400: - import requests - resp.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Error", response=resp) - else: - resp.raise_for_status.return_value = None - return resp +def _completed_proc( + payload: Any = None, + *, + returncode: int = 0, + stderr_payload: Any = None, +) -> subprocess.CompletedProcess[str]: + stdout = json.dumps(payload) if payload is not None else "" + stderr = json.dumps(stderr_payload) if stderr_payload is not None else "" + return subprocess.CompletedProcess(args=["gemini-api"], returncode=returncode, stdout=stdout, stderr=stderr) -def _gemini_payload(*, b64: str | None = None, mime: str = "image/png", text: str = "Generated image", - usage: Dict[str, Any] | None = None) -> Dict[str, Any]: - parts = [{"text": text}] - if b64 is not None: - parts.append({"inlineData": {"mimeType": mime, "data": b64}}) - body: Dict[str, Any] = {"candidates": [{"content": {"parts": parts}, "finishReason": "STOP"}]} - if usage is not None: - body["usageMetadata"] = usage - return body +def _write_fake_output(tmp_path: Path, name: str = "gemini-image-1.png") -> Path: + out_file = tmp_path / "cache" / "generated" / "images" / name + out_file.parent.mkdir(parents=True, exist_ok=True) + out_file.write_bytes(bytes.fromhex(_PNG_HEX)) + return out_file @pytest.fixture(autouse=True) def _tmp_hermes_home(tmp_path, monkeypatch): + cli_runner.clear_cli_cache() monkeypatch.setenv("HERMES_HOME", str(tmp_path)) for var in ( "GEMINI_API_KEY", "GEMINI_IMAGE_MODEL", "GEMINI_BASE_URL", @@ -86,12 +91,23 @@ def _tmp_hermes_home(tmp_path, monkeypatch): ): monkeypatch.delenv(var, raising=False) yield tmp_path + cli_runner.clear_cli_cache() + + +@pytest.fixture +def fake_cli_bin(tmp_path): + return _make_fake_binary(tmp_path) @pytest.fixture -def provider(monkeypatch): +def provider(monkeypatch, fake_cli_bin): monkeypatch.setenv("GEMINI_API_KEY", "AQ.test-key") - return gemini_plugin.GeminiImageGenProvider() + runner = cli_runner.GeminiCLIRunner( + endpoint_resolver=gemini_plugin._resolve_endpoint, + user_agent=gemini_plugin.CLI_USER_AGENT, + cli_path=str(fake_cli_bin), + ) + return gemini_plugin.GeminiImageGenProvider(runner=runner) # ── Metadata & Setup Schema ───────────────────────────────────────────────── @@ -129,7 +145,6 @@ def test_setup_schema_uses_paid_badge_and_single_gemini_api_key(self, provider, assert schema["badge"] == "paid" assert [v["key"] for v in schema["env_vars"]] == ["GEMINI_API_KEY"] - # A user with GEMINI_API_KEY set must pass the tools_config readiness check monkeypatch.setenv("GEMINI_API_KEY", "AQ.gemini-only") assert _provider_env_ready(schema) is True @@ -138,12 +153,19 @@ def test_setup_schema_uses_paid_badge_and_single_gemini_api_key(self, provider, class TestAvailability: - def test_no_api_key_unavailable(self, monkeypatch): + def test_no_api_key_unavailable(self, monkeypatch, fake_cli_bin): monkeypatch.delenv("GEMINI_API_KEY", raising=False) assert gemini_plugin.GeminiImageGenProvider().is_available() is False - def test_api_key_set_available(self, monkeypatch): + def test_api_key_and_binary_required_for_availability(self, monkeypatch, tmp_path): monkeypatch.setenv("GEMINI_API_KEY", "AQ.test") + monkeypatch.setattr(shutil, "which", lambda _name: None) + monkeypatch.setattr(Path, "home", lambda: tmp_path / "empty-home") + with patch.object(cli_runner, "_is_executable_file", return_value=False): + assert gemini_plugin.GeminiImageGenProvider().is_available() is False + + _make_fake_binary(tmp_path) + cli_runner.clear_cli_cache() assert gemini_plugin.GeminiImageGenProvider().is_available() is True @@ -157,6 +179,10 @@ def test_env_var_override_and_google_prefix_stripping(self, monkeypatch): assert model_id == "gemini-3-pro-image" assert meta["api_model"] == "gemini-3-pro-image" + assert gemini_plugin._strip_google_prefix("--evil-flag") is None + assert gemini_plugin._strip_google_prefix("google/--evil-flag") is None + assert gemini_plugin._strip_google_prefix("google/") is None + def test_config_gemini_model_and_foreign_top_level_ignored(self, tmp_path): (tmp_path / "config.yaml").write_text( yaml.safe_dump({"image_gen": {"model": "gpt-image-2-medium", "gemini": {"model": "gemini-3.1-flash-lite-image"}}}) @@ -164,7 +190,6 @@ def test_config_gemini_model_and_foreign_top_level_ignored(self, tmp_path): model_id, _ = gemini_plugin._resolve_model() assert model_id == "gemini-3.1-flash-lite-image" - # When only a foreign top-level model is set, fallback to DEFAULT_MODEL (tmp_path / "config.yaml").write_text(yaml.safe_dump({"image_gen": {"model": "gpt-image-2-medium"}})) model_id, _ = gemini_plugin._resolve_model() assert model_id == gemini_plugin.DEFAULT_MODEL @@ -174,7 +199,7 @@ def test_config_gemini_model_and_foreign_top_level_ignored(self, tmp_path): class TestEndpointConfig: - def test_config_base_url_and_key_env_reach_availability_and_endpoint(self, monkeypatch, tmp_path): + def test_config_base_url_and_key_env_reach_availability_and_endpoint(self, monkeypatch, tmp_path, fake_cli_bin): monkeypatch.setenv("CUSTOM_GEMINI_TOKEN", "custom-secret") (tmp_path / "config.yaml").write_text(yaml.safe_dump({"image_gen": {"gemini": { "base_url": "https://proxy.example.com/v1beta/", "key_env": "CUSTOM_GEMINI_TOKEN"}}})) @@ -182,11 +207,11 @@ def test_config_base_url_and_key_env_reach_availability_and_endpoint(self, monke assert gemini_plugin._resolve_endpoint() == ("https://proxy.example.com/v1beta", "custom-secret") -# ── Generate ──────────────────────────────────────────────────────────────── +# ── Source image loading ──────────────────────────────────────────────────── class TestSourceImageLoading: - def test_load_image_bytes_blocks_credential_store(self, tmp_path, monkeypatch): + def test_load_image_bytes_blocks_credential_store_and_symlinks(self, tmp_path, monkeypatch): hermes_home = tmp_path / ".hermes" hermes_home.mkdir() auth_json = hermes_home / "auth.json" @@ -196,6 +221,14 @@ def test_load_image_bytes_blocks_credential_store(self, tmp_path, monkeypatch): with pytest.raises(ValueError, match="credential store"): gemini_plugin._load_image_bytes(str(auth_json)) + # A symlink pointing to a blocked credential file must also be rejected after resolution. + symlink_path = tmp_path / "innocent.png" + symlink_path.symlink_to(auth_json) + with pytest.raises(ValueError, match="credential store"): + gemini_plugin._load_image_bytes(str(symlink_path)) + with pytest.raises(ValueError, match="credential store"): + gemini_plugin._sniff_local_image_mime(str(symlink_path)) + def test_load_image_bytes_allows_legit_local_image(self, tmp_path): img = tmp_path / "pic.png" img.write_bytes(bytes.fromhex(_PNG_HEX)) @@ -215,108 +248,88 @@ def test_load_image_bytes_decodes_whitespace_wrapped_data_uri_and_rejects_corrup gemini_plugin._load_image_bytes("data:image/png;base64,!!!not-valid-base64!!!") +# ── Generate (via gemini-api image CLI) ───────────────────────────────────── + + class TestGenerate: def test_empty_prompt_rejected(self, provider): result = provider.generate(" ", aspect_ratio="square") assert result["success"] is False assert result["error_type"] == "invalid_argument" - def test_missing_api_key(self, monkeypatch): + def test_missing_api_key(self, monkeypatch, fake_cli_bin): monkeypatch.delenv("GEMINI_API_KEY", raising=False) result = gemini_plugin.GeminiImageGenProvider().generate("a yellow banana") assert result["success"] is False assert result["error_type"] == "auth_required" - def test_b64_saves_to_cache_and_sends_x_goog_api_key_header(self, provider, tmp_path): - png_bytes = bytes.fromhex(_PNG_HEX) - fake_resp = _fake_http_response(_gemini_payload(b64=_b64_png(), mime="image/jpeg")) + def test_cli_image_saves_to_cache_and_omits_default_m_flag(self, provider, tmp_path): + out_img = _write_fake_output(tmp_path, "gemini-image-out.png") + proc = _completed_proc({ + "path": str(out_img), + "kind": "image", + "mime_type": "image/png", + "size_bytes": out_img.stat().st_size, + "response_id": "int_img_1", + "status": "completed", + }) - with patch("requests.post", return_value=fake_resp) as mock_post: + with patch("subprocess.run", return_value=proc) as mock_run: result = provider.generate("a cute nano banana", aspect_ratio="landscape") assert result["success"] is True + assert result["image"] == str(out_img) assert result["model"] == gemini_plugin.DEFAULT_MODEL assert result["aspect_ratio"] == "landscape" assert result["exact_aspect_ratio"] == "16:9" assert result["provider"] == "gemini" assert result["modality"] == "text" - - saved = Path(result["image"]) - assert saved.exists() - assert saved.suffix == ".jpg" - assert saved.parent in (tmp_path / "cache" / "generated" / "images", tmp_path / "cache" / "images") - assert saved.read_bytes() == png_bytes - - called_url = mock_post.call_args.args[0] - assert called_url == ( - f"https://generativelanguage.googleapis.com/v1beta/models/{gemini_plugin.DEFAULT_MODEL}:generateContent" - ) - assert "key=" not in called_url - assert mock_post.call_args.kwargs["headers"]["x-goog-api-key"] == "AQ.test-key" - ua = mock_post.call_args.kwargs["headers"]["User-Agent"] - assert ua == gemini_plugin.USER_AGENT - assert gemini_plugin.HERMES_VERSION in ua - assert f"gemini-image/{gemini_plugin.PLUGIN_VERSION}" in ua - assert mock_post.call_args.kwargs["json"]["generationConfig"]["imageConfig"] == {"aspectRatio": "16:9"} - - @pytest.mark.parametrize("has_image", [True, False]) - def test_token_usage_reaches_session_accounting(self, provider, has_image): - """Gemini bills per token: ``usageMetadata`` lands as an ``image_generation`` row - even when a billed HTTP 200 carries only a text refusal and no image.""" + assert result["response_id"] == "int_img_1" + + cmd = mock_run.call_args.args[0] + assert cmd[1] == "image" + assert "-m" not in cmd + assert cmd[cmd.index("--out") + 1] == str(tmp_path / "cache" / "generated" / "images") + assert cmd[cmd.index("--aspect-ratio") + 1] == "16:9" + assert cmd[cmd.index("--") + 1:] == ["a cute nano banana"] + header_val = cmd[cmd.index("--header") + 1] + assert header_val == f"User-Agent: {gemini_plugin.CLI_USER_AGENT}" + assert mock_run.call_args.kwargs["env"]["GEMINI_API_KEY"] == "AQ.test-key" + + def test_token_usage_reaches_session_accounting(self, provider, tmp_path): from agent import aux_accounting - recorded = [] + recorded: List[Any] = [] class _DB: def record_auxiliary_usage(self, *args, **kwargs): recorded.append((args, kwargs)) - payload = _gemini_payload( - b64=_b64_png() if has_image else None, - text="Here is your image" if has_image else "I cannot generate that image", - usage={"promptTokenCount": 42, "candidatesTokenCount": 1290, "totalTokenCount": 1332}, - ) - token = aux_accounting.set_accounting_context(_DB(), "sess-gemini-1") + out_img = _write_fake_output(tmp_path) + proc = _completed_proc({ + "path": str(out_img), + "kind": "image", + "mime_type": "image/png", + "usage": { + "total_input_tokens": 42, + "total_output_tokens": 1290, + "total_thought_tokens": 668, + "total_tokens": 2000, + }, + }) + token = aux_accounting.set_accounting_context(_DB(), "sess-gemini-img-1") try: - with patch("requests.post", return_value=_fake_http_response(payload)): + with patch("subprocess.run", return_value=proc): result = provider.generate("a yellow banana", aspect_ratio="landscape") finally: aux_accounting.reset_accounting_context(token) - assert result["success"] is has_image - if not has_image: - assert result["error_type"] == "empty_response" - assert "I cannot generate that image" in result["error"] + assert result["success"] is True ((session_id, task), kwargs), = recorded - assert (session_id, task) == ("sess-gemini-1", "image_generation") + assert (session_id, task) == ("sess-gemini-img-1", "image_generation") assert (kwargs["model"], kwargs["billing_provider"]) == (gemini_plugin.DEFAULT_MODEL, "gemini") - assert (kwargs["input_tokens"], kwargs["output_tokens"]) == (42, 1290) - - def test_thinking_tokens_counted_as_output(self, provider): - """Nano Banana 2.1 and Nano Banana Pro reason before they draw, and ``totalTokenCount`` bills those tokens, so - they belong in the output count — otherwise the row does not reconcile with the total.""" - from agent import aux_accounting - - recorded = [] - - class _DB: - def record_auxiliary_usage(self, *args, **kwargs): - recorded.append(kwargs) - - payload = _gemini_payload(b64=_b64_png(), usage={ - "promptTokenCount": 42, "candidatesTokenCount": 1290, - "thoughtsTokenCount": 668, "totalTokenCount": 2000, - }) - token = aux_accounting.set_accounting_context(_DB(), "sess-gemini-2") - try: - with patch("requests.post", return_value=_fake_http_response(payload)): - assert provider.generate("a yellow banana")["success"] is True - finally: - aux_accounting.reset_accounting_context(token) - - kwargs, = recorded + assert kwargs["input_tokens"] == 42 assert kwargs["output_tokens"] == 1290 + 668 - assert kwargs["input_tokens"] + kwargs["output_tokens"] == 2000 @pytest.mark.parametrize( "model_id,expected_upscale", @@ -330,15 +343,12 @@ def record_auxiliary_usage(self, *args, **kwargs): def test_upscale_advertised_only_when_model_has_a_rung_above_1k( self, provider, monkeypatch, model_id, expected_upscale ): - """The lite model is 1K-only, so the tool should not offer it an upscale it cannot honour.""" monkeypatch.setenv("GEMINI_IMAGE_MODEL", model_id) assert provider.capabilities()["supports_upscale"] is expected_upscale def test_config_exact_aspect_ratio_image_size_and_google_search_override_defaults( self, provider, monkeypatch, tmp_path ): - """config.yaml is the sole home for aspect_ratio, image_size, and google_search; - non-secret GEMINI_IMAGE_* env knobs are ignored.""" monkeypatch.setenv("GEMINI_IMAGE_ASPECT_RATIO", "4:5") monkeypatch.setenv("GEMINI_IMAGE_SIZE", "512") monkeypatch.setenv("GEMINI_IMAGE_GOOGLE_SEARCH", "false") @@ -353,67 +363,82 @@ def test_config_exact_aspect_ratio_image_size_and_google_search_override_default } }) ) + out_img = _write_fake_output(tmp_path) + proc = _completed_proc({"path": str(out_img), "mime_type": "image/png"}) - with patch("requests.post", return_value=_fake_http_response(_gemini_payload(b64=_b64_png()))) as mock_post: + with patch("subprocess.run", return_value=proc) as mock_run: result = provider.generate("ultrawide banner", aspect_ratio="landscape") assert result["success"] is True assert result["exact_aspect_ratio"] == "21:9" assert result["image_size"] == "2K" assert result["google_search"] is True - sent = mock_post.call_args.kwargs["json"] - assert sent["generationConfig"]["imageConfig"] == {"aspectRatio": "21:9", "imageSize": "2K"} - assert sent["tools"] == [{"googleSearch": {}}] + cmd = mock_run.call_args.args[0] + assert cmd[cmd.index("--aspect-ratio") + 1] == "21:9" + assert cmd[cmd.index("--image-size") + 1] == "2K" + assert json.loads(cmd[cmd.index("--body") + 1]) == {"tools": [{"type": "google_search"}]} - def test_reference_images_sent_before_text_prompt(self, provider, tmp_path): + def test_reference_images_passed_via_i_flag_and_data_uri_cleaned_up(self, provider, tmp_path): ref_path = tmp_path / "ref.png" ref_path.write_bytes(bytes.fromhex(_PNG_HEX)) - - with patch("requests.post", return_value=_fake_http_response(_gemini_payload(b64=_b64_png()))) as mock_post: - result = provider.generate("make it cyberpunk", image_url=str(ref_path)) + data_uri = f"data:image/png;base64,{_b64_png()}" + out_img = _write_fake_output(tmp_path) + proc = _completed_proc({"path": str(out_img), "mime_type": "image/png"}) + + seen_inputs: List[str] = [] + + def _capture(argv, **_kwargs): + for idx, tok in enumerate(argv): + if tok == "-i": + seen_inputs.append(argv[idx + 1]) + assert Path(seen_inputs[1]).is_file() + return proc + + with patch("subprocess.run", side_effect=_capture): + result = provider.generate( + "make it cyberpunk", + image_url=str(ref_path), + reference_image_urls=[data_uri, "files/ref42"], + ) assert result["success"] is True assert result["modality"] == "image" - parts = mock_post.call_args.kwargs["json"]["contents"][0]["parts"] - assert len(parts) == 2 - assert parts[0]["inlineData"]["mimeType"] == "image/png" - assert parts[0]["inlineData"]["data"] == _b64_png() - assert parts[1] == {"text": "make it cyberpunk"} - - def test_caller_model_honoured_only_when_it_names_a_catalog_entry(self, provider): - """A catalog id from the caller wins; a foreign one falls back instead of reaching the wire. - - ``image_generate`` forwards the shared, provider-agnostic ``image_gen.model`` down as this - kwarg, so it can legitimately name some other backend's model. - """ - with patch("requests.post", return_value=_fake_http_response(_gemini_payload(b64=_b64_png()))) as mock_post: + assert seen_inputs[0] == str(ref_path) + assert seen_inputs[2] == "files/ref42" + assert not Path(seen_inputs[1]).exists() # temp file cleaned up after CLI exit + + def test_caller_model_honoured_only_when_it_names_a_catalog_entry(self, provider, tmp_path): + out_img = _write_fake_output(tmp_path) + proc = _completed_proc({"path": str(out_img), "mime_type": "image/png"}) + + with patch("subprocess.run", return_value=proc) as mock_run: result = provider.generate("a yellow banana", model="gemini-3-pro-image") assert result["model"] == "gemini-3-pro-image" - assert mock_post.call_args.args[0].endswith("/models/gemini-3-pro-image:generateContent") + cmd = mock_run.call_args.args[0] + assert cmd[cmd.index("-m") + 1] == "gemini-3-pro-image" - with patch("requests.post", return_value=_fake_http_response(_gemini_payload(b64=_b64_png()))) as mock_post: + with patch("subprocess.run", return_value=proc) as mock_run: result = provider.generate("a yellow banana", model="gpt-image-2-medium") assert result["success"] is True assert result["model"] == gemini_plugin.DEFAULT_MODEL - assert mock_post.call_args.args[0].endswith( - f"/models/{gemini_plugin.DEFAULT_MODEL}:generateContent") + assert "-m" not in mock_run.call_args.args[0] def test_provider_scoped_custom_model_passes_through_conservatively(self, provider, tmp_path): - """An id under ``image_gen.gemini.model`` is a deliberate opt-in, so a model this catalog - predates still reaches the wire — but without ``imageSize`` or search, which it may reject. - """ (tmp_path / "config.yaml").write_text(yaml.safe_dump({ "image_gen": {"gemini": { "model": "gemini-unlisted-test-image", "image_size": "4K", "google_search": True}}})) - with patch("requests.post", return_value=_fake_http_response(_gemini_payload(b64=_b64_png()))) as mock_post: + out_img = _write_fake_output(tmp_path) + proc = _completed_proc({"path": str(out_img), "mime_type": "image/png"}) + + with patch("subprocess.run", return_value=proc) as mock_run: result = provider.generate("a yellow banana") assert result["success"] is True assert result["model"] == "gemini-unlisted-test-image" - assert mock_post.call_args.args[0].endswith("/models/gemini-unlisted-test-image:generateContent") - sent = mock_post.call_args.kwargs["json"] - assert "imageSize" not in sent["generationConfig"]["imageConfig"] - assert "tools" not in sent + cmd = mock_run.call_args.args[0] + assert cmd[cmd.index("-m") + 1] == "gemini-unlisted-test-image" + assert "--image-size" not in cmd + assert "--body" not in cmd @pytest.mark.parametrize( "model_id,expected_wire_ratio,expected_search,expected_512_size", @@ -427,56 +452,87 @@ def test_provider_scoped_custom_model_passes_through_conservatively(self, provid def test_per_model_gating_for_extreme_aspect_ratios_and_google_search( self, provider, tmp_path, model_id, expected_wire_ratio, expected_search, expected_512_size ): - # Grounding and 512px resolution are gated per model via MODELS metadata. (tmp_path / "config.yaml").write_text( yaml.safe_dump({"image_gen": {"gemini": {"google_search": True, "image_size": "512"}}}) ) - with patch("requests.post", return_value=_fake_http_response(_gemini_payload(b64=_b64_png()))) as mock_post: + out_img = _write_fake_output(tmp_path) + proc = _completed_proc({"path": str(out_img), "mime_type": "image/png"}) + + with patch("subprocess.run", return_value=proc) as mock_run: result = provider.generate("panoramic poster", aspect_ratio="1:4", model=model_id) assert result["success"] is True assert result["exact_aspect_ratio"] == expected_wire_ratio assert result.get("google_search", False) is expected_search assert result.get("image_size") == expected_512_size - sent = mock_post.call_args.kwargs["json"] - assert sent["generationConfig"]["imageConfig"]["aspectRatio"] == expected_wire_ratio - assert sent["generationConfig"]["imageConfig"].get("imageSize") == expected_512_size - assert ("tools" in sent) is expected_search - - def test_reference_images_over_total_request_limit_rejected(self, provider, monkeypatch, tmp_path): - """Each image can be under the per-image cap while the assembled request is not.""" - monkeypatch.setattr(gemini_plugin, "_MAX_INLINE_REQUEST_BYTES", 1024) - big = tmp_path / "big.png" - big.write_bytes(bytes.fromhex(_PNG_HEX) + b"\x00" * 4096) - - with patch("requests.post") as mock_post: - result = provider.generate("combine these", reference_image_urls=[str(big), str(big)]) + cmd = mock_run.call_args.args[0] + assert cmd[cmd.index("--aspect-ratio") + 1] == expected_wire_ratio + if expected_512_size: + assert cmd[cmd.index("--image-size") + 1] == expected_512_size + else: + assert "--image-size" not in cmd + assert ("--body" in cmd) is expected_search + + def test_reference_images_over_inline_budget_auto_upload_via_files_api( + self, provider, monkeypatch, tmp_path + ): + """Oversized reference image batches seamlessly auto-upload through Gemini Files API.""" + monkeypatch.setattr(cli_runner, "CLI_CUMULATIVE_INLINE_BYTES", 128) + ref1 = tmp_path / "r1.png" + ref2 = tmp_path / "r2.png" + ref1.write_bytes(bytes.fromhex(_PNG_HEX)) + ref2.write_bytes(bytes.fromhex(_PNG_HEX) + b"\x00" * 128) + out_img = _write_fake_output(tmp_path) + + upload_proc = _completed_proc({"name": "files/imgref2", "state": "ACTIVE"}) + image_proc = _completed_proc({"path": str(out_img), "mime_type": "image/png"}) + with patch("subprocess.run", side_effect=[upload_proc, image_proc]) as mock_run: + result = provider.generate("combine these", reference_image_urls=[str(ref1), str(ref2)]) - assert result["success"] is False - assert "total request limit" in result["error"] - mock_post.assert_not_called() + assert result["success"] is True + assert mock_run.call_args_list[0].args[0][1:3] == ["files", "upload"] + img_cmd = mock_run.call_args_list[1].args[0] + assert "files/imgref2" in img_cmd - def test_non_image_local_file_rejected_before_upload(self, provider, tmp_path): - """A text file named .png fails locally rather than as an opaque remote 400.""" + def test_non_image_local_file_rejected_before_cli_call(self, provider, tmp_path): decoy = tmp_path / "notes.png" decoy.write_text("this is not an image") - with patch("requests.post") as mock_post: + with patch("subprocess.run") as mock_run: result = provider.generate("edit this", image_url=str(decoy)) assert result["success"] is False assert "not a recognised image" in result["error"] - mock_post.assert_not_called() + mock_run.assert_not_called() - def test_http_error_surfaces_api_message(self, provider): - err_resp = _fake_http_response({"error": {"message": "API key not valid"}}, status_code=403) - with patch("requests.post", return_value=err_resp): + def test_cli_auth_error_and_missing_output_file_surfaced(self, provider, tmp_path): + err_proc = _completed_proc( + returncode=3, + stderr_payload={"error": "API key not valid", "exit_code": 3}, + ) + with patch("subprocess.run", return_value=err_proc): result = provider.generate("a cat") assert result["success"] is False assert result["error_type"] == "auth_required" assert "API key not valid" in result["error"] + missing_proc = _completed_proc({"path": str(tmp_path / "does-not-exist.png")}) + with patch("subprocess.run", return_value=missing_proc): + missing = provider.generate("a cat") + assert missing["success"] is False + assert missing["error_type"] == "invalid_response" + + def test_cleartext_remote_base_url_rejected_before_cli_call(self, provider, monkeypatch): + monkeypatch.setenv("GEMINI_BASE_URL", "http://evil.example.com/v1beta") + with patch("subprocess.run") as mock_run: + result = provider.generate("a cat") + + assert result["success"] is False + assert result["error_type"] == "invalid_argument" + assert "https://" in result["error"] + mock_run.assert_not_called() + # ── Plugin registration ───────────────────────────────────────────────────── @@ -486,18 +542,20 @@ def test_user_installed_plugin_registers_in_image_gen_registry(self, tmp_path): from agent.image_gen_registry import get_provider from hermes_cli.plugins import get_plugin_manager - user_plugin_dir = tmp_path / "plugins" / "gemini-image" + user_plugin_dir = tmp_path / "plugins" / "gemini-api" user_plugin_dir.mkdir(parents=True) - shutil.copy2(_PLUGIN_ROOT / "plugin.yaml", user_plugin_dir / "plugin.yaml") - shutil.copy2(_PLUGIN_ROOT / "__init__.py", user_plugin_dir / "__init__.py") + for fname in ("plugin.yaml", "__init__.py", "cli_runner.py", "cli_tools.py", "SKILL.md"): + src = _PLUGIN_ROOT / fname + if src.is_file(): + shutil.copy2(src, user_plugin_dir / fname) (tmp_path / "config.yaml").write_text( - yaml.safe_dump({"plugins": {"enabled": ["gemini-image"]}}) + yaml.safe_dump({"plugins": {"enabled": ["gemini-api"]}}) ) mgr = get_plugin_manager() mgr.discover_and_load() - assert "gemini-image" in mgr._plugins - assert mgr._plugins["gemini-image"].enabled is True + assert "gemini-api" in mgr._plugins + assert mgr._plugins["gemini-api"].enabled is True registered = get_provider("gemini") assert registered is not None assert registered.name == "gemini"