diff --git a/plugins/jbolivar19/gemini-cli-bridge/.claude-plugin/plugin.json b/plugins/jbolivar19/gemini-cli-bridge/.claude-plugin/plugin.json new file mode 100644 index 00000000..01e1b849 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/.claude-plugin/plugin.json @@ -0,0 +1,48 @@ +{ + "name": "gemini-cli-bridge", + "version": "1.3.0", + "description": "Conecta MiniMax Code con los modelos de Gemini a través del CLI de Gemini: los registra en el selector de modelos como proveedor propio y además ofrece herramientas MCP para consultar, planificar o editar archivos.", + "author": { + "name": "jbolivar19", + "url": "https://github.com/jbolivar19" + }, + "license": "Apache-2.0", + "keywords": [ + "gemini", + "gemini-cli", + "antigravity", + "mcp", + "code-review" + ], + "skills": [ + "./skills/gemini-bridge/SKILL.md", + "./skills/gemini-bridge-visualizer/SKILL.md" + ], + "mcpServers": { + "gemini-bridge": { + "type": "stdio", + "command": "node", + "args": [ + "./server.js" + ], + "cwd": "${PLUGIN_ROOT}" + } + }, + "hooks": { + "SessionStart": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "node", + "args": [ + "${PLUGIN_ROOT}/scripts/session-start.mjs" + ], + "timeout": 8 + } + ] + } + ] + } +} diff --git a/plugins/jbolivar19/gemini-cli-bridge/.minimax-plugin/plugin.json b/plugins/jbolivar19/gemini-cli-bridge/.minimax-plugin/plugin.json new file mode 100644 index 00000000..23d20258 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/.minimax-plugin/plugin.json @@ -0,0 +1,31 @@ +{ + "schemaVersion": 1, + "name": "gemini-cli-bridge", + "displayName": "Gemini CLI Bridge", + "version": "1.3.0", + "description": "Conecta MiniMax Code con los modelos de Gemini a través del CLI de Gemini: los registra en el selector de modelos como proveedor propio y además ofrece herramientas MCP para consultar, planificar o editar archivos.", + "author": "Jesus Bolivar", + "icon": "icon.png", + "darkIcon": "icon-dark.png", + "category": "Code", + "exampleQueries": [ + "Usa Gemini para revisar este archivo PHP y dime qué falla.", + "Pide a Gemini un plan para migrar este plugin de WordPress a PHP 8.3 sin tocar archivos.", + "Usa el modelo Gemini con esfuerzo alto para depurar este error de MySQL.", + "Lista los modelos disponibles del CLI de Gemini." + ], + "apps": [], + "mcpServers": [ + "servers.mcp.json" + ], + "skills": [ + "skills/gemini-bridge/SKILL.md", + "skills/gemini-bridge-visualizer/SKILL.md" + ], + "agents": [ + "agents/gemini.md" + ], + "hooks": [ + "hooks/hooks.json" + ] +} diff --git a/plugins/jbolivar19/gemini-cli-bridge/LICENSE b/plugins/jbolivar19/gemini-cli-bridge/LICENSE new file mode 100644 index 00000000..ec5fe20c --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/LICENSE @@ -0,0 +1,192 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + Copyright 2026 MCode Plugins contributors + + 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 + + http://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. diff --git a/plugins/jbolivar19/gemini-cli-bridge/README.md b/plugins/jbolivar19/gemini-cli-bridge/README.md new file mode 100644 index 00000000..dbef52d2 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/README.md @@ -0,0 +1,118 @@ +# Gemini CLI Bridge + +Use Google's Gemini CLI as a chat model inside MiniMax Code, and let the agent delegate +reviews, plans, and file edits to Gemini without leaving the conversation. + +MiniMax Code cannot talk to the Gemini CLI directly: the CLI is a local binary, not an +HTTP API. This Plugin bridges the two. It ships an MCP server that speaks the Gemini CLI +and exposes it as tools, plus a local OpenAI-compatible proxy so the CLI models can also +appear in the MiniMax Code model picker. + +## Try it + +```text +Usa Gemini para revisar este archivo PHP y dime qué falla. +``` + +Or, to compare models by cost and latency before choosing one: + +```text +Muéstrame el coste y la latencia de cada nivel de esfuerzo de Gemini. +``` + +## What it does + +**As a model in the picker.** Running `node scripts/register-provider.mjs` registers a +`gemini-cli-bridge` provider in your MiniMax Code `config.yaml`. The provider exposes +the models the CLI actually offers, for example `gemini-4-hydrogen` with a +`low`/`medium`/`high`/`xhigh`/`max` effort selector. Requests travel through a local +proxy that translates the OpenAI chat-completions call into a CLI invocation. + +**As MCP tools.** The `gemini-bridge` server exposes: + +| Tool | Purpose | +| --- | --- | +| `gemini_status` | Check that the CLI is installed, its version, and whether the Google sign-in is active. | +| `gemini_models` | List the model identifiers the CLI currently exposes. | +| `gemini_prompt` | Send a prompt to Gemini and return the answer. | +| `gemini_usage` | Return aggregated usage per model and effort: calls, latency, and tokens. | + +`gemini_prompt` accepts a `mode`: + +| Mode | Behaviour | +| --- | --- | +| `consult` | Answers only. Gemini may read project files for context, but is instructed not to modify anything. | +| `plan` | Produces a plan without editing files. | +| `edit` | Applies changes to files in the working directory. | +| `auto` | Runs autonomously, including edits. | + +The CLI executes its own tools and auto-approves them in print mode, so `consult` and +`plan` carry an explicit instruction to leave the disk alone. Use `edit` and `auto` only +when you want files changed. + +## Requirements + +- **Node.js 22 or newer**, on `PATH`. +- **The Gemini CLI** (the Antigravity CLI binary, `antigravity`). The bridge looks for it + in this order: the `ANTIGRAVITY_CLI` or `GEMINI_CLI_PATH` environment variable, a + managed OpenBot runtime under + `%APPDATA%\OpenBot\provider-runtimes\antigravity\\\bin`, and + finally `PATH`. +- **A signed-in Google account** for the Gemini CLI. This Plugin never handles Google + credentials: the CLI owns its own sign-in state, and the bridge only launches it. +- **Windows, macOS, or Linux.** The CLI binary name and the managed-runtime lookup are + resolved per platform. + +## Accounts and paid services + +The Gemini CLI uses the account you signed into the CLI. That account's own plan and +quotas apply, because the CLI is what talks to Google. This Plugin adds no billing of its +own and does not proxy model traffic through any third-party service. + +## Data and network + +- **The Gemini CLI** connects to Google's own endpoints to serve model requests. The + Plugin does not send data anywhere else. +- **The bridge listens on `127.0.0.1:8789`** and accepts connections from the local + machine only. It is started automatically by the `SessionStart` hook and exits quietly + if it is already running. +- **Prompts and file contents** go from MiniMax Code to the CLI, and the CLI sends them to + Google under its own terms. Anything the agent puts in a prompt is sent to Google. +- **Usage records are written locally** to the plugin's own data directory + (`usage.jsonl`): model, effort, mode, latency, token counts, and the conversation ID. + No prompt text, no file contents, and no credentials are recorded. +- **No telemetry** is collected by this Plugin. It makes no network request of its own. + +## Optional: the model picker + +`scripts/register-provider.mjs` writes a `gemini-cli-bridge` block into your MiniMax +Code `config.yaml` so the CLI models appear in the model picker. Run it once: + +```bash +node scripts/register-provider.mjs +``` + +It creates a timestamped backup of `config.yaml` first. To undo it: + +```bash +node scripts/register-provider.mjs --remove +``` + +The MCP tools work without this step; the picker entry is what makes Gemini selectable as +the conversation model. + +## Compatibility + +This package ships both runtime layouts. The top-level `plugin.json` and `mcp.json` are +the portable Agent Plugins 1.0 layout, which is what MiniMax Code 0.3.x reads. The +`.claude-plugin/plugin.json` manifest carries the same Skills, MCP server, and the +`SessionStart` hook in the inline format used by 0.4.0+. + +The `.minimax-plugin/` directory keeps the original MiniMax manifest, including the +icon, the category, the example queries, and the `gemini` subagent. Those declarations +apply when the package is installed through MiniMax Code; a copy installed directly from +GitHub gets the Skills and the MCP server. + +## License + +Apache-2.0. See [LICENSE](LICENSE). diff --git a/plugins/jbolivar19/gemini-cli-bridge/agents/gemini.md b/plugins/jbolivar19/gemini-cli-bridge/agents/gemini.md new file mode 100644 index 00000000..2af599e8 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/agents/gemini.md @@ -0,0 +1,38 @@ +--- +name: gemini +description: Delegar a un modelo de Gemini mediante el CLI de Gemini una revisión, un análisis, un plan o una edición de archivos del proyecto. Usar cuando el usuario pida específicamente que Gemini, Gemini CLI o un modelo de Google resuelva o revise algo. +mcpServers: + - gemini-bridge +skills: + - gemini-bridge +x-mavis: + displayName: Gemini (CLI) +--- + +Eres un agente que delega el trabajo a Gemini a través del CLI de Gemini usando las +herramientas MCP del servidor `gemini-bridge`. + +## Cómo trabajar + +1. Arranca con `gemini_status` solo si no está claro que el CLI responde. Si la + autenticación con Google no está activa, informa y detente. +2. Convierte la petición del usuario en un prompt autosuficiente para Gemini: + incluye el contexto, los archivos relevantes y el resultado esperado. Gemini no ve + esta conversación. +3. Elige el modo según la intención: + - `consult` para preguntas y revisiones que solo necesitan respuesta. + - `plan` para un análisis o propuesta sin tocar archivos. + - `edit` cuando el usuario pidió que se apliquen cambios en el proyecto. + - `auto` para una tarea autónoma que el usuario delegó por completo. +4. Define `cwd` con el directorio del proyecto cuando la tarea lo requiera. +5. Entrega el resultado de Gemini como respuesta final, con un resumen breve de lo que + hizo. Si trabajó en modo `edit` o `auto`, lista los archivos que quedaron modificados. + +## Reglas + +- Si Gemini devuelve error de modelo o esfuerzo, corrige el parámetro y reintenta una + sola vez. +- Si el modelo trae sufijo de esfuerzo (`-high`, `-xhigh`), no añadas `effort` aparte. +- No inventes la respuesta de Gemini: devuélvela tal cual. +- No ejecutes en tu nombre las acciones que el usuario solo pidió a Gemini; tu papel es + formular bien la petición y reportar el resultado. diff --git a/plugins/jbolivar19/gemini-cli-bridge/hooks/hooks.json b/plugins/jbolivar19/gemini-cli-bridge/hooks/hooks.json new file mode 100644 index 00000000..d1941996 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/hooks/hooks.json @@ -0,0 +1,16 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/scripts/session-start.mjs\"", + "commandWindows": "node \"${PLUGIN_ROOT}\\scripts\\session-start.mjs\"", + "timeout": 8 + } + ] + } + ] + } +} diff --git a/plugins/jbolivar19/gemini-cli-bridge/icon-dark.png b/plugins/jbolivar19/gemini-cli-bridge/icon-dark.png new file mode 100644 index 00000000..c1e02855 Binary files /dev/null and b/plugins/jbolivar19/gemini-cli-bridge/icon-dark.png differ diff --git a/plugins/jbolivar19/gemini-cli-bridge/icon.png b/plugins/jbolivar19/gemini-cli-bridge/icon.png new file mode 100644 index 00000000..406854db Binary files /dev/null and b/plugins/jbolivar19/gemini-cli-bridge/icon.png differ diff --git a/plugins/jbolivar19/gemini-cli-bridge/io.minimax.mcode/hooks/hooks.json b/plugins/jbolivar19/gemini-cli-bridge/io.minimax.mcode/hooks/hooks.json new file mode 100644 index 00000000..a08b81ae --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/io.minimax.mcode/hooks/hooks.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://minimax.io/schemas/mcode-hooks/0.1.0/hooks.schema.json", + "hooks": { + "SessionStart": [ + { + "command": "node", + "args": [ + "${PLUGIN_ROOT}/scripts/session-start.mjs" + ], + "timeout": 8000, + "once": false + } + ] + } +} diff --git a/plugins/jbolivar19/gemini-cli-bridge/mcp.json b/plugins/jbolivar19/gemini-cli-bridge/mcp.json new file mode 100644 index 00000000..c2f5d6f5 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/mcp.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", + "mcpServers": { + "gemini-bridge": { + "type": "stdio", + "command": "node", + "args": [ + "./server.js" + ], + "cwd": "${PLUGIN_ROOT}" + } + } +} diff --git a/plugins/jbolivar19/gemini-cli-bridge/plugin.json b/plugins/jbolivar19/gemini-cli-bridge/plugin.json new file mode 100644 index 00000000..286a7269 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/plugin.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "gemini-cli-bridge", + "version": "1.3.0", + "description": "Conecta MiniMax Code con los modelos de Gemini a través del CLI de Gemini: los registra en el selector de modelos como proveedor propio y además ofrece herramientas MCP para consultar, planificar o editar archivos.", + "author": { + "name": "jbolivar19", + "url": "https://github.com/jbolivar19" + }, + "homepage": "https://github.com/jbolivar19/MiniMax-Code-Plugins/tree/main/plugins/jbolivar19/gemini-cli-bridge", + "repository": "https://github.com/jbolivar19/MiniMax-Code-Plugins", + "license": "Apache-2.0", + "keywords": [ + "gemini", + "gemini-cli", + "antigravity", + "mcp", + "code-review" + ] +} diff --git a/plugins/jbolivar19/gemini-cli-bridge/scripts/bridge.mjs b/plugins/jbolivar19/gemini-cli-bridge/scripts/bridge.mjs new file mode 100644 index 00000000..a90f6d3c --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/scripts/bridge.mjs @@ -0,0 +1,660 @@ +#!/usr/bin/env node +/** + * Gemini CLI Bridge — puente OpenAI-compatible sobre el CLI de Gemini (Antigravity CLI). + * + * MiniMax Code habla OpenAI (`POST /v1/chat/completions`) contra los proveedores + * `custom_provider` de config.yaml. Este puente traduce esa llamada al binario real + * del CLI y devuelve la respuesta en el formato que MCode espera, con streaming SSE + * real (el CLI emite deltas de texto). + * + * MCode -> puente (127.0.0.1:8789) -> antigravity --print -> modelos Gemini + * (config.yaml: custom_provider.gemini-cli-bridge) + * + * El binario se resuelve en este orden: ANTIGRAVITY_CLI / GEMINI_CLI_PATH, el + * runtime gestionado por OpenBot (provider-runtimes/antigravity) y por ultimo PATH. + * + * Uso: node bridge.mjs [--port 8789] + */ + +import http from 'node:http'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawn } from 'node:child_process'; +import { createRequire } from 'node:module'; + +/* El ledger de uso es CommonJS para compartirlo con el servidor MCP. */ +const require = createRequire(import.meta.url); +const usageLedger = require('./usage-ledger.cjs'); + +/* ------------------------------------------------------------------ */ +/* Configuracion */ +/* ------------------------------------------------------------------ */ + +const argPort = (() => { + const i = process.argv.indexOf('--port'); + if (i !== -1 && process.argv[i + 1]) return Number(process.argv[i + 1]); + return Number(process.env.GEMINI_BRIDGE_PORT || 8789); +})(); + +const HOST = '127.0.0.1'; +const DEFAULT_MODEL = 'gemini-4-hydrogen'; +const DEFAULT_EFFORT = 'low'; +const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']; +const EFFORT_SUFFIX = /-(low|medium|high|xhigh|max)$/; +/* Por debajo de este tamano el prompt viaja como argumento (con deltas en vivo); + por encima va por stdin, que es el unico modo sin el limite de 32k de Windows. */ +const ARGV_PROMPT_LIMIT = 24000; +/* Modo del CLI. "default" = sin --mode: responde como chat y no se pone a hacer + planes ni a pedir aprobaciones, que es lo que espera un modelo del selector. + "plan" lo convierte en un agente que escribe implementation_plan.md y pide + permiso, asi que no sirve como modelo de conversacion. */ +const CLI_MODE = process.env.GEMINI_BRIDGE_MODE || 'default'; +/* Directorio de trabajo del CLI. Por defecto, el del proceso puente (que el hook + SessionStart arranca en el workspace de la sesion). Se puede fijar con + GEMINI_BRIDGE_CWD para confinar las herramientas de Gemini. */ +const CLI_CWD = process.env.GEMINI_BRIDGE_CWD || process.cwd(); + +const DATA_DIR = + process.env.PLUGIN_DATA || + process.env.MINIMAX_PLUGIN_DATA || + path.join(os.homedir(), '.minimax', 'plugin-data', 'gemini-cli-bridge'); +const LOG_FILE = path.join(DATA_DIR, 'bridge.log'); + +/* ------------------------------------------------------------------ */ +/* Log */ +/* ------------------------------------------------------------------ */ + +function log(level, message) { + const stamp = new Date().toISOString(); + const line = `${stamp} [${level}] ${message}`; + try { + fs.mkdirSync(DATA_DIR, { recursive: true }); + fs.appendFileSync(LOG_FILE, `${line}\n`); + } catch { + /* el log nunca debe romper la peticion */ + } + process.stderr.write(`${line}\n`); +} + +/* ------------------------------------------------------------------ */ +/* Resolucion del binario del CLI */ +/* ------------------------------------------------------------------ */ + +function isFile(p) { + try { + return fs.statSync(p).isFile(); + } catch { + return false; + } +} + +function isDir(p) { + try { + return fs.statSync(p).isDirectory(); + } catch { + return false; + } +} + +function readDirSafe(dir) { + try { + return fs.readdirSync(dir); + } catch { + return []; + } +} + +function compareVersionsDesc(a, b) { + const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0); + const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0); + const len = Math.max(pa.length, pb.length); + for (let i = 0; i < len; i += 1) { + const va = pa[i] || 0; + const vb = pb[i] || 0; + if (va !== vb) return vb - va; + } + return 0; +} + +function managedRuntimeCandidates() { + const out = []; + const roots = []; + const home = os.homedir(); + const push = (p) => { + if (p && isDir(p)) roots.push(p); + }; + if (process.env.APPDATA) { + push(path.join(process.env.APPDATA, 'OpenBot', 'provider-runtimes', 'antigravity')); + } + push(path.join(home, 'Library', 'Application Support', 'OpenBot', 'provider-runtimes', 'antigravity')); + push(path.join(home, '.local', 'share', 'OpenBot', 'provider-runtimes', 'antigravity')); + push(path.join(home, '.config', 'OpenBot', 'provider-runtimes', 'antigravity')); + + const bins = ['antigravity.exe', 'antigravity', 'antigravity.cmd']; + for (const root of roots) { + for (const platform of readDirSafe(root)) { + const platformDir = path.join(root, platform); + if (!isDir(platformDir)) continue; + const versions = readDirSafe(platformDir) + .filter((v) => isDir(path.join(platformDir, v))) + .sort(compareVersionsDesc); + for (const version of versions) { + for (const bin of bins) { + const candidate = path.join(platformDir, version, 'bin', bin); + if (isFile(candidate)) out.push(candidate); + } + } + } + } + return out; +} + +function pathCandidates() { + const out = []; + const bins = ['antigravity.exe', 'antigravity', 'antigravity.cmd']; + for (const dir of (process.env.PATH || '').split(path.delimiter).filter(Boolean)) { + for (const bin of bins) { + const candidate = path.join(dir, bin); + if (isFile(candidate)) out.push(candidate); + } + } + return out; +} + +let cachedCli; + +function resolveCli() { + if (cachedCli !== undefined) return cachedCli; + const explicit = [process.env.ANTIGRAVITY_CLI, process.env.GEMINI_CLI_PATH].filter((v) => v && isFile(v)); + if (explicit.length) { + cachedCli = { path: explicit[0], source: 'env' }; + return cachedCli; + } + const managed = managedRuntimeCandidates(); + if (managed.length) { + cachedCli = { path: managed[0], source: 'openbot-runtime' }; + return cachedCli; + } + const onPath = pathCandidates(); + if (onPath.length) { + cachedCli = { path: onPath[0], source: 'PATH' }; + return cachedCli; + } + cachedCli = null; + return cachedCli; +} + +/* ------------------------------------------------------------------ */ +/* Catalogo de modelos */ +/* ------------------------------------------------------------------ */ + +let modelCache = { at: 0, list: [] }; + +function parseModelLines(text) { + const models = []; + const seen = new Set(); + for (const raw of String(text || '').split(/\r?\n/)) { + const line = raw.replace(/\s+$/, ''); + if (!line || line.startsWith('Fetching')) continue; + const tab = line.indexOf('\t'); + if (tab <= 0) continue; + const id = line.slice(0, tab).trim(); + const label = line.slice(tab + 1).trim(); + if (!id || !label || seen.has(id)) continue; + if (!/^[A-Za-z0-9._-]+$/.test(id)) continue; + seen.add(id); + models.push({ id, label }); + } + return models; +} + +function runCli(args, { timeoutMs = 120000, stdin = null, onLine = null } = {}) { + const cli = resolveCli(); + if (!cli) { + return Promise.resolve({ code: null, stdout: '', stderr: 'CLI de Gemini no encontrado', notFound: true }); + } + return new Promise((resolve) => { + let child; + try { + child = spawn(cli.path, args, { + cwd: CLI_CWD, + env: process.env, + windowsHide: true, + shell: false, + }); + } catch (err) { + resolve({ code: null, stdout: '', stderr: String(err && err.message) }); + return; + } + let stdout = ''; + let stderr = ''; + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + try { + child.kill(); + } catch { + /* ignore */ + } + resolve({ code: null, stdout, stderr: `Tiempo de espera agotado (${timeoutMs} ms)`, timedOut: true }); + }, timeoutMs); + + child.stdout.setEncoding('utf8'); + child.stdout.on('data', (chunk) => { + stdout += chunk; + if (onLine) { + for (const line of chunk.split(/\r?\n/)) { + if (line.trim()) onLine(line.trim()); + } + } + }); + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk) => { + stderr += chunk; + }); + if (stdin !== null) { + child.stdin.on('error', () => {}); + child.stdin.end(stdin); + } else { + child.stdin.end(); + } + child.on('error', (err) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve({ code: null, stdout, stderr: String(err && err.message) }); + }); + child.on('close', (code) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve({ code, stdout, stderr }); + }); + }); +} + +async function listModels() { + if (Date.now() - modelCache.at < 60000 && modelCache.list.length) return modelCache.list; + const res = await runCli(['models'], { timeoutMs: 120000 }); + let list = parseModelLines(res.stdout); + if (!list.length) list = parseModelLines(res.stderr); + if (list.length) modelCache = { at: Date.now(), list }; + return list; +} + +/* ------------------------------------------------------------------ */ +/* Composicion del prompt */ +/* ------------------------------------------------------------------ */ + +function textFromContent(content) { + if (typeof content === 'string') return content; + if (Array.isArray(content)) { + return content + .map((part) => { + if (typeof part === 'string') return part; + if (part && typeof part === 'object' && typeof part.text === 'string') return part.text; + return ''; + }) + .filter(Boolean) + .join('\n'); + } + return ''; +} + +/* Guard de la ruta selector: el CLI trae sus propias herramientas (read_file, + run_command, write_to_file...) y en modo print las auto-aprueba, o sea que + puede escribir en el proyecto sin que MCode lo pida. Ninguna forma de + --settings lo bloquea (solo acepta "permissions", pero no la hace cumplir), + asi que se le pide por prompt que se limite a leer y responder. */ +const CHAT_GUARD = + 'Puedes leer archivos del proyecto para darte contexto y responder con texto. ' + + 'No modifiques ni crees archivos, no ejecutes comandos ni uses herramientas ' + + 'que cambien el disco: solo redacta la respuesta en texto.'; + +function composePrompt(messages) { + const list = Array.isArray(messages) ? messages : []; + const system = []; + const turns = []; + for (const m of list) { + const role = (m && m.role) || 'user'; + const text = textFromContent(m && m.content); + if (!text) continue; + if (role === 'system' || role === 'developer') system.push(text); + else if (role === 'tool') turns.push(`Resultado de herramienta: ${text}`); + else if (role === 'assistant') turns.push(`Asistente: ${text}`); + else turns.push(`Usuario: ${text}`); + } + const parts = []; + if (system.length) parts.push(`Instrucciones:\n${system.join('\n\n')}`); + if (turns.length) parts.push(turns.join('\n\n')); + if (!parts.length) return ''; + return `${CHAT_GUARD}\n\n${parts.join('\n\n')}`; +} + +function pickEffort(body) { + const candidates = [ + body && body.reasoning_effort, + body && body.effort, + body && body.reasoning && body.reasoning.effort, + body && body.thinking && body.thinking.effort, + body && body.thinking_config && body.thinking_config.effort, + body && body.extra_body && body.extra_body.reasoning_effort, + body && body.extra_body && body.extra_body.effort, + ]; + for (const c of candidates) { + if (typeof c === 'string' && EFFORTS.includes(c.toLowerCase())) return c.toLowerCase(); + } + return null; +} + +/** + * Traduce el modelo pedido a los flags del CLI. + * El CLI rechaza --model con sufijo de esfuerzo junto a --effort, asi que el + * sufijo gana y el --effort solo se usa con el modelo base. + */ +function buildCliArgs(body, prompt) { + const requested = typeof (body && body.model) === 'string' && body.model.trim() ? body.model.trim() : DEFAULT_MODEL; + const args = []; + + if (CLI_MODE && CLI_MODE !== 'default') { + args.push('--mode', CLI_MODE); + } + + const suffixMatch = requested.match(EFFORT_SUFFIX); + let cliModel = requested; + let cliEffort = null; + let effectiveEffort = null; + if (suffixMatch) { + cliModel = requested; + effectiveEffort = suffixMatch[1]; + } else { + const effort = pickEffort(body); + cliEffort = effort || DEFAULT_EFFORT; + effectiveEffort = cliEffort; + } + args.push('--model', cliModel); + if (cliEffort) args.push('--effort', cliEffort); + + /* Modelo base y esfuerzo efectivo, para el registro de uso. */ + const effectiveModel = cliModel.replace(EFFORT_SUFFIX, ''); + + if (prompt.length > ARGV_PROMPT_LIMIT) { + args.push('--input-format', 'stream-json'); + args.push('--output-format', 'stream-json'); + return { + args, + model: effectiveModel, + effort: effectiveEffort, + stdin: `${JSON.stringify({ + event: 'user', + message: { role: 'user', content: [{ type: 'text', text: prompt }] }, + })}\n`, + }; + } + + args.push('--output-format', 'stream-json'); + args.push('--print', prompt); + return { args, model: effectiveModel, effort: effectiveEffort, stdin: null }; +} + +/* ------------------------------------------------------------------ */ +/* Traduccion de la respuesta */ +/* ------------------------------------------------------------------ */ + +function extractStreamEvents(text) { + const events = []; + for (const line of String(text || '').split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed || trimmed[0] !== '{') continue; + try { + const parsed = JSON.parse(trimmed); + if (parsed && parsed.event) events.push(parsed); + } catch { + /* linea no JSON */ + } + } + return events; +} + +function textFromEvents(events) { + let text = ''; + let usage = null; + let error = null; + for (const ev of events) { + if (ev.event === 'step_update') { + const su = ev.step_update || {}; + if (su.step_type === 'agent_response' && typeof su.text_delta === 'string') text += su.text_delta; + if (su.usage) usage = su.usage; + } else if (ev.event === 'result') { + const r = ev.result || {}; + if (r.usage) usage = r.usage; + if (r.status && r.status !== 'SUCCESS') error = r.error || r.finished_reason || 'error desconocido'; + if (typeof r.response === 'string' && r.response.trim() && !text.trim()) text = r.response; + } + } + return { text, usage, error }; +} + +function sseSend(res, payload) { + res.write(`data: ${JSON.stringify(payload)}\n\n`); +} + +/** + * Registra el uso de esta consulta en el ledger del plugin. + * El panel de coste y latencia se alimenta de aqui, asi que la ruta del selector + * y la ruta MCP dejan la misma trazabilidad. + */ +function recordUsage(model, built, usage, events) { + try { + const duration = Number( + (events || []).reduce((acc, ev) => { + if (ev.event === 'result' && ev.result && ev.result.duration_seconds) { + return Math.max(acc, Number(ev.result.duration_seconds) || 0); + } + return acc; + }, 0), + ); + const conversation = (events || []).reduce((acc, ev) => { + if (ev.event === 'result' && ev.result && ev.result.conversation_id) return ev.result.conversation_id; + return acc; + }, null); + const norm = usageLedger.normalize(built && built.effort ? built.model : model, built && built.effort); + usageLedger.appendUsage({ + ts: new Date().toISOString(), + model: norm.model, + effort: norm.effort, + mode: 'picker', + duration_seconds: duration, + input_tokens: Number(usage && usage.input_tokens) || 0, + output_tokens: Number(usage && usage.output_tokens) || 0, + thinking_tokens: Number(usage && usage.thinking_tokens) || 0, + total_tokens: Number(usage && usage.total_tokens) || 0, + conversation_id: conversation, + }); + } catch { + /* el registro de uso nunca debe romper una respuesta */ + } +} + +function openAiError(res, status, message) { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: { message, type: 'gemini_bridge_error' } })); +} + +/* ------------------------------------------------------------------ */ +/* Servidor */ +/* ------------------------------------------------------------------ */ + +const server = http.createServer(async (req, res) => { + try { + if (req.url.startsWith('/__health')) { + const cli = resolveCli(); + res.writeHead(200, { 'content-type': 'application/json' }); + return res.end( + JSON.stringify({ + ok: true, + cli: cli ? cli.path : null, + source: cli ? cli.source : null, + mode: CLI_MODE, + port: argPort, + }), + ); + } + + if (req.url.startsWith('/v1/models')) { + const models = await listModels(); + res.writeHead(200, { 'content-type': 'application/json' }); + return res.end( + JSON.stringify({ + object: 'list', + data: models.map((m) => ({ id: m.id, object: 'model', created: 0, owned_by: 'antigravity-cli' })), + }), + ); + } + + if (req.url.startsWith('/v1/chat/completions') && req.method === 'POST') { + let raw = ''; + for await (const chunk of req) raw += chunk; + let body = {}; + try { + body = JSON.parse(raw || '{}'); + } catch { + return openAiError(res, 400, 'Cuerpo JSON invalido'); + } + + const prompt = composePrompt(body.messages); + if (!prompt.trim()) return openAiError(res, 400, 'La peticion no trae mensajes con contenido.'); + + const built = buildCliArgs(body, prompt); + const id = `chatcmpl-${Date.now().toString(36)}`; + const created = Math.floor(Date.now() / 1000); + const model = body.model || DEFAULT_MODEL; + const wantsStream = body.stream === true; + + log( + 'INFO', + `peticion model=${model} stream=${wantsStream} modo=${CLI_MODE} ` + + `promptChars=${prompt.length} claves=${Object.keys(body).sort().join(',')}`, + ); + + if (!wantsStream) { + const res2 = await runCli(built.args, { + timeoutMs: 900000, + stdin: built.stdin, + }); + if (res2.notFound) return openAiError(res, 503, res2.stderr); + const events = extractStreamEvents(res2.stdout); + const parsed = textFromEvents(events); + if (parsed.error) return openAiError(res, 502, `Gemini respondio con error: ${parsed.error}`); + const usage = parsed.usage || {}; + recordUsage(model, built, usage, events); + return res.end( + JSON.stringify({ + id, + object: 'chat.completion', + created, + model, + choices: [ + { + index: 0, + message: { role: 'assistant', content: parsed.text || '' }, + finish_reason: 'stop', + }, + ], + usage: { + prompt_tokens: usage.input_tokens || 0, + completion_tokens: usage.output_tokens || 0, + total_tokens: usage.total_tokens || 0, + }, + }), + ); + } + + res.writeHead(200, { + 'content-type': 'text/event-stream', + 'cache-control': 'no-cache', + connection: 'keep-alive', + }); + + let sent = false; + let usage = null; + let failure = null; + + const res2 = await runCli(built.args, { + timeoutMs: 900000, + stdin: built.stdin, + onLine: (line) => { + let ev; + try { + ev = JSON.parse(line); + } catch { + return; + } + if (!ev || !ev.event) return; + if (ev.event === 'step_update') { + const su = ev.step_update || {}; + if (su.step_type === 'agent_response' && typeof su.text_delta === 'string' && su.text_delta) { + sent = true; + sseSend(res, { + id, + object: 'chat.completion.chunk', + created, + model, + choices: [{ index: 0, delta: { content: su.text_delta }, finish_reason: null }], + }); + } + if (su.usage) usage = su.usage; + } else if (ev.event === 'result') { + const r = ev.result || {}; + if (r.usage) usage = r.usage; + if (r.status && r.status !== 'SUCCESS') failure = r.error || r.finished_reason || 'error desconocido'; + } + }, + }); + + if (res2.notFound) { + sseSend(res, { error: { message: res2.stderr, type: 'gemini_bridge_error' } }); + } else if (failure) { + sseSend(res, { error: { message: `Gemini respondio con error: ${failure}`, type: 'gemini_bridge_error' } }); + } else if (!sent) { + sseSend(res, { id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { content: '' }, finish_reason: null }] }); + } + + const u = usage || {}; + sseSend(res, { + id, + object: 'chat.completion.chunk', + created, + model, + choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], + usage: { + prompt_tokens: u.input_tokens || 0, + completion_tokens: u.output_tokens || 0, + total_tokens: u.total_tokens || 0, + }, + }); + res.write('data: [DONE]\n\n'); + return res.end(); + } + + res.writeHead(404, { 'content-type': 'application/json' }); + return res.end(JSON.stringify({ error: { message: `Ruta no soportada: ${req.url}`, type: 'gemini_bridge_error' } })); + } catch (err) { + log('ERROR', String(err && err.stack)); + if (!res.headersSent) openAiError(res, 500, String(err && err.message)); + else res.end(); + return undefined; + } +}); + +server.listen(argPort, HOST, () => { + const cli = resolveCli(); + log('INFO', `Puente escuchando en http://${HOST}:${argPort} -> ${cli ? cli.path : 'CLI NO ENCONTRADO'} (modo ${CLI_MODE})`); +}); + +server.on('error', (err) => { + log('ERROR', `El servidor no pudo arrancar: ${err.message}`); + process.exit(1); +}); diff --git a/plugins/jbolivar19/gemini-cli-bridge/scripts/register-provider.mjs b/plugins/jbolivar19/gemini-cli-bridge/scripts/register-provider.mjs new file mode 100644 index 00000000..cd59615d --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/scripts/register-provider.mjs @@ -0,0 +1,171 @@ +#!/usr/bin/env node +/** + * Registra (o actualiza) el proveedor `gemini-cli-bridge` en el config.yaml de + * MiniMax Code y retira el proveedor `google-gemini` que dejo el plugin eliminado. + * + * El bloque generado es un hijo de `custom_provider` y apunta al puente local + * (127.0.0.1:8789), que traduce las peticiones OpenAI de MCode al CLI de Gemini. + * + * node register-provider.mjs -> registra/actualiza + * node register-provider.mjs --remove -> quita el bloque + */ + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const CFG = + process.env.MCODE_CONFIG || + path.join(process.env.USERPROFILE || os.homedir(), '.minimax', 'config.yaml'); + +const PROVIDER_ID = 'gemini-cli-bridge'; +const LEGACY_PROVIDER_ID = 'google-gemini'; +const PORT = Number(process.env.GEMINI_BRIDGE_PORT || 8789); + +/* Modelos del CLI de Gemini. El identificador base admite el selector de + esfuerzo; las variantes fijan un nivel concreto (son IDs reales del CLI). */ +const MODELS = [ + ['gemini-4-hydrogen', 'Gemini 4 Hydrogen (Antigravity CLI)', true], + ['gemini-4-hydrogen-low', 'Gemini 4 Hydrogen (Low)', false], + ['gemini-4-hydrogen-medium', 'Gemini 4 Hydrogen (Medium)', false], + ['gemini-4-hydrogen-high', 'Gemini 4 Hydrogen (High)', false], + ['gemini-4-hydrogen-xhigh', 'Gemini 4 Hydrogen (XHigh)', false], +]; + +function blockLines() { + const lines = []; + lines.push(' # --- Gemini CLI (Antigravity CLI): modelos de Gemini ------------------'); + lines.push(' # Puente local que traduce las peticiones OpenAI de MCode al binario'); + lines.push(' # real del CLI de Gemini. Se levanta solo al iniciar sesion.'); + lines.push(` ${PROVIDER_ID}:`); + lines.push(' name: Gemini CLI (Antigravity)'); + lines.push(' kind: custom'); + lines.push(' enabled: true'); + lines.push(' api: openai-completions'); + lines.push(' options:'); + lines.push(` baseURL: http://127.0.0.1:${PORT}/v1`); + lines.push(' authMode: api-key'); + lines.push(' # Placeholder: el puente autentica con la sesion de Google del CLI.'); + lines.push(' apiKey: local-gemini-cli-bridge'); + lines.push(' models:'); + for (const [id, name, withEffort] of MODELS) { + lines.push(` ${id}:`); + lines.push(` name: "${name}"`); + lines.push(' configuration_source: discovered'); + lines.push(' enabled: true'); + lines.push(' attachment: false'); + lines.push(' tool_call: false'); + lines.push(' reasoning: true'); + lines.push(' modalities:'); + lines.push(' input:'); + lines.push(' - text'); + lines.push(' output:'); + lines.push(' - text'); + lines.push(' limit:'); + lines.push(' context: 1048576'); + lines.push(' output: 65536'); + if (withEffort) { + lines.push(' thinking:'); + lines.push(' effortOptions:'); + lines.push(' - low'); + lines.push(' - medium'); + lines.push(' - high'); + lines.push(' - xhigh'); + lines.push(' - max'); + lines.push(' thinking_config:'); + lines.push(' mode: forced_on'); + } + } + return lines; +} + +const isKey = (line, indent) => + new RegExp(`^ {'${indent}'}[A-Za-z0-9._-]+:\\s*$`).test(line); + +/** + * Localiza el bloque de un proveedor dentro de `custom_provider`. + * Devuelve null si no existe. El bloque va desde la linea del proveedor hasta + * justo antes del siguiente proveedor hermano. + */ +function providerBlock(lines, cpStart, cpEnd, id) { + const header = new RegExp(`^ ${id}:\\s*$`); + let start = -1; + for (let i = cpStart + 1; i < cpEnd; i += 1) { + if (header.test(lines[i])) { + start = i; + break; + } + } + if (start === -1) return null; + + let end = cpEnd; + for (let i = start + 1; i < cpEnd; i += 1) { + if (isKey(lines[i], 2)) { + end = i; + break; + } + } + /* Los comentarios que preceden al bloque son suyos (p.ej. "# managed-by: ..."). */ + let head = start; + while (head > cpStart + 1 && /^\s*#/.test(lines[head - 1])) head -= 1; + return { head, start, end }; +} + +function main() { + const remove = process.argv.includes('--remove'); + if (!fs.existsSync(CFG)) { + console.error(`No se encontro el config: ${CFG}`); + process.exit(1); + } + + const raw = fs.readFileSync(CFG, 'utf8'); + const eol = raw.includes('\r\n') ? '\r\n' : '\n'; + const lines = raw.split(/\r?\n/); + + /* 1. Localizar la seccion custom_provider y sus hijos. */ + const cpStart = lines.findIndex((l) => /^custom_provider:\s*$/.test(l)); + if (cpStart === -1) { + console.error('No se encontro la seccion custom_provider en config.yaml'); + process.exit(1); + } + let cpEnd = lines.length; + for (let i = cpStart + 1; i < lines.length; i += 1) { + if (/^[A-Za-z_][A-Za-z0-9_]*:\s*$/.test(lines[i])) { + cpEnd = i; + break; + } + } + + /* 2. Retirar el proveedor heredado (lo dejaba el plugin eliminado). */ + const legacy = providerBlock(lines, cpStart, cpEnd, LEGACY_PROVIDER_ID); + if (legacy) { + lines.splice(legacy.head, legacy.end - legacy.head); + console.log(`Proveedor ${LEGACY_PROVIDER_ID} retirado de config.yaml.`); + } + + /* 3. Reemplazar el bloque previo de este proveedor, si habia uno. */ + cpEnd = Math.min(cpEnd, lines.length); + const current = providerBlock(lines, cpStart, cpEnd, PROVIDER_ID); + if (current) { + lines.splice(current.head, current.end - current.head); + console.log(`Bloque anterior de ${PROVIDER_ID} reemplazado.`); + } + + /* 4. Insertar como primer hijo de custom_provider. */ + if (!remove) { + const at = cpStart + 1; + lines.splice(at, 0, ...blockLines()); + console.log(`Proveedor ${PROVIDER_ID} registrado con ${MODELS.length} modelo(s).`); + } + + const next = lines.join(eol).replace(/(\r?\n){3,}/g, eol + eol); + const bak = `${CFG}.bak-${PROVIDER_ID}`; + if (!fs.existsSync(bak)) fs.writeFileSync(bak, raw, 'utf8'); + fs.writeFileSync(CFG, next, 'utf8'); + console.log('Backup:', bak); + if (!remove) { + console.log('Reinicia MiniMax Code para que el selector cargue los modelos nuevos.'); + } +} + +main(); diff --git a/plugins/jbolivar19/gemini-cli-bridge/scripts/session-start.mjs b/plugins/jbolivar19/gemini-cli-bridge/scripts/session-start.mjs new file mode 100644 index 00000000..80241523 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/scripts/session-start.mjs @@ -0,0 +1,68 @@ +#!/usr/bin/env node +/** + * SessionStart: asegura que el puente OpenAI-compatible este escuchando antes de + * que MiniMax Code intente usar el proveedor `gemini-cli-bridge`. + * + * Fallo abierto: si el puente no arranca, la sesion sigue normal y el proveedor + * simply responde con un error claro en vez de romper el inicio. + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawn } from 'node:child_process'; + +/* PLUGIN_ROOT lo inyecta el runtime, pero se deduce de la ubicacion del propio + script para que el hook tambien funcione cuando se ejecuta a mano. */ +const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url)); +const PLUGIN_ROOT = + process.env.PLUGIN_ROOT || process.env.MINIMAX_PLUGIN_ROOT || path.resolve(SCRIPT_DIR, '..'); +const PORT = Number(process.env.GEMINI_BRIDGE_PORT || 8789); +const HEALTH_TIMEOUT_MS = 1500; + +function dataDir() { + const injected = process.env.PLUGIN_DATA || process.env.MINIMAX_PLUGIN_DATA; + if (injected && injected.trim()) return path.resolve(injected); + return path.join(process.env.USERPROFILE || process.env.HOME || '', '.minimax', 'plugin-data', 'gemini-cli-bridge'); +} + +function healthy() { + return new Promise((resolve) => { + const req = fetch(`http://127.0.0.1:${PORT}/__health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) }) + .then((r) => r.ok) + .catch(() => false); + req.then(resolve, () => resolve(false)); + }); +} + +function startBridge() { + const script = path.join(PLUGIN_ROOT, 'scripts', 'bridge.mjs'); + const child = spawn(process.execPath, [script, '--port', String(PORT)], { + detached: true, + stdio: 'ignore', + env: { ...process.env, PLUGIN_DATA: dataDir() }, + }); + child.on('error', () => {}); + child.unref(); +} + +async function main() { + if (!PLUGIN_ROOT) return 0; + if (!(await healthy())) { + try { + startBridge(); + } catch { + /* fallo abierto */ + } + } + return 0; +} + +main().then( + () => { + process.exitCode = 0; + }, + () => { + process.exitCode = 0; + }, +); diff --git a/plugins/jbolivar19/gemini-cli-bridge/scripts/usage-ledger.cjs b/plugins/jbolivar19/gemini-cli-bridge/scripts/usage-ledger.cjs new file mode 100644 index 00000000..eadeb8e1 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/scripts/usage-ledger.cjs @@ -0,0 +1,156 @@ +'use strict'; +/** + * Registro de uso del CLI de Gemini. + * + * Cada consulta al CLI (por herramienta MCP o por el puente del selector) deja una + * linea JSONL con modelo, esfuerzo, tokens y duracion. Ese registro es la fuente + * de datos del Visualizer: el panel de coste y latencia por combinacion + * modelo/esfuerzo dibuja lo que el flujo de negocio ya midio, sin inventar nada. + * + * Vive en el directorio de datos del plugin (PLUGIN_DATA), que es de solo + * escritura para el host. + */ + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']; +const EFFORT_SUFFIX = /-(low|medium|high|xhigh|max)$/; + +function dataDir() { + const injected = process.env.PLUGIN_DATA || process.env.MINIMAX_PLUGIN_DATA; + if (injected && injected.trim()) return path.resolve(injected); + return path.join(os.homedir(), '.minimax', 'plugin-data', 'gemini-cli-bridge'); +} + +function ledgerFile() { + return path.join(dataDir(), 'usage.jsonl'); +} + +/** Anade una linea de uso. Nunca debe romper la consulta original. */ +function appendUsage(record) { + try { + fs.mkdirSync(dataDir(), { recursive: true }); + fs.appendFileSync(ledgerFile(), `${JSON.stringify(record)}\n`); + return true; + } catch { + return false; + } +} + +/** Lee el registro completo, ignorando lineas corruptas. */ +function readUsage() { + let raw = ''; + try { + raw = fs.readFileSync(ledgerFile(), 'utf8'); + } catch { + return []; + } + const out = []; + for (const line of raw.split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed) continue; + try { + const parsed = JSON.parse(trimmed); + if (parsed && typeof parsed === 'object') out.push(parsed); + } catch { + /* linea corrupta: se ignora */ + } + } + return out; +} + +/** Divide un id de modelo en modelo base y esfuerzo, sin importar cual se uso. */ +function normalize(model, effort) { + let base = typeof model === 'string' ? model.trim() : ''; + let resolved = typeof effort === 'string' ? effort.trim().toLowerCase() : ''; + const suffix = base.match(EFFORT_SUFFIX); + if (suffix) { + resolved = suffix[1]; + base = base.replace(EFFORT_SUFFIX, ''); + } + if (!resolved || !EFFORTS.includes(resolved)) resolved = 'low'; + return { model: base || 'gemini-4-hydrogen', effort: resolved }; +} + +function labelFor(model) { + const base = typeof model === 'string' ? model.replace(EFFORT_SUFFIX, '') : ''; + if (base === 'gemini-4-hydrogen') return 'Gemini 4 Hydrogen'; + const words = base.replace(/[-_]/g, ' ').trim(); + if (!words) return 'Gemini'; + return words.charAt(0).toUpperCase() + words.slice(1); +} + +/** + * Agrega el registro por combinacion modelo/esfuerzo. + * Devuelve el contrato que consume el Visualizer. + */ +function summarize(records) { + const groups = new Map(); + let totalCalls = 0; + let totalTokens = 0; + let durationSum = 0; + + for (const rec of records) { + const norm = normalize(rec.model, rec.effort); + const key = `${norm.model}::${norm.effort}`; + let g = groups.get(key); + if (!g) { + g = { + id: key, + model: norm.model, + effort: norm.effort, + model_label: labelFor(norm.model), + calls: 0, + duration_sum_s: 0, + input_tokens: 0, + output_tokens: 0, + thinking_tokens: 0, + total_tokens: 0, + last_conversation_id: null, + }; + groups.set(key, g); + } + g.calls += 1; + g.duration_sum_s += Number(rec.duration_seconds) || 0; + g.input_tokens += Number(rec.input_tokens) || 0; + g.output_tokens += Number(rec.output_tokens) || 0; + g.thinking_tokens += Number(rec.thinking_tokens) || 0; + g.total_tokens += Number(rec.total_tokens) || 0; + if (rec.conversation_id) g.last_conversation_id = rec.conversation_id; + totalCalls += 1; + totalTokens += Number(rec.total_tokens) || 0; + durationSum += Number(rec.duration_seconds) || 0; + } + + const rows = Array.from(groups.values()).map((g) => ({ + id: g.id, + model: g.model, + effort: g.effort, + model_label: g.model_label, + calls: g.calls, + avg_duration_s: g.calls ? Math.round((g.duration_sum_s / g.calls) * 10) / 10 : 0, + avg_input_tokens: g.calls ? Math.round(g.input_tokens / g.calls) : 0, + avg_output_tokens: g.calls ? Math.round(g.output_tokens / g.calls) : 0, + avg_thinking_tokens: g.calls ? Math.round(g.thinking_tokens / g.calls) : 0, + total_tokens: g.total_tokens, + last_conversation_id: g.last_conversation_id, + })); + + rows.sort((a, b) => b.calls - a.calls || a.model.localeCompare(b.model) || a.effort.localeCompare(b.effort)); + + return { + generated_at: new Date().toISOString(), + source: 'registro de consultas al CLI de Gemini (usage.jsonl del plugin)', + totals: { + calls: totalCalls, + total_tokens: totalTokens, + avg_duration_s: totalCalls ? Math.round((durationSum / totalCalls) * 10) / 10 : 0, + combinations: rows.length, + }, + rows, + }; +} + +module.exports = { appendUsage, readUsage, summarize, normalize, labelFor, EFFORTS }; diff --git a/plugins/jbolivar19/gemini-cli-bridge/server.js b/plugins/jbolivar19/gemini-cli-bridge/server.js new file mode 100644 index 00000000..5e2fd25b --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/server.js @@ -0,0 +1,700 @@ +#!/usr/bin/env node +'use strict'; + +/** + * Gemini CLI Bridge — servidor MCP (stdio) que expone el CLI de Gemini/Gemini CLI + * (Antigravity CLI) como herramientas para MiniMax Code. + * + * Implementación mínima del protocolo MCP sobre JSON-RPC 2.0 delimitado por saltos + * de línea. Sin dependencias externas: el paquete debe ser portable. + */ + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawn } = require('child_process'); +const usageLedger = require('./scripts/usage-ledger.cjs'); + +const SERVER_NAME = 'gemini-bridge'; +const SERVER_VERSION = '1.0.0'; +const DEFAULT_PROTOCOL = '2024-11-05'; +const SUPPORTED_PROTOCOLS = ['2024-10-07', '2024-11-05', '2025-03-26', '2025-06-18']; + +const DEFAULT_TIMEOUT_MS = 180000; +const MAX_TIMEOUT_MS = 900000; +const ARGV_PROMPT_LIMIT = 8000; +const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']; +const EFFORT_SUFFIX = /-(low|medium|high|xhigh|max)$/; + +/* El CLI trae sus propias herramientas (read_file, run_command, write_to_file) y + en modo print las auto-aprueba, o sea que puede escribir en el proyecto sin + que nadie lo pida. En modo consult se le pide por prompt que solo lea y + responda. En plan el CLI usa su propio --mode plan, que planifica sin tocar + el proyecto; en edit y auto las herramientas si son el objetivo. */ +const CONSULT_GUARD = + 'Puedes leer archivos del proyecto para darte contexto y responder con texto. ' + + 'No modifiques ni crees archivos, no ejecutes comandos ni uses herramientas ' + + 'que cambien el disco: solo redacta la respuesta en texto.'; + +/* ------------------------------------------------------------------ */ +/* Resolución del binario */ +/* ------------------------------------------------------------------ */ + +function isDir(p) { + try { + return fs.statSync(p).isDirectory(); + } catch (_) { + return false; + } +} + +function isFile(p) { + try { + return fs.statSync(p).isFile(); + } catch (_) { + return false; + } +} + +function readDirSafe(dir) { + try { + return fs.readdirSync(dir); + } catch (_) { + return []; + } +} + +function compareVersionsDesc(a, b) { + const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0); + const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0); + const len = Math.max(pa.length, pb.length); + for (let i = 0; i < len; i += 1) { + const va = pa[i] || 0; + const vb = pb[i] || 0; + if (va !== vb) return vb - va; + } + return 0; +} + +function runtimeRoots() { + const roots = []; + const home = os.homedir(); + const push = (p) => { + if (p && isDir(p)) roots.push(p); + }; + if (process.env.APPDATA) { + push(path.join(process.env.APPDATA, 'OpenBot', 'provider-runtimes', 'antigravity')); + } + push(path.join(home, 'Library', 'Application Support', 'OpenBot', 'provider-runtimes', 'antigravity')); + push(path.join(home, '.local', 'share', 'OpenBot', 'provider-runtimes', 'antigravity')); + push(path.join(home, '.config', 'OpenBot', 'provider-runtimes', 'antigravity')); + return roots; +} + +function managedRuntimeCandidates() { + const out = []; + const binNames = ['antigravity.exe', 'antigravity', 'antigravity.cmd']; + for (const root of runtimeRoots()) { + for (const platform of readDirSafe(root)) { + const platformDir = path.join(root, platform); + if (!isDir(platformDir)) continue; + const versions = readDirSafe(platformDir) + .filter((v) => isDir(path.join(platformDir, v))) + .sort(compareVersionsDesc); + for (const version of versions) { + for (const bin of binNames) { + const candidate = path.join(platformDir, version, 'bin', bin); + if (isFile(candidate)) out.push(candidate); + } + } + } + } + return out; +} + +function pathCandidates() { + const out = []; + const bins = ['antigravity.exe', 'antigravity', 'antigravity.cmd']; + const dirs = (process.env.PATH || '').split(path.delimiter).filter(Boolean); + for (const dir of dirs) { + for (const bin of bins) { + const candidate = path.join(dir, bin); + if (isFile(candidate)) out.push(candidate); + } + } + return out; +} + +let cachedCli; + +function resolveCli() { + if (cachedCli !== undefined) return cachedCli; + + const explicit = [process.env.ANTIGRAVITY_CLI, process.env.GEMINI_CLI_PATH] + .filter((v) => v && isFile(v)); + if (explicit.length) { + cachedCli = { path: explicit[0], source: 'env' }; + return cachedCli; + } + + const managed = managedRuntimeCandidates(); + if (managed.length) { + cachedCli = { path: managed[0], source: 'openbot-runtime' }; + return cachedCli; + } + + const onPath = pathCandidates(); + if (onPath.length) { + cachedCli = { path: onPath[0], source: 'PATH' }; + return cachedCli; + } + + cachedCli = null; + return cachedCli; +} + +function cliMissingMessage() { + return [ + 'No se encontró el CLI de Gemini (antigravity).', + 'Resolución probada: variable ANTIGRAVITY_CLI o GEMINI_CLI_PATH,', + 'runtime gestionado de OpenBot (provider-runtimes/antigravity) y PATH.', + 'Instala Gemini CLI o define ANTIGRAVITY_CLI con la ruta al ejecutable.', + ].join(' '); +} + +/* ------------------------------------------------------------------ */ +/* Ejecución del CLI */ +/* ------------------------------------------------------------------ */ + +function runCli(args, options) { + const opts = options || {}; + const cli = resolveCli(); + if (!cli) { + return Promise.resolve({ + ok: false, + notFound: true, + stdout: '', + stderr: cliMissingMessage(), + code: null, + }); + } + + return new Promise((resolve) => { + let child; + try { + child = spawn(cli.path, args, { + cwd: opts.cwd && isDir(opts.cwd) ? opts.cwd : process.cwd(), + env: process.env, + windowsHide: true, + shell: false, + }); + } catch (err) { + resolve({ ok: false, stdout: '', stderr: String(err && err.message), code: null }); + return; + } + + if (typeof opts.stdin === 'string') { + child.stdin.on('error', () => { + /* ignore EPIPE si el CLI ya cerro la entrada */ + }); + child.stdin.end(opts.stdin); + } else { + child.stdin.end(); + } + + let stdout = ''; + let stderr = ''; + let settled = false; + + const timer = setTimeout(() => { + if (settled) return; + settled = true; + try { + child.kill(); + } catch (_) { + /* ignore */ + } + resolve({ + ok: false, + stdout, + stderr: `Tiempo de espera agotado tras ${opts.timeoutMs || DEFAULT_TIMEOUT_MS} ms.`, + code: null, + timedOut: true, + }); + }, opts.timeoutMs || DEFAULT_TIMEOUT_MS); + + child.stdout.on('data', (chunk) => { + stdout += chunk.toString(); + }); + child.stderr.on('data', (chunk) => { + stderr += chunk.toString(); + }); + child.on('error', (err) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve({ ok: false, stdout, stderr: String(err && err.message), code: null }); + }); + child.on('close', (code) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve({ ok: code === 0, stdout, stderr, code }); + }); + }); +} + +function extractJson(text) { + if (!text) return null; + const trimmed = text.trim(); + try { + return JSON.parse(trimmed); + } catch (_) { + /* seguir buscando */ + } + for (let i = trimmed.lastIndexOf('{'); i >= 0; i = trimmed.lastIndexOf('{', i - 1)) { + for (let j = trimmed.lastIndexOf('}'); j > i; j = trimmed.lastIndexOf('}', j - 1)) { + try { + const parsed = JSON.parse(trimmed.slice(i, j + 1)); + if (parsed && typeof parsed === 'object') return parsed; + } catch (_) { + /* continuar */ + } + } + } + return null; +} + +function parseModelLines(text) { + const models = []; + const seen = new Set(); + for (const raw of String(text || '').split(/\r?\n/)) { + const line = raw.replace(/\s+$/, ''); + if (!line || line.startsWith('Fetching')) continue; + const tab = line.indexOf('\t'); + if (tab <= 0) continue; + const id = line.slice(0, tab).trim(); + const label = line.slice(tab + 1).trim(); + if (!id || !label || seen.has(id)) continue; + if (!/^[A-Za-z0-9._-]+$/.test(id)) continue; + seen.add(id); + models.push({ id, label }); + } + return models; +} + +/* ------------------------------------------------------------------ */ +/* Tools */ +/* ------------------------------------------------------------------ */ + +function ok(text, extra) { + const payload = { content: [{ type: 'text', text }] }; + if (extra) Object.assign(payload, extra); + return payload; +} + +function fail(text) { + return { content: [{ type: 'text', text }], isError: true }; +} + +function normalizeTimeout(value) { + const n = Number(value); + if (!Number.isFinite(n) || n <= 0) return DEFAULT_TIMEOUT_MS; + return Math.min(Math.round(n), MAX_TIMEOUT_MS); +} + +async function toolGeminiStatus() { + const cli = resolveCli(); + if (!cli) return fail(cliMissingMessage()); + + const version = await runCli(['--version'], { timeoutMs: 30000 }); + const models = await runCli(['models'], { timeoutMs: 120000 }); + const parsed = parseModelLines(models.stdout) || []; + const parsedFromErr = parsed.length ? parsed : parseModelLines(models.stderr); + const list = parsed.length ? parsed : parsedFromErr; + + const versionText = (version.stdout || version.stderr || '').trim().split(/\r?\n/)[0] || 'desconocida'; + const authOk = list.length > 0; + + const lines = [ + `CLI: ${cli.path}`, + `Origen: ${cli.source}`, + `Versión: ${versionText}`, + `Autenticación: ${authOk ? 'activa' : 'NO detectada (puede requerir inicio de sesión con Google)'}`, + `Modelos disponibles: ${list.length}`, + ]; + if (list.length) { + lines.push(''); + for (const m of list) lines.push(`- ${m.id} — ${m.label}`); + } + return ok(lines.join('\n')); +} + +async function toolGeminiModels() { + const result = await runCli(['models'], { timeoutMs: 120000 }); + const fromOut = parseModelLines(result.stdout); + const list = fromOut.length ? fromOut : parseModelLines(result.stderr); + if (!list.length) { + const detail = (result.stderr || result.stdout || '').trim(); + return fail(`No se pudieron listar los modelos.\n${detail || 'El CLI no devolvió salida.'}`); + } + const lines = list.map((m) => `- ${m.id} — ${m.label}`); + return ok(`${list.length} modelo(s) disponible(s):\n${lines.join('\n')}`); +} + +function buildPromptArgs(params) { + const args = []; + const mode = params.mode || 'consult'; + + if (mode === 'plan') { + args.push('--mode', 'plan'); + } else if (mode === 'edit') { + args.push('--mode', 'accept-edits'); + args.push('--dangerously-skip-permissions'); + } else if (mode === 'auto') { + args.push('--mode', 'auto'); + args.push('--dangerously-skip-permissions'); + } + + const model = typeof params.model === 'string' ? params.model.trim() : ''; + const effort = typeof params.effort === 'string' ? params.effort.trim().toLowerCase() : ''; + + if (effort && !EFFORTS.includes(effort)) { + return { error: `Esfuerzo inválido: "${effort}". Valores permitidos: ${EFFORTS.join(', ')}.` }; + } + + if (model) { + if (effort) { + // El sufijo de esfuerzo y --effort son excluyentes: se usa el modelo base. + const base = model.replace(EFFORT_SUFFIX, ''); + args.push('--model', base); + args.push('--effort', effort); + } else { + args.push('--model', model); + } + } else if (effort) { + args.push('--effort', effort); + } + + if (params.conversation_id) { + args.push('--conversation', String(params.conversation_id)); + } + + const prompt = + mode === 'consult' ? `${CONSULT_GUARD}\n\n${String(params.prompt)}` : String(params.prompt); + + // Windows limita la linea de comandos a ~32767 caracteres. Un prompt largo se + // envia por stdin en modo stream-json; uno corto viaja como argumento. + if (prompt.length > ARGV_PROMPT_LIMIT) { + args.push('--input-format', 'stream-json'); + args.push('--output-format', 'stream-json'); + return { + args, + stdin: + JSON.stringify({ + event: 'user', + message: { role: 'user', content: [{ type: 'text', text: prompt }] }, + }) + '\n', + }; + } + + args.push('--output-format', 'json'); + args.push('--print', prompt); + return { args }; +} + +/* El modo stream-json responde con varias lineas NDJSON; la ultima lleva el evento "result". */ +function extractStreamResult(text) { + const lines = String(text || '').split(/\r?\n/); + for (let i = lines.length - 1; i >= 0; i -= 1) { + const line = lines[i].trim(); + if (!line || line[0] !== '{') continue; + try { + const parsed = JSON.parse(line); + if (parsed && parsed.event === 'result' && parsed.result) return parsed.result; + } catch (_) { + /* seguir hacia atras */ + } + } + return null; +} + +async function toolGeminiPrompt(params) { + const prompt = typeof params.prompt === 'string' ? params.prompt.trim() : ''; + if (!prompt) return fail('Falta el parámetro "prompt" con la consulta para Gemini.'); + + const built = buildPromptArgs(params); + if (built.error) return fail(built.error); + + const timeoutMs = normalizeTimeout(params.timeout_ms); + const result = await runCli(built.args, { + cwd: params.cwd, + timeoutMs, + stdin: built.stdin, + }); + + if (result.notFound) return fail(cliMissingMessage()); + if (result.timedOut) { + return fail( + `Gemini no respondió dentro de ${timeoutMs} ms.\n` + + 'Reduce el alcance de la consulta o eleva "timeout_ms" (máximo 900000).', + ); + } + + const payload = built.stdin + ? extractStreamResult(result.stdout) || extractJson(result.stdout) || extractJson(result.stderr) + : extractJson(result.stdout) || extractJson(result.stderr); + if (!payload) { + const detail = (result.stdout || result.stderr || '').trim(); + return fail( + `El CLI no devolvió una respuesta interpretable (código ${result.code}).\n${detail.slice(0, 4000)}`, + ); + } + + if (payload.status && payload.status !== 'SUCCESS') { + const reason = payload.error || payload.finished_reason || 'error desconocido'; + const models = (result.stderr.match(/Available models:[\s\S]*/) || [''])[0].trim(); + const detail = models ? `\n${models}` : ''; + return fail(`Gemini respondió con error: ${reason}${detail}`); + } + + const usage = payload.usage || {}; + + /* Registro de uso: fuente de datos del panel de coste y latencia. */ + const effective = usageLedger.normalize(params.model, params.effort); + usageLedger.appendUsage({ + ts: new Date().toISOString(), + model: effective.model, + effort: effective.effort, + mode: params.mode || 'consult', + duration_seconds: Number(payload.duration_seconds) || 0, + input_tokens: Number(usage.input_tokens) || 0, + output_tokens: Number(usage.output_tokens) || 0, + thinking_tokens: Number(usage.thinking_tokens) || 0, + total_tokens: Number(usage.total_tokens) || 0, + conversation_id: payload.conversation_id || null, + }); + + const meta = [ + '', + '---', + `Modelo: ${params.model || 'por defecto'}`, + params.effort ? `Esfuerzo: ${params.effort}` : null, + `Modo: ${params.mode || 'consult'}`, + `Duración: ${payload.duration_seconds || 0}s`, + `Tokens: entrada ${usage.input_tokens || 0} / salida ${usage.output_tokens || 0}` + + (usage.thinking_tokens ? ` / razonamiento ${usage.thinking_tokens}` : ''), + payload.conversation_id ? `Conversación: ${payload.conversation_id}` : null, + ] + .filter(Boolean) + .join('\n'); + + const body = String(payload.response || '').replace(/\s+$/, ''); + return ok(`${body}\n${meta}`); +} + +/** + * Datos agregados de uso, listos para el panel de coste y latencia. + * No inventa nada: solo agrega lo que el flujo ya midio. + */ +function toolGeminiUsage(params) { + const summary = usageLedger.summarize(usageLedger.readUsage()); + const filter = typeof params.model === 'string' ? params.model.trim().toLowerCase() : ''; + if (filter) { + summary.rows = summary.rows.filter((r) => r.model.toLowerCase().includes(filter)); + summary.totals.combinations = summary.rows.length; + } + return ok(JSON.stringify(summary, null, 2)); +} + +/* ------------------------------------------------------------------ */ +/* Definición de herramientas */ +/* ------------------------------------------------------------------ */ + +const TOOLS = [ + { + name: 'gemini_status', + description: + 'Comprueba si el CLI de Gemini está disponible, su versión, si la autenticación con Google está activa y qué modelos expone. Úsalo antes de la primera consulta si hay dudas de acceso.', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + }, + { + name: 'gemini_models', + description: + 'Lista los modelos de IA disponibles en el CLI de Gemini con su identificador exacto y su etiqueta. Usa el identificador devuelto aquí en el parámetro "model".', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + }, + { + name: 'gemini_prompt', + description: + 'Envía una consulta a Gemini y devuelve su respuesta. Admite modelo, esfuerzo de razonamiento (low|medium|high|xhigh|max) y modo: "consult" solo responde, "plan" analiza sin tocar archivos, "edit" trabaja sobre los archivos del directorio de trabajo, "auto" opera de forma autónoma. Devuelve el conversation_id para continuar la misma conversación.', + inputSchema: { + type: 'object', + properties: { + prompt: { type: 'string', description: 'La consulta para Gemini.' }, + model: { + type: 'string', + description: + 'Identificador del modelo (p. ej. "gemini-4-hydrogen"). Si además indicas "effort", se usa el modelo base con ese esfuerzo.', + }, + effort: { + type: 'string', + enum: EFFORTS, + description: 'Esfuerzo de razonamiento. No puede combinarse con un modelo que ya traiga el sufijo de esfuerzo.', + }, + mode: { + type: 'string', + enum: ['consult', 'plan', 'edit', 'auto'], + description: + 'consult: solo responde. plan: analiza y propone sin modificar archivos. edit: puede editar archivos del directorio. auto: opera de forma autónoma.', + }, + cwd: { + type: 'string', + description: 'Directorio de trabajo para Gemini. Por defecto, el directorio actual.', + }, + conversation_id: { + type: 'string', + description: 'ID de conversación previa devuelto por una llamada anterior, para continuar el hilo.', + }, + timeout_ms: { + type: 'number', + description: `Tiempo máximo de espera en milisegundos (por defecto ${DEFAULT_TIMEOUT_MS}, máximo ${MAX_TIMEOUT_MS}).`, + }, + }, + required: ['prompt'], + additionalProperties: false, + }, + }, + { + name: 'gemini_usage', + description: + 'Devuelve el uso agregado del CLI de Gemini: por cada combinación de modelo y esfuerzo, las consultas, la latencia media y los tokens medios y totales. Úsalo para comparar el coste y la rapidez de cada nivel de esfuerzo antes de elegir uno.', + inputSchema: { + type: 'object', + properties: { + model: { + type: 'string', + description: 'Filtra las filas cuyo id de modelo contenga este texto. Opcional.', + }, + }, + additionalProperties: false, + }, + }, +]; + +/* ------------------------------------------------------------------ */ +/* Servidor MCP (JSON-RPC 2.0 sobre stdio) */ +/* ------------------------------------------------------------------ */ + +function send(message) { + process.stdout.write(`${JSON.stringify(message)}\n`); +} + +function respond(id, result) { + if (id === undefined || id === null) return; + send({ jsonrpc: '2.0', id, result }); +} + +function respondError(id, code, message) { + if (id === undefined || id === null) return; + send({ jsonrpc: '2.0', id, error: { code, message } }); +} + +async function callTool(name, args) { + switch (name) { + case 'gemini_status': + return toolGeminiStatus(); + case 'gemini_models': + return toolGeminiModels(); + case 'gemini_prompt': + return toolGeminiPrompt(args || {}); + case 'gemini_usage': + return toolGeminiUsage(args || {}); + default: + return fail(`Herramienta desconocida: ${name}`); + } +} + +async function handle(message) { + const { id, method, params } = message; + + switch (method) { + case 'initialize': + respond(id, { + protocolVersion: SUPPORTED_PROTOCOLS.includes(params && params.protocolVersion) + ? params.protocolVersion + : DEFAULT_PROTOCOL, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: SERVER_NAME, version: SERVER_VERSION }, + }); + return; + + case 'notifications/initialized': + case 'notifications/cancelled': + return; + + case 'ping': + respond(id, {}); + return; + + case 'tools/list': + respond(id, { tools: TOOLS }); + return; + + case 'tools/call': + try { + const result = await callTool(params && params.name, (params && params.arguments) || {}); + respond(id, result); + } catch (err) { + respond(id, fail(`Fallo interno: ${String(err && err.message)}`)); + } + return; + + case 'resources/list': + respond(id, { resources: [] }); + return; + + case 'prompts/list': + respond(id, { prompts: [] }); + return; + + default: + if (method && method.startsWith('notifications/')) return; + respondError(id, -32601, `Método no soportado: ${method}`); + } +} + +function main() { + let buffer = ''; + + process.stdin.setEncoding('utf8'); + process.stdin.on('data', (chunk) => { + buffer += chunk; + let index = buffer.indexOf('\n'); + while (index !== -1) { + const line = buffer.slice(0, index).trim(); + buffer = buffer.slice(index + 1); + index = buffer.indexOf('\n'); + if (!line) continue; + let message; + try { + message = JSON.parse(line); + } catch (_) { + continue; + } + Promise.resolve(handle(message)).catch(() => { + /* nunca romper el stream */ + }); + } + }); + + process.stdin.on('end', () => { + process.exit(0); + }); + + process.on('uncaughtException', (err) => { + process.stderr.write(`[gemini-bridge] ${String(err && err.stack)}\n`); + }); +} + +main(); diff --git a/plugins/jbolivar19/gemini-cli-bridge/servers.mcp.json b/plugins/jbolivar19/gemini-cli-bridge/servers.mcp.json new file mode 100644 index 00000000..d99b97d2 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/servers.mcp.json @@ -0,0 +1,15 @@ +{ + "schemaVersion": 1, + "mcpServers": { + "gemini-bridge": { + "type": "stdio", + "command": "node", + "args": [ + "./server.js" + ], + "env": {}, + "description": "Expone los modelos del CLI de Gemini (Antigravity CLI) como herramientas: estado, modelos y consultas con modelo, esfuerzo y modo.", + "timeout": 900000 + } + } +} diff --git a/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/SKILL.md b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/SKILL.md new file mode 100644 index 00000000..cc2f052c --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/SKILL.md @@ -0,0 +1,73 @@ +--- +name: gemini-bridge-visualizer +description: Dibujar el panel de coste y latencia del CLI de Gemini a partir de los datos agregados de uso, para comparar modelo y nivel de esfuerzo antes de elegir con que nivel trabajar. Usar cuando el usuario pregunte cuanto cuesta o cuanto tarda cada nivel de esfuerzo de Gemini, o pida comparar el uso de los modelos del CLI. +--- + +# Panel de coste y latencia de Gemini + +Renderiza el panel de uso del CLI de Gemini como un Widget `mavis.widget.v1` de tipo +`dashboard`, a partir del resultado estructurado que produce el flujo de negocio. + +## Regla de oro + +Este Skill **no pide datos**: transforma el resultado de la herramienta `gemini_usage` del +servidor MCP `gemini-bridge`. Si no hay datos, responde en texto. Jamas inventes filas, +metricas ni conclusiones, y nunca repitas una llamada autenticada al CLI desde el Widget. + +## Cuando renderizar + +- **Renderiza** cuando el usuario pregunte por coste, tokens, latencia o duracion de Gemini, + o pida comparar niveles de esfuerzo o modelos. +- **No renderizes** cuando el usuario solo quiere una respuesta de Gemini. Ahi contesta con + texto: el panel anade ruido si la peticion no es sobre el uso. +- **No renderices** sin datos. Si `gemini_usage` devuelve `rows: []`, responde en texto + diciendo que aun no hay consultas registradas y como generarlas. + +## Procedimiento + +1. Llama a la herramienta `gemini_usage` del servidor MCP `gemini-bridge`. Si el MCP no esta + disponible, continua con texto: nunca inventes los datos. +2. Lee `references/genui-widget/SKILL.md` y sus referencias (`color-system.md`, + `visual-rules.md`, `widget-patterns.md`, `widget-recipes.md`) antes de emitir el Widget. +3. Elige el componente segun `references/components.md` y el renderizador segun el numero de + filas comparables. Con 5 filas o menos usa CSS/SVG; con 6 o mas, Chart.js. +4. Emite **exactamente un** `` final, con `mavis-meta`, `mavis-style`, + `mavis-html`, `mavis-data`, `mavis-script` y `mavis-fallback` en ese orden. +5. No llames a ninguna herramienta despues de emitir el Widget. + +## Contrato de datos + +La fuente es `gemini_usage`, cuyo resultado sigue `references/data-schema.json`: + +- `totals`: llamadas, tokens totales, latencia media y numero de combinaciones. +- `rows[]`: una fila por combinacion modelo/esfuerzo con `id`, `model`, `effort`, + `model_label`, `calls`, `avg_duration_s`, `avg_input_tokens`, `avg_output_tokens`, + `avg_thinking_tokens`, `total_tokens` y `last_conversation_id`. + +El `id` de la fila es estable (`model::effort`): usalo como identificador en +`selectedData` para que la accion posterior apunte a la fila exacta. + +## Estados + +- **Normal**: el dashboard con KPIs, comparativa por combinacion y tabla. +- **Vacio**: `rows` vacio. Mantiene el marco y explica en una linea que no hay consultas + registradas todavia. +- **Error**: si `gemini_usage` falla, conserva el texto de respuesta del flujo de negocio y + no emits Widget. +- **Cargando**: el Widget muestra la estructura con KPI en `--` y las pistas de carga. + +## Interacciones + +- Filtrar por modelo, ordenar por metrica y alternar entre tokens y latencia son cambios + **locales** en JavaScript: nunca van al modelo. +- Las acciones de razonamiento usan `window.mavis.sendPrompt()` con un payload minimo: + la fila exacta (`id`, `model`, `effort`), la metrica y la intencion del usuario. +- `text` y `userIntent` van en el idioma de la conversacion. +- Si el Host no soporta `sendPrompt`, quita esa capacidad del Widget y deja solo + interacciones locales. + +## Limites + +- El Widget nunca contiene claves, tokens de API ni rutas sensibles. +- Si `sendPrompt` no esta verificado en el Host, no lo anuncies ni lo simules. +- El texto de `mavis-fallback` es la version sin Widget: debe bastar por si solo. diff --git a/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/genui.json b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/genui.json new file mode 100644 index 00000000..5ce2f02a --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/genui.json @@ -0,0 +1,6 @@ +{ + "protocol": "mavis.widget.v1", + "mode": "forked", + "forkedFrom": "minimax/genui-widget@mavis.widget.v1", + "sourceDigest": "sha256:9fcd5d8eb2178cac3b25beea334a9d5e3d395eb2f01a24cea529933bc7cfeb4d" +} diff --git a/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/components.md b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/components.md new file mode 100644 index 00000000..8057f3b2 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/components.md @@ -0,0 +1,75 @@ +# Componentes del panel de uso de Gemini + +Recetas de dominio para el panel de coste y latencia del CLI de Gemini. La base +generica esta en `genui-widget/references/`. + +## Receta: comparativa de coste y latencia por combinacion + +**Pregunta de negocio.** "Cuanto me cuesta y cuanto tarda cada nivel de esfuerzo de +Gemini, y cual me conviene?" + +**Regla de seleccion.** Se usa cuando el usuario pregunta por coste, tokens, latencia o +duracion, o pide comparar niveles de esfuerzo o modelos. No se usa para pedir una +respuesta de Gemini: ahi contesta el flujo de negocio con texto. + +**Campos de entrada.** `totals.calls`, `totals.total_tokens`, `totals.avg_duration_s`, +`totals.combinations` y `rows[]` con `id`, `model`, `effort`, `model_label`, `calls`, +`avg_duration_s`, `avg_input_tokens`, `avg_output_tokens`, `avg_thinking_tokens`, +`total_tokens`. + +**Unidades.** Latencia en segundos con un decimal. Tokens en enteros. Sin separadores de +miles: los numeros se redondean con `Intl.NumberFormat` y el locale de la conversacion. + +**Politica de nulos.** `avg_*` y `calls` nunca son null en la practica: el agregado +devuelve 0 cuando una combinacion no tiene consultas, y la fila no se emite en ese caso. +`last_conversation_id` puede ser null y se omite del Widget. Si una fila llega sin +`avg_duration_s`, se trata como 0. + +**Procedencia.** Toda cifra viene de `gemini_usage`, que agrega el registro `usage.jsonl` +del plugin. El Widget muestra la procedencia en `mavis-meta.dataSource` y nunca infiere +valores que no esten en el resultado. + +**Tipo de Widget.** `dashboard`. + +**Jerarquia visual.** + +1. Fila de KPIs: consultas, tokens totales, latencia media, combinaciones medidas. +2. Comparativa principal: una barra por combinacion modelo/esfuerzo. +3. Tabla de detalle con el desglose de tokens por combinacion. + +**Layout.** KPIs en `grid-template-columns: repeat(4, 1fr)`. Comparativa en una columna +completa. Tabla debajo a ancho completo. + +**Regla del renderizador.** Con **5 filas comparables o menos** usa CSS/SVG (barras de +banco) y **no** llames a `new Chart(...)`. Con **6 filas o mas** usa Chart.js con un +contenedor de altura explicita y `maintainAspectRatio: false`. + +**Interacciones locales.** + +- Alternar la metrica de las barras entre tokens y latencia: cambia las barras en el + navegador, sin llamar al modelo. +- Ordenar las filas por consultas, tokens o latencia: reordena la tabla en local. +- Filtrar por modelo: filtra filas en local. +- Marcar la combinacion seleccionada: resalta la fila y la barra. + +**Acciones de razonamiento.** Dos, como maximo, sobre elementos visibles: + +1. Pulsar una barra: repetir la ultima consulta con esa combinacion y comparar el + resultado. Payload: `selectedData` con la fila exacta (`id`, `model`, `effort`, + `avg_duration_s`, `total_tokens`, `calls`) y `userIntent` describiendo la intencion. +2. Pulsar un KPI de latencia: explicar que nivel de esfuerzo conviene segun la latencia + medida. Payload: `selectedData` con `totals` y las filas de las combinaciones con mayor + latencia. + +**Estados.** + +- *Normal*: dashboard completo. +- *Cargando*: KPIs en `--`, pistas de carga en las barras, tabla con filas de esqueleto. +- *Vacio*: se mantiene el marco y se explica en una linea centrada que aun no hay + consultas registradas y como generarlas. +- *Error*: si `gemini_usage` falla, no se emite Widget; el flujo de negocio responde en + texto. +- *Auth*: si el CLI no esta autenticado, se dice en texto; el panel no puede medirse. + +**Fallback de texto.** La version sin Widget lista las combinaciones con consultas, +tokens y latencia media en texto plano, mas la procedencia. Debe bastar por si solo. diff --git a/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/data-schema.json b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/data-schema.json new file mode 100644 index 00000000..757ae014 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/data-schema.json @@ -0,0 +1,52 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Uso agregado del CLI de Gemini", + "description": "Resultado de la herramienta MCP gemini_usage: uso agregado por combinacion de modelo y nivel de esfuerzo.", + "type": "object", + "required": ["generated_at", "source", "totals", "rows"], + "additionalProperties": false, + "properties": { + "generated_at": { + "type": "string", + "description": "Marca de tiempo ISO 8601 del momento en que se genero el agregado.", + "format": "date-time" + }, + "source": { + "type": "string", + "description": "Procedencia del dato, para que el usuario sepa de donde sale." + }, + "totals": { + "type": "object", + "required": ["calls", "total_tokens", "avg_duration_s", "combinations"], + "additionalProperties": false, + "properties": { + "calls": { "type": "integer", "minimum": 0, "description": "Consultas registradas en total." }, + "total_tokens": { "type": "integer", "minimum": 0, "description": "Tokens consumidos en total." }, + "avg_duration_s": { "type": "number", "minimum": 0, "description": "Latencia media en segundos, redondeada a un decimal." }, + "combinations": { "type": "integer", "minimum": 0, "description": "Numero de combinaciones modelo/esfuerzo distintas." } + } + }, + "rows": { + "type": "array", + "description": "Una fila por combinacion de modelo y esfuerzo, ordenada por consultas descendentes.", + "items": { + "type": "object", + "required": ["id", "model", "effort", "model_label", "calls", "avg_duration_s", "avg_input_tokens", "avg_output_tokens", "avg_thinking_tokens", "total_tokens"], + "additionalProperties": false, + "properties": { + "id": { "type": "string", "description": "Identificador estable de la fila, con forma model::effort." }, + "model": { "type": "string", "description": "Id del modelo base, sin sufijo de esfuerzo." }, + "effort": { "type": "string", "enum": ["low", "medium", "high", "xhigh", "max"], "description": "Nivel de esfuerzo de razonamiento." }, + "model_label": { "type": "string", "description": "Nombre legible del modelo." }, + "calls": { "type": "integer", "minimum": 0, "description": "Consultas hechas con esta combinacion." }, + "avg_duration_s": { "type": "number", "minimum": 0, "description": "Latencia media en segundos." }, + "avg_input_tokens": { "type": "integer", "minimum": 0, "description": "Tokens de entrada medios por consulta." }, + "avg_output_tokens": { "type": "integer", "minimum": 0, "description": "Tokens de salida medios por consulta." }, + "avg_thinking_tokens": { "type": "integer", "minimum": 0, "description": "Tokens de razonamiento medios por consulta." }, + "total_tokens": { "type": "integer", "minimum": 0, "description": "Tokens totales de esta combinacion." }, + "last_conversation_id": { "type": ["string", "null"], "description": "Ultima conversacion del CLI para esta combinacion, o null." } + } + } + } + } +} diff --git a/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/examples.md b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/examples.md new file mode 100644 index 00000000..4fc6a945 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/examples.md @@ -0,0 +1,307 @@ +# Ejemplos del panel de uso de Gemini + +Ejemplo representativo y completo, grounded en `references/data-schema.json`. Usa 4 filas +comparables, asi que el renderizador es CSS/SVG: las barras se construyen con HTML y CSS, +sin ninguna libreria de graficos instanciada. + +## Ejemplo: comparativa de coste y latencia por combinacion + +Datos de entrada (resultado de `gemini_usage` con 4 combinaciones medidas): + +```json +{ + "generated_at": "2026-12-01T15:10:00.000Z", + "source": "registro de consultas al CLI de Gemini (usage.jsonl del plugin)", + "totals": { + "calls": 24, + "total_tokens": 314880, + "avg_duration_s": 11.4, + "combinations": 4 + }, + "rows": [ + { + "id": "gemini-4-hydrogen::high", + "model": "gemini-4-hydrogen", + "effort": "high", + "model_label": "Gemini 4 Hydrogen", + "calls": 12, + "avg_duration_s": 14.8, + "avg_input_tokens": 12340, + "avg_output_tokens": 640, + "avg_thinking_tokens": 410, + "total_tokens": 160680, + "last_conversation_id": "5f0da440-80c6-4fc3-9d56-bda1abf1f533" + }, + { + "id": "gemini-4-hydrogen::low", + "model": "gemini-4-hydrogen", + "effort": "low", + "model_label": "Gemini 4 Hydrogen", + "calls": 8, + "avg_duration_s": 7.2, + "avg_input_tokens": 12110, + "avg_output_tokens": 190, + "avg_thinking_tokens": 95, + "total_tokens": 98320, + "last_conversation_id": null + }, + { + "id": "gemini-4-hydrogen::medium", + "model": "gemini-4-hydrogen", + "effort": "medium", + "model_label": "Gemini 4 Hydrogen", + "calls": 3, + "avg_duration_s": 10.1, + "avg_input_tokens": 12260, + "avg_output_tokens": 390, + "avg_thinking_tokens": 220, + "total_tokens": 38610, + "last_conversation_id": null + }, + { + "id": "gemini-4-hydrogen::xhigh", + "model": "gemini-4-hydrogen", + "effort": "xhigh", + "model_label": "Gemini 4 Hydrogen", + "calls": 1, + "avg_duration_s": 26.4, + "avg_input_tokens": 12770, + "avg_output_tokens": 890, + "avg_thinking_tokens": 720, + "total_tokens": 17270, + "last_conversation_id": null + } + ] +} +``` + +Widget resultante: + + + {"summary":"El esfuerzo alto concentra la mitad de las consultas y los tokens, mientras xhigh multiplica la latencia por casi cuatro.","dataSource":"registro de consultas al CLI de Gemini (usage.jsonl del plugin)","chartType":"kpi","datasetShape":{"rows":4,"dimensions":["model","effort"],"measures":["calls","total_tokens","avg_duration_s"]},"interactions":[{"id":"drill-combo","label":"Comparar esta combinacion en detalle","capability":"sendPrompt"},{"id":"explain-latency","label":"Explicar que nivel de esfuerzo conviene","capability":"sendPrompt"}]} + + body { margin: 0; padding: 16px; background: var(--mw-bg); color: var(--mw-text); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 14px; } + .kpi-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 16px; } + .kpi { background: var(--mw-surface); border: 1px solid var(--mw-border); border-radius: 10px; padding: 14px; } + .kpi-label { font-size: 12px; color: var(--mw-text-muted); margin-bottom: 4px; } + .kpi-value { font-size: 24px; font-weight: 700; color: var(--mw-text); } + .kpi-note { font-size: 12px; color: var(--mw-text-subtle); margin-top: 4px; } + .card { background: var(--mw-surface); border: 1px solid var(--mw-border); border-radius: 10px; padding: 16px; margin-bottom: 14px; } + .card-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 12px; flex-wrap: wrap; } + .card-title { font-size: 14px; font-weight: 500; } + .legend { display: flex; gap: 16px; font-size: 12px; color: var(--mw-text-muted); } + .legend-item { display: flex; align-items: center; gap: 6px; } + .legend-dot { width: 10px; height: 10px; border-radius: 3px; } + .toggle { display: flex; gap: 6px; } + .toggle-btn { font: inherit; font-size: 12px; padding: 4px 10px; border-radius: 8px; border: 1px solid var(--mw-border); background: var(--mw-surface); color: var(--mw-text-muted); cursor: pointer; } + .toggle-btn[aria-pressed="true"] { background: var(--mw-surface-muted); color: var(--mw-text); border-color: var(--mw-accent); } + .bench { display: grid; grid-template-columns: 148px 1fr 84px; gap: 12px; align-items: center; padding: 7px 0; border-radius: 8px; } + .bench[data-selected="true"] { background: var(--mw-surface-muted); } + .bench-label { font-size: 13px; color: var(--mw-text); } + .bench-track { height: 18px; background: var(--mw-surface-muted); border-radius: 6px; overflow: hidden; } + .bench-fill { height: 100%; background: var(--mw-accent); border-radius: 6px; } + .bench-val { font-size: 13px; font-weight: 500; color: var(--mw-text); text-align: right; font-variant-numeric: tabular-nums; } + .table { width: 100%; border-collapse: collapse; } + .table th { padding: 8px 12px; text-align: left; font-size: 12px; font-weight: 500; color: var(--mw-text-muted); background: var(--mw-surface-muted); border-bottom: 1px solid var(--mw-border); } + .table th.num { text-align: right; } + .table td { padding: 9px 12px; border-bottom: 1px solid var(--mw-border); font-size: 13px; } + .table td.num { text-align: right; font-variant-numeric: tabular-nums; } + .table tr:last-child td { border-bottom: none; } + .hint { font-size: 12px; color: var(--mw-text-subtle); margin-top: 10px; } + + +
+
+
Consultas
+
24
+
Pulsar para ver que nivel conviene
+
+
+
Tokens totales
+
314.880
+
Entrada, salida y razonamiento
+
+
+
Latencia media
+
11,4 s
+
Por consulta registrada
+
+
+
Combinaciones
+
4
+
Modelo y esfuerzo medidos
+
+
+ +
+
+
Coste por combinacion modelo y esfuerzo
+
+ + +
+
+
+ Tokens totales + Latencia media +
+
+

Pulsar una barra para comparar esa combinacion en detalle.

+
+ +
+
+
Desglose por combinacion
+
+ + + + + + + + + + + + +
EsfuerzoConsultasLatencia mediaTokens entradaTokens salidaTokens total
+
+
+ [{"id":"gemini-4-hydrogen::high","model":"gemini-4-hydrogen","effort":"high","model_label":"Gemini 4 Hydrogen","calls":12,"avg_duration_s":14.8,"avg_input_tokens":12340,"avg_output_tokens":640,"avg_thinking_tokens":410,"total_tokens":160680,"last_conversation_id":"5f0da440-80c6-4fc3-9d56-bda1abf1f533"},{"id":"gemini-4-hydrogen::low","model":"gemini-4-hydrogen","effort":"low","model_label":"Gemini 4 Hydrogen","calls":8,"avg_duration_s":7.2,"avg_input_tokens":12110,"avg_output_tokens":190,"avg_thinking_tokens":95,"total_tokens":98320,"last_conversation_id":null},{"id":"gemini-4-hydrogen::medium","model":"gemini-4-hydrogen","effort":"medium","model_label":"Gemini 4 Hydrogen","calls":3,"avg_duration_s":10.1,"avg_input_tokens":12260,"avg_output_tokens":390,"avg_thinking_tokens":220,"total_tokens":38610,"last_conversation_id":null},{"id":"gemini-4-hydrogen::xhigh","model":"gemini-4-hydrogen","effort":"xhigh","model_label":"Gemini 4 Hydrogen","calls":1,"avg_duration_s":26.4,"avg_input_tokens":12770,"avg_output_tokens":890,"avg_thinking_tokens":720,"total_tokens":17270,"last_conversation_id":null}] + + (function () { + var rows = window.__mavisData['main'] || []; + var nf = new Intl.NumberFormat('es-CO'); + var metric = 'total_tokens'; + var selected = null; + + var benches = document.getElementById('benches'); + var tbody = document.getElementById('rows'); + + function valueOf(row, key) { + return key === 'avg_duration_s' ? row.avg_duration_s : row.total_tokens; + } + + function unit(key) { + return key === 'avg_duration_s' ? ' s' : ''; + } + + function render() { + var max = 0; + rows.forEach(function (r) { max = Math.max(max, valueOf(r, metric)); }); + if (max <= 0) max = 1; + + benches.innerHTML = ''; + rows.forEach(function (row) { + var pct = Math.round((valueOf(row, metric) / max) * 100); + var bench = document.createElement('div'); + bench.className = 'bench'; + bench.setAttribute('data-selected', String(selected === row.id)); + bench.setAttribute('data-action', 'drill-combo'); + bench.setAttribute('data-id', row.id); + bench.setAttribute('role', 'button'); + bench.setAttribute('tabindex', '0'); + bench.innerHTML = + '' + row.model_label + ' · ' + row.effort + '' + + '' + + '' + nf.format(valueOf(row, metric)) + unit(metric) + ''; + bench.addEventListener('click', function () { drill(row); }); + bench.addEventListener('keydown', function (ev) { + if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); drill(row); } + }); + benches.appendChild(bench); + }); + } + + function renderTable() { + tbody.innerHTML = ''; + rows.forEach(function (row) { + var tr = document.createElement('tr'); + tr.innerHTML = + '' + row.effort + '' + + '' + nf.format(row.calls) + '' + + '' + nf.format(row.avg_duration_s) + ' s' + + '' + nf.format(row.avg_input_tokens) + '' + + '' + nf.format(row.avg_output_tokens) + '' + + '' + nf.format(row.total_tokens) + ''; + tbody.appendChild(tr); + }); + } + + function drill(row) { + selected = row.id; + render(); + window.mavis.sendPrompt( + 'Compara en detalle la combinacion ' + row.model_label + ' con esfuerzo ' + row.effort + + ': su latencia media, sus tokens y si compensa frente a los demas niveles.', + { + widgetTitle: 'Coste y latencia por nivel de esfuerzo en Gemini', + action: 'drill-combo', + selectedData: { + id: row.id, + model: row.model, + effort: row.effort, + calls: row.calls, + avg_duration_s: row.avg_duration_s, + total_tokens: row.total_tokens + }, + visibleFilters: { metric: metric }, + userIntent: 'comparar en detalle una combinacion de modelo y esfuerzo' + } + ); + } + + document.querySelectorAll('.toggle-btn[data-metric]').forEach(function (btn) { + btn.addEventListener('click', function () { + metric = btn.getAttribute('data-metric'); + document.querySelectorAll('.toggle-btn[data-metric]').forEach(function (other) { + other.setAttribute('aria-pressed', String(other === btn)); + }); + render(); + }); + }); + + document.querySelector('[data-action="explain-latency"]').addEventListener('click', function () { + var slowest = rows.slice().sort(function (a, b) { return b.avg_duration_s - a.avg_duration_s; })[0]; + window.mavis.sendPrompt( + 'Explica que nivel de esfuerzo de Gemini conviene usar segun la latencia y el coste medidos, y cual descartar.', + { + widgetTitle: 'Coste y latencia por nivel de esfuerzo en Gemini', + action: 'explain-latency', + selectedData: { totals: { calls: 24, total_tokens: 314880, avg_duration_s: 11.4 }, slowest: slowest }, + visibleFilters: { metric: metric }, + userIntent: 'recomendar un nivel de esfuerzo segun coste y latencia medidos' + } + ); + }); + + render(); + renderTable(); + })(); + + ### Coste y latencia por nivel de esfuerzo en Gemini + +24 consultas registradas, 314.880 tokens en total y 11,4 s de latencia media, repartidas en 4 combinaciones de modelo y esfuerzo. + +| Esfuerzo | Consultas | Latencia media | Tokens entrada | Tokens salida | Tokens total | +| --- | --- | --- | --- | --- | --- | +| high | 12 | 14,8 s | 12.340 | 640 | 160.680 | +| low | 8 | 7,2 s | 12.110 | 190 | 98.320 | +| medium | 3 | 10,1 s | 12.260 | 390 | 38.610 | +| xhigh | 1 | 26,4 s | 12.770 | 890 | 17.270 | + +El esfuerzo `high` concentra la mitad de las consultas y de los tokens; `xhigh` multiplica la latencia por casi cuatro con una sola consulta; `low` es el mas rapido con 7,2 s de media. + +Procedencia: registro de consultas al CLI de Gemini (usage.jsonl del plugin). +
diff --git a/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/genui-widget/SKILL.md b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/genui-widget/SKILL.md new file mode 100644 index 00000000..1d76ac26 --- /dev/null +++ b/plugins/jbolivar19/gemini-cli-bridge/skills/gemini-bridge-visualizer/references/genui-widget/SKILL.md @@ -0,0 +1,425 @@ +--- +name: genui-widget +description: + 'GenUI widget authoring infrastructure — provides the DSL protocol, security + constraints, --mw-* theme token system, Chart.js/CSS/SVG rendering patterns, and sendPrompt + interaction mechanism. Business skills (data-visualize, financial-analysis, etc.) compose on top + of this to output widgets. Not directly triggered — loaded by reference from business skills.' +--- + +# GenUI Widget + +## What this skill is + +This is a **tool skill**, not a business skill. It does not respond to user triggers directly. +Instead, business skills (e.g. `data-visualize`, `financial-analysis`) reference this skill for the +DSL protocol, security rules, theme tokens, rendering patterns, and interaction mechanisms needed to +output `` blocks. + +If the user explicitly invokes `/genui-widget`, treat it as a compact data-visualization request and +produce the widget yourself using this contract. Do not refuse or explain that this is only an +infrastructure skill. + +## Output routing contract + +Widgets are output **directly in `msg_content` text** — the host streaming parser picks up +`` blocks from the text channel and renders them inline as themed, sandboxed iframes. + +- Do NOT use the `write` tool to save widget DSL to a file — files on disk are invisible to the + rendering pipeline. This includes "drafting" the widget to a temp file first and then copying it + into `msg_content`; that workflow produces a duplicate file artifact the user never asked for. +- Do NOT create workspace directories or HTML files for the visualization. +- Even when the widget is large (200+ lines), output it directly inline in your response text. The + streaming parser handles arbitrarily long widgets. +- The host renders widgets as interactive iframes with Chart.js, theme sync, and clickable + drill-down — directly in the conversation. + +## Final answer contract + +The final assistant message must be concise and render-ready: + +- Output exactly one complete `...` block by default. Do not output + draft widgets, replacement widgets, or multiple alternative widgets unless the user explicitly + asks for multiple separate views. +- Use this response shape: optional one-sentence intro, then the widget, then optional one-sentence + conclusion. Total prose outside the widget should be no more than two short sentences. +- Never output ``, ``, hidden reasoning, planning notes, implementation walkthroughs, + tool transcripts, validation logs, or model self-talk in `msg_content`. +- Do not duplicate widget content outside the widget as Markdown tables, long bullet lists, or a + second written analysis. Put the analytical substance inside the widget and its fallback. +- If you realize the first widget design is wrong before sending, fix it in place and send only the + corrected final widget. + +## Theme safety gate + +This gate constrains theme values only. The model still generates the layout, visual hierarchy, +component composition, and interaction presentation that best fit the user's data and task. + +Use only these host-defined tokens in theme-sensitive CSS: + +`--mw-bg`, `--mw-surface`, `--mw-surface-muted`, `--mw-text`, `--mw-text-muted`, +`--mw-text-subtle`, `--mw-border`, `--mw-accent`, `--mw-success`, `--mw-danger`, `--mw-warning`, +`--mw-chart-1` through `--mw-chart-6`, `--mw-chart-grid`, `--mw-chart-axis`. + +Do not invent `--mw-*` aliases such as `--mw-fg`, `--mw-muted`, `--mw-bg-soft`, `--mw-card`, +`--mw-primary-bg`, or `--mw-warn-bg`. Do not add fallback values to `var(--mw-*)`; use +`var(--mw-text)`, never `var(--mw-text, #111)`. Do not use a fixed light or dark palette for +background, text, border, SVG, chart, hover, focus, selected, or disabled states. Hardcoded colors +are allowed only for rare data-specific semantic marks when no host token exists. + +Before emitting a Widget, scan every `--mw-*` reference and every theme-sensitive color declaration +against this gate. An opening tag with `theme="app"` does not make invalid CSS theme-safe. + +## Kind catalog + +| Kind | Purpose | +| ------------- | --------------------------------------------------------------------------------------------------- | +| `chart` | Single chart or chart pair for trend, comparison, distribution, or correlation (Chart.js available) | +| `dashboard` | KPI cards plus one or more charts plus optional table or inspector (Chart.js available) | +| `map` | Spatial data view with geographic or regional overlay and linked analytics | +| `diagram` | Concept flows, architecture graphs, SVG/HTML diagrams with light interactivity | +| `interactive` | Parameter controls that recompute a metric in real time (CSS/SVG/Canvas only, no Chart.js) | +| `form` | Structured input collection | +| `mockup` | UI mockup or wireframe preview | + +## DSL protocol + +Every visualization MUST be wrapped in the `` DSL envelope. Output the widget inline +in your Markdown response — the streaming parser picks it up from the `msg_content` text channel. +The complete Widget MUST be in the final assistant message, after all tool calls and validation have +finished. Do not call any tool after emitting the Widget. Intermediate assistant messages that also +request a tool are execution progress, not a durable user-visible visualization surface. + +``` + + {"summary":"...","dataSource":"...","chartType":"..."} + /* CSS — short block first for streaming */ + + [...] + /* deferred until widget close — reads window.__mavisData, binds interactions */ + Markdown summary when widget cannot render. + +``` + +### Required opening-tag fields + +| Field | Value | Notes | +| -------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------- | +| `version` | `mavis.widget.v1` | Always this value. | +| `kind` | `chart` / `dashboard` / `map` / `diagram` / `interactive` / `form` / `mockup` | Drives rendering strategy and default height. | +| `title` | Short descriptive text | Shown in loading shell, collapse header, accessibility label. | +| `streaming` | `html-first` | Default. Show structure while data loads. | +| `theme` | `app` | Follow host Argon/Mavis theme. | +| `token-set` | `mavis.semantic.v1` | Stable token contract version. | +| `capabilities` | `resize` or `resize,sendPrompt` | Dashboards and widgets with follow-up actions MUST use `resize,sendPrompt`. | + +### Dashboard contract + +For `kind="dashboard"`, the widget is an analytical surface, not a static image. It MUST include: + +1. `capabilities="resize,sendPrompt"` in the opening tag. +2. At least two visible clickable elements, such as KPI cards, anomaly rows, highlighted + chart-linked controls, or bottom action buttons. +3. Matching `window.mavis.sendPrompt(...)` handlers in ``. +4. `` `interactions` entries whose `"capability"` value is exactly `"sendPrompt"`. + +Do not use placeholder capabilities such as `"explain"`, `"drilldown"`, or `"open"`. If a dashboard +genuinely cannot support a meaningful follow-up, use `kind="chart"` instead. + +### Compact dashboard budget + +For normal analytical dashboards, prefer the compact pattern that fits in one conversation turn: + +- 3-4 KPI cards, up to 3 Chart.js charts, and at most one compact insight list/table. +- 2-4 high-value `sendPrompt` targets, not one target per data point. +- `height` around 720-860 for multi-chart dashboards, `min-height` around 520-640, and + `max-height` up to 1200 when the content genuinely needs it. +- The host may grow the iframe beyond the declared `max-height` to fit measured content, + up to a host safety cap. Still provide realistic height values; do not rely on host + auto-growth for layout. +- Avoid full written reports, repeated chart variants, and large raw-data tables inside the widget. + +### Recommended heights + +| kind | height | min-height | max-height | +| -------------- | ------ | ---------- | ---------- | +| chart (single) | 400 | 280 | 560 | +| chart (combo) | 480 | 320 | 640 | +| dashboard | 560 | 400 | 900 | +| map | 480 | 320 | 720 | +| interactive | 420 | 300 | 700 | +| diagram | 400 | 280 | 640 | +| form | 360 | 240 | 600 | +| mockup | 480 | 320 | 800 | + +Use the compact dashboard budget above for dense analytical dashboards with multiple charts. + +### Sub-block streaming order + +1. `` — short CSS first so structure is styled on arrival. +2. `` — visible structure arrives next; SVG containers, KPI cards, section headers. +3. `` — JSON dataset(s) injected into `window.__mavisData` by the host (NOT in the DOM). +4. `` — deferred until widget close; reads data from `window.__mavisData['name']`. +5. `` — Markdown summary capturing key insight and top data points. + +Avoid hidden tabs or `display: none` sections during streaming. Stack content vertically until +scripts run. + +### `` contract + +Always include: + +```json +{ + "summary": "One-sentence takeaway", + "dataSource": "user-provided or description of origin", + "chartType": "line|bar|pie|area|scatter|radar|heatmap|combo|table|kpi|dashboard" +} +``` + +Recommended additional fields: + +```json +{ + "datasetShape": { + "rows": 36, + "dimensions": ["month", "year"], + "measures": ["ridership"] + }, + "interactions": [ + { + "id": "drill-anomaly", + "label": "Explain anomaly", + "capability": "sendPrompt" + } + ] +} +``` + +`datasetShape` helps the host display dataset summary information and aids testing. `interactions` +declares clickable elements for auditability — it does not grant capabilities (that is still +controlled by the opening tag `capabilities` attribute). + +### `` contract + +Always provide: + +1. The key insight or conclusion +2. Top 3-5 data points as a simple list or Markdown table +3. Trend direction if applicable + +The `` block handles render failures (script error, CSP block). It is NOT an excuse +to write a full Markdown analysis outside the widget "just in case." + +- **`` inside the widget**: 2-4 sentence summary + top 3-5 data points. Shown when + the widget iframe fails. +- **Prose outside the widget**: 1-3 sentences of intro/conclusion. NOT a duplicate of the widget + content. +- **Do NOT output Markdown tables that repeat widget data.** The widget IS the visualization. If it + renders, external tables are redundant. If it fails, the fallback covers it. + +## Data handling rules + +1. Use deterministic local or user-provided data. No auth, no remote APIs, no hidden services. +2. Structure datasets as schema-first arrays of objects: + +```json +[ + { "month": "2025-01", "value": 906, "year": 2025, "yoy": -1.1 }, + { "month": "2025-02", "value": 820, "year": 2025, "yoy": -12.5 } +] +``` + +3. Round every displayed number. Use `Intl.NumberFormat` for locale-aware formatting or `.toFixed()` + for fixed decimals. +4. Never reconstruct data from DOM elements in scripts. Read from `window.__mavisData['name']` only. +5. Multiple datasets are allowed — use short, descriptive names: `main`, `events`, `benchmarks`. + Each `` block must have a unique `name` attribute. + +## Security constraints + +The following are hard prohibitions for all widget output: + +- No `