npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

opencode-gemini-grounding

v1.3.0

Published

OpenCode V2 plugin for Gemini Google Search Grounding with academic-style inline citations, sources list, dynamic model selection, and automatic fallback chain.

Readme

opencode-gemini-grounding


🌟 Overview

opencode-gemini-grounding is a high-performance web search extension developed strictly following the OpenCode V2 plugin specification. Regardless of your active primary model (Claude, DeepSeek, GPT, or local models), this plugin equips it with real-time web search, fact verification, and source attribution capabilities.

Unlike standard web search tools, it returns concise, fact-checked answers accompanied by academic-style inline citations ([1], [2]) calculated through a UTF-8 byte offset reverse-slicing algorithm, complete with verified source URLs and actual search queries.


✨ Features

  • 🚀 Native OpenCode V2 Architecture: Built strictly on OpenCode V2's id + setup(ctx) lifecycle, integrating deeply with ctx.tool, ctx.websearch, ctx.storage, and context.progress.
  • 🌐 Dual-Entry Search Architecture (WebSearch + Custom Tool):
    • System WebSearch Provider (ctx.websearch): Automatically registers as an OpenCode V2 default websearch provider for seamless, transparent search in everyday conversations;
    • Custom Professional Tool (ctx.tool): Exposes google_grounding and websearch_cited under the Code Mode search namespace (tools.search.google_grounding) with full parameter control.
  • 🎯 Smart Anti-Bloat Slicing (Independent Clickable Cards):
    • Every discovered source is rendered as an independent clickable card in the UI, allowing instant navigation to any specific webpage;
    • The first card carries the complete synthesis report, while subsequent cards extract concise cited sentence snippets—saving ~87.5% duplicate tokens (20,000+ context tokens saved per search).
  • ⚡ Native Persistent Caching (ctx.storage): Sandboxed key-value caching with configurable TTL (default 10m). Repeating queries return in 0ms with zero token cost and immunity to HTTP 429 limits.
  • 🔔 Live Progress Feedback (context.progress): Real-time status reporting in TUI and Web UI ("Searching Google...", "Found cached results", "Falling back to next model...").
  • ⚙️ Standardized ctx.options Configuration: Structured plugin configuration via opencode.jsonc with support for {env:VAR} automatic resolution.
  • ⚡ Automatic Fallback Chain: Built-in fault tolerance—configured with a generous 45s per-model timeout and 180s (3 min) total timeout. Automatically rotates through candidate models on rate limits (HTTP 429) or gateway blips (502/503), while immediately halting on fatal auth errors (401/403).
  • 🧠 Dynamic Model Switching & Normalization: Supports runtime model selection per search call; automatically strips provider prefixes like google/ to prevent 404s.
  • 📍 Academic-Style Precision Citations & Clean Markdown: Calculates exact UTF-8 byte offsets from Gemini's groundingSupports with dynamic index remapping (preventing broken citations) and renders clean Markdown hyperlinks [1] [Title](url).
  • 🌐 Reverse Proxy & Custom Gateway Ready: Dual authentication support with both x-goog-api-key and Authorization: Bearer, ensuring seamless compatibility with OneAPI, NewAPI, and LAN gateways.

🔀 Dual Search Architecture

The plugin provides two parallel search pathways to satisfy both transparent daily use and specialized scripted workflows:

                    User Prompt Input
                            │
            ┌───────────────┴───────────────┐
            ▼                               ▼
     [Normal Chat]                   [Specialized Prompt]
  "What's the weather?"          "Search with gemini-3.8-flash"
  "Review of RX 9070 XT"         "Batch query 3 items in Code Mode"
            │                               │
            ▼                               ▼
 LLM calls websearch(...)        LLM calls google_grounding(...)
            │                               │
            ▼                               │
 OpenCode Native Dispatch                   │
(Handled by this plugin)                    │
            │                               │
            └───────────────┬───────────────┘
                            ▼
               Unified Google Grounding Engine
      (Shares 45s timeouts, fallback chain, and cache)

| Entry Pathway | Invocation Method | Best For | Key Advantages | | :--- | :--- | :--- | :--- | | System WebSearch | LLM calls websearch({ query }) | Normal chats, default agent browsing | Completely transparent. Renders multi-source clickable cards without duplicate token bloat. | | Custom Professional Tool | Call google_grounding or tools.search.google_grounding | Deep research, Code Mode batch scripts, custom models | Advanced control. Supports passing model, context guidelines, max_sources, etc. |


🛠️ Tool Signature

When invoking via custom tools (google_grounding or websearch_cited), the following parameters are accepted:

| Argument | Type | Required | Description | | :--- | :--- | :---: | :--- | | query | string | Yes | The question or natural language search query. | | model | string | No | Optional Gemini model ID (e.g. gemini-3.5-flash-lite, gemini-3.8-flash, gemini-3.7-flash, gemini-3.1-flash-lite). Defaults to configured model. | | context | string | No | Optional extra background, constraints, or guidelines for the search. | | max_sources | number | No | Maximum number of grounded source links to return (1-20, default: 8). |


⚙️ Configuration & Priority

1. Modern Plugin Options (opencode.jsonc)

Configure plugin options directly in ~/.config/opencode/opencode.jsonc:

{
  "$schema": "https://opencode.ai/config.json",
  "plugins": [
    {
      "package": "opencode-gemini-grounding",
      "options": {
        "model": "gemini-3.5-flash-lite",      // Primary grounding model
        "apiKey": "{env:GOOGLE_API_KEY}",       // Auto-resolved environment variable
        "cacheTtlMs": 600000,                  // Storage cache duration (ms, default 10m; 0 disables)
        "requestTimeoutMs": 45000,              // Single-model timeout (45s)
        "timeoutMs": 180000,                    // Total fallback chain timeout (3m)
        "setDefaultWebsearch": true             // Register as default OpenCode V2 websearch provider
      }
    }
  ]
}

2. Model Resolution

  1. Dynamic model argument provided in the tool call.
  2. options.model in opencode.jsonc plugin options.
  3. OPENCODE_GOOGLE_MODEL environment variable.
  4. providers.google.model or providers.google.settings.model in ~/.config/opencode/opencode.jsonc.
  5. providers.google.options.websearch_cited.model.
  6. Default fallback: gemini-3.5-flash-lite.

Automatic Fallback Chain: If a model fails or hits rate limits, the plugin tries the next candidate automatically: [Requested Model] -> gemini-3.5-flash-lite -> gemini-3.8-flash -> gemini-3.7-flash -> gemini-3.1-flash-lite -> gemini-3-flash-preview -> gemini-2.5-flash.

3. Base URL (API Gateway)

  1. options.baseURL in opencode.jsonc plugin options.
  2. OPENCODE_GOOGLE_BASE_URL environment variable.
  3. providers.google.settings.baseURL in ~/.config/opencode/opencode.jsonc.
  4. Default: https://generativelanguage.googleapis.com/v1beta (Official Google API).

4. API Key

  1. options.apiKey in opencode.jsonc plugin options (supports {env:VAR}).
  2. OPENCODE_GOOGLE_API_KEY / GOOGLE_API_KEY / GEMINI_API_KEY environment variables.
  3. Stored OpenCode credentials in ~/.local/share/opencode/auth.json (google.key or indor.key).
  4. providers.google.settings.apiKey in opencode.jsonc.

📦 Installation in OpenCode V2

Method 1: Global Plugin Bridge (Recommended)

Create ~/.config/opencode/plugins/google-grounding.js and re-export this repository:

export { default } from "file:///D:/OpenCode/opencode-gemini-grounding/index.js";

Method 2: Directory Junction / Symlink

Link this repository folder directly into OpenCode's plugin directory:

# Windows (PowerShell / Command Prompt)
cmd /c mklink /J "$env:USERPROFILE\.config\opencode\plugins\opencode-gemini-grounding" "D:\OpenCode\opencode-gemini-grounding"

Verify that the plugin is recognized:

opencode plugin list

📝 Example Output

According to the latest meteorological bulletins, Beijing weather for today (September 27) is clear and pleasant after rain[1]:

* **Condition**: Becoming clear and sunny during the day, partly cloudy at night[1][2].
* **Temperature**: Daytime high around 26°C, dropping to 15°C~16°C overnight[1][3].
* **Wind**: Northerly winds around Force 3 with gusts reaching Force 5~6 during daytime[1].

Sources:
[1] [Beijing Daily - Meteorological Bulletin](https://vertexaisearch.cloud.google.com/grounding-api-redirect/...)
[2] [China Weather - Precipitation & Conditions](https://vertexaisearch.cloud.google.com/grounding-api-redirect/...)
[3] [National Meteorological Center - Forecast](https://vertexaisearch.cloud.google.com/grounding-api-redirect/...)

Search queries: Beijing weather September 27; Beijing meteorological bureau report

🙏 Acknowledgements

This project builds upon the ideas and implementations of two pioneering OpenCode V1 plugins:


📄 License

Distributed under the MIT License.