[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AVSY4PJ0P3YQ1TYNH9SHHV":3,"skill-same:01M7AVSY4PJ0P3YQ1TYNH9SHHV":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M7AVSY4PJ0P3YQ1TYNH9SHHV","gemini-vercel-streaming-chatbot",null,"Architect, build, and deploy production AI chatbots with Google Gemini and Vercel Serverless Functions using plain-text chunk streaming, CORS preflight guards, and React stream consumers. Do not use for Python-only stacks, batch JSON APIs, or WebSocket omnichannel bots.","SpectreDeath\u002FBrain-Harness","SpectreDeath","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F207463416?v=4","01M7AVGR1D4X8ADT47APKGVH2Z","JL","01M7AVGR2HSGD23BA5DBTJJTVN",0,"MIT","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgemini-vercel-streaming-chatbot\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: gemini-vercel-streaming-chatbot\ndescription: Architect, build, and deploy production AI chatbots with Google Gemini and Vercel Serverless Functions using plain-text chunk streaming, CORS preflight guards, and React stream consumers. Do not use for Python-only stacks, batch JSON APIs, or WebSocket omnichannel bots.\n---\n\n# Gemini & Vercel Streaming Chatbot: Plain-Text Chunk Streaming Architecture\n\nThe `gemini-vercel-streaming-chatbot` skill provides the definitive engineering methodology for architecting, building, verifying, and deploying production-grade AI chatbots and embeddable widgets using Google Gemini and Vercel Serverless Functions.\n\nSynthesized from Johnson Samuel's literature (*How to Build an AI Chatbot with Gemini and Vercel Serverless Functions 🚀*, freeCodeCamp, 2026), this skill eliminates brittle chatbot implementations—such as multi-second response latency from monolithic JSON blocking, cross-domain CORS preflight failures, unverified backend streaming buffers, and client-side stream consumption bugs—by enforcing **Plain-Text Chunk Streaming**, strict payload sanitization, pre-UI `curl -N` terminal verification, and reactive `ReadableStreamDefaultReader` + `TextDecoder` loops.\n\n```\n[1. API Contract & Sanitization] -> [2. Serverless Streaming & CORS] -> [3. Pre-Flight Terminal Verification] -> [4. Reactive Stream Consumer] -> [5. Deployment & Guardrails]\n```\n\nSee [CARD.md](CARD.md) for the companion summary card, stage matrix, and verification checklist.\nConsult [gradio-app-architect](..\u002Fgradio-app-architect\u002FSKILL.md) for Python-native interfaces, [chatbotx](..\u002Fchatbotx\u002FSKILL.md) for omnichannel messaging networks, and [crafting-skills](..\u002Fcrafting-skills\u002FSKILL.md) for skill authoring craft standards.\n\n---\n\n## 1. API Contract & Payload Sanitization\n\nEstablish a strict boundary contract between client widgets and serverless endpoints. All client-supplied text and contextual objects must be bounded and sanitized before entering model prompt templates.\n\n1. **Formulate Strict API Contract**:\n   - Define exact request signatures for `POST \u002Fapi\u002Fchat`:\n     ```json\n     {\n       \"message\": \"User query or prompt string\",\n       \"resume\": { \"domain_specific\": \"contextual payload object\" }\n     }\n     ```\n   - Prohibit open-ended, untyped payload dumps. Require both active user query text and requisite domain context.\n2. **Enforce Input Length & Cardinality Guardrails**:\n   - Define baseline operational boundaries:\n     ```javascript\n     const MAX_TEXT_LENGTH = 2000;\n     const MAX_ARRAY_LENGTH = 50;\n     ```\n   - Strip leading\u002Ftrailing whitespace, non-printable characters, and excess payload depth.\n   - Truncate arrays exceeding `MAX_ARRAY_LENGTH` to protect model context window limits.\n3. **Assert Immediate Validation Gates**:\n   - Return HTTP 400 Bad Request immediately if input message or domain context is missing, malformed, or exceeds safety thresholds. Never dispatch invalid payloads to the Gemini API.\n\n> **Completion criterion**: API payload contract formulated with explicit length thresholds, input sanitizers, and defensive HTTP 400 validation rejection.\n\n---\n\n## 2. Serverless Streaming Backend & CORS Gate\n\nAuthor the Vercel serverless function (`api\u002Fchat.js` or `api\u002Fchat.ts`) utilizing the `@google\u002Fgenai` SDK and Node.js plain-text chunk streaming.\n\n1. **Instantiate Gemini Client**:\n   - Initialize the Google GenAI SDK client at module scope:\n     ```javascript\n     const { GoogleGenAI } = require(\"@google\u002Fgenai\");\n     const ai = new GoogleGenAI({\n       apiKey: process.env.GOOGLE_API_KEY,\n     });\n     ```\n   - Assert presence of `process.env.GOOGLE_API_KEY`.\n2. **Implement Preflight-Aware CORS Middleware (`allowCors`)**:\n   - Intercept browser `OPTIONS` preflight requests and terminate with HTTP 200:\n     ```javascript\n     const allowCors = fn => async (req, res) => {\n       res.setHeader('Access-Control-Allow-Origin', process.env.ALLOWED_ORIGIN || 'https:\u002F\u002Fyourdomain.com');\n       res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n       res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');\n\n       if (req.method === 'OPTIONS') {\n         return res.status(200).end();\n       }\n       return await fn(req, res);\n     };\n     ```\n3. **Configure HTTP Plain-Text Streaming Response**:\n   - Set streaming response headers prior to chunk emission:\n     ```javascript\n     res.setHeader(\"Content-Type\", \"text\u002Fplain; charset=utf-8\");\n     res.setHeader(\"Cache-Control\", \"no-cache, no-transform\");\n     ```\n4. **Execute Asynchronous Stream Loop**:\n   - Call `ai.models.generateContentStream` with model identifier and structured prompt:\n     ```javascript\n     const stream = await ai.models.generateContentStream({\n       model: \"gemini-2.5-flash\",\n       contents: promptString,\n     });\n\n     for await (const chunk of stream) {\n       if (chunk.text) {\n         res.write(chunk.text);\n       }\n     }\n     res.end();\n     ```\n5. **Provide Diagnostic Healthcheck**:\n   - Expose `GET \u002Fapi\u002Fchat?type=healthcheck` returning `{ \"status\": \"ok\", \"timestamp\": \"...\" }` for uptime probing.\n\n> **Completion criterion**: Serverless function exports CORS-wrapped streaming handler emitting incremental plain-text chunks with dedicated healthcheck probe.\n\n---\n\n## 3. Pre-Flight Terminal Stream Verification\n\nNever author or debug frontend UI components against unverified streaming backends. Verify token chunk arrival directly in the terminal to ensure proxy buffering is disabled.\n\n1. **Execute Unbuffered Terminal Request**:\n   - Use `curl` with the `-N` (`--no-buffer`) flag against the local dev server or deployed staging function:\n     ```bash\n     curl -N -X POST \"http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fchat\" \\\n       -H \"Content-Type: application\u002Fjson\" \\\n       -d '{\"message\":\"Summarize 3 key points\",\"resume\":{\"name\":\"Test Subject\"}}'\n     ```\n2. **Verify Progressive Chunk Emission**:\n   - Assert that text characters appear incrementally in standard output, matching the model's generation cadence.\n   - If output arrives as a single monolithic block after several seconds, inspect intermediate proxies, reverse proxy caches, or missing `res.setHeader(\"Cache-Control\", \"no-cache\")`.\n3. **Validate Preflight Handling**:\n   - Test preflight resolution via terminal:\n     ```bash\n     curl -I -X OPTIONS \"http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fchat\"\n     ```\n   - Assert HTTP 200 OK and expected `Access-Control-Allow-*` response headers.\n\n> **Completion criterion**: Terminal validation confirms unbuffered, progressive token arrival and clean HTTP 200 preflight responses before frontend wiring.\n\n---\n\n## 4. Reactive Stream Consumer & UI State Loop\n\nImplement the frontend stream consumer in React, Solid, or vanilla JavaScript. Decode raw byte streams into UTF-8 text and progressively update UI state to deliver a smooth \"typewriter\" effect.\n\n1. **Dispatch Asynchronous Fetch**:\n   - Send `POST` request with JSON stringified payload:\n     ```javascript\n     const res = await fetch(\"\u002Fapi\u002Fchat\", {\n       method: \"POST\",\n       headers: { \"Content-Type\": \"application\u002Fjson\" },\n       body: JSON.stringify({ message: userText, resume: domainContext }),\n     });\n     if (!res.ok) throw new Error(`HTTP error: ${res.status}`);\n     ```\n2. **Acquire Stream Reader and TextDecoder**:\n   - Obtain a `ReadableStreamDefaultReader` on the response body:\n     ```javascript\n     const reader = res.body.getReader();\n     const decoder = new TextDecoder();\n     ```\n3. **Execute Incremental Accumulation Loop**:\n   - Initialize an empty assistant message in state, then stream incoming chunks:\n     ```javascript\n     let fullText = \"\";\n     setMessages(prev => [...prev, { role: \"assistant\", text: \"\" }]);\n\n     while (true) {\n       const { value, done } = await reader.read();\n       if (done) break;\n\n       const chunk = decoder.decode(value, { stream: true });\n       fullText += chunk;\n\n       setMessages(prev => {\n         const updated = [...prev];\n         updated[updated.length - 1] = { role: \"assistant\", text: fullText };\n         return updated;\n       });\n     }\n     ```\n4. **Defensive Error Handling & Loading Reset**:\n   - Wrap reader loop in `try...catch...finally`.\n   - On network disruption or mid-stream error, render an actionable error message in place without wiping preceding dialogue.\n   - Reset `loading = false` inside `finally` block to re-enable the input box and send button.\n\n> **Completion criterion**: Frontend widget reads streaming byte chunks via `ReadableStreamDefaultReader` and updates UI state progressively with robust error recovery.\n\n---\n\n## 5. Production Hardening, Environment Guardrails & Deployment\n\nHarden the deployment configuration against credential leakage, cross-origin abuse, and unbounded generation costs.\n\n1. **Secure Credential Injection**:\n   - Store `GOOGLE_API_KEY` strictly in Vercel Environment Variables (`Settings -> Environment Variables`).\n   - Never commit `.env` files or expose keys in frontend bundles.\n2. **Origin Hardening**:\n   - Update `Access-Control-Allow-Origin` from development wildcards to the exact production domain where the widget is embedded (e.g. `https:\u002F\u002Fmyapp.com`).\n3. **Automate GitOps Deployment**:\n   - Deploy via Vercel CLI (`vercel --prod`) or configure automatic GitHub main-branch triggers.\n   - Verify production deployment with post-deploy `curl -N` checks against the live Vercel URL.\n4. **Client-Side Cancellation via AbortController**:\n   - Bind an `AbortController` to the fetch request, allowing users to stop streaming midway:\n     ```javascript\n     const controller = new AbortController();\n     \u002F\u002F Pass { signal: controller.signal } into fetch()\n     \u002F\u002F Call controller.abort() when user clicks \"Stop\"\n     ```\n\n> **Completion criterion**: Application deployed to production with locked CORS origin, verified secret injection, and stream cancellation support.\n\n---\n\n## 5-Point Diagnostic Coaching Rubric\n\n| # | Dimension | Diagnostic Question | Passing Standard (Shu Target) | Failing Condition |\n|---|---|---|---|---|\n| **01** | **Stream Chunking** | Does the backend emit chunks incrementally via `res.write()`? | `generateContentStream()` + `res.write(chunk.text)` | Awaiting full response and returning `res.json()` |\n| **02** | **CORS Preflight** | Does the serverless handler handle browser `OPTIONS` preflight requests cleanly? | `if (req.method === 'OPTIONS') return res.status(200).end()` | Unhandled `OPTIONS` resulting in CORS errors or 405 |\n| **03** | **Input Sanitization** | Are client message strings and payload objects length-bounded and validated? | `MAX_TEXT_LENGTH` & `MAX_ARRAY_LENGTH` checks + sanitization | Unsanitized client JSON directly concatenated into prompt templates |\n| **04** | **Client Stream Reader** | Does the frontend use `ReadableStreamDefaultReader` and `TextDecoder`? | `res.body.getReader()` + `TextDecoder` loop updating assistant message | Calling `res.text()` or `res.json()`, discarding streaming |\n| **05** | **Pre-Flight Verification** | Was streaming verified with unbuffered terminal curl before UI wiring? | `curl -N -X POST` with progressive stdout chunk arrival | Wiring UI blindly against untested backend endpoints |\n\n---\n\n## The Visual Brief Specification\n\nWhen architecting or refactoring Gemini and Vercel streaming chatbots or embedded widgets:\n1. **Target Path**: Render an interactive HTML Visual Brief to `%TEMP%\\book-to-skill-forge-\u003Ctimestamp>-gemini-vercel-streaming.html`.\n2. **Visual Assets**: Include Tailwind CSS and Mermaid.js diagrams illustrating the plain-text chunk streaming lifecycle, preflight CORS handling, and client stream consumption.\n3. **Diagnostic Tables**: Embed the 5-point diagnostic scorecard and anti-pattern defense matrix.\n4. **Delivery**: Verify file existence and deliver a clickable link to the user.\n\n---\n\n## Mandatory Checkpoint Gate\n\nBefore scaffolding application files, modifying endpoints, or deploying:\n1. **Present Implementation Plan**: Author a comprehensive implementation plan artifact detailing the API payload schema, streaming backend architecture, terminal verification plan, and deployment targets.\n2. **Set Feedback Header**: Set `RequestFeedback: true` in artifact metadata.\n3. **Human Sign-Off Invariant**: STOP and wait for explicit human review and confirmation before modifying codebase or deploying to production.\n\n---\n\n## 6. Deepened Micro-Kernel IoC Architecture & CLI Seams\n\nFollowing **Rule 49 (Skill-to-IoC Micro-Kernel Seam Elevation Invariant)**, the skill is backed by an authoritative slotted domain engine, typed micro-kernel IoC service seam, domain-partitioned plugin, and headless Click CLI commands:\n\n- **Slotted Domain Engine**: [`gemini_vercel_engine.py`](scripts\u002Fgemini_vercel_engine.py) provides pure Python, zero-dependency static code auditing, 3-tier application scaffolding, stream simulation, and HTML visual brief generation.\n- **Micro-Kernel Service**: `src\u002Fharness\u002Fservices\u002Fgemini_vercel.py` exposes typed `GEMINI_VERCEL_STREAMING_SERVICE_KEY` and `@runtime_checkable` protocol `GeminiVercelStreamingService`.\n- **Domain-Partitioned Plugin**: `plugins\u002Fintegration_and_io\u002Fgemini_vercel_streaming_chatbot\u002F` exports singleton `plugin` with zero-fork configuration.\n- **Headless Click CLI Commands**:\n  - `harness gemini-vercel inspect \u003Ctarget> [--json-output]`\n  - `harness gemini-vercel scaffold [--name \u003Cname>] [--framework \u003Creact|solid|vanilla>] [--language \u003Cjavascript|typescript>] [--write]`\n  - `harness gemini-vercel verify [--prompt \u003Ctext>] [--chunks \u003Cn>] [--json-output]`\n  - `harness gemini-vercel brief [--output \u003Cpath>]`\n\n---\n\n## Anti-Patterns\n\n- **Monolithic Response Blocking** — Awaiting full AI completion and returning single JSON payloads (`res.json()`), causing multi-second blank stalls for users.\n- **Missing CORS Preflight Response** — Failing to intercept and return 200 OK on `OPTIONS` preflight requests, breaking cross-domain embed widgets in browsers.\n- **Wildcard CORS in Production** — Deploying serverless endpoints with `Access-Control-Allow-Origin: *`, allowing unauthorized origins to exhaust Gemini API quotas.\n- **Unsanitized Client Prompt Injection** — Directly interpolating raw, unbounded client JSON or strings into prompt templates without length guards or structure validation.\n- **Monolithic Frontend State Replacement** — Using `fetch().then(res => res.json())` on the frontend, nullifying backend streaming gains and causing UI freezes.\n- **Hardcoded API Secrets** — Baking Google API keys into frontend code or committing them into serverless source code repositories instead of environment variables.\n","# Gemini & Vercel Streaming Chatbot: Plain-Text Chunk Streaming Architecture\n\nThe `gemini-vercel-streaming-chatbot` skill provides the definitive engineering methodology for architecting, building, verifying, and deploying production-grade AI chatbots and embeddable widgets using Google Gemini and Vercel Serverless Functions.\n\nSynthesized from Johnson Samuel's literature (*How to Build an AI Chatbot with Gemini and Vercel Serverless Functions 🚀*, freeCodeCamp, 2026), this skill eliminates brittle chatbot implementations—such as multi-second response latency from monolithic JSON blocking, cross-domain CORS preflight failures, unverified backend streaming buffers, and client-side stream consumption bugs—by enforcing **Plain-Text Chunk Streaming**, strict payload sanitization, pre-UI `curl -N` terminal verification, and reactive `ReadableStreamDefaultReader` + `TextDecoder` loops.\n\n```\n[1. API Contract & Sanitization] -> [2. Serverless Streaming & CORS] -> [3. Pre-Flight Terminal Verification] -> [4. Reactive Stream Consumer] -> [5. Deployment & Guardrails]\n```\n\nSee [CARD.md](CARD.md) for the companion summary card, stage matrix, and verification checklist.\nConsult [gradio-app-architect](..\u002Fgradio-app-architect\u002FSKILL.md) for Python-native interfaces, [chatbotx](..\u002Fchatbotx\u002FSKILL.md) for omnichannel messaging networks, and [crafting-skills](..\u002Fcrafting-skills\u002FSKILL.md) for skill authoring craft standards.\n\n---\n\n## 1. API Contract & Payload Sanitization\n\nEstablish a strict boundary contract between client widgets and serverless endpoints. All client-supplied text and contextual objects must be bounded and sanitized before entering model prompt templates.\n\n1. **Formulate Strict API Contract**:\n   - Define exact request signatures for `POST \u002Fapi\u002Fchat`:\n     ```json\n     {\n       \"message\": \"User query or prompt string\",\n       \"resume\": { \"domain_specific\": \"contextual payload object\" }\n     }\n     ```\n   - Prohibit open-ended, untyped payload dumps. Require both active user query text and requisite domain context.\n2. **Enforce Input Length & Cardinality Guardrails**:\n   - Define baseline operational boundaries:\n     ```javascript\n     const MAX_TEXT_LENGTH = 2000;\n     const MAX_ARRAY_LENGTH = 50;\n     ```\n   - Strip leading\u002Ftrailing whitespace, non-printable characters, and excess payload depth.\n   - Truncate arrays exceeding `MAX_ARRAY_LENGTH` to protect model context window limits.\n3. **Assert Immediate Validation Gates**:\n   - Return HTTP 400 Bad Request immediately if input message or domain context is missing, malformed, or exceeds safety thresholds. Never dispatch invalid payloads to the Gemini API.\n\n> **Completion criterion**: API payload contract formulated with explicit length thresholds, input sanitizers, and defensive HTTP 400 validation rejection.\n\n---\n\n## 2. Serverless Streaming Backend & CORS Gate\n\nAuthor the Vercel serverless function (`api\u002Fchat.js` or `api\u002Fchat.ts`) utilizing the `@google\u002Fgenai` SDK and Node.js plain-text chunk streaming.\n\n1. **Instantiate Gemini Client**:\n   - Initialize the Google GenAI SDK client at module scope:\n     ```javascript\n     const { GoogleGenAI } = require(\"@google\u002Fgenai\");\n     const ai = new GoogleGenAI({\n       apiKey: process.env.GOOGLE_API_KEY,\n     });\n     ```\n   - Assert presence of `process.env.GOOGLE_API_KEY`.\n2. **Implement Preflight-Aware CORS Middleware (`allowCors`)**:\n   - Intercept browser `OPTIONS` preflight requests and terminate with HTTP 200:\n     ```javascript\n     const allowCors = fn => async (req, res) => {\n       res.setHeader('Access-Control-Allow-Origin', process.env.ALLOWED_ORIGIN || 'https:\u002F\u002Fyourdomain.com');\n       res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n       res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');\n\n       if (req.method === 'OPTIONS') {\n         return res.status(200).end();\n       }\n       return await fn(req, res);\n     };\n     ```\n3. **Configure HTTP Plain-Text Streaming Response**:\n   - Set streaming response headers prior to chunk emission:\n     ```javascript\n     res.setHeader(\"Content-Type\", \"text\u002Fplain; charset=utf-8\");\n     res.setHeader(\"Cache-Control\", \"no-cache, no-transform\");\n     ```\n4. **Execute Asynchronous Stream Loop**:\n   - Call `ai.models.generateContentStream` with model identifier and structured prompt:\n     ```javascript\n     const stream = await ai.models.generateContentStream({\n       model: \"gemini-2.5-flash\",\n       contents: promptString,\n     });\n\n     for await (const chunk of stream) {\n       if (chunk.text) {\n         res.write(chunk.text);\n       }\n     }\n     res.end();\n     ```\n5. **Provide Diagnostic Healthcheck**:\n   - Expose `GET \u002Fapi\u002Fchat?type=healthcheck` returning `{ \"status\": \"ok\", \"timestamp\": \"...\" }` for uptime probing.\n\n> **Completion criterion**: Serverless function exports CORS-wrapped streaming handler emitting incremental plain-text chunks with dedicated healthcheck probe.\n\n---\n\n## 3. Pre-Flight Terminal Stream Verification\n\nNever author or debug frontend UI components against unverified streaming backends. Verify token chunk arrival directly in the terminal to ensure proxy buffering is disabled.\n\n1. **Execute Unbuffered Terminal Request**:\n   - Use `curl` with the `-N` (`--no-buffer`) flag against the local dev server or deployed staging function:\n     ```bash\n     curl -N -X POST \"http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fchat\" \\\n       -H \"Content-Type: application\u002Fjson\" \\\n       -d '{\"message\":\"Summarize 3 key points\",\"resume\":{\"name\":\"Test Subject\"}}'\n     ```\n2. **Verify Progressive Chunk Emission**:\n   - Assert that text characters appear incrementally in standard output, matching the model's generation cadence.\n   - If output arrives as a single monolithic block after several seconds, inspect intermediate proxies, reverse proxy caches, or missing `res.setHeader(\"Cache-Control\", \"no-cache\")`.\n3. **Validate Preflight Handling**:\n   - Test preflight resolution via terminal:\n     ```bash\n     curl -I -X OPTIONS \"http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fchat\"\n     ```\n   - Assert HTTP 200 OK and expected `Access-Control-Allow-*` response headers.\n\n> **Completion criterion**: Terminal validation confirms unbuffered, progressive token arrival and clean HTTP 200 preflight responses before frontend wiring.\n\n---\n\n## 4. Reactive Stream Consumer & UI State Loop\n\nImplement the frontend stream consumer in React, Solid, or vanilla JavaScript. Decode raw byte streams into UTF-8 text and progressively update UI state to deliver a smooth \"typewriter\" effect.\n\n1. **Dispatch Asynchronous Fetch**:\n   - Send `POST` request with JSON stringified payload:\n     ```javascript\n     const res = await fetch(\"\u002Fapi\u002Fchat\", {\n       method: \"POST\",\n       headers: { \"Content-Type\": \"application\u002Fjson\" },\n       body: JSON.stringify({ message: userText, resume: domainContext }),\n     });\n     if (!res.ok) throw new Error(`HTTP error: ${res.status}`);\n     ```\n2. **Acquire Stream Reader and TextDecoder**:\n   - Obtain a `ReadableStreamDefaultReader` on the response body:\n     ```javascript\n     const reader = res.body.getReader();\n     const decoder = new TextDecoder();\n     ```\n3. **Execute Incremental Accumulation Loop**:\n   - Initialize an empty assistant message in state, then stream incoming chunks:\n     ```javascript\n     let fullText = \"\";\n     setMessages(prev => [...prev, { role: \"assistant\", text: \"\" }]);\n\n     while (true) {\n       const { value, done } = await reader.read();\n       if (done) break;\n\n       const chunk = decoder.decode(value, { stream: true });\n       fullText += chunk;\n\n       setMessages(prev => {\n         const updated = [...prev];\n         updated[updated.length - 1] = { role: \"assistant\", text: fullText };\n         return updated;\n       });\n     }\n     ```\n4. **Defensive Error Handling & Loading Reset**:\n   - Wrap reader loop in `try...catch...finally`.\n   - On network disruption or mid-stream error, render an actionable error message in place without wiping preceding dialogue.\n   - Reset `loading = false` inside `finally` block to re-enable the input box and send button.\n\n> **Completion criterion**: Frontend widget reads streaming byte chunks via `ReadableStreamDefaultReader` and updates UI state progressively with robust error recovery.\n\n---\n\n## 5. Production Hardening, Environment Guardrails & Deployment\n\nHarden the deployment configuration against credential leakage, cross-origin abuse, and unbounded generation costs.\n\n1. **Secure Credential Injection**:\n   - Store `GOOGLE_API_KEY` strictly in Vercel Environment Variables (`Settings -> Environment Variables`).\n   - Never commit `.env` files or expose keys in frontend bundles.\n2. **Origin Hardening**:\n   - Update `Access-Control-Allow-Origin` from development wildcards to the exact production domain where the widget is embedded (e.g. `https:\u002F\u002Fmyapp.com`).\n3. **Automate GitOps Deployment**:\n   - Deploy via Vercel CLI (`vercel --prod`) or configure automatic GitHub main-branch triggers.\n   - Verify production deployment with post-deploy `curl -N` checks against the live Vercel URL.\n4. **Client-Side Cancellation via AbortController**:\n   - Bind an `AbortController` to the fetch request, allowing users to stop streaming midway:\n     ```javascript\n     const controller = new AbortController();\n     \u002F\u002F Pass { signal: controller.signal } into fetch()\n     \u002F\u002F Call controller.abort() when user clicks \"Stop\"\n     ```\n\n> **Completion criterion**: Application deployed to production with locked CORS origin, verified secret injection, and stream cancellation support.\n\n---\n\n## 5-Point Diagnostic Coaching Rubric\n\n| # | Dimension | Diagnostic Question | Passing Standard (Shu Target) | Failing Condition |\n|---|---|---|---|---|\n| **01** | **Stream Chunking** | Does the backend emit chunks incrementally via `res.write()`? | `generateContentStream()` + `res.write(chunk.text)` | Awaiting full response and returning `res.json()` |\n| **02** | **CORS Preflight** | Does the serverless handler handle browser `OPTIONS` preflight requests cleanly? | `if (req.method === 'OPTIONS') return res.status(200).end()` | Unhandled `OPTIONS` resulting in CORS errors or 405 |\n| **03** | **Input Sanitization** | Are client message strings and payload objects length-bounded and validated? | `MAX_TEXT_LENGTH` & `MAX_ARRAY_LENGTH` checks + sanitization | Unsanitized client JSON directly concatenated into prompt templates |\n| **04** | **Client Stream Reader** | Does the frontend use `ReadableStreamDefaultReader` and `TextDecoder`? | `res.body.getReader()` + `TextDecoder` loop updating assistant message | Calling `res.text()` or `res.json()`, discarding streaming |\n| **05** | **Pre-Flight Verification** | Was streaming verified with unbuffered terminal curl before UI wiring? | `curl -N -X POST` with progressive stdout chunk arrival | Wiring UI blindly against untested backend endpoints |\n\n---\n\n## The Visual Brief Specification\n\nWhen architecting or refactoring Gemini and Vercel streaming chatbots or embedded widgets:\n1. **Target Path**: Render an interactive HTML Visual Brief to `%TEMP%\\book-to-skill-forge-\u003Ctimestamp>-gemini-vercel-streaming.html`.\n2. **Visual Assets**: Include Tailwind CSS and Mermaid.js diagrams illustrating the plain-text chunk streaming lifecycle, preflight CORS handling, and client stream consumption.\n3. **Diagnostic Tables**: Embed the 5-point diagnostic scorecard and anti-pattern defense matrix.\n4. **Delivery**: Verify file existence and deliver a clickable link to the user.\n\n---\n\n## Mandatory Checkpoint Gate\n\nBefore scaffolding application files, modifying endpoints, or deploying:\n1. **Present Implementation Plan**: Author a comprehensive implementation plan artifact detailing the API payload schema, streaming backend architecture, terminal verification plan, and deployment targets.\n2. **Set Feedback Header**: Set `RequestFeedback: true` in artifact metadata.\n3. **Human Sign-Off Invariant**: STOP and wait for explicit human review and confirmation before modifying codebase or deploying to production.\n\n---\n\n## 6. Deepened Micro-Kernel IoC Architecture & CLI Seams\n\nFollowing **Rule 49 (Skill-to-IoC Micro-Kernel Seam Elevation Invariant)**, the skill is backed by an authoritative slotted domain engine, typed micro-kernel IoC service seam, domain-partitioned plugin, and headless Click CLI commands:\n\n- **Slotted Domain Engine**: [`gemini_vercel_engine.py`](scripts\u002Fgemini_vercel_engine.py) provides pure Python, zero-dependency static code auditing, 3-tier application scaffolding, stream simulation, and HTML visual brief generation.\n- **Micro-Kernel Service**: `src\u002Fharness\u002Fservices\u002Fgemini_vercel.py` exposes typed `GEMINI_VERCEL_STREAMING_SERVICE_KEY` and `@runtime_checkable` protocol `GeminiVercelStreamingService`.\n- **Domain-Partitioned Plugin**: `plugins\u002Fintegration_and_io\u002Fgemini_vercel_streaming_chatbot\u002F` exports singleton `plugin` with zero-fork configuration.\n- **Headless Click CLI Commands**:\n  - `harness gemini-vercel inspect \u003Ctarget> [--json-output]`\n  - `harness gemini-vercel scaffold [--name \u003Cname>] [--framework \u003Creact|solid|vanilla>] [--language \u003Cjavascript|typescript>] [--write]`\n  - `harness gemini-vercel verify [--prompt \u003Ctext>] [--chunks \u003Cn>] [--json-output]`\n  - `harness gemini-vercel brief [--output \u003Cpath>]`\n\n---\n\n## Anti-Patterns\n\n- **Monolithic Response Blocking** — Awaiting full AI completion and returning single JSON payloads (`res.json()`), causing multi-second blank stalls for users.\n- **Missing CORS Preflight Response** — Failing to intercept and return 200 OK on `OPTIONS` preflight requests, breaking cross-domain embed widgets in browsers.\n- **Wildcard CORS in Production** — Deploying serverless endpoints with `Access-Control-Allow-Origin: *`, allowing unauthorized origins to exhaust Gemini API quotas.\n- **Unsanitized Client Prompt Injection** — Directly interpolating raw, unbounded client JSON or strings into prompt templates without length guards or structure validation.\n- **Monolithic Frontend State Replacement** — Using `fetch().then(res => res.json())` on the frontend, nullifying backend streaming gains and causing UI freezes.\n- **Hardcoded API Secrets** — Baking Google API keys into frontend code or committing them into serverless source code repositories instead of environment variables.\n",{"name":5,"description":7},"main","eff3b00e36d1d233ad4a4389605c82fbfa0326d3",".agents\u002Fskills\u002Fgemini-vercel-streaming-chatbot","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness","https:\u002F\u002Fgithub.com\u002FSpectreDeath","I'm here to manage stress so I wouldn't expect earth shattering break throughs I'm just an enthusiast that likes making stuff. ","2026-11-15 05:32:58",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add SpectreDeath\u002FBrain-Harness --skill gemini-vercel-streaming-chatbot",{"tool":37,"command":38},"bunx","bunx skills add SpectreDeath\u002FBrain-Harness --skill gemini-vercel-streaming-chatbot",{"tool":40,"command":41},"pnpm","pnpm dlx skills add SpectreDeath\u002FBrain-Harness --skill gemini-vercel-streaming-chatbot","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgemini-vercel-streaming-chatbot\u002FSKILL.md",true,[45,51,55],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"CARD.md","REFERENCE","参考文档",3581,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgemini-vercel-streaming-chatbot\u002FCARD.md",{"path":52,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":53,"sourceHtmlUrl":54},"config.default.yaml",497,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgemini-vercel-streaming-chatbot\u002Fconfig.default.yaml",{"path":56,"resourceType":57,"resourceTypeDesc":58,"sizeBytes":59,"sourceHtmlUrl":60},"scripts\u002Fgemini_vercel_engine.py","SCRIPT","脚本",38057,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgemini-vercel-streaming-chatbot\u002Fscripts\u002Fgemini_vercel_engine.py",[62,69,76,83,90,97],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7E0W6FR68J2N9CXCZTAQJFX","ui-behavior-primitive-architect","Architect, audit, and verify zero-dependency headless UI behavior primitives, WebMCP agent bridges, WAI-ARIA\u002FSSR\u002FRTL tri-modal checks, and framework expert routing. Do not use for static CSS theme styling or backend database migrations.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fui-behavior-primitive-architect\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7E0VZ7JQNW34G271DENFGYP","trustgraph-ontology-governor","Govern knowledge graphs, SHACL-AF triple policies, OntologyRAG subclass validation, PROV-O dual named graphs, and Laya entropy decision scoring. Do not use for relational SQL queries or generic web scraping.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftrustgraph-ontology-governor\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7E0VQ6Z7R45Q8QAZ4MT39EK","shim-harness-governor","Govern universal CLI agent loops, 4-tier tool permissions, ancestor-symlink workspace sandboxes, deterministic-first command routing, collision-safe MCP namespacing, and layered skill loading. Do not use for static UI styling or external SQL analytics.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fshim-harness-governor\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7E0VC18NMP1QBSRJ3TPQ7MB","graphiti-zep-memory-governor","Govern bi-temporal knowledge graphs with Graphiti future-edge clamping, MinHash\u002FLSH entity dedup, RRF\u002FMMR reranking, and Zep typed ontologies. Do not use for static SQL joins or generic web crawling.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgraphiti-zep-memory-governor\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M7E0V12ABE1RW3ZRCST8VH5Z","agora-mcp-workbench-architect","Architect, audit, and orchestrate Agora Workbench MCP servers, loopback sidecars, unified state graphs, gateway\u002Fdispatcher connectors, and policy-enforced data lakes. Do not use for static frontend CSS styling or non-MCP desktop GUI automation.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fagora-mcp-workbench-architect\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M7BFYG6QT3484VC57TZ19V7P","skill-eval-assurance-runner","Evaluate and assure agent skills using small-N Wilson confidence intervals, unbiased pass^k reliability, deterministic trajectory graders, preflight boundary honesty, and sealed digest verification. Do not use for subjective prose review or unconstrained production deployment.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fskill-eval-assurance-runner\u002FSKILL.md",[],[]]