Skip to content

feat: gemini-api-cli (WIP - Blocked) - #3

Closed
gabbyong wants to merge 3 commits into
mainfrom
feat/gemini-api-cli
Closed

gabbyong wants to merge 3 commits into
mainfrom
feat/gemini-api-cli

Conversation

@gabbyong

Copy link
Copy Markdown
Contributor

Summary

Upgrades the plugin from v0.1.0 (gemini-image) to v0.2.0 (gemini-api), powered end-to-end by google-gemini/gemini-api-cli (v0.5.0, Interactions API) under a single GEMINI_API_KEY:

  • Unified Image Generation (image_gen.provider: gemini): Migrates GeminiImageGenProvider from direct REST to gemini-api image, sharing a single GeminiCLIRunner and unified User-Agent across all providers and tools. Preserves Nano Banana 2.1 (gemini-nano-banana-2.1) as default, exact aspect ratios, resolution gating (1K/2K/4K, 512 on gemini-3.1-flash-image), optional Google Search grounding, and multi-reference editing with Files API auto-upload above inline limits.
  • Video Generation (video_gen.provider: gemini): Adds GeminiVideoGenProvider backed by gemini-api video (gemini-omni-1.2-flash), forwarding --aspect-ratio, --resolution, and -i reference images (avoiding argv size limits) and saving MP4 outputs under $HERMES_HOME/cache/videos/.
  • Six Structured Tools (gemini_api toolset) + Bundled Skill:
    • gemini_music (lyria-3.5)
    • gemini_tts (gemini-3.8-flash-tts, single-speaker voices & two-speaker scripts)
    • gemini_analyze (gemini-4-hydrogen, multimodal files, files/<id>, and YouTube URLs with auto-upload >14 MiB)
    • gemini_transcribe (gemini-3.5-transcribe, md/text/json/srt outputs)
    • gemini_deep_research (deep-research-preview-04-2026, async run / status / cancel with structured error surfacing)
    • gemini_files_upload (resumable Gemini Files API upload up to 2 GB)
    • Bundled SKILL.md (gemini-api-cli) for ad-hoc CLI usage.
  • Security & Reliability Hardening:
    • Pins gemini-api v0.5.0 with hardcoded SHA-256 digests across all 6 release targets, 64 MiB download cap, thread-safe atomic installs (opt-in auto_install_cli: false by default).
    • Runs subprocesses with --no-interactive -o json, stdin=DEVNULL, -- end-of-flags delimiter, and an allowlisted secret-scrubbed environment carrying only the active GEMINI_API_KEY.
    • Enforces https:// base URL validation (loopback http:// only for local testing), SSRF-safe remote image fetching, and agent.file_safety.raise_if_read_blocked on local file inputs.
    • Replaces private Hermes core imports in __init__.py and cli_runner.py with public plugin APIs (leaving only the single session token-accounting seam).

Verification

  • Unit tests: 50 passed (tests/test_gemini_provider.py + tests/test_gemini_cli_plugin.py) against Hermes Agent.
  • Hermes validator: hermes plugins validate . passed (security scan — safe, capability probe passed, zero tool collisions).
  • Live end-to-end testing against the Gemini API with gemini-api v0.5.0:
    • image_generate (gemini-nano-banana-2.1, 16:9 → 1376×768 JPEG)
    • gemini_tts (gemini-3.8-flash-tts, voice Kore → 24 kHz WAV)
    • gemini_analyze (multimodal image analysis verified on gemini-4-neon)
    • gemini_transcribe (gemini-3.5-transcribe, verbatim text transcript of the generated WAV)
    • gemini_music (lyria-3.5 → 44.1 kHz stereo MP3)
    • video_generate (gemini-omni-1.2-flash, 9:16 720p → 720×1280 H.264 + 48 kHz AAC MP4)
    • gemini_deep_research (deep-research-preview-04-2026, async run + status poll)

Sample Tests

1. Image gen (gemini-api image): Generate a 16:9 image of a glass terrarium on a wooden desk using image_generate.
2. TTS (gemini_tts): Use gemini_tts with voice Kore to say "Hello from the Hermes Gemini API plugin."
3. Multimodal analyze (gemini_analyze): Use gemini_analyze on the image file you just generated and describe 3 visual details.
4. Transcribe (gemini_transcribe): Use gemini_transcribe on the WAV file you just generated with format "text".
5. Music (gemini_music): Use gemini_music to generate a short upbeat lo-fi acoustic guitar loop.
6. Video gen (gemini-api video): Generate a 9:16 720p video of ocean waves at sunset using video_generate.
7. Deep Research async run + status (gemini_deep_research): Start a background gemini_deep_research run on "2026 solid-state battery breakthroughs", then poll its status once using the returned interaction_id.

…d video provider

Upgrades the plugin slug from gemini-image to gemini-api (v0.2.0) and wraps the official gemini-api Go binary to register a native Hermes video generation provider alongside six structured tools for music, TTS, media analysis, transcription, Deep Research, and Files API uploads. Binary media inputs over 14 MiB (or multi-file batches exceeding 19 MiB base64) are seamlessly uploaded through the Gemini Files API before invoking the CLI, with opt-in binary installation and verified SHA-256 checksums.
… and hardened subprocess execution

- Migrate GeminiImageGenProvider from direct REST to `gemini-api image` (Interactions API) so image, video, and all 6 structured tools share a single GeminiCLIRunner and User-Agent
- Pin gemini-api CLI v0.5.0 with hardcoded SHA-256 checksum verification, thread-safe atomic installs, allowlisted secret-scrubbed subprocess env, and shared HTTPS base URL validation
- Update default models/agents for v0.5.0 (`gemini-nano-banana-2.1`, `gemini-omni-1.2-flash`, `lyria-3.5`, `gemini-3.8-flash-tts`, `gemini-4-hydrogen`, `gemini-3.5-transcribe`, `deep-research-preview-04-2026`)
- Forward `--aspect-ratio`, `--resolution`, and `-i` reference images on `video_generate`, surface Deep Research failure errors, and reconcile Interactions/porcelain token usage into Hermes session accounting
- Replace private Hermes core imports in `__init__.py` and `cli_runner.py` with public plugin APIs (verified with `hermes plugins validate` and 50/50 pytest suite)
@gabbyong gabbyong changed the title Feat/gemini api cli Feat/gemini-api-cli Nov 25, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request transitions the Google AI Studio Gemini plugin for Hermes to be powered end-to-end by the official gemini-api CLI, introducing support for video generation, music generation, text-to-speech, multimodal analysis, transcription, and Deep Research. The review feedback focuses on critical security hardening. Specifically, it highlights several path traversal risks where symlinks must be resolved using .resolve() before performing file safety checks. Additionally, it identifies multiple flag injection vulnerabilities across various CLI commands, recommending validation to ensure that parameters such as model IDs, voice names, languages, and MIME types do not start with a dash.

Comment thread __init__.py Outdated
Comment on lines 424 to 425
raise_if_read_blocked(ref)
path = Path(os.path.expanduser(ref))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

Resolve symlinks using .resolve() before performing the file safety checks and reading the file. If ref is a symlink pointing to a blocked/sensitive file (e.g., ~/.hermes/auth.json), checking only the symlink path itself can bypass the raise_if_read_blocked check, leading to an arbitrary file read vulnerability.

    raise_if_read_blocked(ref)
    path = Path(os.path.expanduser(ref)).resolve()
    raise_if_read_blocked(str(path))

Comment thread cli_runner.py Outdated
Comment on lines +739 to +741
raise_if_read_blocked(cleaned)
abs_str = os.path.abspath(os.path.expanduser(cleaned))
raise_if_read_blocked(abs_str)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

Resolve symlinks using .resolve() to prevent symlink bypass of the raise_if_read_blocked security check. If a symlink points to a blocked file, checking only the symlink path itself allows the check to pass while the underlying file is still read/processed.

Suggested change
raise_if_read_blocked(cleaned)
abs_str = os.path.abspath(os.path.expanduser(cleaned))
raise_if_read_blocked(abs_str)
raise_if_read_blocked(cleaned)
resolved_path = Path(os.path.expanduser(cleaned)).resolve()
raise_if_read_blocked(str(resolved_path))
abs_str = str(resolved_path)

Comment thread cli_runner.py Outdated
Comment on lines +786 to +789
if display_name and display_name.strip():
args.extend(["--display-name", display_name.strip()])
if mime_type and mime_type.strip():
args.extend(["--mime-type", mime_type.strip()])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

Validate that display_name and mime_type do not start with a dash (-) to prevent flag injection attacks on the files upload command.

        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])

Comment thread cli_tools.py Outdated
Comment on lines +140 to +144
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

Harden _strip_google_prefix against flag injection by ensuring that the returned model ID does not start with a dash (-). This prevents malicious or malformed model parameters from being interpreted as command-line flags by the underlying gemini-api CLI.

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 cleaned.startswith(\"-\") else cleaned

Comment thread cli_tools.py
Comment on lines +689 to +691
multi_speaker = str(args.get("multi_speaker") or "").strip()
voice = str(args.get("voice") or "").strip()
if multi_speaker and voice:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

Validate that multi_speaker and voice do not start with a dash (-) to prevent flag injection attacks on the tts command.

        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:

Comment thread cli_tools.py
Comment on lines +705 to +707
language = str(args.get("language") or "").strip()
if language:
cmd_args.extend(["--language", language])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

Validate that language does not start with a dash (-) to prevent flag injection attacks on the tts command.

        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])

Comment thread cli_tools.py
Comment on lines +738 to +740
mime_type = str(args.get("mime_type") or "").strip()
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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

Validate that mime_type does not start with a dash (-) to prevent flag injection attacks on the analyze command.

        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\")

Comment thread cli_tools.py Outdated
Comment on lines +833 to +841
out_path = entry.get("path")
if isinstance(out_path, str) and Path(out_path).is_file():
try:
text_body = Path(out_path).read_text(encoding="utf-8", errors="replace")
if len(text_body) <= 32768:
item_out["content"] = text_body
else:
item_out["content_omitted"] = True
except OSError:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

Perform file safety checks (raise_if_read_blocked) and resolve symlinks on out_path before reading the transcript file. This prevents potential arbitrary file read vulnerabilities if the CLI output is manipulated or contains unexpected paths.

            if isinstance(out_path, str):
                try:
                    from agent.file_safety import raise_if_read_blocked
                    raise_if_read_blocked(out_path)
                    resolved_out = Path(out_path).resolve()
                    raise_if_read_blocked(str(resolved_out))
                    if 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:
                    pass

… I/O per PR review

- Resolve symlinks via Path.resolve() before raise_if_read_blocked checks in image loading, CLI local file validation, and transcript readback (plus enforce cache/transcripts containment on transcript readback)
- Reject leading-dash flag values on display_name, mime_type, voice, multi_speaker, language, and model prefix stripping; serialize --system=<value> safely
- Sniff local reference image MIME types from the first 16 bytes instead of reading up to 25 MB into memory, deduplicate image/video reference preparation into GeminiCLIRunner.prepare_image_input, and reuse cached config.yaml lookups
- Enable follow_redirects and Content-Length pre-check when fetching remote reference image URLs
- Add regression tests for symlink bypasses, out-of-cache transcript readback, and flag injection (51/51 passing)
@gabbyong gabbyong changed the title Feat/gemini-api-cli feat: gemini-api-cli (WIP - Blocked) Nov 26, 2026
@gabbyong

Copy link
Copy Markdown
Contributor Author

Closing first as we are deprioritising integrating gemini-api-cli, will reopen when ready

@gabbyong gabbyong closed this Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant