Generate from Mini Program source code a skill subpackage compliant with wx.modelContext specification (skills/):Analyze source code → identify business → extract interfaces and JSAPI → design atomic interfaces → generate code → integrate configuration → handoff validation。
Responsibility boundaries
- ✅ What this skill does: source code analysis, atomic interface design, on-demand use of automator to obtain real responses, code generation,
app.json/project.config.jsonintegration- Self-checks within the generation process: field source self-check (§5.8),
AUTH_MIGRATION.md §6auth self-check, hard constraint C code consistency self-check
- Self-checks within the generation process: field source self-check (§5.8),
- ❌ What this skill does not do: independent validation of generated artifacts (static rule validation V001~V021, real-device execute pass, component rendering verification) — all handled by
wxa-skills-validate. Self-checks during the generation phase are part of this skill and are not skipped just because "validation is delegated to validate" - 📦 Deliverables:
skills/{skill-name}/(includingmcp.json、SKILL.md、index.js, atomic interface implementation files, utility modules; the component directory exists only when components are generated, see D.3) + configuration file updates +.ai-mode-skills/two analysis artifacts
Analysis artifacts (<源项目>/.ai-mode-skills/)
Analysis results are persisted in two files, split by read frequency, to avoid reading an entire single file in full:
| File | Output timing | Content | Usage |
|---|---|---|---|
analysis-auth.md |
Phase 1.2 | Auth facts + verbatim code snippets | Write once, read many times; referenced in phases 3 / 5.6 |
analysis-apis.md |
Phase 3 | Per-interface specs + probe result summary | Appended per interface; referenced in phases 4 / 5 |
probe/plan.json(input of probe.mjs) and probe/<run-id>.json(script writes to disk) are managed by the subagent scripts and are not analysis artifacts.
Dependencies
- Readable source code directory(if only appid / URL / screenshots are given → trigger blocking)
- Developer tools: WeChat Developer Tools +
scripts/probe.mjs(miniprogram-automatorwith the skill installed in thescripts/, without installing the source project). Used only when one of the two trigger conditions in phase 3.7 is met, see 3.7 andreferences/RUNTIME_PROBE.md
Terminology conventions
- Atomic interface: a callable capability exposed externally to Mini Program AI. Convention path
skills/{skill}/apis/{name}.js(validator also supportstools/services//tools/) - Atomic component: a GUI card used to render data returned by atomic interfaces (whether to generate,
componentPathrules see D.3). - Minified code: artifacts with single lines exceeding 500 characters and single-character variable names (including obfuscation)
- probe: the runtime probing in phase 3.7 of this skill. Use automator (
miniprogram-automatornpm package) to connect to the Developer Tools WS port (9420), on thesource projecttrigger requests, capture real responses, persist artifacts to.ai-mode-skills/probe/。
Reference index
| File | Purpose | Load timing | Conditions for not loading |
|---|---|---|---|
references/ANALYSIS_PATTERNS.md |
Business process identification, interface/JSAPI search patterns | Stage 2 / 3 while scanning source code | When the user has explicitly specified all capabilities and page structure no longer needs to be scanned |
references/JSAPI_WHITELIST.md |
Complete wx API whitelist (interface side / component side / non-migratable); Section D lists only high-frequency items | Stages 1 / 3 / 5 (must check when Section D does not cover the target API) | None (recommended to cross-check every time, do not rely on impression) |
references/CODE_TEMPLATES.md |
Code and configuration templates (index.js / utils / apis / mcp.json / skill SKILL.md / app.json) |
Stages 5 / 6 | When purely modifying existing single-line logic without involving template structure |
references/COMPONENT_TEMPLATES.md |
Atomic component template | Stage 5 (when generating components) | Do not generate components (default, see D.3) |
references/ATOMIC_COMPONENT_DESIGN.md |
Component design specification (size / theme / margin / font / layout) | Same as above (mandatory prerequisite, highest priority) | Same as above |
references/ATOMIC_COMPONENT_CSS.md |
Component WXSS implementation specification | Same as above (when writing styles) | Same as above |
references/STYLE_MIGRATION.md |
Source style extraction + field mapping workflow | Same as above (mandatory prerequisite before writing WXML/WXSS) | Same as above |
references/HALF_SCREEN.md |
Half-screen page API and prohibited list | As needed (source business indeed has detail/supplementary information semantics) | When not generating half-screen by default |
references/RUNTIME_PROBE.md |
Probe trigger scenarios, plan/result format, execution commands | When trigger conditions are hit in Stage 3.7 | When deciding not to run probe after analyzing source code |
references/AUTH_MIGRATION.md |
analysis-auth.md filling guide, auth replication, ensureXxx, §6 self-check | Stages 1.2 / 3 (auth reference) / 5.6 | None ("no login" ≠ "no auth"; generic header/query still need to be read) |
references/SUBAGENT_PROTOCOL.md |
Large project subagent dispatch protocol (capability index → ①auth ②api ③probe; read budget and return discipline) | When Stage 1 determines it is a large project | When reading directly for small projects (pages ≤ ~30 and no multiple subpackages) |
Hard constraints
A. Independent subpackage prohibitions (must be rewritten)
| Prohibitions | Correct approach |
|---|---|
getApp() |
Manage state within the subpackage itself (module variables / wx.storage) |
require('../../xxx') referencing main package / sibling subpackages / import ... from '@/' |
Copy dependenciescompletelyto the current subpackage: for single-skill private use place in {skill}/utils/, for multi-skill reuse place in skills/_shared/ |
Depend on main package wx.cloud.init() |
utils/util.js initialize in ensureCloudInit() itself |
Depend on main package app.js initialize storage |
utils/util.js in ensureStorageInit() initialize itself |
From getApp().globalData read configuration |
baseUrl / env hardcode in subpackage utils/util.js |
| Depend on main package login state | Before each API execution ensureLogin() actively go through the login flow once |
| Use global components registered by the main package | Redeclare in the subpackage JSON usingComponents |
B. Blocking rules that directly terminate generation
If any of the following occurs, immediately terminate generation and inform the user:
| Blocking situation | Detection timing | Notification text |
|---|---|---|
Depend on mini program plugin (plugin:// / requirePlugin / app.json of plugins) |
Stage 1/3 | "This feature relies on a Mini Program plugin and is currently not supported for automatic generation; it must be integrated manually" |
| No corresponding interface or page can be found in the source code for the capability declared by the user | Stage 3 | "Failed to locate in the source code <能力名>, cannot generate; please confirm the capability name or supplement the source code" |
| No readable source code directory provided (only appid / URL / screenshots given) | Before Stage 1 | "Please provide the complete Mini Program source code directory; currently unable to generate based on non-source-code assets" |
| All candidate implementations rely on non-whitelisted JSAPI and there is no alternative | Stage 3 | "This capability relies on a non-whitelisted JSAPI (such as <api>), cannot generate automatically" |
app.json app.json is missing the "lazyCodeLoading": "requiredComponents" configuration |
Stage 1 | "Project app.json top level is missing \"lazyCodeLoading\": \"requiredComponents\", otherwise the atomic interfaces within the independent subpackage cannot be loaded and executed correctly when called by the Mini Program AI router. Please add this field at the top level of app.json and then trigger generation again" |
| The response structure cannot be determined from source code consumption points, and probe is unavailable | Stage 3 | "Interface <api> response structure cannot be determined statically and runtime probing is unavailable; please help provide the interface documentation or troubleshoot the probe environment" |
C. Code Consistency (No additions, no omissions + mandatory reuse of the encapsulation layer)
The sole goal of this skill: migrate/convert the reference source code to the target format, keeping the logic, structure, and behavior consistent with the reference source codecompletely consistent。
Migration = faithful transfer, not rewriting. Every piece of logic present in the source code must be preserved in the output; anything not present in the source code must not be added.
Mandatory reuse of the encapsulation layer:utils/request.js is the only entry point for network requests; all apis/*.js must send requests through it, and it is forbidden for API files to directly call wx.request or assemble URL/header/query on their own—otherwise all authentication parameters will be lost, causing 403/empty data.
C.1 Prohibited additions (logic that does not exist in the source code)
- Adding error handling that does not exist in the reference source code (try/catch, if conditions, etc.)
- Adding default values or fallback logic that do not exist in the reference source code
- Adding input validation that does not exist in the reference source code
- "Optimizing", "correcting", or "completing" logic in the reference source code that appears incomplete
- Any form of "I think this should be added here..."
If the reference source code itself does not handle a certain situation, the output will not handle it either. If something in the reference source code looks like a bug or omission, preserve it as is.
C.2 Prohibited omissions (logic that exists in the source code)
Core principle: you have no authority to judge "whether this parameter is necessary". The backend validation rules are a black box to you, and every header/query in the source code request encapsulation must be preserved.
- Complete preservation of authentication parameters: see
references/AUTH_MIGRATION.md; after generation, self-check according to AUTH_MIGRATION §6 - Complete inlining of dependencies: dependencies traced in Stage 3.2 are fully copied to the subpackage in Stage 5
- Type safety of response fields: before processing array fields in API responses, add null protection (
(x || []).method()orArray.isArray(x) ? x.method() : [])。
D. wx API whitelist (must be checked against on every generation)
During phase 1 authentication scanning, phase 3 JSAPI extraction, and phase 5 code generationmust be checked against the whitelist. If the source code uses a JSAPI outside the list → handle it as a "non-migratable JSAPI".
Complete list(interface side / component side / non-migratable) see
references/JSAPI_WHITELIST.md. The following D.1 / D.2 / D.6 list only high-frequency items; when covering business scenarios, you must consult the complete reference list, do not rely on impressions.
D.1 Interface-side whitelist
"Interface side" refers to handlers registered via
wx.modelContext.registerAPI()and the pure JS modules they depend on — conventionally placed in<skill>/apis/(may also be placed intools/services//tools/, the validator will resolve according to these three candidate directories), the directory name of referenced utility modules (such asutils//services//helpers// custom names) is not restricted.Scope is determined by "whether it is on the atomic interface handler chain", not by directory name。
| Category | High-frequency interfaces |
|---|---|
| Mini Program AI | wx.modelContext.registerAPI、wx.modelContext.createSkill(returns { use, registerAPI })、wx.modelContext.expireAllCards、wx.modelContext.getSessionId(get session ID) |
| Login | wx.login、wx.checkSession |
| Network | wx.request, network status getNetworkType / on*NetworkStatusChange |
| Cloud Development | wx.cloud.init / callFunction / database |
| Location | wx.getLocation / getFuzzyLocation(excluding chooseLocation / openLocation) |
| System | wx.getDeviceInfo、wx.getAppBaseInfo、wx.getWindowInfo |
| Data cache | wx.{get,set,remove,clear,batchGet,batchSet}Storage(including Sync)、wx.getStorageInfo |
| Upload/Download | wx.uploadFile、wx.downloadFile |
| Subscription messages | wx.requestSubscribeMessage |
| Authorization settings | wx.authorize、wx.getSetting(excluding openSetting) |
| Image | wx.getImageInfo |
| Phone number | wx.getPhoneNumber、wx.getRealtimePhoneNumber |
| Account | wx.getAccountInfoSync(callable from both interface and component) |
| Privacy authorization | wx.requestAgentPrivacyAuthorization({ privacyAgreements })(pops up the platform privacy authorization card, returns { authorized }; for usage see references/CODE_TEMPLATES.md section 2) |
Payment types, system pickers/capture (
choose*/scanCode/saveImageToPhotosAlbum), actively opening native pages/panels (openLocation/makePhoneCall/openDocument/shareAppMessage/openSetting/openPrivacyContract), interface feedback (showToast/hideToast)are not on the interface side—— see D.2 /references/JSAPI_WHITELIST.md §2(component side). For other scenarios (face verification, WeRun, encryption, WiFi, Bluetooth/BLE, WebSocket, TCP/UDP, mDNS, sensors, etc.) consultreferences/JSAPI_WHITELIST.md §1the complete table.
If the source code uses a JSAPI outside the list → handle it according to the D.9 determination rules. In phases 1/3/5, check against the whitelist every time, do not rely on impressions.
D.2 Component-side whitelist
"Component side" refers to the code within the atomic component
Component({})and the pure JS modules it references._meta.ui.componentPathis the component base path relative to the skill directory, corresponding to<componentPath>.{js,json,wxml,wxss}; the default template usescomponents/<name>/index。
For the complete list see references/JSAPI_WHITELIST.md §2(including Mini Program AI getContext/getViewContext/setRelatedPage/updateModelContext/expireAllCards/expirePreviousCards, interface previewMedia/showToast/hideToast, system, cache, file, account, location openLocation, device, settings, share, vibration, privacy, all methods of map MapContext, etc.). Component-side prohibition rules (wx.cloud.* and JSAPIs outside the whitelist are unavailable, components and interfaces do not share global variables, context is obtained at the point of use or this._viewCtx cached) are also found in the last paragraph of §2 of that document.
Sync interaction state to the model: when the user changes a selection on the card (selecting a spec, selecting a time slot, etc.), call within the tap handler
wx.modelContext.getViewContext(this).updateModelContext({ content: [{ type: 'text', text: '用户选择了大杯' }] })so the model can perceive the latest state. It must be called in the user's tap click event callback, and must not be called in asynchronous logic or a timer; repeated calls within a short time will be throttled and rejected,contentmust be a non-empty array andtextnon-empty.
D.3 Component configuration (on-demand generation of atomic components + related pages + real-time dynamic capabilities)
Atomic components are not generated by default. Atomic interfaces only return text + structuredContent + handoff(enter the handoff page, see D.6).Only when the user explicitly requests generation of an atomic component (GUI card)is it generated: the corresponding interface declares the path relative to the skill directory _meta.ui.componentPath, and in mcp.json the top-level components[] declares a record,path must be exactly equal to the interface's _meta.ui.componentPath string。
relatedPage Required: the "Enter Mini Program" entry in the upper-right corner of the card title bar is configured through it; if it is missing, cli preview / will be blocked by the platform's strong validation during upload. The value must start with / (an absolute path); after removing the leading / , it is the project app.json page that actually exists (main package pages[] or subpackage root + page); if there is no corresponding page in the business, fall back to filling in the home page /<app.json.pages[0]>. The scenario value for entering the Mini Program through this entry is 1442 / 1443.
permissions.scope.dynamic Declared on demand only when the component needs wx.login / wx.checkSession / wx.request / a timer (rules see references/JSAPI_WHITELIST.md §2.1)。
{
"components": [
{
"path": "components/order-list/index",
"relatedPage": "/pages/order/list"
},
{
"path": "components/weather-card/index",
"relatedPage": "/pages/weather/index",
"permissions": { "scope.dynamic": { "desc": "声明使用场景" } }
}
]
}
At runtime, append query parameters to the related page: you can save created in the component this._viewCtx = wx.modelContext.getViewContext(this), and after receiving NotificationType.Result or a state change, call this._viewCtx.setRelatedPage({ query }); if the component may be related to multiple pages, additionally pass path. You can also obtain viewCtx at the point of use and then call it. For example code, see references/COMPONENT_TEMPLATES.md the "Related Mini Program Page" section. This constraint is validated by static rules (V015).
D.4 Component expiration state declaration (on demand, not mandatory)
Not generated by default.Only whenthe source business has the semantics of "the card becomes invalid at a certain time and should no longer be clickable" (transaction completed, store closed, activity ended, timeout), add to the components[] record expirable: true + business-specific expiredText. Declaration and invocation must be paired.
Choose one of the triggering APIs (do not call both at the same time), fine-grained filtering (componentPaths / match: 'latest'), for code examples see references/COMPONENT_TEMPLATES.md the "Card Expiration" section。
D.5 Half-screen page (on demand,Not generated by default)
The half-screen page discussed in this section isopening another Mini Program page(
openDetailPage), and its runtime environment is equivalent to a normal Mini Program page; it is not the same as thecollapsible-viewwhere the atomic component itself expands into a half-screen. For distinction of usage, seereferences/HALF_SCREEN.md§4。
Attach it only when the source business truly has the semantics of "details / user supplementary information". The entry is only within the atomic component methods (getViewContext(this).openDetailPage,atomic interfaces have no this and cannot be called). For uplink within the half-screen sendFollowUpMessage, the disable list (jump-out type / page routing / chat tools / ads / navigation components, etc.), scenario values, and close button adaptation, see references/HALF_SCREEN.md。
D.6 handoff page (the main way to enter the Mini Program)
Entering the Mini Program uniformly goes through handoff. Default flow: the atomic interface returnstext + Mini Program card, and after the user clicks the card, the platform handoff enters thehandoff business pageContinue the operation.
When it must be configured: if an atomic interface, after it finishes executing, willstop and wait for user confirmation(display a Mini Program card, wait for the user to tap to enter the Mini Program), you must configure pagePathfor it; otherwise the user cannot enter the business page. Pure data interfaces with no pause and continuous flow may skip configuration.
Four-item adaptation (mcp.json configure _meta.ui.pagePath → return value top-level handoff(two forms: object immediate / function delayed, fields query / payload / path) → main package app.js register wx.onAgentHandoff → relay page onLoad(query) consume) field specifications and complete code, see references/CODE_TEMPLATES.md "handoff relay page" section.
Division of labor with inline text links: handoff is torelay the entire current conversation flow into the page; when you only want to give a tappable detail entry in the middle of the reply text, use
outputSchema'sformat: "page-link"(see stage 4.2),do not return handoff. The two can coexist and do not replace each other.
Disabled:
wx.openAgent/wx.navigateBackAgent: the current base library side is not yet connected, and calling it will fail—do not rely on "open Agent / return to Agent conversation" within the relay page; subsequent flows are completed by the business page itself.
D.7 Non-migratable JSAPI (both interfaces and components disabled)
For the complete list and replacement strategies, see references/JSAPI_WHITELIST.md §3(including Taro-specific non-migratable items). High-frequency items:wx.showModal / showLoading series,wx.navigateTo series routing,chooseImage / chooseVideo / previewImage legacy interfaces,setClipboardData / getClipboardData、getUserInfo / getUserProfile、createSelectorQuery / createCanvasContext、pageScrollTo / createAnimation, within ordinary atomic components setTimeout / setInterval。
Note the distinction between "unavailable on both sides" and "just moved to the other side":
showToast/chooseMedia/scanCode/makePhoneCallsuch asnot entirely banned, but merely moved from the interface side to the component side; for what is available on one side, see D.1 / D.2 andreferences/JSAPI_WHITELIST.md。
D.8 button 's open-type rewrite
within the component button disable open-type(share / getPhoneNumber / getRealtimePhoneNumber) → remove open-type, change to bindtap, call the corresponding whitelisted JSAPI within the tap handler (wx.shareAppMessage; mobile phone number-related items must be completed on the atomic interface side, see D.1 / D.2).
D.9 Determination rules
Execute according to references/JSAPI_WHITELIST.md §4 three rules (only achievable with non-migratable JSAPI and no replacement → block B; core logic can be implemented with network requests → pure network request version; legacy interface has a whitelisted replacement → automatic replacement). During automatic replacement,also confirm the side on which the replacement interface resides(most are available only on the component side).
E. Atomic component constraints
For complete constraints such as events / built-in component whitelist / rendering container / real-time dynamic capabilities / animation restrictions, see references/COMPONENT_TEMPLATES.md "Important restrictions" section; for the range of supported CSS properties, see references/ATOMIC_COMPONENT_CSS.md. There are additionally two restrictions:
- Data channels prohibit
properties/observer/dataSource: must obtain viaNotificationType.ResultfetchstructuredContent(seereferences/COMPONENT_TEMPLATES.mdand stage 5.4) - WXML expression restrictions:
{{ }}does not support array indexing (e.g.[0]), function calls (e.g..slice()), template strings, and other complex JS. Any fields that need computation must be preprocessed during theindex.jsnormalization stage beforesetData
Execution checklist (check after copying)
阶段 0 — 业务需求澄清(前置)
- [ ] 判定用户场景是否明确(两项判定)
- [ ] 不明确 → 最小扫描 + 引导澄清 + 等待确认
- [ ] 确认是否生成原子组件(默认不生成,见 D.3)
- [ ] 产出"目标业务场景 + 期望原子能力"清单
阶段 1 — 项目扫描
- [ ] 首检 `lazyCodeLoading`(缺则阻断 B)
- [ ] 提取 app.json / app.js / project.config.json 关键字段
- [ ] 产出云开发 / 插件 / storage 初始化清单
- [ ] 落盘 `analysis-auth.md`(鉴权事实 + 逐字代码片段,见 `AUTH_MIGRATION.md` §2/§3;大项目派 subagent ① 鉴权分析,三类中最先)
- [ ] 大项目:先产能力索引坐标(见 1.0)
阶段 2 — 业务功能识别(用户已明确时跳过)
- [ ] 产出结构化功能清单 JSON
- [ ] 用户二次确认
阶段 3 — 接口与 JSAPI 提取 + 可行性校验
- [ ] 逐接口分析(小项目直读 / 大项目派 **subagent ② api 分析**,须在 ① 完成后,见 3.2),追加到 `analysis-apis.md`
- [ ] 按需 probe(两个触发条件,见 3.7):派 **subagent ③**(须在 ①② 完成后),跑了的回填真实响应到 `analysis-apis.md`
阶段 4 — 原子接口设计
- [ ] 原子接口清单(含 name / description / inputSchema;按需声明 outputSchema。进小程序的接口配 _meta.ui.pagePath + 返回 handoff;_meta.ui.componentPath 仅生成组件时才有)
- [ ] API 依赖图
- [ ] storage key 清单
阶段 5 — 代码生成
- [ ] 进小程序的接口已配 _meta.ui.pagePath + 返回值顶层 handoff(见 D.6)
- [ ] `utils/request.js` 按 `AUTH_MIGRATION.md` §5 生成,§6 自检清单逐条过
- [ ] 每写完一个 `apis/<name>.js` 做字段来源自检(见 5.8)
- [ ] (生成组件时)组件走 5.1–5.4 前置与模板;`components[]` 每条都填了 `relatedPage`
- [ ] `skills/{skill-name}/` 目录完整(mcp.json / SKILL.md / index.js / apis/* / utils/*;仅生成组件时含 components/*);SKILL.md 按 `CODE_TEMPLATES.md` 第五节 5 节结构写完
阶段 6 — 配置集成
- [ ] app.json 加 agent.skills(每项含 `{ name, description, path }`)+ subPackages
- [ ] project.config.json 的 packOptions.include 加 skills
- [ ] (按需)AGENTS.md + `agent.instruction`;page-meta.json + `agent.pageMetadata`(见 6.1 / 6.2)
- [ ] 体积与数量上限自查(上限表见 `CODE_TEMPLATES.md` 6.3)
收尾 — 交棒给 wxa-skills-validate
- [ ] 明确告知用户:"请使用 wxa-skills-validate 做校验"
- [ ] 提示 skills 路径与 project-path
Cross-stage jump rules
| Scenario | flow direction |
|---|---|
| normal main path | 0 → 1 → (2) → 3 → 4 → 5 → 6 → handoff wxa-skills-validate |
| user clearly states the capability | skip 2, 0 → 1 → 3 |
| phase 3 | 3.6 → 3.7 (probe only if trigger conditions are met) → 4 |
| probe environment unavailable | static results are used as usual, code is marked [ai-mode:static], and state at handoff that it has not been verified on a real machine |
| validator feedback T1~T6 / class A/B/C/D errors | return to this skill's phase 5 to modify the code |
| validator feedback T7/T8 (interface partitioning / dependency chain) | return to this skill's phase 4 to redesign |
| any phase triggers blocking rule B | terminate immediately, output the blocking reason |
core principles:
- when the business scenario is unclear,clarification must precede generation
- each phase must fully produce all items in the "deliverables list" before moving to the next phase
incremental changes and re-entry
when the workspace already contains skills/ artifacts:
| user intent | entry phase | description |
|---|---|---|
| add one atomic capability | phase 0 (lightweight) → phase 3 | first clarify the new capability, scan interfaces and add them to the incremental list |
| modify the behavior of an existing atomic interface | phase 4 | update the interface list → 5 → 6 → handoff |
| modify component styles/templates | phase 5 | only modify components/{x}/, re-run 5 → 6 → handoff |
| validator T1~T6 / A/B/C/D feedback | phase 5 | locate the files per the report, hand off after fixing |
| validator T7/T8 feedback | phase 4 | after redesign, 5 → 6 → handoff |
| verification only | do not enter this skill, directly provide wxa-skills-validate |
— |
files already generated on re-entry and untouched remain unchanged; only affected files are updated.
phase 0 — business requirement clarification (mandatory prerequisite)
contract:
| item | content |
|---|---|
| entry conditions | the user initiates a generation request (any request must start from this phase) |
| deliverables | determination result + clarification list if necessary |
| next step | "clear" or clarification confirmed → phase 1 |
determination rules(both items must be satisfied to count as "clear"):
| # | determination item | example |
|---|---|---|
| ① | specifyconcrete business nouns | "product search" "order management" "address management" "check-in"; not "core features" "main capabilities" |
| ② | inferablea granularity of at least 2-3 atomic capabilities | "search products + display list + view details"; not "business-related" |
if any is not satisfied → enter the clarification process below.
Guidance flow when unclear
- Minimal scan: read-only
app.jsonof thetabBar.list、pages(top-level paths),subPackages.root。Forbiddento read JS/WXML/WXSS; dependency analysis is forbidden. - Summarize candidates: based on path keywords (see the
references/ANALYSIS_PATTERNS.mdpage feature identification table), summarize 3~6 candidate scenarios. - Ask the user(ask everything at once; don't interrupt repeatedly):
- Which business scenarios do you want turned into SKILLs for the Mini Program AI?
- What roughly are the atomic capabilities you want exposed to the Mini Program AI for each scenario?
- Does it involve sensitive capabilities such as login state, payment, location, cloud development, etc.?
- Whether to generateatomic components (GUI cards)?Not generated by default—only atomic APIs + handoff (tapping a Mini Program card enters the relay page); generate only when you explicitly need in-conversation card-style GUI.
- After the user repliesonly then can Phase 1 begin. It is strictly forbidden to scan source code or generate code before user confirmation.
Clarification output checklist template:
目标业务场景:
- 场景 A:<名称> → 期望原子能力:<能力 1>、<能力 2>
- 场景 B:<名称> → 期望原子能力:<能力 3>
技术约束:
- 是否涉及支付/登录/位置:是/否
- 是否使用云开发:待阶段 1 扫描确认
- 是否生成原子组件(GUI 卡片):是/否
Phase 1 — Project scan
Project structure overview + read strategy routing
Read app.json to map Phase 0 goals to pages/subpackages. Route by scale:
| Scale | Determination | Strategy |
|---|---|---|
| Small project | Pages ≤ ~30, no multiple subpackages | Main agent directly read/grep |
| Large project | Pages > ~30 / multiple subpackages / huge single files | Follow references/SUBAGENT_PROTOCOL.md to execute (capability index → dispatch all three types of subagents) |
Contract:
| Item | Content |
|---|---|
| Entry condition | Phase 0 output is clear |
| Deliverables | Config fields, cloud development/plugins,analysis-auth.md, storage inventory; large projects include a capability index |
| Next step | Capabilities already clear → Phase 3; otherwise → Phase 2 |
| Blocking condition | Missing lazyCodeLoading / no source code / depends on plugins |
1.1 Config scan
Read app.json / app.js / project.config.json, extract pages / subPackages / tabBar / existing agent / appid / packOptions; scan cloud development (wx.cloud calls / cloudfunctions/ directory) and cloud environment ID (wx.cloud.init({ env }))。lazyCodeLoading must be checked: missing "lazyCodeLoading": "requiredComponents" → blocking rule B (do not "fill it in on their behalf"). For cloud development projects, also scan cloudfunctionRoot/<fn>/index.js 's input/output structures.
1.2 Auth logic scan
According to references/AUTH_MIGRATION.md §2/§3, write to disk <源项目>/.ai-mode-skills/analysis-auth.md(structured auth facts + verbatim code snippets; signature function bodies are not written as step arrays).
- Small project: main agent reads
app.js/request wrapper/login file and fills it in itself - Large project: dispatch subagent ① (auth analysis) to deeply read
app.js/ request wrapper / login file / signature module, and return a conclusion summary (seereferences/SUBAGENT_PROTOCOL.md§3.1)
Once analysis-auth.md is written to disk, it becomes a "trusted fact"; subsequent stages 3 / 5.6 reference it directly and do not re-read the same auth function.
1.3 Main package storage initialization scan (mandatory)
Scan app.js and the main package's .js in wx.{set,get,clear}Storage*, extract key / defaultValue / initCondition / sourceFile. Migration: ① setStorageSync initialization value → subpackage ensureStorageInit() rebuild; ② getApp().globalData runtime cache → module-level variable or write to storage on demand; ③ onLaunch after async fetch write to storage → the subpackage re-sends the request and caches on first call. Form the storage initialization list(not the same table as the internal "storage key list for data passing between interfaces" in stage 4).
1.4 Handling minified code
Identify: single line >500 characters / single- or double-character variable names / missing comments and blank lines. Processing order: ① first ask the user for the unminified source code; ② otherwise try prettier formatting before extracting; ③ if after formatting the key fields are still all a.b.c.d → blocking rule B.Do not blindly guess variable names— guessed code will fail extensively in the validator.
1.5 Plugin detection
Scan app.json 's plugins field, and the usingComponents in the plugin:// references in page/component JSON. If the target capability depends on a plugin → blocking rule B.
Stage 2 — Business function identification (skip when the user has already made it clear)
Contract:
| Item | Content |
|---|---|
| Entry condition | Stage 1 complete and the user only provided source code and did not specify atomic capabilities |
| Deliverable | Structured function list (JSON)and secondary confirmation from the user has been obtained |
| Next step | User confirmation → Stage 3 |
| Blocking condition | The user is never able to confirm → stay in this stage |
Actions:
- For the pages corresponding to the candidate scenarios selected in stage 0, analyze page purpose, interaction events, and data flow according to the
references/ANALYSIS_PATTERNS.mdpattern - Identify function points from the user's perspective (each function = one atomic interface)
- Analyze data dependencies (A's return value is used by B)
mcp.json only registers the atomic capabilities the user directly uses (hard constraint):
The following interfacesare not collected as atomic capabilities, are not written to mcp.json, and do not generate apis/*.js:
- Auth/login type:
wx.login/wx.checkSession/ensureLogin()/ token refresh / obtaining sessionId, etc.—these areinfrastructure, automatically executed by functions such asutils/inensureLogin()before each interface call, and are not capabilities the user directly uses - System-level/lifecycle interfaces: app initialization (
onLaunch/onShow), storage initialization, config retrieval, global state reading, etc.—these are framework/runtime behaviors, not business functions the user actively triggers - Internal helper interfaces: APIs called by other atomic interfaces but not directly user-facing (e.g., "get sub-list" is called internally by "search" but not used directly by the user)—only collect function entries from the user's perspective
- Utility functions:
utils/Pure functions in (formatting, computation, URL concatenation, etc.) — these are code organization, not independent capabilities - Sensitive interfaces(irreversible side effects): logout/deletion/unbinding, etc. — see the dedicated rules below
- Admin-side interfaces: admin-side operations (such as "export data", "manage members", "delete products", "publish announcements", etc.) — these are admin-side operations, not capabilities directly used by users
Determination criteria: ask yourself "Would a user say 'help me do X' to the mini-program AI?" — yes → X is an atomic capability; "something the system does automatically" or "something called internally by another interface" → not.
Sensitive interfaces are not collected as atomic capabilities by default (hard constraint):
will produceirreversible side effectsinterfaces,are not collected as atomic capabilities by default, are not written to mcp.json, and do not generate apis/*.js. Rationale: such interfaces are high-risk (accidental triggering is unrecoverable), low-frequency, and should be actively operated by users on native pages, making them unsuitable for automatic invocation by AI agents.
Determination principles:
- Irreversible state changes: operations that cannot be undone after execution, such as account cancellation, data deletion, and clearing records; operations that cannot be restored, such as unbinding, unsubscribing, disbanding teams, removing members, and exiting
Keyword prompt list(a match ≠ necessarily sensitive; semantic judgment is still required; used to assist screening, not exhaustive):
log_off / 注销 / 销户 / cancel / delete / 删除 / remove / 移除 / unbind / 解绑 / dissolve / 解散 / kick / 踢出
Handling method: when a sensitive interface is identified,skip and do not select it, and annotate it in the feature list JSON as "skipped": "destructive"(with reason). These features are implemented by users themselves on the mini-program's native pages and are not exposed to the AI agent. Only if the userexplicitly requestsmaking a certain sensitive interface into an atomic capability should it be collected, and annotate probe/plan.json on the corresponding api item in "destructive": true + "destructiveReason"
Deliverable JSON(fields uniformly camelCase):
[
{
"functionName": "检索商品",
"pages": ["pages/items/list", "pages/search/index"],
"sourceApis": ["GET /api/items/search"],
"suggestedAtomicInterfaces": ["searchItems"],
"needsComponent": true
}
]
Send the list to the user for secondary confirmationbefore proceeding to Phase 3.
Phase 3 — Interface and JSAPI extraction + feasibility verification
Contract:
| Item | Content |
|---|---|
| Entry conditions | List of target atomic capabilities confirmed by the user + persisted analysis-auth.md |
| Deliverables | analysis-apis.md(per interface: real entry + request construction + source of assignment for each input parameter + auth reference + response fields and source annotations) + feasibility verification results |
| Next step | All capabilities have corresponding implementations found → Phase 4 |
| Blocking conditions | Any capability has no corresponding implementation found / dependency chain contains a plugin → Blocking Rule B |
See detailed matching patterns in references/ANALYSIS_PATTERNS.md。
3.1 Extraction scope: scan only the pages/modules corresponding to user-confirmed capabilities, search for network calls (wx.request / wx.cloud.{callFunction,database,callContainer}) + JSAPIs within the whitelist (for the high-frequency list see "Hard Constraint D", for the complete list see references/JSAPI_WHITELIST.md)。
3.2 Dependency tracing (read real source code, replicate verbatim):
For each capability, first locatethe real interaction entry that carries it— the segment of code in the source that triggers the capability (page lifecycle onLoad/onShow, event handler for buttons / input boxes, etc., or the corresponding business function).The interface actually called by this entry point is the sole standard interface for this capability; replicate it verbatim along with the branch parameters it passes in (type / mode flags, etc.). Capabilities correspond one-to-one with interfaces; do not "pick one that is easier to implement" among multiple interfaces with similar names—everything must be based on the real entry point in the source code.
Trace every input parameter back to its real assignment source: do not just replicate the wx.request line—continue tracing every request field upward:页面 data ← onLoad/onShow/event callback ← JSAPI / wx.getStorageSync / globalData / user input. Dynamic values (location, device, login state, etc.) are recorded in analysis-apis.md; stage 5 generates ensureXxx()(see AUTH_MIGRATION.md §4)。When the source has not been traced clearly, it is forbidden to use fixed values as a fallback; the normal path + failure/default branches must be consistent with the main package.
Location migration is on the same level as authentication: when interface input parameters contain coordinates/location, it cannot be skipped just like authentication—trace to the real source, and stage 5 generates
ensureLocation()actually callswx.getLocationto obtain the true value; hardcoding or read-only cache fallback is forbidden (see details inAUTH_MIGRATION.md§4)。
Route by scale(to prevent context explosion)—the main agent does not read source code in advance to judge interface complexity
- Small projects: the main agent reads directly interface by interface (real entry handler → call site → request construction)
- Large projects: assign 1 subagent ② (api analysis) to deeply readbusiness-layer logic(parameter sources / return structure / jump chain), and return a summary of conclusions. Must be started after ① (authentication analysis) is completed; authentication facts have already been written to disk by ①
analysis-auth.md, and ② only references conclusions (with line numbers) and does not repeatedly probe the authentication chain
For the reading budget (direct coordinate access / read-only 1-hop dependencies / single run ≤ ~5 files / return pending confirmation when approaching the limit) and reporting discipline (only return a ≤20-line conclusion summary, zero raw source text), see references/SUBAGENT_PROTOCOL.md §4.
3.3 Authentication dependency confirmation: in conjunction with analysis-auth.md, confirm for each target interface ① whether login state is required ② token source (direct storage read / requires login first) ③ login method (wx.login + token exchange / other). analysis-apis.md only fills in authentication references (requiresLogin / signing / dynamicValues / inherit via common parameters),does not redefine authentication facts, avoiding drift from analysis-auth.md. See details in AUTH_MIGRATION.md §2/§5。
3.4 Signature / requestability: if the interface request contains signature / anti-crawling fields (sign / timestamp+nonce / fingerprint, etc.), record them in the analysis-auth.md signature list (id / scope / trigger / key source / output fields / dependent modules / source snippet pointer), and put the function body verbatim into the verbatim code snippet section.Do not switch interfaces or simplify signatures because of "better implementation"—if the signature is wrong, everything fails. Requestability determination: dependence on runtime human-computer interaction such as CAPTCHA/SMS → replicable: false + blockers → block or manual integration.
3.5 Plugin dependency: if the dependency chain includes requirePlugin / require('../plugin/') / plugin:// → blocking rule B.
3.6 Three-level feasibility check:
| Level | Identifying features | Handling |
|---|---|---|
| ✅ High confidence | The real entry uniquely determines the interface, and the parameter/return path is clear | Proceed directly to stage 4 |
| ⚠️ Medium confidence | Parameters/returns ambiguous, or multiple parallel real entry points | Read more or ask the user |
| ❌ No confidence | Cannot find any implementation | Blocked B |
Medium-confidence inquiry template:
以下原子能力在源码中存在多个并列的真实入口,请确认对应哪一个:
能力:<能力名>
入口 1:<页面/事件> 调用 <接口/云函数> — 参数 <x>、返回 <y>(来自 pages/xxx.js 第 N 行)
入口 2:<页面/事件> 调用 <接口/云函数> — 参数 <x>、返回 <y>(来自 pages/yyy.js 第 M 行)
请按你实际想暴露的小程序功能确认对应哪个入口(接口由能力入口唯一确定,不以实现难易为取舍)。
3.7 Runtime probing (probe, on demand)
By default, do not run probe; finalize directly whatever static analysis can determine. Triggered only in two cases:
- The value is dynamically delivered at runtime: The URL / header / signature parameters in the request are assembled at runtime in the source code (e.g.
baseUrlis dynamically returned bygetApp().globalData), and the real value cannot be read statically - The response structure cannot be determined from the source-code consumption point: The API returns a large number of fields but the page uses only some of them, and the consumption point does not reveal the field hierarchy / nested structure
If any is hit → dispatch subagent ③ (probe) to execute the entire closed loop (write probe/plan.json → run probe → backfill analysis-apis.md; must be started after ①② are completed. For instructions and read boundaries, see references/SUBAGENT_PROTOCOL.md §3.3; for plan format, environment requirements, and result fields, see references/RUNTIME_PROBE.md):
node scripts/probe.mjs --project <源项目> --plan <plan.json>
Each execution is persisted to disk probe/<run-id>.json, read the real response of a successful run to backfill analysis-apis.md the response section of the corresponding API (probe run files are written by the script, not by hand).
- probe succeeded: The response section of that api is marked
sampleSource: probe:<run-id>,apis/<name>.jstop comment[ai-mode:probe] <run-id> 实际响应字段:… - probe was not run or the environment is unavailable: The response section uses the source-code consumption-point fields, marked
sampleSource: static-source, and the top-of-code comment is[ai-mode:static], and when handing off, state to the user that it has not been verified on a real device - Sensitive APIs do not go into the plan: Irreversible APIs such as logout/delete/unbind are never probed (probe-lib.mjs has a built-in interception); if probing is truly needed, explicitly write it in that plan item
"destructive": true+"confirmDestructive": true, and only when explicitly requested by the user
Phase 4 — Atomic API design
Contract:
| Item | Content |
|---|---|
| Entry conditions | Phase 3 completed:analysis-apis.md Each atomic API already has its request construction and response fields (if probe was run, use the real response; if not, use the source-code consumption point); for authentication, reference analysis-auth.md |
| Deliverables | ① Atomic API list; ② API dependency graph; ③ storage key list |
| Next step | All three deliverables complete → Phase 5 |
4.1 Skill division: Atomic APIs in the same business domain (product/order/address) are aggregated into the same skill; APIs that share storage context stay within the same skill; each skill is recommended to have 3-8 atomic APIs (if more, split by sub-business).
4.2 API fields: Each API must contain name(camelCase, globally unique) / description(including internal chained operations, to help the mini-program AI make decisions) / inputSchema(only the parameters that the mini-program AI needs to obtain from the user; if there are no parameters, use {"type":"object","properties":{}}); add as needed outputSchema(recommended to fill in; if the API return has structuredContent with a clear field structure or uses page-link , declare it, based on the response fields in analysis-apis.md) / _meta.ui.pagePath(as needed, handoff page path, without query; APIs of the type "stop after execution and wait for user confirmation" need to be configured, together with the return value handoff, see D.6 for details) / _meta.ui.componentPath(declared only when generating components; for rules see D.3; if declared, the same base path .js / .json / .wxml / .wxss files are complete).
Multimodal input parameters: when the API requires the user to upload an image or file (e.g., photo editing, image recognition, file parsing), add to the corresponding
inputSchema.properties.<field>either"format": "image"or"format": "file", with typestring(fill in the local path at runtime). The Mini Program AI input box will identify it as a multimodal field accordingly and guide the user to upload.
Text mixed with links (
page-link): if the data returned by an API naturally corresponds to a Mini Program page (product, order, store, etc.), and you want the model toinline clickable blue links in the reply body, inoutputSchemamark the page path field as{ "type": "string", "format": "page-link", "x-link-text-field": "<同级描述字段名>" }, and the API'sstructuredContentjust needs to return the real page path according to the schema; the platform will render it as#小程序:名称/描述. For field constraints and a complete example, seereferences/CODE_TEMPLATES.mdSection 4.Difference from handoff:page-linkonly provides one detail entry point, while handoff relays the entire flow into a page—if you only want the former, do not returnhandoff。
Sensitive API marking: Stage 2 already specifies that sensitive APIs are not collected as atomic capabilities by default. If, due to an explicit user request or an oversight, a sensitive API enters Stage 4, you must in
probe/plan.jsonwrite for the corresponding api item"destructive": trueand"destructiveReason": "<一句话原因>"(probe skips based on this). For the determination principles and keyword list, see Stage 2
4.3 How to enter the Mini Program (default handoff): for APIs that require continued operation/viewing details, configure _meta.ui.pagePath + return handoff(see D.6); the user taps the Mini Program card to enter the relay page. When generating atomic components (see D.3 for rules), match the component template according to the return value type (see references/COMPONENT_TEMPLATES.mdfor details): list/card items → generic list; details/single object → detail card; shopping cart/with quantity and total price → shopping cart; order success/payment result/operation confirmation → status result.
4.4 Example deliverables(default form: no components, with handoff):
[{
"skill": "business",
"name": "searchItems",
"title": "检索商品",
"description": "根据关键词检索商品,返回商品列表",
"inputSchema": { "type": "object", "properties": {} },
"outputSchema": { "type": "object", "properties": { "items": { "type": "array" } } },
"_meta": { "ui": { "pagePath": "/pages/goods/list" } }
}]
API dependency graph (required only when passing context through storage):
searchProducts ──(storage: skills_shopping_lastSearchResult)──▶ addToCart
└─(storage: skills_shopping_lastSearchResult)──▶ getProductDetail
Storage key naming unified as skills_{skillName}_{dataName}, with the list containing key / writer / reader / data structure.
Stage 5 — Code generation
Contract:
| Item | Content |
|---|---|
| Entry conditions | All three Stage 4 deliverables are complete;.ai-mode-skills/analysis-auth.md + analysis-apis.md has been written to disk—if missing, go back to the corresponding stage to fill it in (analysis-auth→1.2, analysis-apis→3.2) |
| Deliverables | Complete skills/{skill-name}/(mcp.json / SKILL.md / index.js / apis/* / utils/* / components/*); each apis/<name>.js passes the 5.8 field source self-check |
| Next step | Code generation complete → Stage 6 |
| Blocking conditions | Missing deliverables → stay in this stage until completed |
For code templates see references/CODE_TEMPLATES.md, for component templates see references/COMPONENT_TEMPLATES.md、for design specifications see references/ATOMIC_COMPONENT_DESIGN.md(highest priority), for CSS implementation specifications see references/ATOMIC_COMPONENT_CSS.md。
5.1–5.4 Four prerequisites for components (applicable only when generating components, see D.3; complete them in order before writing any component WXML/WXSS/JS)
Before generating componentsread in full
references/COMPONENT_TEMPLATES.mdandreferences/ATOMIC_COMPONENT_DESIGN.md. Skipping the reading is a common root cause of "the API request succeeds but the component does not render".
| No. | Topic | Key points | See |
|---|---|---|---|
| 5.1 Design specification (highest priority) | Size/theme/margins/fonts/layout/action area | ① 5 aspect ratios + 4px corner radius; ② Theme color is extracted from the main package according to the §2.1 process using app.json/app.wxss (extract both light + dark, with a "color source=…" chain in a comment at the top of the wxss; only fall back to §2.3 if none of the 6 steps for the main package finds it); ③ Margins: screen 16 / card 12 / element 8·16; ④ Font sizes in three tiers 17/15/12 + layering by 0.9/0.45/0.3 opacity of the same base color; ⑤ Main axis top-bottom/left-right layout; for horizontal overflow you can use <scroll-view scroll-x>, vertical scrolling is prohibited, grids with >2 columns are prohibited; ⑥ ≤3 controls, ≤1 primary action, verb-object copy, primary button on the right |
references/ATOMIC_COMPONENT_DESIGN.md |
| 5.2 Source style extraction + field mapping | 7-step workflow | When there is a conflict with the design specification, thedesign specification prevails, and only the source project's brand color and field mapping results are migrated.Self-check: the wxss primary color is #07c160 / #ff4d4f and the source page does not use it, or the wxml contains item.imageUrl but the source API field is cover/pic/thumb — treat it as "copying the template", and redo it from scratch |
references/STYLE_MIGRATION.md |
| 5.3 Component interaction behavior | A component is the mini program AI's "turn exit", not a "page entry" | Every component must consider both "what to display" + "what the user does next" — according to mcp.json.apis[].description + API dependency graph, list the next step and map it to mcp.json.apis[].name already existingAPIs; if it does not exist, remove the button, anddo not send an upstream name that does not exist. Every interactive element binds bindtap + hover-class, and key entities use data-* to carry |
references/COMPONENT_TEMPLATES.md "upstream message" section |
| 5.4 Component JS skeleton (data access) | Data can only be delivered via NotificationType.Result delivery |
Prohibited properties / dataSource / observers; follow the COMPONENT_TEMPLATES.md skeleton in created to bind Result and Overflow, and print [ai-mode] {componentName} overflow monitor=on |
references/COMPONENT_TEMPLATES.md "Component JS skeleton" section + "overflow handling template" section |
the tap handler's content form (prefer form 2:text + api/call combination),name / arguments alignment rules, logging requirements, and prohibited items, see references/COMPONENT_TEMPLATES.md "upstream message" section.
5.5 Directory structure
{项目根目录}/
├── app.json # 含 agent.skills 注册
└── skills/ # 独立分包(多 skill 共用)
├── _shared/ # 可选:≥2 个 skill 共用的工具函数才放这里
└── {skill-name}/
├── mcp.json # 原子接口 Schema 定义
├── SKILL.md # skill 路由说明
├── index.js # 接口注册入口
├── apis/ # 原子接口实现(推荐目录;validator 兼容 tools/services/、tools/)
├── utils/ # 工具模块(目录名不限,常见 utils/services/helpers)
└── components/{component-name}/ # 默认组件目录;实际组件文件由 mcp.json 的相对 componentPath 决定
Directory layering: cross-skill prohibited
require('../../{otherSkill}/...'); multi-skill reuse goes throughskills/_shared/(not registered inmcp.json, and does not callregisterAPI)。
5.6 Auth code generation
Generate AUTH_MIGRATION.md according to §5/§6 of utils/request.js + index.js; for the template see CODE_TEMPLATES.md. After generation, go through the AUTH_MIGRATION §6 self-check list (item by item).
5.7 mcp.json + the skill's own SKILL.md + return values + logs
mcp.json: top-level{ "apis": [...] }, each item must containname/description/inputSchema;outputSchemais optional, recommended to fill in, and when the API return has a clear field structure forstructuredContentor when usingpage-link, it should be declared. Add_meta.ui.pagePathas needed for APIs entering the mini program (matching the return valuehandoff);_meta.ui.componentPathandcomponents[]Only generated when generating components (components[]ofrelatedPagerequired, real-time dynamic capabilities as needed, see D.3 for details). For size limits seereferences/CODE_TEMPLATES.md6.3 (alloutputSchemaare removed during calculation). For a complete field example seereferences/CODE_TEMPLATES.mdSection 4- The skill's own
SKILL.md(file name strictly all uppercase) is the business orchestration and routing description,in the order of the 5 sections: capability domain positioning → trigger scenarios (user's original words few-shot) → out-of-scope cases → preconditions → usage order. The usage order can describe business processes, registered method names, preconditions, upstream/downstream dependencies, and cross-interface rules; method names must matchmcp.json.apis[].nameverbatim.Throughout, do not write:inputSchema/outputSchema/ parameter table / return value table /componentPath/ storage key / implementation details / install CLI operations. For size limits seereferences/CODE_TEMPLATES.md6.3, and only a single file is supported, with no references to other md files. For the complete template seereferences/CODE_TEMPLATES.mdSection 5 - Return value format:
{ isError?, content: [{type:'text', text}], structuredContent?, _meta?, handoff?, apiCalls? }——contentprovides text to the LLM,structuredContentwhen there isoutputSchemait must be aligned with it,_metais invisible to the LLM and can pass UI components;handoff(entering the mini program as needed) is{ query?, payload?, path? }, which takes over the card click to enter the relay page, see D.6 for details.content/structuredContent/_metaFor size limits seereferences/CODE_TEMPLATES.md6.3 apiCalls(as needed, used when the process is fixed): add at the top level of the return valueapiCalls: [{ name, arguments }]canexplicitly specify the atomic interface to call next, eliminating the model reasoning step and making the chain faster. Typical scenario: discovering within the interface that the user is not logged in → returnapiCalls: [{ name: 'login', arguments: {} }]。namemust be an interface already declared in the current skillmcp.json.apis[],argumentswith itsinputSchemaaligned.Only write it when the source business process is inherently fixed in its connections, open-ended scenarios are still left to the model to judge- Logging specification: atomic interfaces log entry / input parameters / before and after request / exit / catch; atomic components log
created/attached/ receive Result /setData/NotificationType.Overflow(used for validation and trimming). Unified prefix[ai-mode]. When failures occur on real devices, rely on these nodes to locate the problem; logs must be complete
5.8 Field fidelity self-check
After finishing each
apis/<name>.js, check itsstructuredContentfield set on the spot: if that api has a probe real response inanalysis-apis.md, compare against the real response fields; if not, compare against the fields actually consumed by the source page. Check one as soon as it is generated, do not save them all for the end.
- Fields consistent → pass, continue to the next
- Missing/extra fields → code fabrication, correct based on the record
structuredContent; if already declared,outputSchemaalso correct that schema accordingly
Phase 6 — Configuration Integration
Contract:
| Item | Content |
|---|---|
| Entry conditions | Phase 5 generated complete skills/{skill-name}/ |
| Deliverables | app.json includes agent.skills + subPackages;project.config.json of packOptions.include includes skills |
| Next step | Both configuration files have been updated → hand off wxa-skills-validate |
| Blocking conditions | Handing off directly without updating the configuration → will definitely fail, stay in this phase |
| Artifact verification | Before handoffMust confirm the following files exist:skills/{skill-name}/mcp.json + skills/{skill-name}/index.js + each apis/*.js + utils/request.js(or utils/util.js);app.json 's agent.skills[] contains this skill entry and subPackages contains skills independent subpackage;project.config.json 's packOptions.include contains skills. If any is missing → return to stage 5 to add it |
For the configuration format, see references/CODE_TEMPLATES.md Section 6. Key points:
- Multiple skills share the same
skillsindependent subpackage—when adding a skill, only append toagent.skills[]in{ name, description, path }, do not add asubPackagesentry for each skill. Note that the reverse does not hold:one SKILL cannot span subpackages - handoff (as needed): if an interface is configured with
_meta.ui.pagePathand returnshandoff, in the main packageapp.js'sonLaunchregisterwx.onAgentHandoff(see D.6 andreferences/CODE_TEMPLATES.mdthe "handoff relay page" section)
6.1 Global prompt AGENTS.md(as needed)
When multiple skills coexist, or when you need to convey the overall service scope / background knowledge / response style, write a AGENTS.md and in app.json use agent.instruction to point to it (a path relative to the project root). The content is positioned as "global instructions across skills"—service boundaries, the relationships among skills, and the basis for choosing between them; routing instructions internal to a single skill should still be written in that skill's own SKILL.md , do not repeat them. For the template and limits, see references/CODE_TEMPLATES.md Section 6.1.
6.2 Mini Program service direct access page-meta.json(as needed)
When the user intenthas no corresponding atomic interface, and can only lead into a Mini Program page, configure agent.pageMetadata to point to page-meta.json, and the platform will reply with an "account card" accordingly (scene values 1435 / 1436). For entry fields, limits, and templates, see references/CODE_TEMPLATES.md Section 6.2.
6.3 Size and count limits (self-check after generation)
For the limits table, see references/CODE_TEMPLATES.md Section 6.3. Exceeding the limits will cause the platform to reject it during preview / upload.
Wrap-up — hand off to wxa-skills-validate
After stage 6 is complete, clearly inform the user in the reply:
代码生成与配置集成已完成。下一步请使用 `wxa-skills-validate` skill 对产物进行校验与真机验证:
- skills 路径:<abs-path>/skills
- project-path:<abs-path>(含 project.config.json 的 appid 为 <appid>)
wxa-skills-validate 会依次执行:静态校验 → cli agent tool execute → cli agent render → 交付文档。
Outputting code alone does not count as complete—explicitly prompt the user in the conversation to switch to the validation skill before this skill is considered finished.
Suggestion: on complex projects, after handoff, the entire
wxa-skills-validateprocess can be delegated to a subagent for execution (a separate context window, to avoid the validation process crowding out the main context).