kiku-agent 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +459 -407
  2. package/package.json +27 -3
  3. package/server/agent/agentCore.js +635 -267
  4. package/server/agent/appPaths.js +2 -0
  5. package/server/agent/catalogEntityResolver.js +629 -0
  6. package/server/agent/citations.js +0 -21
  7. package/server/agent/clarificationAnalytics.js +1 -1
  8. package/server/agent/clarifyingQuestions.js +286 -216
  9. package/server/agent/cli.js +528 -73
  10. package/server/agent/commandFeatures.js +123 -24
  11. package/server/agent/commandRegistry.js +128 -62
  12. package/server/agent/commands.js +1410 -95
  13. package/server/agent/config.js +253 -163
  14. package/server/agent/contextCompactor.js +239 -25
  15. package/server/agent/dynamicCatalog.js +192 -0
  16. package/server/agent/envBootstrap.js +46 -0
  17. package/server/agent/envManager.js +317 -0
  18. package/server/agent/eventBus.js +3 -3
  19. package/server/agent/feedbackLearning.js +0 -8
  20. package/server/agent/gpuMetrics.js +188 -55
  21. package/server/agent/ingestionWorker.js +339 -0
  22. package/server/agent/lanDiscovery.js +369 -0
  23. package/server/agent/llmClient.js +111 -39
  24. package/server/agent/lmStudioWakeup.js +144 -0
  25. package/server/agent/mcpClient.js +2 -2
  26. package/server/agent/memory.js +635 -494
  27. package/server/agent/modelConfig.js +487 -0
  28. package/server/agent/newsIntelligence.js +219 -0
  29. package/server/agent/newsWatch.js +85 -0
  30. package/server/agent/prompts.js +146 -0
  31. package/server/agent/publicTools.js +7 -0
  32. package/server/agent/queryDetails.js +62 -1
  33. package/server/agent/research.js +314 -35
  34. package/server/agent/routingInterceptor.js +77 -0
  35. package/server/agent/rumoredProjects.js +15 -0
  36. package/server/agent/sanitizer.js +117 -17
  37. package/server/agent/subagent.js +52 -9
  38. package/server/agent/suggestionTui.js +33 -13
  39. package/server/agent/suggestions.js +29 -13
  40. package/server/agent/telemetry.js +0 -11
  41. package/server/agent/terminalImage.js +0 -1
  42. package/server/agent/textToolProtocol.js +190 -0
  43. package/server/agent/tokenTracker.js +220 -0
  44. package/server/agent/toolRouter.js +362 -216
  45. package/server/agent/tools.js +1155 -194
  46. package/server/agent/ui.js +144 -41
  47. package/server/agent/vramService.js +572 -0
  48. package/server/agent/webSearch.js +2279 -273
  49. package/server/agent/youtubeAuth.js +82 -73
  50. package/server/agent/youtubeTranscript.js +209 -0
  51. package/server/apiRouter.js +383 -179
  52. package/server/mcp/data/brands.js +5 -5
  53. package/server/mcp/data/discography.js +56 -45
  54. package/server/mcp/data/gallery.js +9 -0
  55. package/server/mcp/data/index.js +1 -0
  56. package/server/mcp/data/industryIndex.js +251 -0
  57. package/server/mcp/data/profile.js +5 -5
  58. package/server/mcp/data/timeline.js +2 -2
  59. package/server/mcp/data/works.js +2 -2
  60. package/server/mcp/handler.js +0 -2
  61. package/server/mcp/prompts.js +42 -2
  62. package/server/mcp/resources.js +5 -1
  63. package/server/mcp/security.js +25 -14
  64. package/server/mcp/server.js +92 -3
  65. package/server/mcp/tools.js +20 -11
  66. package/server/web-chat/core/connection.js +218 -194
  67. package/server/web-chat/core/conversationContext.js +1 -1
  68. package/server/web-chat/core/directCatalogEngine.js +190 -184
  69. package/server/web-chat/core/followUpEngine.js +88 -11
  70. package/server/web-chat/core/security.js +7 -4
  71. package/server/web-chat/router.js +54 -17
  72. package/server/web-chat/routes/bilibiliRoute.js +34 -0
  73. package/server/web-chat/routes/chatRoute.js +488 -397
  74. package/server/web-chat/routes/clarifyConfigRoute.js +1 -2
  75. package/server/web-chat/routes/exportRoute.js +2 -1
  76. package/server/web-chat/routes/lanDiscoveryRoute.js +90 -0
  77. package/server/web-chat/routes/newsRoute.js +36 -6
  78. package/server/web-chat/routes/providerRoute.js +87 -0
  79. package/server/web-chat/routes/staticRoute.js +61 -13
  80. package/server/web-chat/routes/statusRoute.js +23 -2
  81. package/server/web-chat/routes/vramRoute.js +22 -0
  82. package/server/web-chat/server.js +135 -106
  83. package/server/web-chat/ui/htmlBuilder.js +8 -8
  84. package/server/web-chat/ui/previews/modelSettings.preview.html +41 -0
  85. package/server/web-chat/ui/scripts/agentBubbleSystem.js +0 -5
  86. package/server/web-chat/ui/scripts/client.js +10526 -8397
  87. package/server/web-chat/ui/scripts/webchatI18n.js +190 -138
  88. package/server/web-chat/ui/styles/main.css +7471 -4246
  89. package/server/web-chat/ui/templates/body.html +305 -179
  90. package/src/data/brandsData.js +29 -6
  91. package/src/data/discographyData.js +918 -900
  92. package/src/data/galleryData.js +66 -0
  93. package/src/data/industryIndexData.js +292 -0
  94. package/src/data/musicVideoData.js +48 -5
  95. package/src/data/profileData.js +15 -1
  96. package/src/data/timelineData.js +4 -3
  97. package/src/data/worksData.js +536 -535
  98. package/src/lib/vram/estimator.js +464 -0
  99. package/src/lib/vram/modelRegistry.js +387 -0
  100. package/tokens.css +33 -2
package/README.md CHANGED
@@ -1,407 +1,459 @@
1
- <div align="center">
2
-
3
- <img src="./public/images/jujingyi_portrait.jpg" width="96" height="96" style="border-radius: 50%; object-fit: cover;" alt="Ju Jingyi Icon" />
4
-
5
- # Ju Jingyi (鞠婧祎) Portal & Kiku AI Agent
6
-
7
- *Full-stack fan archive, REST API Suite v1.0, and autonomous AI Agent CLI + MCP Server*
8
-
9
- [![npm version](https://img.shields.io/npm/v/kiku-agent?style=flat-square&color=cb3837)](https://www.npmjs.com/package/kiku-agent)
10
- [![Node.js version](https://img.shields.io/badge/Node.js-%3E%3D20-3c873a?style=flat-square)](https://nodejs.org)
11
- [![ESM only](https://img.shields.io/badge/ESM-only-4a90d9?style=flat-square)](https://nodejs.org/api/esm.html)
12
- [![MCP Protocol](https://img.shields.io/badge/MCP-Protocol-8a2be2?style=flat-square)](https://modelcontextprotocol.io)
13
- [![License](https://img.shields.io/badge/License-GPL--3.0-blue?style=flat-square)](LICENSE)
14
-
15
- ⭐ If you find this project helpful, star it on GitHub!
16
-
17
- [Overview](#overview) • [Quick Start](#quick-start) • [Features](#features) • [CLI Commands](#interactive-chat-slash-commands) • [Agent Tools](#available-agent-tools-45) • [Cloud & Local Models](#multi-provider-cloud--local-models) • [MCP Integration](#model-context-protocol-mcp) • [Web App & REST API](#web-app--rest-api) • [Troubleshooting](#troubleshooting)
18
-
19
- </div>
20
-
21
- ---
22
-
23
- ## Overview
24
-
25
- This repository ships a complete full-stack ecosystem for Chinese singer and actress **Ju Jingyi (鞠婧祎)**, packaged and distributed under the single [`kiku-agent`](https://www.npmjs.com/package/kiku-agent) npm package:
26
-
27
- | Deliverable | Location | Description |
28
- |---|---|---|
29
- | **Fan Portal (SPA)** | `src/` | Vite + React 19 + Tailwind 4 interactive showcase featuring discography, filmography, 4K visual gallery, trivia quiz, and timeline. |
30
- | **REST API v1** | `server/apiRouter.js` | Framework-free Node `http` REST API suite serving 16 endpoints, OpenAPI 3.0 specs, and live interactive `/api-docs`. |
31
- | **AI Agent CLI & MCP Server** | `server/agent/`, `server/mcp/` | Autonomous ReAct agent CLI (`kiku-agent`) and Model Context Protocol server (`kiku-mcp`) connecting to local LM Studio or cloud LLMs. |
32
-
33
- > [!TIP]
34
- > **100% Free Local Inference**: Kiku Agent runs completely offline with zero API token cost when connected to [LM Studio](https://lmstudio.ai/) running `google/gemma-4-e4b`. If no LLM is running, Kiku automatically starts in **catalog-only mode** instead of crashing.
35
-
36
- ---
37
-
38
- ## Quick Start
39
-
40
- ### Global Installation
41
-
42
- Install the Kiku Agent CLI and MCP server globally via npm:
43
-
44
- ```bash
45
- npm install -g kiku-agent
46
- kiku-agent
47
- ```
48
-
49
- > [!NOTE]
50
- > The global package deliberately excludes native binary build dependencies (Python, `node-gyp`, Visual Studio C++ build tools are not required). For a local checkout before publishing, pack and install via `npm install -g ./kiku-agent-1.2.0.tgz`.
51
-
52
- ### Zero-Install One-Shot Query
53
-
54
- Ask questions directly from your terminal using `npx`:
55
-
56
- ```bash
57
- npx kiku-agent --query "ผลงานซีรีส์ปี 2026 มีเรื่องอะไรบ้างและรับบทเป็นใคร"
58
- ```
59
-
60
- ### Local LM Studio Setup
61
-
62
- 1. Open **LM Studio** on your machine.
63
- 2. Download or load **`google/gemma-4-e4b`** (quantization: `Q4_K_M`, `Q6_K`, or `Q8_0`).
64
- 3. Click the **Developer / Local Server** tab (`<->`) on the left sidebar.
65
- 4. Select your loaded Gemma model and click **Start Server** on port `1234` (`http://localhost:1234`).
66
- 5. Launch Kiku Agent:
67
- ```bash
68
- kiku-agent
69
- ```
70
-
71
- ### Launch with Cloud Providers
72
-
73
- ```bash
74
- # OpenAI (GPT-5.6 / GPT-4o)
75
- npm run kiku-agent -- --provider openai --model gpt-5.6-luna
76
-
77
- # Google Gemini (Gemini 3.7 Flash)
78
- npm run kiku-agent -- --provider gemini --model gemini-3.7-flash
79
-
80
- # Groq (Ultra-fast LPU inference)
81
- npm run kiku-agent -- --provider groq --model openai/gpt-oss-120b
82
-
83
- # DeepSeek (DeepSeek V4)
84
- npm run kiku-agent -- --provider deepseek --model deepseek-v4-flash
85
-
86
- # OpenRouter (Dynamic routing)
87
- npm run kiku-agent -- --provider openrouter --model openrouter/auto
88
- ```
89
-
90
- ---
91
-
92
- ## Features
93
-
94
- - **Autonomous ReAct Agent**: Equipped with **45 validated tools** covering catalog knowledge, live web search, YouTube audio playback, filesystem inspection, and research workers.
95
- - **Dynamic Multiline TUI & Instant Paste**: Terminal input area auto-expands up to 6 rows with continuation prefixes, `Shift+Enter` multiline editing, `Ctrl+V` clipboard paste, and bracketed paste batch rendering (pasting 5,000+ characters completes in <30ms without UI freezing).
96
- - **Multi-Agent Adversarial Debate**: The `/debate` command orchestrates dialectic affirmative vs. negative agent workers to challenge factual claims against catalog records and synthesize evidence-backed truth matrices.
97
- - **Smart Memory 2.0**: Long-term conversational memory (`/mem`) featuring TF-IDF keyword indexing, recency decay scoring, topic categorization, and JSON export/import.
98
- - **Multi-Provider Engine**: Seamless switching between local LM Studio and 6 top cloud providers (OpenAI, Gemini, Groq, DeepSeek, OpenRouter, and custom OpenAI-compatible endpoints) with runtime health and latency diagnostics.
99
- - **Local Audio Player**: YouTube streaming via `yt-dlp` and `ffmpeg` with play, pause, skip, track queueing, and mute/unmute controls.
100
- - **Model Context Protocol (MCP)**: Official stdio (`kiku-mcp`) and Streamable HTTP endpoints exposing **43 tools**, **7 resources**, and **7 prompt templates** for Claude Desktop, Cursor, and VS Code.
101
- - **Standalone Web Chat Portal**: Interactive browser chatbot (`/chat` or `/web` on port 3300) with character network visualization, mini Jukebox player, and direct catalog fallback.
102
- - **Developer VIP Keys**: Integrated 15-question trivia quiz (`/quiz`) allowing users to test fan knowledge and earn Developer VIP API keys with elevated rate limits.
103
- - **Rich Transcript Export**: `/save` and `/session export` output single-file self-contained HTML (with embedded CSS & dark mode), Markdown, JSON, or plain text.
104
-
105
- ---
106
-
107
- ## CLI Usage
108
-
109
- ### Command-Line Flags
110
-
111
- | Flag | Description |
112
- |---|---|
113
- | `-h`, `--help` | Display usage instructions and options |
114
- | `-V`, `--version` | Print installed package version |
115
- | `-P`, `--provider <name>` | Select provider (`lmstudio`, `openai`, `gemini`, `groq`, `deepseek`, `openrouter`, `custom`) |
116
- | `-k`, `--api-key <key>` | Cloud provider API key override |
117
- | `-m`, `--model <id>` | Model ID override (e.g. `gpt-5.6-luna`, `gemini-3.7-flash`, `google/gemma-4-e4b`) |
118
- | `-u`, `--url <url>` | Provider base URL override |
119
- | `-t`, `--tools` | List all 45 registered tools |
120
- | `-s`, `--stats` | Print catalog overview statistics |
121
- | `-v`, `--verbose` | Verbose mode with reasoning output |
122
- | `--thinking [show\|hide]` | Toggle visibility of reasoning process |
123
- | `-q`, `--query "<text>"` | One-shot query mode |
124
-
125
- ---
126
-
127
- ## Interactive Chat Slash Commands
128
-
129
- Type `/help` inside any active session for the interactive command palette. Commands are organized by functional domain:
130
-
131
- ### 🤖 Provider & Model
132
- - `/provider [list|use|models|info|test|setkey]` — Inspect, switch, and test AI providers, or set API keys at runtime
133
- - `/model [list|recommend|use|reconnect]` — Switch models on the fly without restarting, or reconnect after starting LM Studio
134
-
135
- ### 🧠 Memory & Conversation Sessions
136
- - `/mem [add|search|list|topics|summary|del|import|export|clear]` — Long-term conversational memory with TF-IDF keyword scoring & recency decay
137
- - `/session [info|summary|list|load|export|clear]` — Manage, restore, or summarize conversation sessions
138
- - `/history [n|search|summary|clear]` — Review and search past conversation turns
139
- - `/save [markdown|html|json|text]` — Export session transcript (single-file HTML with dark mode, Markdown, JSON, plain text)
140
- - `/copy [session|[Qn] [answer|thinking|tools|tool n|all|json]]` — Copy transcript, answers, or diagnostic info to clipboard
141
- - `/clear` — Reset active conversation history
142
-
143
- ### 🔍 Catalog & Discovery
144
- - `/find <query> [--type <type>] [--year YYYY]` — Search works, songs, roles, brands, awards, and stages (AI-enhanced)
145
- - `/compare <item-a> -- <item-b>` — Side-by-side comparison of catalog items or career years (AI-enhanced)
146
- - `/favorites [list|add|remove|export|suggest]` — Personal collection builder with AI recommendations
147
- - `/discover [drama|song|stage|photo]` — Recommendations by type, year, and mood (AI-enhanced)
148
- - `/news [topic] [--days N] [--official-only]` — Dated coverage and recent source-backed updates (AI-enhanced)
149
- - `/stats` — Print summary counts of dramas, songs, brands, and awards (AI-enhanced)
150
- - `/gallery` — Render Ju Jingyi images directly in the terminal
151
-
152
- ### 🔬 Research, Debate & Subagents (Advanced)
153
- - `/debate <claim|status|last>` — Multi-agent adversarial debate with affirmative/negative roles and truth matrix synthesis
154
- - `/timeline [year|era]` — Render career milestone ASCII timeline graphic in terminal
155
- - `/subagent <task>` — Dispatch a bounded research subagent with catalog & web access
156
- - `/research <question>` — Coordinate parallel catalog, web, and verification workers
157
- - `/verify <claim>` — Classify a claim as verified, unverified, conflicting, or false
158
- - `/suggestion [list|run|auto|refresh|topic]` — Auto-generate exploration prompts and execute them with subagents
159
- - `/sources` — Show source URLs captured by the latest research run
160
- - `/jobs [list|show|cancel|clear]` — Inspect and control background research jobs
161
- - `/skill [learn|list|del|on|off|clear]` — Teach persistent response persona preferences across sessions
162
-
163
- ### 🎵 Music Player (Local Audio)
164
- - `/play <song>` / `/stop` / `/pause` / `/resume` — YouTube audio streaming via yt-dlp & FFmpeg
165
- - `/next` / `/prev` / `/queue` / `/add` / `/remove` / `/clearqueue` — Queue and track management
166
- - `/mute` / `/unmute` / `/current` — Volume and playback status
167
-
168
- ### 🛠️ System, UI & Diagnostics
169
- - `/doctor` — Diagnostic check for Node, app data, LM Studio, models, FFmpeg, speaker, and yt-dlp
170
- - `/details [Qn]` — Diagnostic overview of answers, reasoning process, and bounded tool calls (F2)
171
- - `/tools` — View all 45 registered tools with parameter descriptions
172
- - `/lang [th|zh|en|auto]` — Set response language (Thai, Chinese, English)
173
- - `/theme [name|list|current|next|prev|reset]` — Switch terminal color theme
174
- - `/thinking [show|hide|toggle]` — Toggle reasoning process visibility
175
- - `/system` / `/gpu` / `/ping` / `/config` — System info, NVIDIA GPU/VRAM monitor, server latency, and runtime config
176
- - `/quiz [lang]` — 15-question fan trivia quiz to claim a Developer VIP API key
177
- - `/key [show|apply <key>|clear]` — Manage Developer VIP API Key
178
- - `/web [start|open|stop|status|restart] [port]` — Launch or open standalone Web Chat interface (port 3300)
179
- - `/cancel` / `/retry` / `/exit` — Abort query, retry, or exit the agent
180
-
181
- > [!NOTE]
182
- > `/find`, `/compare`, `/favorites suggest`, `/news`, `/discover`, and `/stats` are **catalog-native + AI-enhanced**: they run in catalog-only mode without an LLM, and layer an AI summary on top whenever a model is active.
183
-
184
- ### Example CLI Workflows
185
-
186
- ```text
187
- /find "In Blossom" --type work
188
- /compare "In Blossom" -- "Beauty of Resilience"
189
- /favorites add song "Rain Love"
190
- /debate "Ju Jingyi debuted with SNH48 in 2013"
191
- /timeline 2024
192
- /research "Ju Jingyi 2026 upcoming dramas"
193
- /skill learn "ตอบภาษาไทยแบบสั้น กระชับ"
194
- /quiz lang th
195
- ```
196
-
197
- ---
198
-
199
- ## Available Agent Tools (45)
200
-
201
- Kiku Agent includes **45 validated tools** across 5 categories that the agent autonomously invokes during conversations:
202
-
203
- - **Catalog (14)**: Profile, fandom facts, quotes, filmography (2013–2026), character roles, discography, music videos, brands, career timeline, awards, Weibo/Douyin feeds, 4K gallery, and global fuzzy search.
204
- - **Web & Network (6)**: Live DuckDuckGo search, article extraction, raw webpage fetch, JSON parser, page screenshots, and REST API querying.
205
- - **Music Player (15)**: YouTube streaming via `yt-dlp` & `ffmpeg`, playlist queue management, track playback controls, and volume mute/unmute.
206
- - **Filesystem & System (3)**: Directory listing, safe local file reader, and archive statistics.
207
- - **Research, Skills & VIP (7)**: Autonomous research subagents, deep research coordinator, claim verification, topic suggestion, persistent skill learning, trivia quiz challenge, and Developer VIP key management.
208
-
209
- > [!TIP]
210
- > Run `/tools` inside the CLI or visit [`/api-docs`](https://jujingyi-kikuuu.vercel.app/api-docs) to inspect parameter schemas and test all tools interactively.
211
-
212
- ---
213
-
214
- ## Multi-Provider Cloud & Local Models
215
-
216
- `kiku-agent` natively supports local LM Studio inference alongside top Cloud AI Providers with official endpoints, active cost-effective models, and tool-calling capabilities:
217
-
218
- | Provider | Recommended Active Models | Pricing / Cost Tier | Doc & API Reference | Required ENV Variable |
219
- |---|---|---|---|---|
220
- | **LM Studio** (Local) | `google/gemma-4-e4b` *(Q4_K_M, Q6_K, Q8_0)* | **100% Free / Local** (Zero token cost) | [Docs](https://lmstudio.ai/docs) • [API Ref](https://lmstudio.ai/docs/api/local-server) | `LMSTUDIO_BASE_URL` (default: `http://127.0.0.1:1234/v1`) |
221
- | **OpenAI** | `gpt-5.6-luna` *(default)*, `gpt-5.6-terra`, `gpt-5.6-sol` | **Cost-sensitive → Flagship** ($0.20 - $4.00 / 1M input) | [Docs](https://developers.openai.com/api/docs/models) • [API Ref](https://developers.openai.com/api/reference) | `OPENAI_API_KEY` |
222
- | **Google Gemini** | `gemini-3.7-flash` *(default)*, `gemini-3.5-flash-lite`, `gemini-3.6-flash` | **Free tier / Stable Flash** ($0.30 - $0.75 / 1M input) | [Docs](https://ai.google.dev/gemini-api/docs/models) • [API Ref](https://ai.google.dev/api/generate-content) | `GEMINI_API_KEY` |
223
- | **Groq** | `openai/gpt-oss-120b` *(default)*, `openai/gpt-oss-20b` | **LPU Ultra-Fast** ($0.075 - $0.15 / 1M input) | [Docs](https://console.groq.com/docs/quickstart) • [API Ref](https://console.groq.com/docs/api-reference) | `GROQ_API_KEY` |
224
- | **DeepSeek** | `deepseek-v4-flash` *(default)*, `deepseek-v4-pro` | **V4 / 1M context** ($0.22 - $1.32 / 1M uncached input) | [Docs](https://api-docs.deepseek.com/quick_start/pricing/) • [API Ref](https://api-docs.deepseek.com/api/create-chat-completion) | `DEEPSEEK_API_KEY` |
225
- | **OpenRouter** | `openrouter/auto` *(default, dynamic catalog)* | **Automatic routing** (billed at routed model rate) | [Docs](https://openrouter.ai/docs/guides/routing/routers/auto-router) • [API Ref](https://openrouter.ai/docs/api/reference/overview) | `OPENROUTER_API_KEY` |
226
- | **Custom Gateway** | Any OpenAI-compatible server (vLLM, Ollama, TGI, Azure) | **Custom** | [OpenAI Spec](https://platform.openai.com/docs/api-reference) | `LLM_BASE_URL`, `LLM_API_KEY` |
227
-
228
- ```bash
229
- # Manage providers interactively within the agent CLI:
230
- /provider list # View all 7 providers and key status
231
- /provider use groq openai/gpt-oss-120b # Switch provider and model in one command
232
- /provider models gemini # List curated cost-effective models with pricing & context
233
- /provider info openai # Show developer documentation & API details
234
- /provider test groq # Test live endpoint connection and measure latency
235
- /provider setkey groq gsk-... # Set or update API key dynamically at runtime
236
- /model recommend # View recommended models for active provider
237
- /model use gpt-5.6-luna # Switch active model on current provider
238
- ```
239
-
240
- ---
241
-
242
- ## Model Context Protocol (MCP)
243
-
244
- ### 1. MCP Server (`kiku-mcp`)
245
-
246
- The package ships an official Model Context Protocol server exposing the Ju Jingyi encyclopedia as **43 tools**, **7 resources**, and **7 prompt templates**:
247
-
248
- ```bash
249
- # Stdio transport (Claude Desktop, Cursor, VS Code)
250
- kiku-mcp
251
-
252
- # Zero-install via npx:
253
- npx -y kiku-agent kiku-mcp
254
- ```
255
-
256
- #### Claude Desktop & Cursor Integration
257
-
258
- Add the following snippet to your `claude_desktop_config.json` or Cursor MCP configuration:
259
-
260
- ```json
261
- {
262
- "mcpServers": {
263
- "kiku": {
264
- "command": "npx",
265
- "args": ["-y", "kiku-agent", "kiku-mcp"]
266
- }
267
- }
268
- }
269
- ```
270
-
271
- The production deployment exposes a stateless Streamable HTTP endpoint at `https://jujingyi-kikuuu.vercel.app/mcp` (`POST /mcp`).
272
-
273
- > [!IMPORTANT]
274
- > **HTTP Security**: The remote MCP endpoint is guarded by a bearer token and CORS allow-list:
275
- > - Set `MCP_API_KEY` to require `Authorization: Bearer <MCP_API_KEY>` on `POST /mcp`.
276
- > - Set `MCP_CORS_ORIGINS` to a comma-separated list of allowed browser origins (empty = no CORS).
277
-
278
- ```bash
279
- # Example: curl the Streamable HTTP endpoint
280
- curl -X POST https://jujingyi-kikuuu.vercel.app/mcp \
281
- -H "Authorization: Bearer $MCP_API_KEY" \
282
- -H "Content-Type: application/json" \
283
- -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
284
- ```
285
-
286
- ### 2. MCP Client in `kiku-agent`
287
-
288
- `kiku-agent` can connect to external MCP servers (Streamable HTTP, Stdio) and dynamically load their tools:
289
-
290
- ```bash
291
- # Connect to an MCP server from the CLI:
292
- /mcp connect kiku-remote https://jujingyi-kikuuu.vercel.app/mcp
293
- /mcp connect filesystem stdio npx -y @modelcontextprotocol/server-filesystem ./
294
- /mcp tools
295
- ```
296
-
297
- ---
298
-
299
- ## Environment Variables
300
-
301
- Copy `.env.example` → `.env` (parsed automatically when the CLI runs; only unset variables are filled):
302
-
303
- | Variable | Purpose |
304
- |---|---|
305
- | `LLM_PROVIDER` | Active provider override (`openai`, `openrouter`, `groq`, `deepseek`, `gemini`, `lmstudio`, `custom`) |
306
- | `OPENAI_API_KEY` | OpenAI API Key |
307
- | `OPENROUTER_API_KEY` | OpenRouter API Key |
308
- | `GROQ_API_KEY` | Groq Cloud API Key |
309
- | `DEEPSEEK_API_KEY` | DeepSeek API Key |
310
- | `GEMINI_API_KEY` | Google Gemini API Key |
311
- | `LMSTUDIO_BASE_URL` | LM Studio endpoint (default `http://127.0.0.1:1234/v1`) |
312
- | `KIKU_YT_COOKIES` | Path to a `cookies.txt` file for YouTube playback |
313
- | `KIKU_YT_BROWSER` | Import cookies from a browser (`chrome`, `edge`, `firefox`) |
314
- | `KIKU_YTDLP` | Path/command for yt-dlp binary (default `yt-dlp`) |
315
- | `KIKU_YTDLP_CLIENT` | YouTube player client override (`tv`, `ios`, `web`) |
316
- | `MCP_API_KEY` | Bearer token required by the HTTP MCP endpoint (`POST /mcp`) |
317
- | `MCP_CORS_ORIGINS` | Comma-separated allowed origins for browser MCP calls |
318
- | `KIKU_MCP_ENABLE_WEB_TOOLS` | Set `true` to enable web tools in the MCP server |
319
- | `KIKU_API_KEYS` | Pre-seeded REST API keys (higher rate limits) |
320
- | `KIKU_VIP_KEYS` | Pre-seeded Developer VIP API keys (highest rate limits) |
321
-
322
- > [!CAUTION]
323
- > `.env` is gitignored — never commit it. The checked-in `.env.example` contains placeholders only.
324
- > Likewise, `cookies.txt` at the repo root contains real YouTube session cookies and must never be staged or committed.
325
-
326
- ---
327
-
328
- ## Web App & REST API
329
-
330
- ### Frontend (Vite + React 19 + Tailwind 4)
331
-
332
- ```bash
333
- # Start frontend dev server (API v1 works in-process)
334
- npm run dev
335
-
336
- # Production build
337
- npm run build
338
- ```
339
-
340
- The SPA lives in `src/` (entry `src/App.jsx`) and uses state-based navigation via `NavigationContext` (no react-router). All non-API paths rewrite to `/` in `vercel.json`.
341
-
342
- ### REST API v1
343
-
344
- The API is a single framework-free Node handler in `server/apiRouter.js` (~2000 lines) serving every `/api/v1/*` route plus OpenAPI specifications and interactive documentation:
345
-
346
- - **Base URL (prod):** `https://jujingyi-kikuuu.vercel.app/api/v1`
347
- - **Base URL (dev):** `http://localhost:3000/api/v1` *(or dynamically assigned port e.g. 5173)*
348
- - **Interactive docs:** `https://jujingyi-kikuuu.vercel.app/api-docs`
349
- - **OpenAPI 3.0 JSON:** `https://jujingyi-kikuuu.vercel.app/api/v1/openapi.json`
350
- - **Health check:** `GET /api/v1/health`
351
- - **Web Chat:** `https://jujingyi-kikuuu.vercel.app/chat` *(or local `/web` on port 3300)*
352
-
353
- ```bash
354
- curl https://jujingyi-kikuuu.vercel.app/api/v1/health
355
- ```
356
-
357
- #### 🌟 Kiku Agent Showcase on `/api-docs`
358
-
359
- The interactive `/api-docs` portal features a dedicated **Kiku AI Agent & MCP Ecosystem Showcase** card:
360
- - One-click copyable global CLI installation (`npm install -g kiku-agent`, `kiku-agent`).
361
- - Zero-install one-shot command (`npx kiku-agent --query "..."`).
362
- - Instant MCP server commands (`kiku-mcp`) and ready-to-paste `claude_desktop_config.json` / Cursor JSON snippets.
363
- - Direct links to npm, GitHub, and the live Web Chat interface.
364
-
365
- Endpoint groups include catalog (works, discography, brands, awards, timeline, profile, gallery), stats, quiz challenges and Developer VIP key claiming (`/api/v1/quiz/challenge`, `/api/v1/keys/claim`), plus agent/REST integration. `?key=` or bearer auth with a `KIKU_API_KEYS` / `KIKU_VIP_KEYS` value unlocks higher rate limits.
366
-
367
- ---
368
-
369
- ## Data Architecture & Gotchas
370
-
371
- > [!IMPORTANT]
372
- > **Dual Catalog Notice**: The catalog data lives in two independent copies with the same export names but different contents:
373
- > - `src/data/*.js` (used by the SPA, REST API, and agent tools): Rich, Thai-heavy.
374
- > - `server/mcp/data/*.js` (used by the MCP server): Compact English.
375
- >
376
- > **Any catalog change must be applied to both trees**, or MCP answers will drift from the site/API.
377
-
378
- - **Packaging**: `package.json` `"files"` ships `src/data/**/*.js` because the agent imports them — don't move that directory without updating both `"files"` and every importer. Bins are `kiku-agent` and `kiku-mcp`; package exports map `.` → `server/agent/agentCore.js`.
379
- - **Path aliases**: The `@/*` alias in `jsconfig.json` is unused — use relative imports everywhere (no matching alias in `vite.config.js`).
380
- - **Testing & Verification**: There is no linter or typechecker setup. Verification is `npm test` (running 330 unit/integration tests) plus `npm run build`.
381
-
382
- ---
383
-
384
- ## Troubleshooting
385
-
386
- **Agent won't start or stays in catalog-only mode**
387
- - Ensure LM Studio is running with a Gemma model loaded and the local server started on `127.0.0.1:1234`, or specify a cloud provider with `-P <provider> -k <key>`.
388
- - Run `/doctor` inside the session to diagnose Node, app data, LM Studio, model, FFmpeg, speaker, and yt-dlp availability.
389
-
390
- **Windows install reports `EBUSY` for `ffmpeg-static`**
391
- - Close all active terminal windows running Node or Kiku. In a fresh PowerShell window:
392
- ```powershell
393
- npm uninstall -g kiku-agent
394
- $stale = Join-Path (npm root -g) 'kiku-agent'
395
- if (Test-Path $stale) { Remove-Item -Recurse -Force $stale }
396
- npm cache verify
397
- npm install -g kiku-agent
398
- ```
399
-
400
- **YouTube playback fails**
401
- - Re-authenticate with `/login`, or point `KIKU_YT_COOKIES` / `KIKU_YT_BROWSER` at a valid session and `KIKU_YTDLP` at a working yt-dlp binary. Some regions/clients need `KIKU_YTDLP_CLIENT` set to `tv` or `ios`.
402
-
403
- **Remote MCP returns 401 Unauthorized**
404
- - Set `MCP_API_KEY` on the server and send `Authorization: Bearer <MCP_API_KEY>`. For browser clients, set `MCP_CORS_ORIGINS` to the allowed origins.
405
-
406
- **Reports of missing or stale model after switching providers**
407
- - The CLI automatically queries the provider's live `/models` endpoint at startup, on provider switches, and before one-shot queries, falling back gracefully to recommended active models if a configured model was retired.
1
+ <div align="center">
2
+
3
+ <img src="https://jujingyi-kikuuu.vercel.app/images/jujingyi_portrait.jpg" width="96" height="96" style="border-radius: 50%; object-fit: cover;" alt="Ju Jingyi Icon" />
4
+
5
+ # Ju Jingyi (鞠婧祎) Portal & Kiku AI Agent
6
+
7
+ *Full-stack fan archive, REST API Suite v1.0, and autonomous AI Agent CLI + MCP Server*
8
+
9
+ [![npm version](https://img.shields.io/npm/v/kiku-agent?style=flat-square&color=cb3837)](https://www.npmjs.com/package/kiku-agent)
10
+ [![Node.js version](https://img.shields.io/badge/Node.js-%3E%3D20-3c873a?style=flat-square)](https://nodejs.org)
11
+ [![ESM only](https://img.shields.io/badge/ESM-only-4a90d9?style=flat-square)](https://nodejs.org/api/esm.html)
12
+ [![MCP Protocol](https://img.shields.io/badge/MCP-Protocol-8a2be2?style=flat-square)](https://modelcontextprotocol.io)
13
+ [![License](https://img.shields.io/badge/License-GPL--3.0-blue?style=flat-square)](LICENSE)
14
+
15
+ ⭐ If you find this project helpful, star it on GitHub!
16
+
17
+ [Overview](#overview) • [Quick Start](#quick-start) • [Features](#features) • [CLI Commands](#interactive-chat-slash-commands) • [Agent Tools](#available-agent-tools-59) • [Cloud & Local Models](#multi-provider-cloud--local-models) • [MCP Integration](#model-context-protocol-mcp) • [Evaluation](#live-answer-evaluation) • [Web App & REST API](#web-app--rest-api) • [Troubleshooting](#troubleshooting)
18
+
19
+ </div>
20
+
21
+ ---
22
+
23
+ ## Overview
24
+
25
+ This repository ships a complete full-stack ecosystem for Chinese singer and actress **Ju Jingyi (鞠婧祎)**, packaged and distributed under the single [`kiku-agent`](https://www.npmjs.com/package/kiku-agent) npm package:
26
+
27
+ | Deliverable | Location | Description |
28
+ |---|---|---|
29
+ | **Fan Portal (SPA)** | `src/` | Vite + React 19 + Tailwind 4 interactive showcase featuring discography, filmography, 4K visual gallery, trivia quiz, and timeline. |
30
+ | **REST API v1** | `server/apiRouter.js` | Framework-free Node `http` REST API suite serving 16 endpoints, OpenAPI 3.0 specs, and live interactive `/api-docs`. |
31
+ | **AI Agent CLI & MCP Server** | `server/agent/`, `server/mcp/` | Autonomous ReAct agent CLI (`kiku-agent`, 59 tools) and Model Context Protocol server (`kiku-mcp`, 58 tools) connecting to local LM Studio or cloud LLMs. |
32
+ | **Stateful Memory Engine** | `server/agent/memory/` | Hierarchical run-scoped memory (`kiku/runs/{run_id}/...`), pointer-over-data rule, step checkpoints, and 4-tier context allocator. |
33
+ | **Hybrid Meta-Search Engine** | `server/agent/websearch/` | Zero-key multi-engine search (DuckDuckGo, SearXNG, Jina), token bucket rate limiting, circuit breaker, SSRF defense, and RRF rank fusion. |
34
+ | **Command Center Hub & Dev Suite** | `scripts/kikuHub.js`, `scripts/devAll.js` | Terminal interactive command center (`npm start`) and 3-tier dev environment (`npm run dev:all`: ports 3000, 3001, 3002). |
35
+ | **VRAM & Hardware Engine** | `server/agent/vramService.js`, `src/lib/vram/` | Predictive VRAM footprint estimation, multi-stage memory bus width disambiguation, and offline database of 100+ accelerators. |
36
+ | **NVIDIA Nsight Systems Profiler** | `scripts/profileNsys.js` | Automated GPU CUDA kernel, cuBLAS GEMM, FlashAttention, and memory bus bandwidth profiler with bottleneck diagnostics and GUI support. |
37
+
38
+ > [!TIP]
39
+ > **100% Free Local Inference**: Kiku Agent runs completely offline with zero API token cost when connected to [LM Studio](https://lmstudio.ai/) running `google/gemma-4-e4b`. If no LLM is running, Kiku automatically starts in **catalog-only mode** instead of crashing.
40
+
41
+ ---
42
+
43
+ ## Quick Start
44
+
45
+ ### Global Installation
46
+
47
+ Install the Kiku Agent CLI and MCP server globally via npm:
48
+
49
+ ```bash
50
+ npm install -g kiku-agent
51
+ kiku-agent
52
+ ```
53
+
54
+ > [!NOTE]
55
+ > The global package deliberately excludes native binary build dependencies (Python, `node-gyp`, Visual Studio C++ build tools are not required). For a local checkout before publishing, pack and install via `npm install -g ./kiku-agent-1.3.0.tgz`.
56
+
57
+ ### Zero-Install One-Shot Query
58
+
59
+ Ask questions directly from your terminal using `npx`:
60
+
61
+ ```bash
62
+ npx kiku-agent --query "ผลงานซีรีส์ปี 2026 มีเรื่องอะไรบ้างและรับบทเป็นใคร"
63
+ ```
64
+
65
+ ### Local LM Studio Setup
66
+
67
+ 1. Open **LM Studio** on your machine.
68
+ 2. Download or load **`google/gemma-4-e4b`** (quantization: `Q4_K_M`, `Q6_K`, or `Q8_0`).
69
+ 3. Click the **Developer / Local Server** tab (`<->`) on the left sidebar.
70
+ 4. Select your loaded Gemma model and click **Start Server** on port `1234` (`http://localhost:1234`).
71
+ 5. Launch Kiku Agent:
72
+ ```bash
73
+ kiku-agent
74
+ ```
75
+
76
+ ### Launch with Cloud Providers
77
+
78
+ ```bash
79
+ # OpenAI (GPT-5.6 / GPT-4o)
80
+ npm run kiku-agent -- --provider openai --model gpt-5.6-luna
81
+
82
+ # Google Gemini (Gemini 3.7 Flash)
83
+ npm run kiku-agent -- --provider gemini --model gemini-3.7-flash
84
+
85
+ # Groq (Ultra-fast LPU inference)
86
+ npm run kiku-agent -- --provider groq --model openai/gpt-oss-120b
87
+
88
+ # DeepSeek (DeepSeek V4)
89
+ npm run kiku-agent -- --provider deepseek --model deepseek-v4-flash
90
+
91
+ # OpenRouter (Dynamic routing)
92
+ npm run kiku-agent -- --provider openrouter --model openrouter/auto
93
+ ```
94
+
95
+ ---
96
+
97
+ ## Features
98
+
99
+ - **Autonomous ReAct Agent**: Equipped with **59 validated tools** covering catalog knowledge, live web search, news/encyclopedia discovery, YouTube audio playback, filesystem inspection, stateful memory checkpoints, entertainment analytics, and research workers.
100
+ - **Stateful & Self-Reflective Memory Engine**: Hierarchical workspace (`kiku/runs/{run_id}/...`), pointer-over-data rule (>1,000 chars referenced to prevent context bloat), real-time step checkpoints (`checkpoint_step`, `record_failure`, `load_active_run`), post-run compaction into global reflections (`kiku/knowledge/reflections.md`), and 4-tier token budget allocation.
101
+ - **Fault-Tolerant Hybrid Meta-Search**: Zero-key search combining DuckDuckGo, SearXNG, and Jina with token bucket rate limiting, circuit breakers, SSRF DNS pinning, multilingual query fan-out, and Reciprocal Rank Fusion (RRF).
102
+ - **Predictive VRAM & Telemetry Engine**: Real-time GPU memory footprint estimation, context scaling ladder, multi-stage memory bus width disambiguation, sliding-window attention (SWA) KV cache modeling, and offline database of 100+ accelerators (`/vram`, `npm run vram:live`).
103
+ - **NVIDIA Nsight Systems Profiling Engine**: Automated GPU CUDA kernel tracing, memory bandwidth saturation analysis, and CPU/PCIe bottleneck diagnostics (`npm run profile:nsys`). Captures cuBLAS GEMM, FlashAttention-2, RMSNorm, and RoPE kernels, calculates memory bus efficiency ($(\text{tok/s} \times \text{Model Size}) / \text{Bandwidth Peak}$), warns against PCIe thrashing, and exports executive Markdown summaries with optional GUI visualization (`--gui`).
104
+ - **Interactive Evaluation & Performance Studio**: Standalone offline benchmark reports with zero-click auto-open browser execution, mobile-responsive layouts, live latency, Thai Buddhist Era (พ.ศ.) & duration normalizers, category partitioning (`npm run eval:split`), clamped `[0, 100]%` progress tracking, dedicated workbench on port 3001 (`npm run eval:ui`), automated anomaly row detection (`isAnomalyRow`), targeted one-click retry (`#btnRetry`), and AI benchmark executive summaries with strict thinking-block suppression.
105
+ - **Dynamic Multiline TUI & Instant Paste**: Terminal input area auto-expands up to 6 rows with continuation prefixes, `Shift+Enter` multiline editing, `Ctrl+V` clipboard paste, and bracketed paste batch rendering (pasting 5,000+ characters completes in <30ms without UI freezing).
106
+ - **Multi-Agent Adversarial Debate**: The `/debate` command orchestrates dialectic affirmative vs. negative agent workers to challenge factual claims against catalog records and synthesize evidence-backed truth matrices.
107
+ - **Multi-Provider Engine**: Seamless switching between local LM Studio and 6 top cloud providers (OpenAI, Gemini, Groq, DeepSeek, OpenRouter, and custom OpenAI-compatible endpoints) with runtime health and latency diagnostics.
108
+ - **Local Audio Player**: YouTube streaming via `yt-dlp` and `ffmpeg` with play, pause, skip, track queueing, and mute/unmute controls.
109
+ - **Model Context Protocol (MCP)**: Official stdio (`kiku-mcp`) and Streamable HTTP endpoints exposing **58 tools** (55 agent tools + 3 compatibility aliases: `get_profile`, `get_timeline`, `search_gallery`), **8 resources**, and **7 prompt templates** for Claude Desktop, Cursor, and VS Code.
110
+ - **Standalone Web Chat Portal**: Interactive browser chatbot (`/chat` or `/web` on port 3002 or in-process on port 3000) with character network visualization, mini Jukebox player, and direct catalog fallback.
111
+ - **Developer VIP Keys**: Integrated 15-question trivia quiz (`/quiz`) allowing users to test fan knowledge and earn Developer VIP API keys with elevated rate limits.
112
+ - **Rich Transcript Export**: `/save` and `/session export` output single-file self-contained HTML (with embedded CSS & dark mode), Markdown, JSON, or plain text.
113
+
114
+ ---
115
+
116
+ ## CLI Usage
117
+
118
+ ### Command-Line Flags
119
+
120
+ | Flag | Description |
121
+ |---|---|
122
+ | `-h`, `--help` | Display usage instructions and options |
123
+ | `-V`, `--version` | Print installed package version |
124
+ | `-P`, `--provider <name>` | Select provider (`lmstudio`, `openai`, `gemini`, `groq`, `deepseek`, `openrouter`, `custom`) |
125
+ | `-k`, `--api-key <key>` | Cloud provider API key override |
126
+ | `-m`, `--model <id>` | Model ID override (e.g. `gpt-5.6-luna`, `gemini-3.7-flash`, `google/gemma-4-e4b`) |
127
+ | `-u`, `--url <url>` | Provider base URL override |
128
+ | `-t`, `--tools` | List all 59 registered tools |
129
+ | `-s`, `--stats` | Print catalog overview statistics |
130
+ | `-v`, `--verbose` | Verbose mode with reasoning output |
131
+ | `--hub [filter]` | Launch Kiku Master Command Center hub dashboard |
132
+ | `--portal [open\|api\|chat\|eval\|status]` | Inspect or open Port 3000 Web Portal SPA, REST API docs, or Eval Studio |
133
+ | `--eval [ui\|dashboard\|validate\|quick\|split]` | Manage Eval Studio web UI, performance reports, benchmark validation, and category splitting |
134
+ | `--vram [live\|compare\|ctx\|list\|tier]`, `--gpu` | Real-time VRAM budget, bus width, hardware tier & KV allocation monitor |
135
+ | `npm run profile:nsys` | NVIDIA Nsight Systems GPU CUDA kernels & memory bus bottleneck analyzer (`--mode inference\|agent`, `--gui`) |
136
+ | `--thinking [show\|hide]` | Toggle visibility of reasoning process |
137
+ | `-q`, `--query "<text>"` | One-shot query mode |
138
+
139
+ ---
140
+
141
+ ## Interactive Chat Slash Commands
142
+
143
+ Type `/help` inside any active session for the interactive command palette. Commands are organized by functional domain:
144
+
145
+ ### 🤖 Provider & Model
146
+ - `/provider [list|use|models|info|test|setkey]` — Inspect, switch, and test AI providers, or set API keys at runtime
147
+ - `/model [list|recommend|use|reconnect]` — Switch models on the fly without restarting, or reconnect after starting LM Studio
148
+
149
+ ### 🧠 Memory & Conversation Sessions
150
+ - `/mem [add|search|list|topics|summary|del|import|export|clear]` — Long-term conversational memory with TF-IDF keyword scoring & recency decay
151
+ - `/session [info|summary|list|load|export|clear]` — Manage, restore, or summarize conversation sessions
152
+ - `/history [n|search|summary|clear]` — Review and search past conversation turns
153
+ - `/save [markdown|html|json|text]` — Export session transcript (single-file HTML with dark mode, Markdown, JSON, plain text)
154
+ - `/copy [session|[Qn] [answer|thinking|tools|tool n|all|json]]` — Copy transcript, answers, or diagnostic info to clipboard
155
+ - `/clear` — Reset active conversation history
156
+
157
+ ### 🔍 Catalog & Discovery
158
+ - `/find <query> [--type <type>] [--year YYYY]` — Search works, songs, roles, brands, awards, and stages (AI-enhanced)
159
+ - `/compare <item-a> -- <item-b>` — Side-by-side comparison of catalog items or career years (AI-enhanced)
160
+ - `/favorites [list|add|remove|export|suggest]` — Personal collection builder with AI recommendations
161
+ - `/discover [drama|song|stage|photo]` — Recommendations by type, year, and mood (AI-enhanced)
162
+ - `/news [topic] [--days N] [--official-only]` — Dated coverage and recent source-backed updates (AI-enhanced)
163
+ - `/stats` — Print summary counts of dramas, songs, brands, and awards (AI-enhanced)
164
+ - `/gallery` — Render Ju Jingyi images directly in the terminal
165
+
166
+ ### 🔬 Research, Debate & Subagents (Advanced)
167
+ - `/debate <claim|status|last>` — Multi-agent adversarial debate with affirmative/negative roles and truth matrix synthesis
168
+ - `/timeline [year|era]` — Render career milestone ASCII timeline graphic in terminal
169
+ - `/subagent <task>` — Dispatch a bounded research subagent with catalog & web access
170
+ - `/research <question>` — Coordinate parallel catalog, web, and verification workers
171
+ - `/verify <claim>` — Classify a claim as verified, unverified, conflicting, or false
172
+ - `/suggestion [list|run|auto|refresh|topic]` — Auto-generate exploration prompts and execute them with subagents
173
+ - `/sources` — Show source URLs captured by the latest research run
174
+ - `/jobs [list|show|cancel|clear]` — Inspect and control background research jobs
175
+ - `/skill [learn|list|del|on|off|clear]` — Teach persistent response persona preferences across sessions
176
+
177
+ ### 🎵 Music Player (Local Audio)
178
+ - `/play <song>` / `/stop` / `/pause` / `/resume` — YouTube audio streaming via yt-dlp & FFmpeg
179
+ - `/next` / `/prev` / `/queue` / `/add` / `/remove` / `/clearqueue` — Queue and track management
180
+ - `/mute` / `/unmute` / `/current` — Volume and playback status
181
+
182
+ ### 🛠️ System, UI & Diagnostics
183
+ - `/hub [filter]` — Show Kiku Master Command Center hub with hardware telemetry, system metrics, and command index
184
+ - `/portal [open|api|chat|eval|status]` — Inspect or open local Web Portal SPA, REST API v1 docs, Web Chat, or Eval Studio (port 3000)
185
+ - `/eval [ui|dashboard|validate|quick|run|judge|compare|gate|status]` — Interactive Eval Studio dashboard, report generation, and frozen ground truth benchmark suites
186
+ - `/vram [live|compare|ctx|list|check|tier]` — Real-time VRAM budget, hardware classification tier, bus width disambiguation, context ladders, and pre-flight check
187
+ - `/doctor` — Diagnostic check for Node, app data, LM Studio, models, FFmpeg, speaker, and yt-dlp
188
+ - `/details [Qn]` — Diagnostic overview of answers, reasoning process, and bounded tool calls (F2)
189
+ - `/tools` — View all 56 registered tools with parameter descriptions
190
+ - `/lang [th|zh|en|auto]` — Set response language (Thai, Chinese, English)
191
+ - `/theme [name|list|current|next|prev|reset]` — Switch terminal color theme
192
+ - `/thinking [show|hide|toggle]` — Toggle reasoning process visibility
193
+ - `/system` / `/gpu` / `/ping` / `/config` — System info, NVIDIA GPU/VRAM monitor, server latency, and runtime config
194
+ - `/quiz [lang]` — 15-question fan trivia quiz to claim a Developer VIP API key
195
+ - `/key [show|apply <key>|clear]` — Manage Developer VIP API Key
196
+ - `/web [start|open|stop|status|restart] [port]` — Launch or open standalone Web Chat interface (port 3300)
197
+ - `/cancel` / `/retry` / `/exit` — Abort query, retry, or exit the agent
198
+
199
+ > [!NOTE]
200
+ > `/find`, `/compare`, `/favorites suggest`, `/news`, `/discover`, and `/stats` are **catalog-native + AI-enhanced**: they run in catalog-only mode without an LLM, and layer an AI summary on top whenever a model is active.
201
+
202
+ ### Example CLI Workflows
203
+
204
+ ```text
205
+ /find "In Blossom" --type work
206
+ /compare "In Blossom" -- "Beauty of Resilience"
207
+ /favorites add song "Rain Love"
208
+ /debate "Ju Jingyi debuted with SNH48 in 2013"
209
+ /timeline 2024
210
+ /research "Ju Jingyi 2026 upcoming dramas"
211
+ /skill learn "ตอบภาษาไทยแบบสั้น กระชับ"
212
+ /quiz lang th
213
+ ```
214
+
215
+ ---
216
+
217
+ ## Available Agent Tools (59)
218
+
219
+ Kiku Agent includes **59 validated tools** across 6 categories that the agent autonomously invokes during conversations:
220
+
221
+ - **Catalog (14)**: Profile, fandom facts, quotes, filmography (2013–2026), character roles, discography, music videos, brands, career timeline, awards, Weibo/Douyin feeds, 4K gallery, and global fuzzy search.
222
+ - **Web & Network (6)**: Live DuckDuckGo search, hybrid meta-search orchestrator (SearXNG, Jina), article extraction, raw webpage fetch, JSON parser, page screenshots, and REST API querying.
223
+ - **Discovery & Analytics (11)**: Live news/RSS feeds, encyclopedia lookup, Chinese web portals, Chinese web image search (`search_web_images` for on-set stills, red carpet & press photos), Bilibili video search, music-platform search, YouTube transcripts, datetime utility, and entertainment/industry metrics.
224
+ - **Music Player (15)**: YouTube streaming via `yt-dlp` & `ffmpeg`, playlist queue management, track playback controls, and volume mute/unmute.
225
+ - **Filesystem & Stateful Memory (6)**: Directory listing, safe local file reader, archive statistics, plus **Hierarchical Memory Checkpoints**: `checkpoint_step` (record execution step and state), `record_failure` (capture error code and recovery path), and `load_active_run` (hydrate run context and memory pointers).
226
+ - **Research, Skills & VIP (7)**: Autonomous research subagents, deep research coordinator, claim verification, topic suggestion, persistent skill learning, trivia quiz challenge, and Developer VIP key management.
227
+
228
+ > [!TIP]
229
+ > Run `/tools` inside the CLI or visit [`/api-docs`](https://jujingyi-kikuuu.vercel.app/api-docs) to inspect parameter schemas and test all tools interactively.
230
+
231
+ ---
232
+
233
+ ## Multi-Provider Cloud & Local Models
234
+
235
+ `kiku-agent` natively supports local LM Studio inference alongside top Cloud AI Providers with official endpoints, active cost-effective models, and tool-calling capabilities:
236
+
237
+ | Provider | Recommended Active Models | Pricing / Cost Tier | Doc & API Reference | Required ENV Variable |
238
+ |---|---|---|---|---|
239
+ | **LM Studio** (Local) | `google/gemma-4-e4b` *(Q4_K_M, Q6_K, Q8_0)* | **100% Free / Local** (Zero token cost) | [Docs](https://lmstudio.ai/docs) • [API Ref](https://lmstudio.ai/docs/api/local-server) | `LMSTUDIO_BASE_URL` (default: `http://127.0.0.1:1234/v1`) |
240
+ | **OpenAI** | `gpt-5.6-luna` *(default)*, `gpt-5.6-terra`, `gpt-5.6-sol` | **Cost-sensitive → Flagship** ($0.20 - $4.00 / 1M input) | [Docs](https://developers.openai.com/api/docs/models) • [API Ref](https://developers.openai.com/api/reference) | `OPENAI_API_KEY` |
241
+ | **Google Gemini** | `gemini-3.7-flash` *(default)*, `gemini-3.5-flash-lite`, `gemini-3.6-flash` | **Free tier / Stable Flash** ($0.30 - $0.75 / 1M input) | [Docs](https://ai.google.dev/gemini-api/docs/models) • [API Ref](https://ai.google.dev/api/generate-content) | `GEMINI_API_KEY` |
242
+ | **Groq** | `openai/gpt-oss-120b` *(default)*, `openai/gpt-oss-20b` | **LPU Ultra-Fast** ($0.075 - $0.15 / 1M input) | [Docs](https://console.groq.com/docs/quickstart) • [API Ref](https://console.groq.com/docs/api-reference) | `GROQ_API_KEY` |
243
+ | **DeepSeek** | `deepseek-v4-flash` *(default)*, `deepseek-v4-pro` | **V4 / 1M context** ($0.22 - $1.32 / 1M uncached input) | [Docs](https://api-docs.deepseek.com/quick_start/pricing/) • [API Ref](https://api-docs.deepseek.com/api/create-chat-completion) | `DEEPSEEK_API_KEY` |
244
+ | **OpenRouter** | `openrouter/auto` *(default, dynamic catalog)* | **Automatic routing** (billed at routed model rate) | [Docs](https://openrouter.ai/docs/guides/routing/routers/auto-router) • [API Ref](https://openrouter.ai/docs/api/reference/overview) | `OPENROUTER_API_KEY` |
245
+ | **Custom Gateway** | Any OpenAI-compatible server (vLLM, Ollama, TGI, Azure) | **Custom** | [OpenAI Spec](https://platform.openai.com/docs/api-reference) | `LLM_BASE_URL`, `LLM_API_KEY` |
246
+
247
+ ```bash
248
+ # Manage providers interactively within the agent CLI:
249
+ /provider list # View all 7 providers and key status
250
+ /provider use groq openai/gpt-oss-120b # Switch provider and model in one command
251
+ /provider models gemini # List curated cost-effective models with pricing & context
252
+ /provider info openai # Show developer documentation & API details
253
+ /provider test groq # Test live endpoint connection and measure latency
254
+ /provider setkey groq gsk-... # Set or update API key dynamically at runtime
255
+ /model recommend # View recommended models for active provider
256
+ /model use gpt-5.6-luna # Switch active model on current provider
257
+ ```
258
+
259
+ ---
260
+
261
+ ## Model Context Protocol (MCP)
262
+
263
+ ### 1. MCP Server (`kiku-mcp`)
264
+
265
+ The package ships an official Model Context Protocol server exposing the Ju Jingyi encyclopedia as **58 tools** (55 agent tools + 3 compatibility aliases: `get_profile`, `get_timeline`, `search_gallery`), **8 resources**, and **7 prompt templates**. Live-web and Chinese tools are opt-in via `KIKU_MCP_ENABLE_WEB_TOOLS=true` and `KIKU_ENABLE_CN_WEB_TOOLS=true`:
266
+
267
+ ```bash
268
+ # Stdio transport (Claude Desktop, Cursor, VS Code)
269
+ kiku-mcp
270
+
271
+ # Zero-install via npx:
272
+ npx -y kiku-agent kiku-mcp
273
+ ```
274
+
275
+ #### Claude Desktop & Cursor Integration
276
+
277
+ Add the following snippet to your `claude_desktop_config.json` or Cursor MCP configuration:
278
+
279
+ ```json
280
+ {
281
+ "mcpServers": {
282
+ "kiku": {
283
+ "command": "npx",
284
+ "args": ["-y", "kiku-agent", "kiku-mcp"]
285
+ }
286
+ }
287
+ }
288
+ ```
289
+
290
+ The production deployment exposes a stateless Streamable HTTP endpoint at `https://jujingyi-kikuuu.vercel.app/mcp` (`POST /mcp`).
291
+
292
+ > [!IMPORTANT]
293
+ > **HTTP Security**: The remote MCP endpoint is guarded by a bearer token and CORS allow-list:
294
+ > - Set `MCP_API_KEY` to require `Authorization: Bearer <MCP_API_KEY>` on `POST /mcp`.
295
+ > - Set `MCP_CORS_ORIGINS` to a comma-separated list of allowed browser origins (empty = no CORS).
296
+
297
+ ```bash
298
+ # Example: curl the Streamable HTTP endpoint
299
+ curl -X POST https://jujingyi-kikuuu.vercel.app/mcp \
300
+ -H "Authorization: Bearer $MCP_API_KEY" \
301
+ -H "Content-Type: application/json" \
302
+ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
303
+ ```
304
+
305
+ ### 2. MCP Client in `kiku-agent`
306
+
307
+ `kiku-agent` can connect to external MCP servers (Streamable HTTP, Stdio) and dynamically load their tools:
308
+
309
+ ```bash
310
+ # Connect to an MCP server from the CLI:
311
+ /mcp connect kiku-remote https://jujingyi-kikuuu.vercel.app/mcp
312
+ /mcp connect filesystem stdio npx -y @modelcontextprotocol/server-filesystem ./
313
+ /mcp tools
314
+ ```
315
+
316
+ ---
317
+
318
+ ## Live Answer Evaluation
319
+
320
+ A frozen catalog QA harness in `server/agent/eval/` runs **500 fixed multilingual cases** (350 catalog & reasoning + 150 security & red-teaming across 17 categories) through a fresh real `KikuAgent` per case on local LM Studio, recording answers, tool traces, latency, and token telemetry:
321
+
322
+ ```bash
323
+ npm run eval:validate # Validate frozen 500-case corpus integrity
324
+ npm run eval:quick # 3-case smoke run (needs LM Studio)
325
+ npm run eval:ui # Launch visual Kiku Eval Studio workbench on port 3001 (/eval)
326
+ npm run eval:dashboard # Open interactive mobile-responsive HTML eval report in browser
327
+ npm run eval:split # Split benchmark report into per-category JSON subsets
328
+ npm run eval:run -- --suite catalog --out artifacts/eval/live.json
329
+ npm run eval:run -- --suite all --judge-model google/gemma-4-e4b --gate --dashboard --save-as run1
330
+ npm run eval:compare -- --baseline a.json --candidate b.json
331
+ npm run eval:gate # Gate check against strict quality/security thresholds
332
+ npm run eval:analyze # Deep category & token latency breakdown
333
+ npm run eval:smoke:web
334
+ npm run eval:calibrate
335
+ ```
336
+
337
+ > [!NOTE]
338
+ > The eval harness is dev-only and never published to npm (`package.json`
339
+ > `files` ships `server/agent/*.js` but not the `eval/` subdirectory).
340
+ > Features automatic answer normalization for Thai Buddhist Era years (พ.ศ. 2567 → 2024)
341
+ > and song durations (`03:45` → `3:45`), along with clamped `[0, 100]%` progress tracking.
342
+ > Full operator guide: `server/agent/eval/AGENTS.md`.
343
+
344
+ ---
345
+
346
+ ## Environment Variables
347
+
348
+ Copy `.env.example` → `.env` (parsed automatically when the CLI runs; only unset variables are filled):
349
+
350
+ | Variable | Purpose |
351
+ |---|---|
352
+ | `LLM_PROVIDER` | Active provider override (`openai`, `openrouter`, `groq`, `deepseek`, `gemini`, `lmstudio`, `custom`) |
353
+ | `OPENAI_API_KEY` | OpenAI API Key |
354
+ | `OPENROUTER_API_KEY` | OpenRouter API Key |
355
+ | `GROQ_API_KEY` | Groq Cloud API Key |
356
+ | `DEEPSEEK_API_KEY` | DeepSeek API Key |
357
+ | `GEMINI_API_KEY` | Google Gemini API Key |
358
+ | `LMSTUDIO_BASE_URL` | LM Studio endpoint (default `http://127.0.0.1:1234/v1`) |
359
+ | `KIKU_YT_COOKIES` | Path to a `cookies.txt` file for YouTube playback |
360
+ | `KIKU_YT_BROWSER` | Import cookies from a browser (`chrome`, `edge`, `firefox`) |
361
+ | `KIKU_YTDLP` | Path/command for yt-dlp binary (default `yt-dlp`) |
362
+ | `KIKU_YTDLP_CLIENT` | YouTube player client override (`tv`, `ios`, `web`) |
363
+ | `MCP_API_KEY` | Bearer token required by the HTTP MCP endpoint (`POST /mcp`) |
364
+ | `MCP_CORS_ORIGINS` | Comma-separated allowed origins for browser MCP calls |
365
+ | `KIKU_MCP_ENABLE_WEB_TOOLS` | Set `true` to enable web tools in the MCP server |
366
+ | `KIKU_ENABLE_CN_WEB_TOOLS` | Set `true` to enable Chinese web search portals, Bilibili, and image search |
367
+ | `KIKU_API_KEYS` | Pre-seeded REST API keys (higher rate limits) |
368
+ | `KIKU_VIP_KEYS` | Pre-seeded Developer VIP API keys (highest rate limits) |
369
+
370
+ > [!CAUTION]
371
+ > `.env` is gitignored — never commit it. The checked-in `.env.example` contains placeholders only.
372
+ > Likewise, `cookies.txt` at the repo root contains real YouTube session cookies and must never be staged or committed.
373
+
374
+ ---
375
+
376
+ ## Web App & REST API
377
+
378
+ ### Frontend & Ecosystem Services
379
+
380
+ ```bash
381
+ # 3-tier development suite (runs SPA on 3000, Eval Studio on 3001, and Web Chat on 3002)
382
+ npm run dev:all
383
+
384
+ # Standard Vite dev server (API v1, Web Chat & Eval Studio work in-process on port 3000)
385
+ npm run dev
386
+
387
+ # Production build
388
+ npm run build
389
+ ```
390
+
391
+ The SPA lives in `src/` (entry `src/App.jsx`) and uses state-based navigation via `NavigationContext` (no react-router). All non-API paths rewrite to `/` in `vercel.json`.
392
+
393
+ ### REST API v1
394
+
395
+ The API is a single framework-free Node handler in `server/apiRouter.js` (~4000 lines) serving every `/api/v1/*` route plus OpenAPI specifications and interactive documentation:
396
+
397
+ - **Base URL (prod):** `https://jujingyi-kikuuu.vercel.app/api/v1`
398
+ - **Base URL (dev):** `http://localhost:3000/api/v1` *(all endpoints work in-process alongside Vite)*
399
+ - **Interactive docs:** `https://jujingyi-kikuuu.vercel.app/api-docs`
400
+ - **OpenAPI 3.0 JSON:** `https://jujingyi-kikuuu.vercel.app/api/v1/openapi.json`
401
+ - **Health check:** `GET /api/v1/health`
402
+ - **Web Chat:** `http://localhost:3002/chat` *(or local in-process `http://localhost:3000/chat`)*
403
+ - **Eval Studio:** `http://localhost:3001/eval` *(or local in-process `http://localhost:3000/eval`)*
404
+
405
+ ```bash
406
+ curl https://jujingyi-kikuuu.vercel.app/api/v1/health
407
+ ```
408
+
409
+ #### 🌟 Kiku Agent Showcase on `/api-docs`
410
+
411
+ The interactive `/api-docs` portal features a dedicated **Kiku AI Agent & MCP Ecosystem Showcase** card:
412
+ - One-click copyable global CLI installation (`npm install -g kiku-agent`, `kiku-agent`).
413
+ - Zero-install one-shot command (`npx kiku-agent --query "..."`).
414
+ - Instant MCP server commands (`kiku-mcp`) and ready-to-paste `claude_desktop_config.json` / Cursor JSON snippets.
415
+ - Direct links to npm, GitHub, and the live Web Chat interface.
416
+
417
+ Endpoint groups include catalog (works, discography, brands, awards, timeline, profile, gallery), stats, quiz challenges and Developer VIP key claiming (`/api/v1/quiz/challenge`, `/api/v1/keys/claim`), plus agent/REST integration. `?key=` or bearer auth with a `KIKU_API_KEYS` / `KIKU_VIP_KEYS` value unlocks higher rate limits.
418
+
419
+ ---
420
+
421
+ ## Data Architecture & Gotchas
422
+
423
+ > [!IMPORTANT]
424
+ > **Dual Catalog Notice**: The catalog data lives in two independent copies with the same export names but different contents:
425
+ > - `src/data/*.js` (used by the SPA, REST API, and agent tools): Rich, Thai-heavy.
426
+ > - `server/mcp/data/*.js` (used by the MCP server): Compact English.
427
+ >
428
+ > **Any catalog change must be applied to both trees**, or MCP answers will drift from the site/API.
429
+
430
+ - **Packaging**: `package.json` `"files"` ships `src/data/**/*.js` because the agent imports them — don't move that directory without updating both `"files"` and every importer. Bins are `kiku-agent` and `kiku-mcp`; package exports map `.` → `server/agent/agentCore.js`.
431
+ - **Path aliases**: The `@/*` alias in `jsconfig.json` is unused — use relative imports everywhere (no matching alias in `vite.config.js`).
432
+ - **Testing & Verification**: There is no linter or typechecker setup. Verification is `npm test` (**656 unit/integration tests across 18 suites**) plus `npm run build`.
433
+
434
+ ---
435
+
436
+ ## Troubleshooting
437
+
438
+ **Agent won't start or stays in catalog-only mode**
439
+ - Ensure LM Studio is running with a Gemma model loaded and the local server started on `127.0.0.1:1234`, or specify a cloud provider with `-P <provider> -k <key>`.
440
+ - Run `/doctor` inside the session to diagnose Node, app data, LM Studio, model, FFmpeg, speaker, and yt-dlp availability.
441
+
442
+ **Windows install reports `EBUSY` for `ffmpeg-static`**
443
+ - Close all active terminal windows running Node or Kiku. In a fresh PowerShell window:
444
+ ```powershell
445
+ npm uninstall -g kiku-agent
446
+ $stale = Join-Path (npm root -g) 'kiku-agent'
447
+ if (Test-Path $stale) { Remove-Item -Recurse -Force $stale }
448
+ npm cache verify
449
+ npm install -g kiku-agent
450
+ ```
451
+
452
+ **YouTube playback fails**
453
+ - Re-authenticate with `/login`, or point `KIKU_YT_COOKIES` / `KIKU_YT_BROWSER` at a valid session and `KIKU_YTDLP` at a working yt-dlp binary. Some regions/clients need `KIKU_YTDLP_CLIENT` set to `tv` or `ios`.
454
+
455
+ **Remote MCP returns 401 Unauthorized**
456
+ - Set `MCP_API_KEY` on the server and send `Authorization: Bearer <MCP_API_KEY>`. For browser clients, set `MCP_CORS_ORIGINS` to the allowed origins.
457
+
458
+ **Reports of missing or stale model after switching providers**
459
+ - The CLI automatically queries the provider's live `/models` endpoint at startup, on provider switches, and before one-shot queries, falling back gracefully to recommended active models if a configured model was retired.