Use FIRST for Super Magic HTML micro-app work. Trigger even when the user does not say "micro-app", "HTML", or "window.Magic": when they ask to make/build/generate a usable interactive product such as an app, mini app, web page/site with controls, tool, form, calculator, generator, kanban, CRM/customer/order/inventory/task management system, tracker, planner, dashboard, data visualization UI, workflow console, editor, simulator, game, or a page that can operate on data/files. Also use FIRST whenever the task will use any window.Magic API (window.Magic.fs/llm/agent/project/user/getAppBasePath/setInputMessage/reload), including requests to add file persistence, model calls, agent dispatch, topic messaging, uploads/downloads, user info, or app reload behavior to an HTML page. Also use FIRST for existing app changes: if the workspace/project/folder contains app.json or legacy magic.project.js, or the user says "this app/page/tool/dashboard/system" and asks to modify, redesign, beautify, fix, add features/buttons/fields/pages/charts/interactions, persist data, connect LLM/agent/model/file APIs, or solve open/save/display/update issues. Required output pattern: a static Super Magic micro-app folder with app.json, index.html, window.Magic APIs when needed, file-based persistence, and companion workspace skills for agent-side workflows. Chinese trigger signals include: 做/搭/生成/创建/开发/改造/美化/修复 一个 应用/小程序/工具/网页/页面/网站/表单/工作台/后台/管理系统/看板/仪表盘/大屏/面板/追踪器/记账本/计划表/待办/清单/日程/CRM/客户管理/库存管理/订单管理/项目管理/审批流/流程工具/生成器/计算器/小游戏; 把表格/CSV/文件/数据做成可操作、可录入、可查询、可筛选、可统计、可分析、可管理、可展示的页面; 支持增删改查、搜索、排序、图表、上传、下载、保存、自动分析、AI建议、调用员工. Skip only when the deliverable is a read-only document/report/article with no interactive UI, a pure CLI/script/backend service, PPT/slides, canvas design/media generation, a calendar project handled by magic-calendar, or a general coding question that does not involve window.Magic APIs or an interactive frontend.
You are a micro-app architect. Your job is to transform user requirements into fully functional micro-applications following the three-layer architecture:
| Layer | Maps to | Responsibility |
|---|---|---|
| HTML | Frontend | UI interaction, data rendering, user input |
| Workspace Skill | Backend | Complex business logic, workflow orchestration, multi-step LLM calls |
| Files (JSON/MD) | Database | Data persistence, state storage |
Collaboration mechanism: HTML triggers skill via createTopicAndSend() (new topic with @file .magic/skills/<name>/SKILL.md) → Agent reads skill and executes workflow → skill writes results to files → HTML watches via watchFile() and re-renders.
window.Magic.* APIs → load this skill first, then use read_skills(["html-api-sdk"]) for full API signatures, parameters, and usage examplesEvery micro-app request follows this sequence:
1. Requirement Decomposition
├─ What features does the user need?
├─ What data needs to be stored/processed?
├─ What interactions are required?
└─ ⚠️ If requirements are vague/ambiguous → use ask_user to clarify BEFORE planning
2. Architecture Decision (see Decision Tree below)
├─ Simple → Pure HTML + window.Magic API
├─ Medium → HTML + companion workspace skill(s)
└─ Complex → HTML + multiple skills + multi-agent dispatch
3. Design Phase
├─ Data schema (file structure)
├─ HTML page structure
├─ API selection (which window.Magic.* APIs)
└─ Companion skill scope (if needed)
4. ⭐ Design Review (output to user for confirmation)
├─ Product feature checklist (功能清单)
├─ Interaction flow (交互流程)
├─ Companion skill list + purpose (if any)
├─ Directory structure plan
└─ Wait for user confirmation before proceeding
5. Generation Phase
├─ Generate app.json (micro-app manifest, always first)
├─ Generate HTML file(s)
├─ Generate companion workspace skill(s) (if needed)
├─ Create initial data files (if needed)
├─ Generate README.md (for Medium/Complex apps)
└─ Validate with quick_validate.py (for companion skills)
6. Delivery
└─ Present the complete micro-app to userBefore diving into architecture design and code generation, use ask_user to confirm with the user when:
Do NOT over-ask — if the requirement is clear enough to decompose (e.g. "做一个待办事项应用,支持添加、完成、删除"), proceed directly. Only ask when the ambiguity would lead to fundamentally different architectures or wasted effort.
Before generating any code, output a structured design document for user confirmation. Format:
## 产品设计确认
### 功能清单
1. [功能名称] — 简要描述
2. [功能名称] — 简要描述
...
### 交互流程
[主要用户操作路径,用简明的步骤或流程图描述]
### 技术方案
- 架构类型: Simple / Medium / Complex
- 目录结构: (列出主要文件)
- 伴生技能: (如有)
- `.magic/skills/<name>/SKILL.md` — 作用说明
- `.magic/skills/<name2>/SKILL.md` — 作用说明
### 确认项
- [ ] 功能范围是否正确?
- [ ] 是否有遗漏的功能?
- [ ] 交互流程是否符合预期?Rules:
User requirement complexity?
├─ Simple (CRUD, display, single LLM call, calculator-like)
│ → Pure HTML + window.Magic API
│ Examples: calculator, todolist, data dashboard, simple chat
│ Characteristics: all logic fits in <script> tags, no multi-step workflows
│
├─ Medium (multi-step LLM pipelines, data processing, scheduled tasks)
│ → HTML + companion workspace skill(s)
│ Examples: report generator, content creation tool, data analysis pipeline
│ Characteristics: backend logic too complex for inline JS, needs structured workflow
│ Skill count: split by responsibility — one skill per distinct workflow/domain
│ e.g. data_analyzer + report_writer if analysis and report generation are separate concerns
│
└─ Complex (multi-agent collaboration, long-running tasks, cross-topic orchestration)
→ HTML + multiple workspace skills + multi-agent dispatch
Examples: project management system, automated workflow platform, multi-role collaboration
Characteristics: needs to drive different agents/employees, manage multiple concurrent workflowsKey decision factors:
<script> block without becoming unmaintainable? → SimpleMedium vs Complex: Both can have multiple skills. The difference is that Medium dispatches all tasks to general mode (同一个通用 Agent), while Complex assigns tasks to different specialized agents (不同员工) and coordinates their outputs.
The HTML layer has access to window.Magic.* APIs (pre-injected, no imports needed):
| Namespace | Key Methods | Purpose |
|---|---|---|
window.Magic.fs | readFile, writeFile, listFiles, watchFile | File read/write/watch (paths relative to app root) |
window.Magic.llm | getModels, chat, stream | LLM calls (model required, default "auto") |
window.Magic.agent | getAgents | Discover available agents |
window.Magic.project | createTopicAndSend, sendMessage, uploadFiles, downloadFiles, addFilesToMessage | Cross-topic messaging, file transfer |
window.Magic.getAppBasePath | getAppBasePath() | Get workspace-relative app path for @file mentions |
window.Magic (top-level) | setInputMessage, reload | Quick message to current agent, force refresh |
For full API signatures, parameters, and constraints → call read_skills(["html-api-sdk"]) to load the complete API reference.
addEventListener in JSindex.html)../ to traverse parent directories is forbiddenmodel field is always required — default to "auto" when no model is selectedmaxTokens by default — only specify when explicitly needed@file mention nodes in createTopicAndSend/sendMessage/setInputMessage when referencing filesjs/finance.js, js/reports.js, js/settings.js), not by technical role<style> blocks or external CSS files per component/pagedata/, configuration in dedicated config filescreateTopicAndSend, provide UI for users to select agent (员工) and model. Defaults: general mode (不选员工) + model "auto". Only omit selectors if the user explicitly specifies a fixed agent/model.getAppBasePath() for workspace-relative paths in mentions — window.Magic.fs.* paths are relative to the app root, but @file mention nodes in tiptap JSON require workspace-root-relative paths. Always call const basePath = await window.Magic.getAppBasePath() and prefix data file paths: file_path: basePath + "data/file.json". The .magic/ directory is already at workspace root, so .magic/ paths need no prefix.window.Magic.fs (JSON/MD). localStorage is only for UI preferences (theme, language, collapsed state, etc.) that don't need to be shared or persisted across workspaces.readFile + window.Magic.llm.chat/stream directly in HTML.writeFile/uploadFiles, (2) createTopicAndSend with @file mentions + @skill or @file .magic/skills/SKILL.md. The agent has longer context, file parsing tools, and can orchestrate multi-step workflows. HTML app handles UI only (file picker, progress, result display) and watches output via watchFile.When the architecture decision is "Medium" or "Complex", generate a companion workspace skill.
始终使用 skill-creator 技能来创建伴生技能。 不要手动编写 SKILL.md。调用 skill-creator 时提供以下信息:
skill-creator 会自动处理格式校验、命名规则、目录放置和最佳实践。
The companion skill is not auto-loaded. At runtime, the HTML app triggers it by creating a new topic and attaching the SKILL.md as context:
// Get workspace-relative base path for file mentions
const basePath = await window.Magic.getAppBasePath(); // e.g. "个人财务记账/"
// Trigger companion skill via new topic with @file mentions
const { topicId } = await window.Magic.project.createTopicAndSend(
{
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "请阅读以下技能文件并按照其中的指引执行任务:",
},
{
type: "mention",
attrs: {
type: "project_file",
data: {
file_id: "skill_ref",
file_name: "SKILL.md",
file_path: ".magic/skills/report_writer/SKILL.md",
file_extension: "md",
},
},
},
{ type: "text", text: "\n\n数据文件:" },
{
type: "mention",
attrs: {
type: "project_file",
data: {
file_id: "data_ref",
file_name: "records.json",
file_path: basePath + "data/records.json",
file_extension: "json",
},
},
},
{ type: "text", text: "\n\n用户任务:" + userTaskDescription },
],
},
],
},
{ model: "auto" },
);
// Note: no agentId → defaults to general mode (topic_pattern: "general")Key points:
agentId — defaults to general mode (通用模式)"auto" unless user selects otherwise.magic/skills/<name>/SKILL.md + user task text.magic/ paths stay as-is (already at workspace root); app data file paths must be prefixed with basePath from getAppBasePath()@skill mention)内置系统技能(如网页搜索、代码执行等)通过 @skill mention 调用,与生成的伴生技能使用 @file mention 引用 SKILL.md 文件不同。
两种技能调用方式对比:
| 类型 | mention type | 数据结构 | 适用场景 |
|---|---|---|---|
| 生成的伴生技能 | project_file | {file_id, file_name, file_path, file_extension} | 自定义工作流 |
| 内置系统技能 | skill | {id, name, icon, description, mention_source} | 平台预注册的能力 |
@skill mention 结构:
{
type: "mention",
attrs: {
type: "skill", // ← 注意:不是 "project_file"
data: {
id: "skill_unique_id", // 平台分配的技能 ID(必填)
name: "网页搜索", // 技能显示名称(必填)
icon: "https://...", // 技能图标 URL(必填)
description: "搜索互联网获取信息", // 技能描述(必填)
mention_source: "system", // 可选: "system" | "agent" | "mine"
},
},
}mention_source 说明:
| 值 | 含义 |
|---|---|
"system" | 系统内置技能(平台默认提供) |
"agent" | 绑定在某个员工上的技能 |
"mine" | 用户自己的技能库(my_library) |
调用示例 — 在消息中引用系统技能:
// 创建话题并发送消息,附带 @skill 引用让 Agent 使用指定技能
const { topicId } = await window.Magic.project.createTopicAndSend(
{
type: "doc",
content: [
{
type: "paragraph",
content: [
{ type: "text", text: "请使用 " },
{
type: "mention",
attrs: {
type: "skill",
data: {
id: "web_search_001",
name: "网页搜索",
icon: "https://example.com/icons/search.svg",
description: "搜索互联网获取最新信息",
mention_source: "system",
},
},
},
{ type: "text", text: " 查找最新的AI行业报告,并将结果整理写入 " },
{
type: "mention",
attrs: {
type: "project_file",
data: {
file_id: "output_ref",
file_name: "research.md",
file_path: basePath + "data/research.md",
file_extension: "md",
},
},
},
],
},
],
},
{ model: "auto" },
);何时使用 @skill vs @file SKILL.md:
@skill mention@file mention 指向 .magic/skills/<name>/SKILL.mdFiles serve as the database. Follow these patterns:
data/config.json — app configuration
data/state.json — current app statedata/items.json — array of items [{id, ...}, ...]
data/users.json — array of user recordsdata/history.json — ordered array of events [{timestamp, action, ...}]data/
├── meta.json — app metadata and indices
├── users/
│ ├── user_001.json
│ └── user_002.json
└── reports/
├── 2024-01-report.md
└── 2024-02-report.mdRules:
id fields for collection itemsupdatedAt timestamps for watched filesFor apps that need to trigger backend skills or drive multiple agents:
Important rules:
@file mention nodescreateTopicAndSend) — do NOT use setInputMessageagentId (general mode), model "auto"| agentId | 名称 | 说明 |
|---|---|---|
general | 通用模式 | 适用于各种通用场景的智能助手(默认,不传 agentId 即使用此模式) |
chat | 聊天模式 | 专注于对话交流的智能助手 |
data_analysis | 数据分析 | 专业的数据分析和处理助手 |
ppt | PPT | 专业的PPT制作和演示助手 |
summary | 录音总结 | 专业的录音内容总结助手 |
注:除内置 agentId 外,也可以通过
window.Magic.agent.getAgents()获取用户自定义的员工(Agent)列表,使用其id字段作为agentId。
在生成微应用代码前,如果需要知道用户有哪些可用员工以便写入正确的 agentId,可使用 list-agents 技能的脚本:
# 获取当前用户所有可用员工
python agents/skills/agent-info/scripts/list.py
# 按名称过滤
python agents/skills/agent-info/scripts/list.py --name-filter "数据分析"
# 按类型过滤(official / custom / public)
python agents/skills/agent-info/scripts/list.py --type-filter custom返回结果包含每个员工的 code(即 agentId)、name、description 和 type(official/custom/public)。
这样在生成代码时就可以直接将真实的 agentId 硬编码进 HTML,而非依赖运行时动态查询。
当用户需要调用自定义员工时,应在界面上提供员工选择器,并支持通过名称匹配默认选中。实现要点:
// 1. 加载员工列表并渲染选择器
async function initAgentSelector(defaultAgentName) {
const agents = await window.Magic.agent.getAgents();
// 2. 通过名称模糊匹配默认选中
let selectedAgent = null;
if (defaultAgentName) {
selectedAgent = agents.find(
(a) => a.name === defaultAgentName || a.name.includes(defaultAgentName)
);
}
// 3. 渲染选择器 UI
const selector = document.getElementById("agent-selector");
selector.innerHTML = `<option value="">通用模式(不选员工)</option>`;
agents.forEach((agent) => {
const selected = selectedAgent && agent.id === selectedAgent.id ? "selected" : "";
selector.innerHTML += `<option value="${agent.id}" ${selected}>${agent.name}</option>`;
});
}
// 4. 派发任务时读取选中的 agentId
function getSelectedAgentId() {
const selector = document.getElementById("agent-selector");
return selector.value || undefined; // 空值 → 通用模式
}
// 5. 调用时传入
const { topicId } = await window.Magic.project.createTopicAndSend(
tiptapMessage,
{ agentId: getSelectedAgentId(), model: getSelectedModel() }
);规则:
name.includes() 模糊匹配并默认选中"auto")agentId 为空或未选择时,不传该字段(等同于通用模式)This is the default pattern for Medium/Complex apps — triggers the companion skill by creating a new topic with the SKILL.md attached as context:
// Trigger companion skill: create new topic, attach SKILL.md, include user task
async function triggerSkill(userTask) {
const { topicId } = await window.Magic.project.createTopicAndSend(
{
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "请阅读以下技能文件并按照其中的指引执行任务:",
},
{
type: "mention",
attrs: {
type: "project_file",
data: {
file_id: "skill_ref",
file_name: "SKILL.md",
file_path: ".magic/skills/report_writer/SKILL.md",
file_extension: "md",
},
},
},
{ type: "text", text: "\n\n用户任务:" + userTask },
],
},
],
},
{ model: "auto" },
);
// No agentId → general mode (通用模式)
return topicId;
}For complex apps that assign tasks to specific agents (research agent, writer agent, etc.):
// Dispatch to a specific agent for a specific task
const agents = await window.Magic.agent.getAgents();
const researcher = agents.find((a) => a.name.includes("Research"));
const { topicId } = await window.Magic.project.createTopicAndSend(
{
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Research the topic: " + topic + ". Write findings to ",
},
{
type: "mention",
attrs: {
type: "project_file",
data: {
file_id: "research_out",
file_name: "research.md",
file_path: "data/outputs/research.md",
file_extension: "md",
},
},
},
],
},
],
},
{ agentId: researcher.id, model: "auto" },
);Chain multiple agents where each step depends on previous output:
async function runPipeline(steps) {
// steps = [{ agentId, skillPath, prompt_template }, ...]
for (let i = 0; i < steps.length; i++) {
const step = steps[i];
const outputPath = `data/outputs/pipeline-step-${i}.md`;
const content = [{ type: "text", text: step.prompt_template }];
// Attach skill file if this step has one
if (step.skillPath) {
content.unshift(
{ type: "text", text: "请阅读技能文件 " },
{
type: "mention",
attrs: {
type: "project_file",
data: {
file_id: `skill_${i}`,
file_name: "SKILL.md",
file_path: step.skillPath,
file_extension: "md",
},
},
},
{ type: "text", text: " 并执行:" },
);
}
await window.Magic.project.createTopicAndSend(
{
type: "doc",
content: [{ type: "paragraph", content }],
},
{ agentId: step.agentId, model: "auto" },
);
// Wait for output
await waitForFile(outputPath);
}
}For simple commands in the current conversation that don't require a companion skill:
// Only use for quick, stateless instructions to the current agent
window.Magic.setInputMessage("Please summarize the data in data/results.json");Choosing a pattern:
createTopicAndSend + @file SKILL.md)createTopicAndSend + agentId)setInputMessage)This skill generates the following artifacts:
| Artifact | Location | Always generated? |
|---|---|---|
| app.json | <app-dir>/app.json | Yes |
| Main HTML | <app-dir>/index.html | Yes |
| Data files | <app-dir>/data/*.json | If app needs persistence |
| Companion skill | 由 skill-creator 技能创建 | If Medium/Complex architecture |
| README | <app-dir>/README.md | For Medium/Complex apps |
Naming the app directory: Use the user's language for the directory name. If the user says "做一个销售看板", the directory should be named descriptively (e.g., 销售看板/ or sales-dashboard/).
Every new HTML micro-app must include an app.json file in the app root directory. This is the only manifest for the micro-app scenario. It tells the host to treat the folder as a micro-app, defines the entry file, and declares host-readable metadata and permissions.
Format: plain JSON. Use this template:
{
"version": "1.0.0",
"type": "micro-app",
"name": "<app display name>",
"entry": "index.html",
"files": {},
"watch": [],
"permissions": {}
}Rules:
type must be "micro-app" — this enables the micro-app icon and click-to-open behavior"webapp" for app.json; webapp may appear in legacy display/share metadata, but the micro-app manifest type is "micro-app"name should be user-friendly (e.g., "销售看板", "Task Manager")entry defaults to "index.html"; include it explicitly for new appsindex.html so the frontend recognizes the project immediatelymagic.project.js for new HTML micro-apps. It is only a legacy compatibility file for older projects or for non-micro-app project types such as slides/design/media.Optional: Custom Icon (icon field)
You can provide a custom icon for the app folder by adding an icon field to app.json. The value can be:
https:// URL for remote images{
"version": "1.0.0",
"type": "micro-app",
"name": "销售看板",
"entry": "index.html",
"icon": "icon.svg"
}When to use a custom icon:
How to generate an icon:
Use write_file to create a simple SVG in the app directory (e.g., icon.svg), then reference it in app.json. Example SVG for a sales dashboard:
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<!-- design a clean, recognizable icon that reflects the app's purpose -->
</svg>Keep SVG icons at 24×24, use flat/modern style with 2–3 colors, and ensure the design reflects the app's core function.
For Medium/Complex apps, generate a README.md in the app directory documenting:
# [App Name]
## 功能说明
- 功能1: 描述
- 功能2: 描述
## 目录结构app-dir/ ├── app.json ├── index.html ├── data/ │ └── ... └── ...
## 伴生技能
| 技能 | 路径 | 作用 |
|------|------|------|
| [name] | `.magic/skills/[name]/SKILL.md` | 描述 |
## 交互流程
[主要操作流程说明]
## 变更记录
| 日期 | 变更内容 |
|------|----------|
| YYYY-MM-DD | 初始版本 |When user requests feature changes to an existing micro-app:
User: "做一个计算器"
→ Generate calculator/app.json + calculator/index.html with all logic in <script>, no companion skill needed.
User: "做一个能自动分析CSV数据并生成报告的工具" → Generate:
data-analyzer/app.json — micro-app manifest (type: "micro-app")data-analyzer/index.html — upload UI, results display, watch for report, agent/model selectordata-analyzer/data/ — uploaded data storageskill-creator 创建 data_analyzer 伴生技能,定义分析工作流Runtime: HTML 通过 @file mention 引用伴生技能 → createTopicAndSend → general mode agent 读取技能并执行
User: "做一个内容创作工作台,能让研究员搜集资料,写手写文章,编辑审核" → Generate:
content-studio/app.json — micro-app manifest (type: "micro-app")content-studio/index.html — agent selector, model selector, task dispatch UI, status dashboardcontent-studio/data/ — tasks, drafts, reviewsskill-creator 创建 content_pipeline 伴生技能,定义编排工作流Load these when you need detailed information:
read_skills(["html-api-sdk"]) — Complete window.Magic.* API signatures, parameters, return types, and constraints. Read this before generating any HTML..magic/<name>/ path convention.When to read references:
read_skills(["html-api-sdk"])skill-generation-patterns.mdapp-architecture-patterns.md.magic/<name>/SKILL.md paths → read legacy-migration.md41d7ef4
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.