dtyq/magic/html-api-sdk
Claude Code and agent skill by dtyq/magic
- community
Checking that the SKILL.md file is still in the repository.
Complete API reference for window.Magic.* in SuperMagic HTML micro-apps (HTML 微应用). Read this skill when you need exact method signatures, parameters, return types, or usage examples for: fs (readFile/writeFile/listFiles/listDir/getFileUrl/deleteFile/deleteDir/moveFile/renameFile/watchFile/watchDir), llm (chat/stream/getModels), agent (getAgents/selectAgent), project (createTopicAndSend/sendMessage/uploadFiles/downloadFiles), user (getInfo with app.json userInfo scopes), getAppBasePath, setInpu…
Install
npx vskill@latest install dtyq/magic/html-api-sdkSKILL.md
The same SKILL.md was published earlier as dtyq/magic/html-api-sdk.
window.Magic API — HTML Micro-App Guide
How to Use This Document
- API signatures & constraints → this document
- App manifest & permission declarations →
app.json - TiptapJSON & @mention structures → references/tiptap-json-format.md
- Complete HTML examples → references/complete-examples.md
Important Constraints
- All
window.Magic.*APIs are pre-injected — no imports needed. External CDN allowed. - File paths are relative to app root (
index.htmldir) by default.../is forbidden. Use leading-slash paths such as"/shared/data.json"to access project-root files. Writing, deleting, moving, or renaming files outside the app root triggers host confirmation. window.Magic.llmtokens hosted; noapi_keyin HTML.- No inline event handlers — use
addEventListener. For buttons rendered byinnerHTML, bind one delegated listener on a stable container and usedata-action/data-id. - LLM and Agent calls must include model selector UI unless the user specifies a fixed model. Load the available models with
window.Magic.llm.getModels(), render them in the page, and preselect the first available model. Do not guide users to use"auto"as the default selection. - Complex file-based AI → use
createTopicAndSendwith the task; published micro-app previews automatically provide@micro_appcontext so the Agent can inspect companion skills. Use an explicit@fileonly when selecting one exact skill. Simple →readFile+llm.chat/stream. - High-risk APIs are permission-gated — new HTML micro-apps must declare requested scopes in
app.json.permissions.scopes. The host asks the user to approve high-risk runtime calls for a limited duration. - User info is privacy-gated —
window.Magic.user.getInfo()returns onlynameandavatarby default. Sensitive fields require a matching permission declaration, a runtimegetInfo({ scopes, reason })request, and user confirmation. - Use `app.json` as the micro-app manifest — every new HTML micro-app folder should include
app.jsonnext toindex.html. Puttype,name,entry,anonymous, file aliases, watch hints, and permissions there. Also generate a minimalmagic.project.jsdisplay bridge that mirrorsversion/name/entry/icon; new bridges usetype: "html-app", while existingtype: "micro-app"bridges remain compatible. Do not putanonymous, permissions, files, watch, or business state inmagic.project.js.
``json { "version": "1.0.0", "type": "micro-app", "name": "App Name", "entry": "index.html", "anonymous": false, "files": {}, "watch": [], "permissions": { "scopes": [], "reason": "" } } ``
- Administrator page access is runtime-controlled — when an app has administrator-only pages, put
window.MagicAppConfig.admin_pagesin the sharedapp.jsand callwindow.Magic.db.getProjectAdminAccess()before loading each listed page. The result is based on the real logged-in user; a share token is only an access proof and is never a user identity.
HTML Interaction Safety
Generated micro-app controls must be wired through real JavaScript listeners, not HTML event attributes.
- Do not generate
onclick,onchange,oninput,onsubmit, or other inline event attributes. - For lists, cards, table rows, and menus rendered with
innerHTML, use event delegation:container.addEventListener("click", handler)and buttons such as<button data-action="edit" data-id="...">. - Do not attach action functions to
windowjust to make inline event handlers work. - If using
new FormData(form), every value read withformData.get("field")must have a matchingname="field"on the input/select/textarea. Having onlyid="field"is not enough. - Before calling
.trim(), normalize possibly missing form values, for exampleString(formData.get("title") || "").trim(). - If a form is read by DOM IDs instead, use
.valueconsistently and do not mix it withFormData.get()for unnamed controls.
1. File System (window.Magic.fs)
readFile(path) → Promise<string>
path: string— relative to app root. Max 5 MB; rejects if not found.
writeFile(path, content) → Promise<void>
content: string | Blob | ArrayBuffer. String max 5 MB. Auto-creates dirs.../blocked.
⚠️ Paths relative toindex.htmldir, NOT workspace root.
File Paths and Project-Root Access
By default, relative window.Magic.fs.* paths resolve inside the app folder next to index.html. Use a leading slash for project-root paths. Project-root reads require fs.project.read; project-root writes/deletes/moves/renames require fs.project.write plus a host path confirmation for each destructive operation.
Path rules:
"data/config.json"-> app root, e.g.my-app/data/config.json."/shared/config.json"-> project root."/"lists project-root entries.../remains blocked in all scopes.- Reading project-root file contents or temporary URLs requires
fs.project.read. - Writing, deleting, moving, or renaming files outside the app root requires
fs.project.write, then triggers host path confirmation and may be rejected by the user. listFiles("/")andlistDir("/")are not gated in the current version, but do not depend on them for sensitive directory discovery.
listFiles(dir?) → Promise<string[]>
- Compatibility API. It returns direct child names only. Prefer
listDir()for new list UIs.
listDir(dir?) → Promise<Array<{name,path,isDirectory,updatedAt?}>>
- Returns direct children only. It does not read file contents.
- Use it for list pages. Read the JSON detail only when the user opens, edits, or analyzes one record.
pathis usable withreadFile,writeFile,deleteFile,moveFile, andrenameFile.
getFileUrl(path) → Promise<string>
- Returns a temporary browser-accessible URL for an existing workspace file.
- Use it for previews,
<img>,<audio>,<video>, download links, or libraries that need a URL instead of file text. - It does not download the file by itself. Use
window.Magic.project.downloadFiles(paths)when the user action should trigger a browser download. - Rejects if the file is missing or the path is invalid.
../blocked.
deleteFile(path) → Promise<void>
- Rejects if file not found.
../blocked.
deleteDir(path) → Promise<void>
- Recursively deletes all files and subdirectories. Cannot delete app root or project root. Rejects if dir not found.
../blocked.
moveFile(path, targetDir) → Promise<void>
- Moves a file or directory to the specified target parent directory. Rejects if source file or target directory not found.
../blocked.
renameFile(path, newName) → Promise<void>
- Renames a file or directory.
newNameis just the new name (no path separators). Rejects if file not found.../blocked.
watchFile(path, cb) → () => void
- Polls ~3s; max 10 watched paths per app. Call returned fn to stop.
watchDir(dir, cb) → () => void
- Not a real-time filesystem watcher. It compares refreshed host attachment snapshots after the existing attachment polling or
Update_Attachmentsrefresh. - Watches direct child additions and removals only. File content changes continue to use
watchFile(). - Callback payload:
{ dir, timestamp, added, removed, entries }.
Concurrent Reads
Shared Data Storage Rules
For generated CRUD micro-apps, assume multiple users may share the same app.
- Config or single current state may use one overwritable file, such as
data/config.json. - User-created business records must default to one file per record, such as
data/tasks/<record-file>.json. - List pages must render from
listDir()entries and file-name projection; do not batchreadFile()every record just to draw a list. - Event logs and history should be append-only multi-file records, such as
data/events/<timestamp>__<id>.json. - Reports, analysis output, and caches may be overwritten because they are derived artifacts.
- For more than 500 expected records, bucket by month or business status, such as
data/tasks/2026-06/ordata/tasks/open/, and use pagination or virtual scrolling.
Record file names are list projections only:
Required helpers in generated apps:
buildRecordFileName(record)parseRecordFileName(name)slugifyTitle(title)— lowercase English letters, digits, hyphens only; returnrecordwhen unsafe or not representable.truncateUtf8Bytes(input, maxBytes)
File-name limits:
- Hard limit: 255 bytes.
- Generation target: 120 bytes including
.json. titleSlug: max 40 bytes by default.- Forbidden:
/,\,<,>,:,",|,?,*, control chars,.., leading/trailing spaces. - Never put phone numbers, addresses, notes, detailed amounts, private fields, or long text in file names.
- Always include stable
shortId. Never use only the title. - Sort lists by parsed
sortKey, not by backend return order.
Update safety:
- Create: generate stable
id/shortId, build the file name, then create the record file. If the target file exists in the same dir, regenerateshortId. - Update non-projection fields: write JSON only.
- Update title/status/date projection fields: write JSON first, then
renameFile(), preservingshortId. - Before rename, call
listDir()and block the rename if the target name already exists with a differentshortId. - If JSON and file-name projection disagree, list uses file name, detail uses JSON. Try a background rename repair only when it cannot overwrite another file.
- Complex filters across more than two detail fields, amount ranges, tag combinations, owners, or similar query needs require an index file or backend query capability.
1.5 getAppBasePath() → Promise<string>
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingbackend/super-magic/agents/skills/html-api-sdk/SKILL.md
Popularity
- Repository stars
- 5,063
- Repository forks
- 563
- 7-day trend score
- 42
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/dtyq/magic/html-api-sdk)