vibes-plug 2.14.1 → 3.9.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 (151) hide show
  1. package/.claude/rules/vibes-plug-core.md +5 -0
  2. package/.cursor/rules/vibes-plug-core.mdc +7 -2
  3. package/.cursorrules +8 -2
  4. package/AGENTS.md +23 -2
  5. package/CHANGELOG.md +114 -0
  6. package/CLAUDE.md +10 -3
  7. package/README.md +216 -611
  8. package/bin/vibes.mjs +1104 -0
  9. package/package.json +11 -3
  10. package/plugin.json +4 -3
  11. package/scripts/check-anti-slop.mjs +53 -0
  12. package/scripts/install.js +3 -1
  13. package/scripts/update_skills.js +1 -1
  14. package/scripts/update_skills.mjs +86 -0
  15. package/scripts/validate-skills.mjs +111 -0
  16. package/skills/accessibility-testing-expert/SKILL.md +117 -116
  17. package/skills/affective-computing-emotion-ai/SKILL.md +83 -0
  18. package/skills/agentic-coding-workflow-expert/SKILL.md +297 -0
  19. package/skills/agentic-memory-architect/SKILL.md +52 -0
  20. package/skills/agentic-micro-economy-architect/SKILL.md +92 -0
  21. package/skills/ai-llm-integration-expert/SKILL.md +330 -194
  22. package/skills/ai-media-generation-expert/SKILL.md +173 -172
  23. package/skills/ai-prompt-engineering-expert/SKILL.md +204 -134
  24. package/skills/ai-safety-governance-expert/SKILL.md +223 -0
  25. package/skills/angular-expert/SKILL.md +149 -148
  26. package/skills/anti-slop/SKILL.md +134 -133
  27. package/skills/api-design-expert/SKILL.md +4 -3
  28. package/skills/api-gateway-proxy-expert/SKILL.md +3 -2
  29. package/skills/app-analyzer-optimizer/SKILL.md +4 -3
  30. package/skills/apple-ecosystem-expert/SKILL.md +6 -5
  31. package/skills/astro-framework-expert/SKILL.md +201 -200
  32. package/skills/async-queue-temporal-expert/SKILL.md +218 -217
  33. package/skills/authentication-identity-expert/SKILL.md +174 -173
  34. package/skills/autonomous-red-teamer/SKILL.md +338 -203
  35. package/skills/autonomous-tdd-debugger/SKILL.md +6 -5
  36. package/skills/biome-linter-formatter-expert/SKILL.md +90 -89
  37. package/skills/blockchain-web3-expert/SKILL.md +116 -115
  38. package/skills/brainstorming/SKILL.md +392 -377
  39. package/skills/browser-automation-expert/SKILL.md +260 -222
  40. package/skills/bun-runtime-expert/SKILL.md +5 -4
  41. package/skills/chatbot-messaging-expert/SKILL.md +115 -114
  42. package/skills/ci-cd-devops-architect/SKILL.md +3 -2
  43. package/skills/cloud-hosting-expert/SKILL.md +5 -4
  44. package/skills/coderabbit/SKILL.md +5 -4
  45. package/skills/compliance-gdpr-privacy-expert/SKILL.md +3 -2
  46. package/skills/composable-mach-architect/SKILL.md +338 -0
  47. package/skills/cron-scheduler-expert/SKILL.md +5 -4
  48. package/skills/data-pipeline-etl-expert/SKILL.md +3 -2
  49. package/skills/data-telemetry-expert/SKILL.md +5 -4
  50. package/skills/data-visualization-expert/SKILL.md +155 -154
  51. package/skills/database-orm-expert/SKILL.md +166 -165
  52. package/skills/deep-research-analyst/SKILL.md +182 -136
  53. package/skills/dependency-upgrade-migrator/SKILL.md +11 -10
  54. package/skills/design-system-architect/SKILL.md +4 -3
  55. package/skills/desktop-electron-expert/SKILL.md +129 -128
  56. package/skills/documentation-site-expert/SKILL.md +60 -59
  57. package/skills/doku-mcp-server/SKILL.md +5 -4
  58. package/skills/doku-payment-gateway/SKILL.md +250 -232
  59. package/skills/domain-driven-design-expert/SKILL.md +3 -2
  60. package/skills/e2e-testing-expert/SKILL.md +5 -4
  61. package/skills/ecommerce-expert/SKILL.md +88 -87
  62. package/skills/email-notification-expert/SKILL.md +5 -4
  63. package/skills/ephemeral-generative-ui-architect/SKILL.md +88 -0
  64. package/skills/error-resilience-expert/SKILL.md +14 -13
  65. package/skills/event-driven-architect/SKILL.md +5 -4
  66. package/skills/feature-flag-analytics-expert/SKILL.md +3 -2
  67. package/skills/file-upload-media-expert/SKILL.md +5 -4
  68. package/skills/firebase-security-expert/SKILL.md +5 -4
  69. package/skills/form-validation-expert/SKILL.md +7 -6
  70. package/skills/frontier-ai-models-expert/SKILL.md +116 -0
  71. package/skills/fullstack-expert/SKILL.md +185 -184
  72. package/skills/gemini-agent-booster/SKILL.md +248 -172
  73. package/skills/geospatial-maps-expert/SKILL.md +81 -80
  74. package/skills/global-a11y-i18n-expert/SKILL.md +5 -4
  75. package/skills/glsl-shader-expert/SKILL.md +191 -190
  76. package/skills/go-programming-expert/SKILL.md +5 -4
  77. package/skills/graph-rag-knowledge-expert/SKILL.md +201 -200
  78. package/skills/graphql-apollo-expert/SKILL.md +5 -4
  79. package/skills/headless-cms-expert/SKILL.md +182 -181
  80. package/skills/hig/SKILL.md +5 -4
  81. package/skills/js-backend-expert/SKILL.md +219 -218
  82. package/skills/legacy-code-translator/SKILL.md +6 -5
  83. package/skills/llm-finops-router/SKILL.md +52 -0
  84. package/skills/local-slm-edge-ai-expert/SKILL.md +168 -167
  85. package/skills/logging-error-tracking-expert/SKILL.md +5 -4
  86. package/skills/mcp-server-architect/SKILL.md +315 -307
  87. package/skills/micro-frontend-architect/SKILL.md +5 -4
  88. package/skills/mobile-expo-expert/SKILL.md +5 -4
  89. package/skills/modern-css-native-expert/SKILL.md +190 -189
  90. package/skills/monorepo-architect/SKILL.md +5 -4
  91. package/skills/mpa-orchestrator/SKILL.md +41 -4
  92. package/skills/multi-agent-orchestration/SKILL.md +388 -254
  93. package/skills/mvc-expert/SKILL.md +5 -4
  94. package/skills/n8n-automation-expert/SKILL.md +90 -89
  95. package/skills/nextjs-app-router-expert/SKILL.md +3 -2
  96. package/skills/openapi-swagger-codegen-expert/SKILL.md +4 -3
  97. package/skills/payment-gateway-expert/SKILL.md +131 -128
  98. package/skills/pdf-document-generation-expert/SKILL.md +92 -91
  99. package/skills/performance-web-vitals/SKILL.md +5 -4
  100. package/skills/post-quantum-crypto-migrator/SKILL.md +3 -2
  101. package/skills/prd-architect/SKILL.md +183 -182
  102. package/skills/proactive-background-watcher/SKILL.md +5 -4
  103. package/skills/production-ready-hardener/SKILL.md +10 -9
  104. package/skills/pwa-offline-first-expert/SKILL.md +227 -226
  105. package/skills/pydantic-ai-expert/SKILL.md +162 -161
  106. package/skills/python-programming-expert/SKILL.md +5 -4
  107. package/skills/rate-limit-abuse-prevention/SKILL.md +5 -4
  108. package/skills/realtime-collaboration-expert/SKILL.md +3 -2
  109. package/skills/rich-text-editor-expert/SKILL.md +178 -177
  110. package/skills/rust-programming-expert/SKILL.md +5 -4
  111. package/skills/saas-architect/SKILL.md +155 -154
  112. package/skills/saas-billing/SKILL.md +394 -382
  113. package/skills/saas-multi-tenant/SKILL.md +7 -6
  114. package/skills/scalability-clean-code/SKILL.md +5 -4
  115. package/skills/search-engine-expert/SKILL.md +90 -89
  116. package/skills/self-healing-cloud-orchestrator/SKILL.md +3 -2
  117. package/skills/senior-frontend/SKILL.md +14 -9
  118. package/skills/seo/SKILL.md +4 -4
  119. package/skills/session-memory-manager/SKILL.md +129 -128
  120. package/skills/solidjs-expert/SKILL.md +81 -80
  121. package/skills/spa-orchestrator/SKILL.md +5 -4
  122. package/skills/sse-websocket-streaming-expert/SKILL.md +3 -2
  123. package/skills/state-management-expert/SKILL.md +5 -4
  124. package/skills/supabase-security-expert/SKILL.md +5 -4
  125. package/skills/svelte-sveltekit-expert/SKILL.md +92 -91
  126. package/skills/svg-animation-motion-expert/SKILL.md +3 -2
  127. package/skills/synthetic-data-finetuning-expert/SKILL.md +156 -155
  128. package/skills/tailwind-expert/SKILL.md +62 -5
  129. package/skills/tanstack-query-expert/SKILL.md +5 -4
  130. package/skills/tauri-expert/SKILL.md +5 -4
  131. package/skills/typescript-expert/SKILL.md +5 -4
  132. package/skills/ui-ux-pro-max/SKILL.md +7 -6
  133. package/skills/vector-db-rag-expert/SKILL.md +209 -208
  134. package/skills/vercel-ai-sdk-expert/SKILL.md +226 -181
  135. package/skills/voice-ai-realtime-agent/SKILL.md +243 -242
  136. package/skills/vue-frontend-expert/SKILL.md +5 -4
  137. package/skills/wasm-edge-computing-expert/SKILL.md +3 -2
  138. package/skills/web-3d-graphics-expert/SKILL.md +314 -313
  139. package/skills/web-game-engine-expert/SKILL.md +330 -329
  140. package/skills/web-scraper/SKILL.md +158 -157
  141. package/skills/website-design-cloner/SKILL.md +5 -4
  142. package/skills/webxr-ar-vr-expert/SKILL.md +163 -162
  143. package/skills/wordpress-headless-expert/SKILL.md +145 -144
  144. package/skills/zero-tech-debt-auditor/SKILL.md +115 -0
  145. package/skills/zero-to-prod-orchestrator/SKILL.md +281 -229
  146. package/skills/zero-trust-secret-vault/SKILL.md +3 -2
  147. package/BLUEPRINT.md +0 -319
  148. package/skills/bootstrap-to-modern/SKILL.md +0 -94
  149. package/skills/multiple-entry-points/SKILL.md +0 -91
  150. package/skills/secure-fuzz-testing/SKILL.md +0 -207
  151. package/skills/visual-qa-vision-agent/SKILL.md +0 -71
@@ -1,194 +1,330 @@
1
- ---
2
- name: ai-llm-integration-expert
3
- version: "2.8.0"
4
- description: "Expert guide for integrating Large Language Models (LLMs), Model Context Protocol (MCP v1.x), hybrid reasoning models, RAG architecture, vector databases, and AI agents / Panduan ahli untuk integrasi LLM, Model Context Protocol (MCP), model hybrid reasoning, arsitektur RAG, vector database, dan agen AI."
5
- author: "Roedy Rustam"
6
- ---
7
-
8
- # AI & LLM Integration Expert (2026 Edition)
9
-
10
- [English](#english) | [Bahasa Indonesia](#bahasa-indonesia)
11
-
12
- ---
13
-
14
- <a name="english"></a>
15
- ## English
16
-
17
- ### Description
18
- Production-grade guidelines for integrating AI, Model Context Protocol (MCP), hybrid reasoning models, and Large Language Models (LLMs) into modern software architectures. Covers hybrid reasoning token streaming, Streamable HTTP MCP transports, agentic memory architectures, native context caching, RAG pipelines, and multi-model orchestration.
19
-
20
- ### Trigger Conditions
21
- - Integrating frontier reasoning models: Anthropic Claude 3.7 Sonnet (Hybrid/Extended Thinking), Google Gemini 3.8 Flash / 3.1 Pro (Thinking Mode), OpenAI o1 / o3 / o3-mini / GPT-4.5 / GPT-4o, DeepSeek-R1 / V3, or open-source weights (Llama 4, Qwen 2.5/3 Coder).
22
- - Implementing Model Context Protocol (MCP) server or client integrations with Streamable HTTP transport or MCP Sampling.
23
- - Building AI chatbots, copilots, or autonomous AI agent workflows (LangGraph, OpenAI Agents SDK, Google ADK, Mastra.ai, Vercel AI SDK 5.x/6.x).
24
- - Managing streaming reasoning tokens (`<think>` chunks) separately from final output in user interfaces.
25
- - Implementing hybrid RAG with vector databases (Supabase pgvector HNSW, Qdrant, Pinecone) and cross-encoder rerankers.
26
- - Building agentic memory systems (short-term, long-term semantic, episodic) using Mem0 or vector stores.
27
- - Implementing cost optimization with provider-native Context Caching (Gemini `cachedContent`, Anthropic ephemeral prompt cache, OpenAI prefix cache).
28
-
29
- ### Model Capability Matrix (2026)
30
-
31
- | Provider | Model | Context | Reasoning Type | Primary Strength |
32
- |---|---|---|---|---|
33
- | Anthropic | Claude 3.7 Sonnet | 200K | Hybrid Thinking (Standard + Extended) | Code generation, complex reasoning, Computer Use |
34
- | Anthropic | Claude 3.5 / 4 Opus | 200K | Deep Deliberation | Deep architectural synthesis, policy analysis |
35
- | Google | Gemini 3.8 Flash | 1M–2M | Flash Thinking (Configurable Budget) | Ultra-low latency, multimodal live, high-frequency loops |
36
- | Google | Gemini 3.1 / 3.5 Pro | 2M | Extended Reasoning | Needle-in-a-haystack, long-context repos, deep research |
37
- | OpenAI | o3 / o3-mini | 200K | Native Test-Time Reasoning | Math, competitive coding, formal logic verification |
38
- | OpenAI | GPT-4.5 / GPT-4o | 128K | Direct Instruction & Fast Tooling | Low-latency voice, structured JSON, tool-calling |
39
- | DeepSeek | DeepSeek-R1 | 128K | Open Reasoning (Distill & MoE) | State-of-the-art open weights reasoning, math, coding |
40
- | DeepSeek | DeepSeek-V3 | 128K | General Multimodal / Text | High throughput, extremely cost-efficient coding |
41
- | Qwen | Qwen 2.5 / 3 Coder | 128K | Open Source Code Specialist | Self-hosted coding agent, local copilot integration |
42
-
43
- ### Core Architecture Guidelines
44
-
45
- #### 1. Hybrid Reasoning & Streaming Token Handling
46
- Modern frontier models emit internal thinking/reasoning tokens during test-time compute:
47
- - **Thinking Token Separation**: Separate internal `<think>` or reasoning chunks from conversational output. Stream reasoning into collapsible UI accordion blocks while presenting clean output to the user.
48
- - **Vercel AI SDK 5.x/6.x Integration**:
49
- ```typescript
50
- import { streamText } from 'ai';
51
- import { anthropic } from '@ai-sdk/anthropic';
52
-
53
- const result = streamText({
54
- model: anthropic('claude-3-7-sonnet-20250219'),
55
- providerOptions: {
56
- anthropic: {
57
- thinking: { type: 'enabled', budgetTokens: 4096 },
58
- },
59
- },
60
- prompt: 'Refactor this distributed consensus engine...',
61
- });
62
-
63
- // Access reasoning stream alongside main text
64
- for await (const part of result.fullStream) {
65
- if (part.type === 'reasoning') {
66
- process.stdout.write(`[Thinking]: ${part.textDelta}`);
67
- } else if (part.type === 'text-delta') {
68
- process.stdout.write(part.textDelta);
69
- }
70
- }
71
- ```
72
-
73
- #### 2. Model Context Protocol (MCP) — Streamable HTTP & Sampling
74
- Standardize all agent-tool and agent-host communications using MCP specifications:
75
- - **Streamable HTTP Transport**: Modern cloud deployments use Streamable HTTP (bidirectional JSON-RPC streaming over HTTP POST/SSE hybrid) instead of fragile stdio connections.
76
- - **MCP Sampling**: Allow MCP servers to request LLM completions back from the host client, enabling nested agentic tools without distributing API keys to tool servers.
77
- - **Authorization & Security**: Enforce OAuth 2.1 scoped bearer tokens on remote MCP endpoints. Validate all incoming tool inputs using strict Zod schemas.
78
-
79
- #### 3. Agentic Memory Architecture
80
- Production AI agents require multi-layered memory:
81
- - **In-Context Working Memory**: Pass recent turn messages within the prompt window.
82
- - **Long-Term Semantic Memory**: Embed user preferences and facts using pgvector (HNSW index) or Qdrant; perform cosine similarity searches.
83
- - **Episodic Memory (Mem0 / MemGPT)**: Automatically synthesize session checkpoints and index past user decisions for human-like recall.
84
- - **Knowledge Graph Memory**: Maintain structured entity-relationship triples (using Graph DB or relational junction tables) for multi-hop relationship retrieval.
85
-
86
- #### 4. Advanced RAG & Late Chunking Pipeline
87
- Build high-precision RAG pipelines:
88
- 1. **Document Ingestion**: Chunk semantically (500–1000 tokens) with 10% overlap, or apply *Late Chunking* (chunking after full document contextual embedding).
89
- 2. **Embeddings**: Utilize `text-embedding-3-large`, `gemini-embedding-004`, or local `bge-large-en-v1.5`.
90
- 3. **Hybrid Search**: Combine dense vector cosine similarity with sparse BM25 / PostgreSQL `tsvector` queries.
91
- 4. **Cross-Encoder Reranking**: Reorder top-K candidates using Cohere Rerank 3 or FlashRank before feeding into the prompt.
92
- 5. **Context Window vs RAG Decision**: If document sets fit comfortably under 200k tokens and are queried repeatedly, prefer **Native Context Caching** over RAG chunking to eliminate retrieval boundary errors.
93
-
94
- #### 5. FinOps, Context Caching & Dynamic Model Routing
95
- - **Native Context Caching**: Store static system prompts or large codebases in cache (>32k tokens) to reduce costs by up to 90% (Anthropic ephemeral cache, OpenAI prefix cache, Gemini `cachedContent`).
96
- - **Dynamic Model Router**: Route queries based on complexity scoring (prompt length, required schema, reasoning requirements):
97
- ```typescript
98
- export function selectOptimalModel(promptLength: number, taskType: 'classification' | 'reasoning' | 'summary') {
99
- if (taskType === 'classification' || promptLength < 500) {
100
- return 'gemini-3.8-flash'; // High speed, minimal cost
101
- }
102
- return 'gemini-3.1-pro'; // Deep reasoning
103
- }
104
- ```
105
- - **Semantic Caching**: Hash query vector embeddings into Redis / vector DB to return cached completions for semantically identical questions before calling LLM APIs.
106
- - **Tenant Token Quotas**: Implement per-tenant token budgeting and alert thresholds to prevent cost overruns.
107
-
108
- #### 6. Structured Output & Guardrails
109
- - Utilize native Structured Outputs (`response_format: { type: "json_schema" }`) guaranteed by model token-level grammar masks.
110
- - Use Zod schemas to define tool parameters and final structured entities.
111
- - Implement rate limiting, circuit breakers, and semantic caching (Redis / Upstash vector cache) to prevent runaway recursive tool loops.
112
-
113
- ## Orchestration & Integration
114
- - **`mcp-server-architect`**: Delegate custom MCP server implementation, client consumption, schema definitions, and transport adapters.
115
- - **`multi-agent-orchestration`**: Delegate complex multi-agent state graphs, swarm workflows, and supervisor patterns.
116
- - **`gemini-agent-booster`**: Delegate Gemini 3.x long-context optimization, Multimodal Live API, and thinking budget controls.
117
- - **`ai-prompt-engineering-expert`**: Delegate advanced prompt design, few-shot calibration, automated Promptfoo evals, and system prompt testing.
118
- - **`vector-db-rag-expert`**: Delegate pgvector HNSW indexing and hybrid retrieval fine-tuning.
119
- - **`zero-to-prod-orchestrator`**: Executes this skill during Phase 4 architecture and implementation.
120
-
121
- ---
122
-
123
- <a name="bahasa-indonesia"></a>
124
- ## Bahasa Indonesia
125
-
126
- ### Deskripsi
127
- Panduan tingkat produksi untuk mengintegrasikan AI, Model Context Protocol (MCP), model hybrid reasoning, dan Large Language Models (LLM) ke dalam arsitektur perangkat lunak modern. Mencakup penanganan streaming token penalaran, transport MCP Streamable HTTP, arsitektur memori agentik, context caching native, pipeline RAG, dan orkestrasi multi-model.
128
-
129
- ### Kondisi Pemicu
130
- - Mengintegrasikan model frontier reasoning: Anthropic Claude 3.7 Sonnet (Hybrid/Extended Thinking), Google Gemini 3.8 Flash / 3.1 Pro (Thinking Mode), OpenAI o1 / o3 / o3-mini / GPT-4.5 / GPT-4o, DeepSeek-R1 / V3, atau bobot open-source (Llama 4, Qwen 2.5/3 Coder).
131
- - Mengimplementasikan server atau klien Model Context Protocol (MCP) dengan transport Streamable HTTP atau MCP Sampling.
132
- - Membangun chatbot AI, copilot, atau workflow agen otonom (LangGraph, OpenAI Agents SDK, Google ADK, Mastra.ai, Vercel AI SDK 5.x/6.x).
133
- - Mengelola streaming token penalaran (`<think>`) secara terpisah dari output akhir pada tampilan antarmuka pengguna.
134
- - Mengimplementasikan RAG hibrida dengan database vektor (Supabase pgvector HNSW, Qdrant, Pinecone) dan reranker cross-encoder.
135
- - Membangun sistem memori agentik (jangka pendek, semantik jangka panjang, episodik) menggunakan Mem0 atau vector store.
136
- - Menerapkan optimasi biaya dengan Context Caching native provider (Gemini `cachedContent`, Anthropic ephemeral prompt cache, OpenAI prefix cache).
137
-
138
- ### Matriks Kapabilitas Model (2026)
139
-
140
- | Provider | Model | Konteks | Tipe Penalaran | Keunggulan Utama |
141
- |---|---|---|---|---|
142
- | Anthropic | Claude 3.7 Sonnet | 200K | Hybrid Thinking (Standar + Diperpanjang) | Generasi kode, penalaran kompleks, Computer Use |
143
- | Anthropic | Claude 3.5 / 4 Opus | 200K | Deliberasi Mendalam | Sintesis arsitektur mendalam, analisis kebijakan |
144
- | Google | Gemini 3.8 Flash | 1M–2M | Flash Thinking (Budget Terkonfigurasi) | Latensi ultra-rendah, multimodal live, loop cepat |
145
- | Google | Gemini 3.1 / 3.5 Pro | 2M | Extended Reasoning | Needle-in-a-haystack, repo konteks panjang, riset |
146
- | OpenAI | o3 / o3-mini | 200K | Test-Time Reasoning Native | Matematika, competitive coding, verifikasi logika |
147
- | OpenAI | GPT-4.5 / GPT-4o | 128K | Instruksi Langsung & Tooling Cepat | Suara latensi rendah, JSON terstruktur, tool calling |
148
- | DeepSeek | DeepSeek-R1 | 128K | Open Reasoning (Distill & MoE) | Penalaran open weights terdepan, matematika, koding |
149
- | DeepSeek | DeepSeek-V3 | 128K | Teks & Multimodal Umum | Throughput tinggi, sangat hemat biaya untuk coding |
150
- | Qwen | Qwen 2.5 / 3 Coder | 128K | Spesialis Kode Open Source | Agen coding mandiri / self-hosted, copilot lokal |
151
-
152
- ### Panduan Arsitektur Inti
153
-
154
- #### 1. Hybrid Reasoning & Penanganan Token Streaming
155
- Model frontier modern menghasilkan token pemikiran (*thinking tokens*) selama proses penalaran:
156
- - **Pemisahan Token Pemikiran**: Pisahkan blok `<think>` dari output teks akhir. Alirkan proses pemikiran ke dalam accordion UI yang dapat dibuka/tutup, sementara output utama disajikan dengan bersih kepada user.
157
- - **Integrasi Vercel AI SDK 5.x/6.x**: Gunakan event listener `reasoning` pada stream untuk menangkap proses pemikiran model secara terpisah dari `text-delta`.
158
-
159
- #### 2. Model Context Protocol (MCP) — Streamable HTTP & Sampling
160
- Standarisasi seluruh komunikasi agen-ke-tool dan agen-ke-host menggunakan spesifikasi MCP:
161
- - **Streamable HTTP Transport**: Standar cloud modern yang mendukung streaming dua arah JSON-RPC via HTTP POST/SSE hybrid tanpa ketergantungan koneksi stdio lokal.
162
- - **MCP Sampling**: Memberikan izin kepada server MCP untuk meminta inferensi LLM kembali ke klien host, memungkinkan alat agentik modular tanpa membagikan API key sensitif.
163
- - **Keamanan & Otorisasi**: Wajibkan bearer token berbasis OAuth 2.1 pada endpoint MCP publik dan validasi skema input dengan Zod.
164
-
165
- #### 3. Arsitektur Memori Agentik
166
- - **Memori Kerja In-Context**: Teruskan histori interaksi terbaru di jendela konteks.
167
- - **Memori Semantik Jangka Panjang**: Simpan fakta dan preferensi pengguna di pgvector (indeks HNSW) atau Qdrant dengan pencarian kesamaan kosinus.
168
- - **Memori Episodik (Mem0 / MemGPT)**: Sintesiskan ringkasan sesi secara berkala agar agen memiliki daya ingat historis jangka panjang.
169
- - **Memori Graph Pengetahuan**: Hubungkan entitas relasional dalam basis data graf untuk kueri multi-langkah (*multi-hop reasoning*).
170
-
171
- #### 4. Pipeline RAG Lanjutan & Late Chunking
172
- 1. **Ingesti Dokumen**: Bagi dokumen secara semantik (500–1000 token, 10% overlap) atau gunakan metode *Late Chunking*.
173
- 2. **Embedding**: Gunakan `text-embedding-3-large` atau `gemini-embedding-004`.
174
- 3. **Pencarian Hibrida**: Kombinasikan dense vector cosine similarity dengan sparse keyword BM25 / PostgreSQL full-text search.
175
- 4. **Cross-Encoder Reranking**: Susun ulang kandidat terbaik menggunakan Cohere Rerank 3 atau FlashRank sebelum diteruskan ke system prompt.
176
- 5. **Keputusan Cache vs RAG**: Jika dokumen stabil dan berada di bawah 200k token, utamakan **Context Caching Native** daripada RAG chunking untuk menghindari hilangnya konteks di perbatasan potongan teks.
177
-
178
- #### 5. FinOps, Context Caching & Routing Model Dinamis
179
- - **Context Caching Native**: Simpan prompt sistem atau repositori besar di cache (>32k token) via API `cachedContent` Gemini, ephemeral cache Anthropic, atau prefix cache OpenAI untuk menghemat hingga 90% biaya.
180
- - **Router Model Dinamis**: Arahkan kueri secara cerdas (tugas klasifikasi/parsing ke Flash, penalaran mendalam ke Pro/Opus).
181
- - **Semantic Caching**: Simpan embedding kueri di Redis / Vector DB untuk menyajikan jawaban cache pada pertanyaan identik tanpa memanggil ulang API LLM.
182
- - **Kuota & Anggaran Token**: Terapkan batas konsumsi token harian per pengguna/penyewa guna mencegah pembengkakan biaya.
183
-
184
- #### 6. Output Terstruktur & Guardrails
185
- - Manfaatkan mode Structured Outputs native model dengan skema Zod untuk menjamin integritas JSON.
186
- - Terapkan rate limiting, circuit breaker, dan semantic caching (Redis / Upstash) untuk mencegah pemanggilan tool secara rekursif tak berujung.
187
-
188
- ## Integrasi Orkestrasi
189
- - **`mcp-server-architect`**: Delegasikan pembuatan server MCP kustom, konsumsi klien, definisi skema, dan transport adapter.
190
- - **`multi-agent-orchestration`**: Delegasikan alur kerja graph multi-agen, topologi swarm, dan pattern supervisor.
191
- - **`gemini-agent-booster`**: Delegasikan optimasi long-context Gemini 3.x, Multimodal Live API, dan kontrol thinking budget.
192
- - **`ai-prompt-engineering-expert`**: Delegasikan desain prompt lanjutan, kalibrasi few-shot, evaluasi Promptfoo, dan pengujian prompt.
193
- - **`vector-db-rag-expert`**: Delegasikan tuning indeks HNSW pgvector dan pencarian hibrida.
194
- - **`zero-to-prod-orchestrator`**: Mengeksekusi skill ini pada Fase 4 perancangan arsitektur dan implementasi.
1
+ ---
2
+ name: ai-llm-integration-expert
3
+ description: "Expert guide for integrating Large Language Models (LLMs), Model Context Protocol (MCP v1.x), hybrid reasoning models, RAG architecture, vector databases, and AI agents / Panduan ahli untuk integrasi LLM, Model Context Protocol (MCP), model hybrid reasoning, arsitektur RAG, vector database, dan agen AI."
4
+ author: "Roedy Rustam"
5
+ version: "3.0.0"
6
+ ---
7
+
8
+ # AI & LLM Integration Expert (2026 Edition)
9
+
10
+ [English](#english) | [Bahasa Indonesia](#bahasa-indonesia)
11
+
12
+ ---
13
+
14
+ <a name="english"></a>
15
+ ## English
16
+
17
+ ### Description
18
+ Production-grade guidelines for integrating AI, Model Context Protocol (MCP), hybrid reasoning models, and Large Language Models (LLMs) into modern software architectures. Covers hybrid reasoning token streaming, Streamable HTTP MCP transports, agentic memory architectures, native context caching, RAG pipelines, and multi-model orchestration.
19
+
20
+ ### Trigger Conditions
21
+ - Integrating frontier reasoning models: Anthropic Claude 3.7 Sonnet (Hybrid/Extended Thinking), Google Gemini 3.8 Flash / 3.1 Pro (Thinking Mode), OpenAI o1 / o3 / o3-mini / GPT-4.5 / GPT-4o, DeepSeek-R1 / V3, or open-source weights (Llama 4, Qwen 2.5/3 Coder).
22
+ - Implementing Model Context Protocol (MCP) server or client integrations with Streamable HTTP transport or MCP Sampling.
23
+ - Building AI chatbots, copilots, or autonomous AI agent workflows (LangGraph, OpenAI Agents SDK, Google ADK, Mastra.ai, Vercel AI SDK 5.x/6.x).
24
+ - Managing streaming reasoning tokens (`<think>` chunks) separately from final output in user interfaces.
25
+ - Implementing hybrid RAG with vector databases (Supabase pgvector HNSW, Qdrant, Pinecone) and cross-encoder rerankers.
26
+ - Building agentic memory systems (short-term, long-term semantic, episodic) using Mem0 or vector stores.
27
+ - Implementing cost optimization with provider-native Context Caching (Gemini `cachedContent`, Anthropic ephemeral prompt cache, OpenAI prefix cache).
28
+
29
+ ### Model Capability Matrix (2026)
30
+
31
+ | Provider | Model | Context | Reasoning Type | Primary Strength |
32
+ |---|---|---|---|---|
33
+ | Anthropic | Claude 3.7 Sonnet | 200K | Hybrid Thinking (Standard + Extended) | Code generation, complex reasoning, Computer Use |
34
+ | Anthropic | Claude 3.5 / 4 Opus | 200K | Deep Deliberation | Deep architectural synthesis, policy analysis |
35
+ | Google | Gemini 3.8 Flash | 1M–2M | Flash Thinking (Configurable Budget) | Ultra-low latency, multimodal live, high-frequency loops |
36
+ | Google | Gemini 3.1 / 3.5 Pro | 2M | Extended Reasoning | Needle-in-a-haystack, long-context repos, deep research |
37
+ | OpenAI | o3 / o3-mini | 200K | Native Test-Time Reasoning | Math, competitive coding, formal logic verification |
38
+ | OpenAI | GPT-4.5 / GPT-4o | 128K | Direct Instruction & Fast Tooling | Low-latency voice, structured JSON, tool-calling |
39
+ | DeepSeek | DeepSeek-R1 | 128K | Open Reasoning (Distill & MoE) | State-of-the-art open weights reasoning, math, coding |
40
+ | DeepSeek | DeepSeek-V3 | 128K | General Multimodal / Text | High throughput, extremely cost-efficient coding |
41
+ | Qwen | Qwen 2.5 / 3 Coder | 128K | Open Source Code Specialist | Self-hosted coding agent, local copilot integration |
42
+
43
+ ### Core Architecture Guidelines
44
+
45
+ #### 1. Hybrid Reasoning & Streaming Token Handling
46
+ Modern frontier models emit internal thinking/reasoning tokens during test-time compute:
47
+ - **Thinking Token Separation**: Separate internal `<think>` or reasoning chunks from conversational output. Stream reasoning into collapsible UI accordion blocks while presenting clean output to the user.
48
+ - **Vercel AI SDK 5.x/6.x Integration**:
49
+ ```typescript
50
+ import { streamText } from 'ai';
51
+ import { anthropic } from '@ai-sdk/anthropic';
52
+
53
+ const result = streamText({
54
+ model: anthropic('claude-3-7-sonnet-20250219'),
55
+ providerOptions: {
56
+ anthropic: {
57
+ thinking: { type: 'enabled', budgetTokens: 4096 },
58
+ },
59
+ },
60
+ prompt: 'Refactor this distributed consensus engine...',
61
+ });
62
+
63
+ // Access reasoning stream alongside main text
64
+ for await (const part of result.fullStream) {
65
+ if (part.type === 'reasoning') {
66
+ process.stdout.write(`[Thinking]: ${part.textDelta}`);
67
+ } else if (part.type === 'text-delta') {
68
+ process.stdout.write(part.textDelta);
69
+ }
70
+ }
71
+ ```
72
+ - **Thinking Token Overflow Handling**: If `max_tokens` cuts off reasoning before output generation (e.g., `<think>` block doesn't close), detect missing closing tags and dynamically increase budget/retry or append a forceful closing prompt block.
73
+ - **Multi-Provider Thinking Configuration**: Use Anthropic `thinking` parameter (`budgetTokens`), Google `thinkingConfig` (set to `true` with budget logic), and OpenAI reasoning tokens (via `reasoning_effort: "high"`).
74
+
75
+ #### 2. Model Context Protocol (MCP) — Streamable HTTP & Sampling
76
+ Standardize all agent-tool and agent-host communications using MCP specifications:
77
+ - **Streamable HTTP Transport**: Modern cloud deployments use Streamable HTTP (bidirectional JSON-RPC streaming over HTTP POST/SSE hybrid) instead of fragile stdio connections.
78
+ - **MCP Sampling**: Allow MCP servers to request LLM completions back from the host client, enabling nested agentic tools without distributing API keys to tool servers.
79
+ - **Authorization & Security**: Enforce OAuth 2.1 scoped bearer tokens on remote MCP endpoints. Validate all incoming tool inputs using strict Zod schemas.
80
+
81
+ #### 3. Agentic Memory Architecture
82
+ Production AI agents require multi-layered memory:
83
+ - **In-Context Working Memory**: Pass recent turn messages within the prompt window.
84
+ - **Long-Term Semantic Memory**: Embed user preferences and facts using pgvector (HNSW index) or Qdrant; perform cosine similarity searches.
85
+ - **Episodic Memory (Mem0 / Letta (formerly MemGPT))**: Automatically synthesize session checkpoints and index past user decisions for human-like recall.
86
+ - **Knowledge Graph Memory**: Maintain structured entity-relationship triples (using Graph DB or relational junction tables) for multi-hop relationship retrieval.
87
+
88
+ #### 4. Advanced RAG & Late Chunking Pipeline
89
+ Build high-precision RAG pipelines:
90
+ 1. **Document Ingestion**: Chunk semantically (500–1000 tokens) with 10% overlap, or apply *Late Chunking* (chunking after full document contextual embedding).
91
+ 2. **Embeddings**: Utilize `text-embedding-3-large`, `gemini-embedding-004`, or local `bge-large-en-v1.5`.
92
+ 3. **Hybrid Search**: Combine dense vector cosine similarity with sparse BM25 / PostgreSQL `tsvector` queries.
93
+ 4. **Cross-Encoder Reranking**: Reorder top-K candidates using Cohere Rerank 3 or FlashRank before feeding into the prompt.
94
+ 5. **Context Window vs RAG Decision**: If document sets fit comfortably under 200k tokens and are queried repeatedly, prefer **Native Context Caching** over RAG chunking to eliminate retrieval boundary errors.
95
+
96
+ #### 5. Continuous Multimodal Streaming (Astra Paradigm)
97
+ - **Real-Time Bidirectional Streaming**: Use WebSocket or WebRTC to stream audio and video frames continuously.
98
+ - **Gemini Multimodal Live API**: Implement bidirectional audio streams utilizing `BidiGenerateContent` with `setup`, `clientContent`, and `serverContent` events.
99
+ - **OpenAI Realtime API**: Connect to `wss://api.openai.com/v1/realtime`, manage session configuration, and process audio delta events.
100
+ - **Low Latency Target**: Optimize network and processing paths to maintain sub-200ms response latency.
101
+ - **Live Perception Loop Architecture**: Continuously ingest frames, perform reasoning, execute actions, and loop back.
102
+ ```typescript
103
+ // Basic Gemini Multimodal Live streaming setup
104
+ const ws = new WebSocket('wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent');
105
+ ws.onopen = () => {
106
+ ws.send(JSON.stringify({ setup: { model: 'models/gemini-2.0-flash-exp' } }));
107
+ };
108
+ ws.onmessage = (event) => {
109
+ const response = JSON.parse(event.data);
110
+ if (response.serverContent) {
111
+ console.log('Received audio/text delta:', response.serverContent);
112
+ }
113
+ };
114
+ ```
115
+
116
+ #### 6. Computer-Using Agents (CUA)
117
+ - **CUA Architectural Pattern**: Screen capture → Vision model analysis → Action execution (mouse/keyboard) → Verification loop.
118
+ - **GUI Automation (OpenAI Operator style)**: Use vision-language models to drive complete OS or browser sessions autonomously.
119
+ - **Screen Grounding**: Output exact coordinates (`click at x,y`) based on visual element detection instead of DOM parsing.
120
+ - **Multi-Hour Execution**: Ensure robust checkpoint and resume states for tasks spanning hours.
121
+ - **Safety Guardrails**: Implement confirmation gates for destructive actions, run in sandboxed execution environments, and build rollback capabilities.
122
+ ```typescript
123
+ // CUA action loop with Playwright + Vision model
124
+ const screenshot = await page.screenshot();
125
+ const action = await getVisionModelAction(screenshot); // Returns { action: 'click', x: 100, y: 200 }
126
+ if (action.action === 'click') {
127
+ await page.mouse.click(action.x, action.y);
128
+ }
129
+ ```
130
+
131
+ #### 7. Episodic & Spatio-Temporal Memory
132
+ - **Memory Hierarchy**: Working memory (context window) → Semantic memory (vector DB) → Episodic memory (temporal event store) → Knowledge graph memory.
133
+ - **Spatio-Temporal Awareness**: Track object locations across video frames and sequence temporal events accurately.
134
+ - **Persistent Episodic Memory**: Integrate with Letta (formerly MemGPT) to simulate infinite context through paging episodic records.
135
+ - **Mem0 Integration**: Automatically extract memory snippets and retrieve relevant past context based on user queries.
136
+ - **Memory Consolidation**: Periodically compress short-term observations into long-term summary memories.
137
+ ```typescript
138
+ // Episodic memory storage using Mem0
139
+ import { Mem0 } from 'mem0';
140
+ const mem0 = new Mem0({ apiKey: 'YOUR_API_KEY' });
141
+ await mem0.add("User prefers dark mode and uses VSCode.", { user_id: "u123" });
142
+ const context = await mem0.search("IDE preferences", { user_id: "u123" });
143
+ ```
144
+
145
+ #### 8. Narrative Simulation & Character AI (Fable Paradigm)
146
+ - **Multi-Agent Narrative Simulation**: Build architectures inspired by Fable Studio's Showrunner/SHOW-1 for emergent storylines.
147
+ - **Character Personality Encoding**: Encode Big Five personality traits and emotional valence vectors into the system prompt.
148
+ - **State Management**: Persist character states across sessions to maintain long-term memory and relationship development.
149
+ - **World-State Consistency**: Enforce consistency using a shared state graph that all agents read and write to.
150
+ - **Episodic Generation**: Utilize an autonomous pipeline to generate coherent narrative episodes.
151
+ - **Dialogue Coherence**: Constrain inter-agent dialogue to align with narrative constraints and personality logic.
152
+ ```typescript
153
+ // Character agent with personality state
154
+ const characterState = {
155
+ name: 'Elara',
156
+ traits: { openness: 0.8, conscientiousness: 0.9, extraversion: 0.3, agreeableness: 0.7, neuroticism: 0.2 },
157
+ mood: 'contemplative'
158
+ };
159
+ const prompt = `You are ${characterState.name}. Traits: ${JSON.stringify(characterState.traits)}. Current mood: ${characterState.mood}. Respond to the user.`;
160
+ ```
161
+
162
+ #### 9. FinOps, Context Caching & Dynamic Model Routing
163
+ - **Native Context Caching**: Store static system prompts or large codebases in cache (>32k tokens) to reduce costs by up to 90% (Anthropic ephemeral cache, OpenAI prefix cache, Gemini `cachedContent`).
164
+ - **Dynamic Model Router**: Route queries based on complexity scoring (prompt length, required schema, reasoning requirements):
165
+ ```typescript
166
+ export function selectOptimalModel(promptLength: number, taskType: 'classification' | 'reasoning' | 'summary') {
167
+ if (taskType === 'classification' || promptLength < 500) {
168
+ return 'gemini-3.8-flash'; // High speed, minimal cost
169
+ }
170
+ return 'gemini-3.1-pro'; // Deep reasoning
171
+ }
172
+ ```
173
+ - **Semantic Caching**: Hash query vector embeddings into Redis / vector DB to return cached completions for semantically identical questions before calling LLM APIs.
174
+ - **Tenant Token Quotas**: Implement per-tenant token budgeting and alert thresholds to prevent cost overruns.
175
+
176
+ #### 10. Structured Output & Guardrails
177
+ - Utilize native Structured Outputs (`response_format: { type: "json_schema" }`) guaranteed by model token-level grammar masks.
178
+ - Use Zod schemas to define tool parameters and final structured entities.
179
+ - Implement rate limiting, circuit breakers, and semantic caching (Redis / Upstash vector cache) to prevent runaway recursive tool loops.
180
+
181
+ ## Orchestration & Integration
182
+ - **`mcp-server-architect`**: Delegate custom MCP server implementation, client consumption, schema definitions, and transport adapters.
183
+ - **`multi-agent-orchestration`**: Delegate complex multi-agent state graphs, swarm workflows, and supervisor patterns.
184
+ - **`gemini-agent-booster`**: Delegate Gemini 3.x long-context optimization, Multimodal Live API, and thinking budget controls.
185
+ - **`ai-prompt-engineering-expert`**: Delegate advanced prompt design, few-shot calibration, automated Promptfoo evals, and system prompt testing.
186
+ - **`vector-db-rag-expert`**: Delegate pgvector HNSW indexing and hybrid retrieval fine-tuning.
187
+ - **`zero-to-prod-orchestrator`**: Executes this skill during Phase 4 architecture and implementation.
188
+
189
+ ---
190
+
191
+ <a name="bahasa-indonesia"></a>
192
+ ## Bahasa Indonesia
193
+
194
+ ### Deskripsi
195
+ Panduan tingkat produksi untuk mengintegrasikan AI, Model Context Protocol (MCP), model hybrid reasoning, dan Large Language Models (LLM) ke dalam arsitektur perangkat lunak modern. Mencakup penanganan streaming token penalaran, transport MCP Streamable HTTP, arsitektur memori agentik, context caching native, pipeline RAG, dan orkestrasi multi-model.
196
+
197
+ ### Kondisi Pemicu
198
+ - Mengintegrasikan model frontier reasoning: Anthropic Claude 3.7 Sonnet (Hybrid/Extended Thinking), Google Gemini 3.8 Flash / 3.1 Pro (Thinking Mode), OpenAI o1 / o3 / o3-mini / GPT-4.5 / GPT-4o, DeepSeek-R1 / V3, atau bobot open-source (Llama 4, Qwen 2.5/3 Coder).
199
+ - Mengimplementasikan server atau klien Model Context Protocol (MCP) dengan transport Streamable HTTP atau MCP Sampling.
200
+ - Membangun chatbot AI, copilot, atau workflow agen otonom (LangGraph, OpenAI Agents SDK, Google ADK, Mastra.ai, Vercel AI SDK 5.x/6.x).
201
+ - Mengelola streaming token penalaran (`<think>`) secara terpisah dari output akhir pada tampilan antarmuka pengguna.
202
+ - Mengimplementasikan RAG hibrida dengan database vektor (Supabase pgvector HNSW, Qdrant, Pinecone) dan reranker cross-encoder.
203
+ - Membangun sistem memori agentik (jangka pendek, semantik jangka panjang, episodik) menggunakan Mem0 atau vector store.
204
+ - Menerapkan optimasi biaya dengan Context Caching native provider (Gemini `cachedContent`, Anthropic ephemeral prompt cache, OpenAI prefix cache).
205
+
206
+ ### Matriks Kapabilitas Model (2026)
207
+
208
+ | Provider | Model | Konteks | Tipe Penalaran | Keunggulan Utama |
209
+ |---|---|---|---|---|
210
+ | Anthropic | Claude 3.7 Sonnet | 200K | Hybrid Thinking (Standar + Diperpanjang) | Generasi kode, penalaran kompleks, Computer Use |
211
+ | Anthropic | Claude 3.5 / 4 Opus | 200K | Deliberasi Mendalam | Sintesis arsitektur mendalam, analisis kebijakan |
212
+ | Google | Gemini 3.8 Flash | 1M–2M | Flash Thinking (Budget Terkonfigurasi) | Latensi ultra-rendah, multimodal live, loop cepat |
213
+ | Google | Gemini 3.1 / 3.5 Pro | 2M | Extended Reasoning | Needle-in-a-haystack, repo konteks panjang, riset |
214
+ | OpenAI | o3 / o3-mini | 200K | Test-Time Reasoning Native | Matematika, competitive coding, verifikasi logika |
215
+ | OpenAI | GPT-4.5 / GPT-4o | 128K | Instruksi Langsung & Tooling Cepat | Suara latensi rendah, JSON terstruktur, tool calling |
216
+ | DeepSeek | DeepSeek-R1 | 128K | Open Reasoning (Distill & MoE) | Penalaran open weights terdepan, matematika, koding |
217
+ | DeepSeek | DeepSeek-V3 | 128K | Teks & Multimodal Umum | Throughput tinggi, sangat hemat biaya untuk coding |
218
+ | Qwen | Qwen 2.5 / 3 Coder | 128K | Spesialis Kode Open Source | Agen coding mandiri / self-hosted, copilot lokal |
219
+
220
+ ### Panduan Arsitektur Inti
221
+
222
+ #### 1. Hybrid Reasoning & Penanganan Token Streaming
223
+ Model frontier modern menghasilkan token pemikiran (*thinking tokens*) selama proses penalaran:
224
+ - **Pemisahan Token Pemikiran**: Pisahkan blok `<think>` dari output teks akhir. Alirkan proses pemikiran ke dalam accordion UI yang dapat dibuka/tutup, sementara output utama disajikan dengan bersih kepada user.
225
+ - **Integrasi Vercel AI SDK 5.x/6.x**: Gunakan event listener `reasoning` pada stream untuk menangkap proses pemikiran model secara terpisah dari `text-delta`.
226
+ - **Penanganan Overflow Token Pemikiran**: Jika `max_tokens` memotong proses penalaran sebelum teks output dimulai (blok `<think>` belum tertutup), deteksi tag yang hilang dan secara dinamis tingkatkan anggaran token atau tambahkan blok prompt penutup paksa.
227
+ - **Konfigurasi Thinking Multi-Provider**: Gunakan parameter `thinking` Anthropic (`budgetTokens`), `thinkingConfig` Google (diaktifkan dengan logika anggaran), dan reasoning token OpenAI (via `reasoning_effort: "high"`).
228
+
229
+ #### 2. Model Context Protocol (MCP) — Streamable HTTP & Sampling
230
+ Standarisasi seluruh komunikasi agen-ke-tool dan agen-ke-host menggunakan spesifikasi MCP:
231
+ - **Streamable HTTP Transport**: Standar cloud modern yang mendukung streaming dua arah JSON-RPC via HTTP POST/SSE hybrid tanpa ketergantungan koneksi stdio lokal.
232
+ - **MCP Sampling**: Memberikan izin kepada server MCP untuk meminta inferensi LLM kembali ke klien host, memungkinkan alat agentik modular tanpa membagikan API key sensitif.
233
+ - **Keamanan & Otorisasi**: Wajibkan bearer token berbasis OAuth 2.1 pada endpoint MCP publik dan validasi skema input dengan Zod.
234
+
235
+ #### 3. Arsitektur Memori Agentik
236
+ - **Memori Kerja In-Context**: Teruskan histori interaksi terbaru di jendela konteks.
237
+ - **Memori Semantik Jangka Panjang**: Simpan fakta dan preferensi pengguna di pgvector (indeks HNSW) atau Qdrant dengan pencarian kesamaan kosinus.
238
+ - **Memori Episodik (Mem0 / Letta (formerly MemGPT))**: Sintesiskan ringkasan sesi secara berkala agar agen memiliki daya ingat historis jangka panjang.
239
+ - **Memori Graph Pengetahuan**: Hubungkan entitas relasional dalam basis data graf untuk kueri multi-langkah (*multi-hop reasoning*).
240
+
241
+ #### 4. Pipeline RAG Lanjutan & Late Chunking
242
+ 1. **Ingesti Dokumen**: Bagi dokumen secara semantik (500–1000 token, 10% overlap) atau gunakan metode *Late Chunking*.
243
+ 2. **Embedding**: Gunakan `text-embedding-3-large` atau `gemini-embedding-004`.
244
+ 3. **Pencarian Hibrida**: Kombinasikan dense vector cosine similarity dengan sparse keyword BM25 / PostgreSQL full-text search.
245
+ 4. **Cross-Encoder Reranking**: Susun ulang kandidat terbaik menggunakan Cohere Rerank 3 atau FlashRank sebelum diteruskan ke system prompt.
246
+ 5. **Keputusan Cache vs RAG**: Jika dokumen stabil dan berada di bawah 200k token, utamakan **Context Caching Native** daripada RAG chunking untuk menghindari hilangnya konteks di perbatasan potongan teks.
247
+
248
+ #### 5. Streaming Multimodal Berkelanjutan (Paradigma Astra)
249
+ - **Streaming Real-Time Dua Arah**: Gunakan WebSocket atau WebRTC untuk melakukan streaming audio dan frame video secara berkelanjutan.
250
+ - **Gemini Multimodal Live API**: Implementasikan stream audio dua arah memanfaatkan `BidiGenerateContent` dengan event `setup`, `clientContent`, dan `serverContent`.
251
+ - **OpenAI Realtime API**: Hubungkan ke `wss://api.openai.com/v1/realtime`, kelola konfigurasi sesi, dan proses event delta audio.
252
+ - **Target Latensi Rendah**: Optimasi jaringan dan jalur pemrosesan untuk mempertahankan latensi respons di bawah 200ms.
253
+ - **Arsitektur Loop Persepsi Langsung (Live Perception Loop)**: Ingesti frame terus-menerus, lakukan penalaran, eksekusi aksi, dan loop kembali.
254
+ ```typescript
255
+ // Setup dasar streaming Gemini Multimodal Live
256
+ const ws = new WebSocket('wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent');
257
+ ws.onopen = () => {
258
+ ws.send(JSON.stringify({ setup: { model: 'models/gemini-2.0-flash-exp' } }));
259
+ };
260
+ ws.onmessage = (event) => {
261
+ const response = JSON.parse(event.data);
262
+ if (response.serverContent) {
263
+ console.log('Menerima delta teks/audio:', response.serverContent);
264
+ }
265
+ };
266
+ ```
267
+
268
+ #### 6. Agen Pengguna Komputer (Computer-Using Agents / CUA)
269
+ - **Pola Arsitektural CUA**: Tangkapan layar (Screen capture) → Analisis model vision → Eksekusi aksi (mouse/keyboard) → Loop verifikasi.
270
+ - **Otomatisasi GUI (Gaya OpenAI Operator)**: Gunakan model vision-language untuk menggerakkan seluruh sesi OS atau browser secara otonom.
271
+ - **Screen Grounding**: Hasilkan koordinat pasti (`click at x,y`) berdasarkan deteksi elemen visual daripada parsing DOM.
272
+ - **Eksekusi Multi-Jam**: Pastikan adanya status checkpoint dan resume yang kuat untuk tugas yang berlangsung berjam-jam.
273
+ - **Guardrails Keselamatan**: Implementasikan gerbang konfirmasi untuk tindakan destruktif, jalankan di lingkungan sandbox, dan bangun kemampuan rollback.
274
+ ```typescript
275
+ // Loop aksi CUA dengan Playwright + Vision model
276
+ const screenshot = await page.screenshot();
277
+ const action = await getVisionModelAction(screenshot); // Mengembalikan { action: 'click', x: 100, y: 200 }
278
+ if (action.action === 'click') {
279
+ await page.mouse.click(action.x, action.y);
280
+ }
281
+ ```
282
+
283
+ #### 7. Memori Episodik & Spasio-Temporal
284
+ - **Hierarki Memori**: Memori kerja (context window) → Memori semantik (vector DB) → Memori episodik (penyimpanan event temporal) → Memori knowledge graph.
285
+ - **Kesadaran Spasio-Temporal (Spatio-Temporal Awareness)**: Lacak lokasi objek di seluruh frame video dan urutkan event temporal dengan akurat.
286
+ - **Memori Episodik Persisten**: Integrasikan dengan Letta (sebelumnya MemGPT) untuk mensimulasikan konteks tak terbatas melalui paging catatan episodik.
287
+ - **Integrasi Mem0**: Ekstrak cuplikan memori secara otomatis dan ambil konteks masa lalu yang relevan berdasarkan kueri pengguna.
288
+ - **Konsolidasi Memori**: Kompres observasi jangka pendek secara berkala menjadi memori ringkasan jangka panjang.
289
+ ```typescript
290
+ // Penyimpanan memori episodik menggunakan Mem0
291
+ import { Mem0 } from 'mem0';
292
+ const mem0 = new Mem0({ apiKey: 'YOUR_API_KEY' });
293
+ await mem0.add("Pengguna lebih suka dark mode dan menggunakan VSCode.", { user_id: "u123" });
294
+ const context = await mem0.search("Preferensi IDE", { user_id: "u123" });
295
+ ```
296
+
297
+ #### 8. Simulasi Naratif & Character AI (Paradigma Fable)
298
+ - **Simulasi Naratif Multi-Agen**: Bangun arsitektur yang terinspirasi dari Showrunner/SHOW-1 karya Fable Studio untuk alur cerita emergen.
299
+ - **Enkode Kepribadian Karakter**: Enkode sifat kepribadian Big Five dan vektor valensi emosional ke dalam system prompt.
300
+ - **Manajemen State**: Pertahankan state karakter di seluruh sesi untuk mempertahankan memori jangka panjang dan pengembangan hubungan.
301
+ - **Konsistensi World-State**: Tegakkan konsistensi menggunakan shared state graph yang dibaca dan ditulis oleh semua agen.
302
+ - **Generasi Episodik**: Gunakan pipeline otonom untuk menghasilkan episode naratif yang koheren.
303
+ - **Koherensi Dialog**: Batasi dialog antar-agen agar selaras dengan batasan naratif dan logika kepribadian.
304
+ ```typescript
305
+ // Agen karakter dengan state kepribadian
306
+ const characterState = {
307
+ name: 'Elara',
308
+ traits: { openness: 0.8, conscientiousness: 0.9, extraversion: 0.3, agreeableness: 0.7, neuroticism: 0.2 },
309
+ mood: 'kontemplatif'
310
+ };
311
+ const prompt = `Anda adalah ${characterState.name}. Sifat: ${JSON.stringify(characterState.traits)}. Suasana hati saat ini: ${characterState.mood}. Tanggapi pengguna.`;
312
+ ```
313
+
314
+ #### 9. FinOps, Context Caching & Routing Model Dinamis
315
+ - **Context Caching Native**: Simpan prompt sistem atau repositori besar di cache (>32k token) via API `cachedContent` Gemini, ephemeral cache Anthropic, atau prefix cache OpenAI untuk menghemat hingga 90% biaya.
316
+ - **Router Model Dinamis**: Arahkan kueri secara cerdas (tugas klasifikasi/parsing ke Flash, penalaran mendalam ke Pro/Opus).
317
+ - **Semantic Caching**: Simpan embedding kueri di Redis / Vector DB untuk menyajikan jawaban cache pada pertanyaan identik tanpa memanggil ulang API LLM.
318
+ - **Kuota & Anggaran Token**: Terapkan batas konsumsi token harian per pengguna/penyewa guna mencegah pembengkakan biaya.
319
+
320
+ #### 10. Output Terstruktur & Guardrails
321
+ - Manfaatkan mode Structured Outputs native model dengan skema Zod untuk menjamin integritas JSON.
322
+ - Terapkan rate limiting, circuit breaker, dan semantic caching (Redis / Upstash) untuk mencegah pemanggilan tool secara rekursif tak berujung.
323
+
324
+ ## Integrasi Orkestrasi
325
+ - **`mcp-server-architect`**: Delegasikan pembuatan server MCP kustom, konsumsi klien, definisi skema, dan transport adapter.
326
+ - **`multi-agent-orchestration`**: Delegasikan alur kerja graph multi-agen, topologi swarm, dan pattern supervisor.
327
+ - **`gemini-agent-booster`**: Delegasikan optimasi long-context Gemini 3.x, Multimodal Live API, dan kontrol thinking budget.
328
+ - **`ai-prompt-engineering-expert`**: Delegasikan desain prompt lanjutan, kalibrasi few-shot, evaluasi Promptfoo, dan pengujian prompt.
329
+ - **`vector-db-rag-expert`**: Delegasikan tuning indeks HNSW pgvector dan pencarian hibrida.
330
+ - **`zero-to-prod-orchestrator`**: Mengeksekusi skill ini pada Fase 4 perancangan arsitektur dan implementasi.