commit 85fbc8b05a1e5c91ca3b893a8a3113dcae492bf9 Author: root Date: Sun Aug 16 19:02:10 2026 +0000 Initial commit diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..6f3b76f --- /dev/null +++ b/.env.example @@ -0,0 +1,18 @@ +GEMINI_API_KEY= +MCP_SERVER_TOKEN=replace-with-a-long-random-secret +HOST=127.0.0.1 +PORT=8087 +PUBLIC_BASE_URL=https://mcp.zenvairo.es/zenvairogoogle +PUBLIC_MEDIA_SIGNING_SECRET=replace-with-at-least-32-random-characters +PUBLIC_MEDIA_URL_TTL_SECONDS=86400 +MEDIA_DIR=/opt/gemini-veo-mcp/media +MAX_INLINE_MEDIA_MB=25 +MAX_MEDIA_MB=300 +MAX_REFERENCE_INPUT_MB=25 +MAX_MCP_REQUEST_MB=40 +MEDIA_RETENTION_HOURS=168 +TOMBSTONE_RETENTION_DAYS=30 +PYTHON_BIN=python3 +FFMPEG_BIN=ffmpeg +FFPROBE_BIN=ffprobe +OVERLAY_CARD_SCRIPT=/opt/gemini-veo-mcp/scripts/make_overlay_card.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fa325e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +node_modules/ +dist/ +.env +deploy/.basic-password +deploy/.server-token +deploy/gemini-veo-mcp.env +deploy/zenvairogoogle.conf +deploy/zenvairogoogle.htpasswd +media/* +!media/.gitkeep +gemini-veo-mcp.env diff --git a/README.md b/README.md new file mode 100644 index 0000000..8b78a16 --- /dev/null +++ b/README.md @@ -0,0 +1,120 @@ +# Zenvairo Google Media MCP + +Servidor MCP remoto y *stateless* (Streamable HTTP) para generación de imágenes con Gemini y vídeo con Veo 3.1. Sigue el contrato `submit + poll`: `generate_image`/`generate_video` devuelven inmediatamente un UUID y `query_tasks` entrega el resultado final. + +## API y credenciales de Google + +A fecha de referencia **2026-08-14**, Veo 3.1 Standard, Fast y Lite están disponibles en la capa de pago de la **Gemini Developer API**. Por tanto, tanto imagen como vídeo usan únicamente `GEMINI_API_KEY`; no se requieren `GOOGLE_APPLICATION_CREDENTIALS`, `GCP_PROJECT_ID` ni `GCP_LOCATION` para los modelos expuestos aquí. + +Fuentes oficiales: + +- Imagen: https://ai.google.dev/gemini-api/docs/image-generation +- Veo: https://ai.google.dev/gemini-api/docs/veo +- Precios: https://ai.google.dev/gemini-api/docs/pricing + +La clave nunca forma parte de los schemas o respuestas MCP. El proceso arranca sin clave para permitir `who_am_i` y health checks, pero los jobs fallarán con `SERVER_NOT_CONFIGURED` hasta configurarla. + +## Tools + +- `who_am_i`: catálogo por tipo, alias, argumentos, restricciones y precios oficiales de referencia. +- `generate_image`: envío no bloqueante de una o varias imágenes. +- `generate_video`: envío no bloqueante de un vídeo Veo. +- `compose_video_overlay`: composición local no bloqueante de tarjetas Pillow sobre un vídeo retenido, con un nuevo `generationId`. +- `query_tasks`: polling compartido y entrega final. +- `get_usage`: estimaciones acumuladas desde el último arranque. Google no expone el saldo restante de facturación mediante esta API. + +`arguments` siempre es una lista `{ "name": ..., "value": ... }`, compatible con el patrón del conector Kling. Veo 3.1 siempre genera audio; `with_audio=false` se rechaza explícitamente. + +### Encadenar imágenes de referencia + +`generate_image` acepta `reference_images` con dos variantes mezclables. La recomendada referencia una generación terminada por UUID, de modo que los bytes viajan directamente del disco del servidor a Gemini y nunca pasan por el contexto del LLM: + +```json +{ + "model": "gemini-3.1-flash-image", + "arguments": [ + { "name": "prompt", "value": "Crea la slide 2 manteniendo exactamente el estilo visual de la referencia" }, + { + "name": "reference_images", + "value": [ + { "generation_id": "", "index": 0 } + ] + }, + { "name": "aspect_ratio", "value": "4:5" }, + { "name": "resolution", "value": "1K" } + ] +} +``` + +La variante inline anterior sigue siendo compatible: `{ "base64": "...", "mime_type": "image/png" }`. Un mismo array puede mezclar referencias por ID e inline. Se admiten PNG, JPEG y WebP, hasta 20 MiB por referencia inline y 25 MiB agregados por request. Los límites de cantidad son 3 referencias para Gemini 2.5 Flash Image y 14 para los modelos Gemini 3 expuestos. Las referencias nunca se escriben en logs. + +Las referencias por ID producen códigos claros: `REFERENCE_GENERATION_NOT_FOUND`, `REFERENCE_GENERATION_NOT_COMPLETED`, `REFERENCE_INDEX_OUT_OF_RANGE`, `REFERENCE_GENERATION_EXPIRED` y `REFERENCE_IS_VIDEO`. + +### Componer tarjetas sobre un vídeo + +`compose_video_overlay` recibe el `generationId` de un vídeo vertical 9:16 ya `COMPLETED` y entre 1 y 10 tarjetas temporizadas. Devuelve inmediatamente un `generationId` nuevo; el trabajo se realiza localmente con Pillow, Poppins Bold y ffmpeg, conserva el audio original y se consulta con el mismo `query_tasks`: + +```json +{ + "base_generation_id": "", + "overlays": [ + { "kicker": "GANCHO", "text": "Tu equipo no necesita más herramientas", "style": "normal", "start_time": 0.6, "duration": 2.5 }, + { "kicker": "SIGUIENTE PASO", "text": "Automatiza lo repetitivo", "style": "cta", "start_time": 4.8, "duration": 2.5 } + ] +} +``` + +El vídeo base no se descarga ni regenera: sus bytes pasan del almacén retenido al proceso ffmpeg. El resultado se persiste como otra generación `video/mp4`, con tamaño y SHA-256 reales, retención normal y las mismas `downloadUrl`/`publicUrl`. Los timings deben quedar dentro de la duración real del vídeo; los errores usan códigos `COMPOSE_*` explícitos. Los textos de las tarjetas no se registran en logs. + +## Entrega de medios y límites + +`query_tasks` usa `include_base64=false` por defecto para que los binarios no entren accidentalmente en el contexto del LLM. Cada output devuelve `index`, `mimeType`, `sizeBytes`, `sha256`, el `downloadUrl` protegido anterior y una `publicUrl` firmada que Meta puede descargar sin credenciales. El base64 continúa disponible de forma explícita con `include_base64=true` cuando el tamaño binario agregado del job es como máximo **25 MiB exactos (26.214.400 bytes)**. + +`publicUrl` usa el mismo dominio bajo `/zenvairogoogle/public-media/...`, lleva una firma HMAC ligada al nombre y caducidad, y dura 24 horas por defecto (`PUBLIC_MEDIA_URL_TTL_SECONDS=86400`). La ruta no acepta Basic ni Bearer porque Meta debe leerla directamente; sin firma válida responde 403 y una firma caducada responde 410. Cada llamada posterior a `query_tasks` emite una URL nueva mientras el resultado siga retenido. + +El `downloadUrl` anterior bajo `/zenvairogoogle/media/...` continúa protegido por las credenciales HTTP Basic del conector. Nunca se devuelve una URL de Google, GCS o un CDN tercero. La clave HMAC (`PUBLIC_MEDIA_SIGNING_SECRET`, mínimo 32 caracteres) solo existe en el servidor y no aparece en schemas, logs o respuestas. + +Para publicar sin copiar ni mover base64, pasa `outputs[].publicUrl` directamente a `publish_post` de SocialMCP como `imageUrl`, `videoUrl` o `media[].url`. No llames antes a `upload_media`. + +Los resultados completados se guardan en disco, indexados por `generationId`, con bytes, MIME, SHA-256 e índice en un manifiesto atómico. Se restauran después de reiniciar el servicio y se conservan **7 días (168 horas)** por defecto mediante `MEDIA_RETENTION_HOURS`. Una tarea limpia archivos y manifiestos cada 15 minutos; conserva tombstones pequeños durante 30 días para distinguir IDs purgados de IDs inexistentes. Los jobs todavía pendientes siguen siendo memoria volátil. + +Un artefacto individual mayor de 300 MiB se rechaza para proteger el disco del LXC. No hay reintentos silenciosos de moderación o validación; solo hasta 2 reintentos (3 intentos totales), registrados en log, para 429, 5xx y fallos transitorios de red. + +## Despliegue LXC 210 (Alpine/OpenRC) + +La instalación operativa está en `/opt/gemini-veo-mcp`, ejecutada como `mcp:mcp`, ligada a `127.0.0.1:8087` y supervisada por OpenRC (`gemini-veo-mcp`). nginx protege `/zenvairogoogle/` con Basic y deja pública únicamente `/zenvairogoogle/public-media/`; la aplicación exige en esa ruta una firma HMAC válida y caducable. + +Para añadir la API key: + +```sh +pct exec 210 -- vi /opt/gemini-veo-mcp/gemini-veo-mcp.env +pct exec 210 -- rc-service gemini-veo-mcp restart +``` + +Comprobaciones: + +```sh +pct exec 210 -- rc-service gemini-veo-mcp status +pct exec 210 -- tail -f /var/log/gemini-veo-mcp.log +``` + +Los logs son JSON Lines e incluyen modelo, UUID, duración, bytes de salida, coste estimado y reintentos; no incluyen prompts ni credenciales. + +## Test real pagado + +El test usa el MCP completo: `generate_image` → `query_tasks` hasta `COMPLETED`, decodifica base64 y valida la firma PNG/JPEG. Tras configurar la key y reiniciar: + +```sh +pct exec 210 -- /bin/sh -lc 'cd /opt/gemini-veo-mcp && set -a && . ./gemini-veo-mcp.env && set +a && npm run test:integration' +``` + +Sin credenciales el test se marca como `SKIP` y no incurre en coste. + +## Claude.ai / Cowork + +1. En Claude.ai, abre **Settings → Connectors → Add custom connector**. +2. Usa la URL HTTPS proporcionada al finalizar el despliegue, que ya incorpora el usuario y contraseña HTTP Basic. +3. Activa las tools del conector en Cowork. +4. Llama primero a `who_am_i`; después envía con `generate_*` y consulta el UUID con `query_tasks` hasta estado terminal. + +Para vídeo, espera entre 11 segundos y 6 minutos según la documentación oficial. Evita polling agresivo; 10–15 segundos es razonable. diff --git a/deploy/default.conf.lxc210 b/deploy/default.conf.lxc210 new file mode 100644 index 0000000..6f9b876 --- /dev/null +++ b/deploy/default.conf.lxc210 @@ -0,0 +1,148 @@ +server { + listen 80 default_server; + server_name _; + + location /zenvairogit/ { + auth_basic "ZenvairoGit MCP"; + auth_basic_user_file /etc/nginx/htpasswd/zenvairogit; + + proxy_pass http://127.0.0.1:8081/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Origin ""; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + proxy_send_timeout 300s; + + proxy_set_header Mcp-Protocol-Version $http_mcp_protocol_version; + proxy_set_header Mcp-Session-Id $http_mcp_session_id; + } + + location /zenvairocloud/ { + auth_basic "ZenvairoCloud MCP"; + auth_basic_user_file /etc/nginx/htpasswd/zenvairocloud; + + proxy_pass http://127.0.0.1:8082/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1:8082; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Origin ""; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + proxy_send_timeout 300s; + + proxy_set_header Mcp-Session-Id $http_mcp_session_id; + } + + location /zenvairoanalytics/ { + auth_basic "ZenvairoAnalytics MCP"; + auth_basic_user_file /etc/nginx/htpasswd/zenvairoanalytics; + + proxy_pass http://127.0.0.1:8083/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1:8083; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Origin ""; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + proxy_send_timeout 300s; + + proxy_set_header Mcp-Session-Id $http_mcp_session_id; + } + + location /zenvairomail/ { + auth_basic "ZenvairoMail MCP"; + auth_basic_user_file /etc/nginx/htpasswd/zenvairomail; + + proxy_pass http://127.0.0.1:8084/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1:8084; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Origin ""; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + proxy_send_timeout 300s; + + proxy_set_header Mcp-Session-Id $http_mcp_session_id; + } + + location /zenvairocrm/ { + auth_basic "ZenvairoCRM MCP"; + auth_basic_user_file /etc/nginx/htpasswd/zenvairocrm; + + proxy_pass http://127.0.0.1:8085/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1:8085; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Origin ""; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + proxy_send_timeout 300s; + + proxy_set_header Mcp-Session-Id $http_mcp_session_id; + } + + # Archivos subidos con upload_media: SIN Basic Auth, para que Meta pueda + # descargarlos al publicar (nombre de archivo aleatorio tipo UUID). + location /zenvairosocial/media/ { + proxy_pass http://127.0.0.1:8086/media/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1:8086; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + proxy_send_timeout 300s; + } + + location /zenvairosocial/ { + auth_basic "ZenvairoSocial MCP"; + auth_basic_user_file /etc/nginx/htpasswd/zenvairosocial; + + proxy_pass http://127.0.0.1:8086/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1:8086; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Origin ""; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + proxy_send_timeout 300s; + + proxy_set_header Mcp-Protocol-Version $http_mcp_protocol_version; + proxy_set_header Mcp-Session-Id $http_mcp_session_id; + } + + include /etc/nginx/http.d/zenvairogoogle.inc; + + location = / { + return 404; + } +} diff --git a/deploy/gemini-veo-mcp.env.template b/deploy/gemini-veo-mcp.env.template new file mode 100644 index 0000000..098ae4e --- /dev/null +++ b/deploy/gemini-veo-mcp.env.template @@ -0,0 +1,18 @@ +GEMINI_API_KEY= +MCP_SERVER_TOKEN=__MCP_SERVER_TOKEN__ +HOST=127.0.0.1 +PORT=8087 +PUBLIC_BASE_URL=https://mcp.zenvairo.es/zenvairogoogle +PUBLIC_MEDIA_SIGNING_SECRET=replace-with-at-least-32-random-characters +PUBLIC_MEDIA_URL_TTL_SECONDS=86400 +MEDIA_DIR=/opt/gemini-veo-mcp/media +MAX_INLINE_MEDIA_MB=25 +MAX_MEDIA_MB=300 +MAX_REFERENCE_INPUT_MB=25 +MAX_MCP_REQUEST_MB=40 +MEDIA_RETENTION_HOURS=168 +TOMBSTONE_RETENTION_DAYS=30 +PYTHON_BIN=python3 +FFMPEG_BIN=ffmpeg +FFPROBE_BIN=ffprobe +OVERLAY_CARD_SCRIPT=/opt/gemini-veo-mcp/scripts/make_overlay_card.py diff --git a/deploy/gemini-veo-mcp.openrc b/deploy/gemini-veo-mcp.openrc new file mode 100644 index 0000000..3c07a36 --- /dev/null +++ b/deploy/gemini-veo-mcp.openrc @@ -0,0 +1,26 @@ +#!/sbin/openrc-run + +name="gemini-veo-mcp" +description="Gemini and Veo MCP server (Streamable HTTP, 127.0.0.1:8087)" +command="/usr/bin/node" +command_args="/opt/gemini-veo-mcp/dist/index.js" +directory="/opt/gemini-veo-mcp" +command_user="mcp:mcp" +command_background="yes" +pidfile="/run/${RC_SVCNAME}.pid" +output_log="/var/log/${RC_SVCNAME}.log" +error_log="/var/log/${RC_SVCNAME}.log" +env_file="/opt/gemini-veo-mcp/gemini-veo-mcp.env" + +start_pre() { + checkpath -d -m 0750 -o mcp:mcp /opt/gemini-veo-mcp/media + checkpath -f -m 0640 -o mcp:mcp "${output_log}" + set -a + [ -f "${env_file}" ] && . "${env_file}" + set +a +} + +depend() { + need net + after nginx +} diff --git a/deploy/nginx-location.conf b/deploy/nginx-location.conf new file mode 100644 index 0000000..139ad4c --- /dev/null +++ b/deploy/nginx-location.conf @@ -0,0 +1,57 @@ + # Public only when the application validates the expiring HMAC signature. + location /zenvairogoogle/public-media/ { + auth_basic off; + + proxy_pass http://127.0.0.1:8087/public-media/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1:8087; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 600s; + } + + location /zenvairogoogle/media/ { + auth_basic "Zenvairo Google Media MCP"; + auth_basic_user_file /etc/nginx/htpasswd/zenvairogoogle; + + proxy_pass http://127.0.0.1:8087/media/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1:8087; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-MCP-Server-Token "__MCP_SERVER_TOKEN__"; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 600s; + proxy_send_timeout 600s; + } + + location /zenvairogoogle/ { + auth_basic "Zenvairo Google Media MCP"; + auth_basic_user_file /etc/nginx/htpasswd/zenvairogoogle; + client_max_body_size 40m; + + proxy_pass http://127.0.0.1:8087/; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1:8087; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Origin ""; + proxy_set_header X-MCP-Server-Token "__MCP_SERVER_TOKEN__"; + + proxy_buffering off; + proxy_request_buffering off; + proxy_cache off; + proxy_read_timeout 600s; + proxy_send_timeout 600s; + + proxy_set_header Mcp-Protocol-Version $http_mcp_protocol_version; + proxy_set_header Mcp-Session-Id $http_mcp_session_id; + } diff --git a/media/.gitkeep b/media/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/media/.gitkeep @@ -0,0 +1 @@ + diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..02ea281 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2110 @@ +{ + "name": "@zenvairo/gemini-veo-mcp", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@zenvairo/gemini-veo-mcp", + "version": "1.0.0", + "dependencies": { + "@google/genai": "2.17.1", + "@modelcontextprotocol/sdk": "1.30.0", + "dotenv": "16.6.1", + "express": "5.2.1", + "zod": "3.25.76" + }, + "devDependencies": { + "@types/express": "5.0.3", + "@types/node": "24.3.0", + "tsx": "4.20.5", + "typescript": "5.9.2" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@google/genai": { + "version": "2.17.1", + "resolved": "https://registry.npmjs.org/@google/genai/-/genai-2.17.1.tgz", + "integrity": "sha512-CdZ3M/titoH81hXXkvOikrOW26bC9IXh9iYT7u+r+5p7wi1LnMEnB0AbJfDeWAkjuneP4oJ299BtCt6twmORWg==", + "hasInstallScript": true, + "dependencies": { + "google-auth-library": "^10.3.0", + "p-retry": "^4.6.2", + "protobufjs": "^7.5.4", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.25.2" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/sdk": { + "optional": true + } + } + }, + "node_modules/@hono/node-server": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.1.tgz", + "integrity": "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg==", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz", + "integrity": "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==", + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.0.5", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==" + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "dev": true, + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.3.tgz", + "integrity": "sha512-wGA0NX93b19/dZC1J18tKWVIYWyyF2ZjT9vin/NRu0qzzvfVzWjs04iq2rQ3H65vCTQYlRqs3YHfY7zjdV+9Kw==", + "dev": true, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^5.0.0", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.3.tgz", + "integrity": "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "dev": true + }, + "node_modules/@types/node": { + "version": "24.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.3.0.tgz", + "integrity": "sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow==", + "dependencies": { + "undici-types": "~7.10.0" + } + }, + "node_modules/@types/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==", + "dev": true + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true + }, + "node_modules/@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==", + "dev": true, + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bignumber.js": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz", + "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", + "engines": { + "node": "*" + } + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.6.2", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.2.tgz", + "integrity": "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A==", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/fast-uri": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", + "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ] + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gaxios": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz", + "integrity": "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "node-fetch": "^3.3.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/gcp-metadata": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz", + "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==", + "dependencies": { + "gaxios": "^7.0.0", + "google-logging-utils": "^1.0.0", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-tsconfig": { + "version": "4.14.2", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.2.tgz", + "integrity": "sha512-XpwZALwwl/BaKTAyC6+c5T8y6kCg2jk+XGqOVrKIQmW49pNypYLMRjCUXqa28tQgJlhS2RlzP7sc+Rx7W6qsfw==", + "dev": true, + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/google-auth-library": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz", + "integrity": "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^7.1.4", + "gcp-metadata": "8.1.2", + "google-logging-utils": "1.1.3", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/google-logging-utils": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz", + "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==", + "engines": { + "node": ">=14" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.13.2", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.2.tgz", + "integrity": "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA==", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ip-address": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz", + "integrity": "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + }, + "node_modules/jose": { + "version": "6.2.8", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.8.tgz", + "integrity": "sha512-Bsdjwm3Qsd/P0jR+BHDe3LytDfY7WBq2HmCCLIwuVRHMuEC9ae7/R474GIUdF1NgCyZjzVo/A9DOiOBtXq8ZoQ==", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==" + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-retry": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", + "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "engines": { + "node": ">=8" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/protobufjs": { + "version": "7.6.5", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.5.tgz", + "integrity": "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==", + "hasInstallScript": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "engines": { + "node": ">= 4" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/router/node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tsx": { + "version": "4.20.5", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.20.5.tgz", + "integrity": "sha512-+wKjMNU9w/EaQayHXb7WA7ZaHY6hN8WgfvHNQ3t1PnU91/7O8TcTnIhCDYTZwnt8JsO9IBqZ30Ln1r7pPF52Aw==", + "dev": true, + "dependencies": { + "esbuild": "~0.25.0", + "get-tsconfig": "^4.7.5" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typescript": { + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz", + "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz", + "integrity": "sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..3ffa3d7 --- /dev/null +++ b/package.json @@ -0,0 +1,32 @@ +{ + "name": "@zenvairo/gemini-veo-mcp", + "version": "1.0.0", + "private": true, + "description": "Remote Streamable HTTP MCP server for Google Gemini image and Veo video generation", + "type": "module", + "main": "dist/index.js", + "scripts": { + "build": "tsc -p tsconfig.json", + "start": "node dist/index.js", + "dev": "tsx src/index.ts", + "test": "MEDIA_DIR=/tmp/gemini-veo-mcp-tests-$$ node --import tsx --test test/unit.test.ts", + "test:integration": "node --import tsx --test test/integration-real.test.ts", + "test:integration:compose": "node --import tsx --test test/integration-compose-real.test.ts" + }, + "engines": { + "node": ">=20" + }, + "dependencies": { + "@google/genai": "2.17.1", + "@modelcontextprotocol/sdk": "1.30.0", + "dotenv": "16.6.1", + "express": "5.2.1", + "zod": "3.25.76" + }, + "devDependencies": { + "@types/express": "5.0.3", + "@types/node": "24.3.0", + "tsx": "4.20.5", + "typescript": "5.9.2" + } +} diff --git a/scripts/make_overlay_card.py b/scripts/make_overlay_card.py new file mode 100755 index 0000000..954268a --- /dev/null +++ b/scripts/make_overlay_card.py @@ -0,0 +1,81 @@ +import sys, json +from PIL import Image, ImageDraw, ImageFont, ImageFilter + +W, H = 720, 1280 +POPPINS_BOLD = "/usr/share/fonts/zenvairo/Poppins-Bold.ttf" +NAVY = (10, 22, 48) +CYAN = (45, 224, 234) +WHITE = (255, 255, 255) + +def wrap_text(draw, text, font, max_width): + words = text.split() + lines, cur = [], "" + for w in words: + trial = (cur + " " + w).strip() + bbox = draw.textbbox((0,0), trial, font=font) + if bbox[2] - bbox[0] <= max_width or not cur: + cur = trial + else: + lines.append(cur) + cur = w + if cur: + lines.append(cur) + return lines + +def rounded_rect_with_shadow(size, radius, fill, shadow_blur=18, shadow_offset=(0,10), shadow_opacity=110): + w, h = size + pad = shadow_blur * 3 + canvas = Image.new("RGBA", (w + pad*2, h + pad*2), (0,0,0,0)) + shadow = Image.new("RGBA", canvas.size, (0,0,0,0)) + sd = ImageDraw.Draw(shadow) + sx, sy = pad + shadow_offset[0], pad + shadow_offset[1] + sd.rounded_rectangle([sx, sy, sx+w, sy+h], radius=radius, fill=(0,0,0,shadow_opacity)) + shadow = shadow.filter(ImageFilter.GaussianBlur(shadow_blur)) + canvas = Image.alpha_composite(canvas, shadow) + box = Image.new("RGBA", canvas.size, (0,0,0,0)) + bd = ImageDraw.Draw(box) + bd.rounded_rectangle([pad, pad, pad+w, pad+h], radius=radius, fill=fill) + canvas = Image.alpha_composite(canvas, box) + return canvas, pad + +def make_card(text, out_path, kicker=None, style="normal", max_text_width=560): + img = Image.new("RGBA", (W, H), (0,0,0,0)) + font_size = 50 if len(text) < 40 else (44 if len(text) < 70 else 38) + font = ImageFont.truetype(POPPINS_BOLD, font_size) + tmp_draw = ImageDraw.Draw(img) + lines = wrap_text(tmp_draw, text, font, max_text_width - 80) + line_h = font.getbbox("Ay")[3] - font.getbbox("Ay")[1] + line_spacing = int(line_h * 1.35) + kicker_h = 0 + kfont = None + if kicker: + kfont = ImageFont.truetype(POPPINS_BOLD, 26) + kicker_h = 50 + text_block_h = len(lines) * line_spacing + kicker_h + pill_h = text_block_h + 70 + pill_w = max_text_width + if style == "cta": + fill = (*CYAN, 255); text_color = NAVY; kicker_color = NAVY; accent = None + else: + fill = (*NAVY, 235); text_color = WHITE; kicker_color = CYAN; accent = CYAN + pill, pad = rounded_rect_with_shadow((pill_w, pill_h), radius=34, fill=fill) + if accent: + ad = ImageDraw.Draw(pill) + ad.rounded_rectangle([pad, pad, pad+10, pad+pill_h], radius=5, fill=(*accent,255)) + py = pad + 35 + if kicker: + kd = ImageDraw.Draw(pill) + kd.text((pad + pill_w/2, py), kicker, font=kfont, fill=(*kicker_color,255), anchor="ma") + py += kicker_h + dd = ImageDraw.Draw(pill) + for line in lines: + dd.text((pad + pill_w/2, py), line, font=font, fill=(*text_color,255), anchor="ma") + py += line_spacing + px = (W - pill.width) // 2 + py_pos = int(H * 0.62) - pill.height // 2 + img.alpha_composite(pill, (px, py_pos)) + img.save(out_path) + +if __name__ == "__main__": + cfg = json.loads(sys.argv[1]) + make_card(cfg["text"], cfg["out"], kicker=cfg.get("kicker"), style=cfg.get("style","normal")) diff --git a/src/arguments.ts b/src/arguments.ts new file mode 100644 index 0000000..6d3b65c --- /dev/null +++ b/src/arguments.ts @@ -0,0 +1,118 @@ +import type { GenerationReferenceImage, InlineReferenceImage, ModelSpec, ReferenceImage, ToolArgument } from "./types.js"; + +export function normalizeArguments(model: ModelSpec, input: ToolArgument[]): Record { + const result: Record = {}; + const specs = new Map(model.arguments.map((argument) => [argument.name, argument])); + + for (const argument of input) { + if (!specs.has(argument.name)) throw new Error(`Unknown argument '${argument.name}' for model ${model.name}`); + if (Object.hasOwn(result, argument.name)) throw new Error(`Duplicate argument '${argument.name}'`); + result[argument.name] = argument.value; + } + + for (const spec of model.arguments) { + if (!Object.hasOwn(result, spec.name) && spec.default !== undefined) result[spec.name] = spec.default; + if (spec.required && !Object.hasOwn(result, spec.name)) throw new Error(`Missing required argument '${spec.name}'`); + + const value = result[spec.name]; + if (value === undefined) continue; + if (spec.allowedValues && !spec.allowedValues.some((allowed) => allowed === value)) { + throw new Error(`Invalid '${spec.name}': ${JSON.stringify(value)}. Allowed: ${spec.allowedValues.map(String).join(", ")}`); + } + if (typeof value === "number") { + if (spec.minimum !== undefined && value < spec.minimum) throw new Error(`'${spec.name}' must be >= ${spec.minimum}`); + if (spec.maximum !== undefined && value > spec.maximum) throw new Error(`'${spec.name}' must be <= ${spec.maximum}`); + } + } + + if (typeof result.prompt !== "string" || result.prompt.trim().length === 0) throw new Error("'prompt' must be a non-empty string"); + if (String(result.prompt).length > 8000) throw new Error("'prompt' must be at most 8000 characters"); + + if (model.type === "image" && result.reference_images !== undefined) { + result.reference_images = normalizeReferenceImages(model, result.reference_images); + } + + if (model.type === "video") { + const resolution = String(result.resolution); + const duration = Number(result.duration_seconds); + if ((resolution === "1080p" || resolution === "4k") && duration !== 8) { + throw new Error(`${resolution} video generation requires duration_seconds=8`); + } + if (result.with_audio !== true) throw new Error("Veo 3.1 always generates native audio; with_audio=false is not supported"); + } + + return result; +} + +function normalizeReferenceImages(model: ModelSpec, input: unknown): ReferenceImage[] { + if (!Array.isArray(input)) throw new Error("'reference_images' must be an array of {base64, mime_type} or {generation_id, index?} objects"); + const spec = model.arguments.find((argument) => argument.name === "reference_images"); + const maximumItems = spec?.maximumItems ?? 1; + if (input.length < 1 || input.length > maximumItems) { + throw new Error(`'reference_images' must contain between 1 and ${maximumItems} images for ${model.name}`); + } + + const maxPerImageBytes = 20 * 1024 * 1024; + const maxAggregateBytes = Math.floor((Number(process.env.MAX_REFERENCE_INPUT_MB) || 25) * 1024 * 1024); + let aggregateBytes = 0; + const normalized: ReferenceImage[] = []; + + for (const [index, value] of input.entries()) { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`reference_images[${index}] must be an object`); + const record = value as Record; + const hasInline = Object.hasOwn(record, "base64") || Object.hasOwn(record, "mime_type"); + const hasGeneration = Object.hasOwn(record, "generation_id") || Object.hasOwn(record, "index"); + if (hasInline && hasGeneration) throw new Error(`reference_images[${index}] must use either {base64, mime_type} or {generation_id, index?}, not both`); + + if (hasGeneration) { + if (typeof record.generation_id !== "string" || !isUuid(record.generation_id)) { + throw new Error(`reference_images[${index}].generation_id must be a valid UUID`); + } + const outputIndex = record.index ?? 0; + if (!Number.isInteger(outputIndex) || Number(outputIndex) < 0) { + throw new Error(`reference_images[${index}].index must be a non-negative integer`); + } + normalized.push({ generation_id: record.generation_id, index: Number(outputIndex) } satisfies GenerationReferenceImage); + continue; + } + + const rawBase64 = record.base64; + let mimeType = record.mime_type; + if (typeof rawBase64 !== "string" || rawBase64.length === 0) throw new Error(`reference_images[${index}].base64 must be a non-empty string`); + let base64: string = rawBase64; + + const dataUri = base64.match(/^data:(image\/(?:png|jpeg|webp));base64,(.+)$/s); + if (dataUri) { + mimeType ??= dataUri[1]; + base64 = dataUri[2]; + } + base64 = base64.replace(/\s/g, ""); + if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64) || base64.length % 4 !== 0) { + throw new Error(`reference_images[${index}].base64 is not valid standard base64`); + } + if (mimeType !== "image/png" && mimeType !== "image/jpeg" && mimeType !== "image/webp") { + throw new Error(`reference_images[${index}].mime_type must be image/png, image/jpeg, or image/webp`); + } + + const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0; + const decodedBytes = Math.floor(base64.length * 3 / 4) - padding; + if (decodedBytes <= 0 || decodedBytes > maxPerImageBytes) throw new Error(`reference_images[${index}] exceeds the 20 MiB per-image limit`); + aggregateBytes += decodedBytes; + if (aggregateBytes > maxAggregateBytes) throw new Error(`reference_images exceed the aggregate MAX_REFERENCE_INPUT_MB limit (${maxAggregateBytes} bytes)`); + + const header = Buffer.from(base64.slice(0, 24), "base64"); + if (!mimeMatchesHeader(mimeType, header)) throw new Error(`reference_images[${index}] content does not match ${mimeType}`); + normalized.push({ base64, mime_type: mimeType } satisfies InlineReferenceImage); + } + return normalized; +} + +function mimeMatchesHeader(mimeType: InlineReferenceImage["mime_type"], header: Buffer): boolean { + if (mimeType === "image/png") return header.length >= 8 && header.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])); + if (mimeType === "image/jpeg") return header.length >= 3 && header[0] === 0xff && header[1] === 0xd8 && header[2] === 0xff; + return header.length >= 12 && header.subarray(0, 4).toString("ascii") === "RIFF" && header.subarray(8, 12).toString("ascii") === "WEBP"; +} + +function isUuid(value: string): boolean { + return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value); +} diff --git a/src/catalog.ts b/src/catalog.ts new file mode 100644 index 0000000..c91e363 --- /dev/null +++ b/src/catalog.ts @@ -0,0 +1,125 @@ +import type { ModelSpec } from "./types.js"; + +export const PRICING_REFERENCE_DATE = "2026-08-14"; +export const PRICING_SOURCE = "https://ai.google.dev/gemini-api/docs/pricing"; + +const commonImageRatios = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"]; +const extendedFlashRatios = ["1:1", "1:4", "1:8", "2:3", "3:2", "3:4", "4:1", "4:3", "4:5", "5:4", "8:1", "9:16", "16:9", "21:9"]; + +function imageArguments(resolutions: string[], ratios = commonImageRatios, maximumReferenceImages = 14): ModelSpec["arguments"] { + return [ + { name: "prompt", required: true, description: "Detailed text prompt for the image." }, + { + name: "reference_images", + required: false, + description: "Reference images. Prefer {generation_id,index?} to reuse a completed server-side image without moving base64 through the client; inline {base64,mime_type} remains supported.", + format: 'array<({generation_id:uuid,index?:integer=0}|{base64:string,mime_type:"image/png"|"image/jpeg"|"image/webp"})>', + maximumItems: maximumReferenceImages, + }, + { name: "resolution", required: false, description: "Requested output image size.", allowedValues: resolutions, default: resolutions.includes("1K") ? "1K" : resolutions[0] }, + { name: "aspect_ratio", required: false, description: "Output image aspect ratio.", allowedValues: ratios, default: "1:1" }, + { name: "image_count", required: false, description: "Number of independent images. The server makes one provider request per image.", allowedValues: [1, 2, 3, 4], default: 1 }, + ]; +} + +function videoArguments(resolutions: string[]): ModelSpec["arguments"] { + return [ + { name: "prompt", required: true, description: "Video prompt; may include dialogue, sound and ambience cues." }, + { name: "resolution", required: false, description: "Output resolution. 1080p and 4k require an 8 second duration.", allowedValues: resolutions, default: "720p" }, + { name: "aspect_ratio", required: false, description: "Output orientation.", allowedValues: ["16:9", "9:16"], default: "16:9" }, + { name: "duration_seconds", required: false, description: "Generated clip duration.", allowedValues: [4, 6, 8], default: 8 }, + { name: "with_audio", required: false, description: "Veo 3.1 native audio is always enabled; false is unsupported.", allowedValues: [true], default: true }, + { name: "seed", required: false, description: "Optional seed (improves repeatability but does not guarantee determinism).", minimum: 0, maximum: 2147483647 }, + ]; +} + +export const MODEL_CATALOG: ModelSpec[] = [ + { + name: "gemini-3-pro-image", + aliases: ["nano-banana-pro"], + description: "Nano Banana Pro; professional assets, complex instructions and high-quality text rendering up to 4K.", + type: "image", + canonicalApiModel: "gemini-3-pro-image", + arguments: imageArguments(["1K", "2K", "4K"], commonImageRatios, 14), + pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per output image (text input/tokens excluded)", rates: { "1K": 0.134, "2K": 0.134, "4K": 0.24 }, source: PRICING_SOURCE }, + }, + { + name: "gemini-3.1-flash-image", + aliases: ["nano-banana-2"], + description: "Nano Banana 2; recommended balance of quality, latency and cost, with 0.5K through 4K output.", + type: "image", + canonicalApiModel: "gemini-3.1-flash-image", + arguments: imageArguments(["0.5K", "1K", "2K", "4K"], extendedFlashRatios, 14), + pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per output image (text input/tokens excluded)", rates: { "0.5K": 0.045, "1K": 0.067, "2K": 0.101, "4K": 0.151 }, source: PRICING_SOURCE }, + }, + { + name: "gemini-3.1-flash-lite-image", + aliases: ["nano-banana-2-lite"], + description: "Nano Banana 2 Lite; lowest-latency and lowest-cost 1K image generation.", + type: "image", + canonicalApiModel: "gemini-3.1-flash-lite-image", + arguments: imageArguments(["1K"], commonImageRatios, 14), + pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per output image (text input/tokens excluded)", rates: { "1K": 0.0336 }, source: PRICING_SOURCE }, + }, + { + name: "gemini-2.5-flash-image", + aliases: ["nano-banana"], + description: "Original Nano Banana; efficient fixed-resolution 1K image generation.", + type: "image", + canonicalApiModel: "gemini-2.5-flash-image", + arguments: imageArguments(["1K"], commonImageRatios, 3), + pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per output image (text input/tokens excluded)", rates: { "1K": 0.039 }, source: PRICING_SOURCE }, + }, + { + name: "veo-3.1", + aliases: ["veo-3.1-standard"], + description: "Veo 3.1 Preview standard; highest-quality video with native audio, up to 4K.", + type: "video", + canonicalApiModel: "veo-3.1-generate-preview", + arguments: videoArguments(["720p", "1080p", "4k"]), + pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per generated second, with audio", rates: { "720p": 0.4, "1080p": 0.4, "4k": 0.6 }, source: PRICING_SOURCE }, + }, + { + name: "veo-3.1-fast", + aliases: [], + description: "Veo 3.1 Fast Preview; optimized for fast, high-throughput social and advertising workflows.", + type: "video", + canonicalApiModel: "veo-3.1-fast-generate-preview", + arguments: videoArguments(["720p", "1080p", "4k"]), + pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per generated second, with audio", rates: { "720p": 0.1, "1080p": 0.12, "4k": 0.3 }, source: PRICING_SOURCE }, + }, + { + name: "veo-3.1-lite", + aliases: [], + description: "Veo 3.1 Lite Preview; lowest-cost native-audio video generation at 720p or 1080p.", + type: "video", + canonicalApiModel: "veo-3.1-lite-generate-preview", + arguments: videoArguments(["720p", "1080p"]), + pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per generated second, with audio", rates: { "720p": 0.05, "1080p": 0.08 }, source: PRICING_SOURCE }, + }, +]; + +export function resolveModel(requested: string, type?: "image" | "video"): ModelSpec { + const normalized = requested.trim().toLowerCase(); + const model = MODEL_CATALOG.find((item) => + (item.name.toLowerCase() === normalized || item.aliases.some((alias) => alias.toLowerCase() === normalized)) && + (!type || item.type === type), + ); + if (!model) throw new Error(`Unsupported ${type ?? "generation"} model: ${requested}`); + return model; +} + +export function estimateCost(model: ModelSpec, args: Record): number { + if (model.type === "image") { + const resolution = String(args.resolution ?? "1K"); + const count = Number(args.image_count ?? 1); + return roundUsd((model.pricing.rates[resolution] ?? 0) * count); + } + const resolution = String(args.resolution ?? "720p"); + const seconds = Number(args.duration_seconds ?? 8); + return roundUsd((model.pricing.rates[resolution] ?? 0) * seconds); +} + +function roundUsd(value: number): number { + return Math.round(value * 10000) / 10000; +} diff --git a/src/compositor.ts b/src/compositor.ts new file mode 100644 index 0000000..3fbfb74 --- /dev/null +++ b/src/compositor.ts @@ -0,0 +1,169 @@ +import { spawn } from "node:child_process"; +import { mkdtemp, rm, unlink } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { mediaDir, registerDownloaded } from "./media.js"; +import type { StoredOutput, VideoOverlay } from "./types.js"; + +const commandTimeoutMs = 5 * 60 * 1000; +const maxDiagnosticBytes = 256 * 1024; + +interface VideoMetadata { + durationSeconds: number; + width: number; + height: number; +} + +export async function composeVideoOverlay( + generationId: string, + baseOutput: StoredOutput, + overlays: VideoOverlay[], +): Promise { + const workDir = await mkdtemp(path.join(os.tmpdir(), "zenvairo-compose-")); + const temporaryOutput = path.join(mediaDir, `${generationId}-0.download`); + try { + const metadata = await probeVideo(baseOutput.path); + validateComposition(metadata, overlays); + const cards: string[] = []; + for (const [index, overlay] of overlays.entries()) { + const outputPath = path.join(workDir, `card-${index}.png`); + await run(process.env.PYTHON_BIN || "python3", [ + process.env.OVERLAY_CARD_SCRIPT || "/opt/gemini-veo-mcp/scripts/make_overlay_card.py", + JSON.stringify({ text: overlay.text, kicker: overlay.kicker, style: overlay.style, out: outputPath }), + ]); + cards.push(outputPath); + } + + const ffmpegArgs = buildFfmpegArguments(baseOutput.path, cards, temporaryOutput, metadata, overlays); + await run(process.env.FFMPEG_BIN || "ffmpeg", ffmpegArgs); + return [await registerDownloaded(generationId, 0, temporaryOutput, "video/mp4")]; + } catch (error) { + await unlink(temporaryOutput).catch(() => undefined); + throw error; + } finally { + await rm(workDir, { recursive: true, force: true }); + } +} + +export function buildFfmpegFilter(metadata: Pick, overlays: VideoOverlay[]): string { + const chains: string[] = ["[0:v]setpts=PTS-STARTPTS[base]"]; + overlays.forEach((overlay, index) => { + const fade = Math.min(0.25, overlay.duration / 3); + const fadeOutStart = overlay.duration - fade; + chains.push( + `[${index + 1}:v]format=rgba,scale=${metadata.width}:${metadata.height},` + + `trim=duration=${decimal(overlay.duration)},setpts=PTS-STARTPTS,` + + `fade=t=in:st=0:d=${decimal(fade)}:alpha=1,` + + `fade=t=out:st=${decimal(fadeOutStart)}:d=${decimal(fade)}:alpha=1,` + + `setpts=PTS+${decimal(overlay.start_time)}/TB[overlay${index}]`, + ); + const input = index === 0 ? "base" : `v${index}`; + chains.push( + `[${input}][overlay${index}]overlay=0:0:eof_action=pass:shortest=0:format=auto[v${index + 1}]`, + ); + }); + return chains.join(";"); +} + +function buildFfmpegArguments( + basePath: string, + cards: string[], + outputPath: string, + metadata: VideoMetadata, + overlays: VideoOverlay[], +): string[] { + const args = ["-hide_banner", "-loglevel", "error", "-y", "-i", basePath]; + for (const card of cards) args.push("-loop", "1", "-framerate", "30", "-i", card); + args.push( + "-filter_complex", buildFfmpegFilter(metadata, overlays), + "-map", `[v${overlays.length}]`, + "-map", "0:a?", + "-map_metadata", "0", + "-c:v", "libx264", + "-preset", "medium", + "-crf", "23", + "-pix_fmt", "yuv420p", + "-c:a", "copy", + "-movflags", "+faststart", + "-shortest", + "-f", "mp4", + outputPath, + ); + return args; +} + +async function probeVideo(inputPath: string): Promise { + const result = await run(process.env.FFPROBE_BIN || "ffprobe", [ + "-v", "error", + "-select_streams", "v:0", + "-show_entries", "stream=width,height:format=duration", + "-of", "json", + inputPath, + ]); + let parsed: { streams?: Array<{ width?: number; height?: number }>; format?: { duration?: string } }; + try { + parsed = JSON.parse(result.stdout); + } catch { + throw new Error("COMPOSE_INVALID_BASE_VIDEO: ffprobe returned invalid metadata"); + } + const width = Number(parsed.streams?.[0]?.width); + const height = Number(parsed.streams?.[0]?.height); + const durationSeconds = Number(parsed.format?.duration); + if (!Number.isInteger(width) || !Number.isInteger(height) || !Number.isFinite(durationSeconds) || durationSeconds <= 0) { + throw new Error("COMPOSE_INVALID_BASE_VIDEO: missing duration or dimensions"); + } + return { width, height, durationSeconds }; +} + +function validateComposition(metadata: VideoMetadata, overlays: VideoOverlay[]): void { + const ratio = metadata.width / metadata.height; + if (Math.abs(ratio - 9 / 16) > 0.02) { + throw new Error( + `COMPOSE_BASE_ASPECT_RATIO_UNSUPPORTED: expected a vertical 9:16 video, received ${metadata.width}x${metadata.height}`, + ); + } + for (const [index, overlay] of overlays.entries()) { + if (overlay.start_time >= metadata.durationSeconds) { + throw new Error( + `COMPOSE_TIMING_OUT_OF_RANGE: overlays[${index}].start_time ${overlay.start_time} is outside the ${decimal(metadata.durationSeconds)}s base video`, + ); + } + if (overlay.start_time + overlay.duration > metadata.durationSeconds + 0.05) { + throw new Error( + `COMPOSE_TIMING_OUT_OF_RANGE: overlays[${index}] ends at ${decimal(overlay.start_time + overlay.duration)}s, after the ${decimal(metadata.durationSeconds)}s base video`, + ); + } + } +} + +async function run(command: string, args: string[]): Promise<{ stdout: string; stderr: string }> { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { shell: false, stdio: ["ignore", "pipe", "pipe"] }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + let capturedBytes = 0; + const capture = (target: Buffer[], chunk: Buffer) => { + if (capturedBytes >= maxDiagnosticBytes) return; + const remaining = maxDiagnosticBytes - capturedBytes; + target.push(chunk.subarray(0, remaining)); + capturedBytes += Math.min(chunk.length, remaining); + }; + child.stdout.on("data", (chunk: Buffer) => capture(stdout, chunk)); + child.stderr.on("data", (chunk: Buffer) => capture(stderr, chunk)); + const timeout = setTimeout(() => child.kill("SIGKILL"), commandTimeoutMs); + child.once("error", (error) => { + clearTimeout(timeout); + reject(new Error(`COMPOSE_DEPENDENCY_ERROR: failed to start ${path.basename(command)}: ${error.message}`)); + }); + child.once("close", (code, signal) => { + clearTimeout(timeout); + const output = { stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") }; + if (code === 0) resolve(output); + else reject(new Error(`COMPOSE_COMMAND_FAILED: ${path.basename(command)} exited with ${code ?? signal}: ${output.stderr.slice(-2000)}`)); + }); + }); +} + +function decimal(value: number): string { + return Number(value.toFixed(3)).toString(); +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..f760de1 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,113 @@ +import "dotenv/config"; +import { timingSafeEqual } from "node:crypto"; +import express from "express"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { JobManager } from "./jobs.js"; +import { audit, auditError } from "./log.js"; +import { cleanupOrphanMedia, ensureMediaDir, mediaDir, migrateLegacyOutputs, resolvePublicOutput } from "./media.js"; +import { publicMediaSigningConfigured, validatePublicMediaSignature } from "./public-media.js"; +import { registerTools } from "./tools.js"; + +const jobs = new JobManager(); +const retentionHours = Number(process.env.MEDIA_RETENTION_HOURS) || 168; +await ensureMediaDir(); +const orphanCleanup = async () => { + const removed = await cleanupOrphanMedia(retentionHours); + if (removed > 0) audit("orphan_media_expired", { removed, retentionHours }); +}; +await orphanCleanup(); +const migratedLegacyJobs = await migrateLegacyOutputs(); +if (migratedLegacyJobs > 0) audit("legacy_outputs_migrated", { count: migratedLegacyJobs }); +await jobs.restoreCompletedJobs(); +jobs.startCleanup(retentionHours); +const orphanCleanupInterval = setInterval(() => void orphanCleanup().catch((error) => auditError("orphan_media_cleanup_failed", error)), 15 * 60 * 1000); +orphanCleanupInterval.unref(); + +function buildServer(): McpServer { + const server = new McpServer({ name: "zenvairo-google-media", version: "1.0.0" }); + registerTools(server, jobs); + return server; +} + +const app = express(); +app.disable("x-powered-by"); +app.use(express.json({ limit: `${Number(process.env.MAX_MCP_REQUEST_MB) || 40}mb` })); + +app.get("/public-media/:filename", async (req, res) => { + const started = Date.now(); + const validation = validatePublicMediaSignature(req.params.filename, req.query.expires, req.query.signature); + if (!validation.valid) { + const status = validation.reason === "expired" ? 410 : 403; + res.setHeader("Cache-Control", "private, no-store"); + res.status(status).json({ error: validation.reason === "expired" ? "url_expired" : "invalid_signature" }); + return; + } + const output = await resolvePublicOutput(req.params.filename); + if (!output) { + res.setHeader("Cache-Control", "private, no-store"); + res.status(404).json({ error: "not_found" }); + return; + } + res.setHeader("Cache-Control", "private, no-store"); + res.setHeader("Content-Type", output.mimeType); + res.setHeader("Content-Length", String(output.sizeBytes)); + res.setHeader("X-Content-Type-Options", "nosniff"); + return res.sendFile(output.filename, { root: mediaDir, dotfiles: "deny", maxAge: 0 }, (error) => { + if (error && !res.headersSent) res.status((error as Error & { statusCode?: number }).statusCode || 404).json({ error: "not_found" }); + audit("public_media_download", { filename: output.filename, sizeBytes: output.sizeBytes, durationMs: Date.now() - started, success: !error }); + }); +}); + +app.use(authenticate); + +app.get("/health", (_req, res) => res.json({ ok: true, service: "zenvairo-google-media", googleCredentialsConfigured: Boolean(process.env.GEMINI_API_KEY), publicMediaSigningConfigured: publicMediaSigningConfigured() })); +app.get("/media/:filename", (req, res) => { + if (!/^[0-9a-f-]{36}-\d+\.(png|jpg|mp4)$/.test(req.params.filename)) return res.status(404).json({ error: "not_found" }); + return res.sendFile(req.params.filename, { root: mediaDir, dotfiles: "deny", maxAge: 0 }, (error) => { + if (error && !res.headersSent) res.status((error as Error & { statusCode?: number }).statusCode || 404).json({ error: "not_found" }); + }); +}); + +app.post("/mcp", async (req, res) => { + const started = Date.now(); + try { + const server = buildServer(); + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); + res.on("close", () => { void transport.close(); void server.close(); }); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + audit("mcp_request", { method: req.body?.method, durationMs: Date.now() - started, statusCode: res.statusCode }); + } catch (error) { + auditError("mcp_request_failed", error, { method: req.body?.method, durationMs: Date.now() - started }); + if (!res.headersSent) res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: req.body?.id ?? null }); + } +}); +app.get("/mcp", (_req, res) => res.status(405).json({ error: "Method not allowed; this stateless Streamable HTTP server accepts POST /mcp." })); +app.delete("/mcp", (_req, res) => res.status(405).json({ error: "Method not allowed; this stateless Streamable HTTP server accepts POST /mcp." })); + +const port = Number(process.env.PORT) || 8087; +const host = process.env.HOST || "127.0.0.1"; +app.listen(port, host, () => audit("server_started", { host, port, endpoint: "/mcp", mediaRetentionHours: retentionHours })); + +function authenticate(req: express.Request, res: express.Response, next: express.NextFunction): void { + const required = process.env.MCP_SERVER_TOKEN; + if (!required) { + res.status(503).json({ error: "server_not_configured", message: "MCP_SERVER_TOKEN is required" }); + return; + } + const authorization = req.get("authorization") || ""; + const bearer = authorization.startsWith("Bearer ") ? authorization.slice(7) : ""; + const injected = req.get("x-mcp-server-token") || ""; + if (!safeEqual(required, bearer) && !safeEqual(required, injected)) { + res.setHeader("WWW-Authenticate", "Bearer"); + res.status(401).json({ error: "unauthorized" }); + return; + } + next(); +} + +function safeEqual(expected: string, actual: string): boolean { + const a = Buffer.from(expected); const b = Buffer.from(actual); + return a.length === b.length && timingSafeEqual(a, b); +} diff --git a/src/jobs.ts b/src/jobs.ts new file mode 100644 index 0000000..af37ba6 --- /dev/null +++ b/src/jobs.ts @@ -0,0 +1,231 @@ +import { randomUUID } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { estimateCost, resolveModel } from "./catalog.js"; +import { audit, auditError, providerStatus } from "./log.js"; +import { generationWasPurged, loadPersistedJob, loadPersistedJobs, outputExists, persistCompletedJob, purgeGeneration } from "./media.js"; +import { composeVideoOverlay } from "./compositor.js"; +import { GoogleMediaProvider } from "./provider.js"; +import type { GenerationJob, InlineReferenceImage, JobKind, ReferenceImage, VideoOverlay } from "./types.js"; + +export class JobManager { + private readonly jobs = new Map(); + private estimatedSubmittedUsd = 0; + private estimatedCompletedUsd = 0; + + constructor(private readonly provider = new GoogleMediaProvider()) {} + + submit(kind: JobKind, requestedModel: string, args: Record, taskTraceId?: string): GenerationJob { + const model = resolveModel(requestedModel, kind); + const now = new Date().toISOString(); + const job: GenerationJob = { + generationId: randomUUID(), taskTraceId, kind, model: model.name, canonicalModel: model.canonicalApiModel, + arguments: args, estimatedCostUsd: estimateCost(model, args), status: "QUEUING", createdAt: now, updatedAt: now, + }; + this.jobs.set(job.generationId, job); + this.estimatedSubmittedUsd += job.estimatedCostUsd; + audit("generation_queued", { + generationId: job.generationId, taskTraceId, kind, model: job.model, + referenceImageCount: Array.isArray(args.reference_images) ? args.reference_images.length : 0, + estimatedCostUsd: job.estimatedCostUsd, + }); + setImmediate(() => void (kind === "image" ? this.runImage(job) : this.runVideoSubmit(job))); + return job; + } + + get(generationId: string): GenerationJob | undefined { return this.jobs.get(generationId); } + + async submitComposition(baseGenerationId: string, overlays: VideoOverlay[], taskTraceId?: string): Promise { + let base = this.jobs.get(baseGenerationId); + if (!base) { + base = await loadPersistedJob(baseGenerationId); + if (base) this.jobs.set(base.generationId, base); + } + if (!base) { + const code = await generationWasPurged(baseGenerationId) ? "COMPOSE_BASE_EXPIRED" : "COMPOSE_BASE_NOT_FOUND"; + throw new Error(`${code}: base_generation_id ${baseGenerationId} is unavailable`); + } + if (base.kind !== "video") throw new Error(`COMPOSE_BASE_IS_NOT_VIDEO: base_generation_id ${baseGenerationId} is an image generation`); + if (base.status !== "COMPLETED" || !base.outputs) { + throw new Error(`COMPOSE_BASE_NOT_COMPLETED: base_generation_id ${baseGenerationId} has status ${base.status}; wait for COMPLETED`); + } + const baseOutput = base.outputs.find((output) => output.index === 0 && output.mimeType === "video/mp4"); + if (!baseOutput) throw new Error(`COMPOSE_BASE_OUTPUT_MISSING: base_generation_id ${baseGenerationId} has no video/mp4 output at index 0`); + if (!(await outputExists(baseOutput))) throw new Error(`COMPOSE_BASE_EXPIRED: base_generation_id ${baseGenerationId} media has expired or was purged`); + + const now = new Date().toISOString(); + const job: GenerationJob = { + generationId: randomUUID(), taskTraceId, kind: "video", model: "ffmpeg-overlay", canonicalModel: "local-ffmpeg-overlay-v1", + arguments: { base_generation_id: baseGenerationId, overlays }, estimatedCostUsd: 0, status: "QUEUING", createdAt: now, updatedAt: now, + }; + this.jobs.set(job.generationId, job); + audit("composition_queued", { generationId: job.generationId, taskTraceId, baseGenerationId, overlayCount: overlays.length }); + setImmediate(() => void this.runComposition(job, baseOutput, overlays)); + return job; + } + + async restoreCompletedJobs(): Promise { + const restored = await loadPersistedJobs(); + for (const job of restored) { + this.jobs.set(job.generationId, job); + this.estimatedCompletedUsd += job.estimatedCostUsd; + } + if (restored.length > 0) audit("completed_jobs_restored", { count: restored.length }); + return restored.length; + } + + async resolveImageReferences(args: Record): Promise> { + const references = args.reference_images as ReferenceImage[] | undefined; + if (!references) return args; + const resolved: InlineReferenceImage[] = []; + const maxAggregateBytes = Math.floor((Number(process.env.MAX_REFERENCE_INPUT_MB) || 25) * 1024 * 1024); + let aggregateBytes = 0; + + for (const [position, reference] of references.entries()) { + if ("base64" in reference) { + aggregateBytes += decodedBase64Size(reference.base64); + resolved.push(reference); + } else { + let source = this.jobs.get(reference.generation_id); + if (!source) { + source = await loadPersistedJob(reference.generation_id); + if (source) this.jobs.set(source.generationId, source); + } + if (!source) { + if (await generationWasPurged(reference.generation_id)) { + throw new Error(`REFERENCE_GENERATION_EXPIRED: reference_images[${position}] generation_id ${reference.generation_id} has expired or was purged by retention`); + } + throw new Error(`REFERENCE_GENERATION_NOT_FOUND: reference_images[${position}] generation_id ${reference.generation_id} does not exist`); + } + if (source.kind === "video") { + throw new Error(`REFERENCE_IS_VIDEO: reference_images[${position}] generation_id ${reference.generation_id} is a video generation and cannot be used as an image reference`); + } + if (source.status !== "COMPLETED" || !source.outputs) { + throw new Error(`REFERENCE_GENERATION_NOT_COMPLETED: reference_images[${position}] generation_id ${reference.generation_id} has status ${source.status}; wait for COMPLETED`); + } + const output = source.outputs.find((candidate) => candidate.index === reference.index); + if (!output) { + const available = source.outputs.map((candidate) => candidate.index).sort((a, b) => a - b); + throw new Error(`REFERENCE_INDEX_OUT_OF_RANGE: reference_images[${position}] index ${reference.index} is unavailable for generation ${reference.generation_id}; available indexes: ${available.join(", ") || "none"}`); + } + if (!(await outputExists(output))) { + throw new Error(`REFERENCE_GENERATION_EXPIRED: reference_images[${position}] generation_id ${reference.generation_id} output ${reference.index} has expired or was purged by retention`); + } + if (output.mimeType !== "image/png" && output.mimeType !== "image/jpeg" && output.mimeType !== "image/webp") { + throw new Error(`REFERENCE_IS_VIDEO: reference_images[${position}] generation_id ${reference.generation_id} output ${reference.index} is ${output.mimeType}, not an image`); + } + aggregateBytes += output.sizeBytes; + resolved.push({ base64: (await readFile(output.path)).toString("base64"), mime_type: output.mimeType }); + } + if (aggregateBytes > maxAggregateBytes) { + throw new Error(`REFERENCE_INPUT_TOO_LARGE: reference_images exceed the aggregate MAX_REFERENCE_INPUT_MB limit (${maxAggregateBytes} bytes)`); + } + } + return { ...args, reference_images: resolved }; + } + + async refresh(job: GenerationJob): Promise { + if (job.kind !== "video" || job.status !== "RUNNING" || !job.operation) return job; + try { + const result = await this.provider.pollVideo(job); + job.operation = result.operation; + job.updatedAt = new Date().toISOString(); + if (result.done && result.outputs) await this.complete(job, result.outputs); + } catch (error) { + this.fail(job, error); + } + return job; + } + + usage(): Record { + const jobs = [...this.jobs.values()]; + return { + providerQuotaAvailable: false, + providerQuotaMessage: "The Gemini Developer API does not expose remaining account spend/quota through this generation API.", + scope: "current process plus completed generations restored from retained disk manifests", + jobsSubmitted: jobs.length, + jobsCompleted: jobs.filter((job) => job.status === "COMPLETED").length, + jobsFailed: jobs.filter((job) => job.status === "FAILED").length, + jobsInProgress: jobs.filter((job) => job.status === "QUEUING" || job.status === "RUNNING").length, + estimatedSubmittedCostUsd: Math.round(this.estimatedSubmittedUsd * 10000) / 10000, + estimatedCompletedCostUsd: Math.round(this.estimatedCompletedUsd * 10000) / 10000, + }; + } + + startCleanup(retentionHours: number): NodeJS.Timeout { + const interval = setInterval(() => void this.cleanup(retentionHours), 15 * 60 * 1000); + interval.unref(); + return interval; + } + + async cleanup(retentionHours: number): Promise { + const cutoff = Date.now() - retentionHours * 60 * 60 * 1000; + for (const [id, job] of this.jobs) { + if ((job.status === "COMPLETED" || job.status === "FAILED") && new Date(job.updatedAt).getTime() < cutoff) { + await purgeGeneration(job); + this.jobs.delete(id); + audit("generation_expired", { generationId: id, retentionHours }); + } + } + } + + private async runImage(job: GenerationJob): Promise { + this.start(job); + try { await this.complete(job, await this.provider.generateImages(job)); } + catch (error) { this.fail(job, error); } + } + + private async runVideoSubmit(job: GenerationJob): Promise { + this.start(job); + try { + job.operation = await this.provider.submitVideo(job); + job.updatedAt = new Date().toISOString(); + audit("video_operation_submitted", { generationId: job.generationId, model: job.model }); + } catch (error) { this.fail(job, error); } + } + + private async runComposition(job: GenerationJob, baseOutput: NonNullable[number], overlays: VideoOverlay[]): Promise { + this.start(job); + try { await this.complete(job, await composeVideoOverlay(job.generationId, baseOutput, overlays)); } + catch (error) { this.fail(job, error); } + } + + private start(job: GenerationJob): void { + job.status = "RUNNING"; job.startedAt = new Date().toISOString(); job.updatedAt = job.startedAt; + audit("generation_started", { generationId: job.generationId, kind: job.kind, model: job.model }); + } + + private async complete(job: GenerationJob, outputs: NonNullable): Promise { + job.status = "COMPLETED"; job.outputs = outputs; job.operation = undefined; job.completedAt = new Date().toISOString(); job.updatedAt = job.completedAt; + await persistCompletedJob(job); + job.arguments = {}; + this.estimatedCompletedUsd += job.estimatedCostUsd; + const durationMs = job.startedAt ? Date.now() - new Date(job.startedAt).getTime() : undefined; + audit("generation_completed", { generationId: job.generationId, kind: job.kind, model: job.model, outputCount: outputs.length, outputBytes: outputs.reduce((sum, output) => sum + output.sizeBytes, 0), durationMs, estimatedCostUsd: job.estimatedCostUsd }); + } + + private fail(job: GenerationJob, error: unknown): void { + const status = providerStatus(error); + const rawMessage = error instanceof Error ? error.message : String(error); + job.status = "FAILED"; job.updatedAt = new Date().toISOString(); job.completedAt = job.updatedAt; + job.arguments = {}; + job.error = { code: classifyError(rawMessage, status), message: rawMessage.slice(0, 2000), ...(status ? { providerStatus: status } : {}), retryable: false }; + auditError("generation_failed", error, { generationId: job.generationId, kind: job.kind, model: job.model, durationMs: job.startedAt ? Date.now() - new Date(job.startedAt).getTime() : undefined }); + } +} + +function decodedBase64Size(base64: string): number { + const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0; + return Math.floor(base64.length * 3 / 4) - padding; +} + +function classifyError(message: string, status?: number): string { + const composeCode = message.match(/^(COMPOSE_[A-Z_]+):/)?.[1]; + if (composeCode) return composeCode; + if (message.includes("GEMINI_API_KEY")) return "SERVER_NOT_CONFIGURED"; + if (status === 429) return "PROVIDER_RATE_LIMITED"; + if (status && status >= 500) return "PROVIDER_UNAVAILABLE"; + if (/safety|blocked|moderation|policy/i.test(message)) return "CONTENT_POLICY_BLOCKED"; + if (status === 400 || /invalid|unsupported|required|prompt/i.test(message)) return "INVALID_REQUEST"; + if (status === 401 || status === 403) return "PROVIDER_AUTH_ERROR"; + return "GENERATION_FAILED"; +} diff --git a/src/log.ts b/src/log.ts new file mode 100644 index 0000000..eb0de41 --- /dev/null +++ b/src/log.ts @@ -0,0 +1,27 @@ +export function audit(event: string, fields: Record = {}): void { + process.stdout.write(`${JSON.stringify({ timestamp: new Date().toISOString(), level: "info", event, ...fields })}\n`); +} + +export function auditError(event: string, error: unknown, fields: Record = {}): void { + const details = errorDetails(error); + process.stderr.write(`${JSON.stringify({ timestamp: new Date().toISOString(), level: "error", event, ...fields, ...details })}\n`); +} + +export function errorDetails(error: unknown): { errorName: string; errorMessage: string; providerStatus?: number } { + if (error instanceof Error) { + const status = providerStatus(error); + return { errorName: error.name, errorMessage: error.message, ...(status ? { providerStatus: status } : {}) }; + } + return { errorName: "UnknownError", errorMessage: String(error) }; +} + +export function providerStatus(error: unknown): number | undefined { + if (!error || typeof error !== "object") return undefined; + const record = error as Record; + const candidates = [record.status, record.statusCode, record.code]; + for (const value of candidates) { + const parsed = typeof value === "number" ? value : Number(value); + if (Number.isInteger(parsed) && parsed >= 100 && parsed <= 599) return parsed; + } + return undefined; +} diff --git a/src/media.ts b/src/media.ts new file mode 100644 index 0000000..84029de --- /dev/null +++ b/src/media.ts @@ -0,0 +1,298 @@ +import { createHash } from "node:crypto"; +import { createReadStream } from "node:fs"; +import { chmod, mkdir, open, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; +import path from "node:path"; +import type { GenerationJob, StoredOutput } from "./types.js"; +import { createPublicMediaUrl } from "./public-media.js"; + +export const mediaDir = path.resolve(process.env.MEDIA_DIR || "/opt/gemini-veo-mcp/media"); +export const maxInlineBytes = Math.floor((Number(process.env.MAX_INLINE_MEDIA_MB) || 25) * 1024 * 1024); +export const maxMediaBytes = Math.floor((Number(process.env.MAX_MEDIA_MB) || 300) * 1024 * 1024); +const tombstoneRetentionDays = Number(process.env.TOMBSTONE_RETENTION_DAYS) || 30; + +export async function ensureMediaDir(): Promise { + await mkdir(mediaDir, { recursive: true }); +} + +export async function storeBase64(generationId: string, index: number, data: string, mimeType: string): Promise { + const buffer = Buffer.from(data, "base64"); + if (buffer.length === 0) throw new Error("Google returned an empty media payload"); + if (buffer.length > maxMediaBytes) throw new Error(`Generated media exceeds MAX_MEDIA_MB (${maxMediaBytes} bytes)`); + const normalizedMime = normalizeMime(mimeType, buffer); + const extension = normalizedMime === "video/mp4" ? "mp4" : normalizedMime === "image/jpeg" ? "jpg" : "png"; + const filename = `${generationId}-${index}.${extension}`; + const outputPath = path.join(mediaDir, filename); + await writeFile(outputPath, buffer, { mode: 0o640 }); + return metadata(outputPath, filename, normalizedMime, buffer); +} + +export async function registerDownloaded(generationId: string, index: number, tempPath: string, mimeType = "video/mp4"): Promise { + const file = await stat(tempPath); + if (file.size === 0) throw new Error("Google returned an empty video file"); + if (file.size > maxMediaBytes) { + await unlink(tempPath).catch(() => undefined); + throw new Error(`Generated media exceeds MAX_MEDIA_MB (${maxMediaBytes} bytes)`); + } + const handle = await open(tempPath, "r"); + const header = Buffer.alloc(12); + await handle.read(header, 0, header.length, 0); + await handle.close(); + const normalizedMime = normalizeMime(mimeType, header); + if (normalizedMime !== "video/mp4") throw new Error(`Expected video/mp4, received ${normalizedMime}`); + const filename = `${generationId}-${index}.mp4`; + const outputPath = path.join(mediaDir, filename); + if (tempPath !== outputPath) { + await rename(tempPath, outputPath); + } + await chmod(outputPath, 0o640); + return { index, path: outputPath, filename, mimeType: normalizedMime, sizeBytes: file.size, sha256: await hashFile(outputPath) }; +} + +export async function outputPayload(outputs: StoredOutput[], publicBaseUrl: string, includeBase64 = true): Promise>> { + const totalBytes = outputs.reduce((sum, output) => sum + output.sizeBytes, 0); + const inline = includeBase64 && totalBytes <= maxInlineBytes; + return Promise.all(outputs.map(async (output) => { + const signed = createPublicMediaUrl(output.filename, publicBaseUrl); + return { + index: output.index, + mimeType: output.mimeType, + sizeBytes: output.sizeBytes, + sha256: output.sha256, + ...signed, + ...(inline + ? { base64: (await readFile(output.path)).toString("base64") } + : { downloadUrl: `${publicBaseUrl.replace(/\/$/, "")}/media/${encodeURIComponent(output.filename)}` }), + }; + })); +} + +export async function resolvePublicOutput(filename: string): Promise { + const match = filename.match(/^([0-9a-f-]{36})-(\d+)\.(png|jpg|mp4)$/); + if (!match) return undefined; + const job = await loadPersistedJob(match[1]); + const output = job?.outputs?.find((candidate) => candidate.filename === filename && candidate.index === Number(match[2])); + if (!output || !(await outputExists(output))) return undefined; + return output; +} + +export async function removeOutputs(outputs: StoredOutput[] | undefined): Promise { + if (!outputs) return; + await Promise.all(outputs.map((output) => unlink(output.path).catch(() => undefined))); +} + +export async function persistCompletedJob(job: GenerationJob): Promise { + if (job.status !== "COMPLETED" || !job.outputs) throw new Error("Only completed jobs with outputs can be persisted"); + const manifest = { + version: 1, + generationId: job.generationId, + taskTraceId: job.taskTraceId, + kind: job.kind, + model: job.model, + canonicalModel: job.canonicalModel, + estimatedCostUsd: job.estimatedCostUsd, + status: "COMPLETED", + createdAt: job.createdAt, + startedAt: job.startedAt, + completedAt: job.completedAt, + updatedAt: job.updatedAt, + outputs: job.outputs.map((output) => ({ + index: output.index, + filename: output.filename, + mimeType: output.mimeType, + sizeBytes: output.sizeBytes, + sha256: output.sha256, + })), + }; + const target = manifestPath(job.generationId); + const temporary = `${target}.${process.pid}.tmp`; + await writeFile(temporary, JSON.stringify(manifest), { mode: 0o640 }); + await rename(temporary, target); +} + +export async function loadPersistedJobs(): Promise { + const jobs: GenerationJob[] = []; + for (const filename of await readdir(mediaDir)) { + const match = filename.match(/^([0-9a-f-]{36})\.manifest\.json$/); + if (!match) continue; + const job = await loadPersistedJob(match[1]); + if (job) jobs.push(job); + } + return jobs; +} + +export async function migrateLegacyOutputs(): Promise { + const groups = new Map>(); + for (const filename of await readdir(mediaDir)) { + const match = filename.match(/^([0-9a-f-]{36})-(\d+)\.(png|jpg|mp4)$/); + if (!match) continue; + const list = groups.get(match[1]) ?? []; + list.push({ index: Number(match[2]), filename, extension: match[3] as "png" | "jpg" | "mp4" }); + groups.set(match[1], list); + } + + let migrated = 0; + for (const [generationId, files] of groups) { + try { + await stat(manifestPath(generationId)); + continue; + } catch { + // No manifest: this is an output created by the pre-persistence server. + } + if (await generationWasPurged(generationId)) continue; + const outputs: StoredOutput[] = []; + let latestMtime = 0; + for (const file of files.sort((a, b) => a.index - b.index)) { + const outputPath = path.join(mediaDir, file.filename); + const details = await stat(outputPath); + latestMtime = Math.max(latestMtime, details.mtimeMs); + outputs.push({ + index: file.index, + path: outputPath, + filename: file.filename, + mimeType: file.extension === "png" ? "image/png" : file.extension === "jpg" ? "image/jpeg" : "video/mp4", + sizeBytes: details.size, + sha256: await hashFile(outputPath), + }); + } + const timestamp = new Date(latestMtime || Date.now()).toISOString(); + await persistCompletedJob({ + generationId, + kind: outputs.every((output) => output.mimeType.startsWith("image/")) ? "image" : "video", + model: "legacy-restored", + canonicalModel: "legacy-restored", + arguments: {}, + estimatedCostUsd: 0, + status: "COMPLETED", + createdAt: timestamp, + startedAt: timestamp, + completedAt: timestamp, + updatedAt: timestamp, + outputs, + }); + migrated += 1; + } + return migrated; +} + +export async function loadPersistedJob(generationId: string): Promise { + try { + const parsed = JSON.parse(await readFile(manifestPath(generationId), "utf8")) as Record; + if (parsed.version !== 1 || parsed.generationId !== generationId || parsed.status !== "COMPLETED") return undefined; + if (parsed.kind !== "image" && parsed.kind !== "video") return undefined; + if (!Array.isArray(parsed.outputs)) return undefined; + const outputs: StoredOutput[] = parsed.outputs.map((value, position) => { + if (!value || typeof value !== "object") throw new Error("Invalid persisted output"); + const output = value as Record; + const index = Number(output.index ?? position); + const filename = String(output.filename ?? ""); + if (!Number.isInteger(index) || index < 0 || !safeOutputFilename(generationId, index, filename)) throw new Error("Invalid persisted output path"); + return { + index, + path: path.join(mediaDir, filename), + filename, + mimeType: String(output.mimeType), + sizeBytes: Number(output.sizeBytes), + sha256: String(output.sha256), + }; + }); + return { + generationId, + taskTraceId: typeof parsed.taskTraceId === "string" ? parsed.taskTraceId : undefined, + kind: parsed.kind, + model: String(parsed.model), + canonicalModel: String(parsed.canonicalModel), + arguments: {}, + estimatedCostUsd: Number(parsed.estimatedCostUsd) || 0, + status: "COMPLETED", + createdAt: String(parsed.createdAt), + startedAt: typeof parsed.startedAt === "string" ? parsed.startedAt : undefined, + completedAt: typeof parsed.completedAt === "string" ? parsed.completedAt : undefined, + updatedAt: String(parsed.updatedAt), + outputs, + }; + } catch { + return undefined; + } +} + +export async function purgeGeneration(job: GenerationJob): Promise { + await removeOutputs(job.outputs); + await unlink(manifestPath(job.generationId)).catch(() => undefined); + await writeTombstone(job.generationId); +} + +export async function generationWasPurged(generationId: string): Promise { + try { + return (await stat(tombstonePath(generationId))).isFile(); + } catch { + return false; + } +} + +export async function outputExists(output: StoredOutput): Promise { + try { + const file = await stat(output.path); + return file.isFile() && file.size === output.sizeBytes; + } catch { + return false; + } +} + +export async function cleanupOrphanMedia(retentionHours: number): Promise { + const cutoff = Date.now() - retentionHours * 60 * 60 * 1000; + const tombstoneCutoff = Date.now() - tombstoneRetentionDays * 24 * 60 * 60 * 1000; + let removed = 0; + for (const filename of await readdir(mediaDir)) { + const artifact = filename.match(/^([0-9a-f-]{36})(?:-\d+\.(?:png|jpg|mp4|download)|\.manifest\.json)$/); + const tombstone = filename.match(/^([0-9a-f-]{36})\.expired\.json$/); + if (!artifact && !tombstone) continue; + const outputPath = path.join(mediaDir, filename); + try { + const file = await stat(outputPath); + if (artifact && file.mtimeMs < cutoff) { + await unlink(outputPath); + await writeTombstone(artifact[1]); + removed += 1; + } else if (tombstone && file.mtimeMs < tombstoneCutoff) { + await unlink(outputPath); + } + } catch { + // A concurrent cleanup/download may have removed the file. + } + } + return removed; +} + +function metadata(outputPath: string, filename: string, mimeType: string, buffer: Buffer): StoredOutput { + const index = Number(filename.match(/-(\d+)\.[^.]+$/)?.[1] ?? 0); + return { index, path: outputPath, filename, mimeType, sizeBytes: buffer.length, sha256: createHash("sha256").update(buffer).digest("hex") }; +} + +async function hashFile(outputPath: string): Promise { + const hash = createHash("sha256"); + for await (const chunk of createReadStream(outputPath)) hash.update(chunk as Buffer); + return hash.digest("hex"); +} + +function normalizeMime(reported: string | undefined, data: Buffer): string { + if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "image/png"; + if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return "image/jpeg"; + if (data.length >= 12 && data.subarray(4, 8).toString("ascii") === "ftyp") return "video/mp4"; + return reported || "application/octet-stream"; +} + +function manifestPath(generationId: string): string { + return path.join(mediaDir, `${generationId}.manifest.json`); +} + +function tombstonePath(generationId: string): string { + return path.join(mediaDir, `${generationId}.expired.json`); +} + +async function writeTombstone(generationId: string): Promise { + await writeFile(tombstonePath(generationId), JSON.stringify({ generationId, purgedAt: new Date().toISOString() }), { mode: 0o640 }); +} + +function safeOutputFilename(generationId: string, index: number, filename: string): boolean { + return filename.startsWith(`${generationId}-${index}.`) && /^[0-9a-f-]{36}-\d+\.(png|jpg|mp4)$/.test(filename); +} diff --git a/src/provider.ts b/src/provider.ts new file mode 100644 index 0000000..84226cf --- /dev/null +++ b/src/provider.ts @@ -0,0 +1,101 @@ +import { GoogleGenAI } from "@google/genai"; +import path from "node:path"; +import { mediaDir, registerDownloaded, removeOutputs, storeBase64 } from "./media.js"; +import { withRetry } from "./retry.js"; +import type { GenerationJob, StoredOutput } from "./types.js"; + +export class GoogleMediaProvider { + private readonly client: GoogleGenAI; + + constructor(apiKey = process.env.GEMINI_API_KEY) { + this.client = new GoogleGenAI({ apiKey: apiKey || "missing-gemini-api-key" }); + } + + async generateImages(job: GenerationJob): Promise { + this.assertConfigured(); + const count = Number(job.arguments.image_count ?? 1); + const outputs: StoredOutput[] = []; + + try { + for (let index = 0; index < count; index += 1) { + const references = (job.arguments.reference_images as Array<{ base64: string; mime_type: string }> | undefined) ?? []; + const response: any = await withRetry("generate_image", () => this.client.models.generateContent({ + model: job.canonicalModel, + contents: [{ + role: "user", + parts: [ + ...references.map((reference) => ({ inlineData: { data: reference.base64, mimeType: reference.mime_type } })), + { text: String(job.arguments.prompt) }, + ], + }], + config: { + responseModalities: ["IMAGE"], + imageConfig: { + aspectRatio: String(job.arguments.aspect_ratio), + ...(job.canonicalModel !== "gemini-2.5-flash-image" ? { imageSize: String(job.arguments.resolution) } : {}), + }, + }, + })); + + const parts = response?.candidates?.flatMap((candidate: any) => candidate?.content?.parts ?? []) ?? []; + const imagePart = parts.find((part: any) => part?.inlineData?.data); + if (!imagePart?.inlineData?.data) { + const reason = response?.promptFeedback?.blockReason || response?.candidates?.[0]?.finishReason; + throw new Error(reason ? `Image generation produced no image (${reason})` : "Image generation produced no image"); + } + outputs.push(await storeBase64(job.generationId, index, imagePart.inlineData.data, imagePart.inlineData.mimeType || "image/png")); + } + return outputs; + } catch (error) { + await removeOutputs(outputs); + throw error; + } + } + + async submitVideo(job: GenerationJob): Promise { + this.assertConfigured(); + return withRetry("submit_video", () => this.client.models.generateVideos({ + model: job.canonicalModel, + prompt: String(job.arguments.prompt), + config: { + aspectRatio: String(job.arguments.aspect_ratio), + durationSeconds: Number(job.arguments.duration_seconds), + resolution: String(job.arguments.resolution), + numberOfVideos: 1, + ...(job.arguments.seed !== undefined ? { seed: Number(job.arguments.seed) } : {}), + }, + })); + } + + async pollVideo(job: GenerationJob): Promise<{ done: boolean; operation: unknown; outputs?: StoredOutput[] }> { + this.assertConfigured(); + if (!job.operation) return { done: false, operation: job.operation }; + const operation: any = await withRetry("poll_video", () => this.client.operations.getVideosOperation({ operation: job.operation as any })); + if (!operation?.done) return { done: false, operation }; + if (operation.error) { + const error = new Error(operation.error.message || "Veo generation failed") as Error & { code?: number }; + error.code = operation.error.code; + throw error; + } + + const videos = operation?.response?.generatedVideos ?? []; + if (videos.length === 0) throw new Error("Veo operation completed without a video"); + const outputs: StoredOutput[] = []; + for (let index = 0; index < videos.length; index += 1) { + const video = videos[index]?.video; + if (video?.videoBytes) { + outputs.push(await storeBase64(job.generationId, index, video.videoBytes, video.mimeType || "video/mp4")); + continue; + } + if (!video) throw new Error("Veo returned an invalid video reference"); + const tempPath = path.join(mediaDir, `${job.generationId}-${index}.download`); + await withRetry("download_video", () => this.client.files.download({ file: video, downloadPath: tempPath })); + outputs.push(await registerDownloaded(job.generationId, index, tempPath, video.mimeType || "video/mp4")); + } + return { done: true, operation, outputs }; + } + + private assertConfigured(): void { + if (!process.env.GEMINI_API_KEY) throw new Error("GEMINI_API_KEY is not configured on the MCP server"); + } +} diff --git a/src/public-media.ts b/src/public-media.ts new file mode 100644 index 0000000..caa518b --- /dev/null +++ b/src/public-media.ts @@ -0,0 +1,83 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; + +const DEFAULT_TTL_SECONDS = 24 * 60 * 60; +const MAX_TTL_SECONDS = 7 * 24 * 60 * 60; +const CLOCK_SKEW_SECONDS = 60; + +export interface SignedPublicMediaUrl { + publicUrl: string; + publicUrlExpiresAt: string; +} + +export function publicMediaTtlSeconds(): number { + const configured = Number(process.env.PUBLIC_MEDIA_URL_TTL_SECONDS); + if (!Number.isInteger(configured) || configured < 60) return DEFAULT_TTL_SECONDS; + return Math.min(configured, MAX_TTL_SECONDS); +} + +export function publicMediaSigningConfigured(): boolean { + return signingSecret().length >= 32; +} + +export function createPublicMediaUrl( + filename: string, + publicBaseUrl: string, + nowMs = Date.now(), +): SignedPublicMediaUrl { + assertSafeFilename(filename); + const secret = requireSigningSecret(); + const expires = Math.floor(nowMs / 1000) + publicMediaTtlSeconds(); + const signature = sign(filename, expires, secret); + const base = publicBaseUrl.replace(/\/+$/, ""); + return { + publicUrl: `${base}/public-media/${encodeURIComponent(filename)}?expires=${expires}&signature=${signature}`, + publicUrlExpiresAt: new Date(expires * 1000).toISOString(), + }; +} + +export function validatePublicMediaSignature( + filename: string, + rawExpires: unknown, + rawSignature: unknown, + nowMs = Date.now(), +): { valid: true; expires: number } | { valid: false; reason: "invalid" | "expired" } { + if (!publicMediaSigningConfigured()) return { valid: false, reason: "invalid" }; + try { + assertSafeFilename(filename); + } catch { + return { valid: false, reason: "invalid" }; + } + if (typeof rawExpires !== "string" || !/^\d{10}$/.test(rawExpires)) return { valid: false, reason: "invalid" }; + if (typeof rawSignature !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(rawSignature)) return { valid: false, reason: "invalid" }; + + const expires = Number(rawExpires); + const nowSeconds = Math.floor(nowMs / 1000); + if (!Number.isSafeInteger(expires)) return { valid: false, reason: "invalid" }; + if (expires < nowSeconds) return { valid: false, reason: "expired" }; + if (expires > nowSeconds + publicMediaTtlSeconds() + CLOCK_SKEW_SECONDS) return { valid: false, reason: "invalid" }; + + const expected = Buffer.from(sign(filename, expires, requireSigningSecret())); + const actual = Buffer.from(rawSignature); + if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return { valid: false, reason: "invalid" }; + return { valid: true, expires }; +} + +function sign(filename: string, expires: number, secret: string): string { + return createHmac("sha256", secret) + .update(`zenvairo-public-media-v1\n${filename}\n${expires}`, "utf8") + .digest("base64url"); +} + +function signingSecret(): string { + return process.env.PUBLIC_MEDIA_SIGNING_SECRET || ""; +} + +function requireSigningSecret(): string { + const secret = signingSecret(); + if (secret.length < 32) throw new Error("PUBLIC_MEDIA_SIGNING_SECRET must contain at least 32 characters"); + return secret; +} + +function assertSafeFilename(filename: string): void { + if (!/^[0-9a-f-]{36}-\d+\.(png|jpg|mp4)$/.test(filename)) throw new Error("Invalid public media filename"); +} diff --git a/src/retry.ts b/src/retry.ts new file mode 100644 index 0000000..6bbf000 --- /dev/null +++ b/src/retry.ts @@ -0,0 +1,26 @@ +import { audit } from "./log.js"; +import { providerStatus } from "./log.js"; + +export function isTransient(error: unknown): boolean { + const status = providerStatus(error); + if (status === 429 || (status !== undefined && status >= 500)) return true; + if (error instanceof Error) { + return /ECONNRESET|ETIMEDOUT|EAI_AGAIN|fetch failed|network/i.test(error.message); + } + return false; +} + +export async function withRetry(operation: string, fn: () => Promise, maxRetries = 2): Promise { + let attempt = 0; + while (true) { + try { + return await fn(); + } catch (error) { + if (!isTransient(error) || attempt >= maxRetries) throw error; + attempt += 1; + const delayMs = Math.min(4000, 500 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 250); + audit("provider_retry", { operation, attempt, maxRetries, delayMs, providerStatus: providerStatus(error) }); + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + } +} diff --git a/src/tools.ts b/src/tools.ts new file mode 100644 index 0000000..30adbd9 --- /dev/null +++ b/src/tools.ts @@ -0,0 +1,152 @@ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { z } from "zod"; +import { normalizeArguments } from "./arguments.js"; +import { MODEL_CATALOG, PRICING_REFERENCE_DATE, resolveModel } from "./catalog.js"; +import { JobManager } from "./jobs.js"; +import { maxInlineBytes, outputExists, outputPayload } from "./media.js"; +import { publicMediaSigningConfigured, publicMediaTtlSeconds } from "./public-media.js"; + +const taskTraceIdSchema = z.string().uuid().optional().describe("Optional UUID used to group related calls."); +const inlineReferenceImageSchema = z.object({ + base64: z.string().min(1).describe("Raw standard base64 from query_tasks outputs[].base64; a data URI is also accepted."), + mime_type: z.enum(["image/png", "image/jpeg", "image/webp"]), +}).strict(); +const generationReferenceImageSchema = z.object({ + generation_id: z.string().uuid().describe("generationId of a completed image generation retained by this server."), + index: z.number().int().nonnegative().default(0).describe("Zero-based output index; defaults to 0."), +}).strict(); +const referenceImageSchema = z.union([inlineReferenceImageSchema, generationReferenceImageSchema]); +const argumentsSchema = z.array(z.object({ + name: z.string().min(1), + value: z.union([z.string(), z.number(), z.boolean(), z.array(referenceImageSchema)]), +})).describe("Kling-compatible name/value argument list."); +const videoOverlaySchema = z.object({ + text: z.string().trim().min(1).max(240).describe("Card text; never logged."), + kicker: z.string().trim().min(1).max(40).optional().describe("Optional uppercase label displayed above the text."), + style: z.enum(["normal", "cta"]).default("normal"), + start_time: z.number().finite().min(0).max(600).describe("Seconds from the start of the base video."), + duration: z.number().finite().min(0.5).max(60).describe("Seconds the card remains visible, including 250ms fades."), +}).strict(); + +export function registerTools(server: McpServer, jobs: JobManager): void { + const retentionHours = Number(process.env.MEDIA_RETENTION_HOURS) || 168; + server.tool("who_am_i", "List available Google image/video models, accepted arguments and current cost estimates.", { + taskTraceId: taskTraceIdSchema, + }, async ({ taskTraceId }) => jsonResult({ + service: "Zenvairo Google Media MCP", + taskTraceId, + backend: "Gemini Developer API", + authentication: { googleCredentialsConfigured: Boolean(process.env.GEMINI_API_KEY), credentialsExposed: false }, + pricingReferenceDate: PRICING_REFERENCE_DATE, + costCaveat: "Estimates cover output image/video pricing only; prompt input tokens and optional grounding charges are excluded.", + resultDelivery: { + inlineBase64AggregateLimitBytes: maxInlineBytes, + inlineBase64AggregateLimitMiB: maxInlineBytes / 1024 / 1024, + oversizedAlternative: "Protected same-domain downloadUrl; use the same connector HTTP Basic credentials.", + recommendedDelivery: "publicUrl is an HMAC-signed same-domain URL that Meta can fetch directly without credentials.", + publicUrl: { configured: publicMediaSigningConfigured(), ttlSeconds: publicMediaTtlSeconds(), authentication: "expiring HMAC signature in query string" }, + queryTasksArguments: [ + { name: "generationId", required: true, format: "uuid" }, + { name: "taskTraceId", required: false, format: "uuid" }, + { name: "include_base64", required: false, allowedValues: [true, false], default: false, description: "Default false: compact outputs include publicUrl and protected downloadUrl. Set true only when inline bytes are explicitly required." }, + ], + }, + generationRetention: { + ttlHours: retentionHours, + ttlDays: retentionHours / 24, + storage: "disk manifests and media indexed by generationId", + behaviorAfterExpiry: "References fail with REFERENCE_GENERATION_EXPIRED while the purge tombstone is retained.", + }, + referenceImages: { + argumentName: "reference_images", + variants: [ + { format: '{generation_id:uuid,index?:integer=0}', recommended: true, description: "Reuses a retained completed image entirely server-side; no base64 enters the client context." }, + { format: '{base64:string,mime_type:"image/png"|"image/jpeg"|"image/webp"}', recommended: false, description: "Backward-compatible inline image input." }, + ], + mixingAllowed: true, + modelLimits: { "gemini-2.5-flash-image": 3, "gemini-3-pro-image": 14, "gemini-3.1-flash-image": 14, "gemini-3.1-flash-lite-image": 14 }, + }, + videoComposition: { + tool: "compose_video_overlay", + backend: "local Pillow + ffmpeg; no Google generation call and no media crosses the client context", + asynchronous: true, + baseRequirements: { kind: "video", status: "COMPLETED", mimeType: "video/mp4", aspectRatio: "9:16", retainedByThisServer: true }, + overlayArguments: [ + { name: "text", required: true, maximumCharacters: 240 }, + { name: "kicker", required: false, maximumCharacters: 40 }, + { name: "style", required: false, allowedValues: ["normal", "cta"], default: "normal" }, + { name: "start_time", required: true, unit: "seconds", minimum: 0 }, + { name: "duration", required: true, unit: "seconds", minimum: 0.5, maximum: 60 }, + ], + overlayCount: { minimum: 1, maximum: 10 }, + output: "A new retained generationId polled through query_tasks; use outputs[].publicUrl directly in SocialMCP publish_post.", + }, + models: { + image: MODEL_CATALOG.filter((model) => model.type === "image"), + video: MODEL_CATALOG.filter((model) => model.type === "video"), + }, + })); + + server.tool("generate_image", "Queue a Gemini image generation job and return immediately.", { + model: z.string().min(1), arguments: argumentsSchema, taskTraceId: taskTraceIdSchema, + }, async ({ model, arguments: inputArguments, taskTraceId }) => { + const spec = resolveModel(model, "image"); + const args = await jobs.resolveImageReferences(normalizeArguments(spec, inputArguments)); + const job = jobs.submit("image", model, args, taskTraceId); + return jsonResult(submitPayload(job)); + }); + + server.tool("generate_video", "Queue a Veo video generation job and return immediately.", { + model: z.string().min(1), arguments: argumentsSchema, taskTraceId: taskTraceIdSchema, + }, async ({ model, arguments: inputArguments, taskTraceId }) => { + const spec = resolveModel(model, "video"); + const args = normalizeArguments(spec, inputArguments); + const job = jobs.submit("video", model, args, taskTraceId); + return jsonResult(submitPayload(job)); + }); + + server.tool("compose_video_overlay", "Queue a local Pillow/ffmpeg composition over a retained completed 9:16 video. Returns a new generationId immediately; poll it with query_tasks and publish outputs[].publicUrl directly.", { + base_generation_id: z.string().uuid().describe("generationId of a retained COMPLETED video/mp4 from this server."), + overlays: z.array(videoOverlaySchema).min(1).max(10), + taskTraceId: taskTraceIdSchema, + }, async ({ base_generation_id, overlays, taskTraceId }) => { + const job = await jobs.submitComposition(base_generation_id, overlays, taskTraceId); + return jsonResult(submitPayload(job)); + }); + + server.tool("query_tasks", "Poll either an image or video generation job. Compact output is the default and includes an expiring publicUrl that can be passed directly to SocialMCP publish_post.", { + generationId: z.string().uuid(), + taskTraceId: taskTraceIdSchema, + include_base64: z.boolean().default(false).describe("Default false. Outputs include publicUrl and omit base64. Set true only for explicit inline delivery."), + }, async ({ generationId, taskTraceId, include_base64 }) => { + let job = jobs.get(generationId); + if (!job) return jsonResult({ generationId, status: "FAILED", error: { code: "JOB_NOT_FOUND", message: "Unknown or expired generationId", retryable: false } }, true); + if (taskTraceId && job.taskTraceId && taskTraceId !== job.taskTraceId) { + return jsonResult({ generationId, status: "FAILED", error: { code: "TRACE_ID_MISMATCH", message: "taskTraceId does not match this generation", retryable: false } }, true); + } + job = await jobs.refresh(job); + const payload: Record = { + generationId: job.generationId, taskTraceId: job.taskTraceId, status: job.status, type: job.kind, model: job.model, + estimatedCostUsd: job.estimatedCostUsd, createdAt: job.createdAt, startedAt: job.startedAt, completedAt: job.completedAt, + }; + if (job.status === "FAILED") payload.error = job.error; + if (job.status === "COMPLETED" && job.outputs) { + const allPresent = (await Promise.all(job.outputs.map(outputExists))).every(Boolean); + if (!allPresent) return jsonResult({ ...payload, status: "FAILED", error: { code: "MEDIA_EXPIRED", message: "Generated media is no longer available", retryable: false } }, true); + payload.outputs = await outputPayload(job.outputs, process.env.PUBLIC_BASE_URL || "https://mcp.zenvairo.es/zenvairogoogle", include_base64); + } + return jsonResult(payload, job.status === "FAILED"); + }); + + server.tool("get_usage", "Return process-local estimated generation usage; Google does not expose remaining billing quota here.", { + taskTraceId: taskTraceIdSchema, + }, async ({ taskTraceId }) => jsonResult({ taskTraceId, ...jobs.usage(), pricingReferenceDate: PRICING_REFERENCE_DATE })); +} + +function submitPayload(job: ReturnType): Record { + return { generationId: job.generationId, status: "QUEUING", model: job.model, estimatedCostUsd: job.estimatedCostUsd, creditsConsumed_o_costEstimado: { amount: job.estimatedCostUsd, currency: "USD", kind: "estimate" } }; +} + +function jsonResult(payload: Record, isError = false): { content: Array<{ type: "text"; text: string }>; isError?: boolean } { + return { content: [{ type: "text", text: JSON.stringify(payload) }], ...(isError ? { isError: true } : {}) }; +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..ba481f8 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,89 @@ +export type JobStatus = "QUEUING" | "RUNNING" | "COMPLETED" | "FAILED"; +export type JobKind = "image" | "video"; + +export interface ToolArgument { + name: string; + value: unknown; +} + +export interface StoredOutput { + index: number; + path: string; + filename: string; + mimeType: string; + sizeBytes: number; + sha256: string; +} + +export interface InlineReferenceImage { + base64: string; + mime_type: "image/png" | "image/jpeg" | "image/webp"; +} + +export interface GenerationReferenceImage { + generation_id: string; + index: number; +} + +export type ReferenceImage = InlineReferenceImage | GenerationReferenceImage; + +export interface VideoOverlay { + text: string; + kicker?: string; + style: "normal" | "cta"; + start_time: number; + duration: number; +} + +export interface JobError { + code: string; + message: string; + providerStatus?: number; + retryable: false; +} + +export interface GenerationJob { + generationId: string; + taskTraceId?: string; + kind: JobKind; + model: string; + canonicalModel: string; + arguments: Record; + estimatedCostUsd: number; + status: JobStatus; + createdAt: string; + startedAt?: string; + completedAt?: string; + updatedAt: string; + operation?: unknown; + outputs?: StoredOutput[]; + error?: JobError; +} + +export interface ArgumentSpec { + name: string; + required: boolean; + description: string; + allowedValues?: Array; + default?: string | number | boolean; + minimum?: number; + maximum?: number; + maximumItems?: number; + format?: string; +} + +export interface ModelSpec { + name: string; + aliases: string[]; + description: string; + type: JobKind; + canonicalApiModel: string; + arguments: ArgumentSpec[]; + pricing: { + currency: "USD"; + referenceDate: string; + basis: string; + rates: Record; + source: string; + }; +} diff --git a/test/integration-compose-real.test.ts b/test/integration-compose-real.test.ts new file mode 100644 index 0000000..7d435c0 --- /dev/null +++ b/test/integration-compose-real.test.ts @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import test from "node:test"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; + +test("real Veo generation -> local overlay composition -> signed public URL", { timeout: 900_000 }, async (t) => { + if (!process.env.GEMINI_API_KEY || !process.env.MCP_SERVER_TOKEN) { + t.skip("Set GEMINI_API_KEY and MCP_SERVER_TOKEN to run the paid real integration test"); + return; + } + const endpoint = new URL(process.env.MCP_TEST_URL || "http://127.0.0.1:8087/mcp"); + const transport = new StreamableHTTPClientTransport(endpoint, { + requestInit: { headers: { Authorization: `Bearer ${process.env.MCP_SERVER_TOKEN}` } }, + }); + const client = new Client({ name: "gemini-veo-compose-integration", version: "1.0.0" }); + const taskTraceId = randomUUID(); + await client.connect(transport); + try { + const submitted = parseText(await client.callTool({ name: "generate_video", arguments: { + model: "veo-3.1-lite", + taskTraceId, + arguments: [ + { name: "prompt", value: "Vertical cinematic brand clip of abstract digital infrastructure, dark navy surfaces with cyan light trails, smooth slow camera motion, subtle electronic ambience, no text, no logos, keep the lower-center area visually uncluttered." }, + { name: "resolution", value: "720p" }, + { name: "aspect_ratio", value: "9:16" }, + { name: "duration_seconds", value: 8 }, + { name: "with_audio", value: true }, + ], + } })); + assert.equal(submitted.status, "QUEUING"); + const base = await poll(client, submitted.generationId, taskTraceId, 40, 15_000); + assert.equal(base.type, "video"); + assert.equal(base.outputs[0].base64, undefined); + + const composedSubmission = parseText(await client.callTool({ name: "compose_video_overlay", arguments: { + base_generation_id: submitted.generationId, + taskTraceId, + overlays: [ + { kicker: "ZENVAIRO", text: "La automatización no debería sentirse genérica", style: "normal", start_time: 0.6, duration: 2.5 }, + { kicker: "ACTÚA AHORA", text: "Convierte procesos en ventaja", style: "cta", start_time: 4.8, duration: 2.5 }, + ], + } })); + assert.equal(composedSubmission.status, "QUEUING"); + const composed = await poll(client, composedSubmission.generationId, taskTraceId, 90, 2_000); + assert.equal(composed.model, "ffmpeg-overlay"); + assert.equal(composed.outputs[0].mimeType, "video/mp4"); + assert.equal(composed.outputs[0].base64, undefined); + assert.match(composed.outputs[0].publicUrl, /^https:\/\/mcp\.zenvairo\.es\/zenvairogoogle\/public-media\//); + + const publicResponse = await fetch(composed.outputs[0].publicUrl); + assert.equal(publicResponse.status, 200); + const video = Buffer.from(await publicResponse.arrayBuffer()); + assert.equal(video.length, composed.outputs[0].sizeBytes); + assert.equal(video.subarray(4, 8).toString("ascii"), "ftyp"); + console.log(JSON.stringify({ + baseGenerationId: submitted.generationId, + composedGenerationId: composedSubmission.generationId, + composedSizeBytes: video.length, + publicUrl: composed.outputs[0].publicUrl, + publicUrlExpiresAt: composed.outputs[0].publicUrlExpiresAt, + })); + } finally { + await client.close(); + } +}); + +async function poll(client: Client, generationId: string, taskTraceId: string, attempts: number, intervalMs: number): Promise { + for (let attempt = 0; attempt < attempts; attempt += 1) { + const result = parseText(await client.callTool({ name: "query_tasks", arguments: { generationId, taskTraceId, include_base64: false } })); + console.log(JSON.stringify({ generationId, attempt, status: result.status })); + if (result.status === "FAILED") assert.fail(`Job failed: ${JSON.stringify(result.error)}`); + if (result.status === "COMPLETED") return result; + await new Promise((resolve) => setTimeout(resolve, intervalMs)); + } + assert.fail(`Job ${generationId} did not complete in time`); +} + +function parseText(result: any): any { + const text = result.content?.find((item: any) => item.type === "text")?.text; + assert.ok(text, "tool result did not contain JSON text"); + return JSON.parse(text); +} diff --git a/test/integration-real.test.ts b/test/integration-real.test.ts new file mode 100644 index 0000000..a80ef6b --- /dev/null +++ b/test/integration-real.test.ts @@ -0,0 +1,46 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; + +test("real MCP generate_image -> query_tasks returns a decodable image", { timeout: 240_000 }, async (t) => { + if (!process.env.GEMINI_API_KEY || !process.env.MCP_SERVER_TOKEN) { + t.skip("Set GEMINI_API_KEY and MCP_SERVER_TOKEN to run the paid real integration test"); + return; + } + const endpoint = new URL(process.env.MCP_TEST_URL || "http://127.0.0.1:8087/mcp"); + const transport = new StreamableHTTPClientTransport(endpoint, { requestInit: { headers: { Authorization: `Bearer ${process.env.MCP_SERVER_TOKEN}` } } }); + const client = new Client({ name: "gemini-veo-real-integration", version: "1.0.0" }); + await client.connect(transport); + try { + const submitted = parseText(await client.callTool({ name: "generate_image", arguments: { + model: "gemini-2.5-flash-image", + arguments: [{ name: "prompt", value: "A minimal flat vector blue circle centered on a white background. No text." }, { name: "resolution", value: "1K" }, { name: "aspect_ratio", value: "1:1" }, { name: "image_count", value: 1 }], + } })); + assert.equal(submitted.status, "QUEUING"); + assert.match(String(submitted.generationId), /^[0-9a-f-]{36}$/); + + let completed: any; + for (let attempt = 0; attempt < 36; attempt += 1) { + const polled = parseText(await client.callTool({ name: "query_tasks", arguments: { generationId: submitted.generationId, include_base64: true } })); + if (polled.status === "FAILED") assert.fail(`Generation failed: ${JSON.stringify(polled.error)}`); + if (polled.status === "COMPLETED") { completed = polled; break; } + await new Promise((resolve) => setTimeout(resolve, 5_000)); + } + assert.ok(completed, "generation did not complete within 180 seconds"); + assert.equal(completed.outputs.length, 1); + assert.ok(completed.outputs[0].base64, "expected inline base64 output"); + const image = Buffer.from(completed.outputs[0].base64, "base64"); + const isPng = image.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])); + const isJpeg = image[0] === 0xff && image[1] === 0xd8 && image[2] === 0xff; + assert.ok(isPng || isJpeg, "decoded base64 is not a valid PNG/JPEG image"); + } finally { + await client.close(); + } +}); + +function parseText(result: any): any { + const text = result.content?.find((item: any) => item.type === "text")?.text; + assert.ok(text, "tool result did not contain JSON text"); + return JSON.parse(text); +} diff --git a/test/unit.test.ts b/test/unit.test.ts new file mode 100644 index 0000000..a2e372f --- /dev/null +++ b/test/unit.test.ts @@ -0,0 +1,165 @@ +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { rm } from "node:fs/promises"; +import test, { after } from "node:test"; +import { normalizeArguments } from "../src/arguments.js"; +import { estimateCost, resolveModel } from "../src/catalog.js"; +import { JobManager } from "../src/jobs.js"; +import { ensureMediaDir, loadPersistedJob, mediaDir, outputPayload, persistCompletedJob, purgeGeneration, storeBase64 } from "../src/media.js"; +import { isTransient } from "../src/retry.js"; +import type { GenerationJob } from "../src/types.js"; + +await ensureMediaDir(); +after(async () => { await rm(mediaDir, { recursive: true, force: true }); }); + +test("resolves public aliases and estimates current Veo pricing", () => { + const model = resolveModel("veo-3.1-fast", "video"); + const args = normalizeArguments(model, [ + { name: "prompt", value: "A short vertical brand film" }, + { name: "resolution", value: "1080p" }, + { name: "duration_seconds", value: 8 }, + ]); + assert.equal(model.canonicalApiModel, "veo-3.1-fast-generate-preview"); + assert.equal(estimateCost(model, args), 0.96); +}); + +test("rejects unsupported Veo combinations and audio=false", () => { + const model = resolveModel("veo-3.1-lite", "video"); + assert.throws(() => normalizeArguments(model, [{ name: "prompt", value: "x" }, { name: "resolution", value: "1080p" }, { name: "duration_seconds", value: 4 }]), /requires duration_seconds=8/); + assert.throws(() => normalizeArguments(model, [{ name: "prompt", value: "x" }, { name: "with_audio", value: false }]), /Invalid 'with_audio'.*Allowed: true/); +}); + +test("only transient provider errors are retryable", () => { + assert.equal(isTransient({ status: 429 }), true); + assert.equal(isTransient({ status: 503 }), true); + assert.equal(isTransient({ status: 400 }), false); +}); + +test("accepts a valid inline reference image and rejects mismatched MIME", () => { + const model = resolveModel("nano-banana-2", "image"); + const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]).toString("base64"); + const args = normalizeArguments(model, [ + { name: "prompt", value: "Continue this visual style" }, + { name: "reference_images", value: [{ base64: png, mime_type: "image/png" }] }, + ]); + assert.equal((args.reference_images as unknown[]).length, 1); + assert.throws(() => normalizeArguments(model, [ + { name: "prompt", value: "Continue this visual style" }, + { name: "reference_images", value: [{ base64: png, mime_type: "image/jpeg" }] }, + ]), /content does not match image\/jpeg/); +}); + +test("resolves a generation_id reference and a mixed reference array", async () => { + const manager = managerWithJobs(); + const source = await completedImageJob(); + injectJob(manager, source); + const inline = tinyPng(); + const resolved = await manager.resolveImageReferences({ reference_images: [ + { generation_id: source.generationId, index: 0 }, + { base64: inline, mime_type: "image/png" }, + ] }); + const references = resolved.reference_images as Array>; + assert.equal(references.length, 2); + assert.equal(references[0].mime_type, "image/png"); + assert.equal(references[0].base64, inline); + assert.equal(references[1].base64, inline); +}); + +test("generation_id reference reports nonexistent generation", async () => { + const manager = managerWithJobs(); + await assert.rejects( + manager.resolveImageReferences({ reference_images: [{ generation_id: randomUUID(), index: 0 }] }), + /REFERENCE_GENERATION_NOT_FOUND/, + ); +}); + +test("generation_id reference reports generation not completed", async () => { + const manager = managerWithJobs(); + const source = jobFixture({ status: "RUNNING" }); + injectJob(manager, source); + await assert.rejects( + manager.resolveImageReferences({ reference_images: [{ generation_id: source.generationId, index: 0 }] }), + /REFERENCE_GENERATION_NOT_COMPLETED.*RUNNING/, + ); +}); + +test("generation_id reference reports output index out of range", async () => { + const manager = managerWithJobs(); + const source = await completedImageJob(); + injectJob(manager, source); + await assert.rejects( + manager.resolveImageReferences({ reference_images: [{ generation_id: source.generationId, index: 7 }] }), + /REFERENCE_INDEX_OUT_OF_RANGE/, + ); +}); + +test("generation_id reference reports expired or purged generation", async () => { + const manager = managerWithJobs(); + const source = await completedImageJob(); + await purgeGeneration(source); + await assert.rejects( + manager.resolveImageReferences({ reference_images: [{ generation_id: source.generationId, index: 0 }] }), + /REFERENCE_GENERATION_EXPIRED/, + ); +}); + +test("generation_id reference rejects a video generation", async () => { + const manager = managerWithJobs(); + const source = jobFixture({ kind: "video", status: "COMPLETED", outputs: [] }); + injectJob(manager, source); + await assert.rejects( + manager.resolveImageReferences({ reference_images: [{ generation_id: source.generationId, index: 0 }] }), + /REFERENCE_IS_VIDEO/, + ); +}); + +test("include_base64=false payload is compact and always has a downloadUrl", async () => { + const source = await completedImageJob(); + const payload = await outputPayload(source.outputs!, "https://mcp.example/media-service", false); + assert.equal(payload[0].base64, undefined); + assert.match(String(payload[0].downloadUrl), /^https:\/\/mcp\.example\/media-service\/media\//); + assert.equal(payload[0].sha256, source.outputs![0].sha256); +}); + +test("completed generation metadata survives a disk round-trip", async () => { + const source = await completedImageJob(); + await persistCompletedJob(source); + const restored = await loadPersistedJob(source.generationId); + assert.equal(restored?.status, "COMPLETED"); + assert.equal(restored?.outputs?.[0].sha256, source.outputs?.[0].sha256); + assert.equal(restored?.outputs?.[0].index, 0); +}); + +function managerWithJobs(): JobManager { + return new JobManager({} as never); +} + +function injectJob(manager: JobManager, job: GenerationJob): void { + (manager as unknown as { jobs: Map }).jobs.set(job.generationId, job); +} + +async function completedImageJob(): Promise { + const generationId = randomUUID(); + const output = await storeBase64(generationId, 0, tinyPng(), "image/png"); + return jobFixture({ generationId, status: "COMPLETED", outputs: [output] }); +} + +function jobFixture(overrides: Partial = {}): GenerationJob { + const now = new Date().toISOString(); + return { + generationId: randomUUID(), + kind: "image", + model: "gemini-2.5-flash-image", + canonicalModel: "gemini-2.5-flash-image", + arguments: {}, + estimatedCostUsd: 0.039, + status: "QUEUING", + createdAt: now, + updatedAt: now, + ...overrides, + }; +} + +function tinyPng(): string { + return Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]).toString("base64"); +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..a8d1fe9 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": "src", + "outDir": "dist", + "strict": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true, + "resolveJsonModule": true, + "declaration": true, + "sourceMap": true + }, + "include": ["src/**/*.ts"] +}