- name
- dzmm-builder
- description
- Comprehensive skill for building, debugging, and optimizing DZMM.AI applications. Use this skill when users request creating interactive web apps on the DZMM platform, need guidance on DZMM API usage, or require help with existing DZMM applications. Covers AI-driven chatbots, visual novels, dating sims, content generators, RPG games, content platforms, and visual effect systems. Includes state management games, message management (reroll/edit/delete), multi-opening systems, rich text rendering, modular prompt engineering, resource reuse strategies, React/Vue to DZMM migration, and responsive mobile design.
# DZMM Builder
## Overview
Build AI-driven interactive web applications on the DZMM.AI platform using specialized knowledge, complete examples, and reusable code patterns. This skill provides comprehensive support for creating single-file HTML applications that leverage streaming AI conversations, cloud key-value storage, and browser effect systems.
## When to Use This Skill
Invoke this skill when users:
- Request creating a new DZMM application ("Build me a DZMM chatbot", "Create an AI story generator", "Make a dating sim game", "Build a social media content generator", "Create a visual novel", "Build an interactive fiction game")
- Ask questions about DZMM API usage ("How do I use dzmm.completions?", "How does KV storage work?", "How to parse structured AI output?", "How to use chat API for branching stories?", "How to implement streaming AI responses?")
- Need help debugging DZMM applications ("My DZMM app returns 400 error", "AI responses are not displaying", "State not persisting", "DZMM API not initializing")
- Want to optimize existing DZMM apps (performance, user experience, architecture improvements, mobile responsiveness, reduce token usage)
- Ask about "fourth wall breaking" effects or browser control from AI
- Need guidance on state management in games (stats, mood, relationships, dynamic UI)
- Want to integrate Markdown rendering or rich text formatting (nested structures, dialogue quotes, options buttons)
- Request configuration/setup UI for applications
- Need branching narrative systems (Galgame save/load, multi-route stories, choice history tracking)
- Ask about available models and their performance characteristics
- **Request message management features** ("How to add reroll/regenerate?", "How to let users edit messages?", "How to delete conversation branches?")
- **Want multi-opening/multi-scenario systems** ("How to add multiple starting scenes?", "How to switch between different story routes?")
- **Need help migrating from React/Vue to DZMM** ("How to migrate my app to DZMM?", "What's the DZMM equivalent of useState?", "Can I use React/TypeScript with DZMM?", "How to build DZMM apps with modern frameworks?", "vite-plugin-singlefile for DZMM", "My DZMM app has sandbox errors", "Form submission blocked in DZMM", "localStorage not working in DZMM", "HTTP 400 error with DZMM API", "maxTokens limit exceeded")
- **Ask about resource management** ("How to load images/audio in DZMM?", "Should I use URLs or embed resources?")
## Core Capabilities
### 1. Application Generation
Generate complete, single-file HTML applications for the DZMM platform based on user requirements.
**Approach:**
1. Clarify the application type and core features
2. Select an appropriate architecture pattern (stateless generator, stateful dialogue, or layered cache platform)
3. Use example templates from `assets/examples/` as foundation
4. Customize for specific requirements
5. Test the complete flow (initialization → AI call → display)
**Architecture Patterns:**
**Stateless Generator** - For one-shot content generation:
- Example: Translator, text summarizer, content creator, social media post generator
- No conversation history or state persistence
- Simplest architecture, fastest development
- Optional: Integrate marked.js for Markdown rendering
- Reference: See `assets/examples/小红书文案.html` for minimal implementation
- Code snippets: `references/code-snippets.md` section 2
**State Management Game** - For interactive games with dynamic variables:
- Example: Dating sims, RPG games, decision-based narratives
- Multiple state variables (stats, mood, time, relationships)
- Structured AI output parsing (###STATE/###END format)
- Configuration UI for game initialization
- State-driven UI updates (progress bars, backgrounds, effects)
- Auto-save with KV storage
- Reference: See `assets/examples/恋爱游戏.html` for complete implementation
**Stateful Dialogue System** - For multi-turn conversations:
- Example: Chatbots, interactive stories, Q&A systems
- Maintains conversation history
- Uses Alpine.store for state management
- Persists state with KV storage
- Reference: See `assets/examples/dungeon-adventure.html` and `assets/examples/horror-story.html`
**Layered Cache Platform** - For content communities:
- Example: Forums, story libraries, content platforms
- Two-tier caching (list cache + detail cache)
- On-demand content generation
- Concurrent request locking
- Reference: See `assets/examples/贴吧.html` for full implementation
**Visual Novel / Galgame System** - For narrative-driven interactive fiction:
- Example: Visual novels, interactive stories, AI-driven narrative games
- Multi-opening scene system with dynamic switching
- Rich text rendering with placeholder technique (handles nested structures)
- Message management (reroll, edit, delete with context preservation)
- Multi-slot save/load system with preview
- Modular prompt system (main prompt + character + guidance + emphasis)
- Responsive mobile design with compressed UI
- Reference: See yoshiwara-chronicles project for complete implementation
- Key features: XML-structured prompts, <last_input> emphasis, streaming AI responses
### 2. API Integration Guidance
Provide detailed guidance on using DZMM's specialized APIs.
**Core APIs:**
**window.dzmm.completions()** - Streaming AI generation:
```javascript
await window.dzmm.completions(
{
model: 'nalang-turbo-0826' | 'nalang-medium-0826' |
'nalang-max-0826' | 'nalang-xl-0826' |
'nalang-max-0826-16k' | 'nalang-xl-0826-16k',
messages: [{ role: 'user' | 'assistant', content: string }],
maxTokens: number // Optional, 200-3000, default 1000
},
(newContent, done) => {
// newContent is cumulative, not incremental
// done is true when generation completes
}
);
```
**window.dzmm.chat** - Tree-structured conversation storage (⭐ NEW):
```javascript
// Insert messages into conversation tree (supports branching storylines)
const result = await window.dzmm.chat.insert(parentId, [
{ role: 'user', content: 'Player choice' },
{ role: 'assistant', content: 'Story response' }
]);
const newMessageIds = result.ids; // Array of new message IDs
// Get message details (with parent/children relationships)
const messages = await window.dzmm.chat.list(['msg-123', 'msg-124']);
// Returns: [{ id, role, content, timestamp, parent, children }, ...]
// Get complete conversation timeline
const timeline = await window.dzmm.chat.timeline(messageId);
const fullHistory = await window.dzmm.chat.list(timeline);
```
**Use cases:** Galgame save/load systems, branching narratives, multi-route stories, interactive fiction with choice history.
**window.dzmm.kv** - Cloud key-value storage:
```javascript
// Save (auto-serializes objects)
await window.dzmm.kv.put(key, value);
// Load
const result = await window.dzmm.kv.get(key);
if (result.value) {
const data = result.value;
}
// Delete
await window.dzmm.kv.delete(key);
```
**Limits:** Keys ≤256 chars, values ≤1MB recommended. Development mode: data lost on refresh. Production: persistent.
**Critical Requirements:**
- Must wait for `dzmm:ready` event before any API calls
- Only `user` and `assistant` roles supported (no `system`)
- Limit conversation history to ≤20 messages to avoid token overflow
- maxTokens range: 200-3000, default 1000
- Concurrent requests: ≤3 recommended
- Use versioned keys for KV storage (e.g., `app_state_v1`)
**Reference:** Consult `references/developer-guide.md` sections 2-3 for complete API documentation and `references/code-snippets.md` sections 1-3 for ready-to-use code patterns.
### 3. Effect System Implementation
Implement "fourth wall breaking" effects where AI can control the user's browser environment.
**Effect Categories:**
**Visual Effects:**
- Light control (dimming, darkness, flickering)
- Screen shake (low/medium/high intensity)
- Glitch effects
- Color filters (blood, blur, etc.)
**Audio Effects:**
- Programmatic sound generation (beeps, drones, heartbeats)
- Web Audio API without external files
- Ambient and tension-building sounds
**Dynamic Elements:**
- Particle systems (dust, blood, explosions)
- Jumpscare popups
- Element manipulation
**Implementation Pattern:**
```javascript
// 1. AI outputs special instructions
const aiPrompt = `When the user says "turn off lights", output:
###EFFECT
{"action":"lights","params":{"state":"off"}}
###END`;
// 2. Parse and execute
const effectMatch = content.match(/###EFFECT\s*({[\s\S]*?})\s*###END/);
if (effectMatch) {
const effect = JSON.parse(effectMatch[1]);
executeEffect(effect);
// Remove instruction from display
content = content.replace(/###EFFECT[\s\S]*?###END/, '').trim();
}
// 3. Effect executor
function executeEffect(effect) {
switch(effect.action) {
case 'lights':
document.body.classList.add(`lights-${effect.params.state}`);
break;
// ... more effects
}
}
```
**Reference:** See `assets/examples/horror-story.html` for complete effect system with CSS animations, Web Audio, and Canvas particles.
### 4. Debugging and Optimization
Diagnose and fix common DZMM application issues.
**Common Issues:**
**HTTP 400 Errors:**
- Cause: Using `role: 'system'` in messages (not supported)
- Fix: Convert system prompts to first `user` message or maintain in frontend variables
- Cause: Messages array contains undefined/null values
- Fix: Validate and sanitize messages before sending
**No Response from AI:**
- Cause: API not ready yet
- Fix: Ensure `dzmm:ready` event is awaited before any API calls
**Context Overflow:**
- Cause: Too many messages or overly long content
- Fix: Slice messages array to last 10-20 items, truncate individual messages to 2000 chars
**State Not Persisting:**
- Cause: KV key naming conflicts or version mismatch
- Fix: Use versioned keys with unique identifiers
**Form Submission Blocked (Public Release Only):**
- Cause: DZMM public release uses iframe sandbox without `allow-forms` permission
- Error: `Blocked form submission to '' because the form's frame is sandboxed`
- Fix: Replace `<form>` with `<div>`, use `@click` instead of `@submit.prevent`
- Example:
```html
<!-- ❌ WRONG: Will fail in public release -->
<form @submit.prevent="handleSubmit()">
<button type="submit">Submit</button>
</form>
<!-- ✅ CORRECT: Works in all environments -->
<div>
<button type="button" @click="handleSubmit()">Submit</button>
</div>
```
- Note: This only affects public release, not development mode or workshop preview
**Performance Optimization:**
- Debounce user input to reduce API calls
- Implement two-tier caching for content-heavy apps
- Use concurrent request locks to prevent duplicate API calls
- Limit conversation history proactively
**Reference:** Consult `references/developer-guide.md` section "常见问题" for comprehensive troubleshooting guide.
### 5. Code Patterns and Snippets
Provide reusable, production-ready code patterns for common DZMM tasks.
**Available Patterns:**
1. Initialization and API readiness (dual detection with timeout)
2. AI completions (basic, multi-turn, streaming with real-time display)
3. KV storage operations (save, load, delete, multi-slot, batch operations)
4. Chat API operations (branching narratives, save/load, timeline retrieval)
5. Instruction parsing systems (JSON, XML, ###STATE format)
6. Alpine.js state management (local and global stores)
7. Visual effect systems (CSS animations, particles, audio)
8. Error handling and structured logging (retry with exponential backoff)
9. Utility functions (debounce, sanitize, scroll control)
10. Prompt templates (structured output, XML hierarchy, emphasis sections)
11. Complete application templates
12. **Rich text rendering** (placeholder technique for nested structures)
13. **Message management** (reroll, edit, delete with context preservation)
14. **Multi-opening system** (scene switching with state management)
15. **Resource management** (URL-based asset loading, preloading)
16. **Modular prompt system** (main + character + guidance + emphasis)
17. **Responsive layout patterns** (mobile-first with Tailwind breakpoints)
**Usage:** Reference `references/code-snippets.md` for copy-paste ready code snippets organized by category. All snippets are tested and can be used directly or with minimal modifications.
**New Visual Novel Patterns (from yoshiwara-chronicles):**
- Rich text parser with placeholder technique
- Message reroll/edit/delete functions
- Opening scene switcher with confirmation
- Multi-slot save system with preview extraction
- Streaming AI response with auto-scroll
- XML-structured prompt builder
- Resource manager for external assets
## Workflow Guide
### For New Applications
1. **Clarify Requirements**
- Determine application type (chatbot, game, content platform, etc.)
- Identify core features and interactions
- Choose architecture pattern
2. **Select Template**
- Browse `assets/examples/` for similar applications:
- `小红书文案.html` - Simple content generator, Markdown rendering
- `恋爱游戏.html` - Dating sim, multi-variable state management
- `horror-story.html` - Effect system, immersive experience
- `dungeon-adventure.html` - Turn-based game, state management
- `neon-gomoku.html` - AI opponent, game logic
- `贴吧.html` - Content platform, two-tier caching
3. **Build Application**
- Start with HTML structure and Alpine.js integration
- Implement DZMM API initialization (wait for `dzmm:ready`)
- Add AI completions with appropriate model selection
- Implement state management and KV storage if needed
- Add visual effects or advanced features as required
4. **Test and Refine**
- Test initialization and API readiness
- Verify AI responses and parsing
- Check state persistence across page reloads
- Optimize performance (history limits, debouncing)
### For Debugging Existing Applications
1. **Identify the Issue**
- Review error messages and console logs
- Check network requests in browser DevTools
- Verify API readiness timing
2. **Diagnose Root Cause**
- Cross-reference with common issues in `references/developer-guide.md`
- Check message format compliance (only `user`/`assistant`)
- Validate conversation history length
3. **Apply Fix**
- Use code patterns from `references/code-snippets.md`
- Add error handling if missing
- Implement validation for user inputs and API responses
4. **Optimize**
- Add performance improvements (caching, debouncing)
- Improve user experience (loading states, error messages)
- Enhance code maintainability (structured logging, modularity)
### For Migrating React/Vue Applications to DZMM
**Two Approaches Available:**
#### Approach A: Keep React/Vue Framework (Recommended for Large Projects)
Use modern build tools to maintain component-based development, then bundle to single HTML.
**Tech Stack**: React + TypeScript + Vite + vite-plugin-singlefile
**Workflow**:
1. **Setup**: `npm create vite@latest my-app -- --template react-ts`
2. **Install Plugin**: `npm install -D vite-plugin-singlefile`
3. **Configure Vite**: Add plugin for single-file build mode
4. **Develop**: Keep existing React components structure
5. **Build**: `npm run build:single` → generates standalone HTML
6. **Deploy**: Upload to DZMM platform
**Key Considerations**:
- ✅ Keep TypeScript type safety and component modularity
- ✅ Hot reload during development
- ✅ Rich ecosystem (shadcn/ui, React Router, etc.)
- ⚠️ Handle sandbox restrictions (localStorage, form submission)
- ⚠️ Enforce maxTokens limits (200-3000)
- ⚠️ Prevent consecutive same-role messages in API calls
**Critical Fixes**:
- **localStorage**: Implement fallback to memory storage
- **Forms**: Replace `<form>` with `<div>` + button onClick
- **maxTokens**: Never exceed 3000 (API returns HTTP 400)
- **Messages**: Merge emphasis into last user message to avoid consecutive roles
Ver en GitHub