@mistflow-ai/mcp 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +177 -177
  2. package/dist/index.js +174 -174
  3. package/package.json +4 -1
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var fl=Object.defineProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tn=(t,e)=>{for(var r in e)fl(t,r,{get:e[r],enumerable:!0})};function Ls(){let t=[];return t.push("Mistflow is a full-stack app builder that creates and deploys web apps from natural language descriptions. When a user asks to build, create, or make a web app, website, landing page, dashboard, internal tool, marketplace, content site, or browser game, use Mistflow tools. Mistflow creates NEW apps from scratch. It does NOT modify existing non-Mistflow codebases."),t.push(""),t.push('Every capability is an MCP tool. There is no companion CLI. Long-running work (install, build, qa, deploy) uses the fire-and-poll pattern: the first call returns a jobId and `status: "running"`; subsequent calls with that jobId return fresh state. Each call responds in under a second \u2014 no 60s timeout risk.'),t.push(""),t.push(Tl),t.push(""),t.push(yl),t.push(""),t.push(bl),t.push(""),t.push(wl),t.push(""),t.push(vl),t.push(""),t.push(_l),t.push(""),t.push(xl),t.push(""),t.push("New app workflow:"),t.push("1. Choose destination: if the user didn't already give a path, ask whether to scaffold in the current folder or a new subfolder here. Resolve the absolute path before mist_init."),t.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via your host\'s native question tool (AskUserQuestion in Claude Code / request_user_input in Codex Plan mode / quick pick in Cursor / stop-and-wait for hosts without one \u2014 see RULE_SENTINEL_HANDLING), collect the user\'s actual answers, then submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick via mist_plan with `designConversationId` + `designDirection` (NOT `conversationId` alone).'),t.push("3. Mockup (optional, recommended): call mist_mockup with the planId \u2014 returns a wireframe prompt. Write the HTML to the returned path, open it for the user, wait for approval. Iterate with { feedback }, lock with { approved: true }."),t.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),t.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),t.push("6. Implement: mist_implement runs one plan step at a time and auto-marks the prior step complete. Call repeatedly until all steps are done."),t.push("7. Build: mist_build { projectPath } starts; poll with { jobId }. On failure, the response has `missingModules[]` \u2014 chain mist_install with those modules then mist_build again without asking."),t.push("8. Deploy: mist_deploy { projectPath } starts tar + upload; poll with { action: 'status', deploymentId }. On complete, response has `qaRequired: true` and a `url` \u2014 do NOT surface the URL to the user until mist_qa passes. Subsequent actions: 'promote' (staging \u2192 prod), 'rollback' (revert to a specific deploymentId)."),t.push("9. QA: mist_qa { projectPath } drives Playwright in-process against the live URL \u2014 single synchronous call (~20\u201345s), returns pass/fail and screenshots inline. Only surface the deploy URL to the user after mist_qa returns status: 'pass'."),t.push(""),t.push(kl),t.push(""),t.push(Sl),t.push(""),t.push("Updating an existing Mistflow app:"),t.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),t.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),t.push("- Feature needing new data model: ask product questions, call mist_project action='get' for context, call mist_plan with existingPlanId, then mist_implement, then mist_build \u2192 mist_deploy."),t.push("- Integration addition: ask product questions, mist_project action='get', mist_plan with existingPlanId, mist_implement, mist_config resource='env' for keys, mist_build \u2192 mist_deploy \u2192 mist_qa."),t.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),t.push(""),t.push("Tool summary:"),t.push("- mist_setup: authentication. Only call when the user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth."),t.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),t.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),t.push("- mist_help: returns the full tool reference. Call once per session."),t.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),t.push("- mist_install / mist_build / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),t.push("- mist_qa: synchronous single call. Drives Playwright in-process against the deployed URL. No jobId / no polling \u2014 one call returns the full QA result with screenshots."),t.join(`
3
- `)}var yl,bl,wl,vl,kl,xl,Sl,Tl,_l,Rs,Es,Ns,Os,js,Ds,Ms,Ke=P(()=>{"use strict";yl="mist_plan uses the fire-and-poll shape: the first call returns quickly with status 'running' and a conversationId while the backend Sonnet ask_questions call runs in the background (that call alone can take 30-150s). Poll by calling mist_plan with just { conversationId } every ~10-15s until status is 'clarify' (questions arrived) or 'ready' (plan generated). Do NOT re-send description or answers while polling \u2014 the conversation is already tracked server-side.",bl='Treat the tool\'s returned JSON as authoritative. If `mist_plan` returns `status: "clarify"`, the planning call completed and is waiting on user answers. Do NOT rerun the same call or describe it as "still generating". Only poll again when `status: "design_clarify_pending"`.',wl="When submitting discovery answers back to `mist_plan` (conversationId + answers), pass `answers` as an ARRAY of objects directly: `answers: [{question, decisionKey, answer}, ...]`. Do NOT JSON-stringify the array \u2014 pass the raw array literal. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",vl="Before scaffolding a NEW app, resolve the destination path explicitly. If the user asked to create/build a new app and the current directory is not already that Mistflow project, ask whether to scaffold in the current folder or a new subfolder here (unless the user already gave a path). Do NOT inspect sibling directories and silently adopt one as the base just because it looks similar. Reuse an existing Mistflow project only when the user explicitly asks to continue/edit that project.",kl='Once the user approves the plan, the mist_init \u2192 mist_install \u2192 mist_implement (repeat) \u2192 mist_build \u2192 mist_deploy \u2192 mist_qa chain is expected. Do NOT pause between these calls to ask the user "should I continue?" or offer options like "full build vs step-by-step." A tool returns a status that requires user input when it genuinely needs one (e.g. confirm_new_project, awaiting promotion). Otherwise chain calls continuously. Brief one-line status updates are fine; permission requests are not.',xl="mist_init is all-or-nothing for normal users: it registers the cloud project first, scaffolds in a temp directory, then moves the finished app into place only after both steps succeed. If auth, quota, or network registration fails, stop before any app appears locally. Do NOT suggest reusing another app unless the user explicitly asks.",Sl="If mist_init fails, stop before any cloud command and explain why. Do NOT default to reusing some other existing app as recovery unless the user explicitly asked to continue that app.",Tl='Long-running tools (mist_plan, mist_install, mist_build, mist_qa, mist_deploy) use the fire-and-poll pattern. The first call returns `status: "running"` with a `jobId` or `conversationId`. Every subsequent call with that same id returns the current state \u2014 re-call IMMEDIATELY whenever you see `status: "running"`. DO NOT run `bash sleep`, `setTimeout`, or any wall-clock wait between polls \u2014 Claude Code\'s harness blocks standalone sleeps, and every MCP server poll endpoint holds the connection up to ~10-15s on its side already, returning as soon as state changes. Just call the tool again. Each response is well inside the 60s MCP ceiling. When `status: "complete"` or `"failed"` arrives, the tool is done. Never assume a job stalled because a single call took 10s \u2014 calls return fast, but the work keeps running in the background. Do not ask the user whether to keep polling; polling is how these tools work.',_l="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST ask the user and WAIT for their actual answer before submitting anything back. Use your host's native structured-question UI: `AskUserQuestion` in Claude Code, quick pick in Cursor, `request_user_input` in OpenAI Codex (available in Plan mode \u2014 if Codex returns 'request_user_input is unavailable in <mode> mode', you are in default mode; stop your turn and print the questions as a numbered chat message, then wait for the user's next message). For any host that does not expose a structured question tool, stop your turn immediately, print the questions verbatim as a numbered list with all options visible, and wait \u2014 the user's next message is the answer. The rule across every host: you never submit answers to `mist_plan` in the same turn you received the questions. That is always wrong, regardless of how obvious the `recommended` choice looks, regardless of whether you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode. The `recommended` field is a hint FOR the user, not permission FOR you. Anti-example from a real transcript: the host AI received 7 discovery questions, wrote 'I'll lock in the defaults with Azure OpenAI as the only override,' submitted answers the user never saw, and the user ended up with a plan they didn't choose. That behavior is a regression bug. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to perform that submission step; that is your job.",Rs="Connect the user's Mistflow account. Call this ONLY when: (a) the user has literally never signed in, or (b) a previous tool call returned error code 'auth_missing' or 'auth_revoked'. DO NOT call this tool in response to 500 errors, 404 errors, network errors, or any generic failure \u2014 those are backend issues, not auth issues. Running mist_setup when not needed wastes the user's time and creates login fatigue. Once signed in, the MCP persists a long-lived API key and never asks again. Two-phase device code flow: (1) Call without deviceCode \u2014 opens browser, returns status 'pending' with deviceCode and userCode. Tell the user the verification code and that they need to approve in the browser. (2) Call again with deviceCode after ~15 seconds \u2014 polls for approval. Also accepts an apiKey for headless auth (skips device code entirely).",Es="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'integrations' browses the curated integration blueprint catalog (pass integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",Ns="Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",Os="Returns the full Mistflow MCP tool reference. Call ONCE at session start (or whenever unsure which tool to pick) to learn the 14-tool surface, the fire-and-poll pattern, and how to chain end-to-end from mist_plan through mist_qa. Static \u2014 no backend round-trip, safe to call frequently.",js="Fetch a per-topic Mistflow methodology doc on demand. Two actions: `list` returns the catalog (id, title, kind, description) so you can discover what's available; `get` returns the full markdown for one topic. Topic kinds: 'stack' (framework patterns \u2014 Drizzle, Better Auth, server actions, components, styling), 'skill' (design + structural patterns \u2014 auth-design, app-design, admin-panel, blob-storage), 'integration' (third-party services \u2014 Stripe, Resend, OpenAI, Anthropic, Twilio, etc.). Call BEFORE writing or modifying code that touches an integration or a stack-specific pattern. Lazy-loaded \u2014 pulls only the topic you need instead of paying for the full AGENTS.md monolith every turn. Same content as AGENTS.md / .claude/skills/<topic>/SKILL.md / .cursor/rules/<topic>.mdc on disk; use this tool when those aren't auto-discovered by your host.",Ds="Analyze build errors from a Next.js / TypeScript project. Extracts structured errors with file, line, a human-readable message for the user, and an actionable suggestion. Call with { projectPath } to run `npm run build` and parse the failure; call with { buildOutput } to parse output captured elsewhere (e.g. from a failed mist_build job).",Ms="Generate a grayscale wireframe sketch of the planned app so the user can review layout + information hierarchy before any code is written. The server returns a structured spec + a wireframePrompt \u2014 the host AI writes the HTML file to .mistflow/mockups/mockup-<planId>.html and opens it. Pass { planId } for the first iteration, { planId, feedback: '...' } to iterate, { planId, approved: true } to lock the design before mist_init. Iterative by design \u2014 expect 1-3 rounds of feedback."});import{existsSync as br,readFileSync as qs,writeFileSync as Pl,mkdirSync as Il}from"fs";import{join as fr,dirname as yr}from"path";import{homedir as Cl}from"os";import{fileURLToPath as Al}from"url";function $e(){if(_n)return _n;try{let t=Al(import.meta.url),e=yr(t);for(let r=0;r<6;r++){let n=fr(e,"package.json");if(br(n)){let o=JSON.parse(qs(n,"utf-8"));if(o.name==="@mistflow-ai/mcp"&&typeof o.version=="string")return _n=o.version,o.version}let i=yr(e);if(i===e)break;e=i}}catch{}return _n="0.0.0","0.0.0"}function Pn(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function Us(t,e){let r=Pn(t),n=Pn(e);if(!r||!n)return 0;for(let i=0;i<3;i++){if(r[i]<n[i])return-1;if(r[i]>n[i])return 1}return 0}function Bs(t,e,r){if(r&&Us(t,r)<0)return"unsupported";if(!e||Us(t,e)>=0)return"none";let i=Pn(t),o=Pn(e);return!i||!o?"none":i[0]<o[0]?"major":i[1]<o[1]?"minor":"patch"}function Xt(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||(Ue={latest:e,minSupported:r,changelogUrl:n})}function zs(){let t=process.env.MISTFLOW_STATE_DIR||fr(Cl(),".mistflow");return fr(t,"upgrade-state.json")}function Rl(){try{let t=zs();return br(t)?JSON.parse(qs(t,"utf-8")):{}}catch{return{}}}function El(t){try{let e=zs(),r=yr(e);br(r)||Il(r,{recursive:!0}),Pl(e,JSON.stringify(t,null,2)+`
4
- `,{mode:384})}catch{}}function Nl(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Hs(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!Ue)return null;let t=$e();if(t==="0.0.0")return null;let e=Bs(t,Ue.latest,Ue.minSupported);if(e==="none")return null;if(e==="unsupported")return Fs(e,t,Ue);if($s)return null;let r=Rl(),n=Date.now(),i=Nl(e);return r.dismissedForVersion===Ue.latest&&e!=="major"||r.lastLatestSeen===Ue.latest&&r.lastShownMs&&n-r.lastShownMs<i?null:($s=!0,El({...r,lastShownMs:n,lastLatestSeen:Ue.latest}),Fs(e,t,Ue))}function Fs(t,e,r){let n="npx -y mistflow-ai install",i=r.changelogUrl?`
2
+ var yl=Object.defineProperty;var _=(t,e)=>()=>(t&&(e=t(t=0)),e);var _n=(t,e)=>{for(var r in e)yl(t,r,{get:e[r],enumerable:!0})};function Us(){let t=[];return t.push("Mistflow is a full-stack app builder that creates and deploys web apps from natural language descriptions. When a user asks to build, create, or make a web app, website, landing page, dashboard, internal tool, marketplace, content site, or browser game, use Mistflow tools. Mistflow creates NEW apps from scratch. It does NOT modify existing non-Mistflow codebases."),t.push(""),t.push('Every capability is an MCP tool. There is no companion CLI. Long-running work (install, build, qa, deploy) uses the fire-and-poll pattern: the first call returns a jobId and `status: "running"`; subsequent calls with that jobId return fresh state. Each call responds in under a second \u2014 no 60s timeout risk.'),t.push(""),t.push(_l),t.push(""),t.push(bl),t.push(""),t.push(wl),t.push(""),t.push(vl),t.push(""),t.push(kl),t.push(""),t.push(Pl),t.push(""),t.push(Sl),t.push(""),t.push("New app workflow:"),t.push("1. Choose destination: if the user didn't already give a path, ask whether to scaffold in the current folder or a new subfolder here. Resolve the absolute path before mist_init."),t.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via your host\'s native question tool (AskUserQuestion in Claude Code / request_user_input in Codex Plan mode / quick pick in Cursor / stop-and-wait for hosts without one \u2014 see RULE_SENTINEL_HANDLING), collect the user\'s actual answers, then submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick via mist_plan with `designConversationId` + `designDirection` (NOT `conversationId` alone).'),t.push("3. Mockup (optional, recommended): call mist_mockup with the planId \u2014 returns a wireframe prompt. Write the HTML to the returned path, open it for the user, wait for approval. Iterate with { feedback }, lock with { approved: true }."),t.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),t.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),t.push("6. Implement: mist_implement runs one plan step at a time and auto-marks the prior step complete. Call repeatedly until all steps are done."),t.push("7. Build: mist_build { projectPath } starts; poll with { jobId }. On failure, the response has `missingModules[]` \u2014 chain mist_install with those modules then mist_build again without asking."),t.push("8. Deploy: mist_deploy { projectPath } starts tar + upload; poll with { action: 'status', deploymentId }. On complete, response has `qaRequired: true` and a `url` \u2014 do NOT surface the URL to the user until mist_qa passes. Subsequent actions: 'promote' (staging \u2192 prod), 'rollback' (revert to a specific deploymentId)."),t.push("9. QA: mist_qa { projectPath } drives Playwright in-process against the live URL \u2014 single synchronous call (~20\u201345s), returns pass/fail and screenshots inline. Only surface the deploy URL to the user after mist_qa returns status: 'pass'."),t.push(""),t.push(xl),t.push(""),t.push(Tl),t.push(""),t.push("Updating an existing Mistflow app:"),t.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),t.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),t.push("- Feature needing new data model: ask product questions, call mist_project action='get' for context, call mist_plan with existingPlanId, then mist_implement, then mist_build \u2192 mist_deploy."),t.push("- Integration addition: ask product questions, mist_project action='get', mist_plan with existingPlanId, mist_implement, mist_config resource='env' for keys, mist_build \u2192 mist_deploy \u2192 mist_qa."),t.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),t.push(""),t.push("Tool summary:"),t.push("- mist_setup: authentication. Only call when the user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth."),t.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),t.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),t.push("- mist_help: returns the full tool reference. Call once per session."),t.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),t.push("- mist_install / mist_build / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),t.push("- mist_qa: synchronous single call. Drives Playwright in-process against the deployed URL. No jobId / no polling \u2014 one call returns the full QA result with screenshots."),t.join(`
3
+ `)}var bl,wl,vl,kl,xl,Sl,Tl,_l,Pl,Es,Ns,Os,Ds,js,Ms,Ls,Je=_(()=>{"use strict";bl="mist_plan uses the fire-and-poll shape: the first call returns quickly with status 'running' and a conversationId while the backend Sonnet ask_questions call runs in the background (that call alone can take 30-150s). Poll by calling mist_plan with just { conversationId } every ~10-15s until status is 'clarify' (questions arrived) or 'ready' (plan generated). Do NOT re-send description or answers while polling \u2014 the conversation is already tracked server-side.",wl='Treat the tool\'s returned JSON as authoritative. If `mist_plan` returns `status: "clarify"`, the planning call completed and is waiting on user answers. Do NOT rerun the same call or describe it as "still generating". Only poll again when `status: "design_clarify_pending"`.',vl="When submitting discovery answers back to `mist_plan` (conversationId + answers), pass `answers` as an ARRAY of objects directly: `answers: [{question, decisionKey, answer}, ...]`. Do NOT JSON-stringify the array \u2014 pass the raw array literal. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",kl="Before scaffolding a NEW app, resolve the destination path explicitly. If the user asked to create/build a new app and the current directory is not already that Mistflow project, ask whether to scaffold in the current folder or a new subfolder here (unless the user already gave a path). Do NOT inspect sibling directories and silently adopt one as the base just because it looks similar. Reuse an existing Mistflow project only when the user explicitly asks to continue/edit that project.",xl='Once the user approves the plan, the mist_init \u2192 mist_install \u2192 mist_implement (repeat) \u2192 mist_build \u2192 mist_deploy \u2192 mist_qa chain is expected. Do NOT pause between these calls to ask the user "should I continue?" or offer options like "full build vs step-by-step." A tool returns a status that requires user input when it genuinely needs one (e.g. confirm_new_project, awaiting promotion). Otherwise chain calls continuously. Brief one-line status updates are fine; permission requests are not.',Sl="mist_init is all-or-nothing for normal users: it registers the cloud project first, scaffolds in a temp directory, then moves the finished app into place only after both steps succeed. If auth, quota, or network registration fails, stop before any app appears locally. Do NOT suggest reusing another app unless the user explicitly asks.",Tl="If mist_init fails, stop before any cloud command and explain why. Do NOT default to reusing some other existing app as recovery unless the user explicitly asked to continue that app.",_l='Long-running tools (mist_plan, mist_install, mist_build, mist_qa, mist_deploy) use the fire-and-poll pattern. The first call returns `status: "running"` with a `jobId` or `conversationId`. Every subsequent call with that same id returns the current state \u2014 re-call IMMEDIATELY whenever you see `status: "running"`. DO NOT run `bash sleep`, `setTimeout`, or any wall-clock wait between polls \u2014 Claude Code\'s harness blocks standalone sleeps, and every MCP server poll endpoint holds the connection up to ~10-15s on its side already, returning as soon as state changes. Just call the tool again. Each response is well inside the 60s MCP ceiling. When `status: "complete"` or `"failed"` arrives, the tool is done. Never assume a job stalled because a single call took 10s \u2014 calls return fast, but the work keeps running in the background. Do not ask the user whether to keep polling; polling is how these tools work.',Pl="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST ask the user and WAIT for their actual answer before submitting anything back. Use your host's native structured-question UI: `AskUserQuestion` in Claude Code, quick pick in Cursor, `request_user_input` in OpenAI Codex (available in Plan mode \u2014 if Codex returns 'request_user_input is unavailable in <mode> mode', you are in default mode; stop your turn and print the questions as a numbered chat message, then wait for the user's next message). For any host that does not expose a structured question tool, stop your turn immediately, print the questions verbatim as a numbered list with all options visible, and wait \u2014 the user's next message is the answer. The rule across every host: you never submit answers to `mist_plan` in the same turn you received the questions. That is always wrong, regardless of how obvious the `recommended` choice looks, regardless of whether you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode. The `recommended` field is a hint FOR the user, not permission FOR you. Anti-example from a real transcript: the host AI received 7 discovery questions, wrote 'I'll lock in the defaults with Azure OpenAI as the only override,' submitted answers the user never saw, and the user ended up with a plan they didn't choose. That behavior is a regression bug. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to perform that submission step; that is your job.",Es="Connect the user's Mistflow account. Call this ONLY when: (a) the user has literally never signed in, or (b) a previous tool call returned error code 'auth_missing' or 'auth_revoked'. DO NOT call this tool in response to 500 errors, 404 errors, network errors, or any generic failure \u2014 those are backend issues, not auth issues. Running mist_setup when not needed wastes the user's time and creates login fatigue. Once signed in, the MCP persists a long-lived API key and never asks again. Two-phase device code flow: (1) Call without deviceCode \u2014 opens browser, returns status 'pending' with deviceCode and userCode. Tell the user the verification code and that they need to approve in the browser. (2) Call again with deviceCode after ~15 seconds \u2014 polls for approval. Also accepts an apiKey for headless auth (skips device code entirely).",Ns="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'integrations' browses the curated integration blueprint catalog (pass integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",Os="Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",Ds="Returns the full Mistflow MCP tool reference. Call ONCE at session start (or whenever unsure which tool to pick) to learn the 14-tool surface, the fire-and-poll pattern, and how to chain end-to-end from mist_plan through mist_qa. Static \u2014 no backend round-trip, safe to call frequently.",js="Fetch a per-topic Mistflow methodology doc on demand. Two actions: `list` returns the catalog (id, title, kind, description) so you can discover what's available; `get` returns the full markdown for one topic. Topic kinds: 'stack' (framework patterns \u2014 Drizzle, Better Auth, server actions, components, styling), 'skill' (design + structural patterns \u2014 auth-design, app-design, admin-panel, blob-storage), 'integration' (third-party services \u2014 Stripe, Resend, OpenAI, Anthropic, Twilio, etc.). Call BEFORE writing or modifying code that touches an integration or a stack-specific pattern. Lazy-loaded \u2014 pulls only the topic you need instead of paying for the full AGENTS.md monolith every turn. Same content as AGENTS.md / .claude/skills/<topic>/SKILL.md / .cursor/rules/<topic>.mdc on disk; use this tool when those aren't auto-discovered by your host.",Ms="Analyze build errors from a Next.js / TypeScript project. Extracts structured errors with file, line, a human-readable message for the user, and an actionable suggestion. Call with { projectPath } to run `npm run build` and parse the failure; call with { buildOutput } to parse output captured elsewhere (e.g. from a failed mist_build job).",Ls="Generate a grayscale wireframe sketch of the planned app so the user can review layout + information hierarchy before any code is written. The server returns a structured spec + a wireframePrompt \u2014 the host AI writes the HTML file to .mistflow/mockups/mockup-<planId>.html and opens it. Pass { planId } for the first iteration, { planId, feedback: '...' } to iterate, { planId, approved: true } to lock the design before mist_init. Iterative by design \u2014 expect 1-3 rounds of feedback."});import{existsSync as wr,readFileSync as Bs,writeFileSync as Il,mkdirSync as Cl}from"fs";import{join as yr,dirname as br}from"path";import{homedir as Al}from"os";import{fileURLToPath as Rl}from"url";function qe(){if(Pn)return Pn;try{let t=Rl(import.meta.url),e=br(t);for(let r=0;r<6;r++){let n=yr(e,"package.json");if(wr(n)){let o=JSON.parse(Bs(n,"utf-8"));if(o.name==="@mistflow-ai/mcp"&&typeof o.version=="string")return Pn=o.version,o.version}let i=br(e);if(i===e)break;e=i}}catch{}return Pn="0.0.0","0.0.0"}function In(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function $s(t,e){let r=In(t),n=In(e);if(!r||!n)return 0;for(let i=0;i<3;i++){if(r[i]<n[i])return-1;if(r[i]>n[i])return 1}return 0}function zs(t,e,r){if(r&&$s(t,r)<0)return"unsupported";if(!e||$s(t,e)>=0)return"none";let i=In(t),o=In(e);return!i||!o?"none":i[0]<o[0]?"major":i[1]<o[1]?"minor":"patch"}function Zt(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||(Fe={latest:e,minSupported:r,changelogUrl:n})}function Hs(){let t=process.env.MISTFLOW_STATE_DIR||yr(Al(),".mistflow");return yr(t,"upgrade-state.json")}function El(){try{let t=Hs();return wr(t)?JSON.parse(Bs(t,"utf-8")):{}}catch{return{}}}function Nl(t){try{let e=Hs(),r=br(e);wr(r)||Cl(r,{recursive:!0}),Il(e,JSON.stringify(t,null,2)+`
4
+ `,{mode:384})}catch{}}function Ol(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Ws(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!Fe)return null;let t=qe();if(t==="0.0.0")return null;let e=zs(t,Fe.latest,Fe.minSupported);if(e==="none")return null;if(e==="unsupported")return qs(e,t,Fe);if(Fs)return null;let r=El(),n=Date.now(),i=Ol(e);return r.dismissedForVersion===Fe.latest&&e!=="major"||r.lastLatestSeen===Fe.latest&&r.lastShownMs&&n-r.lastShownMs<i?null:(Fs=!0,Nl({...r,lastShownMs:n,lastLatestSeen:Fe.latest}),qs(e,t,Fe))}function qs(t,e,r){let n="npx -y mistflow-ai install",i=r.changelogUrl?`
5
5
  What's new: ${r.changelogUrl}`:"";return t==="unsupported"?`
6
6
 
7
7
  ---
@@ -21,7 +21,7 @@ This is a major update. Run \`${n}\` and restart your editor.${i}
21
21
  --- Mistflow update available: ${e} -> ${r.latest} ---
22
22
  Run \`${n}\` to upgrade, then restart your editor.${i}`:`
23
23
 
24
- (Mistflow ${r.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function wr(){let t=$e(),e=Ue??{latest:"",minSupported:"",changelogUrl:""},r=Bs(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:Ue!==null}}var _n,Ue,$s,Zt=P(()=>{"use strict";_n=null;Ue=null;$s=!1});var nn={};Tn(nn,{closeBrowser:()=>kr,getIsolatedContext:()=>jl,getPage:()=>vr,getSnapshot:()=>en,takeScreenshot:()=>tn});async function Ws(){try{return await import("playwright")}catch{throw new Error("Playwright is not installed. Run: cd packages/mcp-server && pnpm add playwright && npx playwright install chromium")}}async function Ol(){let t=await Ws();return(!Fe||!Fe.isConnected())&&(Fe=await t.chromium.launch({headless:!0})),ot&&(await ot.close().catch(()=>{}),ot=null),ot=await Fe.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Je=await ot.newPage(),Je}async function vr(){return Je&&!Je.isClosed()?Je:(In||(In=Ol().finally(()=>{In=null})),In)}async function kr(){Je&&!Je.isClosed()&&await Je.close().catch(()=>{}),ot&&await ot.close().catch(()=>{}),Fe?.isConnected()&&await Fe.close().catch(()=>{}),Je=null,ot=null,Fe=null}async function jl(){let t=await Ws();(!Fe||!Fe.isConnected())&&(Fe=await t.chromium.launch({headless:!0}));let e=await Fe.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function en(t){return await t.locator("body").ariaSnapshot()}async function tn(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var Fe,ot,Je,In,Et=P(()=>{"use strict";Fe=null,ot=null,Je=null,In=null;process.once("SIGTERM",()=>{kr().finally(()=>process.exit(0))});process.once("SIGINT",()=>{kr().finally(()=>process.exit(0))})});function p(t,e=!1){let r=t;try{let n=Hs();n&&(r=t+n)}catch{}return{content:[{type:"text",text:r}],isError:e}}function Ee(t){let e={status:"setup_required",reason:"no_credentials",intent:t,instruction:`You must sign in to Mistflow before you can ${t}. Call mist_setup({}) \u2014 it walks the user through device-code authentication (typically <60s). Only retry the original call AFTER mist_setup has fully completed sign-in (status field is no longer "pending").`,nextAction:`Step 1: Call mist_setup({}) now. Do not ask the user for permission first \u2014 sign-in is a precondition for this flow, not a decision point. Step 2: mist_setup returns immediately with a signInUrl + userCode. Show the URL and code to the user and wait for them to approve in their browser. Step 3: If the response had status: "pending", call mist_setup again with the returned deviceCode every ~15s until it returns a non-pending status. Step 4: Only then retry the call that produced this response with the same arguments. Do NOT retry while mist_setup is still pending \u2014 the credentials aren't on disk yet and you'll loop right back into this same response.`};return p(JSON.stringify(e),!0)}function Ye(t){return p(`This is not a Mistflow project (no mistflow.json found at ${t}).
24
+ (Mistflow ${r.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function vr(){let t=qe(),e=Fe??{latest:"",minSupported:"",changelogUrl:""},r=zs(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:Fe!==null}}var Pn,Fe,Fs,en=_(()=>{"use strict";Pn=null;Fe=null;Fs=!1});var rn={};_n(rn,{closeBrowser:()=>xr,getIsolatedContext:()=>jl,getPage:()=>kr,getSnapshot:()=>tn,takeScreenshot:()=>nn});async function Gs(){try{return await import("playwright")}catch{throw new Error("Playwright is not installed. Run: cd packages/mcp-server && pnpm add playwright && npx playwright install chromium")}}async function Dl(){let t=await Gs();return(!Be||!Be.isConnected())&&(Be=await t.chromium.launch({headless:!0})),at&&(await at.close().catch(()=>{}),at=null),at=await Be.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Ye=await at.newPage(),Ye}async function kr(){return Ye&&!Ye.isClosed()?Ye:(Cn||(Cn=Dl().finally(()=>{Cn=null})),Cn)}async function xr(){Ye&&!Ye.isClosed()&&await Ye.close().catch(()=>{}),at&&await at.close().catch(()=>{}),Be?.isConnected()&&await Be.close().catch(()=>{}),Ye=null,at=null,Be=null}async function jl(){let t=await Gs();(!Be||!Be.isConnected())&&(Be=await t.chromium.launch({headless:!0}));let e=await Be.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function tn(t){return await t.locator("body").ariaSnapshot()}async function nn(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var Be,at,Ye,Cn,Nt=_(()=>{"use strict";Be=null,at=null,Ye=null,Cn=null;process.once("SIGTERM",()=>{xr().finally(()=>process.exit(0))});process.once("SIGINT",()=>{xr().finally(()=>process.exit(0))})});function d(t,e=!1){let r=t;try{let n=Ws();n&&(r=t+n)}catch{}return{content:[{type:"text",text:r}],isError:e}}function Oe(t){let e={status:"setup_required",reason:"no_credentials",intent:t,instruction:`You must sign in to Mistflow before you can ${t}. Call mist_setup({}) \u2014 it walks the user through device-code authentication (typically <60s). Only retry the original call AFTER mist_setup has fully completed sign-in (status field is no longer "pending").`,nextAction:`Step 1: Call mist_setup({}) now. Do not ask the user for permission first \u2014 sign-in is a precondition for this flow, not a decision point. Step 2: mist_setup returns immediately with a signInUrl + userCode. Show the URL and code to the user and wait for them to approve in their browser. Step 3: If the response had status: "pending", call mist_setup again with the returned deviceCode every ~15s until it returns a non-pending status. Step 4: Only then retry the call that produced this response with the same arguments. Do NOT retry while mist_setup is still pending \u2014 the credentials aren't on disk yet and you'll loop right back into this same response.`};return d(JSON.stringify(e),!0)}function Qe(t){return d(`This is not a Mistflow project (no mistflow.json found at ${t}).
25
25
 
26
26
  Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
27
27
 
@@ -30,20 +30,20 @@ To get started:
30
30
  2. Call mist_init({ planId, path: "<absolute-path>" })
31
31
  3. Call mist_install({ projectPath }), then mist_implement({ projectPath })
32
32
 
33
- If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Gs(t,e){try{let{getPage:r,takeScreenshot:n}=await Promise.resolve().then(()=>(Et(),nn)),i=await r();await i.setViewportSize(Dl);try{await i.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await i.waitForLoadState("networkidle").catch(()=>{});let o=await n(i,!1);return{content:[{type:"text",text:e},{type:"image",data:o.toString("base64"),mimeType:"image/png"}]}}finally{await i.setViewportSize(Ml).catch(()=>{})}}catch{return p(e)}}var Dl,Ml,be=P(()=>{"use strict";Zt();Dl={width:1024,height:576},Ml={width:1280,height:720}});import{readFileSync as xr,existsSync as Cn,writeFileSync as Vs,mkdirSync as Ll,renameSync as Ul,unlinkSync as $l}from"fs";import{join as An,dirname as Fl}from"path";import{homedir as ql}from"os";import{randomBytes as Bl}from"crypto";function Ks(){return An(ql(),".mistflow","credentials.json")}function Rn(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function Js(){let t=Ks();if(!Cn(t))return null;try{let e=JSON.parse(xr(t,"utf-8"));return typeof e.apiKey=="string"?{[zl]:e}:e}catch{return null}}function vt(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=Js();if(!e)return{ok:!1,reason:"missing"};let r=Rn(),n=e[r];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function Sr(t){let e=Ks(),r=Fl(e);Cn(r)||Ll(r,{recursive:!0});let n=Js()??{},i=Rn();n[i]=t;let o=An(r,`.credentials.tmp.${Bl(8).toString("hex")}`);try{Vs(o,JSON.stringify(n,null,2)+`
34
- `,{mode:384}),Ul(o,e)}catch(s){try{$l(o)}catch{}throw s}}function Ys(){let t=vt();return t.ok?t.creds:null}function Se(){return vt().ok}function it(t){let e=An(t,"mistflow.json");if(!Cn(e))return null;try{return JSON.parse(xr(e,"utf-8"))}catch{return null}}function Tr(t,e){let r=An(t,"mistflow.json");if(Cn(r))try{let i={...JSON.parse(xr(r,"utf-8")),...e};Vs(r,JSON.stringify(i,null,2)+`
35
- `,"utf-8")}catch{}}var zl,kt=P(()=>{"use strict";zl="https://api.mistflow.ai"});var ro={};Tn(ro,{MistflowApiError:()=>G,addDomain:()=>Ar,bindWorkspace:()=>on,cancelSession:()=>Vr,checkAuth:()=>Kl,checkAuthDetailed:()=>eo,checkSubdomain:()=>Nn,checkToolGuard:()=>Kr,createDeployment:()=>Yl,createProject:()=>St,deleteEnvVar:()=>jr,discoverDecisions:()=>Xl,downloadImageryAsset:()=>Ir,downloadSource:()=>tc,downloadSourceWithToken:()=>to,fetchAcceptanceCriteria:()=>sn,fetchActiveSessionPlan:()=>oc,fetchDesignDirections:()=>On,fetchDesignPick:()=>Ql,fetchDesignRenders:()=>Dn,fetchDoc:()=>Br,fetchDocsList:()=>qr,fetchModule:()=>zr,fetchPlanConversation:()=>Mn,fetchProjectImagery:()=>Pr,fetchScaffold:()=>$r,fetchSessionNext:()=>Dt,fetchSessionPlanRevisions:()=>no,fetchStepContext:()=>Fr,forkTemplate:()=>Wr,generatePlan:()=>Ln,getAuthHeaders:()=>xt,getBaseUrl:()=>Pe,getDashboardUrl:()=>Wl,getDbCredentials:()=>Zl,getDeployLogs:()=>Dr,getDeploymentStatus:()=>at,getProject:()=>Jl,getProjectErrors:()=>Mr,getSeedInfo:()=>Fn,getSession:()=>qn,getSiteUrl:()=>Hl,getTemplate:()=>Hr,hasCredentialsOnDisk:()=>Se,hasLocalCredentials:()=>Zs,listDeployments:()=>Ot,listDomains:()=>lt,listEnvVars:()=>Nr,listSessionsForMachine:()=>an,markLocalSetupDone:()=>nc,modifyPlan:()=>Un,pingBackend:()=>_r,promotePreview:()=>Lr,redeployProject:()=>ec,removeDomain:()=>Rr,rollbackDeployment:()=>Ur,shareProject:()=>Gr,startSession:()=>rc,submitAcceptanceResults:()=>Jr,submitDesignPick:()=>jn,submitSessionAnswers:()=>sc,uploadAndDeploy:()=>Cr,uploadQAResults:()=>Er,upsertEnvVar:()=>Or,verifyDomain:()=>$n});function Pe(){return Rn()}function Hl(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9102")}return"https://mistflow.ai"}function Wl(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function xt(){let t=vt();if(!t.ok)throw new G("auth_missing","No Mistflow credentials found.",401);return Gl(t.creds)}function Gl(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":$e()}}function Nt(t){try{Xt(t.headers)}catch{}}async function _r(){try{let t=await fetch(`${Pe()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Nt(t)}catch{}}async function Xs(t,e,r,n){for(let i=0;i<2;i++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(o){let s=o instanceof Error&&o.name==="TimeoutError",a=o instanceof TypeError;if(n&&i===0&&(s||a)){console.error(`[api] Retrying ${t} after ${s?"timeout":"network error"}`);continue}throw o}throw new Error("fetchWithRetry: exhausted retries")}async function rn(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new G(r,n,t.status,e?.details);let i=t.status;return i===401?new G("auth_invalid",n,i):i===403?new G("permission_denied",n,i):i===404?new G("not_found",n,i):i===409?new G("conflict",n,i):i===422?new G("validation_error",n,i):i===429?new G("rate_limited",n,i):i>=500?new G("server_error",t.statusText||"Internal server error",i):new G("client_error",n,i)}async function U(t,e={}){let r=xt(),{timeoutMs:n,idempotent:i,...o}=e,s=n??3e4,a=(o.method??"GET").toUpperCase(),l=i??(a==="GET"||a==="HEAD"),c;try{c=await Xs(`${Pe()}${t}`,{...o,headers:{...r,...o.headers}},s,l)}catch(u){throw u instanceof Error&&u.name==="TimeoutError"?new G("network_error","Request timed out. Try again in a moment."):new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Nt(c),!c.ok)throw await rn(c);return c.json()}function Zs(){return vt().ok}async function Kl(){return(await eo()).ok}async function eo(){if(En!==null&&Date.now()<Qs)return En?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Zs())return{ok:!1,reason:"no_credentials"};try{return await U("/api/org"),En=!0,Qs=Date.now()+Vl,{ok:!0}}catch(t){if(En=null,!(t instanceof G))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function Jl(t){return U(`/api/projects/${encodeURIComponent(t)}`)}async function Nn(t){return U(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function St(t,e={}){return U("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e.template,db_provider:e.dbProvider??"neon",requested_subdomain:e.requestedSubdomain,picked_direction:e.pickedDirection,imagery_brief:e.imageryBrief,plan_context:e.planContext,design_conversation_id:e.designConversationId,session_id:e.sessionId})})}async function Pr(t){return U(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function Ir(t){let e=await fetch(t);if(!e.ok)throw new Error(`Failed to download imagery asset: HTTP ${e.status} ${e.statusText}`);let r=await e.arrayBuffer();return Buffer.from(r)}async function Yl(t,e){return U("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function Cr(t,e,r="production",n,i,o,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=vt();if(!c.ok)throw new G("auth_missing","No Mistflow credentials found.",401);let u=c.creds,h=a(e),d=new Blob([h],{type:"application/gzip"}),v=new FormData;if(v.append("project_id",t),v.append("build",d,l(e)),r!=="production"&&v.append("environment",r),n&&v.append("admin_email",n),i&&v.append("schema_pushed","true"),o){let{existsSync:k}=await import("fs");if(k(o)){let y=a(o),A=new Blob([y],{type:"application/gzip"});v.append("source",A,"source.tar.gz")}}s&&v.append("git_commit_sha",s);let W;try{W=await fetch(`${Pe()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${u.apiKey}`,"X-Mistflow-MCP-Version":$e()},body:v,signal:AbortSignal.timeout(3e5)})}catch{throw new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Nt(W),!W.ok)throw await rn(W);let _=await W.json();return{..._,id:_.deployment_id}}async function at(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return U(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:i}:void 0)}async function On(t){return U(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Ql(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return U(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:i})}async function jn(t,e){return U(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json"},timeoutMs:6e4})}async function Dn(t){try{return await U(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function Mn(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return U(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:i})}async function Ln(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};if(e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&e?.designDirection){let i=e.designDirection,o=256,s=4e3,a=typeof i.id=="string"?i.id:void 0,l=typeof i.custom=="string"?i.custom:void 0,c=a&&a.length>0&&a.length<=o?a:void 0,u=(()=>{if(l&&l.length>0)return l.length<=s?l:l.slice(0,s)+" (truncated)";if(!c){let v=JSON.stringify(i);return v.length<=s?v:v.slice(0,s)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${o}; falling back to custom`);let h=c?{direction_id:c}:{custom:u};e.conversationId&&(h.conversation_id=e.conversationId);let d=await jn(e.designConversationId,h);return{status:"ready",plan:d.plan??{},methodology:d.methodology??"",...d.designMd?{designMd:d.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return U("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function Un(t,e,r={}){return U("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function Xl(t){return U("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Ar(t,e){return U(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function lt(t){return U(`/api/projects/${encodeURIComponent(t)}/domains`)}async function $n(t,e){return U(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Rr(t,e){return U(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Zl(t){return U(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Fn(t){try{return await U(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof G&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Er(t,e){try{return await U(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(r){return console.error("[api] Failed to upload QA results:",r instanceof Error?r.message:r),null}}async function Nr(t){return U(`/api/projects/${encodeURIComponent(t)}/env`)}async function Or(t,e,r,n){return U(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:r,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function jr(t,e){return U(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Dr(t){return U(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Mr(t,e="7d"){return U(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Ot(t){return U(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function ec(t){return U(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Lr(t,e){let r=new URLSearchParams({preview_deployment_id:e});return U(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Ur(t){return U(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function tc(t,e){let r=vt();if(!r.ok)throw new G("auth_missing","Not authenticated.",401);let n=r.creds,i=await fetch(`${Pe()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":$e()},signal:AbortSignal.timeout(12e4)});if(Nt(i),!i.ok)throw await rn(i);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await i.arrayBuffer());o(e,s)}async function jt(t,e){let{timeoutMs:r,idempotent:n,...i}=e??{},o=r??3e4,s=(i.method??"GET").toUpperCase(),a=n??(s==="GET"||s==="HEAD"),l;try{l=await Xs(`${Pe()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":$e()},...i},o,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new G("network_error","Request timed out. Try again in a moment."):new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Nt(l),!l.ok)throw await rn(l);return l.json()}async function $r(t="nextjs"){return jt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Fr(t,e){return jt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function qr(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return jt(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function Br(t,e){return jt(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function zr(t,e,r,n){return jt(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:r,entity_plural:n})})}async function Hr(t){return jt(`/api/templates/${encodeURIComponent(t)}`)}async function Wr(t){return U(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function to(t,e,r){let n;try{n=await fetch(`${Pe()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":$e()},signal:AbortSignal.timeout(12e4)})}catch{throw new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Nt(n),!n.ok)throw n.status===401?new G("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await rn(n);let{writeFileSync:i}=await import("fs"),o=Buffer.from(await n.arrayBuffer());i(r,o)}async function nc(t){await U(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Gr(t,e){return U(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function rc(t){return U("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function qn(t){return U(`/api/sessions/${t}`)}async function Vr(t,e){return U(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Dt(t){return U(`/api/sessions/${t}/next`)}async function sc(t,e){return U(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Kr(t,e){return U(`/api/sessions/${t}/can/${e}`)}async function sn(t){return U(`/api/sessions/${t}/acceptance`)}async function no(t){return U(`/api/sessions/${t}/revisions`)}async function oc(t){let e=await no(t),r=[...e].reverse().find(n=>n.status==="active")??e.at(-1);return!r||!r.body||typeof r.body!="object"||Array.isArray(r.body)?null:{plan:r.body,planRevisionId:r.id}}async function on(t,e){return U(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function an(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return U(`/api/sessions/me/workspaces?${n}`)}async function Jr(t,e,r){return U(`/api/sessions/${t}/acceptance/results`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({results:e,plan_revision_id:r??null}),idempotent:!1})}var G,En,Qs,Vl,_e=P(()=>{"use strict";kt();Zt();G=class extends Error{constructor(r,n,i,o){super(n);this.code=r;this.statusCode=i;this.details=o;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};En=null,Qs=0,Vl=300*1e3});import{z as Yr}from"zod";import{platform as ic}from"os";import{execFile as so}from"child_process";function lc(t){return"error"in t}function io(t){return new Promise(e=>setTimeout(e,t))}function cc(t){return new Promise(e=>{let r=ic();r==="win32"?so("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):so(r==="darwin"?"open":"xdg-open",[t],i=>{i&&console.error("Could not open browser:",i.message),e(!i)}),setTimeout(()=>e(!1),5e3)})}async function oo(t,e,r,n){let i=r,o=n.sleep??io;for(let s=0;s<e;s++){await o(i);let a;try{let c=await n.fetch(`${Pe()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!c.ok)continue;a=await c.json()}catch{continue}if(lc(a))switch(a.error){case"authorization_pending":continue;case"slow_down":i+=5e3;continue;case"expired_token":return p("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return p("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return p("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=a.email||a.org_name||a.org_slug;return Sr({apiKey:a.api_key,apiKeyId:a.api_key_id,apiKeyName:a.api_key_name,orgId:a.org_id,orgSlug:a.org_slug,email:a.email}),p(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function pc(t,e=dc){let r=t;if(r?.apiKey)try{let s=await e.fetch(`${Pe()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!s.ok)return p("Invalid API key. Check the key and try again.",!0);let a=await s.json();return Sr({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),p(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let s=await oo(r.deviceCode,6,5e3,e);return s||p(JSON.stringify({status:"pending",deviceCode:r.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let s=await e.fetch(`${Pe()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!s.ok)return p("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await s.json()}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}let i=`${n.verification_uri}?code=${n.user_code}`;console.error(`
33
+ If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Vs(t,e){try{let{getPage:r,takeScreenshot:n}=await Promise.resolve().then(()=>(Nt(),rn)),i=await r();await i.setViewportSize(Ml);try{await i.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await i.waitForLoadState("networkidle").catch(()=>{});let o=await n(i,!1);return{content:[{type:"text",text:e},{type:"image",data:o.toString("base64"),mimeType:"image/png"}]}}finally{await i.setViewportSize(Ll).catch(()=>{})}}catch{return d(e)}}var Ml,Ll,be=_(()=>{"use strict";en();Ml={width:1024,height:576},Ll={width:1280,height:720}});import{readFileSync as Sr,existsSync as An,writeFileSync as Ks,mkdirSync as Ul,renameSync as $l,unlinkSync as Fl}from"fs";import{join as Rn,dirname as ql}from"path";import{homedir as Bl}from"os";import{randomBytes as zl}from"crypto";function Js(){return Rn(Bl(),".mistflow","credentials.json")}function En(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function Ys(){let t=Js();if(!An(t))return null;try{let e=JSON.parse(Sr(t,"utf-8"));return typeof e.apiKey=="string"?{[Hl]:e}:e}catch{return null}}function xt(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=Ys();if(!e)return{ok:!1,reason:"missing"};let r=En(),n=e[r];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function Tr(t){let e=Js(),r=ql(e);An(r)||Ul(r,{recursive:!0});let n=Ys()??{},i=En();n[i]=t;let o=Rn(r,`.credentials.tmp.${zl(8).toString("hex")}`);try{Ks(o,JSON.stringify(n,null,2)+`
34
+ `,{mode:384}),$l(o,e)}catch(s){try{Fl(o)}catch{}throw s}}function Qs(){let t=xt();return t.ok?t.creds:null}function xe(){return xt().ok}function lt(t){let e=Rn(t,"mistflow.json");if(!An(e))return null;try{return JSON.parse(Sr(e,"utf-8"))}catch{return null}}function _r(t,e){let r=Rn(t,"mistflow.json");if(An(r))try{let i={...JSON.parse(Sr(r,"utf-8")),...e};Ks(r,JSON.stringify(i,null,2)+`
35
+ `,"utf-8")}catch{}}var Hl,St=_(()=>{"use strict";Hl="https://api.mistflow.ai"});var so={};_n(so,{MistflowApiError:()=>K,addDomain:()=>Rr,bindWorkspace:()=>an,cancelSession:()=>Kr,checkAuth:()=>Jl,checkAuthDetailed:()=>to,checkSubdomain:()=>On,checkToolGuard:()=>Jr,createDeployment:()=>Ql,createProject:()=>_t,deleteEnvVar:()=>jr,discoverDecisions:()=>Zl,downloadImageryAsset:()=>Cr,downloadSource:()=>nc,downloadSourceWithToken:()=>no,fetchAcceptanceCriteria:()=>on,fetchActiveSessionPlan:()=>ic,fetchDesignDirections:()=>Dn,fetchDesignPick:()=>Xl,fetchDesignRenders:()=>Mn,fetchDoc:()=>zr,fetchDocsList:()=>Br,fetchModule:()=>Hr,fetchPlanConversation:()=>Ln,fetchProjectImagery:()=>Ir,fetchScaffold:()=>Fr,fetchSessionNext:()=>Mt,fetchSessionPlanRevisions:()=>ro,fetchStepContext:()=>qr,forkTemplate:()=>Gr,generatePlan:()=>Un,getAuthHeaders:()=>Tt,getBaseUrl:()=>Pe,getDashboardUrl:()=>Gl,getDbCredentials:()=>ec,getDeployLogs:()=>Mr,getDeploymentStatus:()=>ct,getProject:()=>Yl,getProjectErrors:()=>Lr,getSeedInfo:()=>qn,getSession:()=>Bn,getSiteUrl:()=>Wl,getTemplate:()=>Wr,hasCredentialsOnDisk:()=>xe,hasLocalCredentials:()=>eo,listDeployments:()=>Dt,listDomains:()=>dt,listEnvVars:()=>Or,listSessionsForMachine:()=>ln,markLocalSetupDone:()=>rc,modifyPlan:()=>$n,pingBackend:()=>Pr,promotePreview:()=>Ur,redeployProject:()=>tc,removeDomain:()=>Er,rollbackDeployment:()=>$r,shareProject:()=>Vr,startSession:()=>sc,submitAcceptanceResults:()=>Yr,submitDesignPick:()=>jn,submitSessionAnswers:()=>oc,uploadAndDeploy:()=>Ar,uploadQAResults:()=>Nr,upsertEnvVar:()=>Dr,verifyDomain:()=>Fn});function Pe(){return En()}function Wl(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9102")}return"https://mistflow.ai"}function Gl(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function Tt(){let t=xt();if(!t.ok)throw new K("auth_missing","No Mistflow credentials found.",401);return Vl(t.creds)}function Vl(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()}}function Ot(t){try{Zt(t.headers)}catch{}}async function Pr(){try{let t=await fetch(`${Pe()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Ot(t)}catch{}}async function Zs(t,e,r,n){for(let i=0;i<2;i++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(o){let s=o instanceof Error&&o.name==="TimeoutError",a=o instanceof TypeError;if(n&&i===0&&(s||a)){console.error(`[api] Retrying ${t} after ${s?"timeout":"network error"}`);continue}throw o}throw new Error("fetchWithRetry: exhausted retries")}async function sn(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new K(r,n,t.status,e?.details);let i=t.status;return i===401?new K("auth_invalid",n,i):i===403?new K("permission_denied",n,i):i===404?new K("not_found",n,i):i===409?new K("conflict",n,i):i===422?new K("validation_error",n,i):i===429?new K("rate_limited",n,i):i>=500?new K("server_error",t.statusText||"Internal server error",i):new K("client_error",n,i)}async function q(t,e={}){let r=Tt(),{timeoutMs:n,idempotent:i,...o}=e,s=n??3e4,a=(o.method??"GET").toUpperCase(),l=i??(a==="GET"||a==="HEAD"),c;try{c=await Zs(`${Pe()}${t}`,{...o,headers:{...r,...o.headers}},s,l)}catch(m){throw m instanceof Error&&m.name==="TimeoutError"?new K("network_error","Request timed out. Try again in a moment."):new K("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ot(c),!c.ok)throw await sn(c);return c.json()}function eo(){return xt().ok}async function Jl(){return(await to()).ok}async function to(){if(Nn!==null&&Date.now()<Xs)return Nn?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!eo())return{ok:!1,reason:"no_credentials"};try{return await q("/api/org"),Nn=!0,Xs=Date.now()+Kl,{ok:!0}}catch(t){if(Nn=null,!(t instanceof K))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function Yl(t){return q(`/api/projects/${encodeURIComponent(t)}`)}async function On(t){return q(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function _t(t,e={}){return q("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e.template,db_provider:e.dbProvider??"neon",requested_subdomain:e.requestedSubdomain,picked_direction:e.pickedDirection,imagery_brief:e.imageryBrief,plan_context:e.planContext,design_conversation_id:e.designConversationId,session_id:e.sessionId})})}async function Ir(t){return q(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function Cr(t){let e=await fetch(t);if(!e.ok)throw new Error(`Failed to download imagery asset: HTTP ${e.status} ${e.statusText}`);let r=await e.arrayBuffer();return Buffer.from(r)}async function Ql(t,e){return q("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function Ar(t,e,r="production",n,i,o,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=xt();if(!c.ok)throw new K("auth_missing","No Mistflow credentials found.",401);let m=c.creds,p=a(e),u=new Blob([p],{type:"application/gzip"}),g=new FormData;if(g.append("project_id",t),g.append("build",u,l(e)),r!=="production"&&g.append("environment",r),n&&g.append("admin_email",n),i&&g.append("schema_pushed","true"),o){let{existsSync:S}=await import("fs");if(S(o)){let y=a(o),R=new Blob([y],{type:"application/gzip"});g.append("source",R,"source.tar.gz")}}s&&g.append("git_commit_sha",s);let j;try{j=await fetch(`${Pe()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":qe()},body:g,signal:AbortSignal.timeout(3e5)})}catch{throw new K("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ot(j),!j.ok)throw await sn(j);let I=await j.json();return{...I,id:I.deployment_id}}async function ct(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return q(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:i}:void 0)}async function Dn(t){return q(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Xl(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return q(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:i})}async function jn(t,e){return q(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),timeoutMs:6e4})}async function Mn(t){try{return await q(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function Ln(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return q(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:i})}async function Un(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};if(e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&e?.designDirection){let i=e.designDirection,o=256,s=4e3,a=typeof i.id=="string"?i.id:void 0,l=typeof i.custom=="string"?i.custom:void 0,c=a&&a.length>0&&a.length<=o?a:void 0,m=(()=>{if(l&&l.length>0)return l.length<=s?l:l.slice(0,s)+" (truncated)";if(!c){let g=JSON.stringify(i);return g.length<=s?g:g.slice(0,s)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${o}; falling back to custom`);let p=c?{direction_id:c}:{custom:m};e.conversationId&&(p.conversation_id=e.conversationId);let u=await jn(e.designConversationId,p);return{status:"ready",plan:u.plan??{},methodology:u.methodology??"",...u.designMd?{designMd:u.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return q("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function $n(t,e,r={}){return q("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function Zl(t){return q("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Rr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function dt(t){return q(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Fn(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Er(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function ec(t){return q(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function qn(t){try{return await q(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof K&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Nr(t,e){try{return await q(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(r){return console.error("[api] Failed to upload QA results:",r instanceof Error?r.message:r),null}}async function Or(t){return q(`/api/projects/${encodeURIComponent(t)}/env`)}async function Dr(t,e,r,n){return q(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:r,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function jr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Mr(t){return q(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Lr(t,e="7d"){return q(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Dt(t){return q(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function tc(t){return q(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Ur(t,e){let r=new URLSearchParams({preview_deployment_id:e});return q(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function $r(t){return q(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function nc(t,e){let r=xt();if(!r.ok)throw new K("auth_missing","Not authenticated.",401);let n=r.creds,i=await fetch(`${Pe()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":qe()},signal:AbortSignal.timeout(12e4)});if(Ot(i),!i.ok)throw await sn(i);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await i.arrayBuffer());o(e,s)}async function jt(t,e){let{timeoutMs:r,idempotent:n,...i}=e??{},o=r??3e4,s=(i.method??"GET").toUpperCase(),a=n??(s==="GET"||s==="HEAD"),l;try{l=await Zs(`${Pe()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()},...i},o,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new K("network_error","Request timed out. Try again in a moment."):new K("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ot(l),!l.ok)throw await sn(l);return l.json()}async function Fr(t="nextjs"){return jt(`/api/scaffold/${encodeURIComponent(t)}`)}async function qr(t,e){return jt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Br(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return jt(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function zr(t,e){return jt(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function Hr(t,e,r,n){return jt(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:r,entity_plural:n})})}async function Wr(t){return jt(`/api/templates/${encodeURIComponent(t)}`)}async function Gr(t){return q(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function no(t,e,r){let n;try{n=await fetch(`${Pe()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":qe()},signal:AbortSignal.timeout(12e4)})}catch{throw new K("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ot(n),!n.ok)throw n.status===401?new K("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await sn(n);let{writeFileSync:i}=await import("fs"),o=Buffer.from(await n.arrayBuffer());i(r,o)}async function rc(t){await q(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Vr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function sc(t){return q("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function Bn(t){return q(`/api/sessions/${t}`)}async function Kr(t,e){return q(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Mt(t){return q(`/api/sessions/${t}/next`)}async function oc(t,e){return q(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Jr(t,e){return q(`/api/sessions/${t}/can/${e}`)}async function on(t){return q(`/api/sessions/${t}/acceptance`)}async function ro(t){return q(`/api/sessions/${t}/revisions`)}async function ic(t){let e=await ro(t),r=[...e].reverse().find(n=>n.status==="active")??e.at(-1);return!r||!r.body||typeof r.body!="object"||Array.isArray(r.body)?null:{plan:r.body,planRevisionId:r.id}}async function an(t,e){return q(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function ln(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return q(`/api/sessions/me/workspaces?${n}`)}async function Yr(t,e,r){return q(`/api/sessions/${t}/acceptance/results`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({results:e,plan_revision_id:r??null}),idempotent:!1})}var K,Nn,Xs,Kl,_e=_(()=>{"use strict";St();en();K=class extends Error{constructor(r,n,i,o){super(n);this.code=r;this.statusCode=i;this.details=o;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};Nn=null,Xs=0,Kl=300*1e3});import{z as Qr}from"zod";import{platform as ac}from"os";import{execFile as oo}from"child_process";function cc(t){return"error"in t}function ao(t){return new Promise(e=>setTimeout(e,t))}function dc(t){return new Promise(e=>{let r=ac();r==="win32"?oo("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):oo(r==="darwin"?"open":"xdg-open",[t],i=>{i&&console.error("Could not open browser:",i.message),e(!i)}),setTimeout(()=>e(!1),5e3)})}async function io(t,e,r,n){let i=r,o=n.sleep??ao;for(let s=0;s<e;s++){await o(i);let a;try{let c=await n.fetch(`${Pe()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!c.ok)continue;a=await c.json()}catch{continue}if(cc(a))switch(a.error){case"authorization_pending":continue;case"slow_down":i+=5e3;continue;case"expired_token":return d("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return d("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return d("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=a.email||a.org_name||a.org_slug;return Tr({apiKey:a.api_key,apiKeyId:a.api_key_id,apiKeyName:a.api_key_name,orgId:a.org_id,orgSlug:a.org_slug,email:a.email}),d(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function uc(t,e=pc){let r=t;if(r?.apiKey)try{let s=await e.fetch(`${Pe()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!s.ok)return d("Invalid API key. Check the key and try again.",!0);let a=await s.json();return Tr({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),d(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let s=await io(r.deviceCode,6,5e3,e);return s||d(JSON.stringify({status:"pending",deviceCode:r.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let s=await e.fetch(`${Pe()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!s.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await s.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let i=`${n.verification_uri}?code=${n.user_code}`;console.error(`
36
36
  Sign in at: ${i}
37
37
  Your code: ${n.user_code}
38
- `);try{await e.openBrowser(i)}catch{}let o=await oo(n.device_code,6,5e3,e);return o||p(JSON.stringify({status:"pending",deviceCode:n.device_code,signInUrl:i,userCode:n.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+n.device_code+"' to check if they approved."}))}var ac,dc,ao,lo=P(()=>{"use strict";Ke();be();_e();kt();ac=Yr.object({apiKey:Yr.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:Yr.string().optional().describe("Resume polling for a pending device code. Returned by a previous mist_setup call with status 'pending'. Call mist_setup again with this value after ~15 seconds to check if the user approved.")});dc={fetch:globalThis.fetch,openBrowser:cc,sleep:io};ao={name:"mist_setup",description:Rs,inputSchema:ac,handler:t=>pc(t)}});import{existsSync as uc,readFileSync as mc}from"fs";function co(t){let e=new Set;if(!uc(t))return e;let r=mc(t,"utf-8");for(let n of r.split(`
39
- `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o>0){let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();a&&a!=='""'&&a!=="''"&&e.add(s)}}return e}var po=P(()=>{"use strict"});var dn={};Tn(dn,{emptyState:()=>cn,fetchRemoteState:()=>bc,fuzzyMatch:()=>vc,getLocalStatePath:()=>Qr,readLocalState:()=>yc,syncRemoteState:()=>wc,writeLocalState:()=>ln});import{existsSync as uo,readFileSync as hc,writeFileSync as gc,mkdirSync as fc}from"fs";import{join as mo}from"path";function Qr(t){return mo(t,".mistflow","state.json")}function yc(t){let e=Qr(t);if(!uo(e))return null;try{return JSON.parse(hc(e,"utf-8"))}catch{return null}}function ln(t,e){let r=mo(t,".mistflow");uo(r)||fc(r,{recursive:!0}),gc(Qr(t),JSON.stringify(e,null,2)+`
40
- `)}function cn(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function bc(t){let e;try{e=xt()}catch{return null}try{let r=await fetch(`${Pe()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":$e()}});try{Xt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function wc(t,e){let r;try{r=xt()}catch{return!1}try{let n=await fetch(`${Pe()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":$e()},body:JSON.stringify(e)});try{Xt(n.headers)}catch{}return n.ok}catch{return!1}}function vc(t,e){let r=t.toLowerCase(),n=e.toLowerCase();return n.includes(r)||r.includes(n)?!0:r.split(/\s+/).some(o=>o.length>=3&&n.includes(o))}var Tt=P(()=>{"use strict";_e();Zt()});var Xr={};Tn(Xr,{ensureBackendRegistered:()=>Ic,ensureShadcnComponents:()=>Cc});import{existsSync as go,readFileSync as kc,writeFileSync as xc}from"fs";import{join as Bn}from"path";import{spawn as Sc}from"child_process";function Tc(t,e,r,n,i){return new Promise(o=>{let s=Sc(t,e,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:n,...i?{env:{...process.env,...i}}:{}}),a="",l="";s.stdout?.on("data",c=>{a+=c.toString()}),s.stderr?.on("data",c=>{l+=c.toString()}),s.on("close",c=>o({success:c===0,stdout:a,stderr:l})),s.on("error",c=>o({success:!1,stdout:a,stderr:l+c.message}))})}function _c(t){let e=Bn(t,"mistflow.json");if(!go(e))return null;try{return JSON.parse(kc(e,"utf-8"))}catch{return null}}function Pc(t,e){xc(Bn(t,"mistflow.json"),JSON.stringify(e,null,2))}async function ho(t,e){try{let r=e.features,n=e.steps,i={plan:e};Array.isArray(r)&&r.length>0&&(i.features=r.map(o=>o.name)),Array.isArray(n)&&n.length>0&&(i.provenance=n.map(o=>({feature:o.name??o.title??`Step ${o.number??"?"}`,user_intent:(o.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${Pe()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...xt(),"Content-Type":"application/json"},body:JSON.stringify(i)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function Ic(t,e={}){let r=_c(t);if(r){if(!Se())return r.projectId;if(!r.projectId)try{let i=r.plan?.requestedSubdomain,o=await St(r.name,{dbProvider:r.dbProvider??"neon",requestedSubdomain:i});return r.projectId=o.id,Pc(t,r),ln(t,cn(o.id,r.name)),r.plan&&await ho(o.id,r.plan),console.error(`[self-heal] registered project ${o.id.slice(0,8)} with backend`),o.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&r.plan&&r.projectId&&await ho(r.projectId,r.plan),r.projectId}}async function Cc(t,e){let r=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],n=e&&e.length>0?e:r,i=Bn(t,"components","ui"),o=[],s=[];for(let c of n)go(Bn(i,`${c}.tsx`))?o.push(c):s.push(c);if(s.length===0)return{installed:[],alreadyPresent:o};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Tc("npx",["--yes","shadcn@latest","add","-y","-o",...s],t,18e4,a);return l.success?{installed:s,alreadyPresent:o}:{installed:[],alreadyPresent:o,failed:`shadcn add failed for: ${s.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Zr=P(()=>{"use strict";_e();Tt()});import{z as ct}from"zod";import{resolve as Ac,join as fo}from"path";import{existsSync as Rc,readFileSync as yo,writeFileSync as Ec}from"fs";var Nc,bo,wo=P(()=>{"use strict";be();po();Nc=ct.object({action:ct.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:ct.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:ct.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:ct.object({key:ct.string(),description:ct.string().optional(),setupUrl:ct.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),bo={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Called internally by mist_project; host AIs should use mist_project directly.",inputSchema:Nc,handler:async t=>{let e=t,r=Ac(e.projectPath??process.cwd()),n=fo(r,"mistflow.json");if(!Rc(n))return Ye(r);let i;try{i=JSON.parse(yo(n,"utf-8"))}catch{return p("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!i.projectId)try{let{ensureBackendRegistered:k}=await Promise.resolve().then(()=>(Zr(),Xr));await k(r)&&(i=JSON.parse(yo(n,"utf-8")))}catch{}let a=i.plan,l=a?.steps?.filter(k=>k.status==="completed").length??0,c=a?.steps?.length??0,u=co(fo(r,".env.local")),h=i.env?.required?Object.entries(i.env.required).map(([k,y])=>({name:k,description:y?.description,configured:u.has(k)})):[];i.projectId&&Promise.resolve().then(()=>(Tt(),dn)).then(({fetchRemoteState:k})=>k(i.projectId)).catch(()=>{});let d=[`Project: ${i.name}`];if(a){d.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let k of a.steps){let y=k.status==="completed"?"\u2713":k.status==="in_progress"?"\u2192":" ";d.push(` [${y}] ${k.number}. ${k.name}`)}}let v=h.filter(k=>!k.configured);v.length>0&&d.push(`Missing env vars: ${v.map(k=>k.name).join(", ")}`),i.deploy?.url?d.push(`Deployed: ${i.deploy.url} (${i.deploy.count??0} deploys)`):d.push("Not deployed yet");let W=[],_=a?.steps?.find(k=>k.status!=="completed");return _?W.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${_.number} (${_.name}).`):a&&l===c&&(i.deploy?.url||W.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),v.length>0&&W.push(`Missing env vars in .env.local: ${v.map(k=>k.name).join(", ")}`),p(JSON.stringify({name:i.name,projectId:i.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:c,completedSteps:l,steps:a.steps}:null,envStatus:h,deploy:i.deploy??null,contextMessage:d.join(`
41
- `),nextSteps:W}))}let o=[];if(e.completedStep!==void 0){let a=i.plan;if(a?.steps){let l=a.steps.findIndex(c=>c.number===e.completedStep);if(l===-1)return p(`Step ${e.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",o.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(i.env||(i.env={required:{}}),i.env.required||(i.env.required={}),i.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},o.push(`Added required env var: ${e.addEnvVar.key}`)),Ec(n,JSON.stringify(i,null,2)+`
42
- `),i.projectId&&Promise.resolve().then(()=>(Tt(),dn)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(r);c&&await l(i.projectId,c)}).catch(()=>{});let s=[];if(e.completedStep!==void 0){let l=i.plan?.steps?.find(c=>c.status!=="completed");l?s.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):s.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }) to deploy the app. Do NOT suggest localhost.")}return e.addEnvVar&&(s.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&s.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),p(JSON.stringify({updated:!0,changes:o,message:o.length>0?`Project state saved. ${o.join(". ")}.`:"No changes made.",nextSteps:s.length>0?s:void 0}))}}});function Oc(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Lt(t){let e=Mt.find(n=>n.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Mt.find(n=>{let i=n.name.toLowerCase().replace(/[^a-z0-9]/g,"");return i===r||i.includes(r)||r.includes(i)})}function Ut(t){return es[t]}function ts(t){return t?Mt.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Mt}function vo(t){let e=t??Mt,r={};for(let i of e){r[i.category]||(r[i.category]=[]);let o=es[i.id],s=o?` \u2014 ${o.description}`:"",a=o?.packages.length?` (${o.packages.join(", ")})`:"";r[i.category].push(`${i.id} \u2014 "${i.name}"${s}${a}`)}let n=[];for(let[i,o]of Object.entries(r))n.push(`**${i}**:
38
+ `);try{await e.openBrowser(i)}catch{}let o=await io(n.device_code,6,5e3,e);return o||d(JSON.stringify({status:"pending",deviceCode:n.device_code,signInUrl:i,userCode:n.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+n.device_code+"' to check if they approved."}))}var lc,pc,lo,co=_(()=>{"use strict";Je();be();_e();St();lc=Qr.object({apiKey:Qr.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:Qr.string().optional().describe("Resume polling for a pending device code. Returned by a previous mist_setup call with status 'pending'. Call mist_setup again with this value after ~15 seconds to check if the user approved.")});pc={fetch:globalThis.fetch,openBrowser:dc,sleep:ao};lo={name:"mist_setup",description:Es,inputSchema:lc,handler:t=>uc(t)}});import{existsSync as mc,readFileSync as hc}from"fs";function po(t){let e=new Set;if(!mc(t))return e;let r=hc(t,"utf-8");for(let n of r.split(`
39
+ `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o>0){let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();a&&a!=='""'&&a!=="''"&&e.add(s)}}return e}var uo=_(()=>{"use strict"});var pn={};_n(pn,{emptyState:()=>dn,fetchRemoteState:()=>wc,fuzzyMatch:()=>kc,getLocalStatePath:()=>Xr,readLocalState:()=>bc,syncRemoteState:()=>vc,writeLocalState:()=>cn});import{existsSync as mo,readFileSync as gc,writeFileSync as fc,mkdirSync as yc}from"fs";import{join as ho}from"path";function Xr(t){return ho(t,".mistflow","state.json")}function bc(t){let e=Xr(t);if(!mo(e))return null;try{return JSON.parse(gc(e,"utf-8"))}catch{return null}}function cn(t,e){let r=ho(t,".mistflow");mo(r)||yc(r,{recursive:!0}),fc(Xr(t),JSON.stringify(e,null,2)+`
40
+ `)}function dn(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function wc(t){let e;try{e=Tt()}catch{return null}try{let r=await fetch(`${Pe()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()}});try{Zt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function vc(t,e){let r;try{r=Tt()}catch{return!1}try{let n=await fetch(`${Pe()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()},body:JSON.stringify(e)});try{Zt(n.headers)}catch{}return n.ok}catch{return!1}}function kc(t,e){let r=t.toLowerCase(),n=e.toLowerCase();return n.includes(r)||r.includes(n)?!0:r.split(/\s+/).some(o=>o.length>=3&&n.includes(o))}var Pt=_(()=>{"use strict";_e();en()});var Zr={};_n(Zr,{ensureBackendRegistered:()=>Cc,ensureShadcnComponents:()=>Ac});import{existsSync as fo,readFileSync as xc,writeFileSync as Sc}from"fs";import{join as zn}from"path";import{spawn as Tc}from"child_process";function _c(t,e,r,n,i){return new Promise(o=>{let s=Tc(t,e,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:n,...i?{env:{...process.env,...i}}:{}}),a="",l="";s.stdout?.on("data",c=>{a+=c.toString()}),s.stderr?.on("data",c=>{l+=c.toString()}),s.on("close",c=>o({success:c===0,stdout:a,stderr:l})),s.on("error",c=>o({success:!1,stdout:a,stderr:l+c.message}))})}function Pc(t){let e=zn(t,"mistflow.json");if(!fo(e))return null;try{return JSON.parse(xc(e,"utf-8"))}catch{return null}}function Ic(t,e){Sc(zn(t,"mistflow.json"),JSON.stringify(e,null,2))}async function go(t,e){try{let r=e.features,n=e.steps,i={plan:e};Array.isArray(r)&&r.length>0&&(i.features=r.map(o=>o.name)),Array.isArray(n)&&n.length>0&&(i.provenance=n.map(o=>({feature:o.name??o.title??`Step ${o.number??"?"}`,user_intent:(o.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${Pe()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...Tt(),"Content-Type":"application/json"},body:JSON.stringify(i)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function Cc(t,e={}){let r=Pc(t);if(r){if(!xe())return r.projectId;if(!r.projectId)try{let i=r.plan?.requestedSubdomain,o=await _t(r.name,{dbProvider:r.dbProvider??"neon",requestedSubdomain:i});return r.projectId=o.id,Ic(t,r),cn(t,dn(o.id,r.name)),r.plan&&await go(o.id,r.plan),console.error(`[self-heal] registered project ${o.id.slice(0,8)} with backend`),o.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&r.plan&&r.projectId&&await go(r.projectId,r.plan),r.projectId}}async function Ac(t,e){let r=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],n=e&&e.length>0?e:r,i=zn(t,"components","ui"),o=[],s=[];for(let c of n)fo(zn(i,`${c}.tsx`))?o.push(c):s.push(c);if(s.length===0)return{installed:[],alreadyPresent:o};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await _c("npx",["--yes","shadcn@latest","add","-y","-o",...s],t,18e4,a);return l.success?{installed:s,alreadyPresent:o}:{installed:[],alreadyPresent:o,failed:`shadcn add failed for: ${s.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var es=_(()=>{"use strict";_e();Pt()});import{z as pt}from"zod";import{resolve as Rc,join as yo}from"path";import{existsSync as Ec,readFileSync as bo,writeFileSync as Nc}from"fs";var Oc,wo,vo=_(()=>{"use strict";be();uo();Oc=pt.object({action:pt.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:pt.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:pt.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:pt.object({key:pt.string(),description:pt.string().optional(),setupUrl:pt.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),wo={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Called internally by mist_project; host AIs should use mist_project directly.",inputSchema:Oc,handler:async t=>{let e=t,r=Rc(e.projectPath??process.cwd()),n=yo(r,"mistflow.json");if(!Ec(n))return Qe(r);let i;try{i=JSON.parse(bo(n,"utf-8"))}catch{return d("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!i.projectId)try{let{ensureBackendRegistered:S}=await Promise.resolve().then(()=>(es(),Zr));await S(r)&&(i=JSON.parse(bo(n,"utf-8")))}catch{}let a=i.plan,l=a?.steps?.filter(S=>S.status==="completed").length??0,c=a?.steps?.length??0,m=po(yo(r,".env.local")),p=i.env?.required?Object.entries(i.env.required).map(([S,y])=>({name:S,description:y?.description,configured:m.has(S)})):[];i.projectId&&Promise.resolve().then(()=>(Pt(),pn)).then(({fetchRemoteState:S})=>S(i.projectId)).catch(()=>{});let u=[`Project: ${i.name}`];if(a){u.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let S of a.steps){let y=S.status==="completed"?"\u2713":S.status==="in_progress"?"\u2192":" ";u.push(` [${y}] ${S.number}. ${S.name}`)}}let g=p.filter(S=>!S.configured);g.length>0&&u.push(`Missing env vars: ${g.map(S=>S.name).join(", ")}`),i.deploy?.url?u.push(`Deployed: ${i.deploy.url} (${i.deploy.count??0} deploys)`):u.push("Not deployed yet");let j=[],I=a?.steps?.find(S=>S.status!=="completed");return I?j.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${I.number} (${I.name}).`):a&&l===c&&(i.deploy?.url||j.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),g.length>0&&j.push(`Missing env vars in .env.local: ${g.map(S=>S.name).join(", ")}`),d(JSON.stringify({name:i.name,projectId:i.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:c,completedSteps:l,steps:a.steps}:null,envStatus:p,deploy:i.deploy??null,contextMessage:u.join(`
41
+ `),nextSteps:j}))}let o=[];if(e.completedStep!==void 0){let a=i.plan;if(a?.steps){let l=a.steps.findIndex(c=>c.number===e.completedStep);if(l===-1)return d(`Step ${e.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",o.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(i.env||(i.env={required:{}}),i.env.required||(i.env.required={}),i.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},o.push(`Added required env var: ${e.addEnvVar.key}`)),Nc(n,JSON.stringify(i,null,2)+`
42
+ `),i.projectId&&Promise.resolve().then(()=>(Pt(),pn)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(r);c&&await l(i.projectId,c)}).catch(()=>{});let s=[];if(e.completedStep!==void 0){let l=i.plan?.steps?.find(c=>c.status!=="completed");l?s.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):s.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }) to deploy the app. Do NOT suggest localhost.")}return e.addEnvVar&&(s.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&s.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),d(JSON.stringify({updated:!0,changes:o,message:o.length>0?`Project state saved. ${o.join(". ")}.`:"No changes made.",nextSteps:s.length>0?s:void 0}))}}});function Dc(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Ut(t){let e=Lt.find(n=>n.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Lt.find(n=>{let i=n.name.toLowerCase().replace(/[^a-z0-9]/g,"");return i===r||i.includes(r)||r.includes(i)})}function $t(t){return ts[t]}function ns(t){return t?Lt.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Lt}function ko(t){let e=t??Lt,r={};for(let i of e){r[i.category]||(r[i.category]=[]);let o=ts[i.id],s=o?` \u2014 ${o.description}`:"",a=o?.packages.length?` (${o.packages.join(", ")})`:"";r[i.category].push(`${i.id} \u2014 "${i.name}"${s}${a}`)}let n=[];for(let[i,o]of Object.entries(r))n.push(`**${i}**:
43
43
  ${o.map(s=>` - ${s}`).join(`
44
44
  `)}`);return n.join(`
45
45
 
46
- `)}function ko(t){return(t?ts(t):Mt).map(r=>{let n=es[r.id];return{id:r.id,slug:Oc(r.name),name:r.name,category:r.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var es,Mt,zn=P(()=>{"use strict";es={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"neon-smart-search":{description:"Semantic and hybrid search using Neon Postgres, pgvector, Postgres full-text search, and embeddings.",tags:["search","semantic","vector","embedding","hybrid","rag","knowledge-base","documents"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for generating embeddings",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://neon.com/docs/extensions/pgvector",packages:["openai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},Mt=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
46
+ `)}function xo(t){return(t?ns(t):Lt).map(r=>{let n=ts[r.id];return{id:r.id,slug:Dc(r.name),name:r.name,category:r.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var ts,Lt,Hn=_(()=>{"use strict";ts={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"neon-smart-search":{description:"Semantic and hybrid search using Neon Postgres, pgvector, Postgres full-text search, and embeddings.",tags:["search","semantic","vector","embedding","hybrid","rag","knowledge-base","documents"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for generating embeddings",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://neon.com/docs/extensions/pgvector",packages:["openai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},Lt=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
47
47
 
48
48
  ### File Structure
49
49
  \`\`\`
@@ -1592,12 +1592,12 @@ export async function searchDocumentsHybrid(query: string, limit = 10) {
1592
1592
  3. **Do not regenerate embeddings on every render.** Generate on create/update or in an explicit reindex action.
1593
1593
  4. **Chunk long content.** Store chunks of 500-1,000 tokens with stable \`sourceType\`, \`sourceId\`, and \`chunkIndex\`.
1594
1594
  5. **Use hybrid search for user-facing search.** Vector search handles meaning; full-text search protects exact names, codes, and phrases.
1595
- 6. **Never ask the user to paste OPENAI_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}]});import{z as De}from"zod";import{resolve as Hn}from"path";import{existsSync as Wn,readFileSync as Gn}from"fs";import{join as Vn}from"path";var jc,xo,So=P(()=>{"use strict";be();Ke();wo();_e();Zt();zn();jc=De.object({action:De.enum(["get","update","share","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:De.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:De.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:De.object({key:De.string(),description:De.string().optional(),setupUrl:De.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:De.string().optional().describe("(share) Short description of what this template builds"),category:De.string().optional().describe("(integrations) Filter integrations by category"),integrationId:De.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:De.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:De.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),xo={name:"mist_project",description:Es,inputSchema:jc,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!Se())return Ee(`${e.action} project state`);switch(e.action){case"get":case"update":return bo.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let n=Hn(e.projectPath??process.cwd()),i=Vn(n,"mistflow.json");if(!Wn(i))return Ye(n);let o;try{o=JSON.parse(Gn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first to register it.",!0);try{let a=await Gr(s,{isTemplate:!0,description:e.templateDescription});return p(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
1595
+ 6. **Never ask the user to paste OPENAI_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}]});import{z as je}from"zod";import{resolve as Wn}from"path";import{existsSync as Gn,readFileSync as Vn}from"fs";import{join as Kn}from"path";var jc,So,To=_(()=>{"use strict";be();Je();vo();_e();en();Hn();jc=je.object({action:je.enum(["get","update","share","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:je.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:je.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:je.object({key:je.string(),description:je.string().optional(),setupUrl:je.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:je.string().optional().describe("(share) Short description of what this template builds"),category:je.string().optional().describe("(integrations) Filter integrations by category"),integrationId:je.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:je.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:je.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),So={name:"mist_project",description:Ns,inputSchema:jc,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!xe())return Oe(`${e.action} project state`);switch(e.action){case"get":case"update":return wo.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let n=Wn(e.projectPath??process.cwd()),i=Kn(n,"mistflow.json");if(!Gn(i))return Qe(n);let o;try{o=JSON.parse(Vn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first to register it.",!0);try{let a=await Vr(s,{isTemplate:!0,description:e.templateDescription});return d(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
1596
1596
 
1597
1597
  Anyone can fork it: ${a.share_url}
1598
1598
 
1599
1599
  Others can use it in their AI editor:
1600
- "build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return p(l,!0)}}case"integrations":{if(e.integrationId){let s=Lt(e.integrationId);if(!s)return p(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=Ut(s.id);return p(JSON.stringify({integration:{id:s.id,name:s.name,category:s.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${s.name}" (${s.category}) \u2014 ${a?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${a?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${a?.docsUrl??"n/a"}.`}))}let n=ko(e.category??void 0),i=ts(e.category??void 0),o=vo(i);return p(JSON.stringify({count:n.length,integrations:n.map(s=>({id:s.id,name:s.name,category:s.category,description:s.description,packages:s.packages,difficulty:s.difficulty,envVars:s.envVars.map(a=>a.key)})),formatted:o,message:`${n.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let n=Hn(e.projectPath??process.cwd()),i=Vn(n,"mistflow.json");if(!Wn(i))return Ye(n);let o;try{o=JSON.parse(Gn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first.",!0);try{let a=await Mr(s,e.period??"7d");return a.total===0?p(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):p(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return p(l,!0)}}case"logs":{let n=Hn(e.projectPath??process.cwd()),i=Vn(n,"mistflow.json");if(!Wn(i))return Ye(n);let o;try{o=JSON.parse(Gn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await Ot(s);if(l.length===0)return p("No deployments found for this project.",!0);a=l[0].id}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return p(c,!0)}try{let[l,c]=await Promise.all([Dr(a),at(a)]),u=l.filter(d=>d.level==="error"),h=l.filter(d=>d.level==="warn");return p(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:u.length,warnCount:h.length,logs:l.map(d=>({time:d.timestamp,level:d.level,phase:d.phase,message:d.message})),message:c.status==="failed"?`Deployment failed. ${u.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${u.length} errors, ${h.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return p(c,!0)}}case"deployments":{let n=Hn(e.projectPath??process.cwd()),i=Vn(n,"mistflow.json");if(!Wn(i))return Ye(n);let o;try{o=JSON.parse(Gn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first.",!0);try{let a=await Ot(s);return p(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return p(l,!0)}}case"version":{wr().backendSignalReceived||await _r();let n=wr(),i=n.severity==="none",o={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return p(JSON.stringify({current:n.current,latest:n.latest||"unknown",minSupported:n.minSupported||"unknown",severity:n.severity,upToDate:i,upgradeCmd:n.upgradeCmd,changelogUrl:n.changelogUrl,backendSignalReceived:n.backendSignalReceived,message:n.backendSignalReceived?`Mistflow MCP ${n.current} (${o[n.severity]??n.severity}). Latest: ${n.latest}.${i?"":` Run \`${n.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${n.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return p(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, or version.`,!0)}}}});import{z as _t}from"zod";var Dc,To,_o=P(()=>{"use strict";Ke();be();Et();Dc=_t.object({action:_t.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:_t.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:_t.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:_t.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:_t.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:_t.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),To={name:"mist_browser",description:Ns,inputSchema:Dc,handler:async t=>{let e=t,r=await vr();if(e.action==="navigate"){if(!e.url)return p("URL is required for 'navigate'.",!0);let o=[],s=c=>{c.type()==="error"&&o.push(c.text())};r.on("console",s),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=c=>a.push(c.message);if(r.on("pageerror",l),await r.waitForTimeout(500),r.removeListener("console",s),r.removeListener("pageerror",l),o.length>0||a.length>0){let c=await en(r),u=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:o,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let h=await tn(r);u.push({type:"image",data:h.toString("base64"),mimeType:"image/png"})}return{content:u}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return p("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return p("Selector is required for 'type'.",!0);if(!e.value)return p("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return p("Selector is required for 'fill'.",!0);if(!e.value)return p("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return p("Selector is required for 'select_option'.",!0);if(!e.value)return p("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return p("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return p("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let o;if(e.selector){let s=await r.$(e.selector);if(!s)return p(`Element not found: ${e.selector}`,!0);o=await s.screenshot({type:"png"})}else o=await tn(r,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:o.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let o=await en(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}]}}let n=await en(r),i=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:n})}];if(e.includeScreenshot){let o=await tn(r);i.push({type:"image",data:o.toString("base64"),mimeType:"image/png"})}return{content:i}}}});import{z as Po}from"zod";var Io,Co,Ao=P(()=>{"use strict";Ke();be();Io=`# Mistflow MCP tool reference
1600
+ "build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return d(l,!0)}}case"integrations":{if(e.integrationId){let s=Ut(e.integrationId);if(!s)return d(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=$t(s.id);return d(JSON.stringify({integration:{id:s.id,name:s.name,category:s.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${s.name}" (${s.category}) \u2014 ${a?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${a?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${a?.docsUrl??"n/a"}.`}))}let n=xo(e.category??void 0),i=ns(e.category??void 0),o=ko(i);return d(JSON.stringify({count:n.length,integrations:n.map(s=>({id:s.id,name:s.name,category:s.category,description:s.description,packages:s.packages,difficulty:s.difficulty,envVars:s.envVars.map(a=>a.key)})),formatted:o,message:`${n.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let n=Wn(e.projectPath??process.cwd()),i=Kn(n,"mistflow.json");if(!Gn(i))return Qe(n);let o;try{o=JSON.parse(Vn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first.",!0);try{let a=await Lr(s,e.period??"7d");return a.total===0?d(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):d(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return d(l,!0)}}case"logs":{let n=Wn(e.projectPath??process.cwd()),i=Kn(n,"mistflow.json");if(!Gn(i))return Qe(n);let o;try{o=JSON.parse(Vn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await Dt(s);if(l.length===0)return d("No deployments found for this project.",!0);a=l[0].id}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return d(c,!0)}try{let[l,c]=await Promise.all([Mr(a),ct(a)]),m=l.filter(u=>u.level==="error"),p=l.filter(u=>u.level==="warn");return d(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:m.length,warnCount:p.length,logs:l.map(u=>({time:u.timestamp,level:u.level,phase:u.phase,message:u.message})),message:c.status==="failed"?`Deployment failed. ${m.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${m.length} errors, ${p.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return d(c,!0)}}case"deployments":{let n=Wn(e.projectPath??process.cwd()),i=Kn(n,"mistflow.json");if(!Gn(i))return Qe(n);let o;try{o=JSON.parse(Vn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first.",!0);try{let a=await Dt(s);return d(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return d(l,!0)}}case"version":{vr().backendSignalReceived||await Pr();let n=vr(),i=n.severity==="none",o={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return d(JSON.stringify({current:n.current,latest:n.latest||"unknown",minSupported:n.minSupported||"unknown",severity:n.severity,upToDate:i,upgradeCmd:n.upgradeCmd,changelogUrl:n.changelogUrl,backendSignalReceived:n.backendSignalReceived,message:n.backendSignalReceived?`Mistflow MCP ${n.current} (${o[n.severity]??n.severity}). Latest: ${n.latest}.${i?"":` Run \`${n.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${n.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return d(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, or version.`,!0)}}}});import{z as It}from"zod";var Mc,_o,Po=_(()=>{"use strict";Je();be();Nt();Mc=It.object({action:It.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:It.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:It.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:It.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:It.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:It.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),_o={name:"mist_browser",description:Os,inputSchema:Mc,handler:async t=>{let e=t,r=await kr();if(e.action==="navigate"){if(!e.url)return d("URL is required for 'navigate'.",!0);let o=[],s=c=>{c.type()==="error"&&o.push(c.text())};r.on("console",s),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=c=>a.push(c.message);if(r.on("pageerror",l),await r.waitForTimeout(500),r.removeListener("console",s),r.removeListener("pageerror",l),o.length>0||a.length>0){let c=await tn(r),m=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:o,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let p=await nn(r);m.push({type:"image",data:p.toString("base64"),mimeType:"image/png"})}return{content:m}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return d("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return d("Selector is required for 'type'.",!0);if(!e.value)return d("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return d("Selector is required for 'fill'.",!0);if(!e.value)return d("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return d("Selector is required for 'select_option'.",!0);if(!e.value)return d("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return d("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let o;if(e.selector){let s=await r.$(e.selector);if(!s)return d(`Element not found: ${e.selector}`,!0);o=await s.screenshot({type:"png"})}else o=await nn(r,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:o.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let o=await tn(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}]}}let n=await tn(r),i=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:n})}];if(e.includeScreenshot){let o=await nn(r);i.push({type:"image",data:o.toString("base64"),mimeType:"image/png"})}return{content:i}}}});import{z as Io}from"zod";var Co,Ao,Ro=_(()=>{"use strict";Je();be();Co=`# Mistflow MCP tool reference
1601
1601
 
1602
1602
  Every capability is an MCP tool. There is no companion CLI. Long-running tools
1603
1603
  (install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
@@ -1914,27 +1914,27 @@ is cheaper than building the wrong thing and iterating.
1914
1914
 
1915
1915
  mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
1916
1916
  mist_deploy({ action: "status", deploymentId }) # poll
1917
- `,Co={name:"mist_help",description:Os,inputSchema:Po.object({command:Po.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return p(Io);let r=e.startsWith("mist_")?e:`mist_${e}`,n=Io.split(`
1918
- `),i=new RegExp(`^### \`${r}`),o=-1,s=n.length;for(let a=0;a<n.length;a++)if(i.test(n[a]))o=a;else if(o>=0&&n[a].startsWith("### ")){s=a;break}else if(o>=0&&n[a].startsWith("## ")&&a>o){s=a;break}return o<0?p(`No tool named '${r}' found. Call mist_help with no args to see the full catalog.`,!0):p(n.slice(o,s).join(`
1919
- `).trim())}}});import{z as pn}from"zod";var Ro,Eo,No=P(()=>{"use strict";Ke();_e();be();Ro=pn.object({action:pn.enum(["list","get"]).default("get").describe("'get' (default) returns the full markdown for one topic \u2014 pass `topic`. 'list' returns the topic catalog so you can discover what's available \u2014 use to answer 'is there a doc for X?' before falling back to web search."),topic:pn.string().optional().describe("Required for action='get'. Stable topic id (e.g. 'auth-design', 'stripe-integration', 'better-auth'). Call action='list' to discover ids."),kind:pn.enum(["stack","skill","integration"]).optional().describe("Optional filter for action='list'. 'stack' = framework methodology, 'skill' = design + structural patterns, 'integration' = third-party services."),stack:pn.string().optional().default("nextjs").describe("Stack slug. Defaults to 'nextjs' (currently the only supported stack).")}),Eo={name:"mist_docs",description:js,inputSchema:Ro,handler:async t=>{let{action:e,topic:r,kind:n,stack:i}=Ro.parse(t);try{if(e==="list"){let a=await qr(i,n),l=[];l.push(`# Mistflow docs catalog (${a.stack})
1917
+ `,Ao={name:"mist_help",description:Ds,inputSchema:Io.object({command:Io.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return d(Co);let r=e.startsWith("mist_")?e:`mist_${e}`,n=Co.split(`
1918
+ `),i=new RegExp(`^### \`${r}`),o=-1,s=n.length;for(let a=0;a<n.length;a++)if(i.test(n[a]))o=a;else if(o>=0&&n[a].startsWith("### ")){s=a;break}else if(o>=0&&n[a].startsWith("## ")&&a>o){s=a;break}return o<0?d(`No tool named '${r}' found. Call mist_help with no args to see the full catalog.`,!0):d(n.slice(o,s).join(`
1919
+ `).trim())}}});import{z as un}from"zod";var Eo,No,Oo=_(()=>{"use strict";Je();_e();be();Eo=un.object({action:un.enum(["list","get"]).default("get").describe("'get' (default) returns the full markdown for one topic \u2014 pass `topic`. 'list' returns the topic catalog so you can discover what's available \u2014 use to answer 'is there a doc for X?' before falling back to web search."),topic:un.string().optional().describe("Required for action='get'. Stable topic id (e.g. 'auth-design', 'stripe-integration', 'better-auth'). Call action='list' to discover ids."),kind:un.enum(["stack","skill","integration"]).optional().describe("Optional filter for action='list'. 'stack' = framework methodology, 'skill' = design + structural patterns, 'integration' = third-party services."),stack:un.string().optional().default("nextjs").describe("Stack slug. Defaults to 'nextjs' (currently the only supported stack).")}),No={name:"mist_docs",description:js,inputSchema:Eo,handler:async t=>{let{action:e,topic:r,kind:n,stack:i}=Eo.parse(t);try{if(e==="list"){let a=await Br(i,n),l=[];l.push(`# Mistflow docs catalog (${a.stack})
1920
1920
  ${a.topics.length} topics. Call \`mist_docs({ action: "get", topic: "<id>" })\` to fetch one.
1921
- `);let c={};for(let h of a.topics)(c[h.kind]??=[]).push(h);let u=["stack","skill","integration"];for(let h of u){let d=c[h];if(!(!d||d.length===0)){l.push(`## ${h}`);for(let v of d)l.push(`- **${v.id}** \u2014 ${v.title}: ${v.description}`);l.push("")}}return p(l.join(`
1922
- `).trim())}if(!r)return p("Missing `topic`. Pass action='get' with a topic id, or action='list' to see available topics.",!0);let o=await Br(i,r),s=`<!-- mist_docs: topic=${o.topic} kind=${o.kind} stack=${o.stack} -->
1921
+ `);let c={};for(let p of a.topics)(c[p.kind]??=[]).push(p);let m=["stack","skill","integration"];for(let p of m){let u=c[p];if(!(!u||u.length===0)){l.push(`## ${p}`);for(let g of u)l.push(`- **${g.id}** \u2014 ${g.title}: ${g.description}`);l.push("")}}return d(l.join(`
1922
+ `).trim())}if(!r)return d("Missing `topic`. Pass action='get' with a topic id, or action='list' to see available topics.",!0);let o=await zr(i,r),s=`<!-- mist_docs: topic=${o.topic} kind=${o.kind} stack=${o.stack} -->
1923
1923
  # ${o.title}
1924
1924
 
1925
1925
  ${o.description}
1926
1926
 
1927
1927
  ---
1928
1928
 
1929
- `;return p(s+o.content)}catch(o){if(o instanceof G&&o.statusCode===404)return p(o.message,!0);let s=o instanceof Error?o.message:String(o);return p(`mist_docs failed: ${s}
1929
+ `;return d(s+o.content)}catch(o){if(o instanceof K&&o.statusCode===404)return d(o.message,!0);let s=o instanceof Error?o.message:String(o);return d(`mist_docs failed: ${s}
1930
1930
 
1931
- If this looks like a network issue, retry. If it persists, you can fall back to reading AGENTS.md / .claude/skills/ in the user's project for the same content.`,!0)}}}});import{existsSync as Kn,mkdirSync as Do,readFileSync as Mo,readdirSync as Lo,writeFileSync as Mc}from"fs";import{join as dt,resolve as Lc}from"path";import{homedir as rs}from"os";import{z as un}from"zod";function $t(t){return t.entity??t.name??"Unknown"}function Ft(t){return typeof t=="string"?t:t.name}function ns(t){return typeof t=="string"?"text":t.type}function Oo(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(i=>{let o={};for(let[s,a]of Object.entries(i))o[s]=a==null?"":String(a);return o});let r=t.fields||[],n=[];for(let i=0;i<3;i++){let o={};for(let s of r)o[Ft(s)]=Uc(Ft(s),ns(s),$t(t),i);n.push(o)}return n}function Uc(t,e,r,n){let i=t.toLowerCase(),o=(e||"text").toLowerCase();return i==="name"||i==="title"?[`${r} Alpha`,`${r} Beta`,`${r} Gamma`][n]:i==="email"?["alice@example.com","bob@example.com","carol@example.com"][n]:i==="status"?["Active","Pending","Completed"][n]:i==="priority"?["High","Medium","Low"][n]:i.includes("date")||o==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][n]:i.includes("price")||i.includes("amount")||i.includes("cost")?["$29","$49","$99"][n]:i.includes("count")||i.includes("quantity")||o==="number"||o==="integer"?["12","34","56"][n]:o==="boolean"||o==="bool"?["Yes","No","Yes"][n]:i.includes("description")||o==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function $c(t){let e=t.dataModel??[],r=t.pages??[],n=t.design??{},i=r.map(h=>({label:h.name??h.path??"Page",route:h.path??h.route??"/"})),o=[],s=e.slice(0,3).map(h=>({name:$t(h),fields:(h.fields||[]).map(d=>({name:Ft(d),type:ns(d)})),sampleData:Oo(h)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(h=>$t(h)).join(", ")}`),a.push("RECENT: Latest activity or items"),o.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(h=>$t(h)).join(", ")} with key metrics.`,informationHierarchy:a,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:s});let l=e[0];if(l){let h=$t(l),d=h.toLowerCase().endsWith("s")?h:`${h}s`;o.push({name:`${h} List`,type:"detail",route:`/${d.toLowerCase()}`,purpose:`Browse, search, and manage ${d.toLowerCase()}. Create new ${h.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${d}" title + "Add ${h}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(v=>Ft(v)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${d.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${d.toLowerCase()} matching..." with clear filter`],entities:[{name:h,fields:(l.fields||[]).map(v=>({name:Ft(v),type:ns(v)})),sampleData:Oo(l)}]})}t.steps.some(h=>{let d=`${h.name??h.title??""} ${h.description??""}`.toLowerCase();return d.includes("landing")||d.includes("hero")||d.includes("marketing")||d.includes("homepage")})&&o.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let u=[];for(let h of e.slice(0,3)){let d=$t(h);(h.fields||[]).find(W=>{let _=Ft(W).toLowerCase();return _==="name"||_==="title"})&&u.push(`What if a ${d.toLowerCase()}'s name is 47 characters? Does the layout break?`),u.push(`What if there are 0 ${d.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&u.push("What does a brand-new user see? (no data, no setup)"),u.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:o,navigation:{style:t.navStyle??"sidebar",items:i},primaryAction:t.primaryAction??null,designDirection:{tone:n.tone??"professional",accentColor:n.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:n.fonts??{heading:"Inter",body:"Inter"}},edgeCases:u}}function Fc(t,e,r){let n=[];n.push(`# Wireframe sketch for ${t.appName}`),n.push(""),n.push(`**${t.appName}** \u2014 ${t.summary}`),n.push(""),e&&(n.push("## Feedback to apply"),n.push(e),n.push("")),n.push("## Design principles"),n.push(""),n.push("Apply these when deciding layout and hierarchy:"),n.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),n.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),n.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),n.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),n.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),n.push(""),n.push("## Wireframe rules (strict)"),n.push(""),n.push(`Write a **single self-contained HTML file** saved to \`${r}\`.`),n.push(""),n.push("The wireframe must:"),n.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),n.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),n.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),n.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),n.push("- Include **HTML comments** explaining design decisions"),n.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),n.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),n.push("- Include a small header bar showing: screen name tabs + the design direction summary"),n.push(""),n.push("The wireframe must NOT:"),n.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),n.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),n.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),n.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),n.push(""),n.push("## Screens to wireframe"),n.push("");for(let i of t.screens){n.push(`### ${i.name} (\`${i.route}\`)`),n.push(`**Purpose**: ${i.purpose}`),n.push(""),n.push("**Information hierarchy** (render in this order, top to bottom):");for(let o of i.informationHierarchy)n.push(`- ${o}`);n.push(""),n.push("**Interaction states** (add HTML comments for non-visible states):");for(let o of i.interactionStates)n.push(`- ${o}`);if(n.push(""),i.entities.length>0){n.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let o of i.entities)n.push(`
1931
+ If this looks like a network issue, retry. If it persists, you can fall back to reading AGENTS.md / .claude/skills/ in the user's project for the same content.`,!0)}}}});import{existsSync as Jn,mkdirSync as Mo,readFileSync as Lo,readdirSync as Uo,writeFileSync as Lc}from"fs";import{join as ut,resolve as Uc}from"path";import{homedir as ss}from"os";import{z as mn}from"zod";function Ft(t){return t.entity??t.name??"Unknown"}function qt(t){return typeof t=="string"?t:t.name}function rs(t){return typeof t=="string"?"text":t.type}function Do(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(i=>{let o={};for(let[s,a]of Object.entries(i))o[s]=a==null?"":String(a);return o});let r=t.fields||[],n=[];for(let i=0;i<3;i++){let o={};for(let s of r)o[qt(s)]=$c(qt(s),rs(s),Ft(t),i);n.push(o)}return n}function $c(t,e,r,n){let i=t.toLowerCase(),o=(e||"text").toLowerCase();return i==="name"||i==="title"?[`${r} Alpha`,`${r} Beta`,`${r} Gamma`][n]:i==="email"?["alice@example.com","bob@example.com","carol@example.com"][n]:i==="status"?["Active","Pending","Completed"][n]:i==="priority"?["High","Medium","Low"][n]:i.includes("date")||o==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][n]:i.includes("price")||i.includes("amount")||i.includes("cost")?["$29","$49","$99"][n]:i.includes("count")||i.includes("quantity")||o==="number"||o==="integer"?["12","34","56"][n]:o==="boolean"||o==="bool"?["Yes","No","Yes"][n]:i.includes("description")||o==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function Fc(t){let e=t.dataModel??[],r=t.pages??[],n=t.design??{},i=r.map(p=>({label:p.name??p.path??"Page",route:p.path??p.route??"/"})),o=[],s=e.slice(0,3).map(p=>({name:Ft(p),fields:(p.fields||[]).map(u=>({name:qt(u),type:rs(u)})),sampleData:Do(p)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(p=>Ft(p)).join(", ")}`),a.push("RECENT: Latest activity or items"),o.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(p=>Ft(p)).join(", ")} with key metrics.`,informationHierarchy:a,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:s});let l=e[0];if(l){let p=Ft(l),u=p.toLowerCase().endsWith("s")?p:`${p}s`;o.push({name:`${p} List`,type:"detail",route:`/${u.toLowerCase()}`,purpose:`Browse, search, and manage ${u.toLowerCase()}. Create new ${p.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${u}" title + "Add ${p}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(g=>qt(g)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${u.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${u.toLowerCase()} matching..." with clear filter`],entities:[{name:p,fields:(l.fields||[]).map(g=>({name:qt(g),type:rs(g)})),sampleData:Do(l)}]})}t.steps.some(p=>{let u=`${p.name??p.title??""} ${p.description??""}`.toLowerCase();return u.includes("landing")||u.includes("hero")||u.includes("marketing")||u.includes("homepage")})&&o.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let m=[];for(let p of e.slice(0,3)){let u=Ft(p);(p.fields||[]).find(j=>{let I=qt(j).toLowerCase();return I==="name"||I==="title"})&&m.push(`What if a ${u.toLowerCase()}'s name is 47 characters? Does the layout break?`),m.push(`What if there are 0 ${u.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&m.push("What does a brand-new user see? (no data, no setup)"),m.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:o,navigation:{style:t.navStyle??"sidebar",items:i},primaryAction:t.primaryAction??null,designDirection:{tone:n.tone??"professional",accentColor:n.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:n.fonts??{heading:"Inter",body:"Inter"}},edgeCases:m}}function qc(t,e,r){let n=[];n.push(`# Wireframe sketch for ${t.appName}`),n.push(""),n.push(`**${t.appName}** \u2014 ${t.summary}`),n.push(""),e&&(n.push("## Feedback to apply"),n.push(e),n.push("")),n.push("## Design principles"),n.push(""),n.push("Apply these when deciding layout and hierarchy:"),n.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),n.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),n.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),n.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),n.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),n.push(""),n.push("## Wireframe rules (strict)"),n.push(""),n.push(`Write a **single self-contained HTML file** saved to \`${r}\`.`),n.push(""),n.push("The wireframe must:"),n.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),n.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),n.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),n.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),n.push("- Include **HTML comments** explaining design decisions"),n.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),n.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),n.push("- Include a small header bar showing: screen name tabs + the design direction summary"),n.push(""),n.push("The wireframe must NOT:"),n.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),n.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),n.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),n.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),n.push(""),n.push("## Screens to wireframe"),n.push("");for(let i of t.screens){n.push(`### ${i.name} (\`${i.route}\`)`),n.push(`**Purpose**: ${i.purpose}`),n.push(""),n.push("**Information hierarchy** (render in this order, top to bottom):");for(let o of i.informationHierarchy)n.push(`- ${o}`);n.push(""),n.push("**Interaction states** (add HTML comments for non-visible states):");for(let o of i.interactionStates)n.push(`- ${o}`);if(n.push(""),i.entities.length>0){n.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let o of i.entities)n.push(`
1932
1932
  **${o.name}** \u2014 fields: ${o.fields.map(s=>`${s.name} (${s.type})`).join(", ")}`),n.push("```json"),n.push(JSON.stringify(o.sampleData,null,2)),n.push("```");n.push("")}}n.push("## Navigation"),n.push(`**Style**: ${t.navigation.style} (use this layout)`),n.push("**Items**:");for(let i of t.navigation.items)n.push(`- ${i.label} \u2192 \`${i.route}\``);if(n.push(""),t.primaryAction&&(n.push("## Primary action (this drives the layout)"),n.push(`- **Action**: ${t.primaryAction.action}`),n.push(`- **Flow**: ${t.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),n.push(""),n.push("The dashboard is an ACTION surface. The primary action should be the most prominent thing on the page \u2014 above the metrics, above the recent items. Users came here to DO something, not to look at numbers."),n.push("")),t.edgeCases.length>0){n.push("## Edge cases to consider"),n.push("Add HTML comments in the wireframe where these matter:");for(let i of t.edgeCases)n.push(`- ${i}`);n.push("")}return n.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),n.push(`The final app will use: ${t.designDirection.tone} tone, ${t.designDirection.accentColor} accent, ${t.designDirection.navStyle} nav, ${t.designDirection.fonts.heading} / ${t.designDirection.fonts.body} fonts.`),n.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),n.push(""),n.push("## After writing the wireframe"),n.push(`1. Write the file to \`${r}\``),n.push(`2. Open it for the user: \`open "${r}"\``),n.push(`3. Tell the user: "Here's a rough wireframe of your app. Does the layout feel right? Let me know what to change, or I can start building if it's close."`),n.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),n.join(`
1933
- `)}function Uo(t){return dt(rs(),".mistflow","mockup-state",`${t}.json`)}function qc(t){let e=Uo(t);if(!Kn(e))return null;try{return JSON.parse(Mo(e,"utf-8"))}catch{return null}}function jo(t,e){let r=dt(rs(),".mistflow","mockup-state");Do(r,{recursive:!0}),Mc(Uo(t),JSON.stringify(e,null,2))}function Fo(t){let e=dt(t,".mistflow","mockups");return Kn(e)?Lo(e).filter(r=>r.endsWith(".html")).map(r=>dt(e,r)):[]}var Bc,$o,ss=P(()=>{"use strict";Ke();be();Bc=un.object({planId:un.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:un.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:un.string().optional().describe("User feedback to apply to the next iteration."),approved:un.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(t=>!(t.feedback&&t.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),$o={name:"mist_mockup",description:Ms,inputSchema:Bc,handler:async t=>{let e=t,{planId:r,feedback:n,approved:i}=e,o=Lc(e.projectPath??process.cwd()),s=dt(rs(),".mistflow","plans",`${r}.json`);if(!Kn(s))return p(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(Mo(s,"utf-8"))}catch{return p("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return p("Plan data is empty. Call mist_plan again.",!0);let c=qc(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let u=dt(o,".mistflow","mockups");Do(u,{recursive:!0});let h=`mockup-${r}.html`,d=dt(u,h);if(i){c.approved=!0,jo(r,c);let y=Kn(u)?Lo(u).filter(A=>A.endsWith(".html")).map(A=>dt(".mistflow","mockups",A)):[];return p(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:y,nextAction:`Call mist_init with planId='${r}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}c.iterationCount++,n&&c.feedback.push(n);let v=$c(l);c.screens=v.screens.map(y=>y.name),jo(r,c);let W=Fc(v,n??void 0,d),_=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,k=n?`Apply the user's feedback to ${d}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${d}, then open it in the browser. Ask the user if the layout feels right.`;return p(JSON.stringify({status:"wireframe",requires_user_input:!0,iterationCount:c.iterationCount,screens:v.screens.map(y=>({name:y.name,type:y.type,route:y.route})),wireframePrompt:W,designDirection:v.designDirection,..._?{nudge:_}:{},mockupFile:h,mockupPath:d,nextAction:k}))}}});function Jn(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,c,u,h,d]=a;e.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:`${h}: ${d}`,humanMessage:`There is a type error in ${l} on line ${c}: ${d}`,suggestion:`Check line ${c} in ${l}. ${h==="TS2345"?"The types of the arguments do not match.":`Fix the ${h} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(n)){let[,l,c,u,h]=a;e.some(d=>d.file===l&&d.line===parseInt(c,10))||e.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:h,humanMessage:`There is an error in ${l} on line ${c}: ${h.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let i=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of t.matchAll(i)){let[,l,c]=a;e.push({file:c,message:`Module not found: ${l}`,humanMessage:`The file ${c??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let o=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(o)){let[,l,c]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${c}${l}`,humanMessage:`The package '${c}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${c}'.`,suggestion:`Add '${c}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let s=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of t.matchAll(s)){let[,l,c,u,h]=a;e.some(d=>d.file===l&&d.line===parseInt(u,10))||e.push({file:l,line:parseInt(u,10),column:parseInt(h,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${u}.`,suggestion:`Check line ${u} in ${l} for a missing closing bracket or unexpected token.`})}return e}var os=P(()=>{"use strict"});import{z as is}from"zod";import{resolve as zc}from"path";import{spawn as Hc}from"child_process";function Gc(t){return new Promise(e=>{let r=Hc("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),n="";r.stdout?.on("data",i=>{n+=i.toString()}),r.stderr?.on("data",i=>{n+=i.toString()}),r.on("error",i=>{e({exitCode:127,combined:`${n}
1934
- ${i.message}`})}),r.on("close",i=>{e({exitCode:i??1,combined:n})})})}var Wc,qo,Bo=P(()=>{"use strict";Ke();be();os();Wc=is.object({projectPath:is.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:is.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});qo={name:"mist_debug",description:Ds,inputSchema:Wc,handler:async t=>{let e=t,r=zc(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let s=await Gc(r);if(s.exitCode===0)return p(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=s.combined}let i=Jn(n),o=n.slice(0,2e3);return i.length===0?p(JSON.stringify({errors:i,rawOutput:o,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):p(JSON.stringify({errors:i,rawOutput:o,message:`Found ${i.length} error${i.length===1?"":"s"} in the build output.`}))}}});import{spawn as Vc}from"child_process";function as(t){if(process.env.MISTFLOW_AUTO_OPEN_PICKER==="false")return{opened:!1,reason:"MISTFLOW_AUTO_OPEN_PICKER=false"};let e;try{e=new URL(t)}catch{return{opened:!1,reason:"invalid URL"}}if(e.protocol!=="http:"&&e.protocol!=="https:"&&e.protocol!=="file:")return{opened:!1,reason:`unsupported protocol ${e.protocol}`};if(Kc())return{opened:!1,reason:"headless environment detected"};let r=process.platform,n,i;r==="darwin"?(n="open",i=[e.href]):r==="win32"?(n="cmd",i=["/c","start","",e.href]):(n="xdg-open",i=[e.href]);try{let o=Vc(n,i,{shell:!1,stdio:"ignore",detached:!0});return o.on("error",()=>{}),o.unref(),{opened:!0}}catch(o){return{opened:!1,reason:o instanceof Error?o.message:"spawn failed"}}}function Kc(){if(process.env.SSH_TTY||process.env.SSH_CONNECTION)return!0;for(let t of["CI","BUILDKITE","GITHUB_ACTIONS","CIRCLECI","GITLAB_CI"])if(process.env[t])return!0;return process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY&&!process.env.WSL_DISTRO_NAME}var zo=P(()=>{"use strict"});function qe(t,e,r,n=3e3){if(e===void 0)return{stop:()=>{}};let i=0,o=!1,a=setInterval(()=>{o||(i++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:i,message:r()}}).catch(()=>{}))},n);return{stop:()=>{o||(o=!0,clearInterval(a))}}}var qt=P(()=>{"use strict"});function Jc(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function Yc(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function Qc(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function Xc(t){let e={},r=[],n=[],i=new Set;for(let o=0;o<t.length;o++){let s=t[o],a=s.decisionKey?Qc(s.decisionKey):`q_${o+1}`,l=a,c=2;for(;i.has(l);)l=`${a}_${c}`,c++;i.add(l);let u=s.freetext?"":`${l}_other`;if(u&&i.add(u),n.push({primary:l,other:u,question:s}),s.freetext){e[l]={type:"string",title:s.question,description:s.why,...s.recommended?{default:s.recommended}:{}},r.push(l);continue}let h=(s.options??[]).map(v=>typeof v=="string"?v:v.label),d=s.noOtherSentinel?[...h]:[...h,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:s.question,description:s.why?`${s.why}${s.recommended?`
1935
- Recommended: ${s.recommended}`:""}`:s.recommended?`Recommended: ${s.recommended}`:void 0,enum:d,enumNames:d,...s.recommended&&h.includes(s.recommended)?{default:s.recommended}:{}},r.push(l),e[u]={type:"string",title:s.otherFieldTitle??"If 'Other' selected above: type your answer",description:"Leave blank if you picked an option from the list."}}return{schema:{type:"object",properties:e,required:r},fieldKeys:n}}function Zc(t,e){let r=[],n;for(let{primary:i,other:o,question:s}of e){let a=String(t[i]??"").trim(),l;if(s.freetext)l=a||s.recommended||"";else{let u=o?String(t[o]??"").trim():"",h=a.toLowerCase(),d=h.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(h);u?l=u:d?l=s.recommended??(s.options?.[0]&&typeof s.options[0]=="object"?s.options[0].label:"")??a:l=a}let c=s.decisionKey??"";if(c==="urlChoice"){n=l;continue}r.push({question:s.question,decisionKey:c,answer:l})}return{answers:r,urlChoice:n}}function Qe(t,e,r){let n;switch(r.outcome){case"submitted":n=`submitted (${r.answers?.length??0} answers${r.urlChoice?`, urlChoice="${r.urlChoice}"`:""})`;break;case"error":n=`error (${r.errorMessage??"unknown"})`;break;case"unsupported":n=`unsupported (${e})`;break;default:n=r.outcome}console.error(`[mist_plan] elicitation/${t}: ${n}`)}async function mn(t,e,r,n="discovery"){if(Yc()){let u={outcome:"unsupported"};return Qe(n,"MISTFLOW_ELICITATION kill switch on",u),u}if(!Jc(t)){let u={outcome:"unsupported"};return Qe(n,"client did not declare elicitation capability",u),u}if(e.length===0){let u={outcome:"submitted",answers:[]};return Qe(n,"no questions to ask",u),u}let{schema:i,fieldKeys:o}=Xc(e),s;try{s=await t.elicitInput({message:r,requestedSchema:i,mode:"form"},{timeout:300*1e3})}catch(u){let h=u instanceof Error?u.message:String(u);if(h.toLowerCase().includes("not support")){let v={outcome:"unsupported"};return Qe(n,`SDK rejected form mode: ${h}`,v),v}let d={outcome:"error",errorMessage:h};return Qe(n,"",d),d}if(s.action==="decline"){let u={outcome:"declined"};return Qe(n,"",u),u}if(s.action==="cancel"){let u={outcome:"cancelled"};return Qe(n,"",u),u}if(s.action!=="accept"||!s.content){let u={outcome:"error",errorMessage:`Unexpected elicitation result: ${s.action}`};return Qe(n,"",u),u}let{answers:a,urlChoice:l}=Zc(s.content,o),c={outcome:"submitted",answers:a,urlChoice:l};return Qe(n,"",c),c}var Ho=P(()=>{"use strict"});function Wo(t,e,r){let n=r?.suggestedName||td(t),i=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",o=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),s=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",a;if(r?.suggestedFeatures&&r.suggestedFeatures.length>0)a=r.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;a=[];for(let c of ed){let u=c.keywords.test(l),h=c.condition(e);(u||h)&&a.push({name:c.name,description:c.description,checked:u,source:u?"explicit":"suggested"})}}return{name:n,audience:i,audienceType:o,surfaceType:s,primaryAction:e.primaryAction||"manage items",features:a,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:r?.language||"English"}}function Go(t){let e=t.features.filter(a=>a.checked),r=t.features.filter(a=>!a.checked),n={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},i={neon:"Postgres",turso:"SQLite (legacy)"},o={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},s=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${o[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${n[t.authModel]??t.authModel} | Database: ${i[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){s.push("**Included:**");for(let a of e)s.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(s.push(""),s.push(`**Integrations:** ${t.integrations.join(", ")}`)),r.length>0){s.push(""),s.push("**Available to add:**");for(let a of r)s.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return s.join(`
1936
- `)}function td(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return Yn(e[1]);let r=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),i=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(o=>o.length>2&&!r.has(o)).slice(0,3);return i.length===0?"my-app":i.join("-")}function Yn(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var ed,Vo=P(()=>{"use strict";ed=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:t=>t.surfaceType==="internal-tool"||t.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:t=>t.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:t=>t.scheduling===!0,keywords:/\b(schedul|book|reserv|appointment|calendar|slot)\b/i},{name:"Payments / Billing",description:"Charge users, invoices, subscriptions (experimental \u2014 Stripe integration is early-stage)",condition:()=>!1,keywords:/\b(payment|billing|invoice|subscription|checkout|stripe)\b/i},{name:"Admin Panel",description:"Manage users, roles, and content",condition:t=>t.multiRole===!0||t.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:t=>t.primaryActor==="customers"||t.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:t=>t.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:t=>t.integrations?.includes("email")===!0,keywords:/\b(notification|alert|reminder|email.?notif|sms|welcome.?email)\b/i},{name:"Analytics / Reports",description:"Usage stats, trends, data exports",condition:()=>!1,keywords:/\b(analytics|report|chart|trend|insight|metric)\b/i},{name:"File Uploads",description:"Images, documents, attachments",condition:t=>t.integrations?.includes("file-uploads")===!0,keywords:/\b(upload|image|photo|attachment|document|gallery|file)\b/i},{name:"AI Features",description:"Chatbot, content generation, AI assistant",condition:t=>t.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:t=>t.integrations?.includes("maps")===!0,keywords:/\b(map|location|address|geo|places)\b/i},{name:"Voice / TTS",description:"Text-to-speech, voice notes, audio generation",condition:()=>!1,keywords:/\b(voice|tts|text.?to.?speech|audio|speak|narrat|podcast|elevenlabs)\b/i},{name:"SMS / Text Messages",description:"Send SMS notifications, OTP verification",condition:t=>t.integrations?.includes("sms")===!0,keywords:/\b(sms|text.?message|twilio|otp|verification.?code|phone.?verif)\b/i},{name:"Web Scraping",description:"Scrape URLs, crawl websites, extract structured data",condition:()=>!1,keywords:/\b(scrape|crawl|web.?scrap|extract.?from.?url|read.?url|ingest.?web|firecrawl)\b/i},{name:"Chat / Messaging",description:"Real-time messaging between users",condition:()=>!1,keywords:/\b(chat|messag|inbox|conversation|dm)\b/i},{name:"Events / Tournaments",description:"Create and manage events, registrations",condition:()=>!1,keywords:/\b(event|tournament|competition|league|registration)\b/i},{name:"High Scores",description:"Track and display top scores with a leaderboard",condition:t=>t.surfaceType==="game",keywords:/\b(high.?score|leaderboard|top.?score|ranking|scoreboard)\b/i},{name:"Save Progress",description:"Save and resume game state between sessions",condition:t=>t.surfaceType==="game",keywords:/\b(save|progress|resume|checkpoint|continue)\b/i},{name:"Guest Play",description:"Play immediately without signing up, optionally link account later",condition:t=>t.surfaceType==="game",keywords:/\b(guest|anonymous|no.?login|play.?now|instant.?play)\b/i},{name:"Levels / Stages",description:"Progressive difficulty with unlockable stages",condition:()=>!1,keywords:/\b(level|stage|unlock|difficult|progress|world)\b/i},{name:"Achievements",description:"Badges, trophies, and milestones for player accomplishments",condition:()=>!1,keywords:/\b(achieve|badge|trophy|milestone|reward|unlock)\b/i},{name:"Daily Challenge",description:"New puzzle or challenge every day to keep players coming back",condition:()=>!1,keywords:/\b(daily|challenge|streak|word.?of.?the.?day|puzzle.?of)\b/i}]});function ls(t,e,r){let n=hn(t||"your app"),i=e.map((s,a)=>{let l=Qn(s.id||`direction-${a}`),c=hn(s.name||`Direction ${a+1}`),u=hn(s.summary||"");return`<button class="tab${a===0?" active":""}" data-target="${l}" type="button"><span class="tab-name">${c}</span>${u?`<span class="tab-sub">${u}</span>`:""}</button>`}).join(`
1937
- `),o=e.map((s,a)=>{let l=Qn(s.id||`direction-${a}`),c=r[s.id??""]??"";return`<iframe class="render-frame${a===0?" active":""}" data-id="${l}" srcdoc="${Qn(c)}" sandbox="allow-same-origin allow-scripts" title="${Qn(s.name||`Direction ${a+1}`)}"></iframe>`}).join(`
1933
+ `)}function $o(t){return ut(ss(),".mistflow","mockup-state",`${t}.json`)}function Bc(t){let e=$o(t);if(!Jn(e))return null;try{return JSON.parse(Lo(e,"utf-8"))}catch{return null}}function jo(t,e){let r=ut(ss(),".mistflow","mockup-state");Mo(r,{recursive:!0}),Lc($o(t),JSON.stringify(e,null,2))}function qo(t){let e=ut(t,".mistflow","mockups");return Jn(e)?Uo(e).filter(r=>r.endsWith(".html")).map(r=>ut(e,r)):[]}var zc,Fo,os=_(()=>{"use strict";Je();be();zc=mn.object({planId:mn.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:mn.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:mn.string().optional().describe("User feedback to apply to the next iteration."),approved:mn.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(t=>!(t.feedback&&t.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),Fo={name:"mist_mockup",description:Ls,inputSchema:zc,handler:async t=>{let e=t,{planId:r,feedback:n,approved:i}=e,o=Uc(e.projectPath??process.cwd()),s=ut(ss(),".mistflow","plans",`${r}.json`);if(!Jn(s))return d(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(Lo(s,"utf-8"))}catch{return d("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return d("Plan data is empty. Call mist_plan again.",!0);let c=Bc(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let m=ut(o,".mistflow","mockups");Mo(m,{recursive:!0});let p=`mockup-${r}.html`,u=ut(m,p);if(i){c.approved=!0,jo(r,c);let y=Jn(m)?Uo(m).filter(R=>R.endsWith(".html")).map(R=>ut(".mistflow","mockups",R)):[];return d(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:y,nextAction:`Call mist_init with planId='${r}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}c.iterationCount++,n&&c.feedback.push(n);let g=Fc(l);c.screens=g.screens.map(y=>y.name),jo(r,c);let j=qc(g,n??void 0,u),I=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,S=n?`Apply the user's feedback to ${u}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${u}, then open it in the browser. Ask the user if the layout feels right.`;return d(JSON.stringify({status:"wireframe",requires_user_input:!0,iterationCount:c.iterationCount,screens:g.screens.map(y=>({name:y.name,type:y.type,route:y.route})),wireframePrompt:j,designDirection:g.designDirection,...I?{nudge:I}:{},mockupFile:p,mockupPath:u,nextAction:S}))}}});function Yn(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,c,m,p,u]=a;e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:`${p}: ${u}`,humanMessage:`There is a type error in ${l} on line ${c}: ${u}`,suggestion:`Check line ${c} in ${l}. ${p==="TS2345"?"The types of the arguments do not match.":`Fix the ${p} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(n)){let[,l,c,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(c,10))||e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:p,humanMessage:`There is an error in ${l} on line ${c}: ${p.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let i=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of t.matchAll(i)){let[,l,c]=a;e.push({file:c,message:`Module not found: ${l}`,humanMessage:`The file ${c??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let o=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(o)){let[,l,c]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${c}${l}`,humanMessage:`The package '${c}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${c}'.`,suggestion:`Add '${c}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let s=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of t.matchAll(s)){let[,l,c,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(m,10))||e.push({file:l,line:parseInt(m,10),column:parseInt(p,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${m}.`,suggestion:`Check line ${m} in ${l} for a missing closing bracket or unexpected token.`})}return e}var is=_(()=>{"use strict"});import{z as as}from"zod";import{resolve as Hc}from"path";import{spawn as Wc}from"child_process";function Vc(t){return new Promise(e=>{let r=Wc("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),n="";r.stdout?.on("data",i=>{n+=i.toString()}),r.stderr?.on("data",i=>{n+=i.toString()}),r.on("error",i=>{e({exitCode:127,combined:`${n}
1934
+ ${i.message}`})}),r.on("close",i=>{e({exitCode:i??1,combined:n})})})}var Gc,Bo,zo=_(()=>{"use strict";Je();be();is();Gc=as.object({projectPath:as.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:as.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});Bo={name:"mist_debug",description:Ms,inputSchema:Gc,handler:async t=>{let e=t,r=Hc(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let s=await Vc(r);if(s.exitCode===0)return d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=s.combined}let i=Yn(n),o=n.slice(0,2e3);return i.length===0?d(JSON.stringify({errors:i,rawOutput:o,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):d(JSON.stringify({errors:i,rawOutput:o,message:`Found ${i.length} error${i.length===1?"":"s"} in the build output.`}))}}});import{spawn as Kc}from"child_process";function ls(t){if(process.env.MISTFLOW_AUTO_OPEN_PICKER==="false")return{opened:!1,reason:"MISTFLOW_AUTO_OPEN_PICKER=false"};let e;try{e=new URL(t)}catch{return{opened:!1,reason:"invalid URL"}}if(e.protocol!=="http:"&&e.protocol!=="https:"&&e.protocol!=="file:")return{opened:!1,reason:`unsupported protocol ${e.protocol}`};if(Jc())return{opened:!1,reason:"headless environment detected"};let r=process.platform,n,i;r==="darwin"?(n="open",i=[e.href]):r==="win32"?(n="cmd",i=["/c","start","",e.href]):(n="xdg-open",i=[e.href]);try{let o=Kc(n,i,{shell:!1,stdio:"ignore",detached:!0});return o.on("error",()=>{}),o.unref(),{opened:!0}}catch(o){return{opened:!1,reason:o instanceof Error?o.message:"spawn failed"}}}function Jc(){if(process.env.SSH_TTY||process.env.SSH_CONNECTION)return!0;for(let t of["CI","BUILDKITE","GITHUB_ACTIONS","CIRCLECI","GITLAB_CI"])if(process.env[t])return!0;return process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY&&!process.env.WSL_DISTRO_NAME}var Ho=_(()=>{"use strict"});function ze(t,e,r,n=3e3){if(e===void 0)return{stop:()=>{}};let i=0,o=!1,a=setInterval(()=>{o||(i++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:i,message:r()}}).catch(()=>{}))},n);return{stop:()=>{o||(o=!0,clearInterval(a))}}}var Bt=_(()=>{"use strict"});function Yc(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function Qc(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function Xc(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function Zc(t){let e={},r=[],n=[],i=new Set;for(let o=0;o<t.length;o++){let s=t[o],a=s.decisionKey?Xc(s.decisionKey):`q_${o+1}`,l=a,c=2;for(;i.has(l);)l=`${a}_${c}`,c++;i.add(l);let m=s.freetext?"":`${l}_other`;if(m&&i.add(m),n.push({primary:l,other:m,question:s}),s.freetext){e[l]={type:"string",title:s.question,description:s.why,...s.recommended?{default:s.recommended}:{}},r.push(l);continue}let p=(s.options??[]).map(g=>typeof g=="string"?g:g.label),u=s.noOtherSentinel?[...p]:[...p,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:s.question,description:s.why?`${s.why}${s.recommended?`
1935
+ Recommended: ${s.recommended}`:""}`:s.recommended?`Recommended: ${s.recommended}`:void 0,enum:u,enumNames:u,...s.recommended&&p.includes(s.recommended)?{default:s.recommended}:{}},r.push(l),e[m]={type:"string",title:s.otherFieldTitle??"If 'Other' selected above: type your answer",description:"Leave blank if you picked an option from the list."}}return{schema:{type:"object",properties:e,required:r},fieldKeys:n}}function ed(t,e){let r=[],n;for(let{primary:i,other:o,question:s}of e){let a=String(t[i]??"").trim(),l;if(s.freetext)l=a||s.recommended||"";else{let m=o?String(t[o]??"").trim():"",p=a.toLowerCase(),u=p.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(p);m?l=m:u?l=s.recommended??(s.options?.[0]&&typeof s.options[0]=="object"?s.options[0].label:"")??a:l=a}let c=s.decisionKey??"";if(c==="urlChoice"){n=l;continue}r.push({question:s.question,decisionKey:c,answer:l})}return{answers:r,urlChoice:n}}function Xe(t,e,r){let n;switch(r.outcome){case"submitted":n=`submitted (${r.answers?.length??0} answers${r.urlChoice?`, urlChoice="${r.urlChoice}"`:""})`;break;case"error":n=`error (${r.errorMessage??"unknown"})`;break;case"unsupported":n=`unsupported (${e})`;break;default:n=r.outcome}console.error(`[mist_plan] elicitation/${t}: ${n}`)}async function hn(t,e,r,n="discovery"){if(Qc()){let m={outcome:"unsupported"};return Xe(n,"MISTFLOW_ELICITATION kill switch on",m),m}if(!Yc(t)){let m={outcome:"unsupported"};return Xe(n,"client did not declare elicitation capability",m),m}if(e.length===0){let m={outcome:"submitted",answers:[]};return Xe(n,"no questions to ask",m),m}let{schema:i,fieldKeys:o}=Zc(e),s;try{s=await t.elicitInput({message:r,requestedSchema:i,mode:"form"},{timeout:300*1e3})}catch(m){let p=m instanceof Error?m.message:String(m);if(p.toLowerCase().includes("not support")){let g={outcome:"unsupported"};return Xe(n,`SDK rejected form mode: ${p}`,g),g}let u={outcome:"error",errorMessage:p};return Xe(n,"",u),u}if(s.action==="decline"){let m={outcome:"declined"};return Xe(n,"",m),m}if(s.action==="cancel"){let m={outcome:"cancelled"};return Xe(n,"",m),m}if(s.action!=="accept"||!s.content){let m={outcome:"error",errorMessage:`Unexpected elicitation result: ${s.action}`};return Xe(n,"",m),m}let{answers:a,urlChoice:l}=ed(s.content,o),c={outcome:"submitted",answers:a,urlChoice:l};return Xe(n,"",c),c}var Wo=_(()=>{"use strict"});function Go(t,e,r){let n=r?.suggestedName||nd(t),i=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",o=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),s=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",a;if(r?.suggestedFeatures&&r.suggestedFeatures.length>0)a=r.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;a=[];for(let c of td){let m=c.keywords.test(l),p=c.condition(e);(m||p)&&a.push({name:c.name,description:c.description,checked:m,source:m?"explicit":"suggested"})}}return{name:n,audience:i,audienceType:o,surfaceType:s,primaryAction:e.primaryAction||"manage items",features:a,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:r?.language||"English"}}function Vo(t){let e=t.features.filter(a=>a.checked),r=t.features.filter(a=>!a.checked),n={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},i={neon:"Postgres",turso:"SQLite (legacy)"},o={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},s=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${o[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${n[t.authModel]??t.authModel} | Database: ${i[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){s.push("**Included:**");for(let a of e)s.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(s.push(""),s.push(`**Integrations:** ${t.integrations.join(", ")}`)),r.length>0){s.push(""),s.push("**Available to add:**");for(let a of r)s.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return s.join(`
1936
+ `)}function nd(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return Qn(e[1]);let r=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),i=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(o=>o.length>2&&!r.has(o)).slice(0,3);return i.length===0?"my-app":i.join("-")}function Qn(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var td,Ko=_(()=>{"use strict";td=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:t=>t.surfaceType==="internal-tool"||t.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:t=>t.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:t=>t.scheduling===!0,keywords:/\b(schedul|book|reserv|appointment|calendar|slot)\b/i},{name:"Payments / Billing",description:"Charge users, invoices, subscriptions (experimental \u2014 Stripe integration is early-stage)",condition:()=>!1,keywords:/\b(payment|billing|invoice|subscription|checkout|stripe)\b/i},{name:"Admin Panel",description:"Manage users, roles, and content",condition:t=>t.multiRole===!0||t.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:t=>t.primaryActor==="customers"||t.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:t=>t.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:t=>t.integrations?.includes("email")===!0,keywords:/\b(notification|alert|reminder|email.?notif|sms|welcome.?email)\b/i},{name:"Analytics / Reports",description:"Usage stats, trends, data exports",condition:()=>!1,keywords:/\b(analytics|report|chart|trend|insight|metric)\b/i},{name:"File Uploads",description:"Images, documents, attachments",condition:t=>t.integrations?.includes("file-uploads")===!0,keywords:/\b(upload|image|photo|attachment|document|gallery|file)\b/i},{name:"AI Features",description:"Chatbot, content generation, AI assistant",condition:t=>t.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:t=>t.integrations?.includes("maps")===!0,keywords:/\b(map|location|address|geo|places)\b/i},{name:"Voice / TTS",description:"Text-to-speech, voice notes, audio generation",condition:()=>!1,keywords:/\b(voice|tts|text.?to.?speech|audio|speak|narrat|podcast|elevenlabs)\b/i},{name:"SMS / Text Messages",description:"Send SMS notifications, OTP verification",condition:t=>t.integrations?.includes("sms")===!0,keywords:/\b(sms|text.?message|twilio|otp|verification.?code|phone.?verif)\b/i},{name:"Web Scraping",description:"Scrape URLs, crawl websites, extract structured data",condition:()=>!1,keywords:/\b(scrape|crawl|web.?scrap|extract.?from.?url|read.?url|ingest.?web|firecrawl)\b/i},{name:"Chat / Messaging",description:"Real-time messaging between users",condition:()=>!1,keywords:/\b(chat|messag|inbox|conversation|dm)\b/i},{name:"Events / Tournaments",description:"Create and manage events, registrations",condition:()=>!1,keywords:/\b(event|tournament|competition|league|registration)\b/i},{name:"High Scores",description:"Track and display top scores with a leaderboard",condition:t=>t.surfaceType==="game",keywords:/\b(high.?score|leaderboard|top.?score|ranking|scoreboard)\b/i},{name:"Save Progress",description:"Save and resume game state between sessions",condition:t=>t.surfaceType==="game",keywords:/\b(save|progress|resume|checkpoint|continue)\b/i},{name:"Guest Play",description:"Play immediately without signing up, optionally link account later",condition:t=>t.surfaceType==="game",keywords:/\b(guest|anonymous|no.?login|play.?now|instant.?play)\b/i},{name:"Levels / Stages",description:"Progressive difficulty with unlockable stages",condition:()=>!1,keywords:/\b(level|stage|unlock|difficult|progress|world)\b/i},{name:"Achievements",description:"Badges, trophies, and milestones for player accomplishments",condition:()=>!1,keywords:/\b(achieve|badge|trophy|milestone|reward|unlock)\b/i},{name:"Daily Challenge",description:"New puzzle or challenge every day to keep players coming back",condition:()=>!1,keywords:/\b(daily|challenge|streak|word.?of.?the.?day|puzzle.?of)\b/i}]});function cs(t,e,r){let n=gn(t||"your app"),i=e.map((s,a)=>{let l=Xn(s.id||`direction-${a}`),c=gn(s.name||`Direction ${a+1}`),m=gn(s.summary||"");return`<button class="tab${a===0?" active":""}" data-target="${l}" type="button"><span class="tab-name">${c}</span>${m?`<span class="tab-sub">${m}</span>`:""}</button>`}).join(`
1937
+ `),o=e.map((s,a)=>{let l=Xn(s.id||`direction-${a}`),c=r[s.id??""]??"";return`<iframe class="render-frame${a===0?" active":""}" data-id="${l}" srcdoc="${Xn(c)}" sandbox="allow-same-origin allow-scripts" title="${Xn(s.name||`Direction ${a+1}`)}"></iframe>`}).join(`
1938
1938
  `);return`<!doctype html>
1939
1939
  <html lang="en">
1940
1940
  <head>
@@ -2023,7 +2023,7 @@ Recommended: ${s.recommended}`:""}`:s.recommended?`Recommended: ${s.recommended}
2023
2023
  ${o}
2024
2024
  </div>
2025
2025
  <footer class="picker-foot">
2026
- <div><strong>How to pick:</strong> click each tab to compare. When you've chosen, tell your AI assistant the direction name (e.g. &ldquo;pick <em>${e[0]?.name?hn(e[0].name):"Morning Paper"}</em>&rdquo;).</div>
2026
+ <div><strong>How to pick:</strong> click each tab to compare. When you've chosen, tell your AI assistant the direction name (e.g. &ldquo;pick <em>${e[0]?.name?gn(e[0].name):"Morning Paper"}</em>&rdquo;).</div>
2027
2027
  <div><strong>None fit?</strong> Tell your assistant <code>describe your own</code> and give a short description.</div>
2028
2028
  </footer>
2029
2029
  <script>
@@ -2041,38 +2041,38 @@ ${o}
2041
2041
  </script>
2042
2042
  </body>
2043
2043
  </html>
2044
- `}function hn(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Qn(t){return hn(t)}var Ko=P(()=>{"use strict"});import{z as D}from"zod";import{existsSync as Xe,mkdirSync as Pt,readFileSync as gn,readdirSync as ti,statSync as ni,unlinkSync as nd,writeFileSync as pt}from"fs";import{dirname as rd,isAbsolute as sd,join as ye}from"path";import{homedir as ut,hostname as Jo}from"os";import{createHash as od,createHmac as ri,randomBytes as id,randomUUID as Yo,timingSafeEqual as ad}from"crypto";function si(){let t=ye(ut(),".mistflow","confirm-secret");if(Xe(t))try{return Buffer.from(gn(t,"utf-8").trim(),"hex")}catch{}let e=id(32);return Pt(ye(ut(),".mistflow"),{recursive:!0}),pt(t,e.toString("hex"),{mode:384}),e}function oi(t){return od("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function cd(t,e){let r={cwd:t,d:oi(e),exp:Date.now()+ld},n=Buffer.from(JSON.stringify(r)).toString("base64url"),i=ri("sha256",si()).update(n).digest("base64url");return`${n}.${i}`}function dd(t,e,r){let n=t.split(".");if(n.length!==2)return!1;let[i,o]=n,s=ri("sha256",si()).update(i).digest("base64url"),a=Buffer.from(o),l=Buffer.from(s);if(a.length!==l.length||!ad(a,l))return!1;try{let c=JSON.parse(Buffer.from(i,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==e||c.d!==oi(r))}catch{return!1}}function pd(t){let e=t,r=ut(),n=!1;for(let i=0;i<64;i++){if(Xe(ye(e,"mistflow.json")))return"mistflow";if(!n&&Xe(ye(e,"package.json"))&&(n=!0),e===r)break;let o=rd(e);if(o===e)break;e=o}return n?"foreign":"none"}function ud(t){let e=ut(),r=t.replace(/\/+$/,"");if(r===e||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let i of n)if(r===ye(e,i))return!0;return!1}function md(t){let e=new Set(["build","create","make","scaffold","start","using","with","mist","mistflow","a","an","the","for","me","my","new","app","application","website","site","web","tool","dashboard","landing","page","platform","please","can","you","i","want","need"]);return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).map(n=>n.trim()).filter(n=>n.length>1&&!e.has(n)).slice(0,4).join("-").slice(0,48)||"new-app"}function Qo(t){if(!Xe(t))return!0;try{return ni(t).isDirectory()?ti(t).filter(n=>n!==".mistflow").length===0:!1}catch{return!1}}function hd(t,e){let r=md(e),n=ye(t,r);if(Qo(n))return n;for(let i=2;i<=50;i++){let o=ye(t,`${r}-${i}`);if(Qo(o))return o}return ye(t,`${r}-${Date.now()}`)}function gd(t,e){if(e)return!0;let r=t.toLowerCase(),n=/\b(build|create|make|scaffold|start|generate)\b/.test(r),i=/\b(app|application|website|site|web\s+app|landing\s+page|dashboard|tool|marketplace|game|blog|portfolio|crm)\b/.test(r),o=/\b(add|change|fix|update|edit|refactor|debug|review)\b/.test(r)&&!n;return n&&i&&!o}function Xo(t){try{Pt(t,{recursive:!0});return}catch(e){return e instanceof Error?e.message:String(e)}}function Zo(t){let{projectPath:e,description:r,confirmToken:n,suggestedPath:i,previousTokenInvalid:o}=t;return JSON.stringify({status:"confirm_new_project",requires_user_input:!0,projectPath:e,description:r,confirmToken:n,suggestedScaffoldPath:i,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:`Creates a fresh project at \`${i}\` without touching the existing code.`},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json).","MANDATORY: Ask the user the provided askUserQuestion before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token returned above.",`Mistflow will create and remember the new app directory at \`${i}\`. Do not change projectPath to the child directory on the retry; the token is intentionally bound to the original directory.`,"If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",o?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
2045
- `)})}function yd(t){let e=[[/payment/i,"Payments"],[/database/i,"Database"],[/auth|sign.?up|login|access/i,"Access"],[/landing.?page/i,"Landing page"],[/who.*using|user|role/i,"Users"],[/design|theme|style/i,"Design"],[/deploy/i,"Deploy"],[/domain/i,"Domain"],[/notification/i,"Notify"],[/email/i,"Email"],[/mobile|responsive/i,"Mobile"],[/integrat/i,"Integration"],[/field|info|propert|detail|contain/i,"Item shape"],[/view|layout|board|grid|list|timeline/i,"View"],[/scope|how many|one.*or.*many|multi/i,"Scope"],[/share|read.?only|viewer|stakeholder/i,"Sharing"],[/workflow|status|state|move|stage|pipeline/i,"Workflow"],[/avoid|bloat|simple|complex|minimal/i,"Constraints"],[/time.*period|quarter|month|sprint/i,"Time periods"],[/swimlane|column|group|categor/i,"Structure"]];for(let[n,i]of e)if(n.test(t))return i;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(n=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(n.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function bd(t){let e=ye(ut(),".mistflow","plans",`${t}.json`);if(!Xe(e))return null;try{return JSON.parse(gn(e,"utf-8")).plan??null}catch{return null}}async function wd(t){let e=Date.now(),r=5e4,n=2e3;for(;Date.now()-e<r;){try{let i=await On(t.design_conversation_id);if(i.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:i.directions,plan:i.plan,methodology:i.methodology};if(i.status==="failed")return{status:"ready",plan:i.plan,methodology:i.methodology}}catch(i){let o=i instanceof Error?i.message:String(i);if(o.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll failed: ${o}`)}await new Promise(i=>setTimeout(i,n))}return console.error("[plan] directions poll exhausted (50s) \u2014 preserving pending so host re-polls"),t}function vd(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function kd(t,e){for(let r of e){let n=vd(t[r]);if(n)return n}}function xd(t){return kd(t,["mockup_url","mockupUrl","preview_url","previewUrl","live_url","liveUrl","deploy_url","deployUrl","url"])}function ei(t,e){return`Next action: call ${t} with ${JSON.stringify(e)}. Do not omit sessionId.`}function Sd(t){let e=xd(t),r=t.reason?`
2046
- Reason: ${t.reason}`:"";switch(t.state){case"COMPLETE":return`Session complete.${e?` Live URL: ${e}`:""}${r}`;case"CANCELLED":return`Session was cancelled.${r}`;case"FAILED":return`Session ended in FAILED.${e?` Last known URL: ${e}`:""}${r}`;case"ABANDONED":return`Session was abandoned.${r}`;case"EXPIRED":return`Session expired.${r}`;default:return`Session finished with state ${t.state}.${e?` URL: ${e}`:""}${r}`}}async function Td(t,e){let{description:r,projectPath:n,sessionId:i,conversationId:o,answers:s,existingPlan:a,existingPlanId:l,templateToken:c,remixDescription:u,autonomous:h,language:d,brandMentioned:v,confirmToken:W,urlChoice:_,designConversationId:k,designDirection:y,userConfirmedCustom:A,forceNew:z}=t;if(i&&!o&&!k)try{let m=await Dt(i),g=[`Session ID: ${m.session_id}`,`Status: ${m.status??"active"}`,`Instruction: ${m.instruction}`];switch(m.reason&&g.push(`Reason: ${m.reason}`),m.instruction){case"wait":return p([...g,`Next action: ${m.reason??"The backend is still preparing the next step."} Tell the user briefly what's happening, then call mist_plan with { projectPath, sessionId: "${m.session_id}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`].join(`
2047
- `));case"resume_conversation":{let w=m.conversation_id;return p([...g,`In-flight conversation: ${w??"(missing \u2014 backend bug)"}`,`Next action: call mist_plan with { projectPath, conversationId: "${w??""}" } to continue the plan flow. The conversation poll renders questions / design directions in the same way it would have on the original mist_plan response.`].join(`
2048
- `))}case"continue":return p([...g,`Next action: ${m.reason??"Continue from where you left off \u2014 read mistflow.json to find the next pending step, then call mist_install / mist_implement / mist_build / mist_deploy as appropriate."}`].join(`
2049
- `));case"call_mist_init":return p([...g,ei("mist_init",{sessionId:m.session_id,path:n})].join(`
2050
- `));case"call_mist_deploy":return p([...g,ei("mist_deploy",{sessionId:m.session_id,projectPath:n})].join(`
2051
- `));case"review_plan":return p([...g,`Next action: ${m.reason??"User asked to review PLAN.md before scaffolding. Open <projectPath>/PLAN.md, let the user read / edit, then call mist_session({ resume }) and re-run mist_init."}`].join(`
2052
- `));case"done":return p([...g,Sd(m)].join(`
2053
- `))}}catch(m){let g=m instanceof Error?m.message:String(m);return p(`Could not poll session '${i}': ${g}`,!0)}if(o&&!r&&!s&&!k&&!y&&!a&&!l&&!c)try{let m=await Mn(o);if(m.status==="clarify_pending"||m.status==="plan_pending"){let g=typeof m.phase_hint=="string"?m.phase_hint:null,w=typeof m.elapsed_seconds=="number"?m.elapsed_seconds:null,T=typeof m.progress=="number"?m.progress:null,O=m.status==="plan_pending",F=O?"generating_plan":"generating_questions",oe=g?`${g}${w!==null?` (${w}s elapsed)`:""}`:O?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return p(JSON.stringify({status:"running",conversationId:o,phase:F,...g?{phaseHint:g}:{},...w!==null?{elapsedSeconds:w}:{},...T!==null?{progress:T}:{},nextAction:`${oe}. Tell the user briefly what's happening (e.g. "${g??(O?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}if(m.status==="design_clarify"&&Array.isArray(m.directions)){let w=m.directions.map((C,xe)=>({id:C.id??String(xe),name:C.name??`Direction ${xe+1}`,summary:C.summary,hero_headline:C.hero_headline,cta_text:C.cta_text,body_sample:C.body_sample,fonts:C.fonts,colors:C.colors,hero_treatment:C.hero_treatment,shape_lang:C.shape_lang,texture:C.texture,decoration_hint:C.decoration_hint})),T=m.plan?.name??"your app",O=m.design_conversation_id,F={},oe=!1;try{if(O){let f=Date.now();for(;Date.now()-f<5e4;){let E=await Dn(O),S=0;for(let de of w){let me=E[de.id];me&&((me.status==="done"||me.status==="ready")&&typeof me.html=="string"&&me.html.length>0?(F[de.id]=me.html,S+=1):me.status==="failed"&&(S+=1))}if(S===w.length){oe=!0;break}await new Promise(de=>setTimeout(de,5e3))}}}catch(C){console.error(`[mist_plan:design_clarify] render poll failed: ${C instanceof Error?C.message:String(C)}`)}if(!oe)return p(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:o,design_conversation_id:O,renderedSoFar:Object.keys(F).length,totalDirections:w.length,nextAction:`${Object.keys(F).length}/${w.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${o}" } again IMMEDIATELY \u2014 do NOT bash sleep. The render-poll holds the connection up to ~50s; each call returns as soon as state changes. Do NOT ask the user about design yet; the picker isn't ready.`}));let le=w.filter(C=>F[C.id]),ie,L,J=ye(n,".mistflow"),ve=ye(J,"design-directions.html"),re=ye(J,"picker-state.json"),ce=!1;if(O)try{Xe(re)&&JSON.parse(gn(re,"utf-8")).opened_for_design_cid===O&&(ce=!0)}catch{}try{if(Pt(J,{recursive:!0}),ce)ie=ve;else{let C=ls(T,le,F);pt(ve,C,"utf-8"),ie=ve;let xe=as(`file://${ve}`);xe.opened||(L=xe.reason),O&&pt(re,JSON.stringify({opened_for_design_cid:O,opened_at:new Date().toISOString()},null,2),"utf-8")}}catch(C){console.error(`[mist_plan:design_clarify] picker write/open failed: ${C instanceof Error?C.message:String(C)}`)}let Te=le.map(C=>({id:C.id,name:C.name})),ue=Te.map(C=>C.name).filter(Boolean);return p(JSON.stringify({status:"design_clarify",previewPath:ie,previewOpenError:L,directionRefs:Te,directionNames:ue,design_conversation_id:O,conversation_id:o,nextAction:[`The visual picker has been opened in the user's browser at file://${ie??"(path missing)"} \u2014 every direction is a real, rendered landing page. The user is looking at it now.`,L?`(auto-open suppressed: ${L} \u2014 tell the user to open file://${ie} manually)`:"",`Now use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names as options: ${ue.map(C=>`"${C}"`).join(", ")}. Do NOT invent extra options. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${o}", designConversationId: "${O}", designDirection: { id: "<map name \u2192 id from directionRefs>" } }. If the user types a custom description, pass designDirection: { custom: "<their exact words>" } and userConfirmedCustom: true.`].filter(Boolean).join(`
2054
-
2055
- `)}))}return p(JSON.stringify(m))}catch(m){let g=m instanceof Error?m.message:String(m);return p(`Could not poll plan conversation '${o}': ${g}`,!0)}let H=r??"";if(!H.trim()&&!o&&!k&&!a&&!l&&!c)return p("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(k&&!y&&!H.trim()&&!s)return p(`You passed designConversationId='${k}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${k}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let ne=a;if(!ne&&l&&(ne=bd(l)??void 0,!ne))return p("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let ee=o;if(!Se())return Ee("plan a new app");let Q,q;if(!ee&&!ne&&!c&&!k){if(!sd(n))return p(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let m=pd(n);if(m!=="mistflow"&&ud(n))return p(JSON.stringify({status:"unsafe_cwd",projectPath:n,instruction:[`The projectPath you passed (${n}) is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Create the subfolder at ${n}/<subfolder-name>.`," 3. Call mist_plan again with the SAME description and projectPath set to the new subfolder.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description."].join(`
2056
- `)}),!0);if(m==="foreign"){let g=W?dd(W,n,H):!1,w=hd(n,H),T=gd(H,v);if(T||g){q=w;let O=Xo(q);if(O)return p(`Mistflow could not create the scaffold directory at ${q}: ${O}`,!0);Q=`Note: Mistflow will scaffold the new app at \`${q}\`. The existing project at \`${n}\` is not modified.`}if(!g&&!T){let O=cd(n,H);if(e?.server){let F=await mn(e.server,[{question:"You're inside an existing project. Where should Mistflow scaffold the new app?",decisionKey:"scopeChoice",recommended:`Create at: ${w}`,why:"Mistflow creates a NEW app and never modifies the surrounding codebase. The default puts it in a subdirectory of the current path, named after your description. You can pick a custom path or cancel if you actually want to edit the existing project instead.",options:[{label:`Create at: ${w}`,description:"Default \u2014 uses your description as the folder name."},{label:"Choose a different path",description:"Type a custom absolute path in the textbox below."},{label:"Cancel \u2014 I wanted to edit the existing project",description:"Stop Mistflow. Handle the request by editing files in the current project instead."}]}],`## Existing project detected
2044
+ `}function gn(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Xn(t){return gn(t)}var Jo=_(()=>{"use strict"});import{z as M}from"zod";import{existsSync as Ze,mkdirSync as Ct,readFileSync as fn,readdirSync as ni,statSync as ri,unlinkSync as rd,writeFileSync as mt}from"fs";import{dirname as sd,isAbsolute as od,join as he}from"path";import{homedir as ht,hostname as Yo}from"os";import{createHash as id,createHmac as si,randomBytes as ad,randomUUID as Qo,timingSafeEqual as ld}from"crypto";function oi(){let t=he(ht(),".mistflow","confirm-secret");if(Ze(t))try{return Buffer.from(fn(t,"utf-8").trim(),"hex")}catch{}let e=ad(32);return Ct(he(ht(),".mistflow"),{recursive:!0}),mt(t,e.toString("hex"),{mode:384}),e}function ii(t){return id("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function dd(t,e){let r={cwd:t,d:ii(e),exp:Date.now()+cd},n=Buffer.from(JSON.stringify(r)).toString("base64url"),i=si("sha256",oi()).update(n).digest("base64url");return`${n}.${i}`}function pd(t,e,r){let n=t.split(".");if(n.length!==2)return!1;let[i,o]=n,s=si("sha256",oi()).update(i).digest("base64url"),a=Buffer.from(o),l=Buffer.from(s);if(a.length!==l.length||!ld(a,l))return!1;try{let c=JSON.parse(Buffer.from(i,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==e||c.d!==ii(r))}catch{return!1}}function ud(t){let e=t,r=ht(),n=!1;for(let i=0;i<64;i++){if(Ze(he(e,"mistflow.json")))return"mistflow";if(!n&&Ze(he(e,"package.json"))&&(n=!0),e===r)break;let o=sd(e);if(o===e)break;e=o}return n?"foreign":"none"}function md(t){let e=ht(),r=t.replace(/\/+$/,"");if(r===e||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let i of n)if(r===he(e,i))return!0;return!1}function hd(t){let e=new Set(["build","create","make","scaffold","start","using","with","mist","mistflow","a","an","the","for","me","my","new","app","application","website","site","web","tool","dashboard","landing","page","platform","please","can","you","i","want","need"]);return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).map(n=>n.trim()).filter(n=>n.length>1&&!e.has(n)).slice(0,4).join("-").slice(0,48)||"new-app"}function Xo(t){if(!Ze(t))return!0;try{return ri(t).isDirectory()?ni(t).filter(n=>n!==".mistflow").length===0:!1}catch{return!1}}function gd(t,e){let r=hd(e),n=he(t,r);if(Xo(n))return n;for(let i=2;i<=50;i++){let o=he(t,`${r}-${i}`);if(Xo(o))return o}return he(t,`${r}-${Date.now()}`)}function fd(t,e){if(e)return!0;let r=t.toLowerCase(),n=/\b(build|create|make|scaffold|start|generate)\b/.test(r),i=/\b(app|application|website|site|web\s+app|landing\s+page|dashboard|tool|marketplace|game|blog|portfolio|crm)\b/.test(r),o=/\b(add|change|fix|update|edit|refactor|debug|review)\b/.test(r)&&!n;return n&&i&&!o}function Zo(t){try{Ct(t,{recursive:!0});return}catch(e){return e instanceof Error?e.message:String(e)}}function ei(t){let{projectPath:e,description:r,confirmToken:n,suggestedPath:i,previousTokenInvalid:o}=t;return JSON.stringify({status:"confirm_new_project",requires_user_input:!0,projectPath:e,description:r,confirmToken:n,suggestedScaffoldPath:i,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:`Creates a fresh project at \`${i}\` without touching the existing code.`},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json).","MANDATORY: Ask the user the provided askUserQuestion before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token returned above.",`Mistflow will create and remember the new app directory at \`${i}\`. Do not change projectPath to the child directory on the retry; the token is intentionally bound to the original directory.`,"If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",o?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
2045
+ `)})}function bd(t){let e=[[/payment/i,"Payments"],[/database/i,"Database"],[/auth|sign.?up|login|access/i,"Access"],[/landing.?page/i,"Landing page"],[/who.*using|user|role/i,"Users"],[/design|theme|style/i,"Design"],[/deploy/i,"Deploy"],[/domain/i,"Domain"],[/notification/i,"Notify"],[/email/i,"Email"],[/mobile|responsive/i,"Mobile"],[/integrat/i,"Integration"],[/field|info|propert|detail|contain/i,"Item shape"],[/view|layout|board|grid|list|timeline/i,"View"],[/scope|how many|one.*or.*many|multi/i,"Scope"],[/share|read.?only|viewer|stakeholder/i,"Sharing"],[/workflow|status|state|move|stage|pipeline/i,"Workflow"],[/avoid|bloat|simple|complex|minimal/i,"Constraints"],[/time.*period|quarter|month|sprint/i,"Time periods"],[/swimlane|column|group|categor/i,"Structure"]];for(let[n,i]of e)if(n.test(t))return i;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(n=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(n.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function wd(t){let e=he(ht(),".mistflow","plans",`${t}.json`);if(!Ze(e))return null;try{return JSON.parse(fn(e,"utf-8")).plan??null}catch{return null}}async function vd(t){let e=Date.now(),r=5e4,n=2e3;for(;Date.now()-e<r;){try{let i=await Dn(t.design_conversation_id);if(i.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:i.directions,plan:i.plan,methodology:i.methodology};if(i.status==="failed")return{status:"ready",plan:i.plan,methodology:i.methodology}}catch(i){let o=i instanceof Error?i.message:String(i);if(o.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll failed: ${o}`)}await new Promise(i=>setTimeout(i,n))}return console.error("[plan] directions poll exhausted (50s) \u2014 preserving pending so host re-polls"),t}function kd(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function xd(t,e){for(let r of e){let n=kd(t[r]);if(n)return n}}function Sd(t){return xd(t,["mockup_url","mockupUrl","preview_url","previewUrl","live_url","liveUrl","deploy_url","deployUrl","url"])}function ti(t,e){return`Next action: call ${t} with ${JSON.stringify(e)}. Do not omit sessionId.`}function Td(t){let e=Sd(t),r=t.reason?`
2046
+ Reason: ${t.reason}`:"";switch(t.state){case"COMPLETE":return`Session complete.${e?` Live URL: ${e}`:""}${r}`;case"CANCELLED":return`Session was cancelled.${r}`;case"FAILED":return`Session ended in FAILED.${e?` Last known URL: ${e}`:""}${r}`;case"ABANDONED":return`Session was abandoned.${r}`;case"EXPIRED":return`Session expired.${r}`;default:return`Session finished with state ${t.state}.${e?` URL: ${e}`:""}${r}`}}async function _d(t,e){let{description:r,projectPath:n,sessionId:i,conversationId:o,answers:s,existingPlan:a,existingPlanId:l,templateToken:c,remixDescription:m,autonomous:p,language:u,brandMentioned:g,confirmToken:j,urlChoice:I,designConversationId:S,designDirection:y,userConfirmedCustom:R,forceNew:z}=t;if(i&&!o&&!S)try{let h=await Mt(i),f=[`Session ID: ${h.session_id}`,`Status: ${h.status??"active"}`,`Instruction: ${h.instruction}`];switch(h.reason&&f.push(`Reason: ${h.reason}`),h.instruction){case"wait":return d([...f,`Next action: ${h.reason??"The backend is still preparing the next step."} Tell the user briefly what's happening, then call mist_plan with { projectPath, sessionId: "${h.session_id}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`].join(`
2047
+ `));case"resume_conversation":{let k=h.conversation_id;return d([...f,`In-flight conversation: ${k??"(missing \u2014 backend bug)"}`,`Next action: call mist_plan with { projectPath, conversationId: "${k??""}" } to continue the plan flow. The conversation poll renders questions / design directions in the same way it would have on the original mist_plan response.`].join(`
2048
+ `))}case"continue":return d([...f,`Next action: ${h.reason??"Continue from where you left off \u2014 read mistflow.json to find the next pending step, then call mist_install / mist_implement / mist_build / mist_deploy as appropriate."}`].join(`
2049
+ `));case"call_mist_init":return d([...f,ti("mist_init",{sessionId:h.session_id,path:n})].join(`
2050
+ `));case"call_mist_deploy":return d([...f,ti("mist_deploy",{sessionId:h.session_id,projectPath:n})].join(`
2051
+ `));case"review_plan":return d([...f,`Next action: ${h.reason??"User asked to review PLAN.md before scaffolding. Open <projectPath>/PLAN.md, let the user read / edit, then call mist_session({ resume }) and re-run mist_init."}`].join(`
2052
+ `));case"done":return d([...f,Td(h)].join(`
2053
+ `))}}catch(h){let f=h instanceof Error?h.message:String(h);return d(`Could not poll session '${i}': ${f}`,!0)}if(o&&!r&&!s&&!S&&!y&&!a&&!l&&!c)try{let h=await Ln(o);if(h.status==="clarify_pending"||h.status==="plan_pending"){let f=typeof h.phase_hint=="string"?h.phase_hint:null,k=typeof h.elapsed_seconds=="number"?h.elapsed_seconds:null,T=typeof h.progress=="number"?h.progress:null,N=h.status==="plan_pending",B=N?"generating_plan":"generating_questions",ne=f?`${f}${k!==null?` (${k}s elapsed)`:""}`:N?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return d(JSON.stringify({status:"running",conversationId:o,phase:B,...f?{phaseHint:f}:{},...k!==null?{elapsedSeconds:k}:{},...T!==null?{progress:T}:{},nextAction:`${ne}. Tell the user briefly what's happening (e.g. "${f??(N?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}if(h.status==="design_clarify"&&Array.isArray(h.directions)){let k=h.directions.map((A,Te)=>({id:A.id??String(Te),name:A.name??`Direction ${Te+1}`,summary:A.summary,hero_headline:A.hero_headline,cta_text:A.cta_text,body_sample:A.body_sample,fonts:A.fonts,colors:A.colors,hero_treatment:A.hero_treatment,shape_lang:A.shape_lang,texture:A.texture,decoration_hint:A.decoration_hint})),T=h.plan?.name??"your app",N=h.design_conversation_id,B={},ne=!1;try{if(N){let ye=Date.now();for(;Date.now()-ye<5e4;){let b=await Mn(N),w=0;for(let $ of k){let ee=b[$.id];ee&&((ee.status==="done"||ee.status==="ready")&&typeof ee.html=="string"&&ee.html.length>0?(B[$.id]=ee.html,w+=1):ee.status==="failed"&&(w+=1))}if(w===k.length){ne=!0;break}await new Promise($=>setTimeout($,5e3))}}}catch(A){console.error(`[mist_plan:design_clarify] render poll failed: ${A instanceof Error?A.message:String(A)}`)}if(!ne)return d(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:o,design_conversation_id:N,renderedSoFar:Object.keys(B).length,totalDirections:k.length,nextAction:`${Object.keys(B).length}/${k.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${o}" } again IMMEDIATELY \u2014 do NOT bash sleep. The render-poll holds the connection up to ~50s; each call returns as soon as state changes. Do NOT ask the user about design yet; the picker isn't ready.`}));let se=k.filter(A=>B[A.id]),me,D,G=he(n,".mistflow"),ve=he(G,"design-directions.html"),re=he(G,"picker-state.json"),fe=!1;if(N)try{Ze(re)&&JSON.parse(fn(re,"utf-8")).opened_for_design_cid===N&&(fe=!0)}catch{}try{if(Ct(G,{recursive:!0}),fe)me=ve;else{let A=cs(T,se,B);mt(ve,A,"utf-8"),me=ve;let Te=ls(`file://${ve}`);Te.opened||(D=Te.reason),N&&mt(re,JSON.stringify({opened_for_design_cid:N,opened_at:new Date().toISOString()},null,2),"utf-8")}}catch(A){console.error(`[mist_plan:design_clarify] picker write/open failed: ${A instanceof Error?A.message:String(A)}`)}let ce=se.map(A=>({id:A.id,name:A.name})),ue=ce.map(A=>A.name).filter(Boolean);return d(JSON.stringify({status:"design_clarify",previewPath:me,previewOpenError:D,directionRefs:ce,directionNames:ue,design_conversation_id:N,conversation_id:o,nextAction:[`The visual picker has been opened in the user's browser at file://${me??"(path missing)"} \u2014 every direction is a real, rendered landing page. The user is looking at it now.`,D?`(auto-open suppressed: ${D} \u2014 tell the user to open file://${me} manually)`:"",`Now use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names as options: ${ue.map(A=>`"${A}"`).join(", ")}. Do NOT invent extra options. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${o}", designConversationId: "${N}", designDirection: { id: "<map name \u2192 id from directionRefs>" } }. If the user types a custom description, pass designDirection: { custom: "<their exact words>" } and userConfirmedCustom: true.`].filter(Boolean).join(`
2054
+
2055
+ `)}))}return d(JSON.stringify(h))}catch(h){let f=h instanceof Error?h.message:String(h);return d(`Could not poll plan conversation '${o}': ${f}`,!0)}let W=r??"";if(!W.trim()&&!o&&!S&&!a&&!l&&!c)return d("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(S&&!y&&!W.trim()&&!s)return d(`You passed designConversationId='${S}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${S}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let te=a;if(!te&&l&&(te=wd(l)??void 0,!te))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let pe=o;if(!xe())return Oe("plan a new app");let L,H;if(!pe&&!te&&!c&&!S){if(!od(n))return d(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let h=ud(n);if(h!=="mistflow"&&md(n))return d(JSON.stringify({status:"unsafe_cwd",projectPath:n,instruction:[`The projectPath you passed (${n}) is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Create the subfolder at ${n}/<subfolder-name>.`," 3. Call mist_plan again with the SAME description and projectPath set to the new subfolder.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description."].join(`
2056
+ `)}),!0);if(h==="foreign"){let f=j?pd(j,n,W):!1,k=gd(n,W),T=fd(W,g);if(T||f){H=k;let N=Zo(H);if(N)return d(`Mistflow could not create the scaffold directory at ${H}: ${N}`,!0);L=`Note: Mistflow will scaffold the new app at \`${H}\`. The existing project at \`${n}\` is not modified.`}if(!f&&!T){let N=dd(n,W);if(e?.server){let B=await hn(e.server,[{question:"You're inside an existing project. Where should Mistflow scaffold the new app?",decisionKey:"scopeChoice",recommended:`Create at: ${k}`,why:"Mistflow creates a NEW app and never modifies the surrounding codebase. The default puts it in a subdirectory of the current path, named after your description. You can pick a custom path or cancel if you actually want to edit the existing project instead.",options:[{label:`Create at: ${k}`,description:"Default \u2014 uses your description as the folder name."},{label:"Choose a different path",description:"Type a custom absolute path in the textbox below."},{label:"Cancel \u2014 I wanted to edit the existing project",description:"Stop Mistflow. Handle the request by editing files in the current project instead."}]}],`## Existing project detected
2057
2057
 
2058
2058
  You're inside \`${n}\` which has a \`package.json\`. Mistflow will create a NEW app in a subdirectory \u2014 it won't modify the existing code.
2059
2059
 
2060
- Default path: \`${w}\``,"scope");if(F.outcome==="submitted"){let oe=F.answers?.[0]?.answer??"",le=oe.toLowerCase(),ie=oe.startsWith("/")?oe:null;if(ie||le.startsWith("create at:")||le.startsWith("choose a different path")){let L=ie||(le.startsWith("choose a different path")?null:w);if(!L)return p("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);q=L;let J=Xo(q);if(J)return p(`Mistflow could not create the scaffold directory at ${q}: ${J}`,!0);Q=`Note: Mistflow will scaffold the new app at \`${q}\`. The existing project at \`${n}\` is not modified.`}else return le.startsWith("cancel")?p("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(`User submitted an unrecognized scope choice: ${oe}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return F.outcome==="declined"?p("User declined the scope confirmation. They wanted to edit the existing project, not create a new Mistflow app. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(Zo({projectPath:n,description:H,confirmToken:O,suggestedPath:w,previousTokenInvalid:!!W}))}else return p(Zo({projectPath:n,description:H,confirmToken:O,suggestedPath:w,previousTokenInvalid:!!W}))}}}if(c)try{if(!(await Hr(c)).plan)return p("This template has no plan to fork. Try a different template.",!0);let g=await Wr(c),w=g.plan,T="";if(u&&g.has_source)try{let J=await Un(g.plan,u),ve=J.plan??J,re=J.diff,ce=ve?.steps??[],Te=new Set([...(re?.added??[]).map(f=>f.number),...(re?.modified??[]).map(f=>f.number)]),ue=ce.map(f=>{let E=f.number;return Te.has(E)?{...f,status:"pending"}:{...f,status:"completed",source:"forked"}});ve.steps=ue,w=ve;let C=ue.filter(f=>f.status==="pending").length;T=` Remixed: ${ue.filter(f=>f.status==="completed").length} steps unchanged, ${C} steps need re-implementation.`}catch(J){console.error("[plan] Remix failed, using original plan:",J),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let O=Yo(),F=ye(ut(),".mistflow","plans");Pt(F,{recursive:!0}),pt(ye(F,`${O}.json`),JSON.stringify({plan:w,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let oe=w?.name??"forked-app",le=g.has_source,ie=le?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",L=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return p(JSON.stringify({planId:O,forkedFrom:g.forked_from,projectId:g.id,hasSource:le,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${T}${L} ${ie} NEXT: Call mist_init, name='${oe}', and planId='${O}' to create the project now.`}))}catch(m){let g=m instanceof Error?m.message:"Failed to fork template";return p(g,!0)}if(ne){let m;if(n){let L=ye(n,"PLAN.md");if(Xe(L))try{m=gn(L,"utf-8")}catch(J){console.error(`[mist_plan:modify] PLAN.md read failed (${L}): ${J instanceof Error?J.message:String(J)}`)}}let g;try{g=await Un(ne,H,{planMd:m})}catch(L){let J=L instanceof Error?L.message:"Failed to modify plan";return p(J,!0)}let w=g.plan,T=g.diff,O=typeof g.plan_md=="string"?g.plan_md:null,F,oe;if(O&&n)try{let L=ye(n,"PLAN.md");pt(L,O,"utf-8"),F=L}catch(L){oe=L instanceof Error?L.message:String(L)}let le=[];if(T?.added?.length){let L=T.added.map(J=>J.title);le.push(`Added ${L.length} step(s): ${L.join(", ")}`)}if(T?.removed?.length){let L=T.removed.map(J=>J.title);le.push(`Removed ${L.length} step(s): ${L.join(", ")}`)}if(T?.modified?.length){let L=T.modified.map(J=>J.title);le.push(`Modified ${L.length} step(s): ${L.join(", ")}`)}let ie=le.length>0?le.join(". "):"No changes detected.";return p(JSON.stringify({plan:w,diff:T,planMdPath:F,planMdError:oe,message:`Plan modified. ${ie}. Update mistflow.json with the new plan${F?"; PLAN.md has been regenerated at "+F:""}, then continue with mist_implement.`}))}let I=_?.trim()||void 0,se=s;if(Array.isArray(s)){let m=s.findIndex(g=>g&&typeof g=="object"&&g.decisionKey==="urlChoice");if(m>=0){let g=s[m];!I&&g.answer&&(I=g.answer);let w=s.slice(0,m).concat(s.slice(m+1));se=w.length>0?w:void 0}}else if(s!=null){let m=s;if(!I&&Xn in m&&(I=m[Xn]),!I&&"urlChoice"in m&&(I=m.urlChoice),Xn in m||"urlChoice"in m){let{[Xn]:g,urlChoice:w,...T}=m;se=Object.keys(T).length>0?T:void 0}}if(I&&(I=I.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),I){let m=I.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(m)?I=m:(console.error(`[mist_plan] Discarding urlChoice '${I}' \u2014 does not look like a subdomain. Backend will auto-generate.`),I=void 0)}let B;if(y){B={...y},delete B.userConfirmedCustom,delete B.user_confirmed_custom;let m={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[g,w]of Object.entries(m))y[g]!==void 0&&B[w]===void 0&&(B[w]=y[g])}let b=B!==void 0&&typeof B.custom=="string"&&!B.id&&!B.name,$=A===!0||y!==void 0&&(y.userConfirmedCustom===!0||y.user_confirmed_custom===!0);if(b&&k)try{let m=await On(k);if(m.status==="pending")return p(`Refusing to submit a custom design direction: the backend's direction-generation BG task is still running (status: pending). The user has not yet had the chance to see the real directions. Stop asking the user about aesthetic / fonts / colors / mood right now \u2014 the backend will produce 3-4 concrete options shortly. Re-call mist_plan with { projectPath, conversationId, designConversationId: '${k}' } to keep polling. When directions are ready (status: 'design_clarify'), surface them to the user via AskUserQuestion. Custom is only legitimate AFTER the user has seen the real options and explicitly rejected them \u2014 never as a workaround for a slow generation run.`,!0);if(m.status==="ready"&&Array.isArray(m.directions)&&m.directions.length>0&&!$){let g=m.directions.map(w=>w.name).join(", ");return p(`Refusing to submit a custom design direction: the backend has ${m.directions.length} real directions ready (${g}). The picker is mandatory \u2014 you must surface those exact directions to the user via AskUserQuestion before submitting any pick. Re-call mist_plan with { conversationId, designConversationId: '${k}' } to get the picker payload (status: 'design_clarify'), render the directions HTML preview at .mistflow/design-directions.html for the user, then submit the user's choice. If the user opens the preview, sees the ${m.directions.length} directions, rejects all of them, and types their own description, ONLY THEN retry this call with userConfirmedCustom: true. Never set userConfirmedCustom: true without first showing the user the real directions.`,!0)}}catch(m){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${m instanceof Error?m.message:String(m)}`)}let V=s?"Generating plan with your answers (LLM call)":k?"Finalizing design direction":"Thinking through discovery questions",M=e?qe(e.server,e.progressToken,()=>V):{stop:()=>{}};if(e&&(e.cleanup=()=>M.stop()),!i&&!o&&!k&&!a&&!l&&!c&&!W&&H.trim().length>0&&!z)try{let m=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),g=336*60*60*1e3,w=Date.now()-g,O=(await an(Jo())).filter(F=>!m.has(F.state)).filter(F=>{let oe=Date.parse(F.updated_at);return Number.isFinite(oe)&&oe>=w}).sort((F,oe)=>Date.parse(oe.updated_at)-Date.parse(F.updated_at)).slice(0,5);if(O.length>0)return M.stop(),p(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:O.map(F=>({sessionId:F.id,state:F.state,description:F.description,currentStep:F.current_step,awaitingInput:F.awaiting_input,updatedAt:F.updated_at})),instruction:"This machine has unfinished Mistflow build(s) in flight. Before starting a new project, ask the user whether they want to resume one of these or start fresh. Show the description, state, and updatedAt for each candidate so they can pick.",nextAction:"Step 1: Show the candidates to the user via your host's question UI (AskUserQuestion in Claude Code, request_user_input in Codex Plan mode, quick pick in Cursor). Step 2a (resume): if they pick a candidate, call mist_session({ action: 'resume', sessionId: '<picked>', projectPath }) and follow the next instruction it returns. Step 2b (start fresh): if they want a new build, call mist_plan again with the SAME description and projectPath, plus forceNew: true. The forceNew flag suppresses this check so the new session can be minted."}))}catch(m){console.error("resume-offer check failed (falling through to bootstrap):",m instanceof Error?m.message:m)}let te=i,R;try{ee&&!se&&!k&&!ne&&!l?R=await Mn(ee):R=await Ln(H,{conversationId:ee,answers:se,autonomous:h,language:d,designConversationId:k,designDirection:B})}catch(m){M.stop();let g=m instanceof Error?m.message:"Failed to generate plan";return p(g,!0)}let ge=R.session_id;if(!te&&ge){te=ge;try{await on(ge,{machine_id:Jo(),local_path:n})}catch(m){console.error("workspace bind failed (resume offers will miss this session):",m instanceof Error?m.message:m)}}if(R.status==="clarify_pending"){M.stop();let m=R;return p(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:te,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.${te?` Carry sessionId="${te}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(R.status==="plan_pending"){M.stop();let m=R;return p(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:te,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(R.status==="design_clarify_pending"&&(V="Generating creative design directions",R=await wd(R)),R.status==="design_clarify_pending")return M.stop(),p(JSON.stringify({status:"running",conversationId:o,designConversationId:R.design_conversation_id,sessionId:te,phase:"generating_design_directions",nextAction:`Creative design directions are still generating (45-60s typical, can stretch on slow runs). Call mist_plan with { projectPath, conversationId: "${o??""}" } IMMEDIATELY to keep polling \u2014 do NOT run bash sleep, do NOT submit a designDirection of your own, do NOT mark the plan as ready, and DO NOT ASK THE USER about aesthetic / fonts / colors / mood / vibe / style while you wait. The backend is generating 3-4 concrete direction options the user will pick from \u2014 asking the user to invent one defeats the entire feature, and the server will reject any { custom } submission while directions are still pending. Just poll. The picker is mandatory; keep polling until status becomes 'design_clarify' with the directions array, then surface those exact directions to the user via AskUserQuestion.`}));if(M.stop(),R.status==="clarify"){let m=R.reflection||"",g=R.suggestedName||"",w=R.suggestedFeatures??[],T=R.questions??[],O=T.some(re=>Array.isArray(re.options)&&typeof re.options[0]=="object"&&re.options[0]?.label),F={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},oe=T.map(re=>{let ce=re.decisionKey&&F[re.decisionKey]||yd(re.question),Te;return O&&Array.isArray(re.options)?Te=re.options.map(ue=>({label:ue.label,description:ue.description??""})):Array.isArray(re.options)?Te=re.options.map((ue,C)=>({label:C===0?`${ue} (Recommended)`:String(ue),description:re.why??""})):Te=[{label:"Yes (Recommended)",description:re.why??""},{label:"No",description:""}],{question:re.question,header:ce,options:Te,multiSelect:!1}}),ie=R.decisions?.audienceType??null,L=w.length>0?Wo(H,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:ie,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:w,language:d}):null,J=L?Go(L):"",ve=Yn(g||"my-app").slice(0,32);try{let re=await Nn(ve);!re.available&&re.suggestion&&(ve=re.suggestion)}catch{}if(J&&(J+=`
2060
+ Default path: \`${k}\``,"scope");if(B.outcome==="submitted"){let ne=B.answers?.[0]?.answer??"",se=ne.toLowerCase(),me=ne.startsWith("/")?ne:null;if(me||se.startsWith("create at:")||se.startsWith("choose a different path")){let D=me||(se.startsWith("choose a different path")?null:k);if(!D)return d("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);H=D;let G=Zo(H);if(G)return d(`Mistflow could not create the scaffold directory at ${H}: ${G}`,!0);L=`Note: Mistflow will scaffold the new app at \`${H}\`. The existing project at \`${n}\` is not modified.`}else return se.startsWith("cancel")?d("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):d(`User submitted an unrecognized scope choice: ${ne}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return B.outcome==="declined"?d("User declined the scope confirmation. They wanted to edit the existing project, not create a new Mistflow app. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):d(ei({projectPath:n,description:W,confirmToken:N,suggestedPath:k,previousTokenInvalid:!!j}))}else return d(ei({projectPath:n,description:W,confirmToken:N,suggestedPath:k,previousTokenInvalid:!!j}))}}}if(c)try{if(!(await Wr(c)).plan)return d("This template has no plan to fork. Try a different template.",!0);let f=await Gr(c),k=f.plan,T="";if(m&&f.has_source)try{let G=await $n(f.plan,m),ve=G.plan??G,re=G.diff,fe=ve?.steps??[],ce=new Set([...(re?.added??[]).map(ye=>ye.number),...(re?.modified??[]).map(ye=>ye.number)]),ue=fe.map(ye=>{let b=ye.number;return ce.has(b)?{...ye,status:"pending"}:{...ye,status:"completed",source:"forked"}});ve.steps=ue,k=ve;let A=ue.filter(ye=>ye.status==="pending").length;T=` Remixed: ${ue.filter(ye=>ye.status==="completed").length} steps unchanged, ${A} steps need re-implementation.`}catch(G){console.error("[plan] Remix failed, using original plan:",G),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let N=Qo(),B=he(ht(),".mistflow","plans");Ct(B,{recursive:!0}),mt(he(B,`${N}.json`),JSON.stringify({plan:k,projectId:f.id,sourceDeploymentId:f.source_deployment_id,forkToken:f.fork_token,requiredEnvVars:f.required_env_vars,dbProvider:f.db_provider}));let ne=k?.name??"forked-app",se=f.has_source,me=se?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",D=f.deploy_url?` Instant deploy started \u2014 your app will be live at ${f.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:N,forkedFrom:f.forked_from,projectId:f.id,hasSource:se,deployUrl:f.deploy_url,message:`Forked "${f.forked_from}" into your workspace.${T}${D} ${me} NEXT: Call mist_init, name='${ne}', and planId='${N}' to create the project now.`}))}catch(h){let f=h instanceof Error?h.message:"Failed to fork template";return d(f,!0)}if(te){let h;if(n){let D=he(n,"PLAN.md");if(Ze(D))try{h=fn(D,"utf-8")}catch(G){console.error(`[mist_plan:modify] PLAN.md read failed (${D}): ${G instanceof Error?G.message:String(G)}`)}}let f;try{f=await $n(te,W,{planMd:h})}catch(D){let G=D instanceof Error?D.message:"Failed to modify plan";return d(G,!0)}let k=f.plan,T=f.diff,N=typeof f.plan_md=="string"?f.plan_md:null,B,ne;if(N&&n)try{let D=he(n,"PLAN.md");mt(D,N,"utf-8"),B=D}catch(D){ne=D instanceof Error?D.message:String(D)}let se=[];if(T?.added?.length){let D=T.added.map(G=>G.title);se.push(`Added ${D.length} step(s): ${D.join(", ")}`)}if(T?.removed?.length){let D=T.removed.map(G=>G.title);se.push(`Removed ${D.length} step(s): ${D.join(", ")}`)}if(T?.modified?.length){let D=T.modified.map(G=>G.title);se.push(`Modified ${D.length} step(s): ${D.join(", ")}`)}let me=se.length>0?se.join(". "):"No changes detected.";return d(JSON.stringify({plan:k,diff:T,planMdPath:B,planMdError:ne,message:`Plan modified. ${me}. Update mistflow.json with the new plan${B?"; PLAN.md has been regenerated at "+B:""}, then continue with mist_implement.`}))}let E=I?.trim()||void 0,Z=s;if(Array.isArray(s)){let h=s.findIndex(f=>f&&typeof f=="object"&&f.decisionKey==="urlChoice");if(h>=0){let f=s[h];!E&&f.answer&&(E=f.answer);let k=s.slice(0,h).concat(s.slice(h+1));Z=k.length>0?k:void 0}}else if(s!=null){let h=s;if(!E&&Zn in h&&(E=h[Zn]),!E&&"urlChoice"in h&&(E=h.urlChoice),Zn in h||"urlChoice"in h){let{[Zn]:f,urlChoice:k,...T}=h;Z=Object.keys(T).length>0?T:void 0}}if(E&&(E=E.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),E){let h=E.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(h)?E=h:(console.error(`[mist_plan] Discarding urlChoice '${E}' \u2014 does not look like a subdomain. Backend will auto-generate.`),E=void 0)}let J;if(y){J={...y},delete J.userConfirmedCustom,delete J.user_confirmed_custom;let h={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[f,k]of Object.entries(h))y[f]!==void 0&&J[k]===void 0&&(J[k]=y[f])}let x=J!==void 0&&typeof J.custom=="string"&&!J.id&&!J.name,C=R===!0||y!==void 0&&(y.userConfirmedCustom===!0||y.user_confirmed_custom===!0);if(x&&S)try{let h=await Dn(S);if(h.status==="pending")return d(`Refusing to submit a custom design direction: the backend's direction-generation BG task is still running (status: pending). The user has not yet had the chance to see the real directions. Stop asking the user about aesthetic / fonts / colors / mood right now \u2014 the backend will produce 3-4 concrete options shortly. Re-call mist_plan with { projectPath, conversationId, designConversationId: '${S}' } to keep polling. When directions are ready (status: 'design_clarify'), surface them to the user via AskUserQuestion. Custom is only legitimate AFTER the user has seen the real options and explicitly rejected them \u2014 never as a workaround for a slow generation run.`,!0);if(h.status==="ready"&&Array.isArray(h.directions)&&h.directions.length>0&&!C){let f=h.directions.map(k=>k.name).join(", ");return d(`Refusing to submit a custom design direction: the backend has ${h.directions.length} real directions ready (${f}). The picker is mandatory \u2014 you must surface those exact directions to the user via AskUserQuestion before submitting any pick. Re-call mist_plan with { conversationId, designConversationId: '${S}' } to get the picker payload (status: 'design_clarify'), render the directions HTML preview at .mistflow/design-directions.html for the user, then submit the user's choice. If the user opens the preview, sees the ${h.directions.length} directions, rejects all of them, and types their own description, ONLY THEN retry this call with userConfirmedCustom: true. Never set userConfirmedCustom: true without first showing the user the real directions.`,!0)}}catch(h){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${h instanceof Error?h.message:String(h)}`)}let V=s?"Generating plan with your answers (LLM call)":S?"Finalizing design direction":"Thinking through discovery questions",F=e?ze(e.server,e.progressToken,()=>V):{stop:()=>{}};if(e&&(e.cleanup=()=>F.stop()),!i&&!o&&!S&&!a&&!l&&!c&&!j&&W.trim().length>0&&!z)try{let h=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),f=336*60*60*1e3,k=Date.now()-f,N=(await ln(Yo())).filter(B=>!h.has(B.state)).filter(B=>{let ne=Date.parse(B.updated_at);return Number.isFinite(ne)&&ne>=k}).sort((B,ne)=>Date.parse(ne.updated_at)-Date.parse(B.updated_at)).slice(0,5);if(N.length>0)return F.stop(),d(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:N.map(B=>({sessionId:B.id,state:B.state,description:B.description,currentStep:B.current_step,awaitingInput:B.awaiting_input,updatedAt:B.updated_at})),instruction:"This machine has unfinished Mistflow build(s) in flight. Before starting a new project, ask the user whether they want to resume one of these or start fresh. Show the description, state, and updatedAt for each candidate so they can pick.",nextAction:"Step 1: Show the candidates to the user via your host's question UI (AskUserQuestion in Claude Code, request_user_input in Codex Plan mode, quick pick in Cursor). Step 2a (resume): if they pick a candidate, call mist_session({ action: 'resume', sessionId: '<picked>', projectPath }) and follow the next instruction it returns. Step 2b (start fresh): if they want a new build, call mist_plan again with the SAME description and projectPath, plus forceNew: true. The forceNew flag suppresses this check so the new session can be minted."}))}catch(h){console.error("resume-offer check failed (falling through to bootstrap):",h instanceof Error?h.message:h)}let le=i,P;try{pe&&!Z&&!S&&!te&&!l?P=await Ln(pe):P=await Un(W,{conversationId:pe,answers:Z,autonomous:p,language:u,designConversationId:S,designDirection:J})}catch(h){F.stop();let f=h instanceof Error?h.message:"Failed to generate plan";return d(f,!0)}let ke=P.session_id;if(!le&&ke){le=ke;try{await an(ke,{machine_id:Yo(),local_path:n})}catch(h){console.error("workspace bind failed (resume offers will miss this session):",h instanceof Error?h.message:h)}}if(P.status==="clarify_pending"){F.stop();let h=P;return d(JSON.stringify({status:"running",conversationId:h.conversation_id,sessionId:le,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${h.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.${le?` Carry sessionId="${le}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(P.status==="plan_pending"){F.stop();let h=P;return d(JSON.stringify({status:"running",conversationId:h.conversation_id,sessionId:le,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${h.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(P.status==="design_clarify_pending"&&(V="Generating creative design directions",P=await vd(P)),P.status==="design_clarify_pending")return F.stop(),d(JSON.stringify({status:"running",conversationId:o,designConversationId:P.design_conversation_id,sessionId:le,phase:"generating_design_directions",nextAction:`Creative design directions are still generating (45-60s typical, can stretch on slow runs). Call mist_plan with { projectPath, conversationId: "${o??""}" } IMMEDIATELY to keep polling \u2014 do NOT run bash sleep, do NOT submit a designDirection of your own, do NOT mark the plan as ready, and DO NOT ASK THE USER about aesthetic / fonts / colors / mood / vibe / style while you wait. The backend is generating 3-4 concrete direction options the user will pick from \u2014 asking the user to invent one defeats the entire feature, and the server will reject any { custom } submission while directions are still pending. Just poll. The picker is mandatory; keep polling until status becomes 'design_clarify' with the directions array, then surface those exact directions to the user via AskUserQuestion.`}));if(F.stop(),P.status==="clarify"){let h=P.reflection||"",f=P.suggestedName||"",k=P.suggestedFeatures??[],T=P.questions??[],N=T.some(re=>Array.isArray(re.options)&&typeof re.options[0]=="object"&&re.options[0]?.label),B={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},ne=T.map(re=>{let fe=re.decisionKey&&B[re.decisionKey]||bd(re.question),ce;return N&&Array.isArray(re.options)?ce=re.options.map(ue=>({label:ue.label,description:ue.description??""})):Array.isArray(re.options)?ce=re.options.map((ue,A)=>({label:A===0?`${ue} (Recommended)`:String(ue),description:re.why??""})):ce=[{label:"Yes (Recommended)",description:re.why??""},{label:"No",description:""}],{question:re.question,header:fe,options:ce,multiSelect:!1}}),me=P.decisions?.audienceType??null,D=k.length>0?Go(W,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:me,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:f,suggestedFeatures:k,language:u}):null,G=D?Vo(D):"",ve=Qn(f||"my-app").slice(0,32);try{let re=await On(ve);!re.available&&re.suggestion&&(ve=re.suggestion)}catch{}if(G&&(G+=`
2061
2061
 
2062
- **Your app URL (you can change this before scaffolding):** https://${ve}.mistflow.app`),e?.server){let re=[g?`## ${g}`:"## Pick a few details","",`${T.length} quick question${T.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
2063
- `),ce=await mn(e.server,T,re,"clarify");if(ce.outcome==="submitted"){M.stop();let Te={};for(let C of ce.answers??[])C.decisionKey?Te[C.decisionKey]=C.answer:Te[C.question]=C.answer;let ue=ce.urlChoice?.trim();ue&&(ue=ue.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let C=await Ln(H,{conversationId:R.conversation_id,answers:Te,autonomous:h,language:d});if(C.status==="plan_pending"){let xe=C;return p(JSON.stringify({status:"running",conversationId:xe.conversation_id,phase:"generating_plan",...ue?{urlChoice:ue}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${xe.conversation_id}"${ue?`, urlChoice: "${ue}"`:""} } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll up to ~10s and returns when the plan lands. Pass urlChoice on every poll so it threads through to the saved plan.`}))}R=C}catch(C){let xe=C instanceof Error?C.message:String(C);return p(`Submitting your answers failed: ${xe}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(ce.outcome==="declined")return M.stop(),p("User declined the planning flow via the form. They likely want a different approach \u2014 ask them what they'd prefer instead of re-running mist_plan.",!0);if(ce.outcome==="cancelled")return M.stop(),p("User cancelled the planning form without picking. The conversation is still alive \u2014 re-run mist_plan with the same conversationId if they want to retry, or start a fresh plan if they want to change the description.",!0);ce.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${ce.errorMessage}) \u2014 falling back to prose flow.`)}}return p(JSON.stringify({status:"clarify",requires_user_input:!0,nextAction:"STOP \u2014 DO NOT submit answers yourself. Render every entry in `askUserQuestions` via your host's native question tool (AskUserQuestion in Claude Code, request_user_input in OpenAI Codex Plan mode, quick pick in Cursor) and WAIT for the user to actually answer. If your host has no native question tool, stop your turn, print the questions verbatim as a numbered list with all options visible, and wait for the user's next message. Calling mist_plan with answers in the same turn you received the questions is ALWAYS wrong, regardless of how obvious `recommended` looks.",conversation_id:R.conversation_id,questions:T,questionCount:T.length,suggestedFeatures:w,suggestedName:g,suggestedSubdomain:ve,reflection:m,briefText:J,askUserQuestions:oe,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:["\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST ask the user via your host's native structured-question","tool (not a text prompt, not a bash echo, not a chat message).","The user has to actually choose. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","Per host (use whichever applies):"," \u2022 Claude Code \u2192 AskUserQuestion tool"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) \u2192 request_user_input returns"," 'unavailable in <mode> mode'. When you see that error, STOP"," your turn, print the questions as a numbered chat message"," with all options visible, and wait for the user's next"," message. Do NOT resume by picking answers yourself."," \u2022 Any host without a native question tool \u2192 same as above:"," stop your turn, print the questions, wait.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 'Locking in the defaults with X as the only override.'"," (inferring answers from the original spec)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping the question UI because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call the tool (when available): pass each object in the","`askUserQuestions` array below. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${R.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${ve}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.',...m||J?["","\u2500\u2500\u2500 BACKGROUND (not for you to summarize and proceed \u2014 it's what the user will see when you show them the questions) \u2500\u2500\u2500",...m?[m]:[],...J?["",J]:[]]:[],...Q?["",Q]:[]].join(`
2064
- `)}))}if(R.status==="design_clarify"){let m=R.directions??[],g=R.plan.name??"your app",w=R.design_conversation_id,T=m.map(S=>({id:S.id,name:S.name,summary:S.summary,hero_headline:S.hero_headline,cta_text:S.cta_text,body_sample:S.body_sample,fonts:S.fonts,colors:S.colors,hero_treatment:S.hero_treatment,shape_lang:S.shape_lang,texture:S.texture,decoration_hint:S.decoration_hint})),O={},F=!1;try{if(w){let me=Date.now();for(;Date.now()-me<5e4;){let Z=await Dn(w),Y=0;for(let x of T){let j=Z[x.id];j&&((j.status==="done"||j.status==="ready")&&typeof j.html=="string"&&j.html.length>0?(O[x.id]=j.html,Y+=1):j.status==="failed"&&(Y+=1))}if(Y===T.length){F=!0;break}await new Promise(x=>setTimeout(x,5e3))}}}catch(S){console.error(`[mist_plan:design_clarify] render poll failed: ${S instanceof Error?S.message:String(S)}`)}if(!F)return p(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:R.conversation_id??o,design_conversation_id:w,renderedSoFar:Object.keys(O).length,totalDirections:T.length,nextAction:`${Object.keys(O).length}/${T.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${R.conversation_id??o??""}" } again IMMEDIATELY \u2014 do NOT bash sleep. Do NOT ask the user about design yet.`}));let oe=T.filter(S=>O[S.id]),le,ie,L=ye(n,".mistflow"),J=ye(L,"design-directions.html"),ve=ye(L,"picker-state.json"),re=()=>{try{if(Xe(ve))return JSON.parse(gn(ve,"utf-8"))}catch{}return{}},ce=S=>{try{Pt(L,{recursive:!0}),pt(ve,JSON.stringify(S,null,2),"utf-8")}catch(de){console.error(`[mist_plan:design_clarify] sidecar write failed: ${de instanceof Error?de.message:String(de)}`)}},Te=re(),ue=w&&Te.opened_for_design_cid===w;try{if(Pt(L,{recursive:!0}),ue)le=J;else{let S=ls(g,oe,O);pt(J,S,"utf-8"),le=J;let de=as(`file://${J}`);de.opened||(ie=de.reason),w&&ce({opened_for_design_cid:w,elicit_state:"pending",elicit_design_cid:w,opened_at:new Date().toISOString()})}}catch(S){console.error(`[mist_plan:design_clarify] picker write/open failed: ${S instanceof Error?S.message:String(S)}`)}let C=re(),xe=oe.map(S=>({id:S.id,name:S.name})),f=xe.map(S=>S.name).filter(Boolean);if(e?.server&&w&&C.elicit_design_cid===w&&C.elicit_state==="pending"){let S=le?[`## ${g} \u2014 pick a creative direction`,"",`${oe.length} directions, each with its own fonts, colors, and mood.`,"",`Visual preview (auto-opened in your browser): file://${le}`,"Each card shows what you'd be picking \u2014 fonts, colors, hero layout."].join(`
2065
- `):`## ${g} \u2014 pick a creative direction
2062
+ **Your app URL (you can change this before scaffolding):** https://${ve}.mistflow.app`),e?.server){let re=[f?`## ${f}`:"## Pick a few details","",`${T.length} quick question${T.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
2063
+ `),fe=await hn(e.server,T,re,"clarify");if(fe.outcome==="submitted"){F.stop();let ce={};for(let A of fe.answers??[])A.decisionKey?ce[A.decisionKey]=A.answer:ce[A.question]=A.answer;let ue=fe.urlChoice?.trim();ue&&(ue=ue.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let A=await Un(W,{conversationId:P.conversation_id,answers:ce,autonomous:p,language:u});if(A.status==="plan_pending"){let Te=A;return d(JSON.stringify({status:"running",conversationId:Te.conversation_id,phase:"generating_plan",...ue?{urlChoice:ue}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${Te.conversation_id}"${ue?`, urlChoice: "${ue}"`:""} } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll up to ~10s and returns when the plan lands. Pass urlChoice on every poll so it threads through to the saved plan.`}))}P=A}catch(A){let Te=A instanceof Error?A.message:String(A);return d(`Submitting your answers failed: ${Te}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(fe.outcome==="declined")return F.stop(),d("User declined the planning flow via the form. They likely want a different approach \u2014 ask them what they'd prefer instead of re-running mist_plan.",!0);if(fe.outcome==="cancelled")return F.stop(),d("User cancelled the planning form without picking. The conversation is still alive \u2014 re-run mist_plan with the same conversationId if they want to retry, or start a fresh plan if they want to change the description.",!0);fe.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${fe.errorMessage}) \u2014 falling back to prose flow.`)}}return d(JSON.stringify({status:"clarify",requires_user_input:!0,nextAction:"STOP \u2014 DO NOT submit answers yourself. Render every entry in `askUserQuestions` via your host's native question tool (AskUserQuestion in Claude Code, request_user_input in OpenAI Codex Plan mode, quick pick in Cursor) and WAIT for the user to actually answer. If your host has no native question tool, stop your turn, print the questions verbatim as a numbered list with all options visible, and wait for the user's next message. Calling mist_plan with answers in the same turn you received the questions is ALWAYS wrong, regardless of how obvious `recommended` looks.",conversation_id:P.conversation_id,questions:T,questionCount:T.length,suggestedFeatures:k,suggestedName:f,suggestedSubdomain:ve,reflection:h,briefText:G,askUserQuestions:ne,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:["\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST ask the user via your host's native structured-question","tool (not a text prompt, not a bash echo, not a chat message).","The user has to actually choose. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","Per host (use whichever applies):"," \u2022 Claude Code \u2192 AskUserQuestion tool"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) \u2192 request_user_input returns"," 'unavailable in <mode> mode'. When you see that error, STOP"," your turn, print the questions as a numbered chat message"," with all options visible, and wait for the user's next"," message. Do NOT resume by picking answers yourself."," \u2022 Any host without a native question tool \u2192 same as above:"," stop your turn, print the questions, wait.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 'Locking in the defaults with X as the only override.'"," (inferring answers from the original spec)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping the question UI because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call the tool (when available): pass each object in the","`askUserQuestions` array below. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${P.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${ve}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.',...h||G?["","\u2500\u2500\u2500 BACKGROUND (not for you to summarize and proceed \u2014 it's what the user will see when you show them the questions) \u2500\u2500\u2500",...h?[h]:[],...G?["",G]:[]]:[],...L?["",L]:[]].join(`
2064
+ `)}))}if(P.status==="design_clarify"){let h=P.directions??[],f=P.plan.name??"your app",k=P.design_conversation_id,T=h.map(w=>({id:w.id,name:w.name,summary:w.summary,hero_headline:w.hero_headline,cta_text:w.cta_text,body_sample:w.body_sample,fonts:w.fonts,colors:w.colors,hero_treatment:w.hero_treatment,shape_lang:w.shape_lang,texture:w.texture,decoration_hint:w.decoration_hint})),N={},B=!1;try{if(k){let ee=Date.now();for(;Date.now()-ee<5e4;){let Le=await Mn(k),Y=0;for(let Q of T){let v=Le[Q.id];v&&((v.status==="done"||v.status==="ready")&&typeof v.html=="string"&&v.html.length>0?(N[Q.id]=v.html,Y+=1):v.status==="failed"&&(Y+=1))}if(Y===T.length){B=!0;break}await new Promise(Q=>setTimeout(Q,5e3))}}}catch(w){console.error(`[mist_plan:design_clarify] render poll failed: ${w instanceof Error?w.message:String(w)}`)}if(!B)return d(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:P.conversation_id??o,design_conversation_id:k,renderedSoFar:Object.keys(N).length,totalDirections:T.length,nextAction:`${Object.keys(N).length}/${T.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${P.conversation_id??o??""}" } again IMMEDIATELY \u2014 do NOT bash sleep. Do NOT ask the user about design yet.`}));let ne=T.filter(w=>N[w.id]),se,me,D=he(n,".mistflow"),G=he(D,"design-directions.html"),ve=he(D,"picker-state.json"),re=()=>{try{if(Ze(ve))return JSON.parse(fn(ve,"utf-8"))}catch{}return{}},fe=w=>{try{Ct(D,{recursive:!0}),mt(ve,JSON.stringify(w,null,2),"utf-8")}catch($){console.error(`[mist_plan:design_clarify] sidecar write failed: ${$ instanceof Error?$.message:String($)}`)}},ce=re(),ue=k&&ce.opened_for_design_cid===k;try{if(Ct(D,{recursive:!0}),ue)se=G;else{let w=cs(f,ne,N);mt(G,w,"utf-8"),se=G;let $=ls(`file://${G}`);$.opened||(me=$.reason),k&&fe({opened_for_design_cid:k,elicit_state:"pending",elicit_design_cid:k,opened_at:new Date().toISOString()})}}catch(w){console.error(`[mist_plan:design_clarify] picker write/open failed: ${w instanceof Error?w.message:String(w)}`)}let A=re(),Te=ne.map(w=>({id:w.id,name:w.name})),ye=Te.map(w=>w.name).filter(Boolean);if(e?.server&&k&&A.elicit_design_cid===k&&A.elicit_state==="pending"){let w=se?[`## ${f} \u2014 pick a creative direction`,"",`${ne.length} directions, each with its own fonts, colors, and mood.`,"",`Visual preview (auto-opened in your browser): file://${se}`,"Each card shows what you'd be picking \u2014 fonts, colors, hero layout."].join(`
2065
+ `):`## ${f} \u2014 pick a creative direction
2066
2066
 
2067
- ${oe.length} directions, each with its own fonts, colors, and mood. Pick one or describe your own.`,de=oe.map(me=>({label:me.name,description:me.summary??""}));de.push({label:"Describe your own direction",description:"Skip the proposed options and type a short description of how the app should feel."});try{let me=await mn(e.server,[{question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,decisionKey:"designDirection",options:de,noOtherSentinel:!0,otherFieldTitle:"If 'Describe your own direction' was picked: type how the app should feel (fonts, colors, mood \u2014 your words)."}],S,"design");if(me.outcome==="submitted"&&me.answers?.[0]){let Z=me.answers[0].answer.trim(),Y=oe.find(j=>j.name===Z),x=Y?{direction_id:Y.id}:{custom:Z};(R.conversation_id??o)&&(x.conversation_id=R.conversation_id??o);try{let j=await jn(w,x);ce({...C,elicit_state:"completed",elicit_design_cid:w}),R={status:"ready",plan:j.plan??{},methodology:j.methodology??"",...j.designMd?{designMd:j.designMd}:{}}}catch(j){return console.error(`[mist_plan:design_clarify] submitDesignPick failed: ${j instanceof Error?j.message:String(j)}`),ce({...C,elicit_state:"skipped"}),p(`Design submission failed: ${j instanceof Error?j.message:String(j)}. Ask the user to retry by re-running mist_plan with their pick.`,!0)}}else return ce({...C,elicit_state:"skipped"}),p(JSON.stringify({status:"design_clarify",previewPath:le,previewOpenError:ie,directionRefs:xe,directionNames:f,design_conversation_id:w,conversation_id:R.conversation_id??o,nextAction:[`The user closed the elicit picker without picking. The visual picker is still open at file://${le??"(path missing)"}.`,`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask which direction they pick. List EXACTLY these names: ${f.map(Z=>`"${Z}"`).join(", ")}.`,`When they pick, call mist_plan with { projectPath, conversationId: "${R.conversation_id??o??""}", designConversationId: "${w??""}", designDirection: { id: "<id from directionRefs>" } }.`].join(`
2067
+ ${ne.length} directions, each with its own fonts, colors, and mood. Pick one or describe your own.`,$=ne.map(ee=>({label:ee.name,description:ee.summary??""}));$.push({label:"Describe your own direction",description:"Skip the proposed options and type a short description of how the app should feel."});try{let ee=await hn(e.server,[{question:`${f} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,decisionKey:"designDirection",options:$,noOtherSentinel:!0,otherFieldTitle:"If 'Describe your own direction' was picked: type how the app should feel (fonts, colors, mood \u2014 your words)."}],w,"design");if(ee.outcome==="submitted"&&ee.answers?.[0]){let Le=ee.answers[0].answer.trim(),Y=ne.find(v=>v.name===Le),Q=Y?{direction_id:Y.id}:{custom:Le};(P.conversation_id??o)&&(Q.conversation_id=P.conversation_id??o);try{let v=await jn(k,Q);fe({...A,elicit_state:"completed",elicit_design_cid:k}),P={status:"ready",plan:v.plan??{},methodology:v.methodology??"",...v.designMd?{designMd:v.designMd}:{}}}catch(v){return console.error(`[mist_plan:design_clarify] submitDesignPick failed: ${v instanceof Error?v.message:String(v)}`),fe({...A,elicit_state:"skipped"}),d(`Design submission failed: ${v instanceof Error?v.message:String(v)}. Ask the user to retry by re-running mist_plan with their pick.`,!0)}}else return fe({...A,elicit_state:"skipped"}),d(JSON.stringify({status:"design_clarify",previewPath:se,previewOpenError:me,directionRefs:Te,directionNames:ye,design_conversation_id:k,conversation_id:P.conversation_id??o,nextAction:[`The user closed the elicit picker without picking. The visual picker is still open at file://${se??"(path missing)"}.`,`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask which direction they pick. List EXACTLY these names: ${ye.map(Le=>`"${Le}"`).join(", ")}.`,`When they pick, call mist_plan with { projectPath, conversationId: "${P.conversation_id??o??""}", designConversationId: "${k??""}", designDirection: { id: "<id from directionRefs>" } }.`].join(`
2068
2068
 
2069
- `)}))}catch(me){console.error(`[mist_plan:design_clarify] elicit failed: ${me instanceof Error?me.message:String(me)}`),ce({...C,elicit_state:"skipped"})}}if(R.status==="design_clarify")return p(JSON.stringify({status:"design_clarify",previewPath:le,previewOpenError:ie,directionRefs:xe,directionNames:f,design_conversation_id:w,conversation_id:R.conversation_id??o,nextAction:[`The visual picker is open in the user's browser at file://${le??"(path missing)"} \u2014 every direction is a real, rendered landing page.`,ie?`(auto-open suppressed: ${ie} \u2014 tell the user to open file://${le} manually)`:"",`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names: ${f.map(S=>`"${S}"`).join(", ")}. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${R.conversation_id??o??""}", designConversationId: "${w??""}", designDirection: { id: "<map name \u2192 id from directionRefs>" } }. If they describe their own, pass designDirection: { custom: "<their exact words>" } and userConfirmedCustom: true.`].filter(Boolean).join(`
2069
+ `)}))}catch(ee){console.error(`[mist_plan:design_clarify] elicit failed: ${ee instanceof Error?ee.message:String(ee)}`),fe({...A,elicit_state:"skipped"})}}if(P.status==="design_clarify")return d(JSON.stringify({status:"design_clarify",previewPath:se,previewOpenError:me,directionRefs:Te,directionNames:ye,design_conversation_id:k,conversation_id:P.conversation_id??o,nextAction:[`The visual picker is open in the user's browser at file://${se??"(path missing)"} \u2014 every direction is a real, rendered landing page.`,me?`(auto-open suppressed: ${me} \u2014 tell the user to open file://${se} manually)`:"",`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names: ${ye.map(w=>`"${w}"`).join(", ")}. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${P.conversation_id??o??""}", designConversationId: "${k??""}", designDirection: { id: "<map name \u2192 id from directionRefs>" } }. If they describe their own, pass designDirection: { custom: "<their exact words>" } and userConfirmedCustom: true.`].filter(Boolean).join(`
2070
2070
 
2071
- `)}))}if(R.status!=="ready")return p(`Unexpected plan status after build: ${R.status}. Please retry by calling mist_plan with the same conversationId.`,!0);let K=R.plan,ae=K.name??"Untitled App",Oe=R.methodology,ke=K.steps;if(!Array.isArray(ke)||ke.length===0)return p("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let we=K.suggestedSubdomain??Yn(ae).slice(0,32)??"my-app";if(!I&&e?.server){try{let g=await Nn(we);!g.available&&g.suggestion&&(we=g.suggestion)}catch{}let m=await mn(e.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${we}.mistflow.app`,why:"Subdomains lock in at scaffold time and are baked into auth callbacks, share links, and analytics. Pick the default to ship now, or type a custom subdomain in the textbox below.",options:[{label:`Keep ${we}.mistflow.app`,description:"Use the suggested subdomain"},{label:"Type a different subdomain",description:"Custom subdomain \u2014 fill the textbox below"}],noOtherSentinel:!0,otherFieldTitle:"Custom subdomain (e.g. 'sales-comm') \u2014 lowercase, alphanumeric + hyphens, 3-32 chars"}],`## ${ae} \u2014 pick the URL
2071
+ `)}))}if(P.status!=="ready")return d(`Unexpected plan status after build: ${P.status}. Please retry by calling mist_plan with the same conversationId.`,!0);let U=P.plan,oe=U.name??"Untitled App",Ce=P.methodology,we=U.steps;if(!Array.isArray(we)||we.length===0)return d("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let Se=U.suggestedSubdomain??Qn(oe).slice(0,32)??"my-app";if(!E&&e?.server){try{let f=await On(Se);!f.available&&f.suggestion&&(Se=f.suggestion)}catch{}let h=await hn(e.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${Se}.mistflow.app`,why:"Subdomains lock in at scaffold time and are baked into auth callbacks, share links, and analytics. Pick the default to ship now, or type a custom subdomain in the textbox below.",options:[{label:`Keep ${Se}.mistflow.app`,description:"Use the suggested subdomain"},{label:"Type a different subdomain",description:"Custom subdomain \u2014 fill the textbox below"}],noOtherSentinel:!0,otherFieldTitle:"Custom subdomain (e.g. 'sales-comm') \u2014 lowercase, alphanumeric + hyphens, 3-32 chars"}],`## ${oe} \u2014 pick the URL
2072
2072
 
2073
- The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(m.outcome==="submitted"){let g=m.urlChoice?.trim()||m.answers?.[0]?.answer.trim()||"";g=g.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(g)||!g)&&(g=we);let w=g.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(w)?I=w:(console.error(`[mist_plan] URL elicitation returned '${g}' \u2014 does not look like a subdomain. Using default '${we}'.`),I=we)}else m.outcome==="declined"||m.outcome,I=we}else I||(I=we);let Le=K.publicPages;if(!Le||Array.isArray(Le)&&Le.length===0){let m=K.pages,g=ke.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),w=Array.isArray(m)&&m.some(T=>T.path==="/"||T.route==="/");g||w?Le=["/","/pricing"]:Le=["/"]}let Rt=K.primaryAction;if(!Rt){let m=K.features;if(Array.isArray(m)&&m.length>0){let w=m.find(O=>typeof O.priority=="string"&&O.priority.toLowerCase()==="must-have")??m[0];Rt={entity:w.name??w.title??"item",action:"create",fromPage:"/dashboard"}}}let Ve=K.nonNegotiables;(!Ve||Array.isArray(Ve)&&Ve.length===0)&&(Ve=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let He=Yo(),nt=ye(ut(),".mistflow","plans");Pt(nt,{recursive:!0});try{let g=Date.now();for(let w of[nt,ye(ut(),".mistflow","mockup-state")])if(Xe(w))for(let T of ti(w))try{let O=ye(w,T),F=ni(O).mtimeMs;g-F>6048e5&&nd(O)}catch{}}catch{}let Ce=K,X={name:K.name,summary:K.summary,dataModel:K.dataModel,pages:K.pages,features:K.features,steps:ke.map(m=>({...m,name:m.name??m.title})),design:K.design,dbProvider:K.dbProvider??"neon",authModel:K.authModel,audienceType:K.audienceType??"b2c",roles:K.roles,defaultRole:K.defaultRole,publicPages:Le,navStyle:K.navStyle,multiTenant:K.multiTenant,primaryAction:Rt,nonNegotiables:Ve,requestedSubdomain:I,...d&&d.toLowerCase()!=="english"?{language:d}:{},...Ce.pickedDirection?{pickedDirection:Ce.pickedDirection}:{},...Ce.imageryBrief?{imageryBrief:Ce.imageryBrief}:{},...Ce.designConversationId?{designConversationId:Ce.designConversationId}:{}};pt(ye(nt,`${He}.json`),JSON.stringify({plan:X,methodology:Oe,...q?{scaffoldTargetPath:q}:{}}));let fe=ke.map(m=>`${m.number}. ${m.name??m.title}`),je,rt="";if(!!!Ce.pickedDirection){let g=(K.audienceType??"b2c")==="b2c";je={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:g?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:g?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},rt=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call."}let st="",We=[];for(let m of ke){let g=m.name??m.title,w=m.integrationId;if(w){let T=Lt(w);if(T){let O=Ut(T.id);We.push({step:g,presetId:T.id,presetName:T.name,envVars:O?.envVars??[]})}}}if(We.length>0){let m=We.flatMap(T=>T.envVars),g=[...new Set(m.map(T=>T.key))];st=` This plan uses integrations (${We.map(T=>T.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return p(JSON.stringify({planId:He,name:K.name,summary:K.summary,stepCount:ke.length,steps:fe,design:K.design,...je?{heroPhotoQuestion:je}:{},...We.length>0?{integrations:We.map(m=>({step:m.step,preset:m.presetId,name:m.presetName,envVars:m.envVars}))}:{},message:`Plan generated for "${ae}" (${ke.length} steps).${st}${rt}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,ke.length*3)}\u2013${ke.length*5} minutes total across ${ke.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_mockup({ planId: '${He}' }). If the user says skip or "just build it", call mist_init({ planId: '${He}'${q?"":", path: '<absolute path>'"} }) immediately.`,...q?{scaffoldTargetPath:q}:{},...Q?{warning:Q}:{}}))}var Xn,ld,fd,ii,ai=P(()=>{"use strict";be();_e();zo();qt();Ho();zn();Vo();Ko();Xn="__mistflow_url_choice__",ld=600*1e3;fd=D.object({description:D.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:D.string().min(1).describe("REQUIRED. Absolute path to the user's current working directory \u2014 where the Mistflow app will be scaffolded. Pass the directory the user is actually working in (e.g. /Users/alice/projects). Do NOT pass '/', '~', $HOME, Desktop, Documents, Downloads, or /tmp \u2014 the tool will refuse to scaffold at those locations. If you are unsure of the user's working directory, ask them before calling this tool."),sessionId:D.string().uuid().optional().describe("Backend-owned session ID. When present, mist_plan polls GET /api/sessions/{id}/next and returns the next instruction (wait, ask_user, pick_design, call_mist_init, etc.). Pass it on every subsequent mist_* call to keep the same session."),conversationId:D.string().optional().describe("Returned by a previous mist_plan call with status 'clarify' or 'running'. Pass it back alone (no description) to poll an in-flight discovery call; pass with answers to submit responses."),answers:D.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("[")&&!e.startsWith("{"))return t;try{return JSON.parse(e)}catch{return t}},D.union([D.record(D.string()),D.array(D.object({question:D.string().optional(),decisionKey:D.string().optional(),answer:D.string()}))]).optional()).describe("User's answers to the clarifying questions. Pass an ARRAY of { question, decisionKey, answer } objects directly \u2014 do NOT stringify it as JSON. The schema also accepts a { '<question text>': '<answer label>' } object map for one-question-per-decisionKey rounds. Strings that look like JSON arrays/objects are auto-parsed for resilience."),existingPlan:D.record(D.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:D.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:D.string().optional().describe("Fork from a shared template. Pass the share token (from a mistflow.ai/t/... URL) to clone that project's plan into your workspace."),remixDescription:D.string().optional().describe("Optional remix request when forking a template. Describes how you want the template to be different. E.g. 'Make it for tracking books instead of habits, add a search feature.' Only used with templateToken."),autonomous:D.boolean().optional().describe("DANGER \u2014 only set this to `true` when the user has EXPLICITLY asked to skip discovery questions (phrases like 'no questions', 'just build it', 'autonomous mode', 'don't ask'). Default is `false` and should stay that way in every other case. Do NOT set autonomous=true as a retry strategy after a plan-gen failure \u2014 it doesn't make things more reliable, it just removes the user's control over discovery answers (roles, integrations, auth model, etc.) and Sonnet ends up guessing. If a plan call fails, retry the SAME call with the same parameters, not a more aggressive one. Do NOT set autonomous=true to speed things up \u2014 the server already runs plan-gen in the background and polls, so there is no speed benefit. When set, skips the clarify round and generates the plan straight from the description. The user loses the chance to pick any option."),language:D.string().optional().describe("UI language for the app. All user-facing text, labels, buttons, and content will be generated in this language. Use the language name in English (e.g. 'Spanish', 'French', 'Arabic', 'Japanese'). Defaults to English if not specified."),brandMentioned:D.boolean().optional().describe("Set to true ONLY when the user's original request explicitly invoked Mistflow by name (e.g. 'build me a CRM using mist', 'make a todo app with mistflow'). Skips the existing-project confirmation gate because the user clearly wants Mistflow. Do NOT set this for generic 'build me X' requests. Do NOT infer this \u2014 only set it when the user literally typed 'mist' or 'mistflow'."),confirmToken:D.string().optional().describe("The token returned in a previous mist_plan response with status 'confirm_new_project'. Only pass this AFTER asking the user via AskUserQuestion and they chose to scaffold a new Mistflow app in an existing-project directory. The token is bound to the projectPath and description \u2014 you must pass the SAME description AND projectPath on the retry."),urlChoice:D.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers."),designConversationId:D.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass it back on the follow-up call together with designDirection to finalize the plan's DESIGN.md."),designDirection:D.object({id:D.string().optional(),name:D.string().optional(),summary:D.string().optional(),heroHeadline:D.string().optional(),ctaText:D.string().optional(),bodySample:D.string().optional(),fontsHint:D.string().optional(),fonts:D.object({display:D.string(),body:D.string()}).partial().optional(),colorMood:D.string().optional(),colors:D.object({bg:D.string(),fg:D.string(),accent:D.string()}).partial().optional(),heroTreatment:D.string().optional(),shapeLang:D.string().optional(),texture:D.string().optional(),decorationHint:D.string().optional(),custom:D.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass ONLY the minimal shape: (a) `{ id: '<short-kebab-id-from-directionRefs>' }` when the user picked one of the proposed options \u2014 copy the id verbatim from `directionRefs[].id`, e.g. 'morning-paper' or 'quiet-utility'; or (b) `{ custom: '<the user\\'s exact words>' }` + `userConfirmedCustom: true` when the user typed their own description. Do NOT pass the full direction object (name, summary, fonts, colors, hero_headline, body_sample, etc.) \u2014 those fields are ignored and may exceed backend length limits, causing 422 rejections. ID values are short kebab-case strings (\u2264256 chars). Custom descriptions are user-typed prose (\u22644000 chars). Anything longer is wrong."),userConfirmedCustom:D.boolean().optional().describe("Set true ONLY when the user themselves typed a custom direction (via AskUserQuestion 'Other' or by explicitly describing the look in the chat). Required when submitting designDirection: { custom: ... } if the backend has real directions cached \u2014 the server rejects custom submissions otherwise to stop the AI from silently bypassing the picker. NEVER set this true unless the words in `custom` came directly from the user."),forceNew:D.boolean().optional().describe("Set to true ONLY after the user has explicitly chosen 'start fresh' from a previous mist_plan response with status 'resume_offer'. Suppresses the resume-offer check and lets a new session start even when this machine has unfinished work in flight. Do NOT set this preemptively on the first call \u2014 the resume-offer check needs to run so the user gets the chance to pick up where they left off.")});ii={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist'). Clear new-app requests inside an existing non-Mistflow repo are scaffolded into a remembered child directory; Mistflow does not edit the surrounding codebase.","",`DESIGN REFERENCES (screenshots, Figma, brand names): if the user drags a screenshot, pastes a Figma URL, or names a brand to match ("make it feel like Linear"), use your native vision/knowledge to extract design tokens and submit them via designDirection: { custom: '<your description>', ...extracted_tokens } with userConfirmedCustom: true. The flag is required because the user supplied the reference; without it the server rejects the submission to stop AIs from inventing custom directions. Full flow at docs/design-references.md.`,"","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). For clear new-app requests it automatically creates and remembers a child scaffold directory. For ambiguous requests, it returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token from the response. Do not change projectPath to the suggested child path; Mistflow stores that target for mist_init.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_init with the returned planId. If the response includes scaffoldTargetPath you do not need to pass path; mist_init loads it from the cached plan. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","SESSIONID FLOW (dumb-ai-proof, when the response includes sessionId): keep the sessionId and pass it on every subsequent mist_* call. Calling mist_plan with just { sessionId, projectPath } polls GET /api/sessions/{id}/next and returns the next instruction (wait | ask_user | pick_design | review_mockup | call_mist_init | call_mist_install | call_mist_implement | call_mist_build | call_mist_deploy | call_mist_qa | done). Do exactly what the instruction says \u2014 don't branch on raw state. The backend owns routing; the host relays.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. The aesthetic (fonts, colors, motion) is decided by the design-direction picker step \u2014 the host AI doesn't pick a catalog ID."].join(`
2074
- `),inputSchema:fd,handler:Td}});function _d(t){let e=t.match(/^v?(\d+)\.(\d+)\.(\d+)/);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null}function Bt(t=process.version){let e=_d(t);return!e||e.major>=23?!0:e.major===22?e.minor>=12:e.major===20?e.minor>=19:!1}function Pd(t=process.execPath){return t.includes("Library/pnpm/")||t.includes("AppData\\pnpm\\")||t.includes("/.pnpm/")?"pnpm":t.includes("/.fnm/")||process.env.FNM_DIR?"fnm":process.env.NVM_DIR||t.includes("/.nvm/")?"nvm":process.env.VOLTA_HOME||t.includes("/.volta/")?"volta":t.startsWith("/opt/homebrew/")||t.startsWith("/usr/local/")?"brew":t==="/usr/bin/node"?"system":"unknown"}function It(t=process.version,e=Pd()){let r={pnpm:"Run: pnpm env use --global 22.12.0",fnm:"Run: fnm install 22.12 && fnm use 22.12",nvm:"Run: nvm install 22.12 && nvm use 22.12",volta:"Run: volta install node@22.12",brew:"Run: brew install node@22 && brew link node@22 --force --overwrite",system:"Install Node 22.12+ from https://nodejs.org/download",unknown:"Install Node 22.12+ from https://nodejs.org/download"};return[`OpenNext/Cloudflare builds require Node 20.19+, 22.12+, or 23+. The current MCP process is running ${t}.`,r[e],"Then quit and reopen your IDE so the MCP picks up the new Node."].join(`
2075
- `)}var Zn=P(()=>{"use strict"});var er,cs=P(()=>{er="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n"});var tr,ds=P(()=>{tr=`# Landing Page Rules
2073
+ The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(h.outcome==="submitted"){let f=h.urlChoice?.trim()||h.answers?.[0]?.answer.trim()||"";f=f.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(f)||!f)&&(f=Se);let k=f.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(k)?E=k:(console.error(`[mist_plan] URL elicitation returned '${f}' \u2014 does not look like a subdomain. Using default '${Se}'.`),E=Se)}else h.outcome==="declined"||h.outcome,E=Se}else E||(E=Se);let Me=U.publicPages;if(!Me||Array.isArray(Me)&&Me.length===0){let h=U.pages,f=we.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),k=Array.isArray(h)&&h.some(T=>T.path==="/"||T.route==="/");f||k?Me=["/","/pricing"]:Me=["/"]}let rt=U.primaryAction;if(!rt){let h=U.features;if(Array.isArray(h)&&h.length>0){let k=h.find(N=>typeof N.priority=="string"&&N.priority.toLowerCase()==="must-have")??h[0];rt={entity:k.name??k.title??"item",action:"create",fromPage:"/dashboard"}}}let Ve=U.nonNegotiables;(!Ve||Array.isArray(Ve)&&Ve.length===0)&&(Ve=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Ke=Qo(),st=he(ht(),".mistflow","plans");Ct(st,{recursive:!0});try{let f=Date.now();for(let k of[st,he(ht(),".mistflow","mockup-state")])if(Ze(k))for(let T of ni(k))try{let N=he(k,T),B=ri(N).mtimeMs;f-B>6048e5&&rd(N)}catch{}}catch{}let Ae=U,X={name:U.name,summary:U.summary,dataModel:U.dataModel,pages:U.pages,features:U.features,steps:we.map(h=>({...h,name:h.name??h.title})),design:U.design,dbProvider:U.dbProvider??"neon",authModel:U.authModel,audienceType:U.audienceType??"b2c",roles:U.roles,defaultRole:U.defaultRole,publicPages:Me,navStyle:U.navStyle,multiTenant:U.multiTenant,primaryAction:rt,nonNegotiables:Ve,requestedSubdomain:E,...u&&u.toLowerCase()!=="english"?{language:u}:{},...Ae.pickedDirection?{pickedDirection:Ae.pickedDirection}:{},...Ae.imageryBrief?{imageryBrief:Ae.imageryBrief}:{},...Ae.designConversationId?{designConversationId:Ae.designConversationId}:{}};mt(he(st,`${Ke}.json`),JSON.stringify({plan:X,methodology:Ce,...H?{scaffoldTargetPath:H}:{}}));let ge=we.map(h=>`${h.number}. ${h.name??h.title}`),Re,ot="";if(!!!Ae.pickedDirection){let f=(U.audienceType??"b2c")==="b2c";Re={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:f?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:f?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},ot=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call."}let it="",$e=[];for(let h of we){let f=h.name??h.title,k=h.integrationId;if(k){let T=Ut(k);if(T){let N=$t(T.id);$e.push({step:f,presetId:T.id,presetName:T.name,envVars:N?.envVars??[]})}}}if($e.length>0){let h=$e.flatMap(T=>T.envVars),f=[...new Set(h.map(T=>T.key))];it=` This plan uses integrations (${$e.map(T=>T.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${f.length>0?` The user will need these API keys: ${f.join(", ")}.`:""}`}return d(JSON.stringify({planId:Ke,name:U.name,summary:U.summary,stepCount:we.length,steps:ge,design:U.design,...Re?{heroPhotoQuestion:Re}:{},...$e.length>0?{integrations:$e.map(h=>({step:h.step,preset:h.presetId,name:h.presetName,envVars:h.envVars}))}:{},message:`Plan generated for "${oe}" (${we.length} steps).${it}${ot}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,we.length*3)}\u2013${we.length*5} minutes total across ${we.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_mockup({ planId: '${Ke}' }). If the user says skip or "just build it", call mist_init({ planId: '${Ke}'${H?"":", path: '<absolute path>'"} }) immediately.`,...H?{scaffoldTargetPath:H}:{},...L?{warning:L}:{}}))}var Zn,cd,yd,ai,li=_(()=>{"use strict";be();_e();Ho();Bt();Wo();Hn();Ko();Jo();Zn="__mistflow_url_choice__",cd=600*1e3;yd=M.object({description:M.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:M.string().min(1).describe("REQUIRED. Absolute path to the user's current working directory \u2014 where the Mistflow app will be scaffolded. Pass the directory the user is actually working in (e.g. /Users/alice/projects). Do NOT pass '/', '~', $HOME, Desktop, Documents, Downloads, or /tmp \u2014 the tool will refuse to scaffold at those locations. If you are unsure of the user's working directory, ask them before calling this tool."),sessionId:M.string().uuid().optional().describe("Backend-owned session ID. When present, mist_plan polls GET /api/sessions/{id}/next and returns the next instruction (wait, ask_user, pick_design, call_mist_init, etc.). Pass it on every subsequent mist_* call to keep the same session."),conversationId:M.string().optional().describe("Returned by a previous mist_plan call with status 'clarify' or 'running'. Pass it back alone (no description) to poll an in-flight discovery call; pass with answers to submit responses."),answers:M.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("[")&&!e.startsWith("{"))return t;try{return JSON.parse(e)}catch{return t}},M.union([M.record(M.string()),M.array(M.object({question:M.string().optional(),decisionKey:M.string().optional(),answer:M.string()}))]).optional()).describe("User's answers to the clarifying questions. Pass an ARRAY of { question, decisionKey, answer } objects directly \u2014 do NOT stringify it as JSON. The schema also accepts a { '<question text>': '<answer label>' } object map for one-question-per-decisionKey rounds. Strings that look like JSON arrays/objects are auto-parsed for resilience."),existingPlan:M.record(M.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:M.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:M.string().optional().describe("Fork from a shared template. Pass the share token (from a mistflow.ai/t/... URL) to clone that project's plan into your workspace."),remixDescription:M.string().optional().describe("Optional remix request when forking a template. Describes how you want the template to be different. E.g. 'Make it for tracking books instead of habits, add a search feature.' Only used with templateToken."),autonomous:M.boolean().optional().describe("DANGER \u2014 only set this to `true` when the user has EXPLICITLY asked to skip discovery questions (phrases like 'no questions', 'just build it', 'autonomous mode', 'don't ask'). Default is `false` and should stay that way in every other case. Do NOT set autonomous=true as a retry strategy after a plan-gen failure \u2014 it doesn't make things more reliable, it just removes the user's control over discovery answers (roles, integrations, auth model, etc.) and Sonnet ends up guessing. If a plan call fails, retry the SAME call with the same parameters, not a more aggressive one. Do NOT set autonomous=true to speed things up \u2014 the server already runs plan-gen in the background and polls, so there is no speed benefit. When set, skips the clarify round and generates the plan straight from the description. The user loses the chance to pick any option."),language:M.string().optional().describe("UI language for the app. All user-facing text, labels, buttons, and content will be generated in this language. Use the language name in English (e.g. 'Spanish', 'French', 'Arabic', 'Japanese'). Defaults to English if not specified."),brandMentioned:M.boolean().optional().describe("Set to true ONLY when the user's original request explicitly invoked Mistflow by name (e.g. 'build me a CRM using mist', 'make a todo app with mistflow'). Skips the existing-project confirmation gate because the user clearly wants Mistflow. Do NOT set this for generic 'build me X' requests. Do NOT infer this \u2014 only set it when the user literally typed 'mist' or 'mistflow'."),confirmToken:M.string().optional().describe("The token returned in a previous mist_plan response with status 'confirm_new_project'. Only pass this AFTER asking the user via AskUserQuestion and they chose to scaffold a new Mistflow app in an existing-project directory. The token is bound to the projectPath and description \u2014 you must pass the SAME description AND projectPath on the retry."),urlChoice:M.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers."),designConversationId:M.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass this ONLY on the SUBMIT call after the user has picked a direction \u2014 i.e. ALWAYS together with `designDirection`. Do NOT include it on polling calls (status: 'rendering_directions' / 'design_clarify_pending') \u2014 for polling, send only `{ projectPath, conversationId }`. Including `designConversationId` without `designDirection` makes the backend respond 'you passed designConversationId but no designDirection' and wastes a round-trip. Decision rule: if the user has not yet typed/clicked a pick, omit this field; if they have, include both this field AND designDirection together in the same call."),designDirection:M.object({id:M.string().optional(),name:M.string().optional(),summary:M.string().optional(),heroHeadline:M.string().optional(),ctaText:M.string().optional(),bodySample:M.string().optional(),fontsHint:M.string().optional(),fonts:M.object({display:M.string(),body:M.string()}).partial().optional(),colorMood:M.string().optional(),colors:M.object({bg:M.string(),fg:M.string(),accent:M.string()}).partial().optional(),heroTreatment:M.string().optional(),shapeLang:M.string().optional(),texture:M.string().optional(),decorationHint:M.string().optional(),custom:M.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass ONLY the minimal shape: (a) `{ id: '<short-kebab-id-from-directionRefs>' }` when the user picked one of the proposed options \u2014 copy the id verbatim from `directionRefs[].id`, e.g. 'morning-paper' or 'quiet-utility'; or (b) `{ custom: '<the user\\'s exact words>' }` + `userConfirmedCustom: true` when the user typed their own description. Do NOT pass the full direction object (name, summary, fonts, colors, hero_headline, body_sample, etc.) \u2014 those fields are ignored and may exceed backend length limits, causing 422 rejections. ID values are short kebab-case strings (\u2264256 chars). Custom descriptions are user-typed prose (\u22644000 chars). Anything longer is wrong."),userConfirmedCustom:M.boolean().optional().describe("Set true ONLY when the user themselves typed a custom direction (via AskUserQuestion 'Other' or by explicitly describing the look in the chat). Required when submitting designDirection: { custom: ... } if the backend has real directions cached \u2014 the server rejects custom submissions otherwise to stop the AI from silently bypassing the picker. NEVER set this true unless the words in `custom` came directly from the user."),forceNew:M.boolean().optional().describe("Set to true ONLY after the user has explicitly chosen 'start fresh' from a previous mist_plan response with status 'resume_offer'. Suppresses the resume-offer check and lets a new session start even when this machine has unfinished work in flight. Do NOT set this preemptively on the first call \u2014 the resume-offer check needs to run so the user gets the chance to pick up where they left off.")});ai={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist'). Clear new-app requests inside an existing non-Mistflow repo are scaffolded into a remembered child directory; Mistflow does not edit the surrounding codebase.","",`DESIGN REFERENCES (screenshots, Figma, brand names): if the user drags a screenshot, pastes a Figma URL, or names a brand to match ("make it feel like Linear"), use your native vision/knowledge to extract design tokens and submit them via designDirection: { custom: '<your description>', ...extracted_tokens } with userConfirmedCustom: true. The flag is required because the user supplied the reference; without it the server rejects the submission to stop AIs from inventing custom directions. Full flow at docs/design-references.md.`,"","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). For clear new-app requests it automatically creates and remembers a child scaffold directory. For ambiguous requests, it returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token from the response. Do not change projectPath to the suggested child path; Mistflow stores that target for mist_init.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_init with the returned planId. If the response includes scaffoldTargetPath you do not need to pass path; mist_init loads it from the cached plan. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","SESSIONID FLOW (dumb-ai-proof, when the response includes sessionId): keep the sessionId and pass it on every subsequent mist_* call. Calling mist_plan with just { sessionId, projectPath } polls GET /api/sessions/{id}/next and returns the next instruction (wait | ask_user | pick_design | review_mockup | call_mist_init | call_mist_install | call_mist_implement | call_mist_build | call_mist_deploy | call_mist_qa | done). Do exactly what the instruction says \u2014 don't branch on raw state. The backend owns routing; the host relays.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. The aesthetic (fonts, colors, motion) is decided by the design-direction picker step \u2014 the host AI doesn't pick a catalog ID."].join(`
2074
+ `),inputSchema:yd,handler:_d}});function Pd(t){let e=t.match(/^v?(\d+)\.(\d+)\.(\d+)/);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null}function zt(t=process.version){let e=Pd(t);return!e||e.major>=23?!0:e.major===22?e.minor>=12:e.major===20?e.minor>=19:!1}function Id(t=process.execPath){return t.includes("Library/pnpm/")||t.includes("AppData\\pnpm\\")||t.includes("/.pnpm/")?"pnpm":t.includes("/.fnm/")||process.env.FNM_DIR?"fnm":process.env.NVM_DIR||t.includes("/.nvm/")?"nvm":process.env.VOLTA_HOME||t.includes("/.volta/")?"volta":t.startsWith("/opt/homebrew/")||t.startsWith("/usr/local/")?"brew":t==="/usr/bin/node"?"system":"unknown"}function At(t=process.version,e=Id()){let r={pnpm:"Run: pnpm env use --global 22.12.0",fnm:"Run: fnm install 22.12 && fnm use 22.12",nvm:"Run: nvm install 22.12 && nvm use 22.12",volta:"Run: volta install node@22.12",brew:"Run: brew install node@22 && brew link node@22 --force --overwrite",system:"Install Node 22.12+ from https://nodejs.org/download",unknown:"Install Node 22.12+ from https://nodejs.org/download"};return[`OpenNext/Cloudflare builds require Node 20.19+, 22.12+, or 23+. The current MCP process is running ${t}.`,r[e],"Then quit and reopen your IDE so the MCP picks up the new Node."].join(`
2075
+ `)}var er=_(()=>{"use strict"});var tr,ds=_(()=>{tr="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n"});var nr,ps=_(()=>{nr=`# Landing Page Rules
2076
2076
 
2077
2077
  These rules apply to every landing page. They are non-negotiable.
2078
2078
 
@@ -2486,29 +2486,29 @@ app/
2486
2486
  \`\`\`
2487
2487
 
2488
2488
  Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
2489
- `});import{existsSync as Ad,readFileSync as Rd,writeFileSync as Ed}from"fs";import{join as li}from"path";function ps(t){return t?Nd[t]??"\u23ED\uFE0F":"\u23ED\uFE0F"}function us(t){return t.name??t.title??`Step ${t.number}`}function ci(t){return t.entity??t.name??"Unknown"}function Od(t){let e=t.fields??[];return e.length===0?"":typeof e[0]=="string"?e.join(", "):e.map(r=>r.name).filter(Boolean).join(", ")}function jd(t){let e=[],r=t.plan,n=(t.name??r?.name??"App").split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ");e.push(`# ${n}`),e.push(""),e.push("Per-app orientation doc for host AIs editing this Mistflow-scaffolded codebase. Pairs with AGENTS.md (stack methodology) and DESIGN.md (aesthetic). Auto-regenerated by mist_init, mist_implement, and mist_deploy."),e.push("");let i=r?.summary??r?.description;if(i){if(e.push("## What this is"),e.push(""),e.push(i),r?.audienceType&&(e.push(""),e.push(`Audience: **${r.audienceType}**.`)),r?.design?.archetype){let c=r.design.tone?` (${r.design.tone} tone)`:"";e.push(`Aesthetic: **${r.design.archetype}**${c} \u2014 see DESIGN.md.`)}e.push("")}let o=r?.steps??[];if(o.length>0){e.push("## Build progress"),e.push("");let c=o.filter(d=>d.status==="completed"||d.status==="done"),u=o.filter(d=>d.status==="in_progress"),h=o.filter(d=>d.status!=="completed"&&d.status!=="done"&&d.status!=="in_progress");if(c.length>0){e.push(`**Done (${c.length}/${o.length}):**`);for(let d of c)e.push(`- ${ps(d.status)} ${us(d)}`);e.push("")}if(u.length>0){e.push("**In progress:**");for(let d of u)e.push(`- ${ps(d.status)} ${us(d)}`);e.push("")}if(h.length>0){e.push("**Planned next:**");for(let d of h)e.push(`- ${ps(d.status)} ${us(d)}`);e.push("")}}let s=r?.dataModel??[];if(s.length>0){e.push("## Data model"),e.push("");for(let c of s){let u=Od(c);u?e.push(`- **${ci(c)}**(${u})`):e.push(`- **${ci(c)}**`)}e.push("")}let a=r?.integrations??[];if(a.length>0){e.push("## Active integrations"),e.push("");for(let c of a){let u=c.name??c.id??"integration";e.push(`- **${u}**`)}e.push(""),e.push('Per-integration patterns: load the matching skill via `mist_docs({ topic: "<id>-integration" })` or read `.claude/skills/<id>-integration/SKILL.md`.'),e.push("")}let l=t.deploy;return l?.url&&(e.push("## Deploy"),e.push(""),e.push(`- URL: ${l.url}`),l.completedAt&&e.push(`- Last deploy: ${l.completedAt}`),l.deploymentId&&e.push(`- Last deployment id: \`${l.deploymentId}\``),e.push("")),e.push("## For fresh state"),e.push(""),e.push("This file is a **snapshot** written at scaffold/implement/deploy time \u2014 it can lag the live state of the app by minutes. For authoritative state (current step statuses, env vars actually set, deployment history, runtime errors), call:"),e.push(""),e.push("```"),e.push('mist_project({ action: "get", projectPath })'),e.push("```"),e.push(""),e.join(`
2489
+ `});import{existsSync as Rd,readFileSync as Ed,writeFileSync as Nd}from"fs";import{join as ci}from"path";function us(t){return t?Od[t]??"\u23ED\uFE0F":"\u23ED\uFE0F"}function ms(t){return t.name??t.title??`Step ${t.number}`}function di(t){return t.entity??t.name??"Unknown"}function Dd(t){let e=t.fields??[];return e.length===0?"":typeof e[0]=="string"?e.join(", "):e.map(r=>r.name).filter(Boolean).join(", ")}function jd(t){let e=[],r=t.plan,n=(t.name??r?.name??"App").split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ");e.push(`# ${n}`),e.push(""),e.push("Per-app orientation doc for host AIs editing this Mistflow-scaffolded codebase. Pairs with AGENTS.md (stack methodology) and DESIGN.md (aesthetic). Auto-regenerated by mist_init, mist_implement, and mist_deploy."),e.push("");let i=r?.summary??r?.description;if(i){if(e.push("## What this is"),e.push(""),e.push(i),r?.audienceType&&(e.push(""),e.push(`Audience: **${r.audienceType}**.`)),r?.design?.archetype){let c=r.design.tone?` (${r.design.tone} tone)`:"";e.push(`Aesthetic: **${r.design.archetype}**${c} \u2014 see DESIGN.md.`)}e.push("")}let o=r?.steps??[];if(o.length>0){e.push("## Build progress"),e.push("");let c=o.filter(u=>u.status==="completed"||u.status==="done"),m=o.filter(u=>u.status==="in_progress"),p=o.filter(u=>u.status!=="completed"&&u.status!=="done"&&u.status!=="in_progress");if(c.length>0){e.push(`**Done (${c.length}/${o.length}):**`);for(let u of c)e.push(`- ${us(u.status)} ${ms(u)}`);e.push("")}if(m.length>0){e.push("**In progress:**");for(let u of m)e.push(`- ${us(u.status)} ${ms(u)}`);e.push("")}if(p.length>0){e.push("**Planned next:**");for(let u of p)e.push(`- ${us(u.status)} ${ms(u)}`);e.push("")}}let s=r?.dataModel??[];if(s.length>0){e.push("## Data model"),e.push("");for(let c of s){let m=Dd(c);m?e.push(`- **${di(c)}**(${m})`):e.push(`- **${di(c)}**`)}e.push("")}let a=r?.integrations??[];if(a.length>0){e.push("## Active integrations"),e.push("");for(let c of a){let m=c.name??c.id??"integration";e.push(`- **${m}**`)}e.push(""),e.push('Per-integration patterns: load the matching skill via `mist_docs({ topic: "<id>-integration" })` or read `.claude/skills/<id>-integration/SKILL.md`.'),e.push("")}let l=t.deploy;return l?.url&&(e.push("## Deploy"),e.push(""),e.push(`- URL: ${l.url}`),l.completedAt&&e.push(`- Last deploy: ${l.completedAt}`),l.deploymentId&&e.push(`- Last deployment id: \`${l.deploymentId}\``),e.push("")),e.push("## For fresh state"),e.push(""),e.push("This file is a **snapshot** written at scaffold/implement/deploy time \u2014 it can lag the live state of the app by minutes. For authoritative state (current step statuses, env vars actually set, deployment history, runtime errors), call:"),e.push(""),e.push("```"),e.push('mist_project({ action: "get", projectPath })'),e.push("```"),e.push(""),e.join(`
2490
2490
  `).trimEnd()+`
2491
- `}function zt(t){try{let e=li(t,"mistflow.json");if(!Ad(e))return;let r=Rd(e,"utf-8"),n=JSON.parse(r),i=jd(n);Ed(li(t,"PROJECT.md"),i,"utf-8")}catch{}}var Nd,nr=P(()=>{"use strict";Nd={completed:"\u2705",done:"\u2705",in_progress:"\u{1F7E1}",pending:"\u23ED\uFE0F",skipped:"\u23ED\uFE0F"}});function di(t){if(!t)return"Item";let e=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return e.length===0?"Item":e.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}function Dd(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function Md(t){let e=di(t);return e.charAt(0).toLowerCase()+e.slice(1)}function hs(){return["# Integration contracts","","This directory holds the single source of truth for every API shape in","this app. Frontend code and backend routes both import from here, so","drift becomes a compile error instead of a silent runtime bug.","","## The convention","","Every entity defined in `db/schema.ts` MUST have a matching contract","file in this directory. Each contract file exports three things:","","- `<Entity>Schema` \u2014 the Zod schema for reading the entity (derived from"," the Drizzle table via `createSelectSchema`).","- `Create<Entity>Input` \u2014 the Zod schema for creating a new row"," (derived via `createInsertSchema`, typically with `id` and"," `createdAt` omitted).","- `<Entity>` \u2014 the inferred TypeScript type from `<Entity>Schema`.","","File name is the kebab-case singular of the entity, e.g. `habit.ts`,","`blog-post.ts`. One entity per file.","","## Example","","```ts","// contracts/habit.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { habit } from "@/db/schema";',"","export const HabitSchema = createSelectSchema(habit);","export type Habit = z.infer<typeof HabitSchema>;","","export const CreateHabitInput = createInsertSchema(habit).omit({"," id: true,"," createdAt: true,","});","export type CreateHabitInput = z.infer<typeof CreateHabitInput>;","```","","## Usage","","Frontend fetch and backend route should BOTH import from `contracts/`:","","```ts","// app/api/habits/route.ts",'import { CreateHabitInput, HabitSchema } from "@/contracts/habit";',"","export async function POST(request: Request) {"," const body = CreateHabitInput.parse(await request.json());"," const row = await db.insert(habit).values(body).returning();"," return Response.json(HabitSchema.parse(row[0]));","}","```","","```ts","// app/habits/page.tsx",'import type { Habit } from "@/contracts/habit";',"",'const res = await fetch("/api/habits");',"const habits: Habit[] = await res.json();","```","","## Adding a new entity","","1. Add the Drizzle table to `db/schema.ts`.","2. Create the matching `contracts/<entity>.ts` file using the template above.","3. Import from `contracts/` in every route, server action, and client"," component that touches the entity. Never inline the type.","","Run `mist_doctor` to check for entities that are missing a contract.",""].join(`
2492
- `)}function pi(){return["<!-- mist:contracts:start -->","## Integration contracts","","Every API shape in this app lives in `contracts/`. The directory holds","Zod schemas derived from `db/schema.ts` via `drizzle-zod`. Frontend and","backend both import from `contracts/`, so type drift becomes a compile","error instead of a runtime bug.","","### Rules for AI agents","","1. Every API route (`app/api/**/route.ts`) and server action MUST"," import its request + response types from `contracts/<entity>.ts`."," Never inline a Zod schema or a TypeScript type for an entity that"," already has a contract. Never `z.object({ ... })` inside a route"," handler for a known entity.","2. When you add a new entity to `db/schema.ts`, you MUST create the"," matching contract file BEFORE writing any route that uses it. Order"," matters: schema -> contract -> route.","3. Validate every request body with the contract's `.parse()` method."," If validation fails, return a 400 with the Zod error message \u2014 the"," contract is the boundary, not a decoration.","4. Validate every response body before returning it. Use the select"," schema's `.parse()` on the row(s) you read from the DB. This catches"," the case where the DB shape has drifted from the contract.","5. Client components that fetch an entity MUST import the inferred",' TypeScript type (`import type { Habit } from "@/contracts/habit"`)'," \u2014 never hand-write a duplicate type.","","### Contract file shape","","```ts","// contracts/<entity>.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { entityTable } from "@/db/schema";',"","export const EntitySchema = createSelectSchema(entityTable);","export type Entity = z.infer<typeof EntitySchema>;","","export const CreateEntityInput = createInsertSchema(entityTable).omit({"," id: true,"," createdAt: true,","});","export type CreateEntityInput = z.infer<typeof CreateEntityInput>;","```","","### Example route using a contract","","```ts","// app/api/entities/route.ts",'import { db } from "@/lib/db";','import { entityTable } from "@/db/schema";','import { CreateEntityInput, EntitySchema } from "@/contracts/entity";',"","export async function POST(request: Request) {"," const body = CreateEntityInput.parse(await request.json());"," const [row] = await db.insert(entityTable).values(body).returning();"," return Response.json(EntitySchema.parse(row));","}","```","","Run `mist_doctor` to check every entity in `db/schema.ts` has a","contract file. Missing contracts are reported as warnings.","<!-- mist:contracts:end -->",""].join(`
2493
- `)}function gs(t){let e=pi();if(t.includes(ms)){let n=t.indexOf(ms),i=ui,o=t.indexOf(i,n);if(o===-1)return t.slice(0,n)+e;let s=t.slice(o+i.length);return t.slice(0,n)+e+s.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
2491
+ `}function Ht(t){try{let e=ci(t,"mistflow.json");if(!Rd(e))return;let r=Ed(e,"utf-8"),n=JSON.parse(r),i=jd(n);Nd(ci(t,"PROJECT.md"),i,"utf-8")}catch{}}var Od,rr=_(()=>{"use strict";Od={completed:"\u2705",done:"\u2705",in_progress:"\u{1F7E1}",pending:"\u23ED\uFE0F",skipped:"\u23ED\uFE0F"}});function pi(t){if(!t)return"Item";let e=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return e.length===0?"Item":e.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}function Md(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function Ld(t){let e=pi(t);return e.charAt(0).toLowerCase()+e.slice(1)}function gs(){return["# Integration contracts","","This directory holds the single source of truth for every API shape in","this app. Frontend code and backend routes both import from here, so","drift becomes a compile error instead of a silent runtime bug.","","## The convention","","Every entity defined in `db/schema.ts` MUST have a matching contract","file in this directory. Each contract file exports three things:","","- `<Entity>Schema` \u2014 the Zod schema for reading the entity (derived from"," the Drizzle table via `createSelectSchema`).","- `Create<Entity>Input` \u2014 the Zod schema for creating a new row"," (derived via `createInsertSchema`, typically with `id` and"," `createdAt` omitted).","- `<Entity>` \u2014 the inferred TypeScript type from `<Entity>Schema`.","","File name is the kebab-case singular of the entity, e.g. `habit.ts`,","`blog-post.ts`. One entity per file.","","## Example","","```ts","// contracts/habit.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { habit } from "@/db/schema";',"","export const HabitSchema = createSelectSchema(habit);","export type Habit = z.infer<typeof HabitSchema>;","","export const CreateHabitInput = createInsertSchema(habit).omit({"," id: true,"," createdAt: true,","});","export type CreateHabitInput = z.infer<typeof CreateHabitInput>;","```","","## Usage","","Frontend fetch and backend route should BOTH import from `contracts/`:","","```ts","// app/api/habits/route.ts",'import { CreateHabitInput, HabitSchema } from "@/contracts/habit";',"","export async function POST(request: Request) {"," const body = CreateHabitInput.parse(await request.json());"," const row = await db.insert(habit).values(body).returning();"," return Response.json(HabitSchema.parse(row[0]));","}","```","","```ts","// app/habits/page.tsx",'import type { Habit } from "@/contracts/habit";',"",'const res = await fetch("/api/habits");',"const habits: Habit[] = await res.json();","```","","## Adding a new entity","","1. Add the Drizzle table to `db/schema.ts`.","2. Create the matching `contracts/<entity>.ts` file using the template above.","3. Import from `contracts/` in every route, server action, and client"," component that touches the entity. Never inline the type.","","Run `mist_doctor` to check for entities that are missing a contract.",""].join(`
2492
+ `)}function ui(){return["<!-- mist:contracts:start -->","## Integration contracts","","Every API shape in this app lives in `contracts/`. The directory holds","Zod schemas derived from `db/schema.ts` via `drizzle-zod`. Frontend and","backend both import from `contracts/`, so type drift becomes a compile","error instead of a runtime bug.","","### Rules for AI agents","","1. Every API route (`app/api/**/route.ts`) and server action MUST"," import its request + response types from `contracts/<entity>.ts`."," Never inline a Zod schema or a TypeScript type for an entity that"," already has a contract. Never `z.object({ ... })` inside a route"," handler for a known entity.","2. When you add a new entity to `db/schema.ts`, you MUST create the"," matching contract file BEFORE writing any route that uses it. Order"," matters: schema -> contract -> route.","3. Validate every request body with the contract's `.parse()` method."," If validation fails, return a 400 with the Zod error message \u2014 the"," contract is the boundary, not a decoration.","4. Validate every response body before returning it. Use the select"," schema's `.parse()` on the row(s) you read from the DB. This catches"," the case where the DB shape has drifted from the contract.","5. Client components that fetch an entity MUST import the inferred",' TypeScript type (`import type { Habit } from "@/contracts/habit"`)'," \u2014 never hand-write a duplicate type.","","### Contract file shape","","```ts","// contracts/<entity>.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { entityTable } from "@/db/schema";',"","export const EntitySchema = createSelectSchema(entityTable);","export type Entity = z.infer<typeof EntitySchema>;","","export const CreateEntityInput = createInsertSchema(entityTable).omit({"," id: true,"," createdAt: true,","});","export type CreateEntityInput = z.infer<typeof CreateEntityInput>;","```","","### Example route using a contract","","```ts","// app/api/entities/route.ts",'import { db } from "@/lib/db";','import { entityTable } from "@/db/schema";','import { CreateEntityInput, EntitySchema } from "@/contracts/entity";',"","export async function POST(request: Request) {"," const body = CreateEntityInput.parse(await request.json());"," const [row] = await db.insert(entityTable).values(body).returning();"," return Response.json(EntitySchema.parse(row));","}","```","","Run `mist_doctor` to check every entity in `db/schema.ts` has a","contract file. Missing contracts are reported as warnings.","<!-- mist:contracts:end -->",""].join(`
2493
+ `)}function fs(t){let e=ui();if(t.includes(hs)){let n=t.indexOf(hs),i=mi,o=t.indexOf(i,n);if(o===-1)return t.slice(0,n)+e;let s=t.slice(o+i.length);return t.slice(0,n)+e+s.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
2494
2494
 
2495
- `+e}function fs(t,e){let r=di(t),n=e??Md(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${n} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${r}Schema = createSelectSchema(${n});`,`export type ${r} = z.infer<typeof ${r}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${r}Input = createInsertSchema(${n}).omit({`," id: true,"," createdAt: true,","});",`export type Create${r}Input = z.infer<typeof Create${r}Input>;`,""].join(`
2496
- `)}function ys(t){return`contracts/${Dd(t)}.ts`}var ms,ui,bs=P(()=>{"use strict";ms="<!-- mist:contracts:start -->",ui="<!-- mist:contracts:end -->"});import{z as Ht}from"zod";import{existsSync as Ne,mkdirSync as Wt,rmSync as Ld,writeFileSync as Ze,readFileSync as Gt,readdirSync as gi,copyFileSync as Ud}from"fs";import{join as he,resolve as fi,dirname as fn,isAbsolute as $d}from"path";import{homedir as Fd}from"os";import{spawn as $g}from"child_process";import{randomBytes as qd}from"crypto";import{simpleGit as zd}from"simple-git";function Bd(t){let e=he(Fd(),".mistflow","plans",`${t}.json`);if(!Ne(e))return null;try{let r=JSON.parse(Gt(e,"utf-8"));return r.plan?{plan:r.plan,...typeof r.scaffoldTargetPath=="string"?{scaffoldTargetPath:r.scaffoldTargetPath}:{}}:null}catch{return null}}function Wd(t){let e=fn(fi(t)),r=10,n=0;for(;n<r&&e!==fn(e);){if(Ne(he(e,"pnpm-workspace.yaml"))||Ne(he(e,"lerna.json"))||Ne(he(e,"pnpm-lock.yaml"))||Ne(he(e,"package-lock.json"))||Ne(he(e,"yarn.lock"))||Ne(he(e,"bun.lockb"))||Ne(he(e,"bun.lock")))return e;let i=he(e,"package.json");if(Ne(i))try{if(JSON.parse(Gt(i,"utf-8")).workspaces)return e}catch{}e=fn(e),n++}return null}function N(t,e,r){let n=he(t,e);Wt(fn(n),{recursive:!0}),Ze(n,r)}function Yd(t,e){N(t,".cursor/rules/mistflow.mdc",Vd),N(t,".github/copilot-instructions.md",Kd),N(t,".continue/rules/mistflow.md",rr),N(t,"CONVENTIONS.md",rr),N(t,".aider.conf.yml",Jd)}function Qd(t){if(!t.startsWith(`---
2495
+ `+e}function ys(t,e){let r=pi(t),n=e??Ld(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${n} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${r}Schema = createSelectSchema(${n});`,`export type ${r} = z.infer<typeof ${r}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${r}Input = createInsertSchema(${n}).omit({`," id: true,"," createdAt: true,","});",`export type Create${r}Input = z.infer<typeof Create${r}Input>;`,""].join(`
2496
+ `)}function bs(t){return`contracts/${Md(t)}.ts`}var hs,mi,ws=_(()=>{"use strict";hs="<!-- mist:contracts:start -->",mi="<!-- mist:contracts:end -->"});import{z as Wt}from"zod";import{existsSync as De,mkdirSync as Gt,rmSync as Ud,writeFileSync as et,readFileSync as Vt,readdirSync as fi,copyFileSync as $d}from"fs";import{join as de,resolve as yi,dirname as yn,isAbsolute as Fd}from"path";import{homedir as qd}from"os";import{spawn as Fg}from"child_process";import{randomBytes as Bd}from"crypto";import{simpleGit as Hd}from"simple-git";function zd(t){let e=de(qd(),".mistflow","plans",`${t}.json`);if(!De(e))return null;try{let r=JSON.parse(Vt(e,"utf-8"));return r.plan?{plan:r.plan,...typeof r.scaffoldTargetPath=="string"?{scaffoldTargetPath:r.scaffoldTargetPath}:{}}:null}catch{return null}}function Gd(t){let e=yn(yi(t)),r=10,n=0;for(;n<r&&e!==yn(e);){if(De(de(e,"pnpm-workspace.yaml"))||De(de(e,"lerna.json"))||De(de(e,"pnpm-lock.yaml"))||De(de(e,"package-lock.json"))||De(de(e,"yarn.lock"))||De(de(e,"bun.lockb"))||De(de(e,"bun.lock")))return e;let i=de(e,"package.json");if(De(i))try{if(JSON.parse(Vt(i,"utf-8")).workspaces)return e}catch{}e=yn(e),n++}return null}function O(t,e,r){let n=de(t,e);Gt(yn(n),{recursive:!0}),et(n,r)}function Qd(t,e){O(t,".cursor/rules/mistflow.mdc",Kd),O(t,".github/copilot-instructions.md",Jd),O(t,".continue/rules/mistflow.md",sr),O(t,"CONVENTIONS.md",sr),O(t,".aider.conf.yml",Yd)}function Xd(t){if(!t.startsWith(`---
2497
2497
  `))return{frontmatter:null,body:t};let e=t.indexOf(`
2498
2498
  ---
2499
2499
  `,4);if(e<0)return{frontmatter:null,body:t};let r=t.slice(4,e),n={};for(let i of r.split(`
2500
- `)){let o=i.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/);if(!o)continue;let[,s,a]=o;(s==="name"||s==="description")&&(n[s]=a.trim())}return{frontmatter:n,body:t.slice(e+5).replace(/^\n+/,"")}}function Xd(t,e){for(let[r,n]of Object.entries(e)){if(!n||n.trim().length===0)continue;let{frontmatter:i,body:o}=Qd(n),s=i?.name??r,a=i?.description??`Mistflow skill: ${r}`,l=`---
2500
+ `)){let o=i.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/);if(!o)continue;let[,s,a]=o;(s==="name"||s==="description")&&(n[s]=a.trim())}return{frontmatter:n,body:t.slice(e+5).replace(/^\n+/,"")}}function Zd(t,e){for(let[r,n]of Object.entries(e)){if(!n||n.trim().length===0)continue;let{frontmatter:i,body:o}=Xd(n),s=i?.name??r,a=i?.description??`Mistflow skill: ${r}`,l=`---
2501
2501
  name: ${s}
2502
2502
  description: ${a}
2503
2503
  ---
2504
2504
 
2505
- `;N(t,`.claude/skills/${r}/SKILL.md`,l+o);let c=`---
2505
+ `;O(t,`.claude/skills/${r}/SKILL.md`,l+o);let c=`---
2506
2506
  description: ${a}
2507
2507
  alwaysApply: false
2508
2508
  ---
2509
2509
 
2510
- `;N(t,`.cursor/rules/${r}.mdc`,c+o)}}function Zd(t){if(!Ne(t))return!0;let e;try{e=gi(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}function ep(t,e){let r=(e??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"new-app",n=he(t,r);return`${t} isn't empty, so we can't scaffold the project here without clobbering existing files. Retry mist_init with path: "${n}" (a subdirectory) \u2014 the user almost certainly meant "create a new app inside this folder," not "overwrite this folder." Confirm with the user once if you're not sure, but the suggested sub-path is usually right. (A leftover .mistflow/ from planning is fine \u2014 init preserves it.)`}function rp(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let r=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},i=r.split(`
2511
- `),o=null,s=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of i){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let d=a(c.slice(6).trim());(d==="dark"||d==="light")&&(n.theme=d);continue}let u=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(u){o=u[1],s=null;continue}if(c.length>0&&!c.startsWith(" ")&&!c.startsWith(" ")&&c.match(/^[a-zA-Z0-9_-]+:(\s|$)/)){o=null,s=null;continue}if(o==="typography"){let d=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(d){s=d[1].replace(/-/g,"_"),n.typography[s]={};continue}let v=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(v&&s){n.typography[s][v[1]]=a(v[2]);continue}}let h=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(h&&o){let d=h[1].replace(/-/g,"_"),v=a(h[2]);o==="colors"?n.colors[d]=v:o==="rounded"?n.rounded[d]=v:o==="spacing"&&(n.spacing[d]=v)}}return n}function sp(t,e){let r=t.colors,i=[["--color-background",r.background],["--color-foreground",r.on_background??r.on_surface],["--color-card",r.surface??r.background],["--color-card-foreground",r.on_surface??r.on_background],["--color-popover",r.surface??r.background],["--color-popover-foreground",r.on_surface??r.on_background],["--color-muted",r.surface_variant??r.outline_variant??r.outline],["--color-muted-foreground",r.on_surface_variant??r.outline],["--color-border",r.outline_variant??r.outline],["--color-input",r.outline_variant??r.outline],["--color-primary",r.primary],["--color-primary-foreground",r.on_primary],["--color-ring",r.primary],["--color-secondary",r.secondary],["--color-secondary-foreground",r.on_secondary],["--color-accent",r.secondary],["--color-accent-foreground",r.on_secondary],["--color-destructive",r.error],["--color-destructive-foreground",r.on_error],["--color-success",r.success],["--color-success-foreground",r.on_success],["--color-warning",r.warning],["--color-warning-foreground",r.on_warning],["--color-info",r.info??r.primary],["--color-info-foreground",r.on_info??r.on_primary]].filter(a=>typeof a[1]=="string").map(([a,l])=>` ${a}: ${l};`).join(`
2510
+ `;O(t,`.cursor/rules/${r}.mdc`,c+o)}}function ep(t){if(!De(t))return!0;let e;try{e=fi(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}function tp(t,e){let r=(e??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"new-app",n=de(t,r);return`${t} isn't empty, so we can't scaffold the project here without clobbering existing files. Retry mist_init with path: "${n}" (a subdirectory) \u2014 the user almost certainly meant "create a new app inside this folder," not "overwrite this folder." Confirm with the user once if you're not sure, but the suggested sub-path is usually right. (A leftover .mistflow/ from planning is fine \u2014 init preserves it.)`}function sp(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let r=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},i=r.split(`
2511
+ `),o=null,s=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of i){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let u=a(c.slice(6).trim());(u==="dark"||u==="light")&&(n.theme=u);continue}let m=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(m){o=m[1],s=null;continue}if(c.length>0&&!c.startsWith(" ")&&!c.startsWith(" ")&&c.match(/^[a-zA-Z0-9_-]+:(\s|$)/)){o=null,s=null;continue}if(o==="typography"){let u=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(u){s=u[1].replace(/-/g,"_"),n.typography[s]={};continue}let g=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(g&&s){n.typography[s][g[1]]=a(g[2]);continue}}let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(p&&o){let u=p[1].replace(/-/g,"_"),g=a(p[2]);o==="colors"?n.colors[u]=g:o==="rounded"?n.rounded[u]=g:o==="spacing"&&(n.spacing[u]=g)}}return n}function op(t,e){let r=t.colors,i=[["--color-background",r.background],["--color-foreground",r.on_background??r.on_surface],["--color-card",r.surface??r.background],["--color-card-foreground",r.on_surface??r.on_background],["--color-popover",r.surface??r.background],["--color-popover-foreground",r.on_surface??r.on_background],["--color-muted",r.surface_variant??r.outline_variant??r.outline],["--color-muted-foreground",r.on_surface_variant??r.outline],["--color-border",r.outline_variant??r.outline],["--color-input",r.outline_variant??r.outline],["--color-primary",r.primary],["--color-primary-foreground",r.on_primary],["--color-ring",r.primary],["--color-secondary",r.secondary],["--color-secondary-foreground",r.on_secondary],["--color-accent",r.secondary],["--color-accent-foreground",r.on_secondary],["--color-destructive",r.error],["--color-destructive-foreground",r.on_error],["--color-success",r.success],["--color-success-foreground",r.on_success],["--color-warning",r.warning],["--color-warning-foreground",r.on_warning],["--color-info",r.info??r.primary],["--color-info-foreground",r.on_info??r.on_primary]].filter(a=>typeof a[1]=="string").map(([a,l])=>` ${a}: ${l};`).join(`
2512
2512
  `),o=[` --radius-sm: ${t.rounded.sm??"0.25rem"};`,` --radius-md: ${t.rounded.md??e};`,` --radius-lg: ${t.rounded.lg??"0.5rem"};`,` --radius-xl: ${t.rounded.xl??"0.75rem"};`].join(`
2513
2513
  `);return`@import "tailwindcss";
2514
2514
  @import "tw-animate-css";
@@ -2565,11 +2565,11 @@ ${o}
2565
2565
 
2566
2566
  button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
2567
2567
  button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
2568
- `}function op(t,e){let r=t?.borderRadius??"subtle",n=tp[r]??"0.375rem";if(e){let o=rp(e);if(o)return sp(o,n)}return`@import "tailwindcss";
2568
+ `}function ip(t,e){let r=t?.borderRadius??"subtle",n=np[r]??"0.375rem";if(e){let o=sp(e);if(o)return op(o,n)}return`@import "tailwindcss";
2569
2569
  @import "tw-animate-css";
2570
2570
 
2571
2571
  @theme {
2572
- ${[...np.map(([o,s])=>` ${o}: ${s};`)," --radius-sm: 0.25rem;",` --radius-md: ${n};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
2572
+ ${[...rp.map(([o,s])=>` ${o}: ${s};`)," --radius-sm: 0.25rem;",` --radius-md: ${n};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
2573
2573
  `)}
2574
2574
  }
2575
2575
 
@@ -2619,7 +2619,7 @@ ${[...np.map(([o,s])=>` ${o}: ${s};`)," --radius-sm: 0.25rem;",` --radius-md:
2619
2619
 
2620
2620
  button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
2621
2621
  button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
2622
- `}function hi(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return mi[e]?mi[e]:e.replace(/\s+/g,"_")}function ip(t){return t?{english:"en",spanish:"es",french:"fr",german:"de",italian:"it",portuguese:"pt",dutch:"nl",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",arabic:"ar",hebrew:"he",hindi:"hi",turkish:"tr",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",thai:"th",vietnamese:"vi",indonesian:"id",malay:"ms",farsi:"fa",persian:"fa",czech:"cs",greek:"el",romanian:"ro",hungarian:"hu",ukrainian:"uk",bengali:"bn",tamil:"ta",telugu:"te",urdu:"ur"}[t.toLowerCase()]??"en":"en"}function lp(t,e,r){let n=t.replace(/[\\"`$]/g,""),i=ip(r),s=ap.has(i)?`lang="${i}" dir="rtl"`:`lang="${i}"`,a=e?.fonts?.heading,l=e?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
2622
+ `}function gi(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return hi[e]?hi[e]:e.replace(/\s+/g,"_")}function ap(t){return t?{english:"en",spanish:"es",french:"fr",german:"de",italian:"it",portuguese:"pt",dutch:"nl",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",arabic:"ar",hebrew:"he",hindi:"hi",turkish:"tr",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",thai:"th",vietnamese:"vi",indonesian:"id",malay:"ms",farsi:"fa",persian:"fa",czech:"cs",greek:"el",romanian:"ro",hungarian:"hu",ukrainian:"uk",bengali:"bn",tamil:"ta",telugu:"te",urdu:"ur"}[t.toLowerCase()]??"en":"en"}function cp(t,e,r){let n=t.replace(/[\\"`$]/g,""),i=ap(r),s=lp.has(i)?`lang="${i}" dir="rtl"`:`lang="${i}"`,a=e?.fonts?.heading,l=e?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
2623
2623
  import { DM_Sans } from "next/font/google";
2624
2624
  import { Toaster } from "sonner";
2625
2625
  import "./globals.css";
@@ -2635,7 +2635,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2635
2635
  </html>
2636
2636
  );
2637
2637
  }
2638
- `;let c=hi(a??l),u=hi(l??a);return c===u?`import type { Metadata } from "next";
2638
+ `;let c=gi(a??l),m=gi(l??a);return c===m?`import type { Metadata } from "next";
2639
2639
  import { ${c} } from "next/font/google";
2640
2640
  import { Toaster } from "sonner";
2641
2641
  import "./globals.css";
@@ -2652,12 +2652,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2652
2652
  );
2653
2653
  }
2654
2654
  `:`import type { Metadata } from "next";
2655
- import { ${c}, ${u} } from "next/font/google";
2655
+ import { ${c}, ${m} } from "next/font/google";
2656
2656
  import { Toaster } from "sonner";
2657
2657
  import "./globals.css";
2658
2658
 
2659
2659
  const heading = ${c}({ subsets: ["latin"], variable: "--font-heading" });
2660
- const body = ${u}({ subsets: ["latin"], variable: "--font-body" });
2660
+ const body = ${m}({ subsets: ["latin"], variable: "--font-body" });
2661
2661
 
2662
2662
  export const metadata: Metadata = { title: "${n}", description: "Built with Mistflow" };
2663
2663
 
@@ -2668,59 +2668,59 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2668
2668
  </html>
2669
2669
  );
2670
2670
  }
2671
- `}function yn(t,...e){let r=JSON.stringify(t).toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function ws(t,...e){return(Array.isArray(t.integrations)?t.integrations:[]).some(n=>{let i=JSON.stringify(n).toLowerCase();return e.some(o=>i.includes(o.toLowerCase()))})}function cp(t){return t.realMoney===!1?!1:t.realMoney===!0||ws(t,"stripe")||yn(t,"stripe","payment","billing","subscription","checkout")}function dp(t,e){return e==="none"?ws(t,"resend","email"):e==="email"||e==="invite-only"||ws(t,"resend","email")||yn(t,"email notification","email reminder","send email","resend")}function vs(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[r,n]of Object.entries(pp))if(e.includes(r))return n;return"Circle"}function bn(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function up(t){if(t.authModel==="none")return null;let e=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed","/images","/assets"];if(t.publicPages&&Array.isArray(t.publicPages))for(let o of t.publicPages){if(typeof o!="string"||o.length<1)continue;let s=o.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!s)continue;let a=s.startsWith("/")?s:"/"+s;e.includes(a)||e.push(a)}let r=e.filter(o=>o==="/"),n=e.filter(o=>o!=="/"),i=[];i.push('import { NextRequest, NextResponse } from "next/server";'),i.push(""),i.push("const PUBLIC_PREFIXES = [");for(let o of n)i.push(' "'+o+'",');return i.push("];"),i.push(""),r.length>0&&(i.push('const PUBLIC_EXACT = ["'+r.join('", "')+'"];'),i.push("")),i.push("export function middleware(req: NextRequest) {"),i.push(" const { pathname, search } = req.nextUrl;"),i.push(""),r.length>0&&i.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),i.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),i.push(""),i.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),i.push(" if (!token) {"),i.push(' const loginUrl = new URL("/login", req.url);'),i.push(" const params = new URLSearchParams(search);"),i.push(' for (const key of ["verified", "error"]) {'),i.push(" const v = params.get(key);"),i.push(" if (v) loginUrl.searchParams.set(key, v);"),i.push(" }"),i.push(" return NextResponse.redirect(loginUrl);"),i.push(" }"),i.push(""),i.push(" return NextResponse.next();"),i.push("}"),i.push(""),i.push("export const config = {"),i.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),i.push("};"),i.push(""),i.join(`
2672
- `)}function mp(t){if(t.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],n=(t.pages??[]).filter(l=>{let c=l.path??l.route??"";return c==="/"||c===""||c.includes("[")||c.replace(/^\//,"").split("/").length>1?!1:!e.some(h=>c.startsWith(h))}).map(l=>{let c=l.path??l.route??"",u=c.startsWith("/")?c:"/"+c,h=l.name??bn(c.replace(/^\//,"")),d=vs(h);return{label:h,href:u,icon:d}});n.some(l=>l.href==="/dashboard")||n.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let i=t.authModel==="none",o=[...new Set(n.map(l=>l.icon))];i||o.push("LogOut");let s=bn(t.name);if(t.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),i||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+o.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let c of n)l.push(' { label: "'+c.label+'", href: "'+c.href+'", icon: '+c.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+s+"</span>"),l.push(' <div className="flex items-center gap-1">'),l.push(" {NAV_ITEMS.map((item) => ("),l.push(" <Link"),l.push(" key={item.href}"),l.push(" href={item.href}"),l.push(' aria-current={pathname === item.href ? "page" : undefined}'),l.push(" className={cn("),l.push(' "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",'),l.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground"'),l.push(" )}"),l.push(" >"),l.push(' <item.icon className="h-4 w-4" />'),l.push(" {item.label}"),l.push(" </Link>"),l.push(" ))}"),l.push(" </div>"),l.push(" </div>"),i?l.push(' <span className="text-sm text-muted-foreground">{user.name}</span>'):(l.push(' <div className="flex items-center gap-2">'),l.push(' <span className="text-sm text-muted-foreground">{user.email}</span>'),l.push(" <Button"),l.push(' variant="ghost"'),l.push(' size="sm"'),l.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),l.push(" >"),l.push(' <LogOut className="h-4 w-4" />'),l.push(" </Button>"),l.push(" </div>")),l.push(" </div>"),l.push(" </nav>"),l.push(" );"),l.push("}"),l.push(""),{path:"components/topnav.tsx",content:l.join(`
2671
+ `}function bn(t,...e){let r=JSON.stringify(t).toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function vs(t,...e){return(Array.isArray(t.integrations)?t.integrations:[]).some(n=>{let i=JSON.stringify(n).toLowerCase();return e.some(o=>i.includes(o.toLowerCase()))})}function dp(t){return t.realMoney===!1?!1:t.realMoney===!0||vs(t,"stripe")||bn(t,"stripe","payment","billing","subscription","checkout")}function pp(t,e){return e==="none"?vs(t,"resend","email"):e==="email"||e==="invite-only"||vs(t,"resend","email")||bn(t,"email notification","email reminder","send email","resend")}function ks(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[r,n]of Object.entries(up))if(e.includes(r))return n;return"Circle"}function wn(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function mp(t){if(t.authModel==="none")return null;let e=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed","/images","/assets"];if(t.publicPages&&Array.isArray(t.publicPages))for(let o of t.publicPages){if(typeof o!="string"||o.length<1)continue;let s=o.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!s)continue;let a=s.startsWith("/")?s:"/"+s;e.includes(a)||e.push(a)}let r=e.filter(o=>o==="/"),n=e.filter(o=>o!=="/"),i=[];i.push('import { NextRequest, NextResponse } from "next/server";'),i.push(""),i.push("const PUBLIC_PREFIXES = [");for(let o of n)i.push(' "'+o+'",');return i.push("];"),i.push(""),r.length>0&&(i.push('const PUBLIC_EXACT = ["'+r.join('", "')+'"];'),i.push("")),i.push("export function middleware(req: NextRequest) {"),i.push(" const { pathname, search } = req.nextUrl;"),i.push(""),r.length>0&&i.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),i.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),i.push(""),i.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),i.push(" if (!token) {"),i.push(' const loginUrl = new URL("/login", req.url);'),i.push(" const params = new URLSearchParams(search);"),i.push(' for (const key of ["verified", "error"]) {'),i.push(" const v = params.get(key);"),i.push(" if (v) loginUrl.searchParams.set(key, v);"),i.push(" }"),i.push(" return NextResponse.redirect(loginUrl);"),i.push(" }"),i.push(""),i.push(" return NextResponse.next();"),i.push("}"),i.push(""),i.push("export const config = {"),i.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),i.push("};"),i.push(""),i.join(`
2672
+ `)}function hp(t){if(t.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],n=(t.pages??[]).filter(l=>{let c=l.path??l.route??"";return c==="/"||c===""||c.includes("[")||c.replace(/^\//,"").split("/").length>1?!1:!e.some(p=>c.startsWith(p))}).map(l=>{let c=l.path??l.route??"",m=c.startsWith("/")?c:"/"+c,p=l.name??wn(c.replace(/^\//,"")),u=ks(p);return{label:p,href:m,icon:u}});n.some(l=>l.href==="/dashboard")||n.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let i=t.authModel==="none",o=[...new Set(n.map(l=>l.icon))];i||o.push("LogOut");let s=wn(t.name);if(t.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),i||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+o.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let c of n)l.push(' { label: "'+c.label+'", href: "'+c.href+'", icon: '+c.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+s+"</span>"),l.push(' <div className="flex items-center gap-1">'),l.push(" {NAV_ITEMS.map((item) => ("),l.push(" <Link"),l.push(" key={item.href}"),l.push(" href={item.href}"),l.push(' aria-current={pathname === item.href ? "page" : undefined}'),l.push(" className={cn("),l.push(' "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",'),l.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground"'),l.push(" )}"),l.push(" >"),l.push(' <item.icon className="h-4 w-4" />'),l.push(" {item.label}"),l.push(" </Link>"),l.push(" ))}"),l.push(" </div>"),l.push(" </div>"),i?l.push(' <span className="text-sm text-muted-foreground">{user.name}</span>'):(l.push(' <div className="flex items-center gap-2">'),l.push(' <span className="text-sm text-muted-foreground">{user.email}</span>'),l.push(" <Button"),l.push(' variant="ghost"'),l.push(' size="sm"'),l.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),l.push(" >"),l.push(' <LogOut className="h-4 w-4" />'),l.push(" </Button>"),l.push(" </div>")),l.push(" </div>"),l.push(" </nav>"),l.push(" );"),l.push("}"),l.push(""),{path:"components/topnav.tsx",content:l.join(`
2673
2673
  `)}}let a=[];a.push('"use client";'),a.push(""),a.push('import { useState } from "react";'),a.push('import Link from "next/link";'),a.push('import { usePathname } from "next/navigation";'),i||a.push('import { authClient } from "@/lib/auth-client";'),a.push('import { Button } from "@/components/ui/button";'),a.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),a.push('import { cn } from "@/lib/utils";'),a.push("import { Menu, "+o.join(", ")+' } from "lucide-react";'),a.push(""),a.push("interface SidebarProps {"),a.push(" user: { name: string | null; email: string; role?: string | undefined };"),a.push("}"),a.push(""),a.push("const NAV_ITEMS = [");for(let l of n)a.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return a.push("];"),a.push(""),a.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),a.push(" return ("),a.push(" <>"),a.push(' <div className="flex h-14 items-center border-b px-4">'),a.push(' <span className="text-lg font-semibold">'+s+"</span>"),a.push(" </div>"),a.push(' <nav className="flex-1 space-y-1 p-2">'),a.push(" {NAV_ITEMS.map((item) => ("),a.push(" <Link"),a.push(" key={item.href}"),a.push(" href={item.href}"),a.push(" onClick={onNavigate}"),a.push(' aria-current={pathname === item.href ? "page" : undefined}'),a.push(" className={cn("),a.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),a.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),a.push(" )}"),a.push(" >"),a.push(' <item.icon className="h-4 w-4" />'),a.push(" {item.label}"),a.push(" </Link>"),a.push(" ))}"),a.push(" </nav>"),a.push(' <div className="border-t p-4">'),a.push(' <div className="flex items-center gap-3">'),a.push(' <div className="flex-1 truncate">'),a.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),a.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),a.push(" </div>"),i||(a.push(" <Button"),a.push(' variant="ghost"'),a.push(' size="icon"'),a.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),a.push(" >"),a.push(' <LogOut className="h-4 w-4" />'),a.push(" </Button>")),a.push(" </div>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),a.push("export default function Sidebar({ user }: SidebarProps) {"),a.push(" const pathname = usePathname();"),a.push(" const [open, setOpen] = useState(false);"),a.push(""),a.push(" return ("),a.push(" <>"),a.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),a.push(" <NavContent pathname={pathname} user={user} />"),a.push(" </aside>"),a.push(' <div className="sticky top-0 z-[var(--z-sticky)] flex h-14 items-center gap-3 border-b bg-card px-4 md:hidden">'),a.push(" <Sheet open={open} onOpenChange={setOpen}>"),a.push(" <SheetTrigger asChild>"),a.push(' <Button variant="ghost" size="icon" className="-ml-2">'),a.push(' <Menu className="h-5 w-5" />'),a.push(" </Button>"),a.push(" </SheetTrigger>"),a.push(' <SheetContent side="left" className="w-64 p-0">'),a.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),a.push(' <div className="flex h-full flex-col">'),a.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),a.push(" </div>"),a.push(" </SheetContent>"),a.push(" </Sheet>"),a.push(' <span className="text-lg font-semibold">'+s+"</span>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),{path:"components/sidebar.tsx",content:a.join(`
2674
- `)}}function hp(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,r=t.defaultRole??e[0],n=[];n.push("export type Role = "+e.map(i=>'"'+i+'"').join(" | ")+";"),n.push(""),n.push("export const ROLES = ["+e.map(i=>'"'+i+'"').join(", ")+"] as const;"),n.push(""),n.push('export const DEFAULT_ROLE: Role = "'+r+'";'),n.push(""),n.push("export const ROLE_LABELS: Record<Role, string> = {");for(let i of e){let o=i.charAt(0).toUpperCase()+i.slice(1);n.push(' "'+i+'": "'+o+'",')}return n.push("};"),n.push(""),n.push("export function getUserRole(user: Record<string, unknown>): Role {"),n.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),n.push(" if (ROLES.includes(role as Role)) return role as Role;"),n.push(" return DEFAULT_ROLE;"),n.push("}"),n.push(""),n.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),n.push(" if (!userRole) return false;"),n.push(" const allowed = Array.isArray(required) ? required : [required];"),n.push(" return allowed.includes(userRole as Role);"),n.push("}"),n.push(""),n.join(`
2675
- `)}function gp(t){let e=bn(t.name);if(t.authModel==="none"){let o=[];return o.push("export default function HomePage() {"),o.push(" return ("),o.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),o.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&o.push(' <p className="mt-4 text-lg text-muted-foreground">'+t.summary+"</p>"),o.push(" </main>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
2674
+ `)}}function gp(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,r=t.defaultRole??e[0],n=[];n.push("export type Role = "+e.map(i=>'"'+i+'"').join(" | ")+";"),n.push(""),n.push("export const ROLES = ["+e.map(i=>'"'+i+'"').join(", ")+"] as const;"),n.push(""),n.push('export const DEFAULT_ROLE: Role = "'+r+'";'),n.push(""),n.push("export const ROLE_LABELS: Record<Role, string> = {");for(let i of e){let o=i.charAt(0).toUpperCase()+i.slice(1);n.push(' "'+i+'": "'+o+'",')}return n.push("};"),n.push(""),n.push("export function getUserRole(user: Record<string, unknown>): Role {"),n.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),n.push(" if (ROLES.includes(role as Role)) return role as Role;"),n.push(" return DEFAULT_ROLE;"),n.push("}"),n.push(""),n.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),n.push(" if (!userRole) return false;"),n.push(" const allowed = Array.isArray(required) ? required : [required];"),n.push(" return allowed.includes(userRole as Role);"),n.push("}"),n.push(""),n.join(`
2675
+ `)}function fp(t){let e=wn(t.name);if(t.authModel==="none"){let o=[];return o.push("export default function HomePage() {"),o.push(" return ("),o.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),o.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&o.push(' <p className="mt-4 text-lg text-muted-foreground">'+t.summary+"</p>"),o.push(" </main>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
2676
2676
  `)}let r=t.publicPages?.includes("/"),n=t.design?.landingTone;if(r&&n){let o=[];return o.push('import Link from "next/link";'),o.push(""),o.push("export default function HomePage() {"),o.push(" return ("),o.push(' <main className="flex min-h-screen flex-col">'),o.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),o.push(' <h1 className="text-5xl font-bold tracking-tight">'+e+"</h1>"),t.summary&&o.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+t.summary+"</p>"),o.push(' <div className="flex gap-4">'),o.push(' <Link href="/register" className="inline-flex h-11 items-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),o.push(" Get Started"),o.push(" </Link>"),o.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),o.push(" Sign In"),o.push(" </Link>"),o.push(" </div>"),o.push(" </section>"),o.push(" </main>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
2677
2677
  `)}if(r){let o=[];return o.push('import Link from "next/link";'),o.push(""),o.push("export default function HomePage() {"),o.push(" return ("),o.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),o.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&o.push(' <p className="text-lg text-muted-foreground">'+t.summary+"</p>"),o.push(' <Link href="/login" className="inline-flex h-10 items-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),o.push(" Sign In"),o.push(" </Link>"),o.push(" </main>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
2678
2678
  `)}let i=[];return i.push('import { headers } from "next/headers";'),i.push('import { redirect } from "next/navigation";'),i.push('import { auth } from "@/lib/auth";'),i.push(""),i.push("export default async function HomePage() {"),i.push(" const session = await auth.api.getSession({ headers: await headers() });"),i.push(' if (session) redirect("/dashboard");'),i.push(' redirect("/login");'),i.push("}"),i.push(""),i.join(`
2679
- `)}function fp(t,e){let r=t.authModel==="none",n=[];r||(n.push('import { Suspense } from "react";'),n.push('import { headers } from "next/headers";'),n.push('import { redirect } from "next/navigation";'),n.push('import { auth } from "@/lib/auth";'),n.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?n.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&n.push('import Sidebar from "@/components/sidebar";'),!r&&t.roles&&t.roles.length>0&&n.push('import { getUserRole } from "@/lib/roles";'),n.push(""),n.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),r?n.push(' const user = { name: "Guest", email: "" };'):(n.push(" const session = await auth.api.getSession({ headers: await headers() });"),n.push(' if (!session) redirect("/login");'),n.push(""),t.roles&&t.roles.length>0?(n.push(" const role = getUserRole(session.user as Record<string, unknown>);"),n.push(" const user = { name: session.user.name, email: session.user.email, role };")):(n.push(" const user = {"),n.push(" name: session.user.name,"),n.push(" email: session.user.email,"),n.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),n.push(" };"))),n.push("");let i=r?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(" <TopNav user={user} />"),n.push(' <main className="mx-auto max-w-7xl p-6">'+i+"{children}</main>"),n.push(" </div>"),n.push(" );")):t.navStyle==="none"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(' <main className="mx-auto max-w-5xl p-6">'+i+"{children}</main>"),n.push(" </div>"),n.push(" );")):(n.push(" return ("),n.push(' <div className="flex flex-col md:flex-row min-h-screen">'),n.push(" <Sidebar user={user} />"),n.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+i+"{children}</main>"),n.push(" </div>"),n.push(" );")),n.push("}"),n.push(""),n.join(`
2680
- `)}function yp(t){let e=bn(t.name),r=t.dataModel??[],n=[];if(r.length>0){let i=r.map(s=>vs(s.entity??s.name??"item")),o=[...new Set(i)];n.push('import { Card, CardContent } from "@/components/ui/card";'),n.push("import { "+o.join(", ")+' } from "lucide-react";'),n.push("")}if(n.push("export default function DashboardPage() {"),n.push(" return ("),n.push(' <div className="space-y-6">'),n.push(" <div>"),n.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),t.summary&&n.push(' <p className="mt-1 text-muted-foreground">'+t.summary+"</p>"),n.push(" </div>"),r.length>0){n.push(' <div className="rounded-lg border p-8 text-center">'),n.push(' <h2 className="text-lg font-semibold">Get started</h2>'),n.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),n.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let i of r){let o=i.entity??i.name??"Item",s=vs(o),a=bn(o.replace(/_/g,"-"));n.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),n.push(" <"+s+' className="h-5 w-5 text-muted-foreground" />'),n.push(' <span className="text-sm font-medium">Add your first '+a+"</span>"),n.push(" </div>")}n.push(" </div>"),n.push(" </div>")}return n.push(" </div>"),n.push(" );"),n.push("}"),n.push(""),n.join(`
2681
- `)}function bp(t,e=!1){if(!t.multiTenant)return null;let r=[];return e?(r.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = pgTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),r.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = pgTable(")):(r.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),r.push('import { sql } from "drizzle-orm";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = sqliteTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = sqliteTable(")),r.push(' "org_member",'),r.push(" {"),r.push(' id: text("id").primaryKey(),'),r.push(' orgId: text("org_id").notNull().references(() => organization.id),'),r.push(' userId: text("user_id").notNull().references(() => user.id),'),r.push(' role: text("role").notNull(),'),e?r.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):r.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(" },"),r.push(" (table) => ({"),r.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),r.push(' userIdx: index("org_member_user_idx").on(table.userId),'),r.push(" }),"),r.push(");"),r.push(""),r.join(`
2682
- `)}function wp(t){if(!t.multiTenant)return null;let e=[];return e.push('import { db } from "./db";'),e.push('import { organization, orgMember } from "@/db/schema/organization";'),e.push('import { eq } from "drizzle-orm";'),e.push(""),e.push("export async function getCurrentOrg(userId: string) {"),e.push(" const membership = await db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.userId, userId))"),e.push(" .limit(1);"),e.push(" if (membership.length === 0) return null;"),e.push(" const org = await db"),e.push(" .select()"),e.push(" .from(organization)"),e.push(" .where(eq(organization.id, membership[0].orgId))"),e.push(" .limit(1);"),e.push(" return org[0] ?? null;"),e.push("}"),e.push(""),e.push("export async function getOrgMembers(orgId: string) {"),e.push(" return db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.orgId, orgId));"),e.push("}"),e.push(""),e.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),e.push(" const id = crypto.randomUUID();"),e.push(" await db.insert(orgMember).values({"),e.push(" id,"),e.push(" orgId,"),e.push(" userId: email,"),e.push(" role,"),e.push(" });"),e.push(" return { id, orgId, email, role };"),e.push("}"),e.push(""),e.join(`
2683
- `)}function vp(t){if(!t.multiTenant)return null;let e=[];return e.push('"use client";'),e.push(""),e.push("import {"),e.push(" DropdownMenu,"),e.push(" DropdownMenuContent,"),e.push(" DropdownMenuItem,"),e.push(" DropdownMenuTrigger,"),e.push('} from "@/components/ui/dropdown-menu";'),e.push('import { Button } from "@/components/ui/button";'),e.push('import { ChevronsUpDown } from "lucide-react";'),e.push(""),e.push("interface OrgSwitcherProps {"),e.push(" orgs: Array<{ id: string; name: string }>;"),e.push(" currentOrgId: string;"),e.push("}"),e.push(""),e.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),e.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),e.push(""),e.push(" return ("),e.push(" <DropdownMenu>"),e.push(" <DropdownMenuTrigger asChild>"),e.push(' <Button variant="outline" className="w-full justify-between">'),e.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),e.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),e.push(" </Button>"),e.push(" </DropdownMenuTrigger>"),e.push(' <DropdownMenuContent className="w-56">'),e.push(" {orgs.map((org) => ("),e.push(" <DropdownMenuItem key={org.id}>"),e.push(" {org.name}"),e.push(" </DropdownMenuItem>"),e.push(" ))}"),e.push(" </DropdownMenuContent>"),e.push(" </DropdownMenu>"),e.push(" );"),e.push("}"),e.push(""),e.join(`
2684
- `)}function kp(t,e,r){let n=[],i=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");n.push(`# ${i}`),n.push(""),e?.summary&&(n.push(e.summary),n.push(""));let o=e?.features??[];if(o.length>0){n.push("## Features"),n.push("");for(let l of o){let c=l.description?` \u2014 ${l.description}`:"";n.push(`- **${l.name}**${c}`)}n.push("")}n.push("## Tech Stack"),n.push(""),n.push("| Layer | Technology |"),n.push("|-------|------------|"),n.push("| Framework | Next.js 15 (App Router) |"),n.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),n.push("| Auth | Better Auth (email/password, social login) |"),n.push("| Styling | Tailwind CSS + shadcn/ui |"),n.push("| Deployment | Mistflow Cloud |"),r.hasStripe&&n.push("| Payments | Stripe |"),r.hasResend&&n.push("| Email | Resend + React Email |"),r.hasStorage&&n.push("| File Storage | Mistflow Cloud (managed blob storage) |"),r.hasAdmin&&n.push("| Admin | Better Auth admin plugin |"),r.hasAI&&n.push("| AI | Vercel AI SDK + OpenAI |"),n.push("");let s=e?.pages??[];if(s.length>0){n.push("## Pages"),n.push(""),n.push("| Route | Description |"),n.push("|-------|-------------|");for(let l of s){let c=l.path??l.route??l.name??"",u=l.description??"";n.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${u} |`)}n.push("")}let a=e?.dataModel??[];if(a.length>0){n.push("## Data Model"),n.push("");for(let l of a){let c=l.entity??l.name??"Unknown";if(n.push(`### ${c}`),n.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")n.push(`Fields: ${l.fields.join(", ")}`);else{n.push("| Field | Type |"),n.push("|-------|------|");for(let u of l.fields)n.push(`| ${u.name} | ${u.type} |`)}n.push("")}}}return n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),r.isNeon?n.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(n.push("| `TURSO_URL` | Database connection URL | Yes |"),n.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),n.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),r.hasStripe&&(n.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),n.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),n.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),r.hasResend&&(n.push("| `RESEND_API_KEY` | Resend API key | Yes |"),n.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),(r.hasAI||r.hasStorage)&&n.push("| `MISTFLOW_RUNTIME_KEY` | Mistflow Cloud runtime key \u2014 authenticates AI gateway, file storage, and other managed features | Auto-provisioned at `mist_init` |"),r.hasAI&&n.push("| `OPENROUTER_API_KEY` | OpenRouter key for your-key fallback (only used when `MISTFLOW_RUNTIME_KEY` is unset) | Optional |"),n.push(""),n.push("### Local database"),n.push(""),r.isNeon?(n.push("For local development, start a local Postgres server:"),n.push(""),n.push("```bash"),n.push("# Using Docker:"),n.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),n.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),n.push("```")):(n.push("For local development, start a local Turso server:"),n.push(""),n.push("```bash"),n.push("npx turso dev"),n.push("```")),n.push(""),n.push("Then set up the database:"),n.push(""),n.push("```bash"),n.push("npm run db:push"),n.push("```"),n.push(""),n.push("### Run"),n.push(""),n.push("```bash"),n.push("npm run dev"),n.push("```"),n.push(""),n.push("Open [http://localhost:3000](http://localhost:3000)."),n.push(""),n.push("## Project Structure"),n.push(""),n.push("```"),n.push("app/"),n.push(" (auth)/ Login and registration pages"),n.push(" (dashboard)/ Authenticated app pages"),r.hasAdmin&&n.push(" admin/ Admin panel pages (at /admin/...)"),n.push(" home/ Public landing page (served via / \u2192 /home redirect)"),n.push(" api/ API routes (auth, health, webhooks)"),n.push(" layout.tsx Root layout with fonts and providers"),n.push(" globals.css Design tokens and Tailwind config"),n.push("components/ Reusable UI components"),n.push("db/"),n.push(" schema/ Database table definitions"),n.push(" index.ts Schema exports"),n.push("lib/"),n.push(" auth.ts Better Auth server config"),n.push(" auth-client.ts Better Auth client config"),n.push(` db.ts ${r.isNeon?"Postgres":"SQLite"} database connection`),r.hasStripe&&n.push(" stripe.ts Stripe client"),r.hasResend&&(n.push(" resend.ts Resend client"),n.push(" email.ts Email send helpers")),r.hasStorage&&n.push(" storage.ts File upload/download helpers"),r.hasAI&&(n.push(" ai.ts Back-compat export for server AI helpers"),n.push(" server/ai.ts Server-only AI Gateway and provider helpers")),r.hasResend&&n.push("emails/ React Email templates"),n.push("```"),n.push(""),n.push("## Deploy"),n.push(""),n.push("Deploy to production with Mistflow:"),n.push(""),n.push("```"),n.push("# In your AI editor (Claude Code, Cursor, etc.):"),n.push("mist_deploy action='deploy'"),n.push("```"),n.push(""),n.push("Your app will be live at `https://<app-name>.mistflow.app`."),n.push(""),e?.design&&(n.push("## Design"),n.push(""),e.design.tone&&n.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(n.push(`- **Heading font**: ${e.design.fonts.heading}`),n.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&n.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&n.push(`- **Border radius**: ${e.design.borderRadius}`),n.push("")),n.push("---"),n.push(""),n.push("Built with [Mistflow](https://mistflow.ai)"),n.push(""),n.join(`
2685
- `)}async function xp(t,e){if(!Se())return Ee("scaffold a new project");if(!Bt())return p(JSON.stringify({status:"node_version_unsupported",code:"node_version_unsupported",message:It(),nextAction:"Tell the user their Node version is too old, paste the upgrade command from `message`, and stop. Do NOT proceed with mist_init \u2014 the scaffolded app would build-fail at deploy time."}),!0);let{name:r,plan:n,path:i,planId:o,sessionId:s}=t,a,l,c=null,u=n;if(typeof u=="string")try{let b=JSON.parse(u);b&&typeof b=="object"&&!Array.isArray(b)&&"plan"in b?u=b.plan:u=b}catch{return p("mist_init received `plan` as a string, but it is not valid JSON. Pass the plan object directly or pass planId from mist_plan.",!0)}if(!u&&o){if(c=Bd(o),!c)return p(`No plan found for planId '${o}'. Call mist_plan first, or pass the plan object inline.`,!0);u=c.plan}if(!u||typeof u!="object"||Array.isArray(u))return p("mist_init requires a plan object or a valid planId from mist_plan. Refusing to scaffold without a structured plan because mist_implement would not know what to build.",!0);let h=i??c?.scaffoldTargetPath;if(!h)return p("mist_init requires an explicit 'path' unless the planId cache includes a scaffoldTargetPath. Call mist_init with the planId returned by mist_plan, pass the absolute scaffold directory, or pass { sessionId, path } in session mode.",!0);if(!$d(h))return p(`mist_init 'path' must be an absolute path \u2014 received '${h}'. Pass the full absolute path to the target directory.`,!0);let d=fi(h),v=r??(typeof u.name=="string"?u.name:void 0);if(!v)return p("mist_init requires a human-readable app name. Pass `name`, or call it with a planId whose cached plan includes a name.",!0);let W=u?.design,_=typeof u.authModel=="string"?u.authModel:void 0,k=_==="none",y=cp(u),A=dp(u,_),z=u?yn(u,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,H=u?yn(u,"admin panel","admin dashboard","admin management"):!1,ne=u?yn(u,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,ee=u,Q=typeof u.dbProvider=="string"?u.dbProvider:"neon",q=Array.isArray(u.dataModel)&&u.dataModel.length>0,I=Q==="none"||k&&!q&&!z,se=I?"none":Q,B=se==="neon";if(!Zd(d))return p(ep(d,u?.name),!0);Wt(d,{recursive:!0});try{try{let f=he(d,".mistflow","rules");Wt(f,{recursive:!0}),Ze(he(f,"design-quality.md"),er),Ze(he(f,"landing.md"),tr)}catch(f){console.error("Could not write design rule files:",f instanceof Error?f.message:f)}try{let f=he(fn(d),".mistflow","mockups");if(Ne(f)){let E=gi(f).filter(S=>S.endsWith(".html"));if(E.length>0){let S=he(d,".mistflow","mockups");Wt(S,{recursive:!0});for(let de of E)Ud(he(f,de),he(S,de));console.error(`Copied ${E.length} mockup file(s) into project`)}}}catch(f){console.error("Could not copy mockup files:",f instanceof Error?f.message:f)}let b=null;try{b=await $r("nextjs")}catch(f){console.error("Could not fetch scaffold from API, using minimal scaffold:",f instanceof Error?f.message:f)}if(b){let f=v.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let x of b.files){if(x.path==="package.json"||x.path==="middleware.ts"||x.path==="components/sidebar.tsx"||x.path==="components/topnav.tsx"||x.path==="app/(dashboard)/layout.tsx"||x.path==="app/(dashboard)/page.tsx"||x.path==="app/(dashboard)/dashboard/page.tsx"||I&&(x.path==="lib/db.ts"||x.path==="drizzle.config.ts"||x.path==="db/index.ts"||x.path.startsWith("db/schema/"))||k&&(x.path.includes("(auth)")||x.path.includes("(admin)")||x.path.startsWith("app/admin/")||x.path.includes("components/auth/")||x.path.includes("admin-sidebar")||x.path.includes("app/api/auth/")||x.path.includes("app/api/admin/seed")||x.path==="lib/auth.ts"||x.path==="lib/auth-client.ts"||x.path==="db/schema/auth.ts"||x.path==="db/schema/index.ts"||x.path==="db/index.ts")||!y&&(x.path.includes("stripe")||x.path.includes("webhook/stripe"))||!A&&(x.path.includes("resend")||x.path.includes("emails/"))||!H&&(x.path.includes("(admin)")||x.path.startsWith("app/admin/")||x.path.includes("admin-sidebar"))||B&&(x.path==="lib/db.ts"||x.path==="lib/auth.ts"||x.path==="drizzle.config.ts"||x.path==="db/schema/auth.ts"))continue;let j=x.content.replace(/\{\{APP_NAME\}\}/g,v).replace(/\{\{WORKER_NAME\}\}/g,f);if(B&&x.path==="next.config.ts"&&(j=j.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),x.path==="next.config.ts"){let Ie=Wd(d);Ie&&(console.error(`[init] Project is inside monorepo at ${Ie} \u2014 adding outputFileTracingRoot`),j.includes("outputFileTracingRoot")||(j=j.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
2679
+ `)}function yp(t,e){let r=t.authModel==="none",n=[];r||(n.push('import { Suspense } from "react";'),n.push('import { headers } from "next/headers";'),n.push('import { redirect } from "next/navigation";'),n.push('import { auth } from "@/lib/auth";'),n.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?n.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&n.push('import Sidebar from "@/components/sidebar";'),!r&&t.roles&&t.roles.length>0&&n.push('import { getUserRole } from "@/lib/roles";'),n.push(""),n.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),r?n.push(' const user = { name: "Guest", email: "" };'):(n.push(" const session = await auth.api.getSession({ headers: await headers() });"),n.push(' if (!session) redirect("/login");'),n.push(""),t.roles&&t.roles.length>0?(n.push(" const role = getUserRole(session.user as Record<string, unknown>);"),n.push(" const user = { name: session.user.name, email: session.user.email, role };")):(n.push(" const user = {"),n.push(" name: session.user.name,"),n.push(" email: session.user.email,"),n.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),n.push(" };"))),n.push("");let i=r?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(" <TopNav user={user} />"),n.push(' <main className="mx-auto max-w-7xl p-6">'+i+"{children}</main>"),n.push(" </div>"),n.push(" );")):t.navStyle==="none"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(' <main className="mx-auto max-w-5xl p-6">'+i+"{children}</main>"),n.push(" </div>"),n.push(" );")):(n.push(" return ("),n.push(' <div className="flex flex-col md:flex-row min-h-screen">'),n.push(" <Sidebar user={user} />"),n.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+i+"{children}</main>"),n.push(" </div>"),n.push(" );")),n.push("}"),n.push(""),n.join(`
2680
+ `)}function bp(t){let e=wn(t.name),r=t.dataModel??[],n=[];if(r.length>0){let i=r.map(s=>ks(s.entity??s.name??"item")),o=[...new Set(i)];n.push('import { Card, CardContent } from "@/components/ui/card";'),n.push("import { "+o.join(", ")+' } from "lucide-react";'),n.push("")}if(n.push("export default function DashboardPage() {"),n.push(" return ("),n.push(' <div className="space-y-6">'),n.push(" <div>"),n.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),t.summary&&n.push(' <p className="mt-1 text-muted-foreground">'+t.summary+"</p>"),n.push(" </div>"),r.length>0){n.push(' <div className="rounded-lg border p-8 text-center">'),n.push(' <h2 className="text-lg font-semibold">Get started</h2>'),n.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),n.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let i of r){let o=i.entity??i.name??"Item",s=ks(o),a=wn(o.replace(/_/g,"-"));n.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),n.push(" <"+s+' className="h-5 w-5 text-muted-foreground" />'),n.push(' <span className="text-sm font-medium">Add your first '+a+"</span>"),n.push(" </div>")}n.push(" </div>"),n.push(" </div>")}return n.push(" </div>"),n.push(" );"),n.push("}"),n.push(""),n.join(`
2681
+ `)}function wp(t,e=!1){if(!t.multiTenant)return null;let r=[];return e?(r.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = pgTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),r.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = pgTable(")):(r.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),r.push('import { sql } from "drizzle-orm";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = sqliteTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = sqliteTable(")),r.push(' "org_member",'),r.push(" {"),r.push(' id: text("id").primaryKey(),'),r.push(' orgId: text("org_id").notNull().references(() => organization.id),'),r.push(' userId: text("user_id").notNull().references(() => user.id),'),r.push(' role: text("role").notNull(),'),e?r.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):r.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(" },"),r.push(" (table) => ({"),r.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),r.push(' userIdx: index("org_member_user_idx").on(table.userId),'),r.push(" }),"),r.push(");"),r.push(""),r.join(`
2682
+ `)}function vp(t){if(!t.multiTenant)return null;let e=[];return e.push('import { db } from "./db";'),e.push('import { organization, orgMember } from "@/db/schema/organization";'),e.push('import { eq } from "drizzle-orm";'),e.push(""),e.push("export async function getCurrentOrg(userId: string) {"),e.push(" const membership = await db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.userId, userId))"),e.push(" .limit(1);"),e.push(" if (membership.length === 0) return null;"),e.push(" const org = await db"),e.push(" .select()"),e.push(" .from(organization)"),e.push(" .where(eq(organization.id, membership[0].orgId))"),e.push(" .limit(1);"),e.push(" return org[0] ?? null;"),e.push("}"),e.push(""),e.push("export async function getOrgMembers(orgId: string) {"),e.push(" return db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.orgId, orgId));"),e.push("}"),e.push(""),e.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),e.push(" const id = crypto.randomUUID();"),e.push(" await db.insert(orgMember).values({"),e.push(" id,"),e.push(" orgId,"),e.push(" userId: email,"),e.push(" role,"),e.push(" });"),e.push(" return { id, orgId, email, role };"),e.push("}"),e.push(""),e.join(`
2683
+ `)}function kp(t){if(!t.multiTenant)return null;let e=[];return e.push('"use client";'),e.push(""),e.push("import {"),e.push(" DropdownMenu,"),e.push(" DropdownMenuContent,"),e.push(" DropdownMenuItem,"),e.push(" DropdownMenuTrigger,"),e.push('} from "@/components/ui/dropdown-menu";'),e.push('import { Button } from "@/components/ui/button";'),e.push('import { ChevronsUpDown } from "lucide-react";'),e.push(""),e.push("interface OrgSwitcherProps {"),e.push(" orgs: Array<{ id: string; name: string }>;"),e.push(" currentOrgId: string;"),e.push("}"),e.push(""),e.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),e.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),e.push(""),e.push(" return ("),e.push(" <DropdownMenu>"),e.push(" <DropdownMenuTrigger asChild>"),e.push(' <Button variant="outline" className="w-full justify-between">'),e.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),e.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),e.push(" </Button>"),e.push(" </DropdownMenuTrigger>"),e.push(' <DropdownMenuContent className="w-56">'),e.push(" {orgs.map((org) => ("),e.push(" <DropdownMenuItem key={org.id}>"),e.push(" {org.name}"),e.push(" </DropdownMenuItem>"),e.push(" ))}"),e.push(" </DropdownMenuContent>"),e.push(" </DropdownMenu>"),e.push(" );"),e.push("}"),e.push(""),e.join(`
2684
+ `)}function xp(t,e,r){let n=[],i=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");n.push(`# ${i}`),n.push(""),e?.summary&&(n.push(e.summary),n.push(""));let o=e?.features??[];if(o.length>0){n.push("## Features"),n.push("");for(let l of o){let c=l.description?` \u2014 ${l.description}`:"";n.push(`- **${l.name}**${c}`)}n.push("")}n.push("## Tech Stack"),n.push(""),n.push("| Layer | Technology |"),n.push("|-------|------------|"),n.push("| Framework | Next.js 15 (App Router) |"),n.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),n.push("| Auth | Better Auth (email/password, social login) |"),n.push("| Styling | Tailwind CSS + shadcn/ui |"),n.push("| Deployment | Mistflow Cloud |"),r.hasStripe&&n.push("| Payments | Stripe |"),r.hasResend&&n.push("| Email | Resend + React Email |"),r.hasStorage&&n.push("| File Storage | Mistflow Cloud (managed blob storage) |"),r.hasAdmin&&n.push("| Admin | Better Auth admin plugin |"),r.hasAI&&n.push("| AI | Vercel AI SDK + OpenAI |"),n.push("");let s=e?.pages??[];if(s.length>0){n.push("## Pages"),n.push(""),n.push("| Route | Description |"),n.push("|-------|-------------|");for(let l of s){let c=l.path??l.route??l.name??"",m=l.description??"";n.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${m} |`)}n.push("")}let a=e?.dataModel??[];if(a.length>0){n.push("## Data Model"),n.push("");for(let l of a){let c=l.entity??l.name??"Unknown";if(n.push(`### ${c}`),n.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")n.push(`Fields: ${l.fields.join(", ")}`);else{n.push("| Field | Type |"),n.push("|-------|------|");for(let m of l.fields)n.push(`| ${m.name} | ${m.type} |`)}n.push("")}}}return n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),r.isNeon?n.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(n.push("| `TURSO_URL` | Database connection URL | Yes |"),n.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),n.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),r.hasStripe&&(n.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),n.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),n.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),r.hasResend&&(n.push("| `RESEND_API_KEY` | Resend API key | Yes |"),n.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),(r.hasAI||r.hasStorage)&&n.push("| `MISTFLOW_RUNTIME_KEY` | Mistflow Cloud runtime key \u2014 authenticates AI gateway, file storage, and other managed features | Auto-provisioned at `mist_init` |"),r.hasAI&&n.push("| `OPENROUTER_API_KEY` | OpenRouter key for your-key fallback (only used when `MISTFLOW_RUNTIME_KEY` is unset) | Optional |"),n.push(""),n.push("### Local database"),n.push(""),r.isNeon?(n.push("For local development, start a local Postgres server:"),n.push(""),n.push("```bash"),n.push("# Using Docker:"),n.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),n.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),n.push("```")):(n.push("For local development, start a local Turso server:"),n.push(""),n.push("```bash"),n.push("npx turso dev"),n.push("```")),n.push(""),n.push("Then set up the database:"),n.push(""),n.push("```bash"),n.push("npm run db:push"),n.push("```"),n.push(""),n.push("### Run"),n.push(""),n.push("```bash"),n.push("npm run dev"),n.push("```"),n.push(""),n.push("Open [http://localhost:3000](http://localhost:3000)."),n.push(""),n.push("## Project Structure"),n.push(""),n.push("```"),n.push("app/"),n.push(" (auth)/ Login and registration pages"),n.push(" (dashboard)/ Authenticated app pages"),r.hasAdmin&&n.push(" admin/ Admin panel pages (at /admin/...)"),n.push(" home/ Public landing page (served via / \u2192 /home redirect)"),n.push(" api/ API routes (auth, health, webhooks)"),n.push(" layout.tsx Root layout with fonts and providers"),n.push(" globals.css Design tokens and Tailwind config"),n.push("components/ Reusable UI components"),n.push("db/"),n.push(" schema/ Database table definitions"),n.push(" index.ts Schema exports"),n.push("lib/"),n.push(" auth.ts Better Auth server config"),n.push(" auth-client.ts Better Auth client config"),n.push(` db.ts ${r.isNeon?"Postgres":"SQLite"} database connection`),r.hasStripe&&n.push(" stripe.ts Stripe client"),r.hasResend&&(n.push(" resend.ts Resend client"),n.push(" email.ts Email send helpers")),r.hasStorage&&n.push(" storage.ts File upload/download helpers"),r.hasAI&&(n.push(" ai.ts Back-compat export for server AI helpers"),n.push(" server/ai.ts Server-only AI Gateway and provider helpers")),r.hasResend&&n.push("emails/ React Email templates"),n.push("```"),n.push(""),n.push("## Deploy"),n.push(""),n.push("Deploy to production with Mistflow:"),n.push(""),n.push("```"),n.push("# In your AI editor (Claude Code, Cursor, etc.):"),n.push("mist_deploy action='deploy'"),n.push("```"),n.push(""),n.push("Your app will be live at `https://<app-name>.mistflow.app`."),n.push(""),e?.design&&(n.push("## Design"),n.push(""),e.design.tone&&n.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(n.push(`- **Heading font**: ${e.design.fonts.heading}`),n.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&n.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&n.push(`- **Border radius**: ${e.design.borderRadius}`),n.push("")),n.push("---"),n.push(""),n.push("Built with [Mistflow](https://mistflow.ai)"),n.push(""),n.join(`
2685
+ `)}async function Sp(t,e){if(!xe())return Oe("scaffold a new project");if(!zt())return d(JSON.stringify({status:"node_version_unsupported",code:"node_version_unsupported",message:At(),nextAction:"Tell the user their Node version is too old, paste the upgrade command from `message`, and stop. Do NOT proceed with mist_init \u2014 the scaffolded app would build-fail at deploy time."}),!0);let{name:r,plan:n,path:i,planId:o,sessionId:s}=t,a,l=[],c,m=null,p=n;if(typeof p=="string")try{let C=JSON.parse(p);C&&typeof C=="object"&&!Array.isArray(C)&&"plan"in C?p=C.plan:p=C}catch{return d("mist_init received `plan` as a string, but it is not valid JSON. Pass the plan object directly or pass planId from mist_plan.",!0)}if(!p&&o){if(m=zd(o),!m)return d(`No plan found for planId '${o}'. Call mist_plan first, or pass the plan object inline.`,!0);p=m.plan}if(!p||typeof p!="object"||Array.isArray(p))return d("mist_init requires a plan object or a valid planId from mist_plan. Refusing to scaffold without a structured plan because mist_implement would not know what to build.",!0);let u=i??m?.scaffoldTargetPath;if(!u)return d("mist_init requires an explicit 'path' unless the planId cache includes a scaffoldTargetPath. Call mist_init with the planId returned by mist_plan, pass the absolute scaffold directory, or pass { sessionId, path } in session mode.",!0);if(!Fd(u))return d(`mist_init 'path' must be an absolute path \u2014 received '${u}'. Pass the full absolute path to the target directory.`,!0);let g=yi(u),j=r??(typeof p.name=="string"?p.name:void 0);if(!j)return d("mist_init requires a human-readable app name. Pass `name`, or call it with a planId whose cached plan includes a name.",!0);let I=p?.design,S=typeof p.authModel=="string"?p.authModel:void 0,y=S==="none",R=dp(p),z=pp(p,S),W=p?bn(p,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,te=p?bn(p,"admin panel","admin dashboard","admin management"):!1,pe=p?bn(p,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,L=p,H=typeof p.dbProvider=="string"?p.dbProvider:"neon",E=Array.isArray(p.dataModel)&&p.dataModel.length>0,Z=H==="none"||y&&!E&&!W,J=Z?"none":H,x=J==="neon";if(!ep(g))return d(tp(g,p?.name),!0);Gt(g,{recursive:!0});try{try{let b=de(g,".mistflow","rules");Gt(b,{recursive:!0}),et(de(b,"design-quality.md"),tr),et(de(b,"landing.md"),nr)}catch(b){console.error("Could not write design rule files:",b instanceof Error?b.message:b)}try{let b=de(yn(g),".mistflow","mockups");if(De(b)){let w=fi(b).filter($=>$.endsWith(".html"));if(w.length>0){let $=de(g,".mistflow","mockups");Gt($,{recursive:!0});for(let ee of w)$d(de(b,ee),de($,ee));console.error(`Copied ${w.length} mockup file(s) into project`)}}}catch(b){console.error("Could not copy mockup files:",b instanceof Error?b.message:b)}let C=null;try{C=await Fr("nextjs")}catch(b){console.error("Could not fetch scaffold from API, using minimal scaffold:",b instanceof Error?b.message:b)}if(C){let b=j.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let v of C.files){if(v.path==="package.json"||v.path==="middleware.ts"||v.path==="components/sidebar.tsx"||v.path==="components/topnav.tsx"||v.path==="app/(dashboard)/layout.tsx"||v.path==="app/(dashboard)/page.tsx"||v.path==="app/(dashboard)/dashboard/page.tsx"||Z&&(v.path==="lib/db.ts"||v.path==="drizzle.config.ts"||v.path==="db/index.ts"||v.path.startsWith("db/schema/"))||y&&(v.path.includes("(auth)")||v.path.includes("(admin)")||v.path.startsWith("app/admin/")||v.path.includes("components/auth/")||v.path.includes("admin-sidebar")||v.path.includes("app/api/auth/")||v.path.includes("app/api/admin/seed")||v.path==="lib/auth.ts"||v.path==="lib/auth-client.ts"||v.path==="db/schema/auth.ts"||v.path==="db/schema/index.ts"||v.path==="db/index.ts")||!R&&(v.path.includes("stripe")||v.path.includes("webhook/stripe"))||!z&&(v.path.includes("resend")||v.path.includes("emails/"))||!te&&(v.path.includes("(admin)")||v.path.startsWith("app/admin/")||v.path.includes("admin-sidebar"))||x&&(v.path==="lib/db.ts"||v.path==="lib/auth.ts"||v.path==="drizzle.config.ts"||v.path==="db/schema/auth.ts"))continue;let ie=v.content.replace(/\{\{APP_NAME\}\}/g,j).replace(/\{\{WORKER_NAME\}\}/g,b);if(x&&v.path==="next.config.ts"&&(ie=ie.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),v.path==="next.config.ts"){let Ie=Gd(g);Ie&&(console.error(`[init] Project is inside monorepo at ${Ie} \u2014 adding outputFileTracingRoot`),ie.includes("outputFileTracingRoot")||(ie=ie.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
2686
2686
  import { dirname } from "path";
2687
2687
  import { fileURLToPath } from "url";
2688
2688
 
2689
- const __dirname = dirname(fileURLToPath(import.meta.url));`),j=j.replace("images: {",`outputFileTracingRoot: __dirname,
2690
- images: {`)))}!H&&x.path.includes("sidebar")&&(j=j.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),j=j.replace(/, Shield/g,"")),N(d,x.path,j)}let E={...b.dependencies},S={...b.devDependencies};E["drizzle-zod"]||(E["drizzle-zod"]="^0.5.1"),k&&delete E["better-auth"],I&&(delete E["drizzle-orm"],delete E["@libsql/client"],delete E["@neondatabase/serverless"],delete S["drizzle-kit"],delete S["@electric-sql/pglite"]),B&&(delete E["@libsql/client"],E["@neondatabase/serverless"]="^0.10.0",S["@electric-sql/pglite"]="^0.2.0"),y&&(E.stripe="^17.0.0"),A&&(E.resend="^4.0.0",E["@react-email/components"]="^0.0.31"),ne&&(E.ai="^4.0.0",E["@ai-sdk/openai"]="^1.0.0",E.openai="^4.0.0",E["server-only"]="^0.0.1",E["zod-to-json-schema"]="3.24.6");let de={"@noble/ciphers":"^1.3.0"},me={react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"},Z={dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint",...I?{}:{"db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"}};if(N(d,"package.json",JSON.stringify({name:v,version:"0.1.0",private:!0,scripts:Z,dependencies:E,devDependencies:S,optionalDependencies:de,overrides:me},null,2)),b.methodology){let x=b.methodology;B||(x=x.replace(/import \{ pgTable, text, timestamp(?:, boolean)? \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
2689
+ const __dirname = dirname(fileURLToPath(import.meta.url));`),ie=ie.replace("images: {",`outputFileTracingRoot: __dirname,
2690
+ images: {`)))}!te&&v.path.includes("sidebar")&&(ie=ie.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),ie=ie.replace(/, Shield/g,"")),O(g,v.path,ie)}let w={...C.dependencies},$={...C.devDependencies};w["drizzle-zod"]||(w["drizzle-zod"]="^0.5.1"),y&&delete w["better-auth"],Z&&(delete w["drizzle-orm"],delete w["@libsql/client"],delete w["@neondatabase/serverless"],delete $["drizzle-kit"],delete $["@electric-sql/pglite"]),x&&(delete w["@libsql/client"],w["@neondatabase/serverless"]="^0.10.0",$["@electric-sql/pglite"]="^0.2.0"),R&&(w.stripe="^17.0.0"),z&&(w.resend="^4.0.0",w["@react-email/components"]="^0.0.31"),pe&&(w.ai="^4.0.0",w["@ai-sdk/openai"]="^1.0.0",w.openai="^4.0.0",w["server-only"]="^0.0.1",w["zod-to-json-schema"]="3.24.6");let ee={"@noble/ciphers":"^1.3.0"},Le={react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"},Y={dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint",...Z?{}:{"db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"}};if(O(g,"package.json",JSON.stringify({name:j,version:"0.1.0",private:!0,scripts:Y,dependencies:w,devDependencies:$,optionalDependencies:ee,overrides:Le},null,2)),C.methodology){let v=C.methodology;x||(v=v.replace(/import \{ pgTable, text, timestamp(?:, boolean)? \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
2691
2691
  import { sql } from "drizzle-orm";`).replace(/import \{ pgTable, text \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text } from "drizzle-orm/sqlite-core";
2692
- import { sql } from "drizzle-orm";`).replace(/pgTable/g,"sqliteTable").replace(/drizzle-orm\/pg-core/g,"drizzle-orm/sqlite-core").replace(/timestamp\("created_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("created_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("updated_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("updated_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("([a-z_]+)"\)/g,'text("$1")').replace(/boolean\("([a-z_]+)"\)\.default\(false\)/g,'integer("$1", { mode: "boolean" }).default(false)')),x=gs(x),x=x+`
2693
-
2694
- `+Hd+`
2695
- `,N(d,"AGENTS.md",x),N(d,"CLAUDE.md",x),Yd(d,x)}b.skills&&Object.keys(b.skills).length>0&&Xd(d,b.skills);let Y=a??u?.designMd;if(Y&&N(d,"DESIGN.md",Y),l&&N(d,"PLAN.md",l),B)if(N(d,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);",' } else if (process.env.NODE_ENV !== "production") {'," // Local dev \u2014 PGlite (zero-install embedded Postgres). Gating on"," // NODE_ENV !== 'production' lets webpack/esbuild dead-code-eliminate"," // this entire branch in `next build` and the Cloudflare Worker"," // bundle, so pglite + its 30MB WASM never reach prod. In `next dev`"," // the branch is live, the static require resolves ./db-local, and"," // pglite (declared in next.config.ts's serverExternalPackages) is"," // left as an external runtime import. No bundler-evasion tricks."," // eslint-disable-next-line @typescript-eslint/no-require-imports",' const { createLocalDb } = require("./db-local");'," _db = createLocalDb();"," } else {"," throw new Error(",` "DATABASE_URL is not set in production. The Mistflow deploy pipeline injects it automatically \u2014 check the project's env vars in the dashboard."`," );"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
2696
- `)),N(d,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its 30MB","// WASM binary. db.ts only requires this file when NODE_ENV !==","// 'production', so esbuild dead-code-eliminates the import in prod and","// never reaches this file. In dev, pglite is declared as a server","// external package in next.config.ts so webpack leaves it alone too.","",'import { PGlite } from "@electric-sql/pglite";','import { drizzle } from "drizzle-orm/pglite";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
2697
- `)),N(d,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
2698
- `)),k)N(d,"db/schema/index.ts",["// Re-export schema tables here as they are added.",""].join(`
2699
- `)),N(d,"db/index.ts",["// Re-export schema tables here as they are added.",'export * from "./schema";',""].join(`
2700
- `));else{N(d,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
2701
- `)),N(d,"db/schema/index.ts",['export * from "./auth";',""].join(`
2702
- `)),N(d,"db/index.ts",['export * from "./schema/auth";',""].join(`
2703
- `));let x=u.defaultRole??"user";N(d,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { genericOAuth } from "better-auth/plugins/generic-oauth";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"","async function sendEmail({ to, subject, html, fallbackUrl }: { to: string; subject: string; html: string; fallbackUrl?: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {"," if (fallbackUrl) {"," console.error(`\\n[auth] No RESEND_API_KEY set. Email to ${to} was not sent.`);"," console.error(`[auth] Dev fallback \u2014 use this link directly:\\n ${fallbackUrl}\\n`);"," } else {"," console.error(`[auth] RESEND_API_KEY not set \u2014 skipping email send to ${to}`);"," }"," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' const body = await res.text().catch(() => "unknown");'," console.error(`[auth] Email send failed (${res.status}): ${body}`);"," throw new Error(`Email send failed: ${res.status}`);"," }","}","","function createAuth() {",' const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',' const isLocal = baseURL.includes("localhost") || baseURL.includes("127.0.0.1");'," const canSendEmail = Boolean(process.env.RESEND_API_KEY);"," const mistflowAppId = process.env.MISTFLOW_APP_ID;"," const mistflowOAuthProxyURL = process.env.MISTFLOW_OAUTH_PROXY_URL;"," // Refuse to boot a production app with email auth but no mail sender. Mistflow's"," // deploy pipeline injects a managed Resend key automatically; if it's missing,"," // that's a real misconfig and silent fallbacks let unverified users sign up."," if (!isLocal && !canSendEmail) {",` throw new Error("[auth] RESEND_API_KEY is required in production. The Mistflow deploy pipeline injects one automatically \u2014 if you're seeing this, check the project's env vars in the dashboard, or set your own RESEND_API_KEY.");`," }"," return betterAuth({"," baseURL,"," // Include the Mistflow OAuth proxy in trustedOrigins so Better Auth"," // accepts the OAuth callback round-trip without 'invalid origin' errors."," trustedOrigins: [baseURL, mistflowOAuthProxyURL].filter((u): u is string => Boolean(u)),",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,"," requireEmailVerification: !isLocal && canSendEmail,"," sendResetPassword: async ({ user, token }: { user: { email: string; name: string }; url: string; token: string }) => {"," // Better Auth's default reset URL points at /reset-password/:token (path),"," // which our frontend doesn't route. We build our own pointing at our"," // /reset-password?token=xxx page which reads the token from the query."," const resetUrl = `${baseURL}/reset-password?token=${token}`;"," await sendEmail({"," to: user.email,",' subject: "Reset your password",',' html: `<p>Hi ${user.name},</p><p>Click the link below to reset your password:</p><p><a href="${resetUrl}">${resetUrl}</a></p>`,'," fallbackUrl: isLocal ? resetUrl : undefined,"," });"," },"," },"," emailVerification: {"," sendOnSignUp: canSendEmail,"," autoSignInAfterVerification: true,"," sendVerificationEmail: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Verify your email address",',' html: `<p>Hi ${user.name},</p><p>Click the link below to verify your email:</p><p><a href="${url}">${url}</a></p>`,'," fallbackUrl: isLocal ? url : undefined,"," });"," },"," },"," secret: process.env.AUTH_SECRET,"," plugins: [",` admin({ defaultRole: "${x}" }),`," ...(mistflowAppId && mistflowOAuthProxyURL ? ["," genericOAuth({"," config: [{",' providerId: "google",'," clientId: mistflowAppId,",' clientSecret: "pkce",'," discoveryUrl: `${mistflowOAuthProxyURL}/.well-known/openid-configuration`,",' scopes: ["openid", "email", "profile"],'," pkce: true,"," redirectURI: `${baseURL}/api/auth/oauth2/callback/google`,"," }],"," }),"," ] : []),"," nextCookies(),"," ],"," databaseHooks: {"," user: {"," create: {"," // Auto-promote the app owner to admin on first signup. ADMIN_EMAIL"," // is injected by the Mistflow deploy pipeline (the email of the"," // account that ran mist_deploy). Email verification still gates"," // login when Resend is configured, so a collision attempt can't"," // actually sign in without clicking a link delivered to the"," // owner's inbox."," before: async (user: { email?: string; [k: string]: unknown }) => {"," const adminEmail = process.env.ADMIN_EMAIL;"," if (adminEmail && user.email?.toLowerCase() === adminEmail.toLowerCase()) {",' return { data: { ...user, role: "admin" } };'," }"," return { data: user };"," },"," },"," },"," },"," socialProviders: {"," ...(process.env.GITHUB_CLIENT_ID ? {"," github: {"," clientId: process.env.GITHUB_CLIENT_ID,"," clientSecret: process.env.GITHUB_CLIENT_SECRET!,"," },"," } : {}),"," },"," });","}","","// Lazy init \u2014 process.env isn't populated at module scope on Cloudflare Workers.","// The `has` trap is required: better-auth's toNextJsHandler does",'// `"handler" in auth ? auth.handler(request) : auth(request)` \u2014 without a `has`',"// trap the default forwards to the empty target object, returns false, and the","// handler tries to call the Proxy as a function, which throws TypeError and","// returns 500 on every /api/auth/* request.","let _auth: ReturnType<typeof createAuth> | null = null;","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_target, prop, receiver) {"," if (!_auth) _auth = createAuth();"," const value = Reflect.get(_auth, prop, receiver);",' if (typeof value === "function") return value.bind(_auth);'," return value;"," },"," has(_target, prop) {"," if (!_auth) _auth = createAuth();"," return prop in _auth;"," },","});",""].join(`
2704
- `))}}else N(d,"package.json",JSON.stringify({name:v,version:"0.1.0",private:!0},null,2));let $=a??u?.designMd;N(d,"app/globals.css",op(W,$)),N(d,"app/layout.tsx",lp(v,W,ee?.language)),N(d,"README.md",kp(v,u,{hasStripe:y,hasResend:A,hasStorage:z,hasAdmin:H,hasAI:ne,isNeon:B})),N(d,"contracts/README.md",hs());let V=u?.dataModel??[],M=new Set,pe=0;for(let f of V){let E=f.entity??f.name;if(!E||typeof E!="string")continue;let S=ys(E);M.has(S)||(M.add(S),N(d,S,fs(E)),pe++)}pe===0&&N(d,"contracts/.gitkeep","");let te=[],R=u?.publicPages;if(Array.isArray(R))te=R;else if(typeof R=="string"){try{te=JSON.parse(R)}catch{te=[]}Array.isArray(te)||(te=[])}if(!te.includes("/")){let f=u?.steps?.some(S=>{let de=((S.name??"")+" "+(S.description??"")).toLowerCase();return de.includes("landing")||de.includes("marketing")||de.includes("homepage")}),E=u?.pages?.some(S=>S.path==="/");(f||E)&&(te=["/",...te])}let ge={name:v,summary:u?.summary,authModel:_,roles:u?.roles,defaultRole:u?.defaultRole,publicPages:te,navStyle:u?.navStyle,multiTenant:u?.multiTenant,pages:u?.pages,dataModel:u?.dataModel,design:u?.design},K=up(ge);K&&N(d,"middleware.ts",K);let ae=mp(ge);ae&&N(d,ae.path,ae.content);let Oe=hp(ge);if(Oe&&N(d,"lib/roles.ts",Oe),N(d,"app/page.tsx",gp(ge)),N(d,"app/(dashboard)/layout.tsx",fp(ge,H)),N(d,"app/(dashboard)/dashboard/page.tsx",yp(ge)),ge.multiTenant){let f=bp(ge,B);f&&N(d,"db/schema/organization.ts",f);let E=wp(ge);E&&N(d,"lib/org.ts",E);let S=vp(ge);S&&N(d,"components/org-switcher.tsx",S)}N(d,"tsconfig.json",JSON.stringify({compilerOptions:{target:"ES2017",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!1,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,plugins:[{name:"next"}],paths:{"@/*":["./*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],exclude:["node_modules"]},null,2)),y&&N(d,"lib/stripe.ts",['import Stripe from "stripe";',"","let _stripe: Stripe | null = null;","","function getStripe(): Stripe {"," if (!_stripe) {"," if (!process.env.STRIPE_SECRET_KEY) {",' throw new Error("STRIPE_SECRET_KEY is not set");'," }"," _stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {"," typescript: true,"," });"," }"," return _stripe;","}","","// Lazy proxy \u2014 Stripe isn't initialized at import/build time","export const stripe = new Proxy({} as Stripe, {"," get(_target, prop) {"," return (getStripe() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
2705
- `)),A&&(N(d,"lib/resend.ts",['import { Resend } from "resend";',"","let _resend: Resend | null = null;","","function getResend(): Resend {"," if (!_resend) {"," if (!process.env.RESEND_API_KEY) {",' throw new Error("RESEND_API_KEY is not set");'," }"," _resend = new Resend(process.env.RESEND_API_KEY);"," }"," return _resend;","}","","// Lazy proxy \u2014 Resend isn't initialized at import/build time","export const resend = new Proxy({} as Resend, {"," get(_target, prop) {"," return (getResend() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
2706
- `)),N(d,"lib/email.ts",['import { resend } from "./resend";',"",'const FROM = process.env.EMAIL_FROM ?? "onboarding@resend.dev";',"","export async function sendEmail({"," to,"," subject,"," react,","}: {"," to: string;"," subject: string;"," react: React.ReactElement;","}) {"," return resend.emails.send({ from: FROM, to, subject, react });","}",""].join(`
2707
- `)),N(d,"lib/server/email.ts",['import "server-only";','import { render } from "@react-email/render";','import type { ReactElement } from "react";',"",'export class EmailConfigError extends Error { readonly code = "email_config"; }','export class EmailRateLimitError extends Error { readonly code = "email_rate_limit"; }','export class EmailCreditExhaustedError extends Error { readonly code = "email_credits_exhausted"; }','export class EmailUpstreamError extends Error { readonly code = "email_upstream_error"; }','export class EmailValidationError extends Error { readonly code = "email_validation"; }',"","function runtimeKey(): string | undefined {"," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","","export type EmailSendOptions = {"," to: string | string[];"," subject: string;"," html?: string;"," text?: string;"," react?: ReactElement;"," cc?: string[];"," bcc?: string[];"," replyTo?: string;"," idempotencyKey?: string;"," tags?: Record<string, string>;","};","","export const email = {"," /** Send an email. Sandbox decision is server-enforced via the runtime key's"," * environment field \u2014 your app cannot accidentally email real users from"," * dev or preview deploys. Real sends only fire when the key is",' * environment="production".'," *"," * React components are rendered to HTML locally before the gateway call"," * (React doesn't serialize over HTTP). */"," async send(opts: EmailSendOptions): Promise<{ id: string; sandbox?: boolean }> {"," if (!opts.to || (Array.isArray(opts.to) && opts.to.length === 0)) {",' throw new EmailValidationError("Recipient (to) is required");'," }"," if (!opts.subject) {",' throw new EmailValidationError("Subject is required");'," }"," let html = opts.html;"," if (opts.react && !html) {"," html = await render(opts.react);"," }",""," const key = runtimeKey();"," if (key) {"," // Managed mode \u2014 gateway handles sandbox enforcement, idempotency, billing."," const body = {"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, replyTo: opts.replyTo,"," idempotencyKey: opts.idempotencyKey, tags: opts.tags,"," };",' const r = await fetch(apiUrl() + "/api/email/send", {',' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": key },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new EmailConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (r.status === 402) throw new EmailCreditExhaustedError("Email/AI credits exhausted.");',' if (r.status === 429) throw new EmailRateLimitError("Rate limited.");'," if (r.status === 422) throw new EmailValidationError(await r.text());",' if (!r.ok) throw new EmailUpstreamError("Email gateway error " + r.status);'," return (await r.json()) as { id: string; sandbox?: boolean };"," }",""," if (process.env.RESEND_API_KEY) {"," // BYOK direct \u2014 no sandbox enforcement, user is responsible.",' const { Resend } = await import("resend");'," const client = new Resend(process.env.RESEND_API_KEY);",' const fromAddr = process.env.EMAIL_FROM ?? "onboarding@resend.dev";'," const result = await client.emails.send({"," from: fromAddr,"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, reply_to: opts.replyTo,",' ...(opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}),'," });"," if (result.error) throw new EmailUpstreamError(result.error.message);",' return { id: result.data?.id ?? "unknown", sandbox: false };'," }",""," throw new EmailConfigError(",` "Email is not configured. Run 'mist_setup' for managed mode (sandbox-safe in dev) or set RESEND_API_KEY."`," );"," },","};",""].join(`
2708
- `))),z&&(N(d,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai";',"const RUNTIME_KEY = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","",'export type UploadMode = "rename" | "overwrite" | "fail";',"","export interface UploadIntent {"," /** Pre-signed PUT URL \u2014 client uploads bytes here directly. Short-lived (15 min). */"," uploadUrl: string;"," /** The fully-qualified storage key the file ends up at. Use this when persisting attachment refs. */"," finalKey: string;"," /** ISO8601 timestamp when the signed URL expires. */"," expiresAt: string;"," /** Hard upload size cap, in bytes (storage-edge enforced). */"," maxSize: number;","}","","function authHeaders(): Record<string, string> {"," if (!RUNTIME_KEY) {",` throw new Error("Storage requires MISTFLOW_RUNTIME_KEY. Run 'mist_setup' or check your .env.local.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": RUNTIME_KEY,'," };","}","","// 100MB hard cap matches the backend's storage_gateway.MAX_UPLOAD_SIZE_BYTES.","const MAX_UPLOAD_SIZE = 100 * 1024 * 1024;","","/**"," * Ask Mistflow for a pre-signed PUT URL."," *"," * The runtime key scopes the upload to this project's storage prefix on R2 \u2014"," * other projects can't read/write each other's files. The signed URL is good"," * for 15 minutes; the client PUTs the bytes directly to R2 (no proxy through"," * Mistflow). Persist `finalKey` (not `file.name`) when storing the attachment"," * reference, since the backend may have prefixed it for project isolation."," */","export async function getUploadIntent("," key: string,",' contentType: string = "application/octet-stream",'," contentLength: number,","): Promise<UploadIntent> {"," if (contentLength > MAX_UPLOAD_SIZE) {"," throw new Error(`File is over the 100MB upload limit (${contentLength} bytes)`);"," }"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-upload`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key, contentType, contentLength }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return { ...data, maxSize: MAX_UPLOAD_SIZE };","}","","/** Get a short-lived signed download URL for a previously-uploaded key. */","export async function getDownloadUrl(finalKey: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-download`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.downloadUrl as string;","}","","export async function deleteFile(finalKey: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/object`, {",' method: "DELETE",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });","}","","/**"," * Upload a file directly from the client to R2 using the pre-signed PUT URL."," * Returns { finalKey } \u2014 persist this when storing the attachment reference;"," * pair it with `getDownloadUrl(finalKey)` to render the file later."," */","export async function uploadFile(file: File): Promise<{ finalKey: string }> {"," const intent = await getUploadIntent(file.name, file.type, file.size);"," const res = await fetch(intent.uploadUrl, {",' method: "PUT",',' headers: { "Content-Type": file.type || "application/octet-stream" },'," body: file,"," });"," if (!res.ok) throw new Error(`Upload failed (${res.status})`);"," return { finalKey: intent.finalKey };","}",""].join(`
2709
- `)),N(d,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadIntent } from "@/lib/storage";',"","// Server-side intent broker. The route receives the client's filename +","// content type, asks Mistflow for a signed PUT URL using the project's","// runtime key, and hands the URL back to the client. The client then PUTs","// the bytes directly to R2 \u2014 bytes never proxy through this server.","export async function POST(req: NextRequest) {"," const { key, filename, contentType, contentLength } = await req.json();"," // Backwards-compat: older client code sent { filename } without { key }."," const finalKeyHint = key ?? filename;"," if (!finalKeyHint) {",' return NextResponse.json({ error: "key (or filename) is required" }, { status: 400 });'," }",' if (typeof contentLength !== "number" || contentLength < 1) {',' return NextResponse.json({ error: "contentLength is required (file size in bytes)" }, { status: 400 });'," }"," try {"," const intent = await getUploadIntent("," finalKeyHint,",' contentType ?? "application/octet-stream",'," contentLength,"," );"," return NextResponse.json(intent);"," } catch (err) {",' const msg = err instanceof Error ? err.message : "Failed to prepare upload";'," return NextResponse.json({ error: msg }, { status: 500 });"," }","}",""].join(`
2710
- `)),N(d,"lib/server/storage.ts",['import "server-only";',"",'export class StorageConfigError extends Error { readonly code = "storage_config"; }','export class StorageUpstreamError extends Error { readonly code = "storage_upstream_error"; }','export class StorageQuotaError extends Error { readonly code = "storage_quota"; }',"","function runtimeKey(): string {"," const k = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;",` if (!k) throw new StorageConfigError("Storage requires managed mode. Run 'mist_setup' to enable.");`," return k;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","async function callGateway<T>(path: string, body: unknown): Promise<T> {"," const r = await fetch(apiUrl() + path, {",' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new StorageConfigError("Runtime key rejected. Re-run mist_setup.");',' if (r.status === 402) throw new StorageQuotaError("Storage quota exhausted.");',' if (r.status === 413) throw new StorageQuotaError("File exceeds the 100MB upload limit.");',' if (!r.ok) throw new StorageUpstreamError("Storage gateway error " + r.status);'," return (await r.json()) as T;","}","","export const storage = {"," /** Upload a Blob/File. Backend mints a signed URL; client PUTs directly to R2. */"," async put(opts: { key: string; blob: Blob; contentType: string; expiresIn?: number }): Promise<{ finalKey: string }> {"," const signed = await callGateway<{ uploadUrl: string; finalKey: string; expiresAt: string }>(",' "/api/storage/sign-upload",'," {"," key: opts.key,"," contentType: opts.contentType,"," contentLength: opts.blob.size,"," expiresIn: opts.expiresIn,"," },"," );"," const res = await fetch(signed.uploadUrl, {",' method: "PUT",'," body: opts.blob,",' headers: { "Content-Type": opts.contentType },'," });"," if (!res.ok) {",' throw new StorageUpstreamError("Direct R2 upload failed: " + res.status);'," }"," return { finalKey: signed.finalKey };"," },",""," /** Get a short-lived signed download URL for a stored object. */"," async get(opts: { key: string; expiresIn?: number }): Promise<{ url: string; expiresAt: string }> {"," const signed = await callGateway<{ downloadUrl: string; expiresAt: string }>(",' "/api/storage/sign-download",'," { key: opts.key, expiresIn: opts.expiresIn },"," );"," return { url: signed.downloadUrl, expiresAt: signed.expiresAt };"," },",""," /** Delete an object. Server-side delete via R2 SDK. */"," async delete(opts: { key: string }): Promise<void> {",' const r = await fetch(apiUrl() + "/api/storage/object", {',' method: "DELETE",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify({ key: opts.key }),"," });"," if (!r.ok && r.status !== 204) {",' throw new StorageUpstreamError("Delete failed: " + r.status);'," }"," },",""," /** List objects under an optional prefix. Always scoped to your project. */"," async list(opts: { prefix?: string; limit?: number; cursor?: string } = {}): Promise<{ keys: { key: string; size: number }[]; cursor?: string }> {",' return callGateway("/api/storage/list", opts);'," },","};",""].join(`
2711
- `))),ne&&(N(d,"lib/server/ai.ts",['import "server-only";',"",'import { createOpenAI } from "@ai-sdk/openai";','import { streamText, type CoreMessage } from "ai";','import type { z } from "zod";','import { zodToJsonSchema } from "zod-to-json-schema";',"","export const MISTFLOW_AI_HELPER_VERSION = 2;","","// \u2500\u2500 Typed error hierarchy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Catch the specific class to give the user actionable copy.",'export class AIConfigError extends Error { readonly code = "ai_config"; }','export class AIRateLimitError extends Error { readonly code = "ai_rate_limit"; }','export class AICreditExhaustedError extends Error { readonly code = "ai_credits_exhausted"; }','export class AIModelError extends Error { readonly code = "ai_model_error"; }',"export class AISchemaError extends Error {",' readonly code = "ai_schema_error";'," /** Raw model output that failed validation. Redacted by default; set"," * MISTFLOW_DEBUG=1 in dev to see full output. */"," readonly rawOutput?: string;"," constructor(message: string, rawOutput?: string) {"," super(message);"," this.rawOutput = rawOutput;"," }","}","","function redact(s: string | undefined): string | undefined {"," if (!s) return s;",' if (process.env.MISTFLOW_DEBUG === "1") return s;',' if (s.length <= 80) return "<redacted>";',' return s.slice(0, 40) + " ...<redacted>... " + s.slice(-20);',"}","","// \u2500\u2500 Env + dispatch helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",'const DEFAULT_MISTFLOW_AI_API_URL = "https://api.mistflow.ai";',"","function runtimeKey(): string | undefined {"," // Canonical name first; legacy alias for one release of compat."," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","","function mistflowAiApiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? DEFAULT_MISTFLOW_AI_API_URL).replace(/\\/$/, "");',"}","","function gatewayHeaders(): HeadersInit {"," const key = runtimeKey();"," if (!key) {",` throw new AIConfigError("MISTFLOW_RUNTIME_KEY not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY for BYOK.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": key,'," };","}","","function isManagedAvailable(): boolean { return !!runtimeKey(); }","function isBYOKAvailable(): boolean { return !!process.env.OPENROUTER_API_KEY; }","","function noConfigError(): AIConfigError {"," return new AIConfigError(",` "AI is not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY in .env.local."`," );","}","","async function callManaged(path: string, body: unknown): Promise<Response> {"," const response = await fetch(mistflowAiApiUrl() + path, {",' method: "POST",'," headers: gatewayHeaders(),"," body: JSON.stringify(body),"," });",' if (response.status === 401) throw new AIConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (response.status === 402) throw new AICreditExhaustedError("AI credits exhausted. Top up at https://app.mistflow.ai/ai-gateway");',' if (response.status === 429) throw new AIRateLimitError("Rate limited by gateway. Retry with backoff.");'," if (!response.ok) {",' const text = await response.text().catch(() => "");',' throw new AIModelError("AI gateway error " + response.status + ": " + redact(text));'," }"," return response;","}","","// BYOK direct OpenRouter \u2014 used when MISTFLOW_RUNTIME_KEY is not set.","export const openrouter = createOpenAI({"," apiKey: process.env.OPENROUTER_API_KEY,",' baseURL: "https://openrouter.ai/api/v1",'," headers: {",' "HTTP-Referer": process.env.NEXT_PUBLIC_APP_URL ?? "https://mistflow.app",',' "X-Title": "Mistflow App",'," },","});","","// \u2500\u2500 Public surface: the `ai` object \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Always import this. The wrapper handles all dispatch (managed-first,","// BYOK fallback). Never write process.env.OPENROUTER_API_KEY in feature code.","","export type TextOptions = {"," messages: CoreMessage[];"," model?: string;"," useCase?: string;"," idempotencyKey?: string;","};","","export type ImageOptions = { prompt: string; size?: string; model?: string; idempotencyKey?: string };","export type EmbedOptions = { model?: string };","export type TTSOptions = { text: string; voice?: string; model?: string };","export type STTOptions = { audio: Blob | ArrayBuffer; model?: string };","export type RealtimeOptions = { instructions?: string; useCase?: string };","","export const ai = {"," async text(opts: TextOptions): Promise<string> {"," if (isManagedAvailable()) {",' const r = await callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: false, messages: opts.messages,"," });"," const json = (await r.json()) as { text?: string };",' return json.text ?? "";'," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return await result.text;"," }"," throw noConfigError();"," },",""," async streamText(opts: TextOptions): Promise<Response> {"," if (isManagedAvailable()) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: true, messages: opts.messages,"," });"," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return result.toDataStreamResponse();"," }"," throw noConfigError();"," },",""," async extractJSON<T>(opts: { prompt: string; schema: z.ZodType<T>; model?: string; useCase?: string }): Promise<T> {"," // Per Codex review: no dedicated /runtime/extract-json endpoint."," // Wrapper uses /runtime/text + JSON-schema-mode + local Zod validation.",' const jsonSchema = zodToJsonSchema(opts.schema, { target: "openApi3" });'," const messages: CoreMessage[] = [",' { role: "system", content: "Respond ONLY with valid JSON matching this schema: " + JSON.stringify(jsonSchema) },',' { role: "user", content: opts.prompt },'," ];",' const text = await this.text({ messages, model: opts.model, useCase: opts.useCase ?? "extract" });'," let parsed: unknown;"," try { parsed = JSON.parse(text); }",' catch { throw new AISchemaError("Model returned non-JSON output", redact(text)); }'," const result = opts.schema.safeParse(parsed);"," if (!result.success) {",' throw new AISchemaError("Model output failed schema validation: " + result.error.message, redact(text));'," }"," return result.data;"," },",""," async embed(input: string | string[], opts: EmbedOptions = {}): Promise<number[][]> {"," if (!isManagedAvailable()) {"," // BYOK embed via OpenRouter is not in v1; require managed mode for embeddings."," throw noConfigError();"," }",' const r = await callManaged("/api/ai-gateway/runtime/embed", { input, model: opts.model });'," const json = (await r.json()) as { vectors: number[][] };"," return json.vectors;"," },",""," async generateImage(opts: ImageOptions): Promise<{ url: string }[]> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt: opts.prompt, model: opts.model, size: opts.size,"," idempotency_key: opts.idempotencyKey,"," });"," const json = (await r.json()) as { url?: string; image?: string };",' return [{ url: json.url ?? json.image ?? "" }];'," },",""," async speak(opts: TTSOptions): Promise<Blob> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/tts", {'," text: opts.text, voice: opts.voice, model: opts.model,"," });"," return await r.blob();"," },",""," async transcribe(opts: STTOptions): Promise<{ text: string }> {"," if (!isManagedAvailable()) throw noConfigError();"," const blob = opts.audio instanceof Blob ? opts.audio : new Blob([opts.audio]);"," const form = new FormData();",' form.append("audio", blob);',' if (opts.model) form.append("model", opts.model);'," const key = runtimeKey();"," if (!key) throw noConfigError();",' const response = await fetch(mistflowAiApiUrl() + "/api/ai-gateway/runtime/stt", {',' method: "POST", body: form, headers: { "X-Mistflow-AI-Key": key },'," });",' if (!response.ok) throw new AIModelError("STT failed: " + response.status);'," return (await response.json()) as { text: string };"," },",""," async createRealtimeSession(opts: RealtimeOptions = {}): Promise<Record<string, unknown>> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/realtime-session", {',' use_case: opts.useCase ?? "agent", instructions: opts.instructions,'," });"," return (await r.json()) as Record<string, unknown>;"," },","};","","// \u2500\u2500 Legacy named exports (back-compat for older scaffolds + chat route) \u2500\u2500","// These wrap the new `ai` object so existing call sites keep working.",'export type AiCapability = "llm" | "voice_realtime" | "tts" | "stt" | "image";',"type ManagedTextOptions = { capability?: AiCapability; useCase?: string; model?: string; idempotencyKey?: string; stream?: boolean };","",'export function openrouterModel(model = "openai/gpt-5-mini") { return openrouter(model); }',"",'export async function streamOpenRouterText(messages: CoreMessage[], model = "openai/gpt-5-mini") {'," return streamText({ model: openrouter(model), messages });","}","","export async function mistflowManagedText(messages: CoreMessage[], options: ManagedTextOptions = {}) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: options.capability ?? "llm", use_case: options.useCase ?? "chat",'," model: options.model, idempotency_key: options.idempotencyKey,"," stream: options.stream ?? false, messages,"," });","}","","export async function mistflowManagedImage(prompt: string, options: { model?: string; size?: string; idempotencyKey?: string } = {}) {",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt, model: options.model, idempotency_key: options.idempotencyKey, size: options.size,"," });"," return await r.json();","}","","export async function mistflowManagedRealtimeSession(instructions?: string) {"," return ai.createRealtimeSession({ instructions });","}","","export async function reportDirectAIUsage(report: Record<string, unknown>): Promise<void> {"," if (!isManagedAvailable()) return;",' try { await callManaged("/api/ai-gateway/runtime/report-usage", report); } catch { /* never break user request path */ }',"}",""].join(`
2712
- `)),N(d,"lib/ai.ts",['import "server-only";',"",'export * from "./server/ai";',""].join(`
2713
- `)),N(d,"app/api/chat/route.ts",['import { ai, AIConfigError, AICreditExhaustedError } from "@/lib/server/ai";','import type { CoreMessage } from "ai";',"","export async function POST(req: Request) {"," const { messages } = (await req.json()) as { messages?: CoreMessage[] };"," if (!messages) {",' return Response.json({ error: "messages is required" }, { status: 400 });'," }"," try {"," return await ai.streamText({ messages });"," } catch (e) {"," if (e instanceof AIConfigError) return Response.json({ error: e.message }, { status: 503 });"," if (e instanceof AICreditExhaustedError) return Response.json({ error: e.message }, { status: 402 });",' return Response.json({ error: "AI request failed" }, { status: 500 });'," }","}",""].join(`
2714
- `)));let ke=Array.isArray(u?.integrations)?u.integrations.map(f=>({name:f.name,preset:f.preset,envVars:f.envVars??[]})):[],we={};for(let f of ke)for(let E of f.envVars??[])we[E.key]||(we[E.key]={description:E.description,setupUrl:E.setupUrl,...f.name?{integration:f.name}:{}});let Le=ee?.requestedSubdomain||void 0,Rt={name:v,methodologyVersion:b?.version??"1.0",createdAt:new Date().toISOString(),...o?{planId:o}:{},...Le?{requestedSubdomain:Le}:{},plan:Array.isArray(u?.steps)?{...u,steps:u.steps.map(f=>({number:f.number,name:f.name??f.title,description:f.description,entities:f.entities,pages:f.pages,features:f.features,status:"pending"}))}:u,dbProvider:se,env:{managed:{...!I&&B?{DATABASE_URL:{description:"Postgres connection URL",scope:"production"}}:I?{}:{TURSO_URL:{description:"Turso database URL",scope:"production"},TURSO_AUTH_TOKEN:{description:"Turso database auth token",scope:"production"}},...k?{}:{AUTH_SECRET:{description:"Auth encryption secret",scope:"production"}},...y?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...A?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{}},...Object.keys(we).length>0?{required:we}:{}},authModel:_??"email",roles:u?.roles??null,navStyle:u?.navStyle??"sidebar",multiTenant:u?.multiTenant??!1,hasAdmin:H,hasResend:A,hasStorage:z,hasAI:ne,deploy:null};N(d,"mistflow.json",JSON.stringify(Rt,null,2)),zt(d);let Ve=qd(32).toString("hex"),He=y?`
2692
+ import { sql } from "drizzle-orm";`).replace(/pgTable/g,"sqliteTable").replace(/drizzle-orm\/pg-core/g,"drizzle-orm/sqlite-core").replace(/timestamp\("created_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("created_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("updated_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("updated_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("([a-z_]+)"\)/g,'text("$1")').replace(/boolean\("([a-z_]+)"\)\.default\(false\)/g,'integer("$1", { mode: "boolean" }).default(false)')),v=fs(v),v=v+`
2693
+
2694
+ `+Wd+`
2695
+ `,O(g,"AGENTS.md",v),O(g,"CLAUDE.md",v),Qd(g,v)}C.skills&&Object.keys(C.skills).length>0&&Zd(g,C.skills);let Q=a??p?.designMd;if(Q&&O(g,"DESIGN.md",Q),c&&O(g,"PLAN.md",c),x)if(O(g,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);",' } else if (process.env.NODE_ENV !== "production") {'," // Local dev \u2014 PGlite (zero-install embedded Postgres). Gating on"," // NODE_ENV !== 'production' lets webpack/esbuild dead-code-eliminate"," // this entire branch in `next build` and the Cloudflare Worker"," // bundle, so pglite + its 30MB WASM never reach prod. In `next dev`"," // the branch is live, the static require resolves ./db-local, and"," // pglite (declared in next.config.ts's serverExternalPackages) is"," // left as an external runtime import. No bundler-evasion tricks."," // eslint-disable-next-line @typescript-eslint/no-require-imports",' const { createLocalDb } = require("./db-local");'," _db = createLocalDb();"," } else {"," throw new Error(",` "DATABASE_URL is not set in production. The Mistflow deploy pipeline injects it automatically \u2014 check the project's env vars in the dashboard."`," );"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
2696
+ `)),O(g,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its 30MB","// WASM binary. db.ts only requires this file when NODE_ENV !==","// 'production', so esbuild dead-code-eliminates the import in prod and","// never reaches this file. In dev, pglite is declared as a server","// external package in next.config.ts so webpack leaves it alone too.","",'import { PGlite } from "@electric-sql/pglite";','import { drizzle } from "drizzle-orm/pglite";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
2697
+ `)),O(g,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
2698
+ `)),y)O(g,"db/schema/index.ts",["// Re-export schema tables here as they are added.",""].join(`
2699
+ `)),O(g,"db/index.ts",["// Re-export schema tables here as they are added.",'export * from "./schema";',""].join(`
2700
+ `));else{O(g,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
2701
+ `)),O(g,"db/schema/index.ts",['export * from "./auth";',""].join(`
2702
+ `)),O(g,"db/index.ts",['export * from "./schema/auth";',""].join(`
2703
+ `));let v=p.defaultRole??"user";O(g,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { genericOAuth } from "better-auth/plugins/generic-oauth";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"","async function sendEmail({ to, subject, html, fallbackUrl }: { to: string; subject: string; html: string; fallbackUrl?: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {"," if (fallbackUrl) {"," console.error(`\\n[auth] No RESEND_API_KEY set. Email to ${to} was not sent.`);"," console.error(`[auth] Dev fallback \u2014 use this link directly:\\n ${fallbackUrl}\\n`);"," } else {"," console.error(`[auth] RESEND_API_KEY not set \u2014 skipping email send to ${to}`);"," }"," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' const body = await res.text().catch(() => "unknown");'," console.error(`[auth] Email send failed (${res.status}): ${body}`);"," throw new Error(`Email send failed: ${res.status}`);"," }","}","","function createAuth() {",' const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',' const isLocal = baseURL.includes("localhost") || baseURL.includes("127.0.0.1");'," const canSendEmail = Boolean(process.env.RESEND_API_KEY);"," const mistflowAppId = process.env.MISTFLOW_APP_ID;"," const mistflowOAuthProxyURL = process.env.MISTFLOW_OAUTH_PROXY_URL;"," // Refuse to boot a production app with email auth but no mail sender. Mistflow's"," // deploy pipeline injects a managed Resend key automatically; if it's missing,"," // that's a real misconfig and silent fallbacks let unverified users sign up."," if (!isLocal && !canSendEmail) {",` throw new Error("[auth] RESEND_API_KEY is required in production. The Mistflow deploy pipeline injects one automatically \u2014 if you're seeing this, check the project's env vars in the dashboard, or set your own RESEND_API_KEY.");`," }"," return betterAuth({"," baseURL,"," // Include the Mistflow OAuth proxy in trustedOrigins so Better Auth"," // accepts the OAuth callback round-trip without 'invalid origin' errors."," trustedOrigins: [baseURL, mistflowOAuthProxyURL].filter((u): u is string => Boolean(u)),",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,"," requireEmailVerification: !isLocal && canSendEmail,"," sendResetPassword: async ({ user, token }: { user: { email: string; name: string }; url: string; token: string }) => {"," // Better Auth's default reset URL points at /reset-password/:token (path),"," // which our frontend doesn't route. We build our own pointing at our"," // /reset-password?token=xxx page which reads the token from the query."," const resetUrl = `${baseURL}/reset-password?token=${token}`;"," await sendEmail({"," to: user.email,",' subject: "Reset your password",',' html: `<p>Hi ${user.name},</p><p>Click the link below to reset your password:</p><p><a href="${resetUrl}">${resetUrl}</a></p>`,'," fallbackUrl: isLocal ? resetUrl : undefined,"," });"," },"," },"," emailVerification: {"," sendOnSignUp: canSendEmail,"," autoSignInAfterVerification: true,"," sendVerificationEmail: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Verify your email address",',' html: `<p>Hi ${user.name},</p><p>Click the link below to verify your email:</p><p><a href="${url}">${url}</a></p>`,'," fallbackUrl: isLocal ? url : undefined,"," });"," },"," },"," secret: process.env.AUTH_SECRET,"," plugins: [",` admin({ defaultRole: "${v}" }),`," ...(mistflowAppId && mistflowOAuthProxyURL ? ["," genericOAuth({"," config: [{",' providerId: "google",'," clientId: mistflowAppId,",' clientSecret: "pkce",'," discoveryUrl: `${mistflowOAuthProxyURL}/.well-known/openid-configuration`,",' scopes: ["openid", "email", "profile"],'," pkce: true,"," redirectURI: `${baseURL}/api/auth/oauth2/callback/google`,"," }],"," }),"," ] : []),"," nextCookies(),"," ],"," databaseHooks: {"," user: {"," create: {"," // Auto-promote the app owner to admin on first signup. ADMIN_EMAIL"," // is injected by the Mistflow deploy pipeline (the email of the"," // account that ran mist_deploy). Email verification still gates"," // login when Resend is configured, so a collision attempt can't"," // actually sign in without clicking a link delivered to the"," // owner's inbox."," before: async (user: { email?: string; [k: string]: unknown }) => {"," const adminEmail = process.env.ADMIN_EMAIL;"," if (adminEmail && user.email?.toLowerCase() === adminEmail.toLowerCase()) {",' return { data: { ...user, role: "admin" } };'," }"," return { data: user };"," },"," },"," },"," },"," socialProviders: {"," ...(process.env.GITHUB_CLIENT_ID ? {"," github: {"," clientId: process.env.GITHUB_CLIENT_ID,"," clientSecret: process.env.GITHUB_CLIENT_SECRET!,"," },"," } : {}),"," },"," });","}","","// Lazy init \u2014 process.env isn't populated at module scope on Cloudflare Workers.","// The `has` trap is required: better-auth's toNextJsHandler does",'// `"handler" in auth ? auth.handler(request) : auth(request)` \u2014 without a `has`',"// trap the default forwards to the empty target object, returns false, and the","// handler tries to call the Proxy as a function, which throws TypeError and","// returns 500 on every /api/auth/* request.","let _auth: ReturnType<typeof createAuth> | null = null;","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_target, prop, receiver) {"," if (!_auth) _auth = createAuth();"," const value = Reflect.get(_auth, prop, receiver);",' if (typeof value === "function") return value.bind(_auth);'," return value;"," },"," has(_target, prop) {"," if (!_auth) _auth = createAuth();"," return prop in _auth;"," },","});",""].join(`
2704
+ `))}}else O(g,"package.json",JSON.stringify({name:j,version:"0.1.0",private:!0},null,2));let V=a??p?.designMd;O(g,"app/globals.css",ip(I,V)),O(g,"app/layout.tsx",cp(j,I,L?.language)),O(g,"README.md",xp(j,p,{hasStripe:R,hasResend:z,hasStorage:W,hasAdmin:te,hasAI:pe,isNeon:x})),O(g,"contracts/README.md",gs());let F=p?.dataModel??[],ae=new Set,le=0;for(let b of F){let w=b.entity??b.name;if(!w||typeof w!="string")continue;let $=bs(w);ae.has($)||(ae.add($),O(g,$,ys(w)),le++)}le===0&&O(g,"contracts/.gitkeep","");let P=[],ke=p?.publicPages;if(Array.isArray(ke))P=ke;else if(typeof ke=="string"){try{P=JSON.parse(ke)}catch{P=[]}Array.isArray(P)||(P=[])}if(!P.includes("/")){let b=p?.steps?.some($=>{let ee=(($.name??"")+" "+($.description??"")).toLowerCase();return ee.includes("landing")||ee.includes("marketing")||ee.includes("homepage")}),w=p?.pages?.some($=>$.path==="/");(b||w)&&(P=["/",...P])}let U={name:j,summary:p?.summary,authModel:S,roles:p?.roles,defaultRole:p?.defaultRole,publicPages:P,navStyle:p?.navStyle,multiTenant:p?.multiTenant,pages:p?.pages,dataModel:p?.dataModel,design:p?.design},oe=mp(U);oe&&O(g,"middleware.ts",oe);let Ce=hp(U);Ce&&O(g,Ce.path,Ce.content);let we=gp(U);if(we&&O(g,"lib/roles.ts",we),O(g,"app/page.tsx",fp(U)),O(g,"app/(dashboard)/layout.tsx",yp(U,te)),O(g,"app/(dashboard)/dashboard/page.tsx",bp(U)),U.multiTenant){let b=wp(U,x);b&&O(g,"db/schema/organization.ts",b);let w=vp(U);w&&O(g,"lib/org.ts",w);let $=kp(U);$&&O(g,"components/org-switcher.tsx",$)}O(g,"tsconfig.json",JSON.stringify({compilerOptions:{target:"ES2017",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!1,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,plugins:[{name:"next"}],paths:{"@/*":["./*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],exclude:["node_modules"]},null,2)),R&&O(g,"lib/stripe.ts",['import Stripe from "stripe";',"","let _stripe: Stripe | null = null;","","function getStripe(): Stripe {"," if (!_stripe) {"," if (!process.env.STRIPE_SECRET_KEY) {",' throw new Error("STRIPE_SECRET_KEY is not set");'," }"," _stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {"," typescript: true,"," });"," }"," return _stripe;","}","","// Lazy proxy \u2014 Stripe isn't initialized at import/build time","export const stripe = new Proxy({} as Stripe, {"," get(_target, prop) {"," return (getStripe() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
2705
+ `)),z&&(O(g,"lib/resend.ts",['import { Resend } from "resend";',"","let _resend: Resend | null = null;","","function getResend(): Resend {"," if (!_resend) {"," if (!process.env.RESEND_API_KEY) {",' throw new Error("RESEND_API_KEY is not set");'," }"," _resend = new Resend(process.env.RESEND_API_KEY);"," }"," return _resend;","}","","// Lazy proxy \u2014 Resend isn't initialized at import/build time","export const resend = new Proxy({} as Resend, {"," get(_target, prop) {"," return (getResend() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
2706
+ `)),O(g,"lib/email.ts",['import { resend } from "./resend";',"",'const FROM = process.env.EMAIL_FROM ?? "onboarding@resend.dev";',"","export async function sendEmail({"," to,"," subject,"," react,","}: {"," to: string;"," subject: string;"," react: React.ReactElement;","}) {"," return resend.emails.send({ from: FROM, to, subject, react });","}",""].join(`
2707
+ `)),O(g,"lib/server/email.ts",['import "server-only";','import { render } from "@react-email/render";','import type { ReactElement } from "react";',"",'export class EmailConfigError extends Error { readonly code = "email_config"; }','export class EmailRateLimitError extends Error { readonly code = "email_rate_limit"; }','export class EmailCreditExhaustedError extends Error { readonly code = "email_credits_exhausted"; }','export class EmailUpstreamError extends Error { readonly code = "email_upstream_error"; }','export class EmailValidationError extends Error { readonly code = "email_validation"; }',"","function runtimeKey(): string | undefined {"," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","","export type EmailSendOptions = {"," to: string | string[];"," subject: string;"," html?: string;"," text?: string;"," react?: ReactElement;"," cc?: string[];"," bcc?: string[];"," replyTo?: string;"," idempotencyKey?: string;"," tags?: Record<string, string>;","};","","export const email = {"," /** Send an email. Sandbox decision is server-enforced via the runtime key's"," * environment field \u2014 your app cannot accidentally email real users from"," * dev or preview deploys. Real sends only fire when the key is",' * environment="production".'," *"," * React components are rendered to HTML locally before the gateway call"," * (React doesn't serialize over HTTP). */"," async send(opts: EmailSendOptions): Promise<{ id: string; sandbox?: boolean }> {"," if (!opts.to || (Array.isArray(opts.to) && opts.to.length === 0)) {",' throw new EmailValidationError("Recipient (to) is required");'," }"," if (!opts.subject) {",' throw new EmailValidationError("Subject is required");'," }"," let html = opts.html;"," if (opts.react && !html) {"," html = await render(opts.react);"," }",""," const key = runtimeKey();"," if (key) {"," // Managed mode \u2014 gateway handles sandbox enforcement, idempotency, billing."," const body = {"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, replyTo: opts.replyTo,"," idempotencyKey: opts.idempotencyKey, tags: opts.tags,"," };",' const r = await fetch(apiUrl() + "/api/email/send", {',' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": key },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new EmailConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (r.status === 402) throw new EmailCreditExhaustedError("Email/AI credits exhausted.");',' if (r.status === 429) throw new EmailRateLimitError("Rate limited.");'," if (r.status === 422) throw new EmailValidationError(await r.text());",' if (!r.ok) throw new EmailUpstreamError("Email gateway error " + r.status);'," return (await r.json()) as { id: string; sandbox?: boolean };"," }",""," if (process.env.RESEND_API_KEY) {"," // BYOK direct \u2014 no sandbox enforcement, user is responsible.",' const { Resend } = await import("resend");'," const client = new Resend(process.env.RESEND_API_KEY);",' const fromAddr = process.env.EMAIL_FROM ?? "onboarding@resend.dev";'," const result = await client.emails.send({"," from: fromAddr,"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, reply_to: opts.replyTo,",' ...(opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}),'," });"," if (result.error) throw new EmailUpstreamError(result.error.message);",' return { id: result.data?.id ?? "unknown", sandbox: false };'," }",""," throw new EmailConfigError(",` "Email is not configured. Run 'mist_setup' for managed mode (sandbox-safe in dev) or set RESEND_API_KEY."`," );"," },","};",""].join(`
2708
+ `))),W&&(O(g,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai";',"const RUNTIME_KEY = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","",'export type UploadMode = "rename" | "overwrite" | "fail";',"","export interface UploadIntent {"," /** Pre-signed PUT URL \u2014 client uploads bytes here directly. Short-lived (15 min). */"," uploadUrl: string;"," /** The fully-qualified storage key the file ends up at. Use this when persisting attachment refs. */"," finalKey: string;"," /** ISO8601 timestamp when the signed URL expires. */"," expiresAt: string;"," /** Hard upload size cap, in bytes (storage-edge enforced). */"," maxSize: number;","}","","function authHeaders(): Record<string, string> {"," if (!RUNTIME_KEY) {",` throw new Error("Storage requires MISTFLOW_RUNTIME_KEY. Run 'mist_setup' or check your .env.local.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": RUNTIME_KEY,'," };","}","","// 100MB hard cap matches the backend's storage_gateway.MAX_UPLOAD_SIZE_BYTES.","const MAX_UPLOAD_SIZE = 100 * 1024 * 1024;","","/**"," * Ask Mistflow for a pre-signed PUT URL."," *"," * The runtime key scopes the upload to this project's storage prefix on R2 \u2014"," * other projects can't read/write each other's files. The signed URL is good"," * for 15 minutes; the client PUTs the bytes directly to R2 (no proxy through"," * Mistflow). Persist `finalKey` (not `file.name`) when storing the attachment"," * reference, since the backend may have prefixed it for project isolation."," */","export async function getUploadIntent("," key: string,",' contentType: string = "application/octet-stream",'," contentLength: number,","): Promise<UploadIntent> {"," if (contentLength > MAX_UPLOAD_SIZE) {"," throw new Error(`File is over the 100MB upload limit (${contentLength} bytes)`);"," }"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-upload`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key, contentType, contentLength }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return { ...data, maxSize: MAX_UPLOAD_SIZE };","}","","/** Get a short-lived signed download URL for a previously-uploaded key. */","export async function getDownloadUrl(finalKey: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-download`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.downloadUrl as string;","}","","export async function deleteFile(finalKey: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/object`, {",' method: "DELETE",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });","}","","/**"," * Upload a file directly from the client to R2 using the pre-signed PUT URL."," * Returns { finalKey } \u2014 persist this when storing the attachment reference;"," * pair it with `getDownloadUrl(finalKey)` to render the file later."," */","export async function uploadFile(file: File): Promise<{ finalKey: string }> {"," const intent = await getUploadIntent(file.name, file.type, file.size);"," const res = await fetch(intent.uploadUrl, {",' method: "PUT",',' headers: { "Content-Type": file.type || "application/octet-stream" },'," body: file,"," });"," if (!res.ok) throw new Error(`Upload failed (${res.status})`);"," return { finalKey: intent.finalKey };","}",""].join(`
2709
+ `)),O(g,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadIntent } from "@/lib/storage";',"","// Server-side intent broker. The route receives the client's filename +","// content type, asks Mistflow for a signed PUT URL using the project's","// runtime key, and hands the URL back to the client. The client then PUTs","// the bytes directly to R2 \u2014 bytes never proxy through this server.","export async function POST(req: NextRequest) {"," const { key, filename, contentType, contentLength } = await req.json();"," // Backwards-compat: older client code sent { filename } without { key }."," const finalKeyHint = key ?? filename;"," if (!finalKeyHint) {",' return NextResponse.json({ error: "key (or filename) is required" }, { status: 400 });'," }",' if (typeof contentLength !== "number" || contentLength < 1) {',' return NextResponse.json({ error: "contentLength is required (file size in bytes)" }, { status: 400 });'," }"," try {"," const intent = await getUploadIntent("," finalKeyHint,",' contentType ?? "application/octet-stream",'," contentLength,"," );"," return NextResponse.json(intent);"," } catch (err) {",' const msg = err instanceof Error ? err.message : "Failed to prepare upload";'," return NextResponse.json({ error: msg }, { status: 500 });"," }","}",""].join(`
2710
+ `)),O(g,"lib/server/storage.ts",['import "server-only";',"",'export class StorageConfigError extends Error { readonly code = "storage_config"; }','export class StorageUpstreamError extends Error { readonly code = "storage_upstream_error"; }','export class StorageQuotaError extends Error { readonly code = "storage_quota"; }',"","function runtimeKey(): string {"," const k = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;",` if (!k) throw new StorageConfigError("Storage requires managed mode. Run 'mist_setup' to enable.");`," return k;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","async function callGateway<T>(path: string, body: unknown): Promise<T> {"," const r = await fetch(apiUrl() + path, {",' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new StorageConfigError("Runtime key rejected. Re-run mist_setup.");',' if (r.status === 402) throw new StorageQuotaError("Storage quota exhausted.");',' if (r.status === 413) throw new StorageQuotaError("File exceeds the 100MB upload limit.");',' if (!r.ok) throw new StorageUpstreamError("Storage gateway error " + r.status);'," return (await r.json()) as T;","}","","export const storage = {"," /** Upload a Blob/File. Backend mints a signed URL; client PUTs directly to R2. */"," async put(opts: { key: string; blob: Blob; contentType: string; expiresIn?: number }): Promise<{ finalKey: string }> {"," const signed = await callGateway<{ uploadUrl: string; finalKey: string; expiresAt: string }>(",' "/api/storage/sign-upload",'," {"," key: opts.key,"," contentType: opts.contentType,"," contentLength: opts.blob.size,"," expiresIn: opts.expiresIn,"," },"," );"," const res = await fetch(signed.uploadUrl, {",' method: "PUT",'," body: opts.blob,",' headers: { "Content-Type": opts.contentType },'," });"," if (!res.ok) {",' throw new StorageUpstreamError("Direct R2 upload failed: " + res.status);'," }"," return { finalKey: signed.finalKey };"," },",""," /** Get a short-lived signed download URL for a stored object. */"," async get(opts: { key: string; expiresIn?: number }): Promise<{ url: string; expiresAt: string }> {"," const signed = await callGateway<{ downloadUrl: string; expiresAt: string }>(",' "/api/storage/sign-download",'," { key: opts.key, expiresIn: opts.expiresIn },"," );"," return { url: signed.downloadUrl, expiresAt: signed.expiresAt };"," },",""," /** Delete an object. Server-side delete via R2 SDK. */"," async delete(opts: { key: string }): Promise<void> {",' const r = await fetch(apiUrl() + "/api/storage/object", {',' method: "DELETE",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify({ key: opts.key }),"," });"," if (!r.ok && r.status !== 204) {",' throw new StorageUpstreamError("Delete failed: " + r.status);'," }"," },",""," /** List objects under an optional prefix. Always scoped to your project. */"," async list(opts: { prefix?: string; limit?: number; cursor?: string } = {}): Promise<{ keys: { key: string; size: number }[]; cursor?: string }> {",' return callGateway("/api/storage/list", opts);'," },","};",""].join(`
2711
+ `))),pe&&(O(g,"lib/server/ai.ts",['import "server-only";',"",'import { createOpenAI } from "@ai-sdk/openai";','import { streamText, type CoreMessage } from "ai";','import type { z } from "zod";','import { zodToJsonSchema } from "zod-to-json-schema";',"","export const MISTFLOW_AI_HELPER_VERSION = 2;","","// \u2500\u2500 Typed error hierarchy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Catch the specific class to give the user actionable copy.",'export class AIConfigError extends Error { readonly code = "ai_config"; }','export class AIRateLimitError extends Error { readonly code = "ai_rate_limit"; }','export class AICreditExhaustedError extends Error { readonly code = "ai_credits_exhausted"; }','export class AIModelError extends Error { readonly code = "ai_model_error"; }',"export class AISchemaError extends Error {",' readonly code = "ai_schema_error";'," /** Raw model output that failed validation. Redacted by default; set"," * MISTFLOW_DEBUG=1 in dev to see full output. */"," readonly rawOutput?: string;"," constructor(message: string, rawOutput?: string) {"," super(message);"," this.rawOutput = rawOutput;"," }","}","","function redact(s: string | undefined): string | undefined {"," if (!s) return s;",' if (process.env.MISTFLOW_DEBUG === "1") return s;',' if (s.length <= 80) return "<redacted>";',' return s.slice(0, 40) + " ...<redacted>... " + s.slice(-20);',"}","","// \u2500\u2500 Env + dispatch helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",'const DEFAULT_MISTFLOW_AI_API_URL = "https://api.mistflow.ai";',"","function runtimeKey(): string | undefined {"," // Canonical name first; legacy alias for one release of compat."," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","","function mistflowAiApiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? DEFAULT_MISTFLOW_AI_API_URL).replace(/\\/$/, "");',"}","","function gatewayHeaders(): HeadersInit {"," const key = runtimeKey();"," if (!key) {",` throw new AIConfigError("MISTFLOW_RUNTIME_KEY not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY for BYOK.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": key,'," };","}","","function isManagedAvailable(): boolean { return !!runtimeKey(); }","function isBYOKAvailable(): boolean { return !!process.env.OPENROUTER_API_KEY; }","","function noConfigError(): AIConfigError {"," return new AIConfigError(",` "AI is not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY in .env.local."`," );","}","","async function callManaged(path: string, body: unknown): Promise<Response> {"," const response = await fetch(mistflowAiApiUrl() + path, {",' method: "POST",'," headers: gatewayHeaders(),"," body: JSON.stringify(body),"," });",' if (response.status === 401) throw new AIConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (response.status === 402) throw new AICreditExhaustedError("AI credits exhausted. Top up at https://app.mistflow.ai/ai-gateway");',' if (response.status === 429) throw new AIRateLimitError("Rate limited by gateway. Retry with backoff.");'," if (!response.ok) {",' const text = await response.text().catch(() => "");',' throw new AIModelError("AI gateway error " + response.status + ": " + redact(text));'," }"," return response;","}","","// BYOK direct OpenRouter \u2014 used when MISTFLOW_RUNTIME_KEY is not set.","export const openrouter = createOpenAI({"," apiKey: process.env.OPENROUTER_API_KEY,",' baseURL: "https://openrouter.ai/api/v1",'," headers: {",' "HTTP-Referer": process.env.NEXT_PUBLIC_APP_URL ?? "https://mistflow.app",',' "X-Title": "Mistflow App",'," },","});","","// \u2500\u2500 Public surface: the `ai` object \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Always import this. The wrapper handles all dispatch (managed-first,","// BYOK fallback). Never write process.env.OPENROUTER_API_KEY in feature code.","","export type TextOptions = {"," messages: CoreMessage[];"," model?: string;"," useCase?: string;"," idempotencyKey?: string;","};","","export type ImageOptions = { prompt: string; size?: string; model?: string; idempotencyKey?: string };","export type EmbedOptions = { model?: string };","export type TTSOptions = { text: string; voice?: string; model?: string };","export type STTOptions = { audio: Blob | ArrayBuffer; model?: string };","export type RealtimeOptions = { instructions?: string; useCase?: string };","","export const ai = {"," async text(opts: TextOptions): Promise<string> {"," if (isManagedAvailable()) {",' const r = await callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: false, messages: opts.messages,"," });"," const json = (await r.json()) as { text?: string };",' return json.text ?? "";'," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return await result.text;"," }"," throw noConfigError();"," },",""," async streamText(opts: TextOptions): Promise<Response> {"," if (isManagedAvailable()) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: true, messages: opts.messages,"," });"," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return result.toDataStreamResponse();"," }"," throw noConfigError();"," },",""," async extractJSON<T>(opts: { prompt: string; schema: z.ZodType<T>; model?: string; useCase?: string }): Promise<T> {"," // Per Codex review: no dedicated /runtime/extract-json endpoint."," // Wrapper uses /runtime/text + JSON-schema-mode + local Zod validation.",' const jsonSchema = zodToJsonSchema(opts.schema, { target: "openApi3" });'," const messages: CoreMessage[] = [",' { role: "system", content: "Respond ONLY with valid JSON matching this schema: " + JSON.stringify(jsonSchema) },',' { role: "user", content: opts.prompt },'," ];",' const text = await this.text({ messages, model: opts.model, useCase: opts.useCase ?? "extract" });'," let parsed: unknown;"," try { parsed = JSON.parse(text); }",' catch { throw new AISchemaError("Model returned non-JSON output", redact(text)); }'," const result = opts.schema.safeParse(parsed);"," if (!result.success) {",' throw new AISchemaError("Model output failed schema validation: " + result.error.message, redact(text));'," }"," return result.data;"," },",""," async embed(input: string | string[], opts: EmbedOptions = {}): Promise<number[][]> {"," if (!isManagedAvailable()) {"," // BYOK embed via OpenRouter is not in v1; require managed mode for embeddings."," throw noConfigError();"," }",' const r = await callManaged("/api/ai-gateway/runtime/embed", { input, model: opts.model });'," const json = (await r.json()) as { vectors: number[][] };"," return json.vectors;"," },",""," async generateImage(opts: ImageOptions): Promise<{ url: string }[]> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt: opts.prompt, model: opts.model, size: opts.size,"," idempotency_key: opts.idempotencyKey,"," });"," const json = (await r.json()) as { url?: string; image?: string };",' return [{ url: json.url ?? json.image ?? "" }];'," },",""," async speak(opts: TTSOptions): Promise<Blob> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/tts", {'," text: opts.text, voice: opts.voice, model: opts.model,"," });"," return await r.blob();"," },",""," async transcribe(opts: STTOptions): Promise<{ text: string }> {"," if (!isManagedAvailable()) throw noConfigError();"," const blob = opts.audio instanceof Blob ? opts.audio : new Blob([opts.audio]);"," const form = new FormData();",' form.append("audio", blob);',' if (opts.model) form.append("model", opts.model);'," const key = runtimeKey();"," if (!key) throw noConfigError();",' const response = await fetch(mistflowAiApiUrl() + "/api/ai-gateway/runtime/stt", {',' method: "POST", body: form, headers: { "X-Mistflow-AI-Key": key },'," });",' if (!response.ok) throw new AIModelError("STT failed: " + response.status);'," return (await response.json()) as { text: string };"," },",""," async createRealtimeSession(opts: RealtimeOptions = {}): Promise<Record<string, unknown>> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/realtime-session", {',' use_case: opts.useCase ?? "agent", instructions: opts.instructions,'," });"," return (await r.json()) as Record<string, unknown>;"," },","};","","// \u2500\u2500 Legacy named exports (back-compat for older scaffolds + chat route) \u2500\u2500","// These wrap the new `ai` object so existing call sites keep working.",'export type AiCapability = "llm" | "voice_realtime" | "tts" | "stt" | "image";',"type ManagedTextOptions = { capability?: AiCapability; useCase?: string; model?: string; idempotencyKey?: string; stream?: boolean };","",'export function openrouterModel(model = "openai/gpt-5-mini") { return openrouter(model); }',"",'export async function streamOpenRouterText(messages: CoreMessage[], model = "openai/gpt-5-mini") {'," return streamText({ model: openrouter(model), messages });","}","","export async function mistflowManagedText(messages: CoreMessage[], options: ManagedTextOptions = {}) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: options.capability ?? "llm", use_case: options.useCase ?? "chat",'," model: options.model, idempotency_key: options.idempotencyKey,"," stream: options.stream ?? false, messages,"," });","}","","export async function mistflowManagedImage(prompt: string, options: { model?: string; size?: string; idempotencyKey?: string } = {}) {",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt, model: options.model, idempotency_key: options.idempotencyKey, size: options.size,"," });"," return await r.json();","}","","export async function mistflowManagedRealtimeSession(instructions?: string) {"," return ai.createRealtimeSession({ instructions });","}","","export async function reportDirectAIUsage(report: Record<string, unknown>): Promise<void> {"," if (!isManagedAvailable()) return;",' try { await callManaged("/api/ai-gateway/runtime/report-usage", report); } catch { /* never break user request path */ }',"}",""].join(`
2712
+ `)),O(g,"lib/ai.ts",['import "server-only";',"",'export * from "./server/ai";',""].join(`
2713
+ `)),O(g,"app/api/chat/route.ts",['import { ai, AIConfigError, AICreditExhaustedError } from "@/lib/server/ai";','import type { CoreMessage } from "ai";',"","export async function POST(req: Request) {"," const { messages } = (await req.json()) as { messages?: CoreMessage[] };"," if (!messages) {",' return Response.json({ error: "messages is required" }, { status: 400 });'," }"," try {"," return await ai.streamText({ messages });"," } catch (e) {"," if (e instanceof AIConfigError) return Response.json({ error: e.message }, { status: 503 });"," if (e instanceof AICreditExhaustedError) return Response.json({ error: e.message }, { status: 402 });",' return Response.json({ error: "AI request failed" }, { status: 500 });'," }","}",""].join(`
2714
+ `)));let Se=Array.isArray(p?.integrations)?p.integrations.map(b=>({name:b.name,preset:b.preset,envVars:b.envVars??[]})):[],Me={};for(let b of Se)for(let w of b.envVars??[])Me[w.key]||(Me[w.key]={description:w.description,setupUrl:w.setupUrl,...b.name?{integration:b.name}:{}});let rt=L?.requestedSubdomain||void 0,Ve={name:j,methodologyVersion:C?.version??"1.0",createdAt:new Date().toISOString(),...o?{planId:o}:{},...rt?{requestedSubdomain:rt}:{},plan:Array.isArray(p?.steps)?{...p,steps:p.steps.map(b=>({number:b.number,name:b.name??b.title,description:b.description,entities:b.entities,pages:b.pages,features:b.features,status:"pending"}))}:p,dbProvider:J,env:{managed:{...!Z&&x?{DATABASE_URL:{description:"Postgres connection URL",scope:"production"}}:Z?{}:{TURSO_URL:{description:"Turso database URL",scope:"production"},TURSO_AUTH_TOKEN:{description:"Turso database auth token",scope:"production"}},...y?{}:{AUTH_SECRET:{description:"Auth encryption secret",scope:"production"}},...R?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...z?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{}},...Object.keys(Me).length>0?{required:Me}:{}},authModel:S??"email",roles:p?.roles??null,navStyle:p?.navStyle??"sidebar",multiTenant:p?.multiTenant??!1,hasAdmin:te,hasResend:z,hasStorage:W,hasAI:pe,deploy:null};O(g,"mistflow.json",JSON.stringify(Ve,null,2)),Ht(g);let Ke=Bd(32).toString("hex"),st=R?`
2715
2715
  # Stripe
2716
2716
  STRIPE_SECRET_KEY=
2717
2717
  STRIPE_WEBHOOK_SECRET=
2718
2718
  NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
2719
- `:"",nt=A?`
2719
+ `:"",Ae=z?`
2720
2720
  # Email (Resend)
2721
2721
  RESEND_API_KEY=
2722
2722
  EMAIL_FROM=onboarding@resend.dev
2723
- `:"",Ce="",fe=ne||z?`
2723
+ `:"",X="",Re=pe||W?`
2724
2724
  # Mistflow Cloud (server-only; never prefix with NEXT_PUBLIC_).
2725
2725
  # One runtime key authenticates every managed feature: AI gateway, file storage,
2726
2726
  # and future cloud-powered features. Auto-provisioned by \`mist_init\`.
@@ -2730,26 +2730,26 @@ MISTFLOW_API_URL=https://api.mistflow.ai
2730
2730
  MISTFLOW_AI_API_URL=https://api.mistflow.ai
2731
2731
  # BYOK fallback for AI only (used when MISTFLOW_RUNTIME_KEY is unset).
2732
2732
  OPENROUTER_API_KEY=
2733
- `:"",je=k?"":`
2734
- AUTH_SECRET=${Ve}`,rt=k?"":`
2735
- AUTH_SECRET=your-secret-here`,wt=I?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2733
+ `:"",ot=y?"":`
2734
+ AUTH_SECRET=${Ke}`,kt=y?"":`
2735
+ AUTH_SECRET=your-secret-here`,it=Z?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2736
2736
  # Set DATABASE_URL only for production or to use a remote Postgres
2737
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,st=I?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2737
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,$e=Z?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2738
2738
  # Set DATABASE_URL only for production or to use a remote Postgres
2739
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;N(d,".env.local",`${wt}${je}
2740
- ${k?"":`
2739
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;O(g,".env.local",`${it}${ot}
2740
+ ${y?"":`
2741
2741
  # Mistflow-hosted Google sign-in (zero Google Cloud setup)
2742
2742
  MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
2743
- `}${He}${nt}${Ce}${fe}`),N(d,".env.example",`${st}${rt}
2744
- ${He}${nt}${Ce}${fe}`);let m=[],g=(f,E)=>{m.push({phase:f,message:E})},w=(f,E)=>{let S=m.find(de=>de.phase===f&&!de.durationMs);S&&(S.durationMs=E)};if(e){let f=qe(e.server,e.progressToken,()=>m[m.length-1]?.message??"Setting up project...");e.cleanup=()=>f.stop()}let T=Le,O=ee?.pickedDirection??ee?.designDirection??void 0,F=ee?.imageryBrief??O?.imagery??void 0,oe=ee?.designConversationId??void 0,le=ee?{name:ee.name,summary:ee.summary,audienceType:ee.audienceType,authModel:ee.authModel,dbProvider:se,dataModel:ee.dataModel,design:ee.design,publicLanding:ee.publicLanding}:void 0,ie,L;g("register","Registering project on Mistflow...");let J=Date.now();try{let f=await St(v,{template:void 0,dbProvider:se,requestedSubdomain:T,pickedDirection:O,imageryBrief:F,planContext:le,designConversationId:oe,sessionId:s});if(ie=f.id,f.design_md&&(a=f.design_md),f.plan_md&&(l=f.plan_md),f.layout_spec&&u&&typeof u=="object"&&(u.layoutSpec=f.layout_spec),f.picker_render_html&&typeof f.picker_render_html=="string")try{let Z=he(d,".mistflow");Wt(Z,{recursive:!0}),Ze(he(Z,"picker-render.html"),f.picker_render_html),console.error(`[mist_init] picker render written to .mistflow/picker-render.html (${f.picker_render_html.length} chars)`)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);console.error(`[mist_init] picker render write failed: ${Y}`)}if(F)try{let Z=await Pr(ie),Y=he(d,"public","images");Wt(Y,{recursive:!0});let x=0,j=0;for(let[Ie,Ae]of Object.entries(Z.slots))if(Ae.status==="done"&&Ae.signed_url)try{let Re=await Ir(Ae.signed_url);Ze(he(Y,`${Ie}.png`),Re),x++}catch(Re){let gl=Re instanceof Error?Re.message:String(Re);console.error(`[mist_init] imagery: ${Ie} download failed: ${gl}`)}else(Ae.status==="queued"||Ae.status==="running")&&j++;(x>0||j>0)&&console.error(`[mist_init] imagery: ${x} ready, ${j} still rendering`)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);console.error(`[mist_init] imagery manifest fetch failed: ${Y}`)}let E=he(d,"mistflow.json"),S=JSON.parse(Gt(E,"utf-8"));if(S.projectId=ie,f.layout_spec&&S.plan&&typeof S.plan=="object"&&(S.plan.layoutSpec=f.layout_spec),Ze(E,JSON.stringify(S,null,2)),ln(d,cn(ie,v)),f.managed_env&&Object.keys(f.managed_env).length>0){let Z=he(d,".env.local"),Y=Ne(Z)?Gt(Z,"utf-8"):"";for(let[x,j]of Object.entries(f.managed_env)){let Ie=new RegExp(`^${x}=.*$`,"m");Ie.test(Y)?Y=Y.replace(Ie,`${x}=${j}`):Y+=`
2745
- ${x}=${j}`}Ze(Z,Y)}let me=f.runtimeKey;if(me?.rawKey){let Z=he(d,".env.local"),Y=Ne(Z)?Gt(Z,"utf-8"):"",x=(j,Ie)=>{let Ae=new RegExp(`^${j}=\\s*$`,"m"),Re=new RegExp(`^${j}=`,"m");Ae.test(Y)?Y=Y.replace(Ae,`${j}=${Ie}`):Re.test(Y)||(Y+=`
2746
- ${j}=${Ie}`)};x("MISTFLOW_RUNTIME_KEY",me.rawKey),x("MISTFLOW_AI_RUNTIME_KEY",me.rawKey),Ze(Z,Y)}if(!k&&f.mistflow_app_id){let Z=he(d,".env.local"),Y=Ne(Z)?Gt(Z,"utf-8"):"";/^MISTFLOW_OAUTH_PROXY_URL=/m.test(Y)||(Y+=`
2743
+ `}${st}${Ae}${X}${Re}`),O(g,".env.example",`${$e}${kt}
2744
+ ${st}${Ae}${X}${Re}`);let f=[],k=(b,w)=>{f.push({phase:b,message:w})},T=(b,w)=>{let $=f.find(ee=>ee.phase===b&&!ee.durationMs);$&&($.durationMs=w)};if(e){let b=ze(e.server,e.progressToken,()=>f[f.length-1]?.message??"Setting up project...");e.cleanup=()=>b.stop()}let N=rt,B=L?.pickedDirection??L?.designDirection??void 0,ne=L?.imageryBrief??B?.imagery??void 0,se=L?.designConversationId??void 0,me=L?{name:L.name,summary:L.summary,audienceType:L.audienceType,authModel:L.authModel,dbProvider:J,dataModel:L.dataModel,design:L.design,publicLanding:L.publicLanding}:void 0,D,G;k("register","Registering project on Mistflow...");let ve=Date.now();try{let b=await _t(j,{template:void 0,dbProvider:J,requestedSubdomain:N,pickedDirection:B,imageryBrief:ne,planContext:me,designConversationId:se,sessionId:s});if(D=b.id,b.design_md&&(a=b.design_md),b.plan_md&&(c=b.plan_md),Array.isArray(b.design_warnings)&&b.design_warnings.length>0){l=b.design_warnings;for(let Y of b.design_warnings)console.error(`[mist_init] design warning [${Y.code}]: ${Y.detail}`)}if(b.layout_spec&&p&&typeof p=="object"&&(p.layoutSpec=b.layout_spec),b.picker_render_html&&typeof b.picker_render_html=="string")try{let Y=de(g,".mistflow");Gt(Y,{recursive:!0}),et(de(Y,"picker-render.html"),b.picker_render_html),console.error(`[mist_init] picker render written to .mistflow/picker-render.html (${b.picker_render_html.length} chars)`)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);console.error(`[mist_init] picker render write failed: ${Q}`)}if(ne)try{let Y=await Ir(D),Q=de(g,"public","images");Gt(Q,{recursive:!0});let v=0,ie=0;for(let[Ie,Ee]of Object.entries(Y.slots))if(Ee.status==="done"&&Ee.signed_url)try{let Ne=await Cr(Ee.signed_url);et(de(Q,`${Ie}.png`),Ne),v++}catch(Ne){let fl=Ne instanceof Error?Ne.message:String(Ne);console.error(`[mist_init] imagery: ${Ie} download failed: ${fl}`)}else(Ee.status==="queued"||Ee.status==="running")&&ie++;(v>0||ie>0)&&console.error(`[mist_init] imagery: ${v} ready, ${ie} still rendering`)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);console.error(`[mist_init] imagery manifest fetch failed: ${Q}`)}let w=de(g,"mistflow.json"),$=JSON.parse(Vt(w,"utf-8"));if($.projectId=D,b.layout_spec&&$.plan&&typeof $.plan=="object"&&($.plan.layoutSpec=b.layout_spec),et(w,JSON.stringify($,null,2)),cn(g,dn(D,j)),b.managed_env&&Object.keys(b.managed_env).length>0){let Y=de(g,".env.local"),Q=De(Y)?Vt(Y,"utf-8"):"";for(let[v,ie]of Object.entries(b.managed_env)){let Ie=new RegExp(`^${v}=.*$`,"m");Ie.test(Q)?Q=Q.replace(Ie,`${v}=${ie}`):Q+=`
2745
+ ${v}=${ie}`}et(Y,Q)}let Le=b.runtimeKey;if(Le?.rawKey){let Y=de(g,".env.local"),Q=De(Y)?Vt(Y,"utf-8"):"",v=(ie,Ie)=>{let Ee=new RegExp(`^${ie}=\\s*$`,"m"),Ne=new RegExp(`^${ie}=`,"m");Ee.test(Q)?Q=Q.replace(Ee,`${ie}=${Ie}`):Ne.test(Q)||(Q+=`
2746
+ ${ie}=${Ie}`)};v("MISTFLOW_RUNTIME_KEY",Le.rawKey),v("MISTFLOW_AI_RUNTIME_KEY",Le.rawKey),et(Y,Q)}if(!y&&b.mistflow_app_id){let Y=de(g,".env.local"),Q=De(Y)?Vt(Y,"utf-8"):"";/^MISTFLOW_OAUTH_PROXY_URL=/m.test(Q)||(Q+=`
2747
2747
  # Mistflow-hosted Google sign-in (zero Google Cloud setup)
2748
2748
  MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
2749
- `),/^MISTFLOW_APP_ID=/m.test(Y)||(Y+=`
2749
+ `),/^MISTFLOW_APP_ID=/m.test(Q)||(Q+=`
2750
2750
  # Mistflow-hosted Google sign-in (zero GCP setup)
2751
- MISTFLOW_APP_ID=${f.mistflow_app_id}
2752
- `),Ze(Z,Y)}try{let{getBaseUrl:Z,getAuthHeaders:Y}=await Promise.resolve().then(()=>(_e(),ro)),x=Y(),j=u?.features,Ie=u?.steps,Ae={};Array.isArray(j)&&j.length>0&&(Ae.features=j.map(Re=>Re.name)),u&&(Ae.plan=u),Array.isArray(Ie)&&Ie.length>0&&(Ae.provenance=Ie.map(Re=>({feature:Re.name??Re.title??`Step ${Re.number??"?"}`,user_intent:(Re.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(Ae).length>0&&await fetch(`${Z()}/api/projects/${encodeURIComponent(ie)}/state`,{method:"PUT",headers:{...x,"Content-Type":"application/json"},body:JSON.stringify(Ae)})}catch{}m[m.length-1].message=`Registered as ${ie.slice(0,8)}`}catch(f){let E=f instanceof Error?f.message:String(f);console.error("Could not register project on backend:",E),L=`Project created locally but NOT registered on Mistflow servers (${E}). Deploy will auto-register it.`,m[m.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}w("register",Date.now()-J),g("git","Initializing git repository...");let ve=Date.now();try{let f=zd(d);await f.init(),await f.add("."),await f.commit("Initial Mistflow project setup"),m[m.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),m[m.length-1].message="Git init skipped"}w("git",Date.now()-ve);let re=m.reduce((f,E)=>f+(E.durationMs??0),0),ce={projectPath:d,projectId:ie,status:"awaiting_install"};T&&(ce.requestedSubdomain=T,ce.productionUrl=`https://${T}.mistflow.app`);let Te=m.map(f=>{let E=f.durationMs?` (${(f.durationMs/1e3).toFixed(1)}s)`:"";return`${f.message}${E}`});ce.progress=Te,ce.totalSetupTime=`${(re/1e3).toFixed(1)}s`;let ue=[];ie||ue.push("Project was not registered with Mistflow (backend error during create). mist_deploy will retry registration automatically on the first deploy."),L&&(ce.registrationWarning=L),ue.length>0&&(ce.warnings=ue);let xe=`${T?`TELL THE USER: "Your app's URL is reserved: https://${T}.mistflow.app \u2014 it goes live when you deploy. While it's being built, you'll get a local preview to watch your app come together in real time." `:""}NEXT: Call mist_install({ projectPath: "${d}" }). This is fire-and-poll \u2014 the first call returns a jobId and status: "running"; re-call with the same jobId every ~15-30s until status is "complete". Typical duration 30-90s. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. After install completes, call mist_implement({ projectPath: "${d}" }) to build the first plan step.`;return ce.nextAction=ie?xe:`${xe} NOTE: The project could not be registered with the backend during init (${L??"see registrationWarning"}). mist_deploy will retry the registration automatically on the first deploy \u2014 no manual recovery needed.`,p(JSON.stringify(ce))}catch(b){try{Ld(d,{recursive:!0,force:!0})}catch{}throw b}}var Hd,Gd,rr,Vd,Kd,Jd,tp,np,mi,ap,pp,yi,bi=P(()=>{"use strict";be();qt();Zn();cs();ds();_e();Tt();nr();bs();bs();Hd=`## Project plan (PLAN.md)
2751
+ MISTFLOW_APP_ID=${b.mistflow_app_id}
2752
+ `),et(Y,Q)}try{let{getBaseUrl:Y,getAuthHeaders:Q}=await Promise.resolve().then(()=>(_e(),so)),v=Q(),ie=p?.features,Ie=p?.steps,Ee={};Array.isArray(ie)&&ie.length>0&&(Ee.features=ie.map(Ne=>Ne.name)),p&&(Ee.plan=p),Array.isArray(Ie)&&Ie.length>0&&(Ee.provenance=Ie.map(Ne=>({feature:Ne.name??Ne.title??`Step ${Ne.number??"?"}`,user_intent:(Ne.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(Ee).length>0&&await fetch(`${Y()}/api/projects/${encodeURIComponent(D)}/state`,{method:"PUT",headers:{...v,"Content-Type":"application/json"},body:JSON.stringify(Ee)})}catch{}f[f.length-1].message=`Registered as ${D.slice(0,8)}`}catch(b){let w=b instanceof Error?b.message:String(b);console.error("Could not register project on backend:",w),G=`Project created locally but NOT registered on Mistflow servers (${w}). Deploy will auto-register it.`,f[f.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}T("register",Date.now()-ve),k("git","Initializing git repository...");let re=Date.now();try{let b=Hd(g);await b.init(),await b.add("."),await b.commit("Initial Mistflow project setup"),f[f.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),f[f.length-1].message="Git init skipped"}T("git",Date.now()-re);let fe=f.reduce((b,w)=>b+(w.durationMs??0),0),ce={projectPath:g,projectId:D,status:"awaiting_install"};N&&(ce.requestedSubdomain=N,ce.productionUrl=`https://${N}.mistflow.app`);let ue=f.map(b=>{let w=b.durationMs?` (${(b.durationMs/1e3).toFixed(1)}s)`:"";return`${b.message}${w}`});ce.progress=ue,ce.totalSetupTime=`${(fe/1e3).toFixed(1)}s`;let A=[];D||A.push("Project was not registered with Mistflow (backend error during create). mist_deploy will retry registration automatically on the first deploy."),G&&(ce.registrationWarning=G),A.length>0&&(ce.warnings=A),l.length>0&&(ce.designPipelineWarnings=l,ce.designPipelineWarningsHostAction=`Tell the user explicitly: "The design generation pipeline had a partial failure \u2014 your scaffolded landing may not match the picker preview exactly. The build will continue with fallback design tokens. If the deployed landing looks wrong, run mist_plan({ description: '<original description>' }) again to get a fresh picker." Then continue with the install step. Do not silently proceed.`);let ye=`${N?`TELL THE USER: "Your app's URL is reserved: https://${N}.mistflow.app \u2014 it goes live when you deploy. While it's being built, you'll get a local preview to watch your app come together in real time." `:""}NEXT: Call mist_install({ projectPath: "${g}" }). This is fire-and-poll \u2014 the first call returns a jobId and status: "running"; re-call with the same jobId every ~15-30s until status is "complete". Typical duration 30-90s. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. After install completes, call mist_implement({ projectPath: "${g}" }) to build the first plan step.`;return ce.nextAction=D?ye:`${ye} NOTE: The project could not be registered with the backend during init (${G??"see registrationWarning"}). mist_deploy will retry the registration automatically on the first deploy \u2014 no manual recovery needed.`,d(JSON.stringify(ce))}catch(C){try{Ud(g,{recursive:!0,force:!0})}catch{}throw C}}var Wd,Vd,sr,Kd,Jd,Yd,np,rp,hi,lp,up,bi,wi=_(()=>{"use strict";be();Bt();er();ds();ps();_e();Pt();rr();ws();ws();Wd=`## Project plan (PLAN.md)
2753
2753
 
2754
2754
  This project ships with a \`PLAN.md\` at the root \u2014 a PRD-style
2755
2755
  projection of the plan with the data model, pages, steps, and per-step
@@ -2770,17 +2770,17 @@ control plane.
2770
2770
  To change the plan (new feature, missed requirement, scope shift),
2771
2771
  call \`mist_plan\` with \`modify: true\` and a description. The backend
2772
2772
  generates a new plan revision and regenerates PLAN.md.
2773
- `;Gd=Ht.object({name:Ht.string().min(1).optional().describe("Human-readable app name (e.g. 'Task Flow'). Optional when planId is provided \u2014 the cached plan's name is used."),plan:Ht.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Ht.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Ht.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted."),sessionId:Ht.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")});rr="# Mistflow project\n\nThis is a Mistflow-generated app. The full conventions, stack guide, and\nintegration contracts are in `AGENTS.md` (universal) and `CLAUDE.md`\n(identical copy for Claude Code).\n\nThe current build plan is in `PLAN.md` \u2014 read it for the data model,\npages, steps, and acceptance criteria. The plan is render-only; do\nnot hand-edit step status or check boxes. Step status lives in\n`mistflow.json` and is updated by `mist_implement` automatically.\n\nTo change the plan, call `mist_plan` with `modify: true` \u2014 never edit\nPLAN.md's structure manually.\n",Vd=`---
2773
+ `;Vd=Wt.object({name:Wt.string().min(1).optional().describe("Human-readable app name (e.g. 'Task Flow'). Optional when planId is provided \u2014 the cached plan's name is used."),plan:Wt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Wt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Wt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted."),sessionId:Wt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")});sr="# Mistflow project\n\nThis is a Mistflow-generated app. The full conventions, stack guide, and\nintegration contracts are in `AGENTS.md` (universal) and `CLAUDE.md`\n(identical copy for Claude Code).\n\nThe current build plan is in `PLAN.md` \u2014 read it for the data model,\npages, steps, and acceptance criteria. The plan is render-only; do\nnot hand-edit step status or check boxes. Step status lives in\n`mistflow.json` and is updated by `mist_implement` automatically.\n\nTo change the plan, call `mist_plan` with `modify: true` \u2014 never edit\nPLAN.md's structure manually.\n",Kd=`---
2774
2774
  description: Mistflow project conventions \u2014 read AGENTS.md + PLAN.md first
2775
2775
  alwaysApply: false
2776
2776
  ---
2777
2777
 
2778
- ${rr}`,Kd=`# VS Code Copilot instructions
2778
+ ${sr}`,Jd=`# VS Code Copilot instructions
2779
2779
 
2780
2780
  This is the project's primary instruction file for VS Code Copilot.
2781
2781
 
2782
- ${rr}`,Jd=`read: ["CONVENTIONS.md", "AGENTS.md", "PLAN.md"]
2783
- `;tp={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},np=[["--color-background","#ffffff"],["--color-foreground","#0a0a0a"],["--color-card","#ffffff"],["--color-card-foreground","#0a0a0a"],["--color-popover","#ffffff"],["--color-popover-foreground","#0a0a0a"],["--color-muted","#f5f5f5"],["--color-muted-foreground","#525252"],["--color-border","#e5e5e5"],["--color-input","#e5e5e5"],["--color-primary","#0a0a0a"],["--color-primary-foreground","#ffffff"],["--color-ring","#0a0a0a"],["--color-secondary","#f5f5f5"],["--color-secondary-foreground","#0a0a0a"],["--color-accent","#f5f5f5"],["--color-accent-foreground","#0a0a0a"],["--color-destructive","#b91c1c"],["--color-destructive-foreground","#ffffff"],["--color-success","#15803d"],["--color-success-foreground","#ffffff"],["--color-warning","#a16207"],["--color-warning-foreground","#ffffff"],["--color-info","#0369a1"],["--color-info-foreground","#ffffff"]];mi={"Fredoka One":"Fredoka","Source Sans Pro":"Source_Sans_3","Source Serif Pro":"Source_Serif_4","Open Sans Condensed":"Open_Sans","Baloo 2":"Baloo_2","DM Serif Display":"DM_Serif_Display","DM Serif Text":"DM_Serif_Text","IBM Plex Mono":"IBM_Plex_Mono","IBM Plex Sans":"IBM_Plex_Sans","IBM Plex Serif":"IBM_Plex_Serif","Fira Code":"Fira_Code","Fira Sans":"Fira_Sans","Noto Sans JP":"Noto_Sans_JP","PT Sans":"PT_Sans","PT Serif":"PT_Serif","Work Sans":"Work_Sans","Space Mono":"Space_Mono","Space Grotesk":"Space_Grotesk","Plus Jakarta Sans":"Plus_Jakarta_Sans"};ap=new Set(["ar","he","fa","ur"]);pp={dashboard:"Home",home:"Home",overview:"Home",patient:"Users",member:"Users",user:"Users",people:"Users",team:"Users",client:"Users",contact:"Users",customer:"Users",appointment:"Calendar",schedule:"Calendar",booking:"Calendar",event:"Calendar",billing:"CreditCard",invoice:"CreditCard",payment:"CreditCard",pricing:"CreditCard",treatment:"ClipboardList",plan:"ClipboardList",task:"CheckSquare",exercise:"Dumbbell",workout:"Dumbbell",report:"BarChart3",analytics:"BarChart3",stats:"BarChart3",setting:"Settings",config:"Settings",profile:"User",account:"User",message:"MessageSquare",chat:"MessageSquare",inbox:"MessageSquare",product:"Package",item:"Package",catalog:"Package",order:"ShoppingCart",cart:"ShoppingCart",file:"FileText",document:"FileText",upload:"Upload",notification:"Bell",alert:"Bell",project:"FolderKanban",board:"FolderKanban",post:"PenSquare",blog:"PenSquare",article:"PenSquare",course:"GraduationCap",lesson:"GraduationCap",class:"GraduationCap",habit:"Target",goal:"Target",streak:"Flame",progress:"TrendingUp",feature:"Sparkles",subscription:"CreditCard",price:"CreditCard",recipe:"ChefHat",food:"UtensilsCrossed",meal:"UtensilsCrossed",pet:"PawPrint",animal:"PawPrint",music:"Music",playlist:"ListMusic",song:"Music",photo:"Image",image:"Image",gallery:"Images",video:"Video",movie:"Film",map:"MapPin",location:"MapPin",place:"MapPin",search:"Search",explore:"Compass",inventory:"Boxes",stock:"Boxes",warehouse:"Warehouse",review:"Star",rating:"Star",feedback:"Star",log:"ScrollText",history:"Clock",activity:"Activity"};yi={name:"mist_init",description:"Initialize a new Next.js project using the Mistflow stack. Downloads templates from the Mistflow registry, installs dependencies, sets up auth, and initializes git. Use this after mist_plan to create the project.",inputSchema:Gd,handler:xp}});var vi,wi=P(()=>{vi=`# Consumer Warm Archetype
2782
+ ${sr}`,Yd=`read: ["CONVENTIONS.md", "AGENTS.md", "PLAN.md"]
2783
+ `;np={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},rp=[["--color-background","#ffffff"],["--color-foreground","#0a0a0a"],["--color-card","#ffffff"],["--color-card-foreground","#0a0a0a"],["--color-popover","#ffffff"],["--color-popover-foreground","#0a0a0a"],["--color-muted","#f5f5f5"],["--color-muted-foreground","#525252"],["--color-border","#e5e5e5"],["--color-input","#e5e5e5"],["--color-primary","#0a0a0a"],["--color-primary-foreground","#ffffff"],["--color-ring","#0a0a0a"],["--color-secondary","#f5f5f5"],["--color-secondary-foreground","#0a0a0a"],["--color-accent","#f5f5f5"],["--color-accent-foreground","#0a0a0a"],["--color-destructive","#b91c1c"],["--color-destructive-foreground","#ffffff"],["--color-success","#15803d"],["--color-success-foreground","#ffffff"],["--color-warning","#a16207"],["--color-warning-foreground","#ffffff"],["--color-info","#0369a1"],["--color-info-foreground","#ffffff"]];hi={"Fredoka One":"Fredoka","Source Sans Pro":"Source_Sans_3","Source Serif Pro":"Source_Serif_4","Open Sans Condensed":"Open_Sans","Baloo 2":"Baloo_2","DM Serif Display":"DM_Serif_Display","DM Serif Text":"DM_Serif_Text","IBM Plex Mono":"IBM_Plex_Mono","IBM Plex Sans":"IBM_Plex_Sans","IBM Plex Serif":"IBM_Plex_Serif","Fira Code":"Fira_Code","Fira Sans":"Fira_Sans","Noto Sans JP":"Noto_Sans_JP","PT Sans":"PT_Sans","PT Serif":"PT_Serif","Work Sans":"Work_Sans","Space Mono":"Space_Mono","Space Grotesk":"Space_Grotesk","Plus Jakarta Sans":"Plus_Jakarta_Sans"};lp=new Set(["ar","he","fa","ur"]);up={dashboard:"Home",home:"Home",overview:"Home",patient:"Users",member:"Users",user:"Users",people:"Users",team:"Users",client:"Users",contact:"Users",customer:"Users",appointment:"Calendar",schedule:"Calendar",booking:"Calendar",event:"Calendar",billing:"CreditCard",invoice:"CreditCard",payment:"CreditCard",pricing:"CreditCard",treatment:"ClipboardList",plan:"ClipboardList",task:"CheckSquare",exercise:"Dumbbell",workout:"Dumbbell",report:"BarChart3",analytics:"BarChart3",stats:"BarChart3",setting:"Settings",config:"Settings",profile:"User",account:"User",message:"MessageSquare",chat:"MessageSquare",inbox:"MessageSquare",product:"Package",item:"Package",catalog:"Package",order:"ShoppingCart",cart:"ShoppingCart",file:"FileText",document:"FileText",upload:"Upload",notification:"Bell",alert:"Bell",project:"FolderKanban",board:"FolderKanban",post:"PenSquare",blog:"PenSquare",article:"PenSquare",course:"GraduationCap",lesson:"GraduationCap",class:"GraduationCap",habit:"Target",goal:"Target",streak:"Flame",progress:"TrendingUp",feature:"Sparkles",subscription:"CreditCard",price:"CreditCard",recipe:"ChefHat",food:"UtensilsCrossed",meal:"UtensilsCrossed",pet:"PawPrint",animal:"PawPrint",music:"Music",playlist:"ListMusic",song:"Music",photo:"Image",image:"Image",gallery:"Images",video:"Video",movie:"Film",map:"MapPin",location:"MapPin",place:"MapPin",search:"Search",explore:"Compass",inventory:"Boxes",stock:"Boxes",warehouse:"Warehouse",review:"Star",rating:"Star",feedback:"Star",log:"ScrollText",history:"Clock",activity:"Activity"};bi={name:"mist_init",description:"Initialize a new Next.js project using the Mistflow stack. Downloads templates from the Mistflow registry, installs dependencies, sets up auth, and initializes git. Use this after mist_plan to create the project.",inputSchema:Vd,handler:Sp}});var ki,vi=_(()=>{ki=`# Consumer Warm Archetype
2784
2784
 
2785
2785
  Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
2786
2786
 
@@ -2947,7 +2947,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
2947
2947
  - Small touch targets. Phone-first means \`h-12\` minimum.
2948
2948
  - Empty states that just say "No data." Be encouraging.
2949
2949
  - Dark theme as default. Consumer warm apps default to light.
2950
- `});var xi,ki=P(()=>{xi=`# Consumer Bold Archetype
2950
+ `});var Si,xi=_(()=>{Si=`# Consumer Bold Archetype
2951
2951
 
2952
2952
  Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
2953
2953
 
@@ -3118,7 +3118,7 @@ Social/competitive apps need an activity feed:
3118
3118
  - Card-only layouts with no hierarchy. Use hero cards + supporting cards.
3119
3119
  - Missing achievement/progress systems. The gamification IS the product.
3120
3120
  - Light-touch buttons. CTAs should be unmissable.
3121
- `});var Ti,Si=P(()=>{Ti=`# Professional Clean Archetype
3121
+ `});var _i,Ti=_(()=>{_i=`# Professional Clean Archetype
3122
3122
 
3123
3123
  Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
3124
3124
 
@@ -3330,7 +3330,7 @@ h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
3330
3330
  - Missing status workflows. Every booking/appointment needs a clear state machine.
3331
3331
  - Dark theme as default. Clients associate light themes with professionalism.
3332
3332
  - Emoji in the UI. Professional context.
3333
- `});var Pi,_i=P(()=>{Pi=`# Education Structured Archetype
3333
+ `});var Ii,Pi=_(()=>{Ii=`# Education Structured Archetype
3334
3334
 
3335
3335
  Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
3336
3336
 
@@ -3530,7 +3530,7 @@ border-2 border-destructive bg-destructive/5 rounded-xl p-4
3530
3530
  - Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
3531
3531
  - Long lesson pages with no progress indicator. Users need to know where they are.
3532
3532
  - Multiple competing elements per view. One thing at a time. One question at a time.
3533
- `});var Ci,Ii=P(()=>{Ci=`# Marketplace Browse Archetype
3533
+ `});var Ai,Ci=_(()=>{Ai=`# Marketplace Browse Archetype
3534
3534
 
3535
3535
  Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
3536
3536
 
@@ -3754,7 +3754,7 @@ border-b border-border/30 py-4
3754
3754
  - Small product images. The image is the primary decision-making element.
3755
3755
  - No empty state for zero search results. "No results for 'xyz'. Try broader terms."
3756
3756
  - Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
3757
- `});var Ri,Ai=P(()=>{Ri=`# SaaS Analytical Archetype
3757
+ `});var Ei,Ri=_(()=>{Ei=`# SaaS Analytical Archetype
3758
3758
 
3759
3759
  Component-level design guidance for B2B SaaS tools, CRMs, analytics dashboards, admin panels, ops tooling, and team productivity apps. This is the biggest category \u2014 most apps that don't fit consumer, marketplace, or booking archetypes land here.
3760
3760
 
@@ -3935,7 +3935,7 @@ The most recognizable B2B SaaS landing pattern.
3935
3935
  - **Inter as the only font.** Pair it with a distinctive heading font or swap it entirely.
3936
3936
  - **Centered text + centered image below.** The most overused AI hero. Use split or offset layouts.
3937
3937
  - **Animation on every element.** Efficient motion only: hero entrance, card reveals on scroll, number counters. Nothing else.
3938
- `});var Ni,Ei=P(()=>{Ni=`# Content Editorial Archetype
3938
+ `});var Oi,Ni=_(()=>{Oi=`# Content Editorial Archetype
3939
3939
 
3940
3940
  Component-level design guidance for blogs, newsletters, magazines, publications, documentation sites, knowledge bases, and wiki-style content tools. Substack, The Verge, Medium, Linear's changelog, Stripe's docs are the reference bar.
3941
3941
 
@@ -4142,7 +4142,7 @@ Below the hero: 3 featured pieces laid out as a horizontal strip with **oversize
4142
4142
  - **Dark mode as default for a reading tool.** Offer it as a toggle, not the default.
4143
4143
  - **Flashy motion while reading.** Scroll hijacking, parallax on body text, animated backgrounds behind paragraphs \u2014 all break reading flow.
4144
4144
  - **More than 2 fonts.** Heading + body is enough. Adding a third font for captions or metadata dilutes the identity.
4145
- `});var ji,Oi=P(()=>{ji=`# Devtool Technical Archetype
4145
+ `});var ji,Di=_(()=>{ji=`# Devtool Technical Archetype
4146
4146
 
4147
4147
  Component-level design guidance for developer tools, APIs, CLIs, SDKs, infrastructure platforms, monitoring/observability, AI/ML platforms, deployment targets, and CI/CD tooling. Vercel, Linear, Supabase, Sentry, Warp, Raycast, Cursor, Neon, Anthropic Console are the reference bar.
4148
4148
 
@@ -4331,7 +4331,7 @@ Numbers styled as terminal output: \`> 47,293 deploys this week\`, \`> 99.98% up
4331
4331
  - **Marketing testimonials.** Replace with GitHub star count, StackOverflow mentions, a few short founder-quoted specifics ("Cut our deploy time from 12min to 18sec" from a named engineer at a known company).
4332
4332
  - **Feature cards with rocket / lightning / puzzle icons.** Use technical icons (terminal, code, database, network) or skip icons entirely.
4333
4333
  - **Motion on code blocks** while the user is trying to read them. Type out ONCE on load, then leave them alone.
4334
- `});var Mi,Di=P(()=>{Mi=`# Creative Showcase Archetype
4334
+ `});var Li,Mi=_(()=>{Li=`# Creative Showcase Archetype
4335
4335
 
4336
4336
  Component-level design guidance for portfolios, design agencies, creative studios, photographers, artists, architects, filmmakers, and any brand whose primary selling point is "look at the work we've made." Apple, Dribbble, Behance, Pentagram, IDEO are the reference bar.
4337
4337
 
@@ -4548,7 +4548,7 @@ Premium agency touch: on first load, a full-screen loading component shows the s
4548
4548
  - **Scroll hijacking through the whole site.** Use sparingly \u2014 one or two scroll-pinned sections maximum.
4549
4549
  - **Mystery-meat navigation.** Clever is bad here. "Work / About / Contact" is fine. Don't make visitors guess.
4550
4550
  - **No contact info.** The primary purpose of this site is to generate inquiries. Make it stupid-easy to contact you.
4551
- `});var Ui,Li=P(()=>{Ui=`# Finance Clarity Archetype
4551
+ `});var $i,Ui=_(()=>{$i=`# Finance Clarity Archetype
4552
4552
 
4553
4553
  Component-level design guidance for fintech apps, invoicing tools, expense trackers, budget apps, payroll, accounting software, banking dashboards, and any product where **money is the primary data type**. Stripe, Wise, Revolut, Mercury, Brex, QuickBooks, Ramp are the reference bar.
4554
4554
 
@@ -4767,11 +4767,11 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
4767
4767
  - **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
4768
4768
  - **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
4769
4769
  - **Confidence-shaking UX:** progress bars that stall, skeletons that flash between states, tiny fonts for fine print. Users are nervous about their money; give them stability.
4770
- `});function Fi(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return $i[e]}var $i,vf,qi=P(()=>{"use strict";wi();ki();Si();_i();Ii();Ai();Ei();Oi();Di();Li();$i={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:vi},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:xi},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Ti},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Pi},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Ci},"saas-analytical":{id:"saas-analytical",name:"SaaS Analytical",description:"B2B SaaS, CRM, analytics, admin panels, ops tooling, team productivity (Linear, Notion, Stripe reference bar)",content:Ri},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Ni},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:ji},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:Mi},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:Ui}},vf=Object.keys($i)});import{spawn as Op,execFileSync as jp}from"child_process";import{existsSync as sr,mkdirSync as Hi,openSync as ks,closeSync as xs,readSync as Dp,readFileSync as Wi,writeFileSync as Gi,renameSync as Vi,unlinkSync as Mp,readdirSync as Tf,statSync as Lp}from"fs";import{homedir as Ki}from"os";import{join as Me,dirname as Ji}from"path";import{randomBytes as Yi,randomUUID as Up}from"crypto";function or(){return Me(Ki(),".mistflow","jobs")}function Fp(){return Me(Ki(),".mistflow","job-wrapper.cjs")}function qp(){let t=Fp(),e=Ji(t);sr(e)||Hi(e,{recursive:!0});let r=`v${Qi}`;if(sr(t))try{if(Wi(t,"utf-8").includes(r))return t}catch{}let n=Me(e,`.job-wrapper.tmp.${Yi(6).toString("hex")}`);return Gi(n,$p),Vi(n,t),t}function Vt(t){return Me(or(),t)}function Xi(t){return Me(Vt(t),"status.json")}function Bi(t,e){let r=Xi(t),n=Me(Ji(r),`.status.tmp.${Yi(6).toString("hex")}`);try{Gi(n,JSON.stringify(e,null,2)+`
4771
- `),Vi(n,r)}catch(i){try{Mp(n)}catch{}throw i}}function Bp(t){let e=Xi(t);if(!sr(e))return null;try{return JSON.parse(Wi(e,"utf-8"))}catch{return null}}async function mt(t){let e=`job_${Up().replace(/-/g,"").slice(0,12)}`,r=Vt(e);Hi(r,{recursive:!0}),xs(ks(Me(r,"stdout.log"),"a")),xs(ks(Me(r,"stderr.log"),"a"));let n=new Date().toISOString(),i={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:n,cmd:t.cmd,args:t.args,cwd:t.cwd};Bi(e,i);let o=qp(),s={...process.env,...t.env??{}},a=Op("node",[o,r,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:s});a.unref();let l={...i,wrapperPid:a.pid??0};return Bi(e,l),l}function zp(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function Hp(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=jp("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=zp(r),i=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(i)&&Math.abs(n-i)>2e3)return!1}catch{}return!0}function Wp(t,e){let r=Date.parse(t),n=e?Date.parse(e):Date.now();if(!Number.isFinite(r)||!Number.isFinite(n))return"0s";let i=Math.max(0,n-r),o=Math.floor(i/1e3);if(o<60)return`${o}s`;let s=Math.floor(o/60),a=o%60;return s<60?`${s}m ${a}s`:`${Math.floor(s/60)}h ${s%60}m`}function zi(t,e){if(!sr(t))return"";let r=Lp(t);if(r.size===0)return"";let n=r.size>e?r.size-e:0,i=r.size-n,o=ks(t,"r");try{let s=Buffer.alloc(i);return Dp(o,s,0,i,n),s.toString("utf-8")}finally{xs(o)}}function Gp(t,e=200){let r=zi(Me(Vt(t),"stdout.log"),65536),n=zi(Me(Vt(t),"stderr.log"),64*1024),i=[];return r.trim()&&i.push(...r.split(`
4770
+ `});function qi(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return Fi[e]}var Fi,kf,Bi=_(()=>{"use strict";vi();xi();Ti();Pi();Ci();Ri();Ni();Di();Mi();Ui();Fi={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:ki},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:Si},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:_i},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Ii},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Ai},"saas-analytical":{id:"saas-analytical",name:"SaaS Analytical",description:"B2B SaaS, CRM, analytics, admin panels, ops tooling, team productivity (Linear, Notion, Stripe reference bar)",content:Ei},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Oi},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:ji},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:Li},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:$i}},kf=Object.keys(Fi)});import{spawn as Dp,execFileSync as jp}from"child_process";import{existsSync as or,mkdirSync as Wi,openSync as xs,closeSync as Ss,readSync as Mp,readFileSync as Gi,writeFileSync as Vi,renameSync as Ki,unlinkSync as Lp,readdirSync as _f,statSync as Up}from"fs";import{homedir as Ji}from"os";import{join as Ue,dirname as Yi}from"path";import{randomBytes as Qi,randomUUID as $p}from"crypto";function ir(){return Ue(Ji(),".mistflow","jobs")}function qp(){return Ue(Ji(),".mistflow","job-wrapper.cjs")}function Bp(){let t=qp(),e=Yi(t);or(e)||Wi(e,{recursive:!0});let r=`v${Xi}`;if(or(t))try{if(Gi(t,"utf-8").includes(r))return t}catch{}let n=Ue(e,`.job-wrapper.tmp.${Qi(6).toString("hex")}`);return Vi(n,Fp),Ki(n,t),t}function Kt(t){return Ue(ir(),t)}function Zi(t){return Ue(Kt(t),"status.json")}function zi(t,e){let r=Zi(t),n=Ue(Yi(r),`.status.tmp.${Qi(6).toString("hex")}`);try{Vi(n,JSON.stringify(e,null,2)+`
4771
+ `),Ki(n,r)}catch(i){try{Lp(n)}catch{}throw i}}function zp(t){let e=Zi(t);if(!or(e))return null;try{return JSON.parse(Gi(e,"utf-8"))}catch{return null}}async function gt(t){let e=`job_${$p().replace(/-/g,"").slice(0,12)}`,r=Kt(e);Wi(r,{recursive:!0}),Ss(xs(Ue(r,"stdout.log"),"a")),Ss(xs(Ue(r,"stderr.log"),"a"));let n=new Date().toISOString(),i={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:n,cmd:t.cmd,args:t.args,cwd:t.cwd};zi(e,i);let o=Bp(),s={...process.env,...t.env??{}},a=Dp("node",[o,r,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:s});a.unref();let l={...i,wrapperPid:a.pid??0};return zi(e,l),l}function Hp(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function Wp(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=jp("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=Hp(r),i=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(i)&&Math.abs(n-i)>2e3)return!1}catch{}return!0}function Gp(t,e){let r=Date.parse(t),n=e?Date.parse(e):Date.now();if(!Number.isFinite(r)||!Number.isFinite(n))return"0s";let i=Math.max(0,n-r),o=Math.floor(i/1e3);if(o<60)return`${o}s`;let s=Math.floor(o/60),a=o%60;return s<60?`${s}m ${a}s`:`${Math.floor(s/60)}h ${s%60}m`}function Hi(t,e){if(!or(t))return"";let r=Up(t);if(r.size===0)return"";let n=r.size>e?r.size-e:0,i=r.size-n,o=xs(t,"r");try{let s=Buffer.alloc(i);return Mp(o,s,0,i,n),s.toString("utf-8")}finally{Ss(o)}}function Vp(t,e=200){let r=Hi(Ue(Kt(t),"stdout.log"),65536),n=Hi(Ue(Kt(t),"stderr.log"),64*1024),i=[];return r.trim()&&i.push(...r.split(`
4772
4772
  `).slice(-e).map(o=>`[out] ${o}`)),n.trim()&&i.push(...n.split(`
4773
4773
  `).slice(-e).map(o=>`[err] ${o}`)),i.filter(o=>o.trim().length>0).join(`
4774
- `)}function Ct(t){return{stdout:Me(Vt(t),"stdout.log"),stderr:Me(Vt(t),"stderr.log")}}async function ht(t){let e=Bp(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!Hp(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:Wp(r.startedAt,r.endedAt),logTail:Gp(t)}}async function Kt(t,e){let r=Math.max(100,e.pollIntervalMs??500),n=Date.now()+Math.max(0,e.timeoutMs),i=["complete","failed","unknown_exit"];for(;;){let o=await ht(t);if(!o)return null;try{e.onPoll?.(o)}catch{}if(i.includes(o.status))return o;let s=n-Date.now();if(s<=0)return o;await new Promise(a=>setTimeout(a,Math.min(r,s)))}}var Qi,$p,wn=P(()=>{"use strict";Qi=1,$p=`// Generated by @mistflow-ai/mcp local-jobs (v${Qi}). Do not edit.
4774
+ `)}function Rt(t){return{stdout:Ue(Kt(t),"stdout.log"),stderr:Ue(Kt(t),"stderr.log")}}async function ft(t){let e=zp(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!Wp(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:Gp(r.startedAt,r.endedAt),logTail:Vp(t)}}async function Jt(t,e){let r=Math.max(100,e.pollIntervalMs??500),n=Date.now()+Math.max(0,e.timeoutMs),i=["complete","failed","unknown_exit"];for(;;){let o=await ft(t);if(!o)return null;try{e.onPoll?.(o)}catch{}if(i.includes(o.status))return o;let s=n-Date.now();if(s<=0)return o;await new Promise(a=>setTimeout(a,Math.min(r,s)))}}var Xi,Fp,vn=_(()=>{"use strict";Xi=1,Fp=`// Generated by @mistflow-ai/mcp local-jobs (v${Xi}). Do not edit.
4775
4775
  const { spawn } = require('node:child_process');
4776
4776
  const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
4777
4777
  const { join, dirname } = require('node:path');
@@ -4835,9 +4835,9 @@ child.on('error', (err) => {
4835
4835
  });
4836
4836
  process.exit(1);
4837
4837
  });
4838
- `});import{createServer as Vp}from"net";import{existsSync as ir,readFileSync as Zi,writeFileSync as ea,mkdirSync as ta}from"fs";import{join as ar}from"path";import{spawn as Kp}from"child_process";function na(){let t=(process.env.MISTFLOW_VISUAL_CONTEXT??"full").toLowerCase();return t==="off"||t==="preview"||t==="full"?t:"full"}function ra(t){return ar(t,".mistflow","visual-context.json")}function sa(t){let e=ra(t);if(!ir(e))return{screenshotsTaken:0,lastScreenshotStep:0};try{return JSON.parse(Zi(e,"utf-8"))}catch{return{screenshotsTaken:0,lastScreenshotStep:0}}}function Jp(t,e){let r=ar(t,".mistflow");ir(r)||ta(r,{recursive:!0}),ea(ra(t),JSON.stringify(e,null,2)+`
4839
- `)}function oa(t,e,r){if(na()!=="full")return!1;let n=sa(t);return n.screenshotsTaken>=Yp?!1:n.screenshotsTaken===0||r>0&&e>=r||e>0&&e!==n.lastScreenshotStep&&e%3===0}function ia(t,e){let r=sa(t);Jp(t,{screenshotsTaken:r.screenshotsTaken+1,lastScreenshotStep:e})}async function Qp(){return new Promise((t,e)=>{let r=Vp();r.unref(),r.on("error",e),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(n&&typeof n=="object"){let i=n.port;r.close(()=>t(i))}else r.close(()=>e(new Error("could not read assigned port")))})})}async function aa(t,e=15e3,r=500){let n=Date.now()+e;for(;Date.now()<n;){try{let i=new AbortController,o=setTimeout(()=>i.abort(),Math.min(r*2,2e3)),s=await fetch(t,{method:"HEAD",signal:i.signal});if(clearTimeout(o),s)return!0}catch{}await new Promise(i=>setTimeout(i,r))}return!1}function la(t){return ar(t,".mistflow","preview.json")}function ca(t){let e=la(t);if(!ir(e))return null;try{return JSON.parse(Zi(e,"utf-8"))}catch{return null}}function da(t){return ca(t)}function Xp(t,e){let r=ar(t,".mistflow");ir(r)||ta(r,{recursive:!0}),ea(la(t),JSON.stringify(e,null,2)+`
4840
- `)}async function pa(t){if(na()==="off")return null;let e=ca(t);if(e){let n=await ht(e.jobId);if(n&&(n.status==="running"||n.status==="starting"))return{state:e,freshlyStarted:!1}}let r;try{r=await Qp()}catch{return null}try{let n=await mt({type:"preview",cmd:"sh",args:["-c",`npm run dev -- --port ${r}`],cwd:t});await new Promise(a=>setTimeout(a,600));let i=await ht(n.id);if(i&&(i.status==="failed"||i.status==="unknown_exit"))return null;let o=`http://localhost:${r}`,s={port:r,url:o,jobId:n.id,startedAt:n.startedAt};return Xp(t,s),{state:s,freshlyStarted:!0}}catch{return null}}function ua(t){try{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];Kp(e,r,{detached:!0,stdio:"ignore"}).unref()}catch{}}var Yp,Ss=P(()=>{"use strict";wn();Yp=5});var ha,ma=P(()=>{ha=`# Design Doctrine
4838
+ `});import{createServer as Kp}from"net";import{existsSync as ar,readFileSync as ea,writeFileSync as ta,mkdirSync as na}from"fs";import{join as lr}from"path";import{spawn as Jp}from"child_process";function ra(){let t=(process.env.MISTFLOW_VISUAL_CONTEXT??"full").toLowerCase();return t==="off"||t==="preview"||t==="full"?t:"full"}function sa(t){return lr(t,".mistflow","visual-context.json")}function oa(t){let e=sa(t);if(!ar(e))return{screenshotsTaken:0,lastScreenshotStep:0};try{return JSON.parse(ea(e,"utf-8"))}catch{return{screenshotsTaken:0,lastScreenshotStep:0}}}function Yp(t,e){let r=lr(t,".mistflow");ar(r)||na(r,{recursive:!0}),ta(sa(t),JSON.stringify(e,null,2)+`
4839
+ `)}function ia(t,e,r){if(ra()!=="full")return!1;let n=oa(t);return n.screenshotsTaken>=Qp?!1:n.screenshotsTaken===0||r>0&&e>=r||e>0&&e!==n.lastScreenshotStep&&e%3===0}function aa(t,e){let r=oa(t);Yp(t,{screenshotsTaken:r.screenshotsTaken+1,lastScreenshotStep:e})}async function Xp(){return new Promise((t,e)=>{let r=Kp();r.unref(),r.on("error",e),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(n&&typeof n=="object"){let i=n.port;r.close(()=>t(i))}else r.close(()=>e(new Error("could not read assigned port")))})})}async function la(t,e=15e3,r=500){let n=Date.now()+e;for(;Date.now()<n;){try{let i=new AbortController,o=setTimeout(()=>i.abort(),Math.min(r*2,2e3)),s=await fetch(t,{method:"HEAD",signal:i.signal});if(clearTimeout(o),s)return!0}catch{}await new Promise(i=>setTimeout(i,r))}return!1}function ca(t){return lr(t,".mistflow","preview.json")}function da(t){let e=ca(t);if(!ar(e))return null;try{return JSON.parse(ea(e,"utf-8"))}catch{return null}}function pa(t){return da(t)}function Zp(t,e){let r=lr(t,".mistflow");ar(r)||na(r,{recursive:!0}),ta(ca(t),JSON.stringify(e,null,2)+`
4840
+ `)}async function ua(t){if(ra()==="off")return null;let e=da(t);if(e){let n=await ft(e.jobId);if(n&&(n.status==="running"||n.status==="starting"))return{state:e,freshlyStarted:!1}}let r;try{r=await Xp()}catch{return null}try{let n=await gt({type:"preview",cmd:"sh",args:["-c",`npm run dev -- --port ${r}`],cwd:t});await new Promise(a=>setTimeout(a,600));let i=await ft(n.id);if(i&&(i.status==="failed"||i.status==="unknown_exit"))return null;let o=`http://localhost:${r}`,s={port:r,url:o,jobId:n.id,startedAt:n.startedAt};return Zp(t,s),{state:s,freshlyStarted:!0}}catch{return null}}function ma(t){try{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];Jp(e,r,{detached:!0,stdio:"ignore"}).unref()}catch{}}var Qp,Ts=_(()=>{"use strict";vn();Qp=5});var ga,ha=_(()=>{ga=`# Design Doctrine
4841
4841
 
4842
4842
  This is the standard for every UI you generate. It is not aspirational. It is the floor.
4843
4843
 
@@ -4903,7 +4903,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
4903
4903
  8. Is there ONE memorable moment on the page (signature typography / orchestrated motion / unexpected layout)? **If zero, add one. If three, keep the strongest one.**
4904
4904
 
4905
4905
  If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
4906
- `});var fa,ga=P(()=>{fa=`# Typography
4906
+ `});var ya,fa=_(()=>{ya=`# Typography
4907
4907
 
4908
4908
  Typography is the cheapest way to escape AI slop and the most visible place it shows up. Every generic landing uses Inter. Every remarkable landing picks something you'd notice.
4909
4909
 
@@ -4991,7 +4991,7 @@ Pick exactly one:
4991
4991
  - **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
4992
4992
 
4993
4993
  Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
4994
- `});var ba,ya=P(()=>{ba="# Color\n\nColor is a commitment, not a palette swatch. The #1 failure mode in AI-generated landings is an evenly-distributed palette: a little emerald here, a little amber there, a gradient, a badge. That's visual hedging \u2014 it signals \"I couldn't pick a point of view.\"\n\nPick one color. Use it with intent.\n\n## The Token System\n\nEvery color on every screen goes through a CSS variable defined in `globals.css`. You do not hand-pick hex values in JSX. You do not use Tailwind palette utilities (`bg-emerald-500`, `text-blue-600`, `border-slate-200`). If a color isn't in the token scheme, it doesn't exist for this app.\n\n### Core tokens\n\n- `--color-background` \u2014 page background\n- `--color-foreground` \u2014 default body text\n- `--color-card` \u2014 elevated surface (cards, panels)\n- `--color-card-foreground` \u2014 text on cards\n- `--color-muted` \u2014 low-emphasis surface fill\n- `--color-muted-foreground` \u2014 secondary text (\u2265 WCAG AA contrast vs background)\n- `--color-border` \u2014 subtle dividers\n- `--color-input` \u2014 form input borders\n- `--color-popover` / `--color-popover-foreground` \u2014 dropdowns, tooltips, menus\n\n### Interactive tokens\n\n- `--color-primary` \u2014 primary CTAs, links, active tab, focus ring\n- `--color-primary-foreground` \u2014 text on primary (derived for WCAG AA contrast)\n- `--color-ring` \u2014 focus outline (same hue as primary)\n- `--color-secondary` / `--color-secondary-foreground` \u2014 quieter than primary, more than muted\n- `--color-accent` / `--color-accent-foreground` \u2014 hover states on neutrals\n\n### Semantic tokens\n\n- `--color-success` \u2014 confirmation, \"verified\" banners, positive states\n- `--color-warning` \u2014 pending states, attention, non-destructive caution\n- `--color-destructive` / `--color-destructive-foreground` \u2014 errors, irreversible actions\n- `--color-info` \u2014 neutral system messages, tips\n\n**You use these semantic tokens for all status UI.** When you need a \"green checkmark\" you reach for `text-success`, not `text-emerald-500`. When you need an amber alert you reach for `bg-warning/10 text-warning`, not `bg-amber-50 text-amber-700`.\n\n## Usage Rules\n\n**Primary color:**\n- Primary CTAs, links, the active navigation tab, focus rings.\n- NOT for headings. Black or foreground-colored headings are stronger.\n- NOT for large surface fills (it's a splash of color, not a wash).\n- NOT for borders except focus rings.\n- One bold use of primary beats twenty sprinkled uses.\n\n**Neutrals do the structural work:**\n- Background, cards, borders \u2014 all come from the neutral scale.\n- Text hierarchy via opacity on foreground (`text-foreground`, `text-foreground/80`, `text-muted-foreground`) \u2014 not different colors.\n\n**Semantic colors:**\n- Use `bg-success/10 text-success border border-success/30` for success banners (reproducibility: a light-tinted version of the success color for surface, the solid version for text and border).\n- Same shape for warning, info, destructive.\n\n## Dark Mode\n\nCommit to one theme. If DESIGN.md says the app is dark-themed, make it unambiguously dark \u2014 `#0c0c0c` / near-black base, not neutral-900. If light-themed, commit to light.\n\nDo NOT auto-swap based on `prefers-color-scheme` when DESIGN.md declared a theme direction. It chose a theme for a reason; respect it.\n\n## Forbidden\n\n- Palette utilities: `bg-emerald-500`, `text-blue-600`, `border-slate-200`, `from-purple-500`, `via-pink-300`, `to-amber-400`. Every one of these in your output is a slop indicator.\n- Hex literals inside `className` or inline `style` props.\n- Named colors from CSS (`red`, `lightgrey`, `rebeccapurple`) \u2014 never used in production UI; always a sign of rushed work.\n- Purple gradients on white. The single most overused AI-design pattern.\n- Three-color gradient pills. Rainbow badges. \"Vibrant\" anything.\n\n## Contrast\n\nEvery text/surface pair in DESIGN.md is already WCAG AA-verified by Mistflow's contrast test. You do not need to re-check \u2014 the tokens are safe by construction. You DO need to:\n\n- Not override token combinations with hardcoded classes that might fail contrast.\n- Maintain contrast for overlays (text on images, modals on scrims). When stacking text over a gradient or image, include a scrim (`bg-background/80 backdrop-blur-sm`) so body text stays \u2265 4.5:1.\n\n## Getting Color Wrong\n\nThe specific failure mode to avoid: a page where primary is used in five places, all small and incidental \u2014 a checkmark, a hover state, a tiny badge. That's AI hedging. Either use primary confidently on a hero CTA and mean it, OR don't use primary on the page at all and let neutrals carry the identity.\n"});var va,wa=P(()=>{va=`# Motion
4994
+ `});var wa,ba=_(()=>{wa="# Color\n\nColor is a commitment, not a palette swatch. The #1 failure mode in AI-generated landings is an evenly-distributed palette: a little emerald here, a little amber there, a gradient, a badge. That's visual hedging \u2014 it signals \"I couldn't pick a point of view.\"\n\nPick one color. Use it with intent.\n\n## The Token System\n\nEvery color on every screen goes through a CSS variable defined in `globals.css`. You do not hand-pick hex values in JSX. You do not use Tailwind palette utilities (`bg-emerald-500`, `text-blue-600`, `border-slate-200`). If a color isn't in the token scheme, it doesn't exist for this app.\n\n### Core tokens\n\n- `--color-background` \u2014 page background\n- `--color-foreground` \u2014 default body text\n- `--color-card` \u2014 elevated surface (cards, panels)\n- `--color-card-foreground` \u2014 text on cards\n- `--color-muted` \u2014 low-emphasis surface fill\n- `--color-muted-foreground` \u2014 secondary text (\u2265 WCAG AA contrast vs background)\n- `--color-border` \u2014 subtle dividers\n- `--color-input` \u2014 form input borders\n- `--color-popover` / `--color-popover-foreground` \u2014 dropdowns, tooltips, menus\n\n### Interactive tokens\n\n- `--color-primary` \u2014 primary CTAs, links, active tab, focus ring\n- `--color-primary-foreground` \u2014 text on primary (derived for WCAG AA contrast)\n- `--color-ring` \u2014 focus outline (same hue as primary)\n- `--color-secondary` / `--color-secondary-foreground` \u2014 quieter than primary, more than muted\n- `--color-accent` / `--color-accent-foreground` \u2014 hover states on neutrals\n\n### Semantic tokens\n\n- `--color-success` \u2014 confirmation, \"verified\" banners, positive states\n- `--color-warning` \u2014 pending states, attention, non-destructive caution\n- `--color-destructive` / `--color-destructive-foreground` \u2014 errors, irreversible actions\n- `--color-info` \u2014 neutral system messages, tips\n\n**You use these semantic tokens for all status UI.** When you need a \"green checkmark\" you reach for `text-success`, not `text-emerald-500`. When you need an amber alert you reach for `bg-warning/10 text-warning`, not `bg-amber-50 text-amber-700`.\n\n## Usage Rules\n\n**Primary color:**\n- Primary CTAs, links, the active navigation tab, focus rings.\n- NOT for headings. Black or foreground-colored headings are stronger.\n- NOT for large surface fills (it's a splash of color, not a wash).\n- NOT for borders except focus rings.\n- One bold use of primary beats twenty sprinkled uses.\n\n**Neutrals do the structural work:**\n- Background, cards, borders \u2014 all come from the neutral scale.\n- Text hierarchy via opacity on foreground (`text-foreground`, `text-foreground/80`, `text-muted-foreground`) \u2014 not different colors.\n\n**Semantic colors:**\n- Use `bg-success/10 text-success border border-success/30` for success banners (reproducibility: a light-tinted version of the success color for surface, the solid version for text and border).\n- Same shape for warning, info, destructive.\n\n## Dark Mode\n\nCommit to one theme. If DESIGN.md says the app is dark-themed, make it unambiguously dark \u2014 `#0c0c0c` / near-black base, not neutral-900. If light-themed, commit to light.\n\nDo NOT auto-swap based on `prefers-color-scheme` when DESIGN.md declared a theme direction. It chose a theme for a reason; respect it.\n\n## Forbidden\n\n- Palette utilities: `bg-emerald-500`, `text-blue-600`, `border-slate-200`, `from-purple-500`, `via-pink-300`, `to-amber-400`. Every one of these in your output is a slop indicator.\n- Hex literals inside `className` or inline `style` props.\n- Named colors from CSS (`red`, `lightgrey`, `rebeccapurple`) \u2014 never used in production UI; always a sign of rushed work.\n- Purple gradients on white. The single most overused AI-design pattern.\n- Three-color gradient pills. Rainbow badges. \"Vibrant\" anything.\n\n## Contrast\n\nEvery text/surface pair in DESIGN.md is already WCAG AA-verified by Mistflow's contrast test. You do not need to re-check \u2014 the tokens are safe by construction. You DO need to:\n\n- Not override token combinations with hardcoded classes that might fail contrast.\n- Maintain contrast for overlays (text on images, modals on scrims). When stacking text over a gradient or image, include a scrim (`bg-background/80 backdrop-blur-sm`) so body text stays \u2265 4.5:1.\n\n## Getting Color Wrong\n\nThe specific failure mode to avoid: a page where primary is used in five places, all small and incidental \u2014 a checkmark, a hover state, a tiny badge. That's AI hedging. Either use primary confidently on a hero CTA and mean it, OR don't use primary on the page at all and let neutrals carry the identity.\n"});var ka,va=_(()=>{ka=`# Motion
4995
4995
 
4996
4996
  Motion is the most-ignored dimension of AI-generated UI. Generic landings either have no motion or sprinkle tiny fades on everything. Remarkable landings pick ONE orchestrated moment and execute it precisely.
4997
4997
 
@@ -5069,7 +5069,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
5069
5069
  ## One-Line Motion Rule
5070
5070
 
5071
5071
  If the motion you're about to add could be described as "subtle animation on scroll", delete it. Design motion is specific, named, and described in one sentence: "the headline lines drop in from above with a 50ms stagger at page load." If you can't describe it that specifically, you don't have a motion design \u2014 you have motion noise.
5072
- `});var xa,ka=P(()=>{xa=`# Spatial Composition
5072
+ `});var Sa,xa=_(()=>{Sa=`# Spatial Composition
5073
5073
 
5074
5074
  Layout is where AI-slop is most visible. A centered single-column hero with a pill, headline, subhead, and two CTAs is the most-recognizable generic-SaaS pattern on the internet. It is the layout you must not use.
5075
5075
 
@@ -5139,7 +5139,7 @@ To signal "designed, not templated":
5139
5139
  Negative space is a design element. A hero with \`py-32\` and a tight \`max-w-2xl\` text block in a wide viewport reads as confident. A hero that fills every pixel with checkmarks, logos, and counters reads as scared.
5140
5140
 
5141
5141
  Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
5142
- `});var Ta,Sa=P(()=>{Ta=`# Interaction
5142
+ `});var _a,Ta=_(()=>{_a=`# Interaction
5143
5143
 
5144
5144
  Every interactive element has a designed state for every phase: rest, hover, focus, active, disabled. The difference between remarkable and adequate lives in these states.
5145
5145
 
@@ -5224,7 +5224,7 @@ Small moments that add up to "designed":
5224
5224
  - **Empty states** offer a specific next action, not "No data yet".
5225
5225
 
5226
5226
  These micro-interactions are the texture of a designed product. Ship them.
5227
- `});var Pa,_a=P(()=>{Pa=`# UX Writing
5227
+ `});var Ia,Pa=_(()=>{Ia=`# UX Writing
5228
5228
 
5229
5229
  Copy is design. A remarkable page has copy that could only be about this specific product. A generic page has copy that could describe a hundred.
5230
5230
 
@@ -5300,17 +5300,17 @@ If there's a pricing page:
5300
5300
  ## The Footer
5301
5301
 
5302
5302
  A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is fine, but the company name / tagline should be specific. "StandupSync \u2014 async updates, human-sized" is better than "\xA9 2026 StandupSync Inc."
5303
- `});import{existsSync as iu,readFileSync as au,writeFileSync as lu}from"fs";import{join as cu}from"path";import{z as vn}from"zod";function cr(t,e){if(e.length===0)return{added:[],skipped:[]};let r=cu(t,"mistflow.json");if(!iu(r))throw new Error(`mistflow.json not found at ${t}`);let n=au(r,"utf-8"),i=JSON.parse(n);i.env=i.env??{},i.env.required=i.env.required??{};let o=i.env.required,s=[],a=[];for(let l of e)if(!(!l?.key||typeof l.key!="string"||!du.test(l.key))){if(o[l.key]){a.push(l.key);continue}o[l.key]={description:typeof l.description=="string"?l.description:"",...typeof l.setupUrl=="string"&&l.setupUrl?{setupUrl:l.setupUrl}:{},...typeof l.integration=="string"&&l.integration?{integration:l.integration}:{}},s.push(l.key)}return s.length>0&&lu(r,JSON.stringify(i,null,2)+`
5304
- `),{added:s,skipped:a}}var lr,du,Ts=P(()=>{"use strict";lr=vn.object({key:vn.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:vn.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:vn.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:vn.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),du=/^[A-Z][A-Z0-9_]*$/});import{z as kn}from"zod";import{existsSync as gt,readFileSync as Ps,writeFileSync as _s,mkdirSync as pu}from"fs";import{join as et,resolve as uu,dirname as mu}from"path";import{createConnection as hu}from"net";function gu(t){return new Promise(e=>{let r=hu({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}function yu(t){let e=et(t,"mistflow.json");if(!gt(e))return null;try{return JSON.parse(Ps(e,"utf-8"))}catch{return null}}function Ia(t,e){let r=et(t,"mistflow.json");_s(r,JSON.stringify(e,null,2)+`
5305
- `),zt(t)}function dr(t){return t.entity??t.name??"Unknown"}function bu(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Ca(t){return t.path??t.route??t.name??""}function wu(t){let e=(t||"text").toLowerCase();return e==="string"||e==="varchar"||e==="char"?"text":e==="integer"||e==="int"||e==="number"||e==="float"||e==="decimal"||e==="double"?"number":e==="boolean"||e==="bool"?"boolean":e==="date"||e==="datetime"||e==="timestamp"?"date":e==="email"?"email":e==="url"||e==="uri"?"url":e==="enum"||e==="select"?"select":e==="text"||e==="longtext"||e==="textarea"?"textarea":"text"}function Aa(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let i=dr(n).toLowerCase();return r.some(o=>i.includes(o)||o.includes(i))})}function vu(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let i=(n.name??"").toLowerCase(),o=Ca(n).toLowerCase();return r.some(s=>i.includes(s)||s.includes(i)||o.includes(s))})}function xu(t){let e=t.stepType;if(e&&ku.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name??t.title??""} ${t.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function Su(t){switch(t){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function Tu(t){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&e.push(`- **App tone**: ${t.tone}`),t.fonts&&(e.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let r={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${t.borderRadius} (${r[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let r={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${r[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let r={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${t.cardStyle} \u2014 ${r[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&e.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let r=t.visualStrategy,n=t.heroPhoto!==!1,i=n&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),i&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let s=r.heroImages[0];e.push(`- URL: ${s.url}`),e.push(`- Alt text for img tag: "${s.alt||"Hero image"} \u2014 Photo by ${s.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!r.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/home/page.tsx.'"):n||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(r.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let s of r.sectionImages)e.push(`- ${s.url} \u2014 alt: "${s.alt||"section image"} \u2014 Photo by ${s.photographer} on Unsplash"`)}(i||r.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let o=Fi(t);o?(e.push(""),e.push(`### Page composition \u2014 ${o.name} archetype`),e.push(`This plan was classified as **${o.id}** \u2014 ${o.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),e.push(""),e.push(o.content)):(e.push(""),e.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),i?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows. Must be DOMAIN-SPECIFIC."),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return e.join(`
5306
- `)}function _u(t){let e=[];return e.push("### Landing layout (Plan G IR \u2014 STRUCTURAL AUTHORITY for this page):"),e.push(""),e.push("Build the landing page with EXACTLY these sections, in this order. Each section's `type` names a primitive \u2014 render it using the picked direction's fonts + colors + shape language. The `intent` explains WHY the section exists; the `props` are the content."),e.push(""),e.push(`- **Page intent**: ${t.page_intent}`),e.push(`- **Narrative arc**: ${t.narrative_arc}`),e.push(`- **Audience**: ${t.audience_persona}`),t.primary_cta&&e.push(`- **Primary CTA**: \`${t.primary_cta.label}\` \u2014 ${t.primary_cta.intent}`),e.push(""),e.push("**Sections (build in order):**"),e.push(""),t.sections.forEach((r,n)=>{let i=n+1;e.push(`${i}. \`${r.type}\` (id: \`${r.id}\`, role: \`${r.narrative_role}\`)`),e.push(` - **Intent**: ${r.intent}`),r.answers_section_id&&e.push(` - **Answers**: section \`${r.answers_section_id}\` (use visual cues \u2014 paired typography, matching accent, sequential numbering \u2014 to make the relationship readable)`),e.push(" - **Props** (JSON):"),e.push(" ```json");let o=JSON.stringify(r.props,null,2).split(`
5303
+ `});import{existsSync as au,readFileSync as lu,writeFileSync as cu}from"fs";import{join as du}from"path";import{z as kn}from"zod";function dr(t,e){if(e.length===0)return{added:[],skipped:[]};let r=du(t,"mistflow.json");if(!au(r))throw new Error(`mistflow.json not found at ${t}`);let n=lu(r,"utf-8"),i=JSON.parse(n);i.env=i.env??{},i.env.required=i.env.required??{};let o=i.env.required,s=[],a=[];for(let l of e)if(!(!l?.key||typeof l.key!="string"||!pu.test(l.key))){if(o[l.key]){a.push(l.key);continue}o[l.key]={description:typeof l.description=="string"?l.description:"",...typeof l.setupUrl=="string"&&l.setupUrl?{setupUrl:l.setupUrl}:{},...typeof l.integration=="string"&&l.integration?{integration:l.integration}:{}},s.push(l.key)}return s.length>0&&cu(r,JSON.stringify(i,null,2)+`
5304
+ `),{added:s,skipped:a}}var cr,pu,_s=_(()=>{"use strict";cr=kn.object({key:kn.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:kn.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:kn.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:kn.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),pu=/^[A-Z][A-Z0-9_]*$/});import{z as xn}from"zod";import{existsSync as yt,readFileSync as Is,writeFileSync as Ps,mkdirSync as uu}from"fs";import{join as tt,resolve as mu,dirname as hu}from"path";import{createConnection as gu}from"net";function fu(t){return new Promise(e=>{let r=gu({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}function bu(t){let e=tt(t,"mistflow.json");if(!yt(e))return null;try{return JSON.parse(Is(e,"utf-8"))}catch{return null}}function Ca(t,e){let r=tt(t,"mistflow.json");Ps(r,JSON.stringify(e,null,2)+`
5305
+ `),Ht(t)}function pr(t){return t.entity??t.name??"Unknown"}function wu(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Aa(t){return t.path??t.route??t.name??""}function vu(t){let e=(t||"text").toLowerCase();return e==="string"||e==="varchar"||e==="char"?"text":e==="integer"||e==="int"||e==="number"||e==="float"||e==="decimal"||e==="double"?"number":e==="boolean"||e==="bool"?"boolean":e==="date"||e==="datetime"||e==="timestamp"?"date":e==="email"?"email":e==="url"||e==="uri"?"url":e==="enum"||e==="select"?"select":e==="text"||e==="longtext"||e==="textarea"?"textarea":"text"}function Ra(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let i=pr(n).toLowerCase();return r.some(o=>i.includes(o)||o.includes(i))})}function ku(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let i=(n.name??"").toLowerCase(),o=Aa(n).toLowerCase();return r.some(s=>i.includes(s)||s.includes(i)||o.includes(s))})}function Su(t){let e=t.stepType;if(e&&xu.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name??t.title??""} ${t.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function Tu(t){switch(t){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function _u(t){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&e.push(`- **App tone**: ${t.tone}`),t.fonts&&(e.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let r={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${t.borderRadius} (${r[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let r={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${r[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let r={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${t.cardStyle} \u2014 ${r[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&e.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let r=t.visualStrategy,n=t.heroPhoto!==!1,i=n&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),i&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let s=r.heroImages[0];e.push(`- URL: ${s.url}`),e.push(`- Alt text for img tag: "${s.alt||"Hero image"} \u2014 Photo by ${s.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!r.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/home/page.tsx.'"):n||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(r.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let s of r.sectionImages)e.push(`- ${s.url} \u2014 alt: "${s.alt||"section image"} \u2014 Photo by ${s.photographer} on Unsplash"`)}(i||r.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let o=qi(t);o?(e.push(""),e.push(`### Page composition \u2014 ${o.name} archetype`),e.push(`This plan was classified as **${o.id}** \u2014 ${o.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),e.push(""),e.push(o.content)):(e.push(""),e.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),i?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows. Must be DOMAIN-SPECIFIC."),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return e.join(`
5306
+ `)}function Pu(t){let e=[];return e.push("### Landing layout (Plan G IR \u2014 STRUCTURAL AUTHORITY for this page):"),e.push(""),e.push("Build the landing page with EXACTLY these sections, in this order. Each section's `type` names a primitive \u2014 render it using the picked direction's fonts + colors + shape language. The `intent` explains WHY the section exists; the `props` are the content."),e.push(""),e.push(`- **Page intent**: ${t.page_intent}`),e.push(`- **Narrative arc**: ${t.narrative_arc}`),e.push(`- **Audience**: ${t.audience_persona}`),t.primary_cta&&e.push(`- **Primary CTA**: \`${t.primary_cta.label}\` \u2014 ${t.primary_cta.intent}`),e.push(""),e.push("**Sections (build in order):**"),e.push(""),t.sections.forEach((r,n)=>{let i=n+1;e.push(`${i}. \`${r.type}\` (id: \`${r.id}\`, role: \`${r.narrative_role}\`)`),e.push(` - **Intent**: ${r.intent}`),r.answers_section_id&&e.push(` - **Answers**: section \`${r.answers_section_id}\` (use visual cues \u2014 paired typography, matching accent, sequential numbering \u2014 to make the relationship readable)`),e.push(" - **Props** (JSON):"),e.push(" ```json");let o=JSON.stringify(r.props,null,2).split(`
5307
5307
  `).map(s=>` ${s}`);e.push(...o),e.push(" ```"),e.push("")}),e.push("**Rules:**"),e.push("- Render sections in the order above. Do not add, remove, or reorder."),e.push("- Each section's `type` is a known primitive \u2014 implement it as a real component with the props as content. Field names in `props` are descriptive of the role (e.g. `hero_magazine.pullquote` is an italicized 15-40 word quote with a left-rule mark)."),e.push("- Use the picked direction's `fonts.display` / `fonts.body` / `colors.bg/fg/accent` / `shape_lang` (border radius scale) / `texture` (background overlay) \u2014 those are in the design choices block above."),e.push("- The IR is the structural authority for THIS page; landing-rules.md still applies for anti-slop / motion choreography / general quality. If they conflict on structure, the IR wins."),e.push("- Don't invent placeholder content \u2014 every `props` value here is what the section should display."),e.join(`
5308
- `)}async function Pu(t){try{let e=await Fr("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
5308
+ `)}async function Iu(t){try{let e=await qr("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
5309
5309
  - Follow existing patterns in the codebase
5310
- - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Iu(t,e,r,n,i,o){let s=[];s.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),s.push(""),s.push("### What to build:"),s.push(t.description),s.push(""),e.primaryAction&&(s.push("### Primary user action (non-negotiable):"),s.push(`- **Core action**: ${e.primaryAction.action}`),s.push(`- **User flow**: ${e.primaryAction.flow}`),s.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),s.push(""),s.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),s.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l){s.push(Tu(e.design)),s.push("");let _=o?et(o,".mistflow","rules","design-quality.md"):null;_&&gt(_)?(s.push("### Design quality rules (non-negotiable):"),s.push("**Read `.mistflow/rules/design-quality.md` BEFORE writing any code for this step.** That file contains the full rule set (shadcn usage, routes, typography, color, layout, motion, responsive, UX writing, cognitive load, production hardening, anti-patterns). It's been written to disk to keep this prompt under the per-tool-result token cap \u2014 read it once, then write your code."),s.push("")):(s.push(er),s.push(""))}else e.design&&!l&&(s.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&s.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),s.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),s.push(""));if(o){let _=Fo(o);if(_.length>0){s.push("### Approved wireframe (MUST READ before writing any files):"),s.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let k of _){let y=k.replace(o,"").replace(/^\//,"");s.push(`- \`${y}\``)}s.push(""),s.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),s.push(""),s.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),s.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),s.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),s.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),s.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),s.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),s.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(s.push("### Role system (from plan):"),s.push(`- Roles: ${e.roles.join(", ")}`),s.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),s.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),s.push("")),e.multiTenant&&(s.push("### Multi-tenant (from plan):"),s.push("- Organization tables are in `db/schema/organization.ts`"),s.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),s.push("- All data queries MUST be scoped to the current org (filter by orgId)"),s.push("- Org switcher component is at `components/org-switcher.tsx`"),s.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),s.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),s.push("")),e.language&&(s.push(`### Language: ${e.language}`),s.push(`ALL user-facing text must be written in ${e.language}:`),s.push("- Page titles, headings, labels, button text, placeholder text"),s.push("- Navigation items, menu labels, footer text"),s.push("- Error messages, success messages, empty states"),s.push("- Landing page copy, marketing text, CTAs"),s.push("- Form labels and validation messages"),s.push("Code (variable names, comments, file names) stays in English."),s.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),s.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(i)&&(e.audienceType==="b2c"?(s.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),s.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),s.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),s.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),s.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),s.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),s.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),s.push("")):e.audienceType==="b2b"?(s.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),s.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),s.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),s.push("- Testimonials: from business owners who use the platform"),s.push("- Features: business benefits ('Track dietary preferences across all orders')"),s.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),s.push("")):e.audienceType==="internal"&&(s.push("### Audience: internal staff tool. No marketing copy needed."),s.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),s.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),s.push(""))),r.length>0&&(s.push("### Already completed:"),r.forEach(_=>s.push(`- ${_}`)),s.push(""));let u=e.dataModel?Aa(t,e.dataModel):[];u.length>0&&(s.push("### Data model (from plan):"),u.forEach(_=>{let k=dr(_),y=bu(_.fields);s.push(`- **${k}**: ${y}`),s.push(` Schema file: \`db/schema/${k.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let h=e.pages?vu(t,e.pages):[];if(h.length>0&&(s.push("### Pages to create/update:"),h.forEach(_=>{let k=_.description?` \u2014 ${_.description}`:"";s.push(`- \`${Ca(_)}\`${k}`)}),s.push("")),i==="crud"&&u.length>0&&u.forEach(_=>{let k=dr(_),y=k.toLowerCase().replace(/\s+/g,"-"),A=y.endsWith("s")?y:`${y}s`;s.push(`### Files for ${k} CRUD:`),s.push(`- List page: \`app/(dashboard)/${A}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${A}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${A}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${A}/actions.ts\``),s.push(`- DataTable columns: \`components/${y}-table-columns.tsx\``),s.push(`- Form: \`components/${y}-form.tsx\``),s.push("")}),l){s.push("## Design Doctrine (the standard for every UI step)"),s.push(""),s.push(ha),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(fa),s.push(""),s.push("### Color"),s.push(ba),s.push(""),s.push("### Motion"),s.push(va),s.push(""),s.push("### Spatial Composition"),s.push(xa),s.push(""),s.push("### Interaction"),s.push(Ta),s.push(""),s.push("### UX Writing"),s.push(Pa),s.push("");let _=o?et(o,"DESIGN.md"):void 0,k=_&&gt(_)?(()=>{try{return Ps(_,"utf-8")}catch{return null}})():null;k&&(s.push("### Design system (source of truth: DESIGN.md):"),s.push(""),s.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),s.push(""),s.push(k),s.push(""));let y=o?et(o,".mistflow","picker-render.html"):void 0;(i==="landing"||i==="design")&&y&&gt(y)&&(s.push("### Picked landing page render \u2014 ground-truth design contract"),s.push(""),s.push("The user picked their direction from a **fully-rendered HTML preview** of this landing page. That render is at `.mistflow/picker-render.html` (relative to the project root). **Read it** \u2014 it is the design contract the user agreed to."),s.push(""),s.push("Your job for this step is **mechanical translation**: convert that standalone HTML to Next.js Server Components + Client Components in `app/home/page.tsx` (and `components/landing/*.tsx` for any sections you split out). You are NOT redesigning. The user already picked the design \u2014 colors, fonts, composition, copy, and section order are LOCKED."),s.push(""),s.push("How to translate:\n1. **Preserve every voice sample exactly.** The H1 in the rendered HTML is the headline the user picked. The CTA button text is the CTA the user picked. Do NOT paraphrase, shorten, or 'improve' them. The picker is a contract.\n2. **Preserve the section order.** Each `<section data-section-id=\"X\">` in the rendered HTML maps to a TSX section in the SAME order. You may split each section into its own component file (`components/landing/{section-id}.tsx`) for readability \u2014 that's the only structural transformation allowed.\n3. **Migrate inline `<style>` to globals.css**. The render uses one inline `<style>` block; move those rules to `app/globals.css` so the rest of the app shares the design tokens. CSS custom properties (`--color-bg` / `--color-fg` / `--color-accent`) become the canonical design tokens.\n4. **Tailwind utility classes are FORBIDDEN in this step**, the same way they were forbidden in the render. The render already emits raw CSS; keep it that way in the TSX (use `className` to attach classes defined in globals.css, not Tailwind utilities).\n5. **Image slots:** each `<img data-image-slot=\"hero|feature-1|feature-2|feature-3|og|favicon\">` in the render points at picsum placeholder URLs. Replace each `src` with `/images/{slot}.png` \u2014 those files arrive in `public/images/` from the imagery pipeline (see Plan F A.6.1; check `mist_project action='imagery'` for status during the build). For the favicon slot, also wire `app/icon.png` to the same asset.\n6. **Do not add or remove sections.** If the render has 6 sections, the deployed page has 6 sections in the same order. Adding a CTA the user didn't pick is a bug; dropping a feature card the user did pick is also a bug.\n"),s.push("Bar: a designer comparing the picker iframe and the deployed /home page side by side should not be able to tell them apart at first glance. The HTML\u2192TSX translation is mechanical. Anything creative belongs in a separate refinement step the user explicitly asks for."),s.push(""))}if(i==="landing"||i==="design"){s.push("### File location for the landing page (non-negotiable):"),s.push('Write the landing page to **`app/home/page.tsx`** \u2014 NOT `app/page.tsx`. The scaffold\'s `middleware.ts` 308-redirects `/` to `/home` as a workaround for an OpenNext Cloudflare bug. Visitors land at `/` and end up on `/home` transparently. Internal links like `<Link href="/">` still work because the middleware does the redirect on every request.'),s.push("");let _=o?et(o,".mistflow","rules","landing.md"):null;_&&gt(_)?(s.push("### Landing page rules:"),s.push("**Read `.mistflow/rules/landing.md` BEFORE writing the landing page.** That file contains the full conversion structure, section catalog, motion menu, and anti-slop audit. Written to disk to keep this prompt under the per-tool-result token cap \u2014 read once, then write your code."),s.push("")):(s.push(tr),s.push(""))}i==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(s.push(_u(e.layoutSpec)),s.push(""));let d=t.integrationId?Lt(t.integrationId):void 0;if(d){let _=Ut(d.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${d.name}** (${d.category})`),_?.docsUrl&&s.push(`Official docs: ${_.docsUrl}`),_?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let k of _.envVars)s.push(`- \`${k.key}\`: ${k.description} \u2014 Get it at ${k.setupUrl}`);s.push(""),s.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}_?.packages?.length&&(s.push(""),s.push(`**Packages to install:** \`npm install ${_.packages.join(" ")}\``)),s.push(""),s.push("---"),s.push(d.prompt),s.push("---"),s.push(""),s.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),s.push("")}let{reminders:v,skill:W}=await Pu(i);return s.push(v),s.push(""),W&&(s.push(`### ${i} reference:`),s.push(W),s.push("")),l&&(s.push("## Self-Audit \u2014 run before submitting this file"),s.push(""),s.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),s.push(""),s.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),s.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),s.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),s.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),s.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),s.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),s.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),s.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),s.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),s.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),s.push(""),s.push(`If every answer is "no, I'm good" \u2014 then submit.`),s.push("")),s.join(`
5311
- `)}async function Cu(t){let{projectPath:e,step:r,envVarsRequired:n,sessionId:i}=t,o=uu(e??process.cwd());if(n&&n.length>0)try{let b=cr(o,n);b.added.length>0&&console.error(`[implement] declared env.required: ${b.added.join(", ")}`)}catch(b){console.error("[implement] env var merge skipped:",b instanceof Error?b.message:String(b))}let s=yu(o);if(!s)return Ye(o);if(!gt(et(o,"node_modules")))return p(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:b,ensureShadcnComponents:$}=await Promise.resolve().then(()=>(Zr(),Xr)),V=await b(o);V&&!s.projectId&&(s.projectId=V);let M=await $(o);M.failed?console.error(`[implement] ${M.failed}`):M.installed.length>0&&console.error(`[implement] installed ${M.installed.length} shadcn components`)}catch(b){console.error("[implement] self-heal skipped:",b instanceof Error?b.message:String(b))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return p("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let l,c=a.steps.find(b=>b.status==="in_progress");if(c){let b=a.steps.findIndex($=>$.number===c.number);b!==-1&&(a.steps[b].status="completed",l=`Auto-completed step ${c.number} (${c.name})`,Ia(o,s))}let u;if(r!==void 0){if(u=a.steps.find(b=>b.number===r),!u)return p(`Step ${r} not found. The plan has ${a.steps.length} steps (numbered ${a.steps[0].number} to ${a.steps[a.steps.length-1].number}).`,!0)}else if(u=a.steps.find(b=>b.status!=="completed"),!u)return p(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(b=>b.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let h=a.steps.filter(b=>b.status==="completed").map(b=>`Step ${b.number}: ${b.name}`),{readLocalState:d}=await Promise.resolve().then(()=>(Tt(),dn)),v=d(o),W=xu(u),_=[];if((W==="crud"||W==="schema")&&a.dataModel&&u.entities&&u.entities.length>0){let b=Aa(u,a.dataModel);for(let $ of b){let V=dr($);try{let M=($.fields||[]).map(ae=>typeof ae=="string"?{name:ae,type:"text"}:{name:ae.name,type:wu(ae.type),required:ae.required!==!1});if(M.length===0)continue;let pe=s.dbProvider==="neon"?"nextjs-neon":"nextjs",te=await zr(pe,V,M),R=0,ge=0;for(let ae of te.files){let Oe=et(o,ae.path);if(gt(Oe)){ge++;continue}pu(mu(Oe),{recursive:!0}),_s(Oe,ae.content),R++}let K=et(o,"db","index.ts");if(gt(K)){let ae=Ps(K,"utf-8");ae.includes(te.dbExport)||_s(K,ae.trimEnd()+`
5312
- `+te.dbExport+`
5313
- `)}R>0?_.push(`${te.entityPascal} CRUD (${R} new files${ge>0?`, ${ge} existing skipped`:""})`):ge>0&&_.push(`${te.entityPascal} CRUD (all ${ge} files already exist \u2014 skipped)`)}catch(M){console.error(`Module generation failed for ${V} (non-fatal):`,M instanceof Error?M.message:M)}}}let k=await Iu(u,a,h,null,W,o),y=a.steps.findIndex(b=>b.number===u.number);if(y!==-1&&(s.plan.steps[y].status="in_progress",Ia(o,s)),v&&s.projectId){let{syncRemoteState:b}=await Promise.resolve().then(()=>(Tt(),dn));b(s.projectId,v).catch(()=>{})}let A=a.steps.every(b=>b.status==="completed"||b.number===u.number),z;A?z=`THIS IS THE LAST STEP. Rules for speed:
5310
+ - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Cu(t,e,r,n,i,o){let s=[];s.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),s.push(""),s.push("### What to build:"),s.push(t.description),s.push(""),e.primaryAction&&(s.push("### Primary user action (non-negotiable):"),s.push(`- **Core action**: ${e.primaryAction.action}`),s.push(`- **User flow**: ${e.primaryAction.flow}`),s.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),s.push(""),s.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),s.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l){s.push(_u(e.design)),s.push("");let I=o?tt(o,".mistflow","rules","design-quality.md"):null;I&&yt(I)?(s.push("### Design quality rules (non-negotiable):"),s.push("**Read `.mistflow/rules/design-quality.md` BEFORE writing any code for this step.** That file contains the full rule set (shadcn usage, routes, typography, color, layout, motion, responsive, UX writing, cognitive load, production hardening, anti-patterns). It's been written to disk to keep this prompt under the per-tool-result token cap \u2014 read it once, then write your code."),s.push("")):(s.push(tr),s.push(""))}else e.design&&!l&&(s.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&s.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),s.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),s.push(""));if(o){let I=qo(o);if(I.length>0){s.push("### Approved wireframe (MUST READ before writing any files):"),s.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let S of I){let y=S.replace(o,"").replace(/^\//,"");s.push(`- \`${y}\``)}s.push(""),s.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),s.push(""),s.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),s.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),s.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),s.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),s.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),s.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),s.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(s.push("### Role system (from plan):"),s.push(`- Roles: ${e.roles.join(", ")}`),s.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),s.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),s.push("")),e.multiTenant&&(s.push("### Multi-tenant (from plan):"),s.push("- Organization tables are in `db/schema/organization.ts`"),s.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),s.push("- All data queries MUST be scoped to the current org (filter by orgId)"),s.push("- Org switcher component is at `components/org-switcher.tsx`"),s.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),s.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),s.push("")),e.language&&(s.push(`### Language: ${e.language}`),s.push(`ALL user-facing text must be written in ${e.language}:`),s.push("- Page titles, headings, labels, button text, placeholder text"),s.push("- Navigation items, menu labels, footer text"),s.push("- Error messages, success messages, empty states"),s.push("- Landing page copy, marketing text, CTAs"),s.push("- Form labels and validation messages"),s.push("Code (variable names, comments, file names) stays in English."),s.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),s.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(i)&&(e.audienceType==="b2c"?(s.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),s.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),s.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),s.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),s.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),s.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),s.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),s.push("")):e.audienceType==="b2b"?(s.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),s.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),s.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),s.push("- Testimonials: from business owners who use the platform"),s.push("- Features: business benefits ('Track dietary preferences across all orders')"),s.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),s.push("")):e.audienceType==="internal"&&(s.push("### Audience: internal staff tool. No marketing copy needed."),s.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),s.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),s.push(""))),r.length>0&&(s.push("### Already completed:"),r.forEach(I=>s.push(`- ${I}`)),s.push(""));let m=e.dataModel?Ra(t,e.dataModel):[];m.length>0&&(s.push("### Data model (from plan):"),m.forEach(I=>{let S=pr(I),y=wu(I.fields);s.push(`- **${S}**: ${y}`),s.push(` Schema file: \`db/schema/${S.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let p=e.pages?ku(t,e.pages):[];if(p.length>0&&(s.push("### Pages to create/update:"),p.forEach(I=>{let S=I.description?` \u2014 ${I.description}`:"";s.push(`- \`${Aa(I)}\`${S}`)}),s.push("")),i==="crud"&&m.length>0&&m.forEach(I=>{let S=pr(I),y=S.toLowerCase().replace(/\s+/g,"-"),R=y.endsWith("s")?y:`${y}s`;s.push(`### Files for ${S} CRUD:`),s.push(`- List page: \`app/(dashboard)/${R}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${R}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${R}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${R}/actions.ts\``),s.push(`- DataTable columns: \`components/${y}-table-columns.tsx\``),s.push(`- Form: \`components/${y}-form.tsx\``),s.push("")}),l){s.push("## Design Doctrine (the standard for every UI step)"),s.push(""),s.push(ga),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(ya),s.push(""),s.push("### Color"),s.push(wa),s.push(""),s.push("### Motion"),s.push(ka),s.push(""),s.push("### Spatial Composition"),s.push(Sa),s.push(""),s.push("### Interaction"),s.push(_a),s.push(""),s.push("### UX Writing"),s.push(Ia),s.push("");let I=o?tt(o,"DESIGN.md"):void 0,S=I&&yt(I)?(()=>{try{return Is(I,"utf-8")}catch{return null}})():null;S&&(s.push("### Design system (source of truth: DESIGN.md):"),s.push(""),s.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),s.push(""),s.push(S),s.push(""));let y=o?tt(o,".mistflow","picker-render.html"):void 0;(i==="landing"||i==="design")&&y&&yt(y)&&(s.push("### Picked landing page render \u2014 ground-truth design contract"),s.push(""),s.push("The user picked their direction from a **fully-rendered HTML preview** of this landing page. That render is at `.mistflow/picker-render.html` (relative to the project root). **Read it** \u2014 it is the design contract the user agreed to."),s.push(""),s.push("Your job for this step is **mechanical translation**: convert that standalone HTML to Next.js Server Components + Client Components in `app/home/page.tsx` (and `components/landing/*.tsx` for any sections you split out). You are NOT redesigning. The user already picked the design \u2014 colors, fonts, composition, copy, and section order are LOCKED."),s.push(""),s.push("How to translate:\n1. **Preserve every voice sample exactly.** The H1 in the rendered HTML is the headline the user picked. The CTA button text is the CTA the user picked. Do NOT paraphrase, shorten, or 'improve' them. The picker is a contract.\n2. **Preserve the section order.** Each `<section data-section-id=\"X\">` in the rendered HTML maps to a TSX section in the SAME order. You may split each section into its own component file (`components/landing/{section-id}.tsx`) for readability \u2014 that's the only structural transformation allowed.\n3. **Migrate inline `<style>` to globals.css**. The render uses one inline `<style>` block; move those rules to `app/globals.css` so the rest of the app shares the design tokens. CSS custom properties (`--color-bg` / `--color-fg` / `--color-accent`) become the canonical design tokens.\n4. **Tailwind utility classes are FORBIDDEN in this step**, the same way they were forbidden in the render. The render already emits raw CSS; keep it that way in the TSX (use `className` to attach classes defined in globals.css, not Tailwind utilities).\n5. **Image slots:** each `<img data-image-slot=\"hero|feature-1|feature-2|feature-3|og|favicon\">` in the render points at picsum placeholder URLs. Replace each `src` with `/images/{slot}.png` \u2014 those files arrive in `public/images/` from the imagery pipeline (see Plan F A.6.1; check `mist_project action='imagery'` for status during the build). For the favicon slot, also wire `app/icon.png` to the same asset.\n6. **Do not add or remove sections.** If the render has 6 sections, the deployed page has 6 sections in the same order. Adding a CTA the user didn't pick is a bug; dropping a feature card the user did pick is also a bug.\n"),s.push("Bar: a designer comparing the picker iframe and the deployed /home page side by side should not be able to tell them apart at first glance. The HTML\u2192TSX translation is mechanical. Anything creative belongs in a separate refinement step the user explicitly asks for."),s.push(""))}if(i==="landing"||i==="design"){s.push("### File location for the landing page (non-negotiable):"),s.push('Write the landing page to **`app/home/page.tsx`** \u2014 NOT `app/page.tsx`. The scaffold\'s `middleware.ts` 308-redirects `/` to `/home` as a workaround for an OpenNext Cloudflare bug. Visitors land at `/` and end up on `/home` transparently. Internal links like `<Link href="/">` still work because the middleware does the redirect on every request.'),s.push("");let I=o?tt(o,".mistflow","rules","landing.md"):null;I&&yt(I)?(s.push("### Landing page rules:"),s.push("**Read `.mistflow/rules/landing.md` BEFORE writing the landing page.** That file contains the full conversion structure, section catalog, motion menu, and anti-slop audit. Written to disk to keep this prompt under the per-tool-result token cap \u2014 read once, then write your code."),s.push("")):(s.push(nr),s.push(""))}i==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(s.push(Pu(e.layoutSpec)),s.push(""));let u=t.integrationId?Ut(t.integrationId):void 0;if(u){let I=$t(u.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${u.name}** (${u.category})`),I?.docsUrl&&s.push(`Official docs: ${I.docsUrl}`),I?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let S of I.envVars)s.push(`- \`${S.key}\`: ${S.description} \u2014 Get it at ${S.setupUrl}`);s.push(""),s.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}I?.packages?.length&&(s.push(""),s.push(`**Packages to install:** \`npm install ${I.packages.join(" ")}\``)),s.push(""),s.push("---"),s.push(u.prompt),s.push("---"),s.push(""),s.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),s.push("")}let{reminders:g,skill:j}=await Iu(i);return s.push(g),s.push(""),j&&(s.push(`### ${i} reference:`),s.push(j),s.push("")),l&&(s.push("## Self-Audit \u2014 run before submitting this file"),s.push(""),s.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),s.push(""),s.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),s.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),s.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),s.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),s.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),s.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),s.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),s.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),s.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),s.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),s.push(""),s.push(`If every answer is "no, I'm good" \u2014 then submit.`),s.push("")),s.join(`
5311
+ `)}async function Au(t){let{projectPath:e,step:r,envVarsRequired:n,sessionId:i}=t,o=mu(e??process.cwd());if(n&&n.length>0)try{let x=dr(o,n);x.added.length>0&&console.error(`[implement] declared env.required: ${x.added.join(", ")}`)}catch(x){console.error("[implement] env var merge skipped:",x instanceof Error?x.message:String(x))}let s=bu(o);if(!s)return Qe(o);if(!yt(tt(o,"node_modules")))return d(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:x,ensureShadcnComponents:C}=await Promise.resolve().then(()=>(es(),Zr)),V=await x(o);V&&!s.projectId&&(s.projectId=V);let F=await C(o);F.failed?console.error(`[implement] ${F.failed}`):F.installed.length>0&&console.error(`[implement] installed ${F.installed.length} shadcn components`)}catch(x){console.error("[implement] self-heal skipped:",x instanceof Error?x.message:String(x))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return d("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let l,c=a.steps.find(x=>x.status==="in_progress");if(c){let x=a.steps.findIndex(C=>C.number===c.number);x!==-1&&(a.steps[x].status="completed",l=`Auto-completed step ${c.number} (${c.name})`,Ca(o,s))}let m;if(r!==void 0){if(m=a.steps.find(x=>x.number===r),!m)return d(`Step ${r} not found. The plan has ${a.steps.length} steps (numbered ${a.steps[0].number} to ${a.steps[a.steps.length-1].number}).`,!0)}else if(m=a.steps.find(x=>x.status!=="completed"),!m)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(x=>x.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let p=a.steps.filter(x=>x.status==="completed").map(x=>`Step ${x.number}: ${x.name}`),{readLocalState:u}=await Promise.resolve().then(()=>(Pt(),pn)),g=u(o),j=Su(m),I=[];if((j==="crud"||j==="schema")&&a.dataModel&&m.entities&&m.entities.length>0){let x=Ra(m,a.dataModel);for(let C of x){let V=pr(C);try{let F=(C.fields||[]).map(oe=>typeof oe=="string"?{name:oe,type:"text"}:{name:oe.name,type:vu(oe.type),required:oe.required!==!1});if(F.length===0)continue;let ae=s.dbProvider==="neon"?"nextjs-neon":"nextjs",le=await Hr(ae,V,F),P=0,ke=0;for(let oe of le.files){let Ce=tt(o,oe.path);if(yt(Ce)){ke++;continue}uu(hu(Ce),{recursive:!0}),Ps(Ce,oe.content),P++}let U=tt(o,"db","index.ts");if(yt(U)){let oe=Is(U,"utf-8");oe.includes(le.dbExport)||Ps(U,oe.trimEnd()+`
5312
+ `+le.dbExport+`
5313
+ `)}P>0?I.push(`${le.entityPascal} CRUD (${P} new files${ke>0?`, ${ke} existing skipped`:""})`):ke>0&&I.push(`${le.entityPascal} CRUD (all ${ke} files already exist \u2014 skipped)`)}catch(F){console.error(`Module generation failed for ${V} (non-fatal):`,F instanceof Error?F.message:F)}}}let S=await Cu(m,a,p,null,j,o),y=a.steps.findIndex(x=>x.number===m.number);if(y!==-1&&(s.plan.steps[y].status="in_progress",Ca(o,s)),g&&s.projectId){let{syncRemoteState:x}=await Promise.resolve().then(()=>(Pt(),pn));x(s.projectId,g).catch(()=>{})}let R=a.steps.every(x=>x.status==="completed"||x.number===m.number),z;R?z=`THIS IS THE LAST STEP. Rules for speed:
5314
5314
 
5315
5315
  1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
5316
5316
  2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
@@ -5327,46 +5327,46 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
5327
5327
  2. Write ALL files for this step using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message. Do NOT write one file at a time.
5328
5328
  3. Do NOT read files you already know: AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts, drizzle.config.ts \u2014 these haven't changed.
5329
5329
  4. Only read a file if you need to MODIFY it (e.g. sidebar.tsx to add a nav link, db/index.ts to add an export).
5330
- 5. After writing ALL files, call mist_implement to move to the next step. If you used any process.env.X that isn't already in mistflow.json env.required, pass it via envVarsRequired on this call so the dashboard can prompt the user for it (skip keys covered by integration presets \u2014 those are pre-declared). Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let H=Su(W),ne={stepNumber:u.number,totalSteps:a.steps.length,estimatedMinutes:H,announcement:`Starting step ${u.number} of ${a.steps.length}: ${u.name}. This step usually takes ${H.min}\u2013${H.max} minutes.`},Q=JSON.stringify({instruction:k,step:{number:u.number,name:u.name,description:u.description,status:"in_progress"},stepTiming:ne,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_implement again immediately after the compaction finishes. The tool finds the in-progress step and returns fresh context \u2014 you don't need to re-read files or re-derive state.",...l?{autoCompleted:l}:{},..._.length>0?{generatedModules:_,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${h.length}/${a.steps.length} steps done`,nextAction:z}),q=da(o),I=q?.url??"http://localhost:3000",se=q?.port??3e3;return await gu(se)&&oa(o,u.number,a.steps.length)?(ia(o,u.number),Gs(I,Q)):p(Q)}var fu,ku,Ra,Ea=P(()=>{"use strict";be();_e();zn();ss();cs();qi();ds();Ss();nr();ma();ga();ya();wa();ka();Sa();_a();Ts();fu=kn.object({projectPath:kn.string().optional().describe("Path to the project directory (default: cwd)"),step:kn.number().optional().describe("Specific step number to implement (default: next incomplete step)"),sessionId:kn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),envVarsRequired:kn.array(lr).optional().describe("Declare any env vars the code you just wrote uses (process.env.X) that aren't already in mistflow.json env.required. Server merges these into the manifest so missing values surface as warnings on deploy. Skip keys already covered by integration presets (Stripe, Resend, etc. \u2014 those are pre-declared). Only declare ad-hoc keys you introduced. First declaration wins; re-declaring is a no-op.")});ku=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);Ra={name:"mist_implement",description:"Execute the next step (or a specific step) from the app plan. Reads mistflow.json, finds the target step, and returns rich context and detailed implementation instructions for the host AI. Auto-commits a checkpoint before changes for safe undo. Use when the user says 'mist implement' or 'mist next step'.",inputSchema:fu,handler:Cu}});import{z as ft}from"zod";import{resolve as Au}from"path";async function Na(t){let{projectPath:e,action:r,key:n,value:i,category:o,description:s,setupUrl:a}=t,l=Au(e??process.cwd());if(!Se())return Ee("manage env vars");let u=it(l)?.projectId;if(!u)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"set":return n?i?(await Or(u,n,i,{category:o,description:s,setupUrl:a}),p(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):p("Value is required. Provide the env var value.",!0):p("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let h=await Nr(u);return h.length===0?p(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):p(JSON.stringify({envVars:h.map(d=>({key:d.key,category:d.category,description:d.description,hasValue:d.has_value})),message:`${h.length} environment variable(s) configured.`}))}case"delete":return n?(await jr(u,n),p(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):p("Key is required. Provide the env var name to delete.",!0);default:return p(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(h){if(h instanceof G)return p(h.message,!0);let d=h instanceof Error?h.message:"An unexpected error occurred";return p(d,!0)}}var wy,Oa=P(()=>{"use strict";be();_e();kt();wy=ft.object({projectPath:ft.string().optional().describe("Path to the project directory (default: cwd)"),action:ft.enum(["set","list","delete"]).describe("Action to perform"),key:ft.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:ft.string().optional().describe("Environment variable value (required for 'set')"),category:ft.string().optional().describe("Category for the env var (default: 'custom')"),description:ft.string().optional().describe("Description of what this env var is for"),setupUrl:ft.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as xn}from"zod";import{resolve as Ru,join as Eu}from"path";import{existsSync as Nu,readFileSync as Ou,writeFileSync as ju}from"fs";function Is(t,e){let r=Eu(t,"mistflow.json");if(!Nu(r))return;let n;try{n=JSON.parse(Ou(r,"utf-8"))}catch{return}n.domains=e,ju(r,JSON.stringify(n,null,2)+`
5331
- `)}async function ja(t){let{projectPath:e,action:r,domain:n,domainId:i}=t,o=Ru(e??process.cwd());if(!Se())return Ee("manage custom domains");let a=it(o)?.projectId;if(!a)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!n)return p("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Ar(a,n),c=await lt(a);return Is(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await lt(a);return l.length===0?p(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):p(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!i){if(n){let h=(await lt(a)).find(d=>d.domain===n);if(h){let d=await $n(a,h.id);return p(JSON.stringify({domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message,message:d.status==="active"?`Domain '${d.domain}' is active and serving traffic.`:`Domain '${d.domain}' is ${d.status}. Make sure DNS records are configured correctly.`}))}return p(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return p("Provide either domainId or domain name to verify.",!0)}let l=await $n(a,i),c=await lt(a);return Is(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!i&&!n)return p("Provide either domainId or domain name to remove.",!0);let l=i;if(!l&&n){let h=(await lt(a)).find(d=>d.domain===n);if(!h)return p(`Domain '${n}' not found.`,!0);l=h.id}await Rr(a,l);let c=await lt(a);return Is(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return p(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof G)return p(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return p(c,!0)}}var Iy,Da=P(()=>{"use strict";be();_e();kt();Iy=xn.object({projectPath:xn.string().optional().describe("Path to the project directory (default: cwd)"),action:xn.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:xn.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:xn.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as Be}from"zod";var Du,Ma,La=P(()=>{"use strict";be();Oa();Da();Du=Be.object({resource:Be.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Be.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Be.string().optional().describe("Path to the project directory (default: cwd)"),key:Be.string().optional().describe("(env) Variable name"),value:Be.string().optional().describe("(env set) Variable value"),category:Be.string().optional().describe("(env set) Category"),description:Be.string().optional().describe("(env set) Description"),setupUrl:Be.string().optional().describe("(env set) URL to obtain the value"),domain:Be.string().optional().describe("(domain) Domain name"),domainId:Be.string().optional().describe("(domain) Domain ID")}),Ma={name:"mist_config",description:"Manage project configuration: app secrets and custom domains. Set resource='env' to manage encrypted app secrets (set, list, delete). Set resource='domain' to manage custom domains (add, list, verify, remove). Use when the user says 'mist env' or 'mist domain'.",inputSchema:Du,handler:async t=>{let e=t;switch(e.resource){case"env":return Na({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return ja({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return p(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}}});import{z as Sn}from"zod";import{resolve as Mu}from"path";import{existsSync as Lu}from"fs";import{join as Uu}from"path";function $u(t,e=15){let r=t.split(`
5330
+ 5. After writing ALL files, call mist_implement to move to the next step. If you used any process.env.X that isn't already in mistflow.json env.required, pass it via envVarsRequired on this call so the dashboard can prompt the user for it (skip keys covered by integration presets \u2014 those are pre-declared). Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let W=Tu(j),te={stepNumber:m.number,totalSteps:a.steps.length,estimatedMinutes:W,announcement:`Starting step ${m.number} of ${a.steps.length}: ${m.name}. This step usually takes ${W.min}\u2013${W.max} minutes.`},L=JSON.stringify({instruction:S,step:{number:m.number,name:m.name,description:m.description,status:"in_progress"},stepTiming:te,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_implement again immediately after the compaction finishes. The tool finds the in-progress step and returns fresh context \u2014 you don't need to re-read files or re-derive state.",...l?{autoCompleted:l}:{},...I.length>0?{generatedModules:I,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${p.length}/${a.steps.length} steps done`,nextAction:z}),H=pa(o),E=H?.url??"http://localhost:3000",Z=H?.port??3e3;return await fu(Z)&&ia(o,m.number,a.steps.length)?(aa(o,m.number),Vs(E,L)):d(L)}var yu,xu,Ea,Na=_(()=>{"use strict";be();_e();Hn();os();ds();Bi();ps();Ts();rr();ha();fa();ba();va();xa();Ta();Pa();_s();yu=xn.object({projectPath:xn.string().optional().describe("Path to the project directory (default: cwd)"),step:xn.number().optional().describe("Specific step number to implement (default: next incomplete step)"),sessionId:xn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),envVarsRequired:xn.array(cr).optional().describe("Declare any env vars the code you just wrote uses (process.env.X) that aren't already in mistflow.json env.required. Server merges these into the manifest so missing values surface as warnings on deploy. Skip keys already covered by integration presets (Stripe, Resend, etc. \u2014 those are pre-declared). Only declare ad-hoc keys you introduced. First declaration wins; re-declaring is a no-op.")});xu=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);Ea={name:"mist_implement",description:"Execute the next step (or a specific step) from the app plan. Reads mistflow.json, finds the target step, and returns rich context and detailed implementation instructions for the host AI. Auto-commits a checkpoint before changes for safe undo. Use when the user says 'mist implement' or 'mist next step'.",inputSchema:yu,handler:Au}});import{z as bt}from"zod";import{resolve as Ru}from"path";async function Oa(t){let{projectPath:e,action:r,key:n,value:i,category:o,description:s,setupUrl:a}=t,l=Ru(e??process.cwd());if(!xe())return Oe("manage env vars");let m=lt(l)?.projectId;if(!m)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"set":return n?i?(await Dr(m,n,i,{category:o,description:s,setupUrl:a}),d(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):d("Value is required. Provide the env var value.",!0):d("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let p=await Or(m);return p.length===0?d(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):d(JSON.stringify({envVars:p.map(u=>({key:u.key,category:u.category,description:u.description,hasValue:u.has_value})),message:`${p.length} environment variable(s) configured.`}))}case"delete":return n?(await jr(m,n),d(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):d("Key is required. Provide the env var name to delete.",!0);default:return d(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(p){if(p instanceof K)return d(p.message,!0);let u=p instanceof Error?p.message:"An unexpected error occurred";return d(u,!0)}}var vy,Da=_(()=>{"use strict";be();_e();St();vy=bt.object({projectPath:bt.string().optional().describe("Path to the project directory (default: cwd)"),action:bt.enum(["set","list","delete"]).describe("Action to perform"),key:bt.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:bt.string().optional().describe("Environment variable value (required for 'set')"),category:bt.string().optional().describe("Category for the env var (default: 'custom')"),description:bt.string().optional().describe("Description of what this env var is for"),setupUrl:bt.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as Sn}from"zod";import{resolve as Eu,join as Nu}from"path";import{existsSync as Ou,readFileSync as Du,writeFileSync as ju}from"fs";function Cs(t,e){let r=Nu(t,"mistflow.json");if(!Ou(r))return;let n;try{n=JSON.parse(Du(r,"utf-8"))}catch{return}n.domains=e,ju(r,JSON.stringify(n,null,2)+`
5331
+ `)}async function ja(t){let{projectPath:e,action:r,domain:n,domainId:i}=t,o=Eu(e??process.cwd());if(!xe())return Oe("manage custom domains");let a=lt(o)?.projectId;if(!a)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!n)return d("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Rr(a,n),c=await dt(a);return Cs(o,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await dt(a);return l.length===0?d(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):d(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!i){if(n){let p=(await dt(a)).find(u=>u.domain===n);if(p){let u=await Fn(a,p.id);return d(JSON.stringify({domain:u.domain,status:u.status,ssl:u.ssl_status,error:u.error_message,message:u.status==="active"?`Domain '${u.domain}' is active and serving traffic.`:`Domain '${u.domain}' is ${u.status}. Make sure DNS records are configured correctly.`}))}return d(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return d("Provide either domainId or domain name to verify.",!0)}let l=await Fn(a,i),c=await dt(a);return Cs(o,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!i&&!n)return d("Provide either domainId or domain name to remove.",!0);let l=i;if(!l&&n){let p=(await dt(a)).find(u=>u.domain===n);if(!p)return d(`Domain '${n}' not found.`,!0);l=p.id}await Er(a,l);let c=await dt(a);return Cs(o,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return d(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof K)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var Cy,Ma=_(()=>{"use strict";be();_e();St();Cy=Sn.object({projectPath:Sn.string().optional().describe("Path to the project directory (default: cwd)"),action:Sn.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:Sn.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:Sn.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as He}from"zod";var Mu,La,Ua=_(()=>{"use strict";be();Da();Ma();Mu=He.object({resource:He.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:He.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:He.string().optional().describe("Path to the project directory (default: cwd)"),key:He.string().optional().describe("(env) Variable name"),value:He.string().optional().describe("(env set) Variable value"),category:He.string().optional().describe("(env set) Category"),description:He.string().optional().describe("(env set) Description"),setupUrl:He.string().optional().describe("(env set) URL to obtain the value"),domain:He.string().optional().describe("(domain) Domain name"),domainId:He.string().optional().describe("(domain) Domain ID")}),La={name:"mist_config",description:"Manage project configuration: app secrets and custom domains. Set resource='env' to manage encrypted app secrets (set, list, delete). Set resource='domain' to manage custom domains (add, list, verify, remove). Use when the user says 'mist env' or 'mist domain'.",inputSchema:Mu,handler:async t=>{let e=t;switch(e.resource){case"env":return Oa({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return ja({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return d(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}}});import{z as Tn}from"zod";import{resolve as Lu}from"path";import{existsSync as Uu}from"fs";import{join as $u}from"path";function Fu(t,e=15){let r=t.split(`
5332
5332
  `).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
5333
- `)}var Fu,Ua,$a=P(()=>{"use strict";be();wn();qt();Ss();Fu=Sn.object({projectPath:Sn.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:Sn.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:Sn.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical install fits in 2 round-trips instead of 5-6. Default 20. Set 0 to disable."),sessionId:Sn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),Ua={name:"mist_install",description:"Install a Mistflow project's npm dependencies with the fire-and-poll pattern. First call with { projectPath } starts the install and returns a jobId. Subsequent calls with { jobId } poll for progress (status: 'running' | 'complete' | 'failed'). Re-call while status is 'running' \u2014 each response is <1s so there is no 60s timeout risk.",inputSchema:Fu,handler:async(t,e)=>{let r=t;if(r.jobId){let l=await ht(r.jobId);if(!l)return p(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No install job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let c=r.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let h=l.elapsed,d=e?qe(e.server,e.progressToken,()=>`Install running (${h}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let v=await Kt(r.jobId,{timeoutMs:c*1e3,onPoll:W=>{h=W.elapsed}});v&&(l=v)}finally{d.stop()}}if(l.status==="running"||l.status==="starting")return p(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:$u(l.logTail),nextAction:"Install still running after long-poll window. Call mist_install again with the same jobId to continue waiting."}));if(l.status==="complete"){let h=await pa(l.cwd),d=!1;h&&h.freshlyStarted?(d=await aa(h.state.url,15e3),d&&ua(h.state.url)):h&&(d=!0);let v=h?d?` PREVIEW: Live dev server at ${h.state.url} (browser opened). TELL THE USER: "Your app is rendering at ${h.state.url} \u2014 it'll refresh live as it's built."`:` PREVIEW: Dev server starting at ${h.state.url} (still compiling). TELL THE USER: "Open ${h.state.url} in your browser in ~30s \u2014 your app will appear there and refresh live as it's built."`:"";return p(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,...h?{previewUrl:h.state.url,previewReady:d}:{},nextAction:`Dependencies installed.${v} Run mist_implement next to start executing plan steps.`}))}let u=Ct(l.id);return p(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:u,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${u.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let n=Mu(r.projectPath);if(!Lu(Uu(n,"package.json")))return p(`No package.json at ${n}. Confirm the path and that mist_init has scaffolded the project.`,!0);let s=`npm install && (${`npx --yes shadcn@latest add -y -o ${["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"].join(" ")}`} || echo 'shadcn add failed \u2014 implement will retry lazily')`,a=await mt({type:"install",cmd:"sh",args:["-c",s],cwd:n,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return p(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:n,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+a.id+"' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s."}))}}});import{z as Jt}from"zod";import{resolve as qu,join as ze}from"path";import{existsSync as Ge,readFileSync as Fa,statSync as Bu,readdirSync as zu}from"fs";function Hu(t){let e=0,r=0,n=[t];for(;n.length>0&&r<1e4;){let i=n.pop();r++;let o;try{o=zu(i)}catch{continue}for(let s of o){let a=ze(i,s),l;try{l=Bu(a)}catch{continue}l.isDirectory()?n.push(a):l.isFile()&&(e+=l.size)}}return e}function Wu(t){if(!(Ge(ze(t,"open-next.config.ts"))||Ge(ze(t,"open-next.config.js"))))return null;let r=ze(t,".open-next","worker.js");if(!Ge(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker entrypoint. Common causes: (1) open-next.config.ts is misconfigured, (2) a client component imports a Node-only API (fs, path, crypto node:* imports in 'use client' files), (3) the adapter crashed silently mid-build. Check the logTail above for "error"/"failed" messages, fix the offending file, and re-run mist_build.`;let n=ze(t,".open-next","server-functions","default");if(!Ge(n))return'Build exited 0 and .open-next/worker.js exists, but .open-next/server-functions/default/ is missing. The OpenNext adapter produced an orchestrator with no server bundle to import. Check the logTail above for "error"/"failed" messages near "Building server function: default..." and re-run mist_build.';let i=Hu(n);return i<qa?`Build exited 0 but the server-functions bundle is only ${i} bytes (expected at least ${qa}). A healthy Next.js + OpenNext bundle is 5-50MB. This size suggests the adapter failed to bundle most of the app. Check the logTail for bundling errors and re-run mist_build.`:null}function Vu(t){let e=ze(or(),t,"stdout.log"),r=ze(or(),t,"stderr.log"),n="";try{Ge(e)&&(n+=Fa(e,"utf-8"))}catch{}try{Ge(r)&&(n+=`
5334
- `+Fa(r,"utf-8"))}catch{}return n}function Ku(t,e=15){let r=t.split(`
5333
+ `)}var qu,$a,Fa=_(()=>{"use strict";be();vn();Bt();Ts();qu=Tn.object({projectPath:Tn.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:Tn.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:Tn.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical install fits in 2 round-trips instead of 5-6. Default 20. Set 0 to disable."),sessionId:Tn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),$a={name:"mist_install",description:"Install a Mistflow project's npm dependencies with the fire-and-poll pattern. First call with { projectPath } starts the install and returns a jobId. Subsequent calls with { jobId } poll for progress (status: 'running' | 'complete' | 'failed'). Re-call while status is 'running' \u2014 each response is <1s so there is no 60s timeout risk.",inputSchema:qu,handler:async(t,e)=>{let r=t;if(r.jobId){let l=await ft(r.jobId);if(!l)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No install job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let c=r.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let p=l.elapsed,u=e?ze(e.server,e.progressToken,()=>`Install running (${p}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let g=await Jt(r.jobId,{timeoutMs:c*1e3,onPoll:j=>{p=j.elapsed}});g&&(l=g)}finally{u.stop()}}if(l.status==="running"||l.status==="starting")return d(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:Fu(l.logTail),nextAction:"Install still running after long-poll window. Call mist_install again with the same jobId to continue waiting."}));if(l.status==="complete"){let p=await ua(l.cwd),u=!1;p&&p.freshlyStarted?(u=await la(p.state.url,15e3),u&&ma(p.state.url)):p&&(u=!0);let g=p?u?` PREVIEW: Live dev server at ${p.state.url} (browser opened). TELL THE USER: "Your app is rendering at ${p.state.url} \u2014 it'll refresh live as it's built."`:` PREVIEW: Dev server starting at ${p.state.url} (still compiling). TELL THE USER: "Open ${p.state.url} in your browser in ~30s \u2014 your app will appear there and refresh live as it's built."`:"";return d(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,...p?{previewUrl:p.state.url,previewReady:u}:{},nextAction:`Dependencies installed.${g} Run mist_implement next to start executing plan steps.`}))}let m=Rt(l.id);return d(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:m,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${m.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let n=Lu(r.projectPath);if(!Uu($u(n,"package.json")))return d(`No package.json at ${n}. Confirm the path and that mist_init has scaffolded the project.`,!0);let s=`npm install && (${`npx --yes shadcn@latest add -y -o ${["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"].join(" ")}`} || echo 'shadcn add failed \u2014 implement will retry lazily')`,a=await gt({type:"install",cmd:"sh",args:["-c",s],cwd:n,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return d(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:n,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+a.id+"' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s."}))}}});import{z as Yt}from"zod";import{resolve as Bu,join as We}from"path";import{existsSync as Ge,readFileSync as qa,statSync as zu,readdirSync as Hu}from"fs";function Wu(t){let e=0,r=0,n=[t];for(;n.length>0&&r<1e4;){let i=n.pop();r++;let o;try{o=Hu(i)}catch{continue}for(let s of o){let a=We(i,s),l;try{l=zu(a)}catch{continue}l.isDirectory()?n.push(a):l.isFile()&&(e+=l.size)}}return e}function Gu(t){if(!(Ge(We(t,"open-next.config.ts"))||Ge(We(t,"open-next.config.js"))))return null;let r=We(t,".open-next","worker.js");if(!Ge(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker entrypoint. Common causes: (1) open-next.config.ts is misconfigured, (2) a client component imports a Node-only API (fs, path, crypto node:* imports in 'use client' files), (3) the adapter crashed silently mid-build. Check the logTail above for "error"/"failed" messages, fix the offending file, and re-run mist_build.`;let n=We(t,".open-next","server-functions","default");if(!Ge(n))return'Build exited 0 and .open-next/worker.js exists, but .open-next/server-functions/default/ is missing. The OpenNext adapter produced an orchestrator with no server bundle to import. Check the logTail above for "error"/"failed" messages near "Building server function: default..." and re-run mist_build.';let i=Wu(n);return i<Ba?`Build exited 0 but the server-functions bundle is only ${i} bytes (expected at least ${Ba}). A healthy Next.js + OpenNext bundle is 5-50MB. This size suggests the adapter failed to bundle most of the app. Check the logTail for bundling errors and re-run mist_build.`:null}function Ku(t){let e=We(ir(),t,"stdout.log"),r=We(ir(),t,"stderr.log"),n="";try{Ge(e)&&(n+=qa(e,"utf-8"))}catch{}try{Ge(r)&&(n+=`
5334
+ `+qa(r,"utf-8"))}catch{}return n}function Ju(t,e=15){let r=t.split(`
5335
5335
  `).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
5336
- `)}function Ju(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let n of t.matchAll(e)){let i=n[1];if(i.startsWith(".")||i.startsWith("@/")||i.startsWith("~/"))continue;let o=i.startsWith("@")?i.split("/").slice(0,2).join("/"):i.split("/")[0];o&&r.add(o)}return[...r]}function Yu(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${It()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var qa,Gu,Ba,za=P(()=>{"use strict";be();wn();os();qt();Zn();qa=100*1024;Gu=Jt.object({projectPath:Jt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Jt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Jt.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls."),waitSeconds:Jt.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical build fits in 2 round-trips instead of 6-8. Default 20. Set 0 to disable."),sessionId:Jt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});Ba={name:"mist_build",description:"Run a Mistflow project's production build with the fire-and-poll pattern. First call with { projectPath } starts `npm run build` and returns a jobId. Subsequent calls with { jobId } poll status. On failure, the response surfaces structured errors (from parseBuildErrors) and any missingModules[] \u2014 chain into mist_install with those modules, then mist_build again, without asking the user.",inputSchema:Gu,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await ht(r.jobId);if(!c)return p(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let u=r.waitSeconds??20;if(u>0&&(c.status==="running"||c.status==="starting")){let A=c.elapsed,z=e?qe(e.server,e.progressToken,()=>`Build running (${A}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let H=await Kt(r.jobId,{timeoutMs:u*1e3,onPoll:ne=>{A=ne.elapsed}});H&&(c=H)}finally{z.stop()}}if(c.status==="running"||c.status==="starting")return p(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Ku(c.logTail),nextAction:"Build still running after long-poll window. Call mist_build again with the same jobId to continue waiting."}));if(c.status==="complete"){let A=Wu(c.cwd);if(A){let z=Ct(c.id);return p(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:z,error:A,nextAction:A+` Full build log: ${z.stdout} and ${z.stderr}.`}),!0)}return p(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let h=Vu(c.id),d=Jn(h),v=Ju(h),W=Yu(h),_=Ct(c.id),k=` Full log: ${_.stdout} and ${_.stderr}.`,y=v.length>0?`Build failed with missing modules: ${v.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${k}`:W?`${W}${k}`:d.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${k}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${k}`;return p(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:d,missingModules:v,logTail:c.logTail,logPaths:_,nextAction:y}),!0)}let n=qu(r.projectPath);if(!Ge(ze(n,"package.json")))return p(`No package.json at ${n}. Run mist_init first.`,!0);if(!Ge(ze(n,"node_modules")))return p(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let i,o,s,a=Ge(ze(n,"open-next.config.ts"))||Ge(ze(n,"open-next.config.js"));if(r.script)i="npm",o=["run",r.script],s=r.script;else if(a){if(!Bt())return p(It(),!0);i="npx",o=["-y","@opennextjs/cloudflare","build"],s="@opennextjs/cloudflare build"}else i="npm",o=["run","build"],s="build";let l=await mt({type:"build",cmd:i,args:o,cwd:n});return p(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:s,nextAction:`Build started. Call mist_build again with { jobId: '${l.id}' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}}});import{existsSync as Qu,readdirSync as Xu}from"fs";import{join as Ha}from"path";import{pathToFileURL as Zu}from"url";async function em(t){let e=Ha(t,".mistflow","acceptance"),r=new Map;if(!Qu(e))return r;let n=Xu(e).filter(i=>i.endsWith(".spec.ts")||i.endsWith(".spec.js")||i.endsWith(".spec.mjs"));for(let i of n){let o=i.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!o)continue;let s=Ha(e,i);try{let a=await import(Zu(s).href),l=a.default??a.run;typeof l=="function"?r.set(o,l):console.error(`Probe ${i} doesn't export a default function (or named 'run'). Skipping.`)}catch(a){console.error(`Failed to load probe ${i}:`,a instanceof Error?a.message:a)}}return r}async function Wa(t,e){let{sessionId:r,projectPath:n,deployUrl:i,seedCredentials:o}=e,a=(await sn(r)).criteria,l=await em(n),c=[];for(let u of a){let h=l.get(u.id);if(!h){c.push({criterion_id:u.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${u.id}.spec.ts`}});continue}try{await t.goto(i,{waitUntil:"domcontentloaded"});let d=await h(t,{url:i,criterion:u,seedCredentials:o});c.push({criterion_id:u.id,status:d.pass?"pass":"fail",evidence:{...d.detail?{detail:d.detail}:{},...d.screenshot?{screenshot:d.screenshot}:{}}})}catch(d){c.push({criterion_id:u.id,status:"fail",evidence:{error:d instanceof Error?d.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var Ga=P(()=>{"use strict";_e()});import{existsSync as tm,readFileSync as nm}from"fs";import{join as rm}from"path";import{z as Yt}from"zod";function Ya(t){let e=rm(t,"mistflow.json");if(!tm(e))return null;try{return JSON.parse(nm(e,"utf-8"))}catch{return null}}async function Va(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await e.text();return{status:e.status,body:r}}catch(e){return{status:0,body:String(e)}}}async function om(t,e,r){try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),i=await n.text(),o;try{o=JSON.parse(i)}catch{}return{status:n.status,json:o}}catch{return{status:0}}}async function Ka(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function yt(t,e,r){let n=[],i=o=>{o.type()==="error"&&n.push(o.text())};t.on("console",i);try{let o=await r(),s=await Ka(t);return{name:e,status:o.pass?"pass":"fail",detail:o.detail,fix:o.fix,screenshot:s,consoleErrors:n.length>0?n:void 0}}catch(o){let s=await Ka(t);return{name:e,status:"fail",detail:`Unexpected error: ${o instanceof Error?o.message:String(o)}`,screenshot:s,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",i)}}async function im(t){if(!t.sessionId)return p("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=Ya(e),n=t.url;if(!n&&t.deploymentId)try{let a=await at(t.deploymentId);a.url&&(n=a.url)}catch(a){console.error(`[acceptance] Could not resolve URL from deploymentId ${t.deploymentId}:`,a instanceof Error?a.message:String(a))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa action='acceptance'.",!0);let i;if(t.deploymentId)try{let l=await Fn(t.deploymentId);l?.adminEmail&&l?.adminPassword&&(i={email:l.adminEmail,password:l.adminPassword})}catch(a){console.error("[acceptance] getSeedInfo failed (continuing without):",a instanceof Error?a.message:String(a))}let o,s;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(Et(),nn)),l=await a();o=l.context,s=l.page}catch(a){return p(`Playwright not available locally \u2014 install it with \`npx playwright install chromium\`. Detail: ${a instanceof Error?a.message:String(a)}`,!0)}try{let{criteria:a,results:l}=await Wa(s,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:i});try{await Jr(t.sessionId,l)}catch(d){console.error("[acceptance] submitAcceptanceResults failed:",d instanceof Error?d.message:String(d))}let c=l.filter(d=>d.status==="pass").length,u=l.filter(d=>d.status==="fail").length,h=l.filter(d=>d.status==="skipped").length;return p(JSON.stringify({status:u===0?"pass":"fail",url:n,totals:{passed:c,failed:u,skipped:h,total:a.length},results:l.map(d=>({criterion_id:d.criterion_id,status:d.status,detail:d.evidence&&typeof d.evidence=="object"&&"detail"in d.evidence?d.evidence.detail:d.evidence&&typeof d.evidence=="object"&&"reason"in d.evidence?d.evidence.reason:void 0})),nextAction:u===0?"All required acceptance criteria passed. The app is shippable.":"Some criteria failed. Read the per-criterion detail, fix the underlying code, then re-run mist_qa action='acceptance'."}),u>0)}finally{if(o)try{await o.close()}catch{}}}async function am(t){let e=t.projectPath??process.cwd(),r=Ya(e),n=t.url;if(!n&&t.deploymentId)try{let A=await at(t.deploymentId);A.url&&(n=A.url)}catch(A){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,A instanceof Error?A.message:String(A))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);n.startsWith("http")||(n=`https://${n}`);let i=r?.projectId,o=[],s=await Va(`${n}/api/health`);if(s.status!==200)return o.push({name:"Health endpoint",status:"fail",detail:`Returns ${s.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),pr(n,o);o.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Va(`${n}/api/auth/ok`);if(a.status!==200)return o.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${a.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),pr(n,o);o.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",u="QaTemp1!",h="single",d="user",v=[];async function W(A,z,H,ne){let ee=await om(`${n}/api/admin/seed`,{token:ne,email:z,password:u,role:H});if(ee.status!==200||!ee.json)return console.error(`[qa] Seed (${A}) returned ${ee.status}`),null;let Q=ee.json.sessionToken;if(!Q)return null;let q=ee.json.seeded===!0;return{role:A,email:z,sessionToken:Q,password:q?u:void 0}}if(i){let A=await Fn(i);if(A){if(h=A.authMode??"single",d=A.defaultRole??"user",console.error(`[qa] auth_mode=${h}, default_role=${d}`),h!=="none"){let H=await W("actor",l,h==="multi"?"admin":d,A.seedToken);if(H&&v.push(H),h==="multi"){let ne=await W("user",c,d,A.seedToken);ne?v.push(ne):o.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${d}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),h="none"}if(h!=="none"&&v.length===0)return o.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy injects ADMIN_SEED_TOKEN and stores it on the backend; the scaffold's /api/admin/seed route accepts { token, email, password, role } and creates synthetic QA users with the requested role."}),pr(n,o);let _,k,y;try{let{getIsolatedContext:A}=await Promise.resolve().then(()=>(Et(),nn)),z=await A();_=z.context,y=z.page}catch(A){let z=A instanceof Error?A.message:String(A);return p(JSON.stringify({status:"cannot_verify",url:n,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:z,httpChecks:o.map(({screenshot:H,...ne})=>ne),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${n}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${n}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_qa again for full verification."].join(`
5337
- `)}),!1)}try{let A=await yt(y,"Landing page",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await y.waitForLoadState("networkidle").catch(()=>{});let Q=await y.evaluate(()=>{let I=document.body;if(!I)return"";let se=document.createTreeWalker(I,NodeFilter.SHOW_TEXT),B="",b;for(;b=se.nextNode();){let $=b.parentElement;if($){let V=window.getComputedStyle($);V.display!=="none"&&V.visibility!=="hidden"&&parseFloat(V.opacity)>0&&(B+=b.textContent?.trim()+" ")}}return B.trim()});if(Q.length<50)return{pass:!1,detail:`Landing page appears blank (${Q.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let q=y.url();return q.includes("/login")||q.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${Q.length} chars)`}});o.push(A),h==="none"&&o.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let z=v[0],H=(Q,q)=>v.length>1&&Q?`${q} (${Q.role})`:q,ne=!1;if(z?.password){let Q=await yt(y,H(z,"Login"),async()=>{await y.goto(`${n}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let q=y.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),I=y.locator('input[type="password"], input[name="password"]');try{await q.first().waitFor({state:"visible",timeout:1e4})}catch{return{pass:!1,detail:"Login page has no visible email input field",fix:"Check app/(auth)/login/page.tsx renders a login form with email and password inputs."}}await q.first().fill(z.email),await I.first().fill(z.password),await y.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await y.waitForURL(B=>!B.pathname.includes("/login"),{timeout:1e4})}catch{let B=await y.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:B?`Login failed: ${B}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified QA accounts."}}return ne=!0,{pass:!0,detail:`Logged in, redirected to ${y.url()}`}});o.push(Q)}else z&&o.push({name:H(z,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!ne&&z){let Q=new URL(n).hostname,q=n.startsWith("https");await _.addCookies([{name:q?"__Secure-better-auth.session_token":"better-auth.session_token",value:z.sessionToken,domain:Q,path:"/",httpOnly:!0,secure:q,sameSite:"Lax"}]),console.error(`[qa] Injected ${z.role} cookie for primary walk`)}if(z){let Q=await yt(y,H(z,"Dashboard"),async()=>{y.url().includes("/dashboard")||(await y.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}),new URL(y.url()).pathname==="/"&&(await y.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{})));let se=await y.content();return se.length<1e3?{pass:!1,detail:`Dashboard page is very small (${se.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await y.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled null/undefined or missing database tables."}:{pass:!0,detail:`Loads (${se.length} bytes)`}});o.push(Q);let q=await y.evaluate(()=>{let se=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(b=>{let $=b.getAttribute("href");$&&$.startsWith("/")&&!$.startsWith("/api")&&!$.includes("[")&&$!=="/dashboard"&&$!=="/"&&!$.includes("/login")&&!$.includes("/sign")&&se.push($)}),[...new Set(se)]});if(q.length>0){let se=0,B=[];for(let b of q.slice(0,8)){let $=await yt(y,H(z,`Page: ${b}`),async()=>{await y.goto(`${n}${b}`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let V=await y.title(),M=await y.content();return V.toLowerCase().includes("500")||V.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 server error",fix:"Server component crashed. Common causes: 1) Database tables missing. 2) Wrong ORM dialect (pgTable vs sqliteTable). 3) Unhandled null/undefined in server component."}:V.toLowerCase().includes("404")||V.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${b} not found. Create the page or remove the nav link.`}:await y.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:M.length<500?{pass:!1,detail:`Page is very small (${M.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});$.status==="fail"&&(se++,B.push(b)),o.push($)}}let I=await yt(y,"Design quality",async()=>{let se=y.url().includes("/dashboard")?y.url():`${n}/dashboard`;y.url().includes("/dashboard")||(await y.goto(se,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}));let B=await y.evaluate(()=>{let b=[],$=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),V=new Set;$.forEach(X=>{V.add(window.getComputedStyle(X).fontSize)}),$.length>=3&&V.size<2&&b.push("TYPOGRAPHY: All headings appear the same size. Create clear hierarchy with 3+ distinct sizes using a modular scale (1.25-1.5x ratio).");let M=Array.from($).map(X=>parseInt(X.tagName.charAt(1),10));for(let X=1;X<M.length;X++)if(M[X]-M[X-1]>1){b.push(`TYPOGRAPHY: Heading level skipped (h${M[X-1]} -> h${M[X]}). Use sequential heading levels for accessibility.`);break}let pe=document.querySelectorAll("*"),te=!1,R=!1;pe.forEach(X=>{let fe=window.getComputedStyle(X);fe.backgroundColor==="rgb(0, 0, 0)"&&X.clientHeight>100&&X.clientWidth>200&&(te=!0);let je=fe.backgroundColor,rt=fe.color;if(je&&!je.includes("0, 0, 0")&&!je.includes("255, 255, 255")&&je!=="rgba(0, 0, 0, 0)"&&je!=="transparent"&&rt.match(/rgb\((\d+), (\d+), (\d+)\)/)){let wt=rt.match(/rgb\((\d+), (\d+), (\d+)\)/);if(wt){let[st,We,m]=[parseInt(wt[1]),parseInt(wt[2]),parseInt(wt[3])],g=Math.abs(st-We)<10&&Math.abs(We-m)<10&&st>80&&st<180,w=je.match(/rgb\((\d+), (\d+), (\d+)\)/);if(g&&w){let[T,O,F]=[parseInt(w[1]),parseInt(w[2]),parseInt(w[3])];!(Math.abs(T-O)<15&&Math.abs(O-F)<15)&&X.textContent&&X.textContent.trim().length>0&&(R=!0)}}}}),te&&b.push("COLOR: Pure black (#000) background detected on a large element. Use a tinted dark color instead (e.g. oklch(15% 0.01 hue) or a deep navy/charcoal)."),R&&b.push("COLOR: Gray text on a colored background detected. Gray looks washed out on color. Use a darker shade of the background color or white instead.");let ge=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),K=!1;ge.forEach(X=>{X.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(K=!0)}),K&&b.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let ae=document.querySelectorAll("p, li, span, div"),Oe=0,ke=0;ae.forEach(X=>{X.textContent&&X.textContent.trim().length>20&&X.clientHeight>0&&(ke++,window.getComputedStyle(X).textAlign==="center"&&Oe++)}),ke>5&&Oe/ke>.7&&b.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let we=new Set;pe.forEach(X=>{let fe=window.getComputedStyle(X);fe.gap&&fe.gap!=="normal"&&fe.gap!=="0px"&&we.add(fe.gap)}),we.size===1&&pe.length>20&&b.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let Le=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(X=>{X.querySelectorAll("tbody tr").length===0&&(X.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||b.push("UX: Empty table with no empty state. Add a helpful message explaining what will appear here and a CTA to create the first item."))});let Ve=document.querySelectorAll("style"),He=!1;Ve.forEach(X=>{let fe=X.textContent||"";(fe.includes("bounce")||fe.includes("elastic")||fe.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(He=!0)}),He&&b.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let nt=document.querySelectorAll("button, a, input, select, [role='button']"),Ce=0;return nt.forEach(X=>{let fe=X.getBoundingClientRect();fe.width>0&&fe.height>0&&(fe.width<32||fe.height<32)&&Ce++}),Ce>3&&b.push(`ACCESSIBILITY: ${Ce} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),b});return B.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${B.length} design quality issue(s) found:
5338
- ${B.map((b,$)=>`${$+1}. ${b}`).join(`
5339
- `)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});o.push(I)}if(o.find(Q=>Q.name==="Landing page"&&Q.status==="pass")){let Q=await yt(y,"Landing design quality",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let q=await y.evaluate(()=>{let I=[];document.querySelectorAll("*").forEach($=>{let V=window.getComputedStyle($);(V.getPropertyValue("-webkit-background-clip")||V.getPropertyValue("background-clip"))==="text"&&$.textContent&&$.textContent.trim().length>0&&I.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let B=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(B){let $=(B.textContent||"").toLowerCase(),V=["transform your","unlock the power","revolutionize your","take your .* to the next level","the future of","welcome to","get started today","join thousands","powerful analytics","seamless integration","lightning fast"];for(let M of V)if($.match(new RegExp(M))){I.push(`COPY: Generic hero text detected ('${M}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach($=>{let M=window.getComputedStyle($).gridTemplateColumns;if(M){let pe=M.split(" ").filter(R=>R!=="").length,te=$.children;if(pe===3&&te.length===3){let R=Array.from(te).map(ae=>ae.offsetHeight),ge=R.every(ae=>Math.abs(ae-R[0])<5),K=Array.from(te).every(ae=>{let Oe=ae.querySelectorAll("svg"),ke=ae.querySelectorAll("h2, h3, h4"),we=ae.querySelectorAll("p");return Oe.length>=1&&ke.length>=1&&we.length>=1});ge&&K&&I.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),I});return q.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${q.length} landing design issue(s):
5340
- ${q.map((I,se)=>`${se+1}. ${I}`).join(`
5341
- `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});o.push(Q)}let ee=v[1];if(ee){let{getIsolatedContext:Q}=await Promise.resolve().then(()=>(Et(),nn)),q=await Q();k=q.context;let I=q.page,se=new URL(n).hostname,B=n.startsWith("https");await k.addCookies([{name:B?"__Secure-better-auth.session_token":"better-auth.session_token",value:ee.sessionToken,domain:se,path:"/",httpOnly:!0,secure:B,sameSite:"Lax"}]),console.error(`[qa] Injected ${ee.role} cookie for secondary walk`);let b=await yt(I,H(ee,"Dashboard"),async()=>{await I.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await I.waitForLoadState("networkidle").catch(()=>{}),new URL(I.url()).pathname==="/"&&(await I.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await I.waitForLoadState("networkidle").catch(()=>{}));let V=await I.content();return V.length<1e3?{pass:!1,detail:`Dashboard is very small (${V.length} bytes) for the default-role user`,fix:"The default-role user dashboard crashed or rendered empty. Check that role-gated server components handle non-admin roles without throwing."}:await I.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary for the default-role user",fix:"A server component crashed under the non-admin role. Likely a role check that throws instead of redirecting."}:{pass:!0,detail:`Loads (${V.length} bytes)`}});o.push(b);let $=await I.evaluate(()=>{let V=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(M=>{let pe=M.getAttribute("href");pe&&pe.startsWith("/")&&!pe.startsWith("/api")&&!pe.includes("[")&&pe!=="/dashboard"&&pe!=="/"&&!pe.includes("/login")&&!pe.includes("/sign")&&V.push(pe)}),[...new Set(V)]});for(let V of $.slice(0,8)){let M=await yt(I,H(ee,`Page: ${V}`),async()=>{await I.goto(`${n}${V}`,{waitUntil:"domcontentloaded",timeout:15e3}),await I.waitForLoadState("networkidle").catch(()=>{});let pe=await I.title(),te=await I.content();return pe.toLowerCase().includes("500")||pe.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 for the default-role user",fix:"Server component crashed under the non-admin role. Check role gates use redirect() not throw."}:pe.toLowerCase().includes("404")||pe.toLowerCase().includes("not found")?{pass:!0,detail:"404 (likely admin-only \u2014 acceptable)"}:await I.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Error boundary on page for default-role user",fix:"Role-gated content crashed. Use a graceful fallback."}:te.length<500?{pass:!1,detail:`Page very small (${te.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});o.push(M)}}}finally{_&&await _.close().catch(()=>{}),k&&await k.close().catch(()=>{})}if(t.deploymentId){let A=o.filter(ne=>ne.status==="fail"),z=o.filter(ne=>ne.status==="pass"),H=Date.now();await Er(t.deploymentId,{checks:o.map(({screenshot:ne,...ee})=>ee),overall:A.length===0?"pass":"fail",passed:z.length,failed:A.length,duration_ms:Date.now()-H}).catch(()=>{})}return pr(n,o)}function pr(t,e){let r=e.filter(o=>o.status==="fail"),n=e.filter(o=>o.status==="pass"),i=[];if(r.length===0)i.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${e.length} checks OK. The app is working correctly.`,url:t,checks:e.map(({screenshot:o,...s})=>s)})});else{let o=r.map((s,a)=>`${a+1}. **${s.name}**: ${s.detail}
5336
+ `)}function Yu(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let n of t.matchAll(e)){let i=n[1];if(i.startsWith(".")||i.startsWith("@/")||i.startsWith("~/"))continue;let o=i.startsWith("@")?i.split("/").slice(0,2).join("/"):i.split("/")[0];o&&r.add(o)}return[...r]}function Qu(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${At()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var Ba,Vu,za,Ha=_(()=>{"use strict";be();vn();is();Bt();er();Ba=100*1024;Vu=Yt.object({projectPath:Yt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Yt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Yt.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls."),waitSeconds:Yt.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical build fits in 2 round-trips instead of 6-8. Default 20. Set 0 to disable."),sessionId:Yt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});za={name:"mist_build",description:"Run a Mistflow project's production build with the fire-and-poll pattern. First call with { projectPath } starts `npm run build` and returns a jobId. Subsequent calls with { jobId } poll status. On failure, the response surfaces structured errors (from parseBuildErrors) and any missingModules[] \u2014 chain into mist_install with those modules, then mist_build again, without asking the user.",inputSchema:Vu,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await ft(r.jobId);if(!c)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let m=r.waitSeconds??20;if(m>0&&(c.status==="running"||c.status==="starting")){let R=c.elapsed,z=e?ze(e.server,e.progressToken,()=>`Build running (${R}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let W=await Jt(r.jobId,{timeoutMs:m*1e3,onPoll:te=>{R=te.elapsed}});W&&(c=W)}finally{z.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Ju(c.logTail),nextAction:"Build still running after long-poll window. Call mist_build again with the same jobId to continue waiting."}));if(c.status==="complete"){let R=Gu(c.cwd);if(R){let z=Rt(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:z,error:R,nextAction:R+` Full build log: ${z.stdout} and ${z.stderr}.`}),!0)}return d(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let p=Ku(c.id),u=Yn(p),g=Yu(p),j=Qu(p),I=Rt(c.id),S=` Full log: ${I.stdout} and ${I.stderr}.`,y=g.length>0?`Build failed with missing modules: ${g.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${S}`:j?`${j}${S}`:u.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${S}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${S}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:u,missingModules:g,logTail:c.logTail,logPaths:I,nextAction:y}),!0)}let n=Bu(r.projectPath);if(!Ge(We(n,"package.json")))return d(`No package.json at ${n}. Run mist_init first.`,!0);if(!Ge(We(n,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let i,o,s,a=Ge(We(n,"open-next.config.ts"))||Ge(We(n,"open-next.config.js"));if(r.script)i="npm",o=["run",r.script],s=r.script;else if(a){if(!zt())return d(At(),!0);i="npx",o=["-y","@opennextjs/cloudflare","build"],s="@opennextjs/cloudflare build"}else i="npm",o=["run","build"],s="build";let l=await gt({type:"build",cmd:i,args:o,cwd:n});return d(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:s,nextAction:`Build started. Call mist_build again with { jobId: '${l.id}' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}}});import{existsSync as Xu,readdirSync as Zu}from"fs";import{join as Wa}from"path";import{pathToFileURL as em}from"url";async function tm(t){let e=Wa(t,".mistflow","acceptance"),r=new Map;if(!Xu(e))return r;let n=Zu(e).filter(i=>i.endsWith(".spec.ts")||i.endsWith(".spec.js")||i.endsWith(".spec.mjs"));for(let i of n){let o=i.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!o)continue;let s=Wa(e,i);try{let a=await import(em(s).href),l=a.default??a.run;typeof l=="function"?r.set(o,l):console.error(`Probe ${i} doesn't export a default function (or named 'run'). Skipping.`)}catch(a){console.error(`Failed to load probe ${i}:`,a instanceof Error?a.message:a)}}return r}async function Ga(t,e){let{sessionId:r,projectPath:n,deployUrl:i,seedCredentials:o}=e,a=(await on(r)).criteria,l=await tm(n),c=[];for(let m of a){let p=l.get(m.id);if(!p){c.push({criterion_id:m.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${m.id}.spec.ts`}});continue}try{await t.goto(i,{waitUntil:"domcontentloaded"});let u=await p(t,{url:i,criterion:m,seedCredentials:o});c.push({criterion_id:m.id,status:u.pass?"pass":"fail",evidence:{...u.detail?{detail:u.detail}:{},...u.screenshot?{screenshot:u.screenshot}:{}}})}catch(u){c.push({criterion_id:m.id,status:"fail",evidence:{error:u instanceof Error?u.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var Va=_(()=>{"use strict";_e()});import{existsSync as nm,readFileSync as rm}from"fs";import{join as sm}from"path";import{z as Qt}from"zod";function Qa(t){let e=sm(t,"mistflow.json");if(!nm(e))return null;try{return JSON.parse(rm(e,"utf-8"))}catch{return null}}async function Ka(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await e.text();return{status:e.status,body:r}}catch(e){return{status:0,body:String(e)}}}async function im(t,e,r){try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),i=await n.text(),o;try{o=JSON.parse(i)}catch{}return{status:n.status,json:o}}catch{return{status:0}}}async function Ja(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function wt(t,e,r){let n=[],i=o=>{o.type()==="error"&&n.push(o.text())};t.on("console",i);try{let o=await r(),s=await Ja(t);return{name:e,status:o.pass?"pass":"fail",detail:o.detail,fix:o.fix,screenshot:s,consoleErrors:n.length>0?n:void 0}}catch(o){let s=await Ja(t);return{name:e,status:"fail",detail:`Unexpected error: ${o instanceof Error?o.message:String(o)}`,screenshot:s,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",i)}}async function am(t){if(!t.sessionId)return d("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=Qa(e),n=t.url;if(!n&&t.deploymentId)try{let a=await ct(t.deploymentId);a.url&&(n=a.url)}catch(a){console.error(`[acceptance] Could not resolve URL from deploymentId ${t.deploymentId}:`,a instanceof Error?a.message:String(a))}if(n||(n=r?.deploy?.url),!n)return d("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa action='acceptance'.",!0);let i;if(t.deploymentId)try{let l=await qn(t.deploymentId);l?.adminEmail&&l?.adminPassword&&(i={email:l.adminEmail,password:l.adminPassword})}catch(a){console.error("[acceptance] getSeedInfo failed (continuing without):",a instanceof Error?a.message:String(a))}let o,s;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(Nt(),rn)),l=await a();o=l.context,s=l.page}catch(a){return d(`Playwright not available locally \u2014 install it with \`npx playwright install chromium\`. Detail: ${a instanceof Error?a.message:String(a)}`,!0)}try{let{criteria:a,results:l}=await Ga(s,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:i});try{await Yr(t.sessionId,l)}catch(u){console.error("[acceptance] submitAcceptanceResults failed:",u instanceof Error?u.message:String(u))}let c=l.filter(u=>u.status==="pass").length,m=l.filter(u=>u.status==="fail").length,p=l.filter(u=>u.status==="skipped").length;return d(JSON.stringify({status:m===0?"pass":"fail",url:n,totals:{passed:c,failed:m,skipped:p,total:a.length},results:l.map(u=>({criterion_id:u.criterion_id,status:u.status,detail:u.evidence&&typeof u.evidence=="object"&&"detail"in u.evidence?u.evidence.detail:u.evidence&&typeof u.evidence=="object"&&"reason"in u.evidence?u.evidence.reason:void 0})),nextAction:m===0?"All required acceptance criteria passed. The app is shippable.":"Some criteria failed. Read the per-criterion detail, fix the underlying code, then re-run mist_qa action='acceptance'."}),m>0)}finally{if(o)try{await o.close()}catch{}}}async function lm(t){let e=t.projectPath??process.cwd(),r=Qa(e),n=t.url;if(!n&&t.deploymentId)try{let R=await ct(t.deploymentId);R.url&&(n=R.url)}catch(R){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,R instanceof Error?R.message:String(R))}if(n||(n=r?.deploy?.url),!n)return d("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);n.startsWith("http")||(n=`https://${n}`);let i=r?.projectId,o=[],s=await Ka(`${n}/api/health`);if(s.status!==200)return o.push({name:"Health endpoint",status:"fail",detail:`Returns ${s.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),ur(n,o);o.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Ka(`${n}/api/auth/ok`);if(a.status!==200)return o.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${a.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),ur(n,o);o.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",m="QaTemp1!",p="single",u="user",g=[];async function j(R,z,W,te){let pe=await im(`${n}/api/admin/seed`,{token:te,email:z,password:m,role:W});if(pe.status!==200||!pe.json)return console.error(`[qa] Seed (${R}) returned ${pe.status}`),null;let L=pe.json.sessionToken;if(!L)return null;let H=pe.json.seeded===!0;return{role:R,email:z,sessionToken:L,password:H?m:void 0}}if(i){let R=await qn(i);if(R){if(p=R.authMode??"single",u=R.defaultRole??"user",console.error(`[qa] auth_mode=${p}, default_role=${u}`),p!=="none"){let W=await j("actor",l,p==="multi"?"admin":u,R.seedToken);if(W&&g.push(W),p==="multi"){let te=await j("user",c,u,R.seedToken);te?g.push(te):o.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${u}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),p="none"}if(p!=="none"&&g.length===0)return o.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy injects ADMIN_SEED_TOKEN and stores it on the backend; the scaffold's /api/admin/seed route accepts { token, email, password, role } and creates synthetic QA users with the requested role."}),ur(n,o);let I,S,y;try{let{getIsolatedContext:R}=await Promise.resolve().then(()=>(Nt(),rn)),z=await R();I=z.context,y=z.page}catch(R){let z=R instanceof Error?R.message:String(R);return d(JSON.stringify({status:"cannot_verify",url:n,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:z,httpChecks:o.map(({screenshot:W,...te})=>te),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${n}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${n}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_qa again for full verification."].join(`
5337
+ `)}),!1)}try{let R=await wt(y,"Landing page",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await y.waitForLoadState("networkidle").catch(()=>{});let L=await y.evaluate(()=>{let E=document.body;if(!E)return"";let Z=document.createTreeWalker(E,NodeFilter.SHOW_TEXT),J="",x;for(;x=Z.nextNode();){let C=x.parentElement;if(C){let V=window.getComputedStyle(C);V.display!=="none"&&V.visibility!=="hidden"&&parseFloat(V.opacity)>0&&(J+=x.textContent?.trim()+" ")}}return J.trim()});if(L.length<50)return{pass:!1,detail:`Landing page appears blank (${L.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let H=y.url();return H.includes("/login")||H.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${L.length} chars)`}});o.push(R),p==="none"&&o.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let z=g[0],W=(L,H)=>g.length>1&&L?`${H} (${L.role})`:H,te=!1;if(z?.password){let L=await wt(y,W(z,"Login"),async()=>{await y.goto(`${n}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let H=y.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),E=y.locator('input[type="password"], input[name="password"]');try{await H.first().waitFor({state:"visible",timeout:1e4})}catch{return{pass:!1,detail:"Login page has no visible email input field",fix:"Check app/(auth)/login/page.tsx renders a login form with email and password inputs."}}await H.first().fill(z.email),await E.first().fill(z.password),await y.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await y.waitForURL(J=>!J.pathname.includes("/login"),{timeout:1e4})}catch{let J=await y.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:J?`Login failed: ${J}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified QA accounts."}}return te=!0,{pass:!0,detail:`Logged in, redirected to ${y.url()}`}});o.push(L)}else z&&o.push({name:W(z,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!te&&z){let L=new URL(n).hostname,H=n.startsWith("https");await I.addCookies([{name:H?"__Secure-better-auth.session_token":"better-auth.session_token",value:z.sessionToken,domain:L,path:"/",httpOnly:!0,secure:H,sameSite:"Lax"}]),console.error(`[qa] Injected ${z.role} cookie for primary walk`)}if(z){let L=await wt(y,W(z,"Dashboard"),async()=>{y.url().includes("/dashboard")||(await y.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}),new URL(y.url()).pathname==="/"&&(await y.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{})));let Z=await y.content();return Z.length<1e3?{pass:!1,detail:`Dashboard page is very small (${Z.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await y.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled null/undefined or missing database tables."}:{pass:!0,detail:`Loads (${Z.length} bytes)`}});o.push(L);let H=await y.evaluate(()=>{let Z=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(x=>{let C=x.getAttribute("href");C&&C.startsWith("/")&&!C.startsWith("/api")&&!C.includes("[")&&C!=="/dashboard"&&C!=="/"&&!C.includes("/login")&&!C.includes("/sign")&&Z.push(C)}),[...new Set(Z)]});if(H.length>0){let Z=0,J=[];for(let x of H.slice(0,8)){let C=await wt(y,W(z,`Page: ${x}`),async()=>{await y.goto(`${n}${x}`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let V=await y.title(),F=await y.content();return V.toLowerCase().includes("500")||V.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 server error",fix:"Server component crashed. Common causes: 1) Database tables missing. 2) Wrong ORM dialect (pgTable vs sqliteTable). 3) Unhandled null/undefined in server component."}:V.toLowerCase().includes("404")||V.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${x} not found. Create the page or remove the nav link.`}:await y.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:F.length<500?{pass:!1,detail:`Page is very small (${F.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});C.status==="fail"&&(Z++,J.push(x)),o.push(C)}}let E=await wt(y,"Design quality",async()=>{let Z=y.url().includes("/dashboard")?y.url():`${n}/dashboard`;y.url().includes("/dashboard")||(await y.goto(Z,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}));let J=await y.evaluate(()=>{let x=[],C=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),V=new Set;C.forEach(X=>{V.add(window.getComputedStyle(X).fontSize)}),C.length>=3&&V.size<2&&x.push("TYPOGRAPHY: All headings appear the same size. Create clear hierarchy with 3+ distinct sizes using a modular scale (1.25-1.5x ratio).");let F=Array.from(C).map(X=>parseInt(X.tagName.charAt(1),10));for(let X=1;X<F.length;X++)if(F[X]-F[X-1]>1){x.push(`TYPOGRAPHY: Heading level skipped (h${F[X-1]} -> h${F[X]}). Use sequential heading levels for accessibility.`);break}let ae=document.querySelectorAll("*"),le=!1,P=!1;ae.forEach(X=>{let ge=window.getComputedStyle(X);ge.backgroundColor==="rgb(0, 0, 0)"&&X.clientHeight>100&&X.clientWidth>200&&(le=!0);let Re=ge.backgroundColor,ot=ge.color;if(Re&&!Re.includes("0, 0, 0")&&!Re.includes("255, 255, 255")&&Re!=="rgba(0, 0, 0, 0)"&&Re!=="transparent"&&ot.match(/rgb\((\d+), (\d+), (\d+)\)/)){let kt=ot.match(/rgb\((\d+), (\d+), (\d+)\)/);if(kt){let[it,$e,h]=[parseInt(kt[1]),parseInt(kt[2]),parseInt(kt[3])],f=Math.abs(it-$e)<10&&Math.abs($e-h)<10&&it>80&&it<180,k=Re.match(/rgb\((\d+), (\d+), (\d+)\)/);if(f&&k){let[T,N,B]=[parseInt(k[1]),parseInt(k[2]),parseInt(k[3])];!(Math.abs(T-N)<15&&Math.abs(N-B)<15)&&X.textContent&&X.textContent.trim().length>0&&(P=!0)}}}}),le&&x.push("COLOR: Pure black (#000) background detected on a large element. Use a tinted dark color instead (e.g. oklch(15% 0.01 hue) or a deep navy/charcoal)."),P&&x.push("COLOR: Gray text on a colored background detected. Gray looks washed out on color. Use a darker shade of the background color or white instead.");let ke=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),U=!1;ke.forEach(X=>{X.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(U=!0)}),U&&x.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let oe=document.querySelectorAll("p, li, span, div"),Ce=0,we=0;oe.forEach(X=>{X.textContent&&X.textContent.trim().length>20&&X.clientHeight>0&&(we++,window.getComputedStyle(X).textAlign==="center"&&Ce++)}),we>5&&Ce/we>.7&&x.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let Se=new Set;ae.forEach(X=>{let ge=window.getComputedStyle(X);ge.gap&&ge.gap!=="normal"&&ge.gap!=="0px"&&Se.add(ge.gap)}),Se.size===1&&ae.length>20&&x.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let Me=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(X=>{X.querySelectorAll("tbody tr").length===0&&(X.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||x.push("UX: Empty table with no empty state. Add a helpful message explaining what will appear here and a CTA to create the first item."))});let Ve=document.querySelectorAll("style"),Ke=!1;Ve.forEach(X=>{let ge=X.textContent||"";(ge.includes("bounce")||ge.includes("elastic")||ge.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Ke=!0)}),Ke&&x.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let st=document.querySelectorAll("button, a, input, select, [role='button']"),Ae=0;return st.forEach(X=>{let ge=X.getBoundingClientRect();ge.width>0&&ge.height>0&&(ge.width<32||ge.height<32)&&Ae++}),Ae>3&&x.push(`ACCESSIBILITY: ${Ae} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),x});return J.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${J.length} design quality issue(s) found:
5338
+ ${J.map((x,C)=>`${C+1}. ${x}`).join(`
5339
+ `)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});o.push(E)}if(o.find(L=>L.name==="Landing page"&&L.status==="pass")){let L=await wt(y,"Landing design quality",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let H=await y.evaluate(()=>{let E=[];document.querySelectorAll("*").forEach(C=>{let V=window.getComputedStyle(C);(V.getPropertyValue("-webkit-background-clip")||V.getPropertyValue("background-clip"))==="text"&&C.textContent&&C.textContent.trim().length>0&&E.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let J=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(J){let C=(J.textContent||"").toLowerCase(),V=["transform your","unlock the power","revolutionize your","take your .* to the next level","the future of","welcome to","get started today","join thousands","powerful analytics","seamless integration","lightning fast"];for(let F of V)if(C.match(new RegExp(F))){E.push(`COPY: Generic hero text detected ('${F}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(C=>{let F=window.getComputedStyle(C).gridTemplateColumns;if(F){let ae=F.split(" ").filter(P=>P!=="").length,le=C.children;if(ae===3&&le.length===3){let P=Array.from(le).map(oe=>oe.offsetHeight),ke=P.every(oe=>Math.abs(oe-P[0])<5),U=Array.from(le).every(oe=>{let Ce=oe.querySelectorAll("svg"),we=oe.querySelectorAll("h2, h3, h4"),Se=oe.querySelectorAll("p");return Ce.length>=1&&we.length>=1&&Se.length>=1});ke&&U&&E.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),E});return H.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${H.length} landing design issue(s):
5340
+ ${H.map((E,Z)=>`${Z+1}. ${E}`).join(`
5341
+ `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});o.push(L)}let pe=g[1];if(pe){let{getIsolatedContext:L}=await Promise.resolve().then(()=>(Nt(),rn)),H=await L();S=H.context;let E=H.page,Z=new URL(n).hostname,J=n.startsWith("https");await S.addCookies([{name:J?"__Secure-better-auth.session_token":"better-auth.session_token",value:pe.sessionToken,domain:Z,path:"/",httpOnly:!0,secure:J,sameSite:"Lax"}]),console.error(`[qa] Injected ${pe.role} cookie for secondary walk`);let x=await wt(E,W(pe,"Dashboard"),async()=>{await E.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await E.waitForLoadState("networkidle").catch(()=>{}),new URL(E.url()).pathname==="/"&&(await E.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await E.waitForLoadState("networkidle").catch(()=>{}));let V=await E.content();return V.length<1e3?{pass:!1,detail:`Dashboard is very small (${V.length} bytes) for the default-role user`,fix:"The default-role user dashboard crashed or rendered empty. Check that role-gated server components handle non-admin roles without throwing."}:await E.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary for the default-role user",fix:"A server component crashed under the non-admin role. Likely a role check that throws instead of redirecting."}:{pass:!0,detail:`Loads (${V.length} bytes)`}});o.push(x);let C=await E.evaluate(()=>{let V=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(F=>{let ae=F.getAttribute("href");ae&&ae.startsWith("/")&&!ae.startsWith("/api")&&!ae.includes("[")&&ae!=="/dashboard"&&ae!=="/"&&!ae.includes("/login")&&!ae.includes("/sign")&&V.push(ae)}),[...new Set(V)]});for(let V of C.slice(0,8)){let F=await wt(E,W(pe,`Page: ${V}`),async()=>{await E.goto(`${n}${V}`,{waitUntil:"domcontentloaded",timeout:15e3}),await E.waitForLoadState("networkidle").catch(()=>{});let ae=await E.title(),le=await E.content();return ae.toLowerCase().includes("500")||ae.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 for the default-role user",fix:"Server component crashed under the non-admin role. Check role gates use redirect() not throw."}:ae.toLowerCase().includes("404")||ae.toLowerCase().includes("not found")?{pass:!0,detail:"404 (likely admin-only \u2014 acceptable)"}:await E.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Error boundary on page for default-role user",fix:"Role-gated content crashed. Use a graceful fallback."}:le.length<500?{pass:!1,detail:`Page very small (${le.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});o.push(F)}}}finally{I&&await I.close().catch(()=>{}),S&&await S.close().catch(()=>{})}if(t.deploymentId){let R=o.filter(te=>te.status==="fail"),z=o.filter(te=>te.status==="pass"),W=Date.now();await Nr(t.deploymentId,{checks:o.map(({screenshot:te,...pe})=>pe),overall:R.length===0?"pass":"fail",passed:z.length,failed:R.length,duration_ms:Date.now()-W}).catch(()=>{})}return ur(n,o)}function ur(t,e){let r=e.filter(o=>o.status==="fail"),n=e.filter(o=>o.status==="pass"),i=[];if(r.length===0)i.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${e.length} checks OK. The app is working correctly.`,url:t,checks:e.map(({screenshot:o,...s})=>s)})});else{let o=r.map((s,a)=>`${a+1}. **${s.name}**: ${s.detail}
5342
5342
  Fix: ${s.fix}`).join(`
5343
5343
 
5344
5344
  `);i.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${r.length} issue(s) on the live app. Fix them and redeploy.`,url:t,passed:n.length,failed:r.length,checks:e.map(({screenshot:s,...a})=>a),fixInstructions:`The deployed app at ${t} has ${r.length} issue(s):
5345
5345
 
5346
5346
  ${o}
5347
5347
 
5348
- Fix these issues in the source code, then call mist_deploy with action='deploy'${t.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let o of e)o.screenshot&&i.push({type:"image",data:o.screenshot,mimeType:"image/png"});return{content:i}}var sm,Ja,Qa=P(()=>{"use strict";be();_e();Ga();sm=Yt.object({projectPath:Yt.string().optional().describe("Absolute path to the Mistflow project. Defaults to the current working directory. Used to read mistflow.json for the deploy URL + projectId."),url:Yt.string().optional().describe("Override the deploy URL to QA. Useful for previews or when mistflow.json doesn't yet have the URL recorded. Defaults to mistflow.json's deploy.url."),deploymentId:Yt.string().optional().describe("Deployment ID to associate QA results with. When set, results are uploaded to the backend and surfaced on the dashboard deployment card."),sessionId:Yt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),action:Yt.enum(["full","acceptance"]).default("full").describe("'full' (default) runs the standard post-deploy QA suite: HTTP pre-flight, landing render, login, sidebar pages, design audits. 'acceptance' runs only the per-criterion Playwright probes from .mistflow/acceptance/<criterion-id>.spec.ts against the deploy URL and uploads pass/fail results to the backend. Requires sessionId.")}),Ja={name:"mist_qa",description:"Post-deploy QA: drives Playwright in-process against the live deploy URL. Checks health + auth endpoints, logs in with a seeded admin account, walks the dashboard and sidebar pages, and runs design-quality audits (typography, color, layout, slop patterns). Returns pass/fail + screenshots inline. Call ONCE after mist_deploy completes. Do NOT surface the deploy URL to the user until mist_qa returns status: 'pass'.",inputSchema:sm,handler:async t=>{let e=t;if(e.action==="acceptance"){let n=await im(e);return n.isError,n}let r=await am(e);return r.isError,r}}});import{existsSync as ur,readdirSync as lm,statSync as Xa,unlinkSync as Za}from"fs";import{join as At}from"path";import{execFile as cm}from"child_process";function dm(t,e){let r=0;for(let n of e){let i=At(t,n);if(ur(i))try{let o=Xa(i);if(o.isFile())r++;else if(o.isDirectory()){let s=[i];for(;s.length;){let a=s.pop(),l=lm(a,{withFileTypes:!0});for(let c of l){let u=At(a,c.name);c.isDirectory()?s.push(u):r++}}}}catch{}}return r}function el(t,e,r){return new Promise(n=>{cm("tar",t,{cwd:e,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(i,o,s)=>{n({success:!i,stderr:s?.toString()??""})})})}async function tl(t){let e=At(t,".open-next-build.tar.gz"),r=[".open-next"];ur(At(t,"db"))&&r.push("db"),ur(At(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),ur(At(t,"package.json"))&&r.push("package.json");let n=dm(t,r),i=await el(["-czf",e,"-C",t,...r],t,12e4);if(!i.success){try{Za(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(i.stderr?`
5349
- ${i.stderr.slice(-500)}`:""))}let o=0;try{o=Xa(e).size}catch{}return{path:e,sizeBytes:o,fileCount:n}}async function nl(t){let e=At(t,".mistflow-source.tar.gz");return(await el(["-czf",e,"-C",t,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],t,12e4)).success?e:null}function Cs(t){if(t)try{Za(t)}catch{}}function rl(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function sl(t){switch(t){case"pending":return"Provisioning...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";case"live":return"Live!";case"failed":return"Failed";default:return`Status: ${t}`}}var ol=P(()=>{"use strict"});import{z as tt}from"zod";import{resolve as pm,join as mr}from"path";import{existsSync as hr}from"fs";function il(t){return hr(mr(t,".open-next"))}function mm(t){return it(t)?.deploy?.strategy==="staging"?"preview":null}async function hm(t,e){if(!(hr(mr(t,"open-next.config.ts"))||hr(mr(t,"open-next.config.js"))))return{kind:"failed",result:p(`No .open-next/ build output at ${t}, and no open-next.config.* either. This project is not configured for the Cloudflare adapter \u2014 mist_deploy ships the .open-next/ artifact, not raw source. If this is a Mistflow project, re-run mist_init to restore the OpenNext config.`,!0)};if(!hr(mr(t,"node_modules")))return{kind:"failed",result:p(`node_modules is missing at ${t}. Call mist_install { projectPath } first, then mist_deploy.`,!0)};if(!Bt())return{kind:"failed",result:p(It(),!0)};let n=await mt({type:"build",cmd:"npx",args:["-y","@opennextjs/cloudflare","build"],cwd:t}),i=e?qe(e.server,e.progressToken,()=>`Auto-building before deploy \u2014 OpenNext adapter (${n.id})`):{stop:()=>{}},o;try{o=await Kt(n.id,{timeoutMs:45e3})}finally{i.stop()}if(!o)return{kind:"failed",result:p(`Auto-build job ${n.id} disappeared. Run mist_build { projectPath } manually, then mist_deploy.`,!0)};if(o.status==="running"||o.status==="starting")return{kind:"running",result:p(JSON.stringify({status:"building",buildJobId:n.id,phase:"auto-build",nextAction:`Build is still running after the 45s inline window. Call mist_build { jobId: '${n.id}' } to keep waiting (long-polls server-side), then call mist_deploy { action: 'deploy', projectPath } again. Do NOT ask the user \u2014 the build is in flight, just keep going.`}))};if(o.status==="complete"&&il(t))return{kind:"ok"};let s=Ct(n.id),a=(o.logTail??"").split(`
5348
+ Fix these issues in the source code, then call mist_deploy with action='deploy'${t.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let o of e)o.screenshot&&i.push({type:"image",data:o.screenshot,mimeType:"image/png"});return{content:i}}var om,Ya,Xa=_(()=>{"use strict";be();_e();Va();om=Qt.object({projectPath:Qt.string().optional().describe("Absolute path to the Mistflow project. Defaults to the current working directory. Used to read mistflow.json for the deploy URL + projectId."),url:Qt.string().optional().describe("Override the deploy URL to QA. Useful for previews or when mistflow.json doesn't yet have the URL recorded. Defaults to mistflow.json's deploy.url."),deploymentId:Qt.string().optional().describe("Deployment ID to associate QA results with. When set, results are uploaded to the backend and surfaced on the dashboard deployment card."),sessionId:Qt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),action:Qt.enum(["full","acceptance"]).default("full").describe("'full' (default) runs the standard post-deploy QA suite: HTTP pre-flight, landing render, login, sidebar pages, design audits. 'acceptance' runs only the per-criterion Playwright probes from .mistflow/acceptance/<criterion-id>.spec.ts against the deploy URL and uploads pass/fail results to the backend. Requires sessionId.")}),Ya={name:"mist_qa",description:"Post-deploy QA: drives Playwright in-process against the live deploy URL. Checks health + auth endpoints, logs in with a seeded admin account, walks the dashboard and sidebar pages, and runs design-quality audits (typography, color, layout, slop patterns). Returns pass/fail + screenshots inline. Call ONCE after mist_deploy completes. Do NOT surface the deploy URL to the user until mist_qa returns status: 'pass'.",inputSchema:om,handler:async t=>{let e=t;if(e.action==="acceptance"){let n=await am(e);return n.isError,n}let r=await lm(e);return r.isError,r}}});import{existsSync as mr,readdirSync as cm,statSync as Za,unlinkSync as el}from"fs";import{join as Et}from"path";import{execFile as dm}from"child_process";function pm(t,e){let r=0;for(let n of e){let i=Et(t,n);if(mr(i))try{let o=Za(i);if(o.isFile())r++;else if(o.isDirectory()){let s=[i];for(;s.length;){let a=s.pop(),l=cm(a,{withFileTypes:!0});for(let c of l){let m=Et(a,c.name);c.isDirectory()?s.push(m):r++}}}}catch{}}return r}function tl(t,e,r){return new Promise(n=>{dm("tar",t,{cwd:e,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(i,o,s)=>{n({success:!i,stderr:s?.toString()??""})})})}async function nl(t){let e=Et(t,".open-next-build.tar.gz"),r=[".open-next"];mr(Et(t,"db"))&&r.push("db"),mr(Et(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),mr(Et(t,"package.json"))&&r.push("package.json");let n=pm(t,r),i=await tl(["-czf",e,"-C",t,...r],t,12e4);if(!i.success){try{el(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(i.stderr?`
5349
+ ${i.stderr.slice(-500)}`:""))}let o=0;try{o=Za(e).size}catch{}return{path:e,sizeBytes:o,fileCount:n}}async function rl(t){let e=Et(t,".mistflow-source.tar.gz");return(await tl(["-czf",e,"-C",t,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],t,12e4)).success?e:null}function As(t){if(t)try{el(t)}catch{}}function sl(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function ol(t){switch(t){case"pending":return"Provisioning...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";case"live":return"Live!";case"failed":return"Failed";default:return`Status: ${t}`}}var il=_(()=>{"use strict"});import{z as nt}from"zod";import{resolve as um,join as hr}from"path";import{existsSync as gr}from"fs";function al(t){return gr(hr(t,".open-next"))}function hm(t){return lt(t)?.deploy?.strategy==="staging"?"preview":null}async function gm(t,e){if(!(gr(hr(t,"open-next.config.ts"))||gr(hr(t,"open-next.config.js"))))return{kind:"failed",result:d(`No .open-next/ build output at ${t}, and no open-next.config.* either. This project is not configured for the Cloudflare adapter \u2014 mist_deploy ships the .open-next/ artifact, not raw source. If this is a Mistflow project, re-run mist_init to restore the OpenNext config.`,!0)};if(!gr(hr(t,"node_modules")))return{kind:"failed",result:d(`node_modules is missing at ${t}. Call mist_install { projectPath } first, then mist_deploy.`,!0)};if(!zt())return{kind:"failed",result:d(At(),!0)};let n=await gt({type:"build",cmd:"npx",args:["-y","@opennextjs/cloudflare","build"],cwd:t}),i=e?ze(e.server,e.progressToken,()=>`Auto-building before deploy \u2014 OpenNext adapter (${n.id})`):{stop:()=>{}},o;try{o=await Jt(n.id,{timeoutMs:45e3})}finally{i.stop()}if(!o)return{kind:"failed",result:d(`Auto-build job ${n.id} disappeared. Run mist_build { projectPath } manually, then mist_deploy.`,!0)};if(o.status==="running"||o.status==="starting")return{kind:"running",result:d(JSON.stringify({status:"building",buildJobId:n.id,phase:"auto-build",nextAction:`Build is still running after the 45s inline window. Call mist_build { jobId: '${n.id}' } to keep waiting (long-polls server-side), then call mist_deploy { action: 'deploy', projectPath } again. Do NOT ask the user \u2014 the build is in flight, just keep going.`}))};if(o.status==="complete"&&al(t))return{kind:"ok"};let s=Rt(n.id),a=(o.logTail??"").split(`
5350
5350
  `).slice(-30).join(`
5351
- `);return{kind:"failed",result:p(JSON.stringify({status:"build_failed",buildJobId:n.id,exitCode:o.exitCode,logTail:a,logPaths:s,nextAction:`Auto-build before deploy failed (exit ${o.exitCode??"?"}). Read the logTail or run mist_debug { projectPath, jobId: '${n.id}' } to extract structured errors. Fix the code, then call mist_deploy { action: 'deploy', projectPath } again.`}),!0)}}async function gm(t){let e=pm(t.projectPath);if(!Se())return Ee("deploy");let r=it(e),n=r?.projectId;if(!n){if(!r?.name)return p(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);try{n=(await St(r.name,{dbProvider:r.dbProvider,requestedSubdomain:r.requestedSubdomain})).id,Tr(e,{projectId:n}),console.error(`[deploy] auto-registered project ${n.slice(0,8)} (${r.name})`+(r.requestedSubdomain?` at ${r.requestedSubdomain}.mistflow.app`:""))}catch(l){let c=l instanceof G||l instanceof Error?l.message:String(l);return p(`Auto-register before deploy failed: ${c}. mistflow.json has no projectId \u2014 mist_init couldn't register the project earlier (likely offline or backend timeout). Try again in a moment, or check Mistflow status.`,!0)}}if(!il(e)){let l=await hm(e,t.ctx);if(l.kind==="running"||l.kind==="failed")return l.result}let i=t.environment??mm(e)??"production",o=t.adminEmail??Ys()?.email,s=null,a=null;try{s=await tl(e),a=await nl(e);let l=await Cr(n,s.path,i,o,void 0,a??void 0,void 0);return p(JSON.stringify({status:"running",jobId:l.deployment_id,deploymentId:l.deployment_id,environment:l.environment??i,buildSize:rl(s.sizeBytes),buildFileCount:s.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${l.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side, so there's no need to sleep between calls. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(l){let c=l instanceof G||l instanceof Error?l.message:String(l);return p(`Deploy upload failed: ${c}`,!0)}finally{Cs(s?.path),Cs(a)}}async function fm(t,e){let r=e.ctx?qe(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let n=await at(t,{waitSeconds:e.waitSeconds}),i=sl(n.status),o=n.id??t;return n.status==="live"?(e.projectPath&&n.url&&(Tr(e.projectPath,{deploy:{url:n.url,deploymentId:o,completedAt:n.completedAt}}),zt(e.projectPath)),p(JSON.stringify({status:"complete",jobId:o,deploymentId:o,url:n.url,completedAt:n.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${n.url??""}', deploymentId: '${o}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`}))):n.status==="failed"?p(JSON.stringify({status:"failed",jobId:o,deploymentId:o,error:n.error,phase:i,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):p(JSON.stringify({status:"running",jobId:o,deploymentId:o,phase:i,phaseCode:n.status,nextAction:`Still ${n.status} after the ${e.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${o}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(n){let i=n instanceof G||n instanceof Error?n.message:String(n);return p(`Could not fetch deploy status: ${i}`,!0)}finally{r.stop()}}async function ym(t,e){if(!Se())return Ee("promote a preview deployment");let n=it(t)?.projectId;if(!n)return p(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let i=e;if(!i)try{let s=(await Ot(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!s)return p("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);i=s.id}catch(o){let s=o instanceof G?o.message:String(o);return p(`Could not list deployments: ${s}`,!0)}try{let o=await Lr(n,i);return p(JSON.stringify({status:"running",jobId:o.deployment_id,deploymentId:o.deployment_id,promotedFrom:i,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${o.deployment_id}' } immediately \u2014 long-polls for up to 20s. Promotion re-uses the preview artifact and typically completes in ~10s, so one poll usually finishes the job.`}))}catch(o){let s=o instanceof G||o instanceof Error?o.message:String(o);return p(`Promote failed: ${s}`,!0)}}async function bm(t){if(!Se())return Ee("roll back a deployment");try{let e=await Ur(t);return p(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let r=e instanceof G||e instanceof Error?e.message:String(e);return p(`Rollback failed: ${r}`,!0)}}var um,al,ll=P(()=>{"use strict";be();_e();kt();kt();nr();ol();qt();Ts();wn();Zn();um=tt.object({action:tt.enum(["deploy","promote","rollback","status"]).default("deploy").describe("'deploy' (default) tars + uploads + starts a deployment. 'promote' promotes a staging preview to production. 'rollback' rolls back to a specific deployment. 'status' polls an in-flight deployment by id."),projectPath:tt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:tt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:tt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:tt.string().optional().describe("Optional override for the owner email. Defaults to the email of whoever ran mist_setup (read from ~/.mistflow/credentials.json). Multi-role apps auto-promote this email to admin on first signup; single-role apps just attach it to the project for the dashboard's Owner Access card. Pass explicitly only when the deploying user is not the intended owner."),waitSeconds:tt.number().min(0).max(20).optional().describe("On action='status' calls: long-poll the backend for up to N seconds (0-20) before returning, so a typical deploy fits in 1-2 round-trips instead of 6-12. Default 20. Ignored for non-status actions."),envVarsRequired:tt.array(lr).optional().describe("Last chance to declare env vars introduced since the last implement call. Merged into mistflow.json env.required before the build is tarred, so the backend's deploy-time check picks them up. Skip keys covered by integration presets (Stripe, Resend, etc.). Only used for action='deploy'."),sessionId:tt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")});al={name:"mist_deploy",description:"Deploy a Mistflow project. action='deploy' (default) tars + uploads + starts backend orchestration; action='status' polls an in-flight deployment; action='promote' ships a staging preview to prod; action='rollback' reverts to a previous deployment. Fire-and-poll: deploy/promote/rollback return a jobId immediately; poll with { action: 'status', deploymentId }. Do NOT show the deploy URL to the user until mist_qa passes \u2014 qaRequired=true is returned on completion.",inputSchema:um,handler:async(t,e)=>{let r=t;switch(r.action??"deploy"){case"deploy":{if(!r.projectPath)return p("projectPath is required for action='deploy'.",!0);if(r.envVarsRequired&&r.envVarsRequired.length>0)try{let i=cr(r.projectPath,r.envVarsRequired);i.added.length>0&&console.error(`[deploy] declared env.required: ${i.added.join(", ")}`)}catch(i){console.error("[deploy] env var merge skipped:",i instanceof Error?i.message:String(i))}return gm({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail,ctx:e})}case"status":return r.deploymentId?fm(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e,projectPath:r.projectPath,sessionId:r.sessionId}):p("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?ym(r.projectPath,r.deploymentId):p("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?bm(r.deploymentId):p("deploymentId is required for action='rollback'.",!0)}}}});import{z as Qt}from"zod";import{hostname as wm}from"os";function cl(){return wm()}function As(t){let e=[`Session: ${t.id}`,`Status: ${t.status}`,`Deploy strategy: ${t.deploy_strategy}`];return t.paused_after_plan&&e.push("Paused: yes (awaiting PLAN.md review \u2014 call mist_session({resume}) when done)"),t.description&&e.push(`Description: ${t.description}`),t.cancelled_at&&e.push(`Cancelled at: ${t.cancelled_at}`),t.completed_at&&e.push(`Completed at: ${t.completed_at}`),e.join(`
5352
- `)}async function vm(t){let e=dl.safeParse(t);if(!e.success){let s=e.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return p(`Invalid input: ${s}`,!0)}let r=e.data;if((r.action==="status"||r.action==="cancel"||r.action==="resume")&&!r.sessionId)return p(`Invalid input: action="${r.action}" requires sessionId.`,!0);if(r.action==="resume"&&!r.projectPath)return p('Invalid input: action="resume" requires projectPath.',!0);if(r.action==="status"){let s=r.sessionId,[a,l,c]=await Promise.all([qn(s),Dt(s).catch(()=>null),sn(s).catch(()=>null)]),u=[As(a),"",l?`Next instruction: ${l.instruction}${l.reason?` (${l.reason})`:""}`:"Next instruction: (unavailable)"];if(c&&c.criteria.length>0){u.push("",`Acceptance criteria (${c.criteria.length}):`);for(let h of c.criteria)u.push(` - [${h.priority}] ${h.id}: ${h.description}`)}return p(u.join(`
5353
- `))}if(r.action==="cancel"){let s=r.sessionId,a=await Vr(s,r.reason);return p(`Session cancelled.
5354
- ${As(a)}
5351
+ `);return{kind:"failed",result:d(JSON.stringify({status:"build_failed",buildJobId:n.id,exitCode:o.exitCode,logTail:a,logPaths:s,nextAction:`Auto-build before deploy failed (exit ${o.exitCode??"?"}). Read the logTail or run mist_debug { projectPath, jobId: '${n.id}' } to extract structured errors. Fix the code, then call mist_deploy { action: 'deploy', projectPath } again.`}),!0)}}async function fm(t){let e=um(t.projectPath);if(!xe())return Oe("deploy");let r=lt(e),n=r?.projectId;if(!n){if(!r?.name)return d(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);try{n=(await _t(r.name,{dbProvider:r.dbProvider,requestedSubdomain:r.requestedSubdomain})).id,_r(e,{projectId:n}),console.error(`[deploy] auto-registered project ${n.slice(0,8)} (${r.name})`+(r.requestedSubdomain?` at ${r.requestedSubdomain}.mistflow.app`:""))}catch(l){let c=l instanceof K||l instanceof Error?l.message:String(l);return d(`Auto-register before deploy failed: ${c}. mistflow.json has no projectId \u2014 mist_init couldn't register the project earlier (likely offline or backend timeout). Try again in a moment, or check Mistflow status.`,!0)}}if(!al(e)){let l=await gm(e,t.ctx);if(l.kind==="running"||l.kind==="failed")return l.result}let i=t.environment??hm(e)??"production",o=t.adminEmail??Qs()?.email,s=null,a=null;try{s=await nl(e),a=await rl(e);let l=await Ar(n,s.path,i,o,void 0,a??void 0,void 0);return d(JSON.stringify({status:"running",jobId:l.deployment_id,deploymentId:l.deployment_id,environment:l.environment??i,buildSize:sl(s.sizeBytes),buildFileCount:s.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${l.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side, so there's no need to sleep between calls. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(l){let c=l instanceof K||l instanceof Error?l.message:String(l);return d(`Deploy upload failed: ${c}`,!0)}finally{As(s?.path),As(a)}}async function ym(t,e){let r=e.ctx?ze(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let n=await ct(t,{waitSeconds:e.waitSeconds}),i=ol(n.status),o=n.id??t;return n.status==="live"?(e.projectPath&&n.url&&(_r(e.projectPath,{deploy:{url:n.url,deploymentId:o,completedAt:n.completedAt}}),Ht(e.projectPath)),d(JSON.stringify({status:"complete",jobId:o,deploymentId:o,url:n.url,completedAt:n.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${n.url??""}', deploymentId: '${o}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`}))):n.status==="failed"?d(JSON.stringify({status:"failed",jobId:o,deploymentId:o,error:n.error,phase:i,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):d(JSON.stringify({status:"running",jobId:o,deploymentId:o,phase:i,phaseCode:n.status,nextAction:`Still ${n.status} after the ${e.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${o}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(n){let i=n instanceof K||n instanceof Error?n.message:String(n);return d(`Could not fetch deploy status: ${i}`,!0)}finally{r.stop()}}async function bm(t,e){if(!xe())return Oe("promote a preview deployment");let n=lt(t)?.projectId;if(!n)return d(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let i=e;if(!i)try{let s=(await Dt(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!s)return d("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);i=s.id}catch(o){let s=o instanceof K?o.message:String(o);return d(`Could not list deployments: ${s}`,!0)}try{let o=await Ur(n,i);return d(JSON.stringify({status:"running",jobId:o.deployment_id,deploymentId:o.deployment_id,promotedFrom:i,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${o.deployment_id}' } immediately \u2014 long-polls for up to 20s. Promotion re-uses the preview artifact and typically completes in ~10s, so one poll usually finishes the job.`}))}catch(o){let s=o instanceof K||o instanceof Error?o.message:String(o);return d(`Promote failed: ${s}`,!0)}}async function wm(t){if(!xe())return Oe("roll back a deployment");try{let e=await $r(t);return d(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let r=e instanceof K||e instanceof Error?e.message:String(e);return d(`Rollback failed: ${r}`,!0)}}var mm,ll,cl=_(()=>{"use strict";be();_e();St();St();rr();il();Bt();_s();vn();er();mm=nt.object({action:nt.enum(["deploy","promote","rollback","status"]).default("deploy").describe("'deploy' (default) tars + uploads + starts a deployment. 'promote' promotes a staging preview to production. 'rollback' rolls back to a specific deployment. 'status' polls an in-flight deployment by id."),projectPath:nt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:nt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:nt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:nt.string().optional().describe("Optional override for the owner email. Defaults to the email of whoever ran mist_setup (read from ~/.mistflow/credentials.json). Multi-role apps auto-promote this email to admin on first signup; single-role apps just attach it to the project for the dashboard's Owner Access card. Pass explicitly only when the deploying user is not the intended owner."),waitSeconds:nt.number().min(0).max(20).optional().describe("On action='status' calls: long-poll the backend for up to N seconds (0-20) before returning, so a typical deploy fits in 1-2 round-trips instead of 6-12. Default 20. Ignored for non-status actions."),envVarsRequired:nt.array(cr).optional().describe("Last chance to declare env vars introduced since the last implement call. Merged into mistflow.json env.required before the build is tarred, so the backend's deploy-time check picks them up. Skip keys covered by integration presets (Stripe, Resend, etc.). Only used for action='deploy'."),sessionId:nt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")});ll={name:"mist_deploy",description:"Deploy a Mistflow project. action='deploy' (default) tars + uploads + starts backend orchestration; action='status' polls an in-flight deployment; action='promote' ships a staging preview to prod; action='rollback' reverts to a previous deployment. Fire-and-poll: deploy/promote/rollback return a jobId immediately; poll with { action: 'status', deploymentId }. Do NOT show the deploy URL to the user until mist_qa passes \u2014 qaRequired=true is returned on completion.",inputSchema:mm,handler:async(t,e)=>{let r=t;switch(r.action??"deploy"){case"deploy":{if(!r.projectPath)return d("projectPath is required for action='deploy'.",!0);if(r.envVarsRequired&&r.envVarsRequired.length>0)try{let i=dr(r.projectPath,r.envVarsRequired);i.added.length>0&&console.error(`[deploy] declared env.required: ${i.added.join(", ")}`)}catch(i){console.error("[deploy] env var merge skipped:",i instanceof Error?i.message:String(i))}return fm({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail,ctx:e})}case"status":return r.deploymentId?ym(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e,projectPath:r.projectPath,sessionId:r.sessionId}):d("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?bm(r.projectPath,r.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?wm(r.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}}});import{z as Xt}from"zod";import{hostname as vm}from"os";function dl(){return vm()}function Rs(t){let e=[`Session: ${t.id}`,`Status: ${t.status}`,`Deploy strategy: ${t.deploy_strategy}`];return t.paused_after_plan&&e.push("Paused: yes (awaiting PLAN.md review \u2014 call mist_session({resume}) when done)"),t.description&&e.push(`Description: ${t.description}`),t.cancelled_at&&e.push(`Cancelled at: ${t.cancelled_at}`),t.completed_at&&e.push(`Completed at: ${t.completed_at}`),e.join(`
5352
+ `)}async function km(t){let e=pl.safeParse(t);if(!e.success){let s=e.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return d(`Invalid input: ${s}`,!0)}let r=e.data;if((r.action==="status"||r.action==="cancel"||r.action==="resume")&&!r.sessionId)return d(`Invalid input: action="${r.action}" requires sessionId.`,!0);if(r.action==="resume"&&!r.projectPath)return d('Invalid input: action="resume" requires projectPath.',!0);if(r.action==="status"){let s=r.sessionId,[a,l,c]=await Promise.all([Bn(s),Mt(s).catch(()=>null),on(s).catch(()=>null)]),m=[Rs(a),"",l?`Next instruction: ${l.instruction}${l.reason?` (${l.reason})`:""}`:"Next instruction: (unavailable)"];if(c&&c.criteria.length>0){m.push("",`Acceptance criteria (${c.criteria.length}):`);for(let p of c.criteria)m.push(` - [${p.priority}] ${p.id}: ${p.description}`)}return d(m.join(`
5353
+ `))}if(r.action==="cancel"){let s=r.sessionId,a=await Kr(s,r.reason);return d(`Session cancelled.
5354
+ ${Rs(a)}
5355
5355
 
5356
- Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(r.action==="resume"){let s=r.sessionId,a=r.projectPath,l=cl(),c=await on(s,{machine_id:l,local_path:a}),u=await qn(s),h=await Dt(s).catch(()=>null);return p(`Resumed session on this machine.
5356
+ Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(r.action==="resume"){let s=r.sessionId,a=r.projectPath,l=dl(),c=await an(s,{machine_id:l,local_path:a}),m=await Bn(s),p=await Mt(s).catch(()=>null);return d(`Resumed session on this machine.
5357
5357
  Machine: ${l}
5358
5358
  Local path: ${c.local_path}
5359
5359
  Last seen: ${c.last_seen_at}
5360
5360
 
5361
- `+As(u)+(h?`
5361
+ `+Rs(m)+(p?`
5362
5362
 
5363
- Next instruction: ${h.instruction}${h.reason?` (${h.reason})`:""}`:""))}let n=cl(),i=await an(n,{includeIdle:r.includeIdle===!0});if(i.length===0){let s=r.includeIdle?"this machine has no sessions bound at all":"no active sessions touched in the last 24h on this machine";return p(`${s} (${n}).
5364
- `+(r.includeIdle?"Run mist_plan to start a new one.":'Run mist_plan to start a new one, mist_session action="resume" with a sessionId, or mist_session action="list" includeIdle=true to see older sessions.'))}let o=[`Sessions bound on this machine (${n}):`,"",...i.map(s=>` - ${s.id} status=${s.status}${s.paused_after_plan?" (paused)":""} ${s.description?`"${s.description.slice(0,60)}"`:"(no description)"}`)];return p(o.join(`
5365
- `))}var dl,pl,ul=P(()=>{"use strict";be();_e();dl=Qt.object({action:Qt.enum(["status","cancel","resume","list"]).describe("status = read current state + acceptance criteria; cancel = terminal CANCELLED transition; resume = bind this machine + path to a session; list = sessions this machine has bound (no sessionId needed)."),sessionId:Qt.string().uuid().optional().describe("Required for status / cancel / resume. Omit for list."),reason:Qt.string().max(500).optional().describe("Optional cancellation reason (used with action=cancel)."),projectPath:Qt.string().min(1).optional().describe("Absolute path to the project directory on this machine. Required for action=resume."),includeIdle:Qt.boolean().optional().describe("For action=list. Default false: only active sessions touched in the last 24h are returned. Set true to see every session ever bound on this machine, including cancelled / completed / stale ones.")});pl={name:"mist_session",description:"Read or correct a Mistflow session. Actions: status (current state + criteria), cancel (terminal), resume (bind this machine to a session for multi-machine work), list (sessions this machine has worked on). All state changes go through the backend so the host AI never directly mutates session state.",inputSchema:dl,handler:vm}});var Im={};import{Server as km}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as xm}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Sm,ListToolsRequestSchema as Tm}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as _m}from"zod-to-json-schema";async function Pm(){let t=process.argv.indexOf("--api-url");t!==-1&&process.argv[t+1]&&(process.env.MISTFLOW_API_URL=process.argv[t+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let e=new xm;await gr.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var gr,ml,hl=P(()=>{"use strict";Ke();be();lo();So();_o();Ao();No();ss();Bo();ai();bi();Ea();La();$a();za();Qa();ll();ul();_e();gr=new km({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Ls()}),ml=[ao,xo,To,Co,Eo,ii,yi,$o,Ra,qo,Ma,Ua,Ba,Ja,al,pl];gr.setRequestHandler(Tm,async()=>({tools:ml.map(t=>({name:t.name,description:t.description,inputSchema:_m(t.inputSchema)}))}));gr.setRequestHandler(Sm,async t=>{let e=ml.find(r=>r.name===t.params.name);if(!e)return p(`Unknown tool: ${t.params.name}`,!0);try{let r=e.inputSchema.safeParse(t.params.arguments);if(!r.success){let s=r.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return p(`Invalid input: ${s}`,!0)}let n=typeof r.data=="object"&&r.data!==null&&"sessionId"in r.data&&typeof r.data.sessionId=="string"?r.data.sessionId:void 0;if(n&&e.name!=="mist_session")try{let s=await Kr(n,e.name);if(!s.allowed)return p(`Tool ${e.name} not allowed for this session.
5363
+ Next instruction: ${p.instruction}${p.reason?` (${p.reason})`:""}`:""))}let n=dl(),i=await ln(n,{includeIdle:r.includeIdle===!0});if(i.length===0){let s=r.includeIdle?"this machine has no sessions bound at all":"no active sessions touched in the last 24h on this machine";return d(`${s} (${n}).
5364
+ `+(r.includeIdle?"Run mist_plan to start a new one.":'Run mist_plan to start a new one, mist_session action="resume" with a sessionId, or mist_session action="list" includeIdle=true to see older sessions.'))}let o=[`Sessions bound on this machine (${n}):`,"",...i.map(s=>` - ${s.id} status=${s.status}${s.paused_after_plan?" (paused)":""} ${s.description?`"${s.description.slice(0,60)}"`:"(no description)"}`)];return d(o.join(`
5365
+ `))}var pl,ul,ml=_(()=>{"use strict";be();_e();pl=Xt.object({action:Xt.enum(["status","cancel","resume","list"]).describe("status = read current state + acceptance criteria; cancel = terminal CANCELLED transition; resume = bind this machine + path to a session; list = sessions this machine has bound (no sessionId needed)."),sessionId:Xt.string().uuid().optional().describe("Required for status / cancel / resume. Omit for list."),reason:Xt.string().max(500).optional().describe("Optional cancellation reason (used with action=cancel)."),projectPath:Xt.string().min(1).optional().describe("Absolute path to the project directory on this machine. Required for action=resume."),includeIdle:Xt.boolean().optional().describe("For action=list. Default false: only active sessions touched in the last 24h are returned. Set true to see every session ever bound on this machine, including cancelled / completed / stale ones.")});ul={name:"mist_session",description:"Read or correct a Mistflow session. Actions: status (current state + criteria), cancel (terminal), resume (bind this machine to a session for multi-machine work), list (sessions this machine has worked on). All state changes go through the backend so the host AI never directly mutates session state.",inputSchema:pl,handler:km}});var Cm={};import{Server as xm}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Sm}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Tm,ListToolsRequestSchema as _m}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as Pm}from"zod-to-json-schema";async function Im(){let t=process.argv.indexOf("--api-url");t!==-1&&process.argv[t+1]&&(process.env.MISTFLOW_API_URL=process.argv[t+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let e=new Sm;await fr.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var fr,hl,gl=_(()=>{"use strict";Je();be();co();To();Po();Ro();Oo();os();zo();li();wi();Na();Ua();Fa();Ha();Xa();cl();ml();_e();fr=new xm({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Us()}),hl=[lo,So,_o,Ao,No,ai,bi,Fo,Ea,Bo,La,$a,za,Ya,ll,ul];fr.setRequestHandler(_m,async()=>({tools:hl.map(t=>({name:t.name,description:t.description,inputSchema:Pm(t.inputSchema)}))}));fr.setRequestHandler(Tm,async t=>{let e=hl.find(r=>r.name===t.params.name);if(!e)return d(`Unknown tool: ${t.params.name}`,!0);try{let r=e.inputSchema.safeParse(t.params.arguments);if(!r.success){let s=r.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return d(`Invalid input: ${s}`,!0)}let n=typeof r.data=="object"&&r.data!==null&&"sessionId"in r.data&&typeof r.data.sessionId=="string"?r.data.sessionId:void 0;if(n&&e.name!=="mist_session")try{let s=await Jr(n,e.name);if(!s.allowed)return d(`Tool ${e.name} not allowed for this session.
5366
5366
  Reason: ${s.reason}
5367
5367
  Status: ${s.status}
5368
5368
 
5369
- Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(s){if(s instanceof G&&s.code==="not_found")console.error(`Guard check 404 for tool ${e.name}: ${s.message}`);else throw s}let i=t.params._meta?.progressToken,o={server:gr,progressToken:i};try{return await e.handler(r.data,o)}finally{o.cleanup?.()}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),p(n,!0)}});Pm().catch(t=>{console.error("Fatal error:",t),process.exit(1)})});import{readFileSync as Cm}from"fs";import{dirname as Am,join as Rm}from"path";import{fileURLToPath as Em}from"url";var bt=process.argv[2];if(bt==="--version"||bt==="-v"){try{let t=Am(Em(import.meta.url)),e=Rm(t,"..","package.json"),r=JSON.parse(Cm(e,"utf-8"));console.log(r.version)}catch{console.log("unknown")}process.exit(0)}(bt==="--help"||bt==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
5369
+ Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(s){if(s instanceof K&&s.code==="not_found")console.error(`Guard check 404 for tool ${e.name}: ${s.message}`);else throw s}let i=t.params._meta?.progressToken,o={server:fr,progressToken:i};try{return await e.handler(r.data,o)}finally{o.cleanup?.()}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),d(n,!0)}});Im().catch(t=>{console.error("Fatal error:",t),process.exit(1)})});import{readFileSync as Am}from"fs";import{dirname as Rm,join as Em}from"path";import{fileURLToPath as Nm}from"url";var vt=process.argv[2];if(vt==="--version"||vt==="-v"){try{let t=Rm(Nm(import.meta.url)),e=Em(t,"..","package.json"),r=JSON.parse(Am(e,"utf-8"));console.log(r.version)}catch{console.log("unknown")}process.exit(0)}(vt==="--help"||vt==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
5370
5370
 
5371
5371
  Usage:
5372
5372
  npx @mistflow-ai/mcp Start the MCP server on stdio (default; invoked by editors)
@@ -5374,8 +5374,8 @@ Usage:
5374
5374
 
5375
5375
  To install the server into your editor config, use the installer:
5376
5376
  npx -y mistflow-ai install
5377
- `),process.exit(0));(bt==="install"||bt==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${bt}' is no longer supported.
5377
+ `),process.exit(0));(vt==="install"||vt==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${vt}' is no longer supported.
5378
5378
  Use the installer package instead:
5379
5379
 
5380
- npx -y mistflow-ai ${bt}
5381
- `),process.exit(1));await Promise.resolve().then(()=>(hl(),Im));
5380
+ npx -y mistflow-ai ${vt}
5381
+ `),process.exit(1));await Promise.resolve().then(()=>(gl(),Cm));