@mistflow-ai/mcp 1.0.16 → 1.0.19

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 +178 -182
  2. package/dist/index.js +175 -179
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,27 +1,27 @@
1
1
  #!/usr/bin/env node
2
- var Yi=Object.defineProperty;var T=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ht=(e,t)=>{for(var r in t)Yi(e,r,{get:t[r],enumerable:!0})};function Hr(){let e=[];return e.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."),e.push(""),e.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.'),e.push(""),e.push(na),e.push(""),e.push(Qi),e.push(""),e.push(Xi),e.push(""),e.push(Zi),e.push(""),e.push(ea),e.push(""),e.push(sa),e.push(""),e.push(oa),e.push(""),e.push("New app workflow:"),e.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."),e.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).'),e.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 }."),e.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),e.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),e.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."),e.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."),e.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)."),e.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'."),e.push(""),e.push(ta),e.push(""),e.push(ra),e.push(""),e.push("Updating an existing Mistflow app:"),e.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),e.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),e.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."),e.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."),e.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),e.push(""),e.push("Tool summary:"),e.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."),e.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),e.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),e.push("- mist_help: returns the full tool reference. Call once per session."),e.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),e.push("- mist_install / mist_build / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),e.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."),e.join(`
3
- `)}var Qi,Xi,Zi,ea,ta,oa,ra,na,sa,Ur,$r,Fr,qr,Br,zr,Be=T(()=>{"use strict";Qi="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.",Xi='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"`.',Zi="When submitting discovery answers back to `mist_plan` (conversationId + answers), prefer an array payload: `answers: [{question, decisionKey, answer}, ...]`. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",ea="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.",ta='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.',oa="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.",ra="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.",na='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.',sa="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.",Ur="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).",$r="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. 'landing-designs' / 'integrations' browse curated catalogs (pass presetId / 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.",Fr="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.",qr="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.",Br="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).",zr="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 Eo,readFileSync as Kr,writeFileSync as ia,mkdirSync as aa}from"fs";import{join as Ro,dirname as No}from"path";import{homedir as la}from"os";import{fileURLToPath as ca}from"url";function Pe(){if(Wt)return Wt;try{let e=ca(import.meta.url),t=No(e);for(let r=0;r<6;r++){let o=Ro(t,"package.json");if(Eo(o)){let i=JSON.parse(Kr(o,"utf-8"));if(i.name==="@mistflow-ai/mcp"&&typeof i.version=="string")return Wt=i.version,i.version}let s=No(t);if(s===t)break;t=s}}catch{}return Wt="0.0.0","0.0.0"}function Gt(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim());return t?[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)]:null}function Wr(e,t){let r=Gt(e),o=Gt(t);if(!r||!o)return 0;for(let s=0;s<3;s++){if(r[s]<o[s])return-1;if(r[s]>o[s])return 1}return 0}function Jr(e,t,r){if(r&&Wr(e,r)<0)return"unsupported";if(!t||Wr(e,t)>=0)return"none";let s=Gt(e),i=Gt(t);return!s||!i?"none":s[0]<i[0]?"major":s[1]<i[1]?"minor":"patch"}function Tt(e){let t=e.get("x-mistflow-mcp-latest")??"",r=e.get("x-mistflow-mcp-min-supported")??"",o=e.get("x-mistflow-mcp-changelog-url")??"";!t&&!r||(Te={latest:t,minSupported:r,changelogUrl:o})}function Yr(){let e=process.env.MISTFLOW_STATE_DIR||Ro(la(),".mistflow");return Ro(e,"upgrade-state.json")}function da(){try{let e=Yr();return Eo(e)?JSON.parse(Kr(e,"utf-8")):{}}catch{return{}}}function pa(e){try{let t=Yr(),r=No(t);Eo(r)||aa(r,{recursive:!0}),ia(t,JSON.stringify(e,null,2)+`
4
- `,{mode:384})}catch{}}function ua(e){return e==="patch"?7*864e5:e==="minor"?1*864e5:0}function Qr(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!Te)return null;let e=Pe();if(e==="0.0.0")return null;let t=Jr(e,Te.latest,Te.minSupported);if(t==="none")return null;if(t==="unsupported")return Vr(t,e,Te);if(Gr)return null;let r=da(),o=Date.now(),s=ua(t);return r.dismissedForVersion===Te.latest&&t!=="major"||r.lastLatestSeen===Te.latest&&r.lastShownMs&&o-r.lastShownMs<s?null:(Gr=!0,pa({...r,lastShownMs:o,lastLatestSeen:Te.latest}),Vr(t,e,Te))}function Vr(e,t,r){let o="npx -y mistflow-ai install",s=r.changelogUrl?`
5
- What's new: ${r.changelogUrl}`:"";return e==="unsupported"?`
2
+ var Ni=Object.defineProperty;var A=(t,e)=>()=>(t&&(e=t(t=0)),e);var Et=(t,e)=>{for(var r in e)Ni(t,r,{get:e[r],enumerable:!0})};function _r(){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(Fi),t.push(""),t.push(Di),t.push(""),t.push(ji),t.push(""),t.push(Oi),t.push(""),t.push(Mi),t.push(""),t.push(qi),t.push(""),t.push(Li),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(Ui),t.push(""),t.push($i),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 Di,ji,Oi,Mi,Ui,Li,$i,Fi,qi,Sr,Tr,Pr,Cr,Ir,Ar,Ee=A(()=>{"use strict";Di="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.",ji='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"`.',Oi="When submitting discovery answers back to `mist_plan` (conversationId + answers), prefer an array payload: `answers: [{question, decisionKey, answer}, ...]`. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",Mi="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.",Ui='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.',Li="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.",$i="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.",Fi='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.',qi="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.",Sr="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).",Tr="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.",Pr="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.",Cr="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.",Ir="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).",Ar="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 ko,readFileSync as Dr,writeFileSync as Bi,mkdirSync as zi}from"fs";import{join as wo,dirname as vo}from"path";import{homedir as Hi}from"os";import{fileURLToPath as Wi}from"url";function ye(){if(Nt)return Nt;try{let t=Wi(import.meta.url),e=vo(t);for(let r=0;r<6;r++){let o=wo(e,"package.json");if(ko(o)){let i=JSON.parse(Dr(o,"utf-8"));if(i.name==="@mistflow-ai/mcp"&&typeof i.version=="string")return Nt=i.version,i.version}let s=vo(e);if(s===e)break;e=s}}catch{}return Nt="0.0.0","0.0.0"}function Dt(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 Rr(t,e){let r=Dt(t),o=Dt(e);if(!r||!o)return 0;for(let s=0;s<3;s++){if(r[s]<o[s])return-1;if(r[s]>o[s])return 1}return 0}function jr(t,e,r){if(r&&Rr(t,r)<0)return"unsupported";if(!e||Rr(t,e)>=0)return"none";let s=Dt(t),i=Dt(e);return!s||!i?"none":s[0]<i[0]?"major":s[1]<i[1]?"minor":"patch"}function ct(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",o=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||(fe={latest:e,minSupported:r,changelogUrl:o})}function Or(){let t=process.env.MISTFLOW_STATE_DIR||wo(Hi(),".mistflow");return wo(t,"upgrade-state.json")}function Gi(){try{let t=Or();return ko(t)?JSON.parse(Dr(t,"utf-8")):{}}catch{return{}}}function Vi(t){try{let e=Or(),r=vo(e);ko(r)||zi(r,{recursive:!0}),Bi(e,JSON.stringify(t,null,2)+`
4
+ `,{mode:384})}catch{}}function Ki(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Mr(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!fe)return null;let t=ye();if(t==="0.0.0")return null;let e=jr(t,fe.latest,fe.minSupported);if(e==="none")return null;if(e==="unsupported")return Nr(e,t,fe);if(Er)return null;let r=Gi(),o=Date.now(),s=Ki(e);return r.dismissedForVersion===fe.latest&&e!=="major"||r.lastLatestSeen===fe.latest&&r.lastShownMs&&o-r.lastShownMs<s?null:(Er=!0,Vi({...r,lastShownMs:o,lastLatestSeen:fe.latest}),Nr(e,t,fe))}function Nr(t,e,r){let o="npx -y mistflow-ai install",s=r.changelogUrl?`
5
+ What's new: ${r.changelogUrl}`:"";return t==="unsupported"?`
6
6
 
7
7
  ---
8
- Mistflow ${t} is no longer supported.
8
+ Mistflow ${e} is no longer supported.
9
9
  You must upgrade to ${r.latest} or newer to continue:
10
10
 
11
11
  ${o}
12
12
 
13
13
  After upgrading, restart your AI editor.${s}
14
- ---`:e==="major"?`
14
+ ---`:t==="major"?`
15
15
 
16
16
  ---
17
- Mistflow ${r.latest} is available (you have ${t}).
17
+ Mistflow ${r.latest} is available (you have ${e}).
18
18
  This is a major update. Run \`${o}\` and restart your editor.${s}
19
- ---`:e==="minor"?`
19
+ ---`:t==="minor"?`
20
20
 
21
- --- Mistflow update available: ${t} -> ${r.latest} ---
21
+ --- Mistflow update available: ${e} -> ${r.latest} ---
22
22
  Run \`${o}\` to upgrade, then restart your editor.${s}`:`
23
23
 
24
- (Mistflow ${r.latest} is out, you have ${t}. Run \`${o}\` when convenient.)`}function Do(){let e=Pe(),t=Te??{latest:"",minSupported:"",changelogUrl:""},r=Jr(e,t.latest,t.minSupported);return{current:e,latest:t.latest,minSupported:t.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:t.changelogUrl,backendSignalReceived:Te!==null}}var Wt,Te,Gr,Pt=T(()=>{"use strict";Wt=null;Te=null;Gr=!1});var Mo={};Ht(Mo,{closeBrowser:()=>Oo,getIsolatedContext:()=>ha,getPage:()=>jo,getSnapshot:()=>Ct,takeScreenshot:()=>It});async function Xr(){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 ma(){let e=await Xr();return(!Ce||!Ce.isConnected())&&(Ce=await e.chromium.launch({headless:!0})),ze&&(await ze.close().catch(()=>{}),ze=null),ze=await Ce.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Ue=await ze.newPage(),Ue}async function jo(){return Ue&&!Ue.isClosed()?Ue:(Vt||(Vt=ma().finally(()=>{Vt=null})),Vt)}async function Oo(){Ue&&!Ue.isClosed()&&await Ue.close().catch(()=>{}),ze&&await ze.close().catch(()=>{}),Ce?.isConnected()&&await Ce.close().catch(()=>{}),Ue=null,ze=null,Ce=null}async function ha(){let e=await Xr();(!Ce||!Ce.isConnected())&&(Ce=await e.chromium.launch({headless:!0}));let t=await Ce.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await t.newPage();return{context:t,page:r}}async function Ct(e){return await e.locator("body").ariaSnapshot()}async function It(e,t=!1){return await e.screenshot({fullPage:t,type:"png"})}var Ce,ze,Ue,Vt,Kt=T(()=>{"use strict";Ce=null,ze=null,Ue=null,Vt=null;process.once("SIGTERM",()=>{Oo().finally(()=>process.exit(0))});process.once("SIGINT",()=>{Oo().finally(()=>process.exit(0))})});function d(e,t=!1){let r=e;try{let o=Qr();o&&(r=e+o)}catch{}return{content:[{type:"text",text:r}],isError:t}}function $e(e){return d(`This is not a Mistflow project (no mistflow.json found at ${e}).
24
+ (Mistflow ${r.latest} is out, you have ${e}. Run \`${o}\` when convenient.)`}function xo(){let t=ye(),e=fe??{latest:"",minSupported:"",changelogUrl:""},r=jr(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 Nt,fe,Er,dt=A(()=>{"use strict";Nt=null;fe=null;Er=!1});var Ot={};Et(Ot,{closeBrowser:()=>To,getIsolatedContext:()=>Yi,getPage:()=>So,getSnapshot:()=>pt,takeScreenshot:()=>ut});async function Ur(){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 Ji(){let t=await Ur();return(!be||!be.isConnected())&&(be=await t.chromium.launch({headless:!0})),Ne&&(await Ne.close().catch(()=>{}),Ne=null),Ne=await be.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),_e=await Ne.newPage(),_e}async function So(){return _e&&!_e.isClosed()?_e:(jt||(jt=Ji().finally(()=>{jt=null})),jt)}async function To(){_e&&!_e.isClosed()&&await _e.close().catch(()=>{}),Ne&&await Ne.close().catch(()=>{}),be?.isConnected()&&await be.close().catch(()=>{}),_e=null,Ne=null,be=null}async function Yi(){let t=await Ur();(!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 pt(t){return await t.locator("body").ariaSnapshot()}async function ut(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var be,Ne,_e,jt,mt=A(()=>{"use strict";be=null,Ne=null,_e=null,jt=null;process.once("SIGTERM",()=>{To().finally(()=>process.exit(0))});process.once("SIGINT",()=>{To().finally(()=>process.exit(0))})});function d(t,e=!1){let r=t;try{let o=Mr();o&&(r=t+o)}catch{}return{content:[{type:"text",text:r}],isError:e}}function Re(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,23 +30,19 @@ 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 Zr(e,t){try{let{getPage:r,takeScreenshot:o}=await Promise.resolve().then(()=>(Kt(),Mo)),s=await r();await s.goto(e,{waitUntil:"domcontentloaded",timeout:15e3}),await s.waitForLoadState("networkidle").catch(()=>{});let i=await o(s,!1);return{content:[{type:"text",text:t},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}catch{return d(t)}}var ee=T(()=>{"use strict";Pt()});import{readFileSync as en,existsSync as Lo,writeFileSync as ga,mkdirSync as fa,renameSync as ya,unlinkSync as ba}from"fs";import{join as Uo,dirname as wa}from"path";import{homedir as va}from"os";import{randomBytes as xa}from"crypto";function tn(){return Uo(va(),".mistflow","credentials.json")}function Jt(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function on(){let e=tn();if(!Lo(e))return null;try{let t=JSON.parse(en(e,"utf-8"));return typeof t.apiKey=="string"?{[ka]:t}:t}catch{return null}}function at(){let e=process.env.MISTFLOW_API_KEY;if(e)return{ok:!0,creds:{apiKey:e,orgId:"",orgSlug:"env"}};let t=on();if(!t)return{ok:!1,reason:"missing"};let r=Jt(),o=t[r];return o&&typeof o.apiKey=="string"&&o.apiKey&&typeof o.orgId=="string"?{ok:!0,creds:o}:{ok:!1,reason:"missing"}}function $o(e){let t=tn(),r=wa(t);Lo(r)||fa(r,{recursive:!0});let o=on()??{},s=Jt();o[s]=e;let i=Uo(r,`.credentials.tmp.${xa(8).toString("hex")}`);try{ga(i,JSON.stringify(o,null,2)+`
34
- `,{mode:384}),ya(i,t)}catch(n){try{ba(i)}catch{}throw n}}function ae(){return at().ok}function He(e){let t=Uo(e,"mistflow.json");if(!Lo(t))return null;try{return JSON.parse(en(t,"utf-8"))}catch{return null}}var ka,lt=T(()=>{"use strict";ka="https://api.mistflow.ai"});var cn={};Ht(cn,{MistflowApiError:()=>$,addDomain:()=>zo,checkAuth:()=>Ca,checkAuthDetailed:()=>an,checkSubdomain:()=>Qt,createDeployment:()=>Aa,createProject:()=>_t,deleteEnvVar:()=>Jo,discoverDecisions:()=>_a,downloadSource:()=>Ea,downloadSourceWithToken:()=>ln,fetchDesignDirections:()=>Bo,fetchModule:()=>or,fetchPlanConversation:()=>Xt,fetchScaffold:()=>er,fetchStepContext:()=>tr,forkTemplate:()=>nr,generatePlan:()=>Zt,getAuthHeaders:()=>Ze,getBaseUrl:()=>le,getDashboardUrl:()=>Sa,getDbCredentials:()=>Ra,getDeployLogs:()=>Yo,getDeploymentStatus:()=>Rt,getProject:()=>Ia,getProjectErrors:()=>Qo,getSeedInfo:()=>Wo,getSiteUrl:()=>ct,getTemplate:()=>rr,hasCredentialsOnDisk:()=>ae,hasLocalCredentials:()=>sn,listDeployments:()=>pt,listDomains:()=>We,listEnvVars:()=>Vo,markLocalSetupDone:()=>Da,modifyPlan:()=>eo,pingBackend:()=>Fo,promotePreview:()=>Xo,redeployProject:()=>Na,removeDomain:()=>Ho,rollbackDeployment:()=>Zo,shareProject:()=>sr,uploadAndDeploy:()=>qo,uploadQAResults:()=>Go,upsertEnvVar:()=>Ko,verifyDomain:()=>to});function le(){return Jt()}function ct(){let e=process.env.MISTFLOW_API_URL;if(e){if(e.includes("mistflow.localhost"))return e.replace("api.mistflow","mistflow");if(e.includes("localhost:9100"))return e.replace(":9100",":9102")}return"https://mistflow.ai"}function Sa(){let e=process.env.MISTFLOW_API_URL;if(e){if(e.includes("mistflow.localhost"))return e.replace("api.mistflow","app.mistflow");if(e.includes("localhost:9100"))return e.replace(":9100",":9101")}return"https://app.mistflow.ai"}function Ze(){let e=at();if(!e.ok)throw new $("auth_missing","No Mistflow credentials found.",401);return Ta(e.creds)}function Ta(e){return{Authorization:`ApiKey ${e.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":Pe()}}function dt(e){try{Tt(e.headers)}catch{}}async function Fo(){try{let e=await fetch(`${le()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});dt(e)}catch{}}async function nn(e,t,r,o){for(let s=0;s<2;s++)try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(i){let n=i instanceof Error&&i.name==="TimeoutError",a=i instanceof TypeError;if(o&&s===0&&(n||a)){console.error(`[api] Retrying ${e} after ${n?"timeout":"network error"}`);continue}throw i}throw new Error("fetchWithRetry: exhausted retries")}async function At(e){let t=null;try{t=await e.json()}catch{t=null}let r=t&&typeof t.code=="string"?t.code:void 0,o=t&&typeof t.message=="string"?t.message:t&&typeof t.detail=="string"?t.detail:e.statusText||"Request failed";if(r)return new $(r,o,e.status,t?.details);let s=e.status;return s===401?new $("auth_invalid",o,s):s===403?new $("permission_denied",o,s):s===404?new $("not_found",o,s):s===409?new $("conflict",o,s):s===422?new $("validation_error",o,s):s===429?new $("rate_limited",o,s):s>=500?new $("server_error",e.statusText||"Internal server error",s):new $("client_error",o,s)}async function q(e,t={}){let r=Ze(),{timeoutMs:o,idempotent:s,...i}=t,n=o??3e4,a=(i.method??"GET").toUpperCase(),l=s??(a==="GET"||a==="HEAD"),c;try{c=await nn(`${le()}${e}`,{...i,headers:{...r,...i.headers}},n,l)}catch(h){throw h instanceof Error&&h.name==="TimeoutError"?new $("network_error","Request timed out. Try again in a moment."):new $("network_error","Cannot reach Mistflow servers. Check your network.")}if(dt(c),!c.ok)throw await At(c);return c.json()}function sn(){return at().ok}async function Ca(){return(await an()).ok}async function an(){if(Yt!==null&&Date.now()<rn)return Yt?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!sn())return{ok:!1,reason:"no_credentials"};try{return await q("/api/org"),Yt=!0,rn=Date.now()+Pa,{ok:!0}}catch(e){if(Yt=null,!(e instanceof $))return{ok:!1,reason:"network_error"};switch(e.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 Ia(e){return q(`/api/projects/${encodeURIComponent(e)}`)}async function Qt(e){return q(`/api/projects/check-subdomain?name=${encodeURIComponent(e)}`)}async function _t(e,t,r="neon",o){return q("/api/projects",{method:"POST",body:JSON.stringify({name:e,template:t,db_provider:r,requested_subdomain:o})})}async function Aa(e,t){return q("/api/deploy",{method:"POST",body:JSON.stringify({project_id:e,build_output_url:t})})}async function qo(e,t,r="production",o,s,i,n){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=at();if(!c.ok)throw new $("auth_missing","No Mistflow credentials found.",401);let h=c.creds,m=a(t),p=new Blob([m],{type:"application/gzip"}),f=new FormData;if(f.append("project_id",e),f.append("build",p,l(t)),r!=="production"&&f.append("environment",r),o&&f.append("admin_email",o),s&&f.append("schema_pushed","true"),i){let{existsSync:y}=await import("fs");if(y(i)){let k=a(i),I=new Blob([k],{type:"application/gzip"});f.append("source",I,"source.tar.gz")}}n&&f.append("git_commit_sha",n);let S;try{S=await fetch(`${le()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":Pe()},body:f,signal:AbortSignal.timeout(3e5)})}catch{throw new $("network_error","Cannot reach Mistflow servers. Check your network.")}if(dt(S),!S.ok)throw await At(S);let b=await S.json();return{...b,id:b.deployment_id}}async function Rt(e,t){let r=t?.waitSeconds??0,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return q(`/api/deploy/${encodeURIComponent(e)}/status${o}`,r>0?{timeoutMs:s}:void 0)}async function Bo(e){return q(`/api/plan/design-directions/${encodeURIComponent(e)}`,{timeoutMs:15e3})}async function Xt(e,t){let r=t?.waitSeconds??20,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return q(`/api/plan/conversations/${encodeURIComponent(e)}${o}`,{timeoutMs:s})}async function Zt(e,t){let r={description:e,conversation_id:t?.conversationId,answers:t?.answers};t?.autonomous&&(r.autonomous=!0),t?.language&&t.language.toLowerCase()!=="english"&&(r.language=t.language),t?.designConversationId&&(r.design_conversation_id=t.designConversationId),t?.designDirection&&(r.design_direction=t.designDirection);let o=t?.conversationId||t?.answers||t?.designConversationId?18e4:6e4;return q("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:o,idempotent:!1})}async function eo(e,t){return q("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:e,modification:t})})}async function _a(e){return q("/api/plan/discover",{method:"POST",body:JSON.stringify({description:e})})}async function zo(e,t){return q(`/api/projects/${encodeURIComponent(e)}/domains`,{method:"POST",body:JSON.stringify({domain:t})})}async function We(e){return q(`/api/projects/${encodeURIComponent(e)}/domains`)}async function to(e,t){return q(`/api/projects/${encodeURIComponent(e)}/domains/${encodeURIComponent(t)}/verify`)}async function Ho(e,t){return q(`/api/projects/${encodeURIComponent(e)}/domains/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Ra(e){return q(`/api/projects/${encodeURIComponent(e)}/db-credentials`)}async function Wo(e){try{return await q(`/api/projects/${encodeURIComponent(e)}/test-accounts`)}catch(t){return t instanceof $&&(t.statusCode===404||t.code==="not_found")||console.error("[api] Failed to fetch seed info:",t instanceof Error?t.message:t),null}}async function Go(e,t){try{return await q(`/api/deploy/${encodeURIComponent(e)}/qa-results`,{method:"POST",body:JSON.stringify(t)})}catch(r){return console.error("[api] Failed to upload QA results:",r instanceof Error?r.message:r),null}}async function Vo(e){return q(`/api/projects/${encodeURIComponent(e)}/env`)}async function Ko(e,t,r,o){return q(`/api/projects/${encodeURIComponent(e)}/env`,{method:"PUT",body:JSON.stringify({key:t,value:r,category:o?.category??"custom",description:o?.description,setup_url:o?.setupUrl})})}async function Jo(e,t){return q(`/api/projects/${encodeURIComponent(e)}/env/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Yo(e){return q(`/api/deploy/${encodeURIComponent(e)}/logs`)}async function Qo(e,t="7d"){return q(`/api/projects/${encodeURIComponent(e)}/errors?period=${encodeURIComponent(t)}`)}async function pt(e){return q(`/api/projects/${encodeURIComponent(e)}/deployments`)}async function Na(e){return q(`/api/deploy/${encodeURIComponent(e)}/redeploy`,{method:"POST"})}async function Xo(e,t){let r=new URLSearchParams({preview_deployment_id:t});return q(`/api/deploy/${encodeURIComponent(e)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Zo(e){return q(`/api/deploy/${encodeURIComponent(e)}/rollback`,{method:"POST"})}async function Ea(e,t){let r=at();if(!r.ok)throw new $("auth_missing","Not authenticated.",401);let o=r.creds,s=await fetch(`${le()}/api/deploy/${encodeURIComponent(e)}/source`,{headers:{Authorization:`ApiKey ${o.apiKey}`,"X-Mistflow-MCP-Version":Pe()},signal:AbortSignal.timeout(12e4)});if(dt(s),!s.ok)throw await At(s);let{writeFileSync:i}=await import("fs"),n=Buffer.from(await s.arrayBuffer());i(t,n)}async function oo(e,t){let{timeoutMs:r,idempotent:o,...s}=t??{},i=r??3e4,n=(s.method??"GET").toUpperCase(),a=o??(n==="GET"||n==="HEAD"),l;try{l=await nn(`${le()}${e}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":Pe()},...s},i,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new $("network_error","Request timed out. Try again in a moment."):new $("network_error","Cannot reach Mistflow servers. Check your network.")}if(dt(l),!l.ok)throw await At(l);return l.json()}async function er(e="nextjs"){return oo(`/api/scaffold/${encodeURIComponent(e)}`)}async function tr(e,t){return oo(`/api/scaffold/${encodeURIComponent(e)}/context?step_type=${encodeURIComponent(t)}`)}async function or(e,t,r,o){return oo(`/api/scaffold/${encodeURIComponent(e)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:t,fields:r,entity_plural:o})})}async function rr(e){return oo(`/api/templates/${encodeURIComponent(e)}`)}async function nr(e){return q(`/api/templates/${encodeURIComponent(e)}/fork`,{method:"POST"})}async function ln(e,t,r){let o;try{o=await fetch(`${le()}/api/deploy/${encodeURIComponent(e)}/fork-source?fork_token=${encodeURIComponent(t)}`,{headers:{"X-Mistflow-MCP-Version":Pe()},signal:AbortSignal.timeout(12e4)})}catch{throw new $("network_error","Cannot reach Mistflow servers. Check your network.")}if(dt(o),!o.ok)throw o.status===401?new $("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",o.status):await At(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(r,i)}async function Da(e){await q(`/api/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function sr(e,t){return q(`/api/projects/${encodeURIComponent(e)}/share`,{method:"POST",body:JSON.stringify({is_template:t?.isTemplate??!1,template_description:t?.description})})}var $,Yt,rn,Pa,ge=T(()=>{"use strict";lt();Pt();$=class extends Error{constructor(r,o,s,i){super(o);this.code=r;this.statusCode=s;this.details=i;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"}};Yt=null,rn=0,Pa=300*1e3});import{z as ir}from"zod";import{platform as ja}from"os";import{execFile as dn}from"child_process";function Ma(e){return"error"in e}function un(e){return new Promise(t=>setTimeout(t,e))}function La(e){return new Promise(t=>{let r=ja();r==="win32"?dn("cmd.exe",["/c","start","",e],o=>{o&&console.error("Could not open browser:",o.message),t(!o)}):dn(r==="darwin"?"open":"xdg-open",[e],s=>{s&&console.error("Could not open browser:",s.message),t(!s)}),setTimeout(()=>t(!1),5e3)})}async function pn(e,t,r,o){let s=r,i=o.sleep??un;for(let n=0;n<t;n++){await i(s);let a;try{let c=await o.fetch(`${le()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e})});if(!c.ok)continue;a=await c.json()}catch{continue}if(Ma(a))switch(a.error){case"authorization_pending":continue;case"slow_down":s+=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 $o({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 $a(e,t=Ua){let r=e;if(r?.apiKey)try{let n=await t.fetch(`${le()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!n.ok)return d("Invalid API key. Check the key and try again.",!0);let a=await n.json();return $o({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 n=await pn(r.deviceCode,6,5e3,t);return n||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 o;try{let n=await t.fetch(`${le()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);o=await n.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let s=`${o.verification_uri}?code=${o.user_code}`;console.error(`
33
+ If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Lr(t,e){try{let{getPage:r,takeScreenshot:o}=await Promise.resolve().then(()=>(mt(),Ot)),s=await r();await s.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await s.waitForLoadState("networkidle").catch(()=>{});let i=await o(s,!1);return{content:[{type:"text",text:e},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}catch{return d(e)}}var re=A(()=>{"use strict";dt()});import{readFileSync as $r,existsSync as Po,writeFileSync as Qi,mkdirSync as Xi,renameSync as Zi,unlinkSync as ea}from"fs";import{join as Co,dirname as ta}from"path";import{homedir as oa}from"os";import{randomBytes as ra}from"crypto";function Fr(){return Co(oa(),".mistflow","credentials.json")}function Mt(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function qr(){let t=Fr();if(!Po(t))return null;try{let e=JSON.parse($r(t,"utf-8"));return typeof e.apiKey=="string"?{[na]:e}:e}catch{return null}}function Be(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=qr();if(!e)return{ok:!1,reason:"missing"};let r=Mt(),o=e[r];return o&&typeof o.apiKey=="string"&&o.apiKey&&typeof o.orgId=="string"?{ok:!0,creds:o}:{ok:!1,reason:"missing"}}function Io(t){let e=Fr(),r=ta(e);Po(r)||Xi(r,{recursive:!0});let o=qr()??{},s=Mt();o[s]=t;let i=Co(r,`.credentials.tmp.${ra(8).toString("hex")}`);try{Qi(i,JSON.stringify(o,null,2)+`
34
+ `,{mode:384}),Zi(i,e)}catch(n){try{ea(i)}catch{}throw n}}function Br(){let t=Be();return t.ok?t.creds:null}function ie(){return Be().ok}function De(t){let e=Co(t,"mistflow.json");if(!Po(e))return null;try{return JSON.parse($r(e,"utf-8"))}catch{return null}}var na,ze=A(()=>{"use strict";na="https://api.mistflow.ai"});var Kr={};Et(Kr,{MistflowApiError:()=>G,addDomain:()=>Eo,checkAuth:()=>ca,checkAuthDetailed:()=>Gr,checkSubdomain:()=>Lt,createDeployment:()=>pa,createProject:()=>gt,deleteEnvVar:()=>Uo,discoverDecisions:()=>ua,downloadSource:()=>ga,downloadSourceWithToken:()=>Vr,fetchDesignDirections:()=>Ro,fetchModule:()=>Ho,fetchPlanConversation:()=>$t,fetchScaffold:()=>Bo,fetchStepContext:()=>zo,forkTemplate:()=>Go,generatePlan:()=>Ft,getAuthHeaders:()=>He,getBaseUrl:()=>ae,getDashboardUrl:()=>ia,getDbCredentials:()=>ma,getDeployLogs:()=>Lo,getDeploymentStatus:()=>ft,getProject:()=>da,getProjectErrors:()=>$o,getSeedInfo:()=>Do,getSiteUrl:()=>sa,getTemplate:()=>Wo,hasCredentialsOnDisk:()=>ie,hasLocalCredentials:()=>Wr,listDeployments:()=>Xe,listDomains:()=>je,listEnvVars:()=>Oo,markLocalSetupDone:()=>fa,modifyPlan:()=>qt,pingBackend:()=>Ao,promotePreview:()=>Fo,redeployProject:()=>ha,removeDomain:()=>No,rollbackDeployment:()=>qo,shareProject:()=>Vo,uploadAndDeploy:()=>_o,uploadQAResults:()=>jo,upsertEnvVar:()=>Mo,verifyDomain:()=>Bt});function ae(){return Mt()}function sa(){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 ia(){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 He(){let t=Be();if(!t.ok)throw new G("auth_missing","No Mistflow credentials found.",401);return aa(t.creds)}function aa(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":ye()}}function Qe(t){try{ct(t.headers)}catch{}}async function Ao(){try{let t=await fetch(`${ae()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Qe(t)}catch{}}async function Hr(t,e,r,o){for(let s=0;s<2;s++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(i){let n=i instanceof Error&&i.name==="TimeoutError",a=i instanceof TypeError;if(o&&s===0&&(n||a)){console.error(`[api] Retrying ${t} after ${n?"timeout":"network error"}`);continue}throw i}throw new Error("fetchWithRetry: exhausted retries")}async function ht(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,o=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new G(r,o,t.status,e?.details);let s=t.status;return s===401?new G("auth_invalid",o,s):s===403?new G("permission_denied",o,s):s===404?new G("not_found",o,s):s===409?new G("conflict",o,s):s===422?new G("validation_error",o,s):s===429?new G("rate_limited",o,s):s>=500?new G("server_error",t.statusText||"Internal server error",s):new G("client_error",o,s)}async function V(t,e={}){let r=He(),{timeoutMs:o,idempotent:s,...i}=e,n=o??3e4,a=(i.method??"GET").toUpperCase(),l=s??(a==="GET"||a==="HEAD"),c;try{c=await Hr(`${ae()}${t}`,{...i,headers:{...r,...i.headers}},n,l)}catch(m){throw m instanceof Error&&m.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(Qe(c),!c.ok)throw await ht(c);return c.json()}function Wr(){return Be().ok}async function ca(){return(await Gr()).ok}async function Gr(){if(Ut!==null&&Date.now()<zr)return Ut?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Wr())return{ok:!1,reason:"no_credentials"};try{return await V("/api/org"),Ut=!0,zr=Date.now()+la,{ok:!0}}catch(t){if(Ut=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 da(t){return V(`/api/projects/${encodeURIComponent(t)}`)}async function Lt(t){return V(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function gt(t,e,r="neon",o){return V("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e,db_provider:r,requested_subdomain:o})})}async function pa(t,e){return V("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function _o(t,e,r="production",o,s,i,n){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=Be();if(!c.ok)throw new G("auth_missing","No Mistflow credentials found.",401);let m=c.creds,p=a(e),u=new Blob([p],{type:"application/gzip"}),w=new FormData;if(w.append("project_id",t),w.append("build",u,l(e)),r!=="production"&&w.append("environment",r),o&&w.append("admin_email",o),s&&w.append("schema_pushed","true"),i){let{existsSync:S}=await import("fs");if(S(i)){let f=a(i),_=new Blob([f],{type:"application/gzip"});w.append("source",_,"source.tar.gz")}}n&&w.append("git_commit_sha",n);let D;try{D=await fetch(`${ae()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":ye()},body:w,signal:AbortSignal.timeout(3e5)})}catch{throw new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Qe(D),!D.ok)throw await ht(D);let x=await D.json();return{...x,id:x.deployment_id}}async function ft(t,e){let r=e?.waitSeconds??0,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return V(`/api/deploy/${encodeURIComponent(t)}/status${o}`,r>0?{timeoutMs:s}:void 0)}async function Ro(t){return V(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function $t(t,e){let r=e?.waitSeconds??20,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return V(`/api/plan/conversations/${encodeURIComponent(t)}${o}`,{timeoutMs:s})}async function Ft(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&(r.design_conversation_id=e.designConversationId),e?.designDirection&&(r.design_direction=e.designDirection);let o=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return V("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:o,idempotent:!1})}async function qt(t,e){return V("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function ua(t){return V("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Eo(t,e){return V(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function je(t){return V(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Bt(t,e){return V(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function No(t,e){return V(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function ma(t){return V(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Do(t){try{return await V(`/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 jo(t,e){try{return await V(`/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 Oo(t){return V(`/api/projects/${encodeURIComponent(t)}/env`)}async function Mo(t,e,r,o){return V(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:r,category:o?.category??"custom",description:o?.description,setup_url:o?.setupUrl})})}async function Uo(t,e){return V(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Lo(t){return V(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function $o(t,e="7d"){return V(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Xe(t){return V(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function ha(t){return V(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Fo(t,e){let r=new URLSearchParams({preview_deployment_id:e});return V(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function qo(t){return V(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function ga(t,e){let r=Be();if(!r.ok)throw new G("auth_missing","Not authenticated.",401);let o=r.creds,s=await fetch(`${ae()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${o.apiKey}`,"X-Mistflow-MCP-Version":ye()},signal:AbortSignal.timeout(12e4)});if(Qe(s),!s.ok)throw await ht(s);let{writeFileSync:i}=await import("fs"),n=Buffer.from(await s.arrayBuffer());i(e,n)}async function zt(t,e){let{timeoutMs:r,idempotent:o,...s}=e??{},i=r??3e4,n=(s.method??"GET").toUpperCase(),a=o??(n==="GET"||n==="HEAD"),l;try{l=await Hr(`${ae()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":ye()},...s},i,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(Qe(l),!l.ok)throw await ht(l);return l.json()}async function Bo(t="nextjs"){return zt(`/api/scaffold/${encodeURIComponent(t)}`)}async function zo(t,e){return zt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Ho(t,e,r,o){return zt(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:r,entity_plural:o})})}async function Wo(t){return zt(`/api/templates/${encodeURIComponent(t)}`)}async function Go(t){return V(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Vr(t,e,r){let o;try{o=await fetch(`${ae()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":ye()},signal:AbortSignal.timeout(12e4)})}catch{throw new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Qe(o),!o.ok)throw o.status===401?new G("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",o.status):await ht(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(r,i)}async function fa(t){await V(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Vo(t,e){return V(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}var G,Ut,zr,la,de=A(()=>{"use strict";ze();dt();G=class extends Error{constructor(r,o,s,i){super(o);this.code=r;this.statusCode=s;this.details=i;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"}};Ut=null,zr=0,la=300*1e3});import{z as Ko}from"zod";import{platform as ya}from"os";import{execFile as Jr}from"child_process";function wa(t){return"error"in t}function Qr(t){return new Promise(e=>setTimeout(e,t))}function va(t){return new Promise(e=>{let r=ya();r==="win32"?Jr("cmd.exe",["/c","start","",t],o=>{o&&console.error("Could not open browser:",o.message),e(!o)}):Jr(r==="darwin"?"open":"xdg-open",[t],s=>{s&&console.error("Could not open browser:",s.message),e(!s)}),setTimeout(()=>e(!1),5e3)})}async function Yr(t,e,r,o){let s=r,i=o.sleep??Qr;for(let n=0;n<e;n++){await i(s);let a;try{let c=await o.fetch(`${ae()}/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(wa(a))switch(a.error){case"authorization_pending":continue;case"slow_down":s+=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 Io({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 xa(t,e=ka){let r=t;if(r?.apiKey)try{let n=await e.fetch(`${ae()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!n.ok)return d("Invalid API key. Check the key and try again.",!0);let a=await n.json();return Io({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 n=await Yr(r.deviceCode,6,5e3,e);return n||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 o;try{let n=await e.fetch(`${ae()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);o=await n.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let s=`${o.verification_uri}?code=${o.user_code}`;console.error(`
35
35
  Sign in at: ${s}
36
36
  Your code: ${o.user_code}
37
- `);try{await t.openBrowser(s)}catch{}let i=await pn(o.device_code,6,5e3,t);return i||d(JSON.stringify({status:"pending",deviceCode:o.device_code,signInUrl:s,userCode:o.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+o.device_code+"' to check if they approved."}))}var Oa,Ua,mn,hn=T(()=>{"use strict";Be();ee();ge();lt();Oa=ir.object({apiKey:ir.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:ir.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.")});Ua={fetch:globalThis.fetch,openBrowser:La,sleep:un};mn={name:"mist_setup",description:Ur,inputSchema:Oa,handler:e=>$a(e)}});import{existsSync as Fa,readFileSync as qa}from"fs";function gn(e){let t=new Set;if(!Fa(e))return t;let r=qa(e,"utf-8");for(let o of r.split(`
38
- `)){let s=o.trim();if(!s||s.startsWith("#"))continue;let i=s.indexOf("=");if(i>0){let n=s.slice(0,i).trim(),a=s.slice(i+1).trim();a&&a!=='""'&&a!=="''"&&t.add(n)}}return t}var fn=T(()=>{"use strict"});var Dt={};Ht(Dt,{emptyState:()=>Et,fetchRemoteState:()=>Ga,fuzzyMatch:()=>Ka,getLocalStatePath:()=>ar,readLocalState:()=>Wa,syncRemoteState:()=>Va,writeLocalState:()=>Nt});import{existsSync as yn,readFileSync as Ba,writeFileSync as za,mkdirSync as Ha}from"fs";import{join as bn}from"path";function ar(e){return bn(e,".mistflow","state.json")}function Wa(e){let t=ar(e);if(!yn(t))return null;try{return JSON.parse(Ba(t,"utf-8"))}catch{return null}}function Nt(e,t){let r=bn(e,".mistflow");yn(r)||Ha(r,{recursive:!0}),za(ar(e),JSON.stringify(t,null,2)+`
39
- `)}function Et(e,t){return{projectId:e,name:t,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Ga(e){let t;try{t=Ze()}catch{return null}try{let r=await fetch(`${le()}/api/projects/${encodeURIComponent(e)}/state`,{headers:{...t,"Content-Type":"application/json","X-Mistflow-MCP-Version":Pe()}});try{Tt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function Va(e,t){let r;try{r=Ze()}catch{return!1}try{let o=await fetch(`${le()}/api/projects/${encodeURIComponent(e)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":Pe()},body:JSON.stringify(t)});try{Tt(o.headers)}catch{}return o.ok}catch{return!1}}function Ka(e,t){let r=e.toLowerCase(),o=t.toLowerCase();return o.includes(r)||r.includes(o)?!0:r.split(/\s+/).some(i=>i.length>=3&&o.includes(i))}var et=T(()=>{"use strict";ge();Pt()});var lr={};Ht(lr,{ensureBackendRegistered:()=>tl,ensureShadcnComponents:()=>ol});import{existsSync as vn,readFileSync as Ja,writeFileSync as Ya}from"fs";import{join as ro}from"path";import{spawn as Qa}from"child_process";function Xa(e,t,r,o,s){return new Promise(i=>{let n=Qa(e,t,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:o,...s?{env:{...process.env,...s}}:{}}),a="",l="";n.stdout?.on("data",c=>{a+=c.toString()}),n.stderr?.on("data",c=>{l+=c.toString()}),n.on("close",c=>i({success:c===0,stdout:a,stderr:l})),n.on("error",c=>i({success:!1,stdout:a,stderr:l+c.message}))})}function Za(e){let t=ro(e,"mistflow.json");if(!vn(t))return null;try{return JSON.parse(Ja(t,"utf-8"))}catch{return null}}function el(e,t){Ya(ro(e,"mistflow.json"),JSON.stringify(t,null,2))}async function wn(e,t){try{let r=t.features,o=t.steps,s={plan:t};Array.isArray(r)&&r.length>0&&(s.features=r.map(i=>i.name)),Array.isArray(o)&&o.length>0&&(s.provenance=o.map(i=>({feature:i.name??i.title??`Step ${i.number??"?"}`,user_intent:(i.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${le()}/api/projects/${encodeURIComponent(e)}/state`,{method:"PUT",headers:{...Ze(),"Content-Type":"application/json"},body:JSON.stringify(s)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function tl(e,t={}){let r=Za(e);if(r){if(!ae())return r.projectId;if(!r.projectId)try{let s=r.plan?.requestedSubdomain,i=await _t(r.name,void 0,r.dbProvider??"neon",s);return r.projectId=i.id,el(e,r),Nt(e,Et(i.id,r.name)),r.plan&&await wn(i.id,r.plan),console.error(`[self-heal] registered project ${i.id.slice(0,8)} with backend`),i.id}catch(o){console.error("[self-heal] createProject failed:",o instanceof Error?o.message:String(o));return}return t.forceSync&&r.plan&&r.projectId&&await wn(r.projectId,r.plan),r.projectId}}async function ol(e,t){let r=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],o=t&&t.length>0?t:r,s=ro(e,"components","ui"),i=[],n=[];for(let c of o)vn(ro(s,`${c}.tsx`))?i.push(c):n.push(c);if(n.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Xa("npx",["--yes","shadcn@latest","add","-y","-o",...n],e,18e4,a);return l.success?{installed:n,alreadyPresent:i}:{installed:[],alreadyPresent:i,failed:`shadcn add failed for: ${n.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var cr=T(()=>{"use strict";ge();et()});import{z as Ge}from"zod";import{resolve as rl,join as xn}from"path";import{existsSync as nl,readFileSync as kn,writeFileSync as sl}from"fs";var il,Sn,Tn=T(()=>{"use strict";ee();fn();il=Ge.object({action:Ge.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:Ge.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:Ge.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:Ge.object({key:Ge.string(),description:Ge.string().optional(),setupUrl:Ge.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),Sn={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:il,handler:async e=>{let t=e,r=rl(t.projectPath??process.cwd()),o=xn(r,"mistflow.json");if(!nl(o))return $e(r);let s;try{s=JSON.parse(kn(o,"utf-8"))}catch{return d("Failed to parse mistflow.json.",!0)}if(t.action==="get"){if(!s.projectId)try{let{ensureBackendRegistered:y}=await Promise.resolve().then(()=>(cr(),lr));await y(r)&&(s=JSON.parse(kn(o,"utf-8")))}catch{}let a=s.plan,l=a?.steps?.filter(y=>y.status==="completed").length??0,c=a?.steps?.length??0,h=gn(xn(r,".env.local")),m=s.env?.required?Object.entries(s.env.required).map(([y,k])=>({name:y,description:k?.description,configured:h.has(y)})):[];s.projectId&&Promise.resolve().then(()=>(et(),Dt)).then(({fetchRemoteState:y})=>y(s.projectId)).catch(()=>{});let p=[`Project: ${s.name}`];if(a){p.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let y of a.steps){let k=y.status==="completed"?"\u2713":y.status==="in_progress"?"\u2192":" ";p.push(` [${k}] ${y.number}. ${y.name}`)}}let f=m.filter(y=>!y.configured);f.length>0&&p.push(`Missing env vars: ${f.map(y=>y.name).join(", ")}`),s.deploy?.url?p.push(`Deployed: ${s.deploy.url} (${s.deploy.count??0} deploys)`):p.push("Not deployed yet");let S=[],b=a?.steps?.find(y=>y.status!=="completed");return b?S.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${b.number} (${b.name}).`):a&&l===c&&(s.deploy?.url||S.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),f.length>0&&S.push(`Missing env vars in .env.local: ${f.map(y=>y.name).join(", ")}`),d(JSON.stringify({name:s.name,projectId:s.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:c,completedSteps:l,steps:a.steps}:null,envStatus:m,deploy:s.deploy??null,contextMessage:p.join(`
40
- `),nextSteps:S}))}let i=[];if(t.completedStep!==void 0){let a=s.plan;if(a?.steps){let l=a.steps.findIndex(c=>c.number===t.completedStep);if(l===-1)return d(`Step ${t.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",i.push(`Step ${t.completedStep} marked as completed`)}}t.addEnvVar&&(s.env||(s.env={required:{}}),s.env.required||(s.env.required={}),s.env.required[t.addEnvVar.key]={description:t.addEnvVar.description,setupUrl:t.addEnvVar.setupUrl},i.push(`Added required env var: ${t.addEnvVar.key}`)),sl(o,JSON.stringify(s,null,2)+`
41
- `),s.projectId&&Promise.resolve().then(()=>(et(),Dt)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(r);c&&await l(s.projectId,c)}).catch(()=>{});let n=[];if(t.completedStep!==void 0){let l=s.plan?.steps?.find(c=>c.status!=="completed");l?n.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):n.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }) to deploy the app. Do NOT suggest localhost.")}return t.addEnvVar&&(n.push(`Add ${t.addEnvVar.key} to your .env.local file`),t.addEnvVar.setupUrl&&n.push(`Get the value from: ${t.addEnvVar.setupUrl}`)),d(JSON.stringify({updated:!0,changes:i,message:i.length>0?`Project state saved. ${i.join(". ")}.`:"No changes made.",nextSteps:n.length>0?n:void 0}))}}});function no(e){let t=ut.find(o=>o.id===e);if(t)return t;let r=e.toLowerCase().replace(/[^a-z0-9]/g,"");return ut.find(o=>{let s=o.title.toLowerCase().replace(/[^a-z0-9]/g,"");return s===r||s.includes(r)||r.includes(s)})}function Pn(e){return dr[e]}function pr(e){return e?ut.filter(t=>t.category.toLowerCase()===e.toLowerCase()):ut}function Cn(e){let t=e??ut;if(t.length===0)return"Landing page presets have been replaced by the tone-based system. The landing page tone is now auto-selected based on your app's description during planning.";let r={};for(let s of t){r[s.category]||(r[s.category]=[]);let i=dr[s.id],n=i?` \u2014 ${i.description}`:"";r[s.category].push(`${s.id} \u2014 "${s.title}"${n}`)}let o=[];for(let[s,i]of Object.entries(r))o.push(`**${s}**:
42
- ${i.map(n=>` \u2022 ${n}`).join(`
43
- `)}`);return o.join(`
44
-
45
- `)}function al(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function In(e){return(e?pr(e):ut).map(r=>{let o=dr[r.id];return{id:r.id,slug:al(r.title),title:r.title,category:r.category,description:o?.description??"",tags:o?.tags??[],theme:o?.theme??"dark",colors:o?.colors??[],style:o?.style??""}})}function An(e,t){return[]}var dr,ut,ur=T(()=>{"use strict";dr={},ut=[]});function ll(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function ht(e){let t=mt.find(o=>o.id===e);if(t)return t;let r=e.toLowerCase().replace(/[^a-z0-9]/g,"");return mt.find(o=>{let s=o.name.toLowerCase().replace(/[^a-z0-9]/g,"");return s===r||s.includes(r)||r.includes(s)})}function gt(e){return mr[e]}function hr(e){return e?mt.filter(t=>t.category.toLowerCase()===e.toLowerCase()):mt}function _n(e){let t=e??mt,r={};for(let s of t){r[s.category]||(r[s.category]=[]);let i=mr[s.id],n=i?` \u2014 ${i.description}`:"",a=i?.packages.length?` (${i.packages.join(", ")})`:"";r[s.category].push(`${s.id} \u2014 "${s.name}"${n}${a}`)}let o=[];for(let[s,i]of Object.entries(r))o.push(`**${s}**:
37
+ `);try{await e.openBrowser(s)}catch{}let i=await Yr(o.device_code,6,5e3,e);return i||d(JSON.stringify({status:"pending",deviceCode:o.device_code,signInUrl:s,userCode:o.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+o.device_code+"' to check if they approved."}))}var ba,ka,Xr,Zr=A(()=>{"use strict";Ee();re();de();ze();ba=Ko.object({apiKey:Ko.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:Ko.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.")});ka={fetch:globalThis.fetch,openBrowser:va,sleep:Qr};Xr={name:"mist_setup",description:Sr,inputSchema:ba,handler:t=>xa(t)}});import{existsSync as Sa,readFileSync as Ta}from"fs";function en(t){let e=new Set;if(!Sa(t))return e;let r=Ta(t,"utf-8");for(let o of r.split(`
38
+ `)){let s=o.trim();if(!s||s.startsWith("#"))continue;let i=s.indexOf("=");if(i>0){let n=s.slice(0,i).trim(),a=s.slice(i+1).trim();a&&a!=='""'&&a!=="''"&&e.add(n)}}return e}var tn=A(()=>{"use strict"});var wt={};Et(wt,{emptyState:()=>bt,fetchRemoteState:()=>_a,fuzzyMatch:()=>Ea,getLocalStatePath:()=>Jo,readLocalState:()=>Aa,syncRemoteState:()=>Ra,writeLocalState:()=>yt});import{existsSync as on,readFileSync as Pa,writeFileSync as Ca,mkdirSync as Ia}from"fs";import{join as rn}from"path";function Jo(t){return rn(t,".mistflow","state.json")}function Aa(t){let e=Jo(t);if(!on(e))return null;try{return JSON.parse(Pa(e,"utf-8"))}catch{return null}}function yt(t,e){let r=rn(t,".mistflow");on(r)||Ia(r,{recursive:!0}),Ca(Jo(t),JSON.stringify(e,null,2)+`
39
+ `)}function bt(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function _a(t){let e;try{e=He()}catch{return null}try{let r=await fetch(`${ae()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":ye()}});try{ct(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function Ra(t,e){let r;try{r=He()}catch{return!1}try{let o=await fetch(`${ae()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":ye()},body:JSON.stringify(e)});try{ct(o.headers)}catch{}return o.ok}catch{return!1}}function Ea(t,e){let r=t.toLowerCase(),o=e.toLowerCase();return o.includes(r)||r.includes(o)?!0:r.split(/\s+/).some(i=>i.length>=3&&o.includes(i))}var We=A(()=>{"use strict";de();dt()});var Yo={};Et(Yo,{ensureBackendRegistered:()=>La,ensureShadcnComponents:()=>$a});import{existsSync as sn,readFileSync as Na,writeFileSync as Da}from"fs";import{join as Ht}from"path";import{spawn as ja}from"child_process";function Oa(t,e,r,o,s){return new Promise(i=>{let n=ja(t,e,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:o,...s?{env:{...process.env,...s}}:{}}),a="",l="";n.stdout?.on("data",c=>{a+=c.toString()}),n.stderr?.on("data",c=>{l+=c.toString()}),n.on("close",c=>i({success:c===0,stdout:a,stderr:l})),n.on("error",c=>i({success:!1,stdout:a,stderr:l+c.message}))})}function Ma(t){let e=Ht(t,"mistflow.json");if(!sn(e))return null;try{return JSON.parse(Na(e,"utf-8"))}catch{return null}}function Ua(t,e){Da(Ht(t,"mistflow.json"),JSON.stringify(e,null,2))}async function nn(t,e){try{let r=e.features,o=e.steps,s={plan:e};Array.isArray(r)&&r.length>0&&(s.features=r.map(i=>i.name)),Array.isArray(o)&&o.length>0&&(s.provenance=o.map(i=>({feature:i.name??i.title??`Step ${i.number??"?"}`,user_intent:(i.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${ae()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...He(),"Content-Type":"application/json"},body:JSON.stringify(s)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function La(t,e={}){let r=Ma(t);if(r){if(!ie())return r.projectId;if(!r.projectId)try{let s=r.plan?.requestedSubdomain,i=await gt(r.name,void 0,r.dbProvider??"neon",s);return r.projectId=i.id,Ua(t,r),yt(t,bt(i.id,r.name)),r.plan&&await nn(i.id,r.plan),console.error(`[self-heal] registered project ${i.id.slice(0,8)} with backend`),i.id}catch(o){console.error("[self-heal] createProject failed:",o instanceof Error?o.message:String(o));return}return e.forceSync&&r.plan&&r.projectId&&await nn(r.projectId,r.plan),r.projectId}}async function $a(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"],o=e&&e.length>0?e:r,s=Ht(t,"components","ui"),i=[],n=[];for(let c of o)sn(Ht(s,`${c}.tsx`))?i.push(c):n.push(c);if(n.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Oa("npx",["--yes","shadcn@latest","add","-y","-o",...n],t,18e4,a);return l.success?{installed:n,alreadyPresent:i}:{installed:[],alreadyPresent:i,failed:`shadcn add failed for: ${n.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Qo=A(()=>{"use strict";de();We()});import{z as Oe}from"zod";import{resolve as Fa,join as an}from"path";import{existsSync as qa,readFileSync as ln,writeFileSync as Ba}from"fs";var za,cn,dn=A(()=>{"use strict";re();tn();za=Oe.object({action:Oe.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:Oe.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:Oe.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:Oe.object({key:Oe.string(),description:Oe.string().optional(),setupUrl:Oe.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),cn={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:za,handler:async t=>{let e=t,r=Fa(e.projectPath??process.cwd()),o=an(r,"mistflow.json");if(!qa(o))return Re(r);let s;try{s=JSON.parse(ln(o,"utf-8"))}catch{return d("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!s.projectId)try{let{ensureBackendRegistered:S}=await Promise.resolve().then(()=>(Qo(),Yo));await S(r)&&(s=JSON.parse(ln(o,"utf-8")))}catch{}let a=s.plan,l=a?.steps?.filter(S=>S.status==="completed").length??0,c=a?.steps?.length??0,m=en(an(r,".env.local")),p=s.env?.required?Object.entries(s.env.required).map(([S,f])=>({name:S,description:f?.description,configured:m.has(S)})):[];s.projectId&&Promise.resolve().then(()=>(We(),wt)).then(({fetchRemoteState:S})=>S(s.projectId)).catch(()=>{});let u=[`Project: ${s.name}`];if(a){u.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let S of a.steps){let f=S.status==="completed"?"\u2713":S.status==="in_progress"?"\u2192":" ";u.push(` [${f}] ${S.number}. ${S.name}`)}}let w=p.filter(S=>!S.configured);w.length>0&&u.push(`Missing env vars: ${w.map(S=>S.name).join(", ")}`),s.deploy?.url?u.push(`Deployed: ${s.deploy.url} (${s.deploy.count??0} deploys)`):u.push("Not deployed yet");let D=[],x=a?.steps?.find(S=>S.status!=="completed");return x?D.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${x.number} (${x.name}).`):a&&l===c&&(s.deploy?.url||D.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),w.length>0&&D.push(`Missing env vars in .env.local: ${w.map(S=>S.name).join(", ")}`),d(JSON.stringify({name:s.name,projectId:s.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:c,completedSteps:l,steps:a.steps}:null,envStatus:p,deploy:s.deploy??null,contextMessage:u.join(`
40
+ `),nextSteps:D}))}let i=[];if(e.completedStep!==void 0){let a=s.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",i.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(s.env||(s.env={required:{}}),s.env.required||(s.env.required={}),s.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},i.push(`Added required env var: ${e.addEnvVar.key}`)),Ba(o,JSON.stringify(s,null,2)+`
41
+ `),s.projectId&&Promise.resolve().then(()=>(We(),wt)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(r);c&&await l(s.projectId,c)}).catch(()=>{});let n=[];if(e.completedStep!==void 0){let l=s.plan?.steps?.find(c=>c.status!=="completed");l?n.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):n.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&&(n.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&n.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),d(JSON.stringify({updated:!0,changes:i,message:i.length>0?`Project state saved. ${i.join(". ")}.`:"No changes made.",nextSteps:n.length>0?n:void 0}))}}});function Ha(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function et(t){let e=Ze.find(o=>o.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Ze.find(o=>{let s=o.name.toLowerCase().replace(/[^a-z0-9]/g,"");return s===r||s.includes(r)||r.includes(s)})}function tt(t){return Xo[t]}function Zo(t){return t?Ze.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Ze}function pn(t){let e=t??Ze,r={};for(let s of e){r[s.category]||(r[s.category]=[]);let i=Xo[s.id],n=i?` \u2014 ${i.description}`:"",a=i?.packages.length?` (${i.packages.join(", ")})`:"";r[s.category].push(`${s.id} \u2014 "${s.name}"${n}${a}`)}let o=[];for(let[s,i]of Object.entries(r))o.push(`**${s}**:
46
42
  ${i.map(n=>` - ${n}`).join(`
47
43
  `)}`);return o.join(`
48
44
 
49
- `)}function Rn(e){return(e?hr(e):mt).map(r=>{let o=mr[r.id];return{id:r.id,slug:ll(r.name),name:r.name,category:r.category,description:o?.description??"",tags:o?.tags??[],envVars:o?.envVars??[],docsUrl:o?.docsUrl??"",packages:o?.packages??[],difficulty:o?.difficulty??"medium"}})}var mr,mt,so=T(()=>{"use strict";mr={"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"},"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
45
+ `)}function un(t){return(t?Zo(t):Ze).map(r=>{let o=Xo[r.id];return{id:r.id,slug:Ha(r.name),name:r.name,category:r.category,description:o?.description??"",tags:o?.tags??[],envVars:o?.envVars??[],docsUrl:o?.docsUrl??"",packages:o?.packages??[],difficulty:o?.difficulty??"medium"}})}var Xo,Ze,Wt=A(()=>{"use strict";Xo={"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"},"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"}},Ze=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
50
46
 
51
47
  ### File Structure
52
48
  \`\`\`
@@ -1466,12 +1462,12 @@ export function ImageGenerator() {
1466
1462
  5. **Replicate charges per prediction.** Flux Schnell is ~$0.003/image. Flux Pro is ~$0.05/image. Video models are $0.05-$0.50/generation. Show generation cost to users.
1467
1463
  6. **Cache generated images.** Store output URLs in your database. Replicate URLs expire after a few hours. Download and re-host on R2 for permanent storage.
1468
1464
  7. **Network I/O does NOT count as CPU time on Workers.** Image generation wait time is all network I/O.
1469
- 8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}]});import{z as ue}from"zod";import{resolve as io}from"path";import{existsSync as ao,readFileSync as lo}from"fs";import{join as co}from"path";var cl,Nn,En=T(()=>{"use strict";ee();Be();Tn();ge();ur();Pt();so();cl=ue.object({action:ue.enum(["get","update","share","landing-designs","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. 'landing-designs' lists curated landing page hero designs. '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:ue.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:ue.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:ue.object({key:ue.string(),description:ue.string().optional(),setupUrl:ue.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:ue.string().optional().describe("(share) Short description of what this template builds"),category:ue.string().optional().describe("(landing-designs) Filter by category"),presetId:ue.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),integrationId:ue.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:ue.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:ue.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),Nn={name:"mist_project",description:$r,inputSchema:cl,handler:async e=>{let t=e;if(["share","errors","logs","deployments"].includes(t.action)&&!ae())return d("You need to sign in first. Run mist_setup to connect your account.",!0);switch(t.action){case"get":case"update":return Sn.handler({action:t.action,projectPath:t.projectPath,completedStep:t.completedStep,addEnvVar:t.addEnvVar});case"share":{let o=io(t.projectPath??process.cwd()),s=co(o,"mistflow.json");if(!ao(s))return $e(o);let i;try{i=JSON.parse(lo(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first to register it.",!0);try{let a=await sr(n,{isTemplate:!0,description:t.templateDescription});return d(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
1465
+ 8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}]});import{z as pe}from"zod";import{resolve as Gt}from"path";import{existsSync as Vt,readFileSync as Kt}from"fs";import{join as Jt}from"path";var Wa,mn,hn=A(()=>{"use strict";re();Ee();dn();de();dt();Wt();Wa=pe.object({action:pe.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:pe.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:pe.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:pe.object({key:pe.string(),description:pe.string().optional(),setupUrl:pe.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:pe.string().optional().describe("(share) Short description of what this template builds"),category:pe.string().optional().describe("(integrations) Filter integrations by category"),integrationId:pe.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:pe.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:pe.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),mn={name:"mist_project",description:Tr,inputSchema:Wa,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!ie())return d("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return cn.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let o=Gt(e.projectPath??process.cwd()),s=Jt(o,"mistflow.json");if(!Vt(s))return Re(o);let i;try{i=JSON.parse(Kt(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first to register it.",!0);try{let a=await Vo(n,{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!
1470
1466
 
1471
1467
  Anyone can fork it: ${a.share_url}
1472
1468
 
1473
1469
  Others can use it in their AI editor:
1474
- "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"landing-designs":{if(t.presetId){let n=no(t.presetId);if(!n)return d(`Preset '${t.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let a=Pn(t.presetId);return d(JSON.stringify({preset:{id:n.id,title:n.title,category:n.category,description:a?.description??"",style:a?.style??"",theme:a?.theme??"dark",colors:a?.colors??[],tags:a?.tags??[],promptLength:n.prompt.length},message:`Landing design "${n.title}" (${n.category}) \u2014 ${a?.description??""}. To use it, pass landingDesign="${n.id}" when calling mist_plan.`}))}let o=In(t.category??void 0),s=pr(t.category),i=Cn(s);return d(JSON.stringify({count:o.length,presets:o.map(n=>({id:n.id,title:n.title,category:n.category,description:n.description,style:n.style,theme:n.theme,colors:n.colors})),formatted:i,message:`${o.length} landing designs available.${t.category?` Filtered by: ${t.category}.`:""} To use one, pass landingDesign="<id>" when calling mist_plan. The design blueprint will be injected during the landing page implementation step. Browse them at ${ct()}/designs?tab=landing-designs.`}))}case"integrations":{if(t.integrationId){let n=ht(t.integrationId);if(!n)return d(`Integration '${t.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=gt(n.id);return d(JSON.stringify({integration:{id:n.id,name:n.name,category:n.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${n.name}" (${n.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 o=Rn(t.category??void 0),s=hr(t.category??void 0),i=_n(s);return d(JSON.stringify({count:o.length,integrations:o.map(n=>({id:n.id,name:n.name,category:n.category,description:n.description,packages:n.packages,difficulty:n.difficulty,envVars:n.envVars.map(a=>a.key)})),formatted:i,message:`${o.length} integration blueprints available.${t.category?` Filtered by: ${t.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 o=io(t.projectPath??process.cwd()),s=co(o,"mistflow.json");if(!ao(s))return $e(o);let i;try{i=JSON.parse(lo(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);try{let a=await Qo(n,t.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 o=io(t.projectPath??process.cwd()),s=co(o,"mistflow.json");if(!ao(s))return $e(o);let i;try{i=JSON.parse(lo(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);let a=t.deploymentId;if(!a)try{let l=await pt(n);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([Yo(a),Rt(a)]),h=l.filter(p=>p.level==="error"),m=l.filter(p=>p.level==="warn");return d(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:h.length,warnCount:m.length,logs:l.map(p=>({time:p.timestamp,level:p.level,phase:p.phase,message:p.message})),message:c.status==="failed"?`Deployment failed. ${h.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${h.length} errors, ${m.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return d(c,!0)}}case"deployments":{let o=io(t.projectPath??process.cwd()),s=co(o,"mistflow.json");if(!ao(s))return $e(o);let i;try{i=JSON.parse(lo(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);try{let a=await pt(n);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":{Do().backendSignalReceived||await Fo();let o=Do(),s=o.severity==="none",i={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:o.current,latest:o.latest||"unknown",minSupported:o.minSupported||"unknown",severity:o.severity,upToDate:s,upgradeCmd:o.upgradeCmd,changelogUrl:o.changelogUrl,backendSignalReceived:o.backendSignalReceived,message:o.backendSignalReceived?`Mistflow MCP ${o.current} (${i[o.severity]??o.severity}). Latest: ${o.latest}.${s?"":` Run \`${o.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${o.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: ${t.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}}});import{z as tt}from"zod";var dl,Dn,jn=T(()=>{"use strict";Be();ee();Kt();dl=tt.object({action:tt.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:tt.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:tt.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:tt.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:tt.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:tt.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),Dn={name:"mist_browser",description:Fr,inputSchema:dl,handler:async e=>{let t=e,r=await jo();if(t.action==="navigate"){if(!t.url)return d("URL is required for 'navigate'.",!0);let i=[],n=c=>{c.type()==="error"&&i.push(c.text())};r.on("console",n),await r.goto(t.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",n),r.removeListener("pageerror",l),i.length>0||a.length>0){let c=await Ct(r),h=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(t.includeScreenshot){let m=await It(r);h.push({type:"image",data:m.toString("base64"),mimeType:"image/png"})}return{content:h}}}else if(t.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(t.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(t.action==="click"){if(!t.selector)return d("Selector is required for 'click'.",!0);await r.click(t.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(t.action==="type"){if(!t.selector)return d("Selector is required for 'type'.",!0);if(!t.value)return d("Value is required for 'type'.",!0);await r.type(t.selector,t.value,{delay:50})}else if(t.action==="fill"){if(!t.selector)return d("Selector is required for 'fill'.",!0);if(!t.value)return d("Value is required for 'fill'.",!0);await r.fill(t.selector,t.value)}else if(t.action==="select_option"){if(!t.selector)return d("Selector is required for 'select_option'.",!0);if(!t.value)return d("Value is required for 'select_option'.",!0);await r.selectOption(t.selector,t.value)}else if(t.action==="hover"){if(!t.selector)return d("Selector is required for 'hover'.",!0);await r.hover(t.selector,{timeout:1e4})}else if(t.action==="press_key"){if(!t.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(t.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(t.action==="screenshot"){t.url&&(await r.goto(t.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let i;if(t.selector){let n=await r.$(t.selector);if(!n)return d(`Element not found: ${t.selector}`,!0);i=await n.screenshot({type:"png"})}else i=await It(r,t.fullPage);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),message:`Screenshot captured (${t.fullPage?"full page":"viewport"})`})},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}else if(t.action==="snapshot"){let i=await Ct(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:i})}]}}let o=await Ct(r),s=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}];if(t.includeScreenshot){let i=await It(r);s.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:s}}}});import{z as On}from"zod";var Mn,Ln,Un=T(()=>{"use strict";Be();ee();Mn=`# Mistflow MCP tool reference
1470
+ "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 n=et(e.integrationId);if(!n)return d(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=tt(n.id);return d(JSON.stringify({integration:{id:n.id,name:n.name,category:n.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${n.name}" (${n.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 o=un(e.category??void 0),s=Zo(e.category??void 0),i=pn(s);return d(JSON.stringify({count:o.length,integrations:o.map(n=>({id:n.id,name:n.name,category:n.category,description:n.description,packages:n.packages,difficulty:n.difficulty,envVars:n.envVars.map(a=>a.key)})),formatted:i,message:`${o.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 o=Gt(e.projectPath??process.cwd()),s=Jt(o,"mistflow.json");if(!Vt(s))return Re(o);let i;try{i=JSON.parse(Kt(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);try{let a=await $o(n,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 o=Gt(e.projectPath??process.cwd()),s=Jt(o,"mistflow.json");if(!Vt(s))return Re(o);let i;try{i=JSON.parse(Kt(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await Xe(n);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([Lo(a),ft(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 o=Gt(e.projectPath??process.cwd()),s=Jt(o,"mistflow.json");if(!Vt(s))return Re(o);let i;try{i=JSON.parse(Kt(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);try{let a=await Xe(n);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":{xo().backendSignalReceived||await Ao();let o=xo(),s=o.severity==="none",i={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:o.current,latest:o.latest||"unknown",minSupported:o.minSupported||"unknown",severity:o.severity,upToDate:s,upgradeCmd:o.upgradeCmd,changelogUrl:o.changelogUrl,backendSignalReceived:o.backendSignalReceived,message:o.backendSignalReceived?`Mistflow MCP ${o.current} (${i[o.severity]??o.severity}). Latest: ${o.latest}.${s?"":` Run \`${o.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${o.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 Ge}from"zod";var Ga,gn,fn=A(()=>{"use strict";Ee();re();mt();Ga=Ge.object({action:Ge.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:Ge.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Ge.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:Ge.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:Ge.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Ge.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),gn={name:"mist_browser",description:Pr,inputSchema:Ga,handler:async t=>{let e=t,r=await So();if(e.action==="navigate"){if(!e.url)return d("URL is required for 'navigate'.",!0);let i=[],n=c=>{c.type()==="error"&&i.push(c.text())};r.on("console",n),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",n),r.removeListener("pageerror",l),i.length>0||a.length>0){let c=await pt(r),m=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let p=await ut(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 i;if(e.selector){let n=await r.$(e.selector);if(!n)return d(`Element not found: ${e.selector}`,!0);i=await n.screenshot({type:"png"})}else i=await ut(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:i.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let i=await pt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:i})}]}}let o=await pt(r),s=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}];if(e.includeScreenshot){let i=await ut(r);s.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:s}}}});import{z as yn}from"zod";var bn,wn,vn=A(()=>{"use strict";Ee();re();bn=`# Mistflow MCP tool reference
1475
1471
 
1476
1472
  Every capability is an MCP tool. There is no companion CLI. Long-running tools
1477
1473
  (install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
@@ -1534,8 +1530,7 @@ returned \`auth_missing\` / \`auth_revoked\`. Do NOT call in response to 500s,
1534
1530
  ### \`mist_project({ action: "get" })\`
1535
1531
  Load plan progress, env vars, deploy info. Call before editing an existing
1536
1532
  Mistflow project so you understand its shape. Other actions: \`update\`,
1537
- \`share\`, \`landing-designs\`, \`integrations\`, \`errors\`, \`logs\`,
1538
- \`deployments\`, \`version\`.
1533
+ \`share\`, \`integrations\`, \`errors\`, \`logs\`, \`deployments\`, \`version\`.
1539
1534
 
1540
1535
  ### \`mist_plan({ description })\`
1541
1536
  Start a new plan. Pass the user's description EXACTLY as written \u2014 do NOT
@@ -1779,14 +1774,14 @@ is cheaper than building the wrong thing and iterating.
1779
1774
 
1780
1775
  mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
1781
1776
  mist_deploy({ action: "status", deploymentId }) # poll
1782
- `,Ln={name:"mist_help",description:qr,inputSchema:On.object({command:On.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 e=>{let{command:t}=e;if(!t)return d(Mn);let r=t.startsWith("mist_")?t:`mist_${t}`,o=Mn.split(`
1777
+ `,wn={name:"mist_help",description:Cr,inputSchema:yn.object({command:yn.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(bn);let r=e.startsWith("mist_")?e:`mist_${e}`,o=bn.split(`
1783
1778
  `),s=new RegExp(`^### \`${r}`),i=-1,n=o.length;for(let a=0;a<o.length;a++)if(s.test(o[a]))i=a;else if(i>=0&&o[a].startsWith("### ")){n=a;break}else if(i>=0&&o[a].startsWith("## ")&&a>i){n=a;break}return i<0?d(`No tool named '${r}' found. Call mist_help with no args to see the full catalog.`,!0):d(o.slice(i,n).join(`
1784
- `).trim())}}});import{existsSync as po,mkdirSync as qn,readFileSync as Bn,readdirSync as zn,writeFileSync as pl}from"fs";import{join as Ve,resolve as ul}from"path";import{homedir as fr}from"os";import{z as jt}from"zod";function ft(e){return e.entity??e.name??"Unknown"}function yt(e){return typeof e=="string"?e:e.name}function gr(e){return typeof e=="string"?"text":e.type}function $n(e){let t=e.sampleRows;if(Array.isArray(t)&&t.length>0)return t.slice(0,3).map(s=>{let i={};for(let[n,a]of Object.entries(s))i[n]=a==null?"":String(a);return i});let r=e.fields||[],o=[];for(let s=0;s<3;s++){let i={};for(let n of r)i[yt(n)]=ml(yt(n),gr(n),ft(e),s);o.push(i)}return o}function ml(e,t,r,o){let s=e.toLowerCase(),i=(t||"text").toLowerCase();return s==="name"||s==="title"?[`${r} Alpha`,`${r} Beta`,`${r} Gamma`][o]:s==="email"?["alice@example.com","bob@example.com","carol@example.com"][o]:s==="status"?["Active","Pending","Completed"][o]:s==="priority"?["High","Medium","Low"][o]:s.includes("date")||i==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][o]:s.includes("price")||s.includes("amount")||s.includes("cost")?["$29","$49","$99"][o]:s.includes("count")||s.includes("quantity")||i==="number"||i==="integer"?["12","34","56"][o]:i==="boolean"||i==="bool"?["Yes","No","Yes"][o]:s.includes("description")||i==="textarea"?["Brief description here","Another example entry","Third sample item"][o]:`Sample ${o+1}`}function hl(e){let t=e.dataModel??[],r=e.pages??[],o=e.design??{},s=r.map(m=>({label:m.name??m.path??"Page",route:m.path??m.route??"/"})),i=[],n=t.slice(0,3).map(m=>({name:ft(m),fields:(m.fields||[]).map(p=>({name:yt(p),type:gr(p)})),sampleData:$n(m)})),a=[];e.primaryAction&&(a.push(`PRIMARY: ${e.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${e.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${t.map(m=>ft(m)).join(", ")}`),a.push("RECENT: Latest activity or items"),i.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:e.primaryAction?`Action surface \u2014 user comes here to ${e.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${t.map(m=>ft(m)).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:n});let l=t[0];if(l){let m=ft(l),p=m.toLowerCase().endsWith("s")?m:`${m}s`;i.push({name:`${m} List`,type:"detail",route:`/${p.toLowerCase()}`,purpose:`Browse, search, and manage ${p.toLowerCase()}. Create new ${m.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${p}" title + "Add ${m}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(f=>yt(f)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${p.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${p.toLowerCase()} matching..." with clear filter`],entities:[{name:m,fields:(l.fields||[]).map(f=>({name:yt(f),type:gr(f)})),sampleData:$n(l)}]})}e.steps.some(m=>{let p=`${m.name??m.title??""} ${m.description??""}`.toLowerCase();return p.includes("landing")||p.includes("hero")||p.includes("marketing")||p.includes("homepage")})&&i.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${e.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${e.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 h=[];for(let m of t.slice(0,3)){let p=ft(m);(m.fields||[]).find(S=>{let b=yt(S).toLowerCase();return b==="name"||b==="title"})&&h.push(`What if a ${p.toLowerCase()}'s name is 47 characters? Does the layout break?`),h.push(`What if there are 0 ${p.toLowerCase()}s? 1? 500?`)}return e.authModel&&e.authModel!=="none"&&h.push("What does a brand-new user see? (no data, no setup)"),h.push("What if the network is slow? What loads first?"),{appName:e.name,summary:e.summary??"",screens:i,navigation:{style:e.navStyle??"sidebar",items:s},primaryAction:e.primaryAction??null,designDirection:{tone:o.tone??"professional",accentColor:o.accentColor??"blue",navStyle:e.navStyle??"sidebar",fonts:o.fonts??{heading:"Inter",body:"Inter"}},edgeCases:h}}function gl(e,t,r){let o=[];o.push(`# Wireframe sketch for ${e.appName}`),o.push(""),o.push(`**${e.appName}** \u2014 ${e.summary}`),o.push(""),t&&(o.push("## Feedback to apply"),o.push(t),o.push("")),o.push("## Design principles"),o.push(""),o.push("Apply these when deciding layout and hierarchy:"),o.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."),o.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),o.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."),o.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),o.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),o.push(""),o.push("## Wireframe rules (strict)"),o.push(""),o.push(`Write a **single self-contained HTML file** saved to \`${r}\`.`),o.push(""),o.push("The wireframe must:"),o.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),o.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),o.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),o.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),o.push("- Include **HTML comments** explaining design decisions"),o.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),o.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),o.push("- Include a small header bar showing: screen name tabs + the design direction summary"),o.push(""),o.push("The wireframe must NOT:"),o.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),o.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),o.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),o.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),o.push(""),o.push("## Screens to wireframe"),o.push("");for(let s of e.screens){o.push(`### ${s.name} (\`${s.route}\`)`),o.push(`**Purpose**: ${s.purpose}`),o.push(""),o.push("**Information hierarchy** (render in this order, top to bottom):");for(let i of s.informationHierarchy)o.push(`- ${i}`);o.push(""),o.push("**Interaction states** (add HTML comments for non-visible states):");for(let i of s.interactionStates)o.push(`- ${i}`);if(o.push(""),s.entities.length>0){o.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let i of s.entities)o.push(`
1785
- **${i.name}** \u2014 fields: ${i.fields.map(n=>`${n.name} (${n.type})`).join(", ")}`),o.push("```json"),o.push(JSON.stringify(i.sampleData,null,2)),o.push("```");o.push("")}}o.push("## Navigation"),o.push(`**Style**: ${e.navigation.style} (use this layout)`),o.push("**Items**:");for(let s of e.navigation.items)o.push(`- ${s.label} \u2192 \`${s.route}\``);if(o.push(""),e.primaryAction&&(o.push("## Primary action (this drives the layout)"),o.push(`- **Action**: ${e.primaryAction.action}`),o.push(`- **Flow**: ${e.primaryAction.flow}`),o.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),o.push(""),o.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."),o.push("")),e.edgeCases.length>0){o.push("## Edge cases to consider"),o.push("Add HTML comments in the wireframe where these matter:");for(let s of e.edgeCases)o.push(`- ${s}`);o.push("")}return o.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),o.push(`The final app will use: ${e.designDirection.tone} tone, ${e.designDirection.accentColor} accent, ${e.designDirection.navStyle} nav, ${e.designDirection.fonts.heading} / ${e.designDirection.fonts.body} fonts.`),o.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),o.push(""),o.push("## After writing the wireframe"),o.push(`1. Write the file to \`${r}\``),o.push(`2. Open it for the user: \`open "${r}"\``),o.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."`),o.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),o.join(`
1786
- `)}function Hn(e){return Ve(fr(),".mistflow","mockup-state",`${e}.json`)}function fl(e){let t=Hn(e);if(!po(t))return null;try{return JSON.parse(Bn(t,"utf-8"))}catch{return null}}function Fn(e,t){let r=Ve(fr(),".mistflow","mockup-state");qn(r,{recursive:!0}),pl(Hn(e),JSON.stringify(t,null,2))}function Gn(e){let t=Ve(e,".mistflow","mockups");return po(t)?zn(t).filter(r=>r.endsWith(".html")).map(r=>Ve(t,r)):[]}var yl,Wn,yr=T(()=>{"use strict";Be();ee();yl=jt.object({planId:jt.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:jt.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:jt.string().optional().describe("User feedback to apply to the next iteration."),approved:jt.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(e=>!(e.feedback&&e.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),Wn={name:"mist_mockup",description:zr,inputSchema:yl,handler:async e=>{let t=e,{planId:r,feedback:o,approved:s}=t,i=ul(t.projectPath??process.cwd()),n=Ve(fr(),".mistflow","plans",`${r}.json`);if(!po(n))return d(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(Bn(n,"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=fl(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let h=Ve(i,".mistflow","mockups");qn(h,{recursive:!0});let m=`mockup-${r}.html`,p=Ve(h,m);if(s){c.approved=!0,Fn(r,c);let k=po(h)?zn(h).filter(I=>I.endsWith(".html")).map(I=>Ve(".mistflow","mockups",I)):[];return d(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:k,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++,o&&c.feedback.push(o);let f=hl(l);c.screens=f.screens.map(k=>k.name),Fn(r,c);let S=gl(f,o??void 0,p),b=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,y=o?`Apply the user's feedback to ${p}. 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 ${p}, then open it in the browser. Ask the user if the layout feels right.`;return d(JSON.stringify({status:"wireframe",iterationCount:c.iterationCount,screens:f.screens.map(k=>({name:k.name,type:k.type,route:k.route})),wireframePrompt:S,designDirection:f.designDirection,...b?{nudge:b}:{},mockupFile:m,mockupPath:p,nextAction:y}))}}});function uo(e){let t=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of e.matchAll(r)){let[,l,c,h,m,p]=a;t.push({file:l,line:parseInt(c,10),column:parseInt(h,10),message:`${m}: ${p}`,humanMessage:`There is a type error in ${l} on line ${c}: ${p}`,suggestion:`Check line ${c} in ${l}. ${m==="TS2345"?"The types of the arguments do not match.":`Fix the ${m} error.`}`})}let o=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of e.matchAll(o)){let[,l,c,h,m]=a;t.some(p=>p.file===l&&p.line===parseInt(c,10))||t.push({file:l,line:parseInt(c,10),column:parseInt(h,10),message:m,humanMessage:`There is an error in ${l} on line ${c}: ${m.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let s=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of e.matchAll(s)){let[,l,c]=a;t.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 i=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of e.matchAll(i)){let[,l,c]=a;t.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 n=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of e.matchAll(n)){let[,l,c,h,m]=a;t.some(p=>p.file===l&&p.line===parseInt(h,10))||t.push({file:l,line:parseInt(h,10),column:parseInt(m,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${h}.`,suggestion:`Check line ${h} in ${l} for a missing closing bracket or unexpected token.`})}return t}var br=T(()=>{"use strict"});import{z as wr}from"zod";import{resolve as bl}from"path";import{spawn as wl}from"child_process";function xl(e){return new Promise(t=>{let r=wl("npm",["run","build"],{cwd:e,stdio:["ignore","pipe","pipe"]}),o="";r.stdout?.on("data",s=>{o+=s.toString()}),r.stderr?.on("data",s=>{o+=s.toString()}),r.on("error",s=>{t({exitCode:127,combined:`${o}
1787
- ${s.message}`})}),r.on("close",s=>{t({exitCode:s??1,combined:o})})})}var vl,Vn,Kn=T(()=>{"use strict";Be();ee();br();vl=wr.object({projectPath:wr.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:wr.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});Vn={name:"mist_debug",description:Br,inputSchema:vl,handler:async e=>{let t=e,r=bl(t.projectPath??process.cwd()),o=t.buildOutput??"";if(!t.buildOutput){let n=await xl(r);if(n.exitCode===0)return d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));o=n.combined}let s=uo(o),i=o.slice(0,2e3);return s.length===0?d(JSON.stringify({errors:s,rawOutput:i,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):d(JSON.stringify({errors:s,rawOutput:i,message:`Found ${s.length} error${s.length===1?"":"s"} in the build output.`}))}}});function Oe(e,t,r,o=3e3){if(t===void 0)return{stop:()=>{}};let s=0,i=!1,a=setInterval(()=>{i||(s++,e.notification({method:"notifications/progress",params:{progressToken:t,progress:s,message:r()}}).catch(()=>{}))},o);return{stop:()=>{i||(i=!0,clearInterval(a))}}}var bt=T(()=>{"use strict"});function kl(e){try{return!!e.getClientCapabilities()?.elicitation}catch{return!1}}function Sl(){let e=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return e==="off"||e==="false"||e==="0"||e==="disabled"}function Tl(e){let t=e.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(t)?t:`_${t}`}function Pl(e){let t={},r=[],o=[],s=new Set;for(let i=0;i<e.length;i++){let n=e[i],a=n.decisionKey?Tl(n.decisionKey):`q_${i+1}`,l=a,c=2;for(;s.has(l);)l=`${a}_${c}`,c++;s.add(l);let h=n.freetext?"":`${l}_other`;if(h&&s.add(h),o.push({primary:l,other:h,question:n}),n.freetext){t[l]={type:"string",title:n.question,description:n.why,...n.recommended?{default:n.recommended}:{}},r.push(l);continue}let m=(n.options??[]).map(f=>typeof f=="string"?f:f.label),p=n.noOtherSentinel?[...m]:[...m,"Other (specify in the 'Other' field below)"];t[l]={type:"string",title:n.question,description:n.why?`${n.why}${n.recommended?`
1788
- Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}`:void 0,enum:p,enumNames:p,...n.recommended&&m.includes(n.recommended)?{default:n.recommended}:{}},r.push(l),t[h]={type:"string",title:n.otherFieldTitle??"If 'Other' selected above: type your answer",description:"Leave blank if you picked an option from the list."}}return{schema:{type:"object",properties:t,required:r},fieldKeys:o}}function Cl(e,t){let r=[],o;for(let{primary:s,other:i,question:n}of t){let a=String(e[s]??"").trim(),l;if(n.freetext)l=a||n.recommended||"";else{let h=i?String(e[i]??"").trim():"",m=a.toLowerCase(),p=m.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(m);h?l=h:p?l=n.recommended??(n.options?.[0]&&typeof n.options[0]=="object"?n.options[0].label:"")??a:l=a}let c=n.decisionKey??"";if(c==="urlChoice"){o=l;continue}r.push({question:n.question,decisionKey:c,answer:l})}return{answers:r,urlChoice:o}}async function mo(e,t,r){if(Sl())return{outcome:"unsupported"};if(!kl(e))return{outcome:"unsupported"};if(t.length===0)return{outcome:"submitted",answers:[]};let{schema:o,fieldKeys:s}=Pl(t),i;try{i=await e.elicitInput({message:r,requestedSchema:o,mode:"form"},{timeout:300*1e3})}catch(l){let c=l instanceof Error?l.message:String(l);return c.toLowerCase().includes("not support")?{outcome:"unsupported"}:{outcome:"error",errorMessage:c}}if(i.action==="decline")return{outcome:"declined"};if(i.action==="cancel")return{outcome:"cancelled"};if(i.action!=="accept"||!i.content)return{outcome:"error",errorMessage:`Unexpected elicitation result: ${i.action}`};let{answers:n,urlChoice:a}=Cl(i.content,s);return{outcome:"submitted",answers:n,urlChoice:a}}var Jn=T(()=>{"use strict"});function Yn(e,t,r){let o=r?.suggestedName||Al(e),s=t.primaryActor==="both"?"Staff + Customers":t.primaryActor==="staff"?"Staff / Admin":t.primaryActor==="customers"?"End Users":"Users",i=t.audienceType??(t.surfaceType==="internal-tool"?"internal":(t.primaryActor==="customers"||t.primaryActor==="both","b2c")),n=t.surfaceType==="internal-tool"?"Internal tool":t.surfaceType==="marketplace"?"Marketplace":t.surfaceType==="content-site"?"Content site":t.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=`${e} ${t.primaryAction||""}`;a=[];for(let c of Il){let h=c.keywords.test(l),m=c.condition(t);(h||m)&&a.push({name:c.name,description:c.description,checked:h,source:h?"explicit":"suggested"})}}return{name:o,audience:s,audienceType:i,surfaceType:n,primaryAction:t.primaryAction||"manage items",features:a,publicLanding:t.publicLanding??!0,authModel:t.authModel??"email",dbProvider:t.dbProvider??"neon",integrations:t.integrations??[],language:r?.language||"English"}}function Qn(e){let t=e.features.filter(a=>a.checked),r=e.features.filter(a=>!a.checked),o={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},s={neon:"Postgres",turso:"SQLite (legacy)"},i={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},n=[`**${e.name}** \u2014 ${e.surfaceType} for ${e.audience}`,`Audience: ${i[e.audienceType]??e.audienceType}`,`Primary action: ${e.primaryAction}`,`Access: ${o[e.authModel]??e.authModel} | Database: ${s[e.dbProvider]??e.dbProvider}${e.publicLanding?" | Landing page: Yes":""}${e.language&&e.language!=="English"?` | Language: ${e.language}`:""}`,""];if(t.length>0){n.push("**Included:**");for(let a of t)n.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(e.integrations.length>0&&(n.push(""),n.push(`**Integrations:** ${e.integrations.join(", ")}`)),r.length>0){n.push(""),n.push("**Available to add:**");for(let a of r)n.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return n.join(`
1789
- `)}function Al(e){let t=e.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(t)return ho(t[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"]),s=e.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(i=>i.length>2&&!r.has(i)).slice(0,3);return s.length===0?"my-app":s.join("-")}function ho(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Il,Xn=T(()=>{"use strict";Il=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:e=>e.surfaceType==="internal-tool"||e.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:e=>e.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:e=>e.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:e=>e.multiRole===!0||e.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:e=>e.primaryActor==="customers"||e.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:e=>e.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:e=>e.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:e=>e.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:e=>e.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:e=>e.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:e=>e.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:e=>e.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:e=>e.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:e=>e.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 vr(e,t,r){return t.includes(e)?e:r}function me(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function wt(e,t){return typeof e!="string"?t:/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(e.trim())?e.trim():t}function El(e){let t=new Set;for(let o of e)o.fonts?.display&&t.add(o.fonts.display),o.fonts?.body&&t.add(o.fonts.body);return t.size===0?"":`https://fonts.googleapis.com/css2?${[...t].map(o=>`family=${o.trim().replace(/\s+/g,"+").replace(/[^A-Za-z0-9+]/g,"")}:wght@400;700`).join("&")}&display=swap`}function Zn(e){let t=(e||"").trim(),r=t.toLowerCase(),o=/mono|courier|code/.test(r)?"ui-monospace, monospace":/serif|garamond|bodoni|fraunces|playfair|lora|sentient|migra|sectra|cormorant|abril|crimson/.test(r)?"Georgia, serif":"system-ui, sans-serif";return t?`"${t.replace(/"/g,"")}", ${o}`:o}function Dl(e){switch(e){case"sharp":return{card:"0px",button:"0px",chip:"0px"};case"pill":return{card:"20px",button:"999px",chip:"999px"};case"organic":return{card:"4px 24px 4px 24px",button:"24px 4px 24px 4px",chip:"12px 2px 12px 2px"};default:return{card:"10px",button:"8px",chip:"6px"}}}function jl(){let e=`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>")`;return`
1779
+ `).trim())}}});import{existsSync as Yt,mkdirSync as Sn,readFileSync as Tn,readdirSync as Pn,writeFileSync as Va}from"fs";import{join as Me,resolve as Ka}from"path";import{homedir as tr}from"os";import{z as vt}from"zod";function ot(t){return t.entity??t.name??"Unknown"}function rt(t){return typeof t=="string"?t:t.name}function er(t){return typeof t=="string"?"text":t.type}function kn(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(s=>{let i={};for(let[n,a]of Object.entries(s))i[n]=a==null?"":String(a);return i});let r=t.fields||[],o=[];for(let s=0;s<3;s++){let i={};for(let n of r)i[rt(n)]=Ja(rt(n),er(n),ot(t),s);o.push(i)}return o}function Ja(t,e,r,o){let s=t.toLowerCase(),i=(e||"text").toLowerCase();return s==="name"||s==="title"?[`${r} Alpha`,`${r} Beta`,`${r} Gamma`][o]:s==="email"?["alice@example.com","bob@example.com","carol@example.com"][o]:s==="status"?["Active","Pending","Completed"][o]:s==="priority"?["High","Medium","Low"][o]:s.includes("date")||i==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][o]:s.includes("price")||s.includes("amount")||s.includes("cost")?["$29","$49","$99"][o]:s.includes("count")||s.includes("quantity")||i==="number"||i==="integer"?["12","34","56"][o]:i==="boolean"||i==="bool"?["Yes","No","Yes"][o]:s.includes("description")||i==="textarea"?["Brief description here","Another example entry","Third sample item"][o]:`Sample ${o+1}`}function Ya(t){let e=t.dataModel??[],r=t.pages??[],o=t.design??{},s=r.map(p=>({label:p.name??p.path??"Page",route:p.path??p.route??"/"})),i=[],n=e.slice(0,3).map(p=>({name:ot(p),fields:(p.fields||[]).map(u=>({name:rt(u),type:er(u)})),sampleData:kn(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=>ot(p)).join(", ")}`),a.push("RECENT: Latest activity or items"),i.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=>ot(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:n});let l=e[0];if(l){let p=ot(l),u=p.toLowerCase().endsWith("s")?p:`${p}s`;i.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(w=>rt(w)).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(w=>({name:rt(w),type:er(w)})),sampleData:kn(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")})&&i.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=ot(p);(p.fields||[]).find(D=>{let x=rt(D).toLowerCase();return x==="name"||x==="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:i,navigation:{style:t.navStyle??"sidebar",items:s},primaryAction:t.primaryAction??null,designDirection:{tone:o.tone??"professional",accentColor:o.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:o.fonts??{heading:"Inter",body:"Inter"}},edgeCases:m}}function Qa(t,e,r){let o=[];o.push(`# Wireframe sketch for ${t.appName}`),o.push(""),o.push(`**${t.appName}** \u2014 ${t.summary}`),o.push(""),e&&(o.push("## Feedback to apply"),o.push(e),o.push("")),o.push("## Design principles"),o.push(""),o.push("Apply these when deciding layout and hierarchy:"),o.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."),o.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),o.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."),o.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),o.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),o.push(""),o.push("## Wireframe rules (strict)"),o.push(""),o.push(`Write a **single self-contained HTML file** saved to \`${r}\`.`),o.push(""),o.push("The wireframe must:"),o.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),o.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),o.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),o.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),o.push("- Include **HTML comments** explaining design decisions"),o.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),o.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),o.push("- Include a small header bar showing: screen name tabs + the design direction summary"),o.push(""),o.push("The wireframe must NOT:"),o.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),o.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),o.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),o.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),o.push(""),o.push("## Screens to wireframe"),o.push("");for(let s of t.screens){o.push(`### ${s.name} (\`${s.route}\`)`),o.push(`**Purpose**: ${s.purpose}`),o.push(""),o.push("**Information hierarchy** (render in this order, top to bottom):");for(let i of s.informationHierarchy)o.push(`- ${i}`);o.push(""),o.push("**Interaction states** (add HTML comments for non-visible states):");for(let i of s.interactionStates)o.push(`- ${i}`);if(o.push(""),s.entities.length>0){o.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let i of s.entities)o.push(`
1780
+ **${i.name}** \u2014 fields: ${i.fields.map(n=>`${n.name} (${n.type})`).join(", ")}`),o.push("```json"),o.push(JSON.stringify(i.sampleData,null,2)),o.push("```");o.push("")}}o.push("## Navigation"),o.push(`**Style**: ${t.navigation.style} (use this layout)`),o.push("**Items**:");for(let s of t.navigation.items)o.push(`- ${s.label} \u2192 \`${s.route}\``);if(o.push(""),t.primaryAction&&(o.push("## Primary action (this drives the layout)"),o.push(`- **Action**: ${t.primaryAction.action}`),o.push(`- **Flow**: ${t.primaryAction.flow}`),o.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),o.push(""),o.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."),o.push("")),t.edgeCases.length>0){o.push("## Edge cases to consider"),o.push("Add HTML comments in the wireframe where these matter:");for(let s of t.edgeCases)o.push(`- ${s}`);o.push("")}return o.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),o.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.`),o.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),o.push(""),o.push("## After writing the wireframe"),o.push(`1. Write the file to \`${r}\``),o.push(`2. Open it for the user: \`open "${r}"\``),o.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."`),o.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),o.join(`
1781
+ `)}function Cn(t){return Me(tr(),".mistflow","mockup-state",`${t}.json`)}function Xa(t){let e=Cn(t);if(!Yt(e))return null;try{return JSON.parse(Tn(e,"utf-8"))}catch{return null}}function xn(t,e){let r=Me(tr(),".mistflow","mockup-state");Sn(r,{recursive:!0}),Va(Cn(t),JSON.stringify(e,null,2))}function An(t){let e=Me(t,".mistflow","mockups");return Yt(e)?Pn(e).filter(r=>r.endsWith(".html")).map(r=>Me(e,r)):[]}var Za,In,or=A(()=>{"use strict";Ee();re();Za=vt.object({planId:vt.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:vt.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:vt.string().optional().describe("User feedback to apply to the next iteration."),approved:vt.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."}),In={name:"mist_mockup",description:Ar,inputSchema:Za,handler:async t=>{let e=t,{planId:r,feedback:o,approved:s}=e,i=Ka(e.projectPath??process.cwd()),n=Me(tr(),".mistflow","plans",`${r}.json`);if(!Yt(n))return d(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(Tn(n,"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=Xa(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let m=Me(i,".mistflow","mockups");Sn(m,{recursive:!0});let p=`mockup-${r}.html`,u=Me(m,p);if(s){c.approved=!0,xn(r,c);let f=Yt(m)?Pn(m).filter(_=>_.endsWith(".html")).map(_=>Me(".mistflow","mockups",_)):[];return d(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:f,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++,o&&c.feedback.push(o);let w=Ya(l);c.screens=w.screens.map(f=>f.name),xn(r,c);let D=Qa(w,o??void 0,u),x=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,S=o?`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",iterationCount:c.iterationCount,screens:w.screens.map(f=>({name:f.name,type:f.type,route:f.route})),wireframePrompt:D,designDirection:w.designDirection,...x?{nudge:x}:{},mockupFile:p,mockupPath:u,nextAction:S}))}}});function Qt(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 o=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(o)){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 s=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of t.matchAll(s)){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 i=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(i)){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 n=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of t.matchAll(n)){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 rr=A(()=>{"use strict"});import{z as nr}from"zod";import{resolve as el}from"path";import{spawn as tl}from"child_process";function rl(t){return new Promise(e=>{let r=tl("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),o="";r.stdout?.on("data",s=>{o+=s.toString()}),r.stderr?.on("data",s=>{o+=s.toString()}),r.on("error",s=>{e({exitCode:127,combined:`${o}
1782
+ ${s.message}`})}),r.on("close",s=>{e({exitCode:s??1,combined:o})})})}var ol,_n,Rn=A(()=>{"use strict";Ee();re();rr();ol=nr.object({projectPath:nr.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:nr.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});_n={name:"mist_debug",description:Ir,inputSchema:ol,handler:async t=>{let e=t,r=el(e.projectPath??process.cwd()),o=e.buildOutput??"";if(!e.buildOutput){let n=await rl(r);if(n.exitCode===0)return d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));o=n.combined}let s=Qt(o),i=o.slice(0,2e3);return s.length===0?d(JSON.stringify({errors:s,rawOutput:i,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):d(JSON.stringify({errors:s,rawOutput:i,message:`Found ${s.length} error${s.length===1?"":"s"} in the build output.`}))}}});function Te(t,e,r,o=3e3){if(e===void 0)return{stop:()=>{}};let s=0,i=!1,a=setInterval(()=>{i||(s++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:s,message:r()}}).catch(()=>{}))},o);return{stop:()=>{i||(i=!0,clearInterval(a))}}}var nt=A(()=>{"use strict"});function nl(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function sl(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function il(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function al(t){let e={},r=[],o=[],s=new Set;for(let i=0;i<t.length;i++){let n=t[i],a=n.decisionKey?il(n.decisionKey):`q_${i+1}`,l=a,c=2;for(;s.has(l);)l=`${a}_${c}`,c++;s.add(l);let m=n.freetext?"":`${l}_other`;if(m&&s.add(m),o.push({primary:l,other:m,question:n}),n.freetext){e[l]={type:"string",title:n.question,description:n.why,...n.recommended?{default:n.recommended}:{}},r.push(l);continue}let p=(n.options??[]).map(w=>typeof w=="string"?w:w.label),u=n.noOtherSentinel?[...p]:[...p,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:n.question,description:n.why?`${n.why}${n.recommended?`
1783
+ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}`:void 0,enum:u,enumNames:u,...n.recommended&&p.includes(n.recommended)?{default:n.recommended}:{}},r.push(l),e[m]={type:"string",title:n.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:o}}function ll(t,e){let r=[],o;for(let{primary:s,other:i,question:n}of e){let a=String(t[s]??"").trim(),l;if(n.freetext)l=a||n.recommended||"";else{let m=i?String(t[i]??"").trim():"",p=a.toLowerCase(),u=p.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(p);m?l=m:u?l=n.recommended??(n.options?.[0]&&typeof n.options[0]=="object"?n.options[0].label:"")??a:l=a}let c=n.decisionKey??"";if(c==="urlChoice"){o=l;continue}r.push({question:n.question,decisionKey:c,answer:l})}return{answers:r,urlChoice:o}}async function Xt(t,e,r){if(sl())return{outcome:"unsupported"};if(!nl(t))return{outcome:"unsupported"};if(e.length===0)return{outcome:"submitted",answers:[]};let{schema:o,fieldKeys:s}=al(e),i;try{i=await t.elicitInput({message:r,requestedSchema:o,mode:"form"},{timeout:300*1e3})}catch(l){let c=l instanceof Error?l.message:String(l);return c.toLowerCase().includes("not support")?{outcome:"unsupported"}:{outcome:"error",errorMessage:c}}if(i.action==="decline")return{outcome:"declined"};if(i.action==="cancel")return{outcome:"cancelled"};if(i.action!=="accept"||!i.content)return{outcome:"error",errorMessage:`Unexpected elicitation result: ${i.action}`};let{answers:n,urlChoice:a}=ll(i.content,s);return{outcome:"submitted",answers:n,urlChoice:a}}var En=A(()=>{"use strict"});function Nn(t,e,r){let o=r?.suggestedName||dl(t),s=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",i=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),n=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 cl){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:o,audience:s,audienceType:i,surfaceType:n,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 Dn(t){let e=t.features.filter(a=>a.checked),r=t.features.filter(a=>!a.checked),o={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},s={neon:"Postgres",turso:"SQLite (legacy)"},i={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},n=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${i[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${o[t.authModel]??t.authModel} | Database: ${s[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){n.push("**Included:**");for(let a of e)n.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(n.push(""),n.push(`**Integrations:** ${t.integrations.join(", ")}`)),r.length>0){n.push(""),n.push("**Available to add:**");for(let a of r)n.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return n.join(`
1784
+ `)}function dl(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return Zt(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"]),s=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(i=>i.length>2&&!r.has(i)).slice(0,3);return s.length===0?"my-app":s.join("-")}function Zt(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var cl,jn=A(()=>{"use strict";cl=[{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 sr(t,e,r){return e.includes(t)?t:r}function ce(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function st(t,e){return typeof t!="string"?e:/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(t.trim())?t.trim():e}function hl(t){let e=new Set;for(let o of t)o.fonts?.display&&e.add(o.fonts.display),o.fonts?.body&&e.add(o.fonts.body);return e.size===0?"":`https://fonts.googleapis.com/css2?${[...e].map(o=>`family=${o.trim().replace(/\s+/g,"+").replace(/[^A-Za-z0-9+]/g,"")}:wght@400;700`).join("&")}&display=swap`}function On(t){let e=(t||"").trim(),r=e.toLowerCase(),o=/mono|courier|code/.test(r)?"ui-monospace, monospace":/serif|garamond|bodoni|fraunces|playfair|lora|sentient|migra|sectra|cormorant|abril|crimson/.test(r)?"Georgia, serif":"system-ui, sans-serif";return e?`"${e.replace(/"/g,"")}", ${o}`:o}function gl(t){switch(t){case"sharp":return{card:"0px",button:"0px",chip:"0px"};case"pill":return{card:"20px",button:"999px",chip:"999px"};case"organic":return{card:"4px 24px 4px 24px",button:"24px 4px 24px 4px",chip:"12px 2px 12px 2px"};default:return{card:"10px",button:"8px",chip:"6px"}}}function fl(){let t=`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>")`;return`
1790
1785
  .card-hero { position: relative; overflow: hidden; isolation: isolate; }
1791
1786
  .card-hero::before {
1792
1787
  content: "";
@@ -1803,17 +1798,17 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
1803
1798
 
1804
1799
  .card-hero.texture-paper-grain::before {
1805
1800
  opacity: 0.35;
1806
- background-image: ${e};
1801
+ background-image: ${t};
1807
1802
  mix-blend-mode: multiply;
1808
1803
  }
1809
1804
  .card-hero.texture-film-grain::before {
1810
1805
  opacity: 0.5;
1811
- background-image: ${e};
1806
+ background-image: ${t};
1812
1807
  mix-blend-mode: overlay;
1813
1808
  }
1814
1809
  .card-hero.texture-noise::before {
1815
1810
  opacity: 0.25;
1816
- background-image: ${e};
1811
+ background-image: ${t};
1817
1812
  mix-blend-mode: overlay;
1818
1813
  }
1819
1814
  .card-hero.texture-scanlines::before {
@@ -1844,67 +1839,67 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
1844
1839
  backdrop-filter: blur(14px);
1845
1840
  mix-blend-mode: normal;
1846
1841
  }
1847
- `}function Ol(e,t,r,o){let s=wt(e.colors?.bg??"","#0f0f0f"),i=wt(e.colors?.fg??"","#f5f5f5"),n=wt(e.colors?.accent??"","#7c9cff"),a=me(e.name),l=me(e.hero_headline||e.name),c=me(e.body_sample||e.summary||""),h=me(e.cta_text||"Continue"),m=`<div class="hero-eyebrow" style="font-family:${r}">${a.toUpperCase()}</div>`,p=`<h2 class="hero-headline" style="font-family:${t}">${l}</h2>`,f=`<p class="hero-body" style="font-family:${r}">${c}</p>`,S=`<button class="hero-cta" style="background:${n};color:${s};font-family:${r};border-radius:${o.button}">${h}</button>`,b=vr(e.hero_treatment,_l,"typographic");if(b==="terminal"){let y=`"${(e.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
1848
- ${m}
1849
- <div class="hero-terminal-lines" style="font-family:${y};color:${i}">
1842
+ `}function yl(t,e,r,o){let s=st(t.colors?.bg??"","#0f0f0f"),i=st(t.colors?.fg??"","#f5f5f5"),n=st(t.colors?.accent??"","#7c9cff"),a=ce(t.name),l=ce(t.hero_headline||t.name),c=ce(t.body_sample||t.summary||""),m=ce(t.cta_text||"Continue"),p=`<div class="hero-eyebrow" style="font-family:${r}">${a.toUpperCase()}</div>`,u=`<h2 class="hero-headline" style="font-family:${e}">${l}</h2>`,w=`<p class="hero-body" style="font-family:${r}">${c}</p>`,D=`<button class="hero-cta" style="background:${n};color:${s};font-family:${r};border-radius:${o.button}">${m}</button>`,x=sr(t.hero_treatment,pl,"typographic");if(x==="terminal"){let S=`"${(t.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
1843
+ ${p}
1844
+ <div class="hero-terminal-lines" style="font-family:${S};color:${i}">
1850
1845
  <div>$ status --all</div>
1851
1846
  <div>api.service.......<span style="color:${n}">OK</span></div>
1852
1847
  <div>worker.queue......<span style="color:${n}">OK</span></div>
1853
1848
  <div>db.primary.......<span style="color:${n}">OK</span></div>
1854
1849
  </div>
1855
- ${p}
1856
- ${f}
1857
- <div class="hero-cta-row">${S}</div>
1858
- `}return b==="split-panel"?`
1850
+ ${u}
1851
+ ${w}
1852
+ <div class="hero-cta-row">${D}</div>
1853
+ `}return x==="split-panel"?`
1859
1854
  <div class="hero-split">
1860
- <div class="hero-split-left" style="background:${n};color:${s};font-family:${t}">
1855
+ <div class="hero-split-left" style="background:${n};color:${s};font-family:${e}">
1861
1856
  <div class="hero-split-mark" style="font-family:${r};color:${s}">${a[0]??"\xB7"}</div>
1862
1857
  </div>
1863
1858
  <div class="hero-split-right">
1864
- ${m}
1865
1859
  ${p}
1866
- ${f}
1867
- <div class="hero-cta-row">${S}</div>
1860
+ ${u}
1861
+ ${w}
1862
+ <div class="hero-cta-row">${D}</div>
1868
1863
  </div>
1869
1864
  </div>
1870
- `:b==="full-bleed-photo"?`
1865
+ `:x==="full-bleed-photo"?`
1871
1866
  <div class="hero-photo" style="background: linear-gradient(160deg, ${n}30 0%, ${i}08 35%, ${s} 100%), ${s}">
1872
1867
  <span class="hero-photo-label" style="font-family:${r};color:${i}">photo slot</span>
1873
1868
  </div>
1874
- ${m}
1875
1869
  ${p}
1876
- ${f}
1877
- <div class="hero-cta-row">${S}</div>
1878
- `:b==="magazine-hero"?`
1879
- ${m}
1880
- <h2 class="hero-headline hero-headline-mag" style="font-family:${t}">${l}</h2>
1870
+ ${u}
1871
+ ${w}
1872
+ <div class="hero-cta-row">${D}</div>
1873
+ `:x==="magazine-hero"?`
1874
+ ${p}
1875
+ <h2 class="hero-headline hero-headline-mag" style="font-family:${e}">${l}</h2>
1881
1876
  <div class="hero-rule" style="background:${i}"></div>
1882
1877
  <p class="hero-body hero-body-mag" style="font-family:${r}">${c}</p>
1883
1878
  <div class="hero-byline" style="font-family:${r};color:${i}">\u2014 Volume 01 \xB7 Issue 01</div>
1884
- <div class="hero-cta-row">${S}</div>
1879
+ <div class="hero-cta-row">${D}</div>
1885
1880
  `:`
1886
- ${m}
1887
1881
  ${p}
1888
- ${f}
1889
- <div class="hero-cta-row">${S}</div>
1890
- `}function es(e,t){let r=El(t),o=t.map(s=>{let i=wt(s.colors?.bg??"","#0f0f0f"),n=wt(s.colors?.fg??"","#f5f5f5"),a=wt(s.colors?.accent??"","#7c9cff"),l=Zn(s.fonts?.display??""),c=Zn(s.fonts?.body??""),h=vr(s.shape_lang,Rl,"soft"),m=vr(s.texture,Nl,"flat"),p=Dl(h),f=Ol(s,l,c,p),S=me(s.name),b=me(s.id),y=me(s.fonts?.display??""),k=me(s.fonts?.body??""),I=me(s.summary||""),R=me(s.decoration_hint||""),P=(M,F)=>`<div class="card-meta-row"><span class="card-meta-label">${M}</span><span class="card-meta-value">${F}</span></div>`;return` <article class="card" data-direction-id="${b}" style="border-radius:${p.card}">
1891
- <div class="card-hero texture-${m}" style="background:${i};color:${n}">${f}
1882
+ ${u}
1883
+ ${w}
1884
+ <div class="hero-cta-row">${D}</div>
1885
+ `}function Mn(t,e){let r=hl(e),o=e.map(s=>{let i=st(s.colors?.bg??"","#0f0f0f"),n=st(s.colors?.fg??"","#f5f5f5"),a=st(s.colors?.accent??"","#7c9cff"),l=On(s.fonts?.display??""),c=On(s.fonts?.body??""),m=sr(s.shape_lang,ul,"soft"),p=sr(s.texture,ml,"flat"),u=gl(m),w=yl(s,l,c,u),D=ce(s.name),x=ce(s.id),S=ce(s.fonts?.display??""),f=ce(s.fonts?.body??""),_=ce(s.summary||""),L=ce(s.decoration_hint||""),W=(R,J)=>`<div class="card-meta-row"><span class="card-meta-label">${R}</span><span class="card-meta-value">${J}</span></div>`;return` <article class="card" data-direction-id="${x}" style="border-radius:${u.card}">
1886
+ <div class="card-hero texture-${p}" style="background:${i};color:${n}">${w}
1892
1887
  </div>
1893
1888
  <div class="card-meta" style="border-top-color:${n}14">
1894
- <div class="card-meta-title">${S}</div>
1895
- <p class="card-meta-summary">${I}</p>
1896
- ${P("Fonts",`${y||"\u2014"} <span class="sep">\xB7</span> ${k||"\u2014"}`)}
1897
- ${P("Palette",`
1889
+ <div class="card-meta-title">${D}</div>
1890
+ <p class="card-meta-summary">${_}</p>
1891
+ ${W("Fonts",`${S||"\u2014"} <span class="sep">\xB7</span> ${f||"\u2014"}`)}
1892
+ ${W("Palette",`
1898
1893
  <span class="card-meta-swatches">
1899
1894
  <span class="card-meta-swatch" title="${i}" style="background:${i}"></span>
1900
1895
  <span class="card-meta-swatch" title="${n}" style="background:${n}"></span>
1901
1896
  <span class="card-meta-swatch" title="${a}" style="background:${a}"></span>
1902
1897
  </span>
1903
1898
  `)}
1904
- ${P("Shape",`<span class="chip" style="border-radius:${p.chip}">${h}</span>`)}
1905
- ${P("Texture",`<span class="chip" style="border-radius:${p.chip}">${me(m)}</span>`)}
1906
- ${R?P("Decoration",me(R)):""}
1907
- ${P("Pick with",`<code>${S}</code>`)}
1899
+ ${W("Shape",`<span class="chip" style="border-radius:${u.chip}">${m}</span>`)}
1900
+ ${W("Texture",`<span class="chip" style="border-radius:${u.chip}">${ce(p)}</span>`)}
1901
+ ${L?W("Decoration",ce(L)):""}
1902
+ ${W("Pick with",`<code>${D}</code>`)}
1908
1903
  </div>
1909
1904
  </article>`}).join(`
1910
1905
  `);return`<!DOCTYPE html>
@@ -1912,7 +1907,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
1912
1907
  <head>
1913
1908
  <meta charset="UTF-8" />
1914
1909
  <meta name="viewport" content="width=device-width,initial-scale=1" />
1915
- <title>Design directions \u2014 ${me(e)}</title>
1910
+ <title>Design directions \u2014 ${ce(t)}</title>
1916
1911
  <link rel="preconnect" href="https://fonts.googleapis.com" />
1917
1912
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
1918
1913
  ${r?`<link rel="stylesheet" href="${r}" />`:""}
@@ -2099,7 +2094,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
2099
2094
  margin-top: 4px;
2100
2095
  }
2101
2096
 
2102
- ${jl()}
2097
+ ${fl()}
2103
2098
 
2104
2099
  /* \u2500\u2500 Card meta footer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2105
2100
  .card-meta {
@@ -2208,7 +2203,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
2208
2203
  <div class="page">
2209
2204
  <header class="page-header">
2210
2205
  <div class="eyebrow"><span class="eyebrow-dot"></span>Mistflow \xB7 design direction</div>
2211
- <h1 class="page-title">How should <strong>${me(e)}</strong> feel?</h1>
2206
+ <h1 class="page-title">How should <strong>${ce(t)}</strong> feel?</h1>
2212
2207
  <p class="page-sub">Each card commits to a different extreme \u2014 different fonts, colors, hero layout, corner radius, texture, and voice. Pick one by telling your coding assistant its name, or describe your own.</p>
2213
2208
  </header>
2214
2209
 
@@ -2228,30 +2223,30 @@ ${o}
2228
2223
  </div>
2229
2224
  </body>
2230
2225
  </html>
2231
- `}var _l,Rl,Nl,ts=T(()=>{"use strict";_l=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],Rl=["sharp","soft","pill","organic"],Nl=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"]});import{z as _}from"zod";import{existsSync as Ot,mkdirSync as fo,readFileSync as rs,readdirSync as Ml,statSync as Ll,unlinkSync as Ul,writeFileSync as yo}from"fs";import{dirname as $l,isAbsolute as Fl,join as de}from"path";import{homedir as Ke}from"os";import{createHash as ql,createHmac as ns,randomBytes as Bl,randomUUID as os,timingSafeEqual as zl}from"crypto";function ss(){let e=de(Ke(),".mistflow","confirm-secret");if(Ot(e))try{return Buffer.from(rs(e,"utf-8").trim(),"hex")}catch{}let t=Bl(32);return fo(de(Ke(),".mistflow"),{recursive:!0}),yo(e,t.toString("hex"),{mode:384}),t}function is(e){return ql("sha256").update(e.trim().toLowerCase()).digest("hex").slice(0,16)}function Wl(e,t){let r={cwd:e,d:is(t),exp:Date.now()+Hl},o=Buffer.from(JSON.stringify(r)).toString("base64url"),s=ns("sha256",ss()).update(o).digest("base64url");return`${o}.${s}`}function Gl(e,t,r){let o=e.split(".");if(o.length!==2)return!1;let[s,i]=o,n=ns("sha256",ss()).update(s).digest("base64url"),a=Buffer.from(i),l=Buffer.from(n);if(a.length!==l.length||!zl(a,l))return!1;try{let c=JSON.parse(Buffer.from(s,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==t||c.d!==is(r))}catch{return!1}}function Vl(e){let t=e,r=Ke(),o=!1;for(let s=0;s<64;s++){if(Ot(de(t,"mistflow.json")))return"mistflow";if(!o&&Ot(de(t,"package.json"))&&(o=!0),t===r)break;let i=$l(t);if(i===t)break;t=i}return o?"foreign":"none"}function Kl(e){let t=Ke(),r=e.replace(/\/+$/,"");if(r===t||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let o=["Desktop","Documents","Downloads"];for(let s of o)if(r===de(t,s))return!0;return!1}function Yl(e){let t=[[/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[o,s]of t)if(o.test(e))return s;return e.replace(/[?.,!]/g,"").split(/\s+/).filter(o=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(o.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function Ql(e){let t=de(Ke(),".mistflow","plans",`${e}.json`);if(!Ot(t))return null;try{return JSON.parse(rs(t,"utf-8")).plan??null}catch{return null}}async function Xl(e){for(let o=0;o<60;o++){try{let s=await Bo(e.design_conversation_id);if(s.status==="ready")return{status:"design_clarify",design_conversation_id:e.design_conversation_id,directions:s.directions,plan:s.plan,methodology:s.methodology};if(s.status==="failed")return{status:"ready",plan:s.plan,methodology:s.methodology}}catch(s){let i=s instanceof Error?s.message:String(s);if(i.toLowerCase().includes("not found"))return{status:"ready",plan:e.plan,methodology:e.methodology};console.error(`[plan] directions poll attempt ${o+1} failed: ${i}`)}await new Promise(s=>setTimeout(s,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:e.plan,methodology:e.methodology}}async function Zl(e,t){let{description:r,projectPath:o,conversationId:s,answers:i,existingPlan:n,existingPlanId:a,templateToken:l,remixDescription:c,autonomous:h,language:m,landingDesign:p,appStyle:f,brandMentioned:S,confirmToken:b,urlChoice:y,designConversationId:k,designDirection:I}=e;if(s&&!r&&!i&&!k&&!I&&!n&&!a&&!l)try{let u=await Xt(s);if(u.status==="clarify_pending"||u.status==="plan_pending"){let g=typeof u.phase_hint=="string"?u.phase_hint:null,x=typeof u.elapsed_seconds=="number"?u.elapsed_seconds:null,C=typeof u.progress=="number"?u.progress:null,W=u.status==="plan_pending",H=W?"generating_plan":"generating_questions",Q=g?`${g}${x!==null?` (${x}s elapsed)`:""}`:W?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return d(JSON.stringify({status:"running",conversationId:s,phase:H,...g?{phaseHint:g}:{},...x!==null?{elapsedSeconds:x}:{},...C!==null?{progress:C}:{},nextAction:`${Q}. Tell the user briefly what's happening (e.g. "${g??(W?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${s}" } 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.`}))}return d(JSON.stringify(u))}catch(u){let g=u instanceof Error?u.message:String(u);return d(`Could not poll plan conversation '${s}': ${g}`,!0)}let R=r??"";if(!R.trim()&&!s&&!k&&!n&&!a&&!l)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(k&&!I&&!R.trim()&&!i)return d(`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 P=n;if(!P&&a&&(P=Ql(a)??void 0,!P))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let M=s;if(!ae())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let F;if(!M&&!P&&!l){if(!Fl(o))return d(`projectPath must be an absolute path \u2014 received '${o}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let u=Vl(o);if(u!=="mistflow"&&Kl(o))return d(JSON.stringify({status:"unsafe_cwd",projectPath:o,instruction:[`The projectPath you passed (${o}) 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 ${o}/<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(`
2232
- `)}),!0);if(u==="foreign"&&!(b?Gl(b,o,R):!1)){let x=Wl(o,R),C=R.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().split(/\s+/).slice(0,3).join("-").slice(0,40)||"new-app",W=de(o,C);if(t?.server){let H=await mo(t.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
2226
+ `}var pl,ul,ml,Un=A(()=>{"use strict";pl=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],ul=["sharp","soft","pill","organic"],ml=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"]});import{z as M}from"zod";import{existsSync as kt,mkdirSync as to,readFileSync as $n,readdirSync as bl,statSync as wl,unlinkSync as vl,writeFileSync as oo}from"fs";import{dirname as kl,isAbsolute as xl,join as le}from"path";import{homedir as Ue}from"os";import{createHash as Sl,createHmac as Fn,randomBytes as Tl,randomUUID as Ln,timingSafeEqual as Pl}from"crypto";function qn(){let t=le(Ue(),".mistflow","confirm-secret");if(kt(t))try{return Buffer.from($n(t,"utf-8").trim(),"hex")}catch{}let e=Tl(32);return to(le(Ue(),".mistflow"),{recursive:!0}),oo(t,e.toString("hex"),{mode:384}),e}function Bn(t){return Sl("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function Il(t,e){let r={cwd:t,d:Bn(e),exp:Date.now()+Cl},o=Buffer.from(JSON.stringify(r)).toString("base64url"),s=Fn("sha256",qn()).update(o).digest("base64url");return`${o}.${s}`}function Al(t,e,r){let o=t.split(".");if(o.length!==2)return!1;let[s,i]=o,n=Fn("sha256",qn()).update(s).digest("base64url"),a=Buffer.from(i),l=Buffer.from(n);if(a.length!==l.length||!Pl(a,l))return!1;try{let c=JSON.parse(Buffer.from(s,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==e||c.d!==Bn(r))}catch{return!1}}function _l(t){let e=t,r=Ue(),o=!1;for(let s=0;s<64;s++){if(kt(le(e,"mistflow.json")))return"mistflow";if(!o&&kt(le(e,"package.json"))&&(o=!0),e===r)break;let i=kl(e);if(i===e)break;e=i}return o?"foreign":"none"}function Rl(t){let e=Ue(),r=t.replace(/\/+$/,"");if(r===e||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let o=["Desktop","Documents","Downloads"];for(let s of o)if(r===le(e,s))return!0;return!1}function Nl(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[o,s]of e)if(o.test(t))return s;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(o=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(o.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function Dl(t){let e=le(Ue(),".mistflow","plans",`${t}.json`);if(!kt(e))return null;try{return JSON.parse($n(e,"utf-8")).plan??null}catch{return null}}async function jl(t){for(let o=0;o<60;o++){try{let s=await Ro(t.design_conversation_id);if(s.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:s.directions,plan:s.plan,methodology:s.methodology};if(s.status==="failed")return{status:"ready",plan:s.plan,methodology:s.methodology}}catch(s){let i=s instanceof Error?s.message:String(s);if(i.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll attempt ${o+1} failed: ${i}`)}await new Promise(s=>setTimeout(s,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:t.plan,methodology:t.methodology}}async function Ol(t,e){let{description:r,projectPath:o,conversationId:s,answers:i,existingPlan:n,existingPlanId:a,templateToken:l,remixDescription:c,autonomous:m,language:p,brandMentioned:u,confirmToken:w,urlChoice:D,designConversationId:x,designDirection:S}=t;if(s&&!r&&!i&&!x&&!S&&!n&&!a&&!l)try{let h=await $t(s);if(h.status==="clarify_pending"||h.status==="plan_pending"){let b=typeof h.phase_hint=="string"?h.phase_hint:null,y=typeof h.elapsed_seconds=="number"?h.elapsed_seconds:null,v=typeof h.progress=="number"?h.progress:null,B=h.status==="plan_pending",g=B?"generating_plan":"generating_questions",k=b?`${b}${y!==null?` (${y}s elapsed)`:""}`:B?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return d(JSON.stringify({status:"running",conversationId:s,phase:g,...b?{phaseHint:b}:{},...y!==null?{elapsedSeconds:y}:{},...v!==null?{progress:v}:{},nextAction:`${k}. Tell the user briefly what's happening (e.g. "${b??(B?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${s}" } 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.`}))}return d(JSON.stringify(h))}catch(h){let b=h instanceof Error?h.message:String(h);return d(`Could not poll plan conversation '${s}': ${b}`,!0)}let f=r??"";if(!f.trim()&&!s&&!x&&!n&&!a&&!l)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(x&&!S&&!f.trim()&&!i)return d(`You passed designConversationId='${x}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${x}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let _=n;if(!_&&a&&(_=Dl(a)??void 0,!_))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let L=s;if(!ie())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let W;if(!L&&!_&&!l){if(!xl(o))return d(`projectPath must be an absolute path \u2014 received '${o}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let h=_l(o);if(h!=="mistflow"&&Rl(o))return d(JSON.stringify({status:"unsafe_cwd",projectPath:o,instruction:[`The projectPath you passed (${o}) 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 ${o}/<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(`
2227
+ `)}),!0);if(h==="foreign"&&!(w?Al(w,o,f):!1)){let y=Il(o,f),v=f.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().split(/\s+/).slice(0,3).join("-").slice(0,40)||"new-app",B=le(o,v);if(e?.server){let g=await Xt(e.server,[{question:"You're inside an existing project. Where should Mistflow scaffold the new app?",decisionKey:"scopeChoice",recommended:`Create at: ${B}`,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: ${B}`,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
2233
2228
 
2234
2229
  You're inside \`${o}\` which has a \`package.json\`. Mistflow will create a NEW app in a subdirectory \u2014 it won't modify the existing code.
2235
2230
 
2236
- Default path: \`${W}\``);if(H.outcome==="submitted"){let Q=H.answers?.[0]?.answer??"",Z=Q.toLowerCase(),Le=Q.startsWith("/")?Q:null;if(Le||Z.startsWith("create at:")||Z.startsWith("choose a different path")){let xe=Le||(Z.startsWith("choose a different path")?null:W);if(!xe)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);F=`Note: Mistflow will scaffold the new app at \`${xe}\`. The existing project at \`${o}\` is not modified. When the user runs mist_init later, pass path: "${xe}".`}else return Z.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: ${Q}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return H.outcome==="declined"||H.outcome==="cancelled"?d("User cancelled the scope confirmation. They didn't pick \u2014 ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.",!0):d(JSON.stringify({status:"confirm_new_project",projectPath:o,description:R,confirmToken:x,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 in this folder 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) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","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.",b?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
2237
- `)}))}else return d(JSON.stringify({status:"confirm_new_project",projectPath:o,description:R,confirmToken:x,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 in this folder 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) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","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.",b?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
2238
- `)}))}}if(l)try{if(!(await rr(l)).plan)return d("This template has no plan to fork. Try a different template.",!0);let g=await nr(l),x=g.plan,C="";if(c&&g.has_source)try{let ce=await eo(g.plan,c),Y=ce.plan??ce,K=ce.diff,ke=Y?.steps??[],je=new Set([...(K?.added??[]).map(Se=>Se.number),...(K?.modified??[]).map(Se=>Se.number)]),ne=ke.map(Se=>{let Ji=Se.number;return je.has(Ji)?{...Se,status:"pending"}:{...Se,status:"completed",source:"forked"}});Y.steps=ne,x=Y;let se=ne.filter(Se=>Se.status==="pending").length;C=` Remixed: ${ne.filter(Se=>Se.status==="completed").length} steps unchanged, ${se} steps need re-implementation.`}catch(ce){console.error("[plan] Remix failed, using original plan:",ce),C=" (Remix failed \u2014 using original plan. You can modify it later.)"}let W=os(),H=de(Ke(),".mistflow","plans");fo(H,{recursive:!0}),yo(de(H,`${W}.json`),JSON.stringify({plan:x,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let Q=x?.name??"forked-app",Z=g.has_source,Le=Z?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",xe=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:W,forkedFrom:g.forked_from,projectId:g.id,hasSource:Z,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${C}${xe} ${Le} NEXT: Call mist_init, name='${Q}', and planId='${W}' to create the project now.`}))}catch(u){let g=u instanceof Error?u.message:"Failed to fork template";return d(g,!0)}if(P){let u;try{u=await eo(P,R)}catch(H){let Q=H instanceof Error?H.message:"Failed to modify plan";return d(Q,!0)}let g=u.plan,x=u.diff,C=[];if(x?.added?.length){let H=x.added.map(Q=>Q.title);C.push(`Added ${H.length} step(s): ${H.join(", ")}`)}if(x?.removed?.length){let H=x.removed.map(Q=>Q.title);C.push(`Removed ${H.length} step(s): ${H.join(", ")}`)}if(x?.modified?.length){let H=x.modified.map(Q=>Q.title);C.push(`Modified ${H.length} step(s): ${H.join(", ")}`)}let W=C.length>0?C.join(". "):"No changes detected.";return d(JSON.stringify({plan:g,diff:x,message:`Plan modified. ${W}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let v=y?.trim()||void 0,U=i;if(Array.isArray(i)){let u=i.findIndex(g=>g&&typeof g=="object"&&g.decisionKey==="urlChoice");if(u>=0){let g=i[u];!v&&g.answer&&(v=g.answer);let x=i.slice(0,u).concat(i.slice(u+1));U=x.length>0?x:void 0}}else if(i!=null){let u=i;if(!v&&go in u&&(v=u[go]),!v&&"urlChoice"in u&&(v=u.urlChoice),go in u||"urlChoice"in u){let{[go]:g,urlChoice:x,...C}=u;U=Object.keys(C).length>0?C:void 0}}if(v&&(v=v.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),v){let u=v.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(u)?v=u:(console.error(`[mist_plan] Discarding urlChoice '${v}' \u2014 does not look like a subdomain. Backend will auto-generate.`),v=void 0)}let G;if(I){G={...I};let u={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,x]of Object.entries(u))I[g]!==void 0&&G[x]===void 0&&(G[x]=I[g])}let V=i?"Generating plan with your answers (LLM call)":k?"Finalizing design direction":"Thinking through discovery questions",oe=t?Oe(t.server,t.progressToken,()=>V):{stop:()=>{}};t&&(t.cleanup=()=>oe.stop());let D;try{M&&!U&&!k&&!P&&!a?D=await Xt(M):D=await Zt(R,{conversationId:M,answers:U,autonomous:h,language:m,designConversationId:k,designDirection:G})}catch(u){oe.stop();let g=u instanceof Error?u.message:"Failed to generate plan";return d(g,!0)}if(D.status==="clarify_pending"){oe.stop();let u=D;return d(JSON.stringify({status:"running",conversationId:u.conversation_id,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${u.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.`}))}if(D.status==="plan_pending"){oe.stop();let u=D;return d(JSON.stringify({status:"running",conversationId:u.conversation_id,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${u.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(D.status==="design_clarify_pending"&&(V="Generating creative design directions",D=await Xl(D)),oe.stop(),D.status==="clarify"){let u=D.reflection||"",g=D.suggestedName||"",x=D.suggestedFeatures??[],C=D.questions??[],W=C.some(K=>Array.isArray(K.options)&&typeof K.options[0]=="object"&&K.options[0]?.label),H={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"},Q=C.map(K=>{let ke=K.decisionKey&&H[K.decisionKey]||Yl(K.question),je;return W&&Array.isArray(K.options)?je=K.options.map(ne=>({label:ne.label,description:ne.description??""})):Array.isArray(K.options)?je=K.options.map((ne,se)=>({label:se===0?`${ne} (Recommended)`:String(ne),description:K.why??""})):je=[{label:"Yes (Recommended)",description:K.why??""},{label:"No",description:""}],{question:K.question,header:ke,options:je,multiSelect:!1}}),Le=D.decisions?.audienceType??null,xe=x.length>0?Yn(R,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:Le,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:x,language:m}):null,ce=xe?Qn(xe):"",Y=ho(g||"my-app").slice(0,32);try{let K=await Qt(Y);!K.available&&K.suggestion&&(Y=K.suggestion)}catch{}if(ce&&(ce+=`
2239
-
2240
- **Your app URL (you can change this before scaffolding):** https://${Y}.mistflow.app`),t?.server){let K=[g?`## ${g}`:"## Pick a few details","",`${C.length} quick question${C.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
2241
- `),ke=await mo(t.server,C,K);if(ke.outcome==="submitted"){oe.stop();let je={};for(let se of ke.answers??[])se.decisionKey?je[se.decisionKey]=se.answer:je[se.question]=se.answer;let ne=ke.urlChoice?.trim();ne&&(ne=ne.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let se=await Zt(R,{conversationId:D.conversation_id,answers:je,autonomous:h,language:m});if(se.status==="plan_pending"){let St=se;return d(JSON.stringify({status:"running",conversationId:St.conversation_id,phase:"generating_plan",...ne?{urlChoice:ne}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${St.conversation_id}"${ne?`, urlChoice: "${ne}"`:""} } 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.`}))}D=se}catch(se){let St=se instanceof Error?se.message:String(se);return d(`Submitting your answers failed: ${St}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(ke.outcome==="declined")return oe.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(ke.outcome==="cancelled")return oe.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);ke.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${ke.errorMessage}) \u2014 falling back to prose flow.`)}}return d(JSON.stringify({status:"clarify",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:D.conversation_id,questions:C,questionCount:C.length,suggestedFeatures:x,suggestedName:g,suggestedSubdomain:Y,reflection:u,briefText:ce,askUserQuestions:Q,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: "${D.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: "${Y}".`,'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.',...u||ce?["","\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",...u?[u]:[],...ce?["",ce]:[]]:[],...F?["",F]:[]].join(`
2242
- `)}))}if(D.status==="design_clarify"){let u=D.directions??[],g=D.plan.name??"your app",x;try{let Z=u.map(Y=>({id:Y.id,name:Y.name,summary:Y.summary,hero_headline:Y.hero_headline,cta_text:Y.cta_text,body_sample:Y.body_sample,fonts:Y.fonts,colors:Y.colors,hero_treatment:Y.hero_treatment,shape_lang:Y.shape_lang,texture:Y.texture,decoration_hint:Y.decoration_hint})),Le=es(g,Z),xe=de(o,".mistflow");fo(xe,{recursive:!0});let ce=de(xe,"design-directions.html");yo(ce,Le,"utf-8"),x=ce}catch(Z){console.error(`[mist_plan] design-directions preview render failed: ${Z instanceof Error?Z.message:String(Z)}`)}let C=u.map(Z=>({label:Z.name,description:`${Z.summary} \u2014 ${Z.fonts?.display??""} + ${Z.fonts?.body??""}`}));C.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let W={question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:C,multiSelect:!1},H=x?[`A visual preview of all ${u.length} directions has been written to:`,` ${x}`,"Each card is rendered in its direction's own fonts + palette so the user can see what they're picking \u2014 the picker is meaningless without it.","","OPEN THE PREVIEW NOW. Pick whichever works in your host:",` \u2022 macOS: run open "${x}"`,` \u2022 Linux: run xdg-open "${x}"`,` \u2022 Windows: run start "" "${x}"`," \u2022 No shell access: tell the user the exact path and ask them to open it in their browser before they answer.",'Do NOT skip the preview. "I described the options in text" is NOT a replacement \u2014 the user needs to SEE the directions.'].join(`
2243
- `):"No visual preview rendered (see server logs). The question options below carry fonts + mood so the user can still pick, but warn them the HTML preview didn't land.",Q=x?`open "${x}"`:"";return d(JSON.stringify({status:"design_clarify",designConversationId:D.design_conversation_id,directions:u,previewPath:x,askUserQuestion:W,instruction:[`The plan for "${g}" is ready. I've proposed ${u.length} creative directions \u2014 each commits to a specific aesthetic (fonts, colors, voice).`,"","\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 PICK A DIRECTION YOURSELF. THE USER PICKS.","\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","",H,Q?`Run this command to open the preview for the user: ${Q}`:"","","Then ASK THE USER which direction they want. Use whichever your host supports:"," \u2022 Claude Code \u2192 AskUserQuestion tool with the directionQuestion payload above"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) OR any host without a native question tool:"," STOP your turn. Print the direction names + one-line summaries as a"," numbered chat message and wait for the user's reply. Do NOT resume.","","What NOT to do (these have all happened in production transcripts and are unacceptable):"," \u2717 'I'll go with a custom ops-focused brief that fits better than the default.'"," (auto-picking a direction the user never chose)"," \u2717 'Submitting a custom design brief now so we can keep moving.'"," \u2717 Calling mist_plan with designDirection: { custom: '<your own description>' }"," because the user didn't respond fast enough."," \u2717 Skipping this picker because you already decided on the design yourself."," \u2717 Opening the HTML preview but not actually asking the user anything.","","Once the user picks a direction, call mist_plan with:",` designConversationId: "${D.design_conversation_id}"`," designDirection: <the full direction object from the 'directions' array that the user picked>","(No description needed \u2014 server has it from the first call.)","","IF the user picks 'Describe your own direction':"," Ask them a short open question ('How should the app feel? Any fonts or colors in mind?'),"," wait for a real answer, then call mist_plan with"," designDirection: { custom: '<their exact words>' } + the same designConversationId.","","The next mist_plan call takes ~10-20s \u2014 that's the LLM generating the final DESIGN.md with the picked direction. Tell the user 'Locking in the direction now \u2014 this takes about 15 seconds.' before calling."].filter(Boolean).join(`
2244
- `)}))}let j=D.plan,ie=j.name??"Untitled App",he=D.methodology,O=j.steps;if(!Array.isArray(O)||O.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 X=j.suggestedSubdomain??ho(ie).slice(0,32)??"my-app";if(!v&&t?.server){try{let g=await Qt(X);!g.available&&g.suggestion&&(X=g.suggestion)}catch{}let u=await mo(t.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${X}.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 ${X}.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"}],`## ${ie} \u2014 pick the URL
2245
-
2246
- The plan is ready. One last decision before I scaffold: what's the app's URL?`);if(u.outcome==="submitted"){let g=u.urlChoice?.trim()||u.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=X);let x=g.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(x)?v=x:(console.error(`[mist_plan] URL elicitation returned '${g}' \u2014 does not look like a subdomain. Using default '${X}'.`),v=X)}else u.outcome==="declined"||u.outcome,v=X}else v||(v=X);let fe=j.publicPages;if(!fe||Array.isArray(fe)&&fe.length===0){let u=j.pages,g=O.some(C=>typeof C.name=="string"&&C.name.toLowerCase().includes("landing")||typeof C.title=="string"&&C.title.toLowerCase().includes("landing")),x=Array.isArray(u)&&u.some(C=>C.path==="/"||C.route==="/");g||x?fe=["/","/pricing"]:fe=["/"]}let Re=j.primaryAction;if(!Re){let u=j.features;if(Array.isArray(u)&&u.length>0){let x=u.find(W=>typeof W.priority=="string"&&W.priority.toLowerCase()==="must-have")??u[0];Re={entity:x.name??x.title??"item",action:"create",fromPage:"/dashboard"}}}let Ne=j.nonNegotiables;(!Ne||Array.isArray(Ne)&&Ne.length===0)&&(Ne=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Fe=os(),J=de(Ke(),".mistflow","plans");fo(J,{recursive:!0});try{let g=Date.now();for(let x of[J,de(Ke(),".mistflow","mockup-state")])if(Ot(x))for(let C of Ml(x))try{let W=de(x,C),H=Ll(W).mtimeMs;g-H>6048e5&&Ul(W)}catch{}}catch{}let N;if(p){let u=no(p);u?N=u.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let B=f||void 0,ye=!!N,pe=O.some(u=>{let g=`${u.name??u.title} ${u.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),re=!ye&&pe?An(R,{maxResults:2}):[];re.length>0&&(N=re[0].id,console.error(`Auto-assigned landing layout preset (default): ${re[0].title} (${N})`));let Qe={name:j.name,summary:j.summary,dataModel:j.dataModel,pages:j.pages,features:j.features,steps:O.map(u=>({...u,name:u.name??u.title})),design:j.design,landingDesign:N,appStyle:B,dbProvider:j.dbProvider??"neon",authModel:j.authModel,audienceType:j.audienceType??"b2c",roles:j.roles,defaultRole:j.defaultRole,publicPages:fe,navStyle:j.navStyle,multiTenant:j.multiTenant,primaryAction:Re,nonNegotiables:Ne,requestedSubdomain:v,...m&&m.toLowerCase()!=="english"?{language:m}:{}};yo(de(J,`${Fe}.json`),JSON.stringify({plan:Qe,methodology:he}));let st=O.map(u=>`${u.number}. ${u.name??u.title}`),it="",be=[],Ee;!ye&&re.length>0&&(be=re.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${ct()}/designs?tab=landing-designs`})),Ee={question:"What landing page style fits this app?",header:"Landing Design",options:[...re.map((g,x)=>({label:x===0?`${g.title} (Recommended)`:g.title,description:g.description})),{label:"Design from scratch (Creative)",description:"No template \u2014 the AI designs a bespoke hero from your app's concept using 3D, scroll-driven animation, or particle effects. Higher creative ceiling, takes ~10 min longer, occasionally needs a second pass."},{label:"Browse all landing designs",description:`Not sure? See all landing designs at ${ct()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},it=` REQUIRED: ask the user which landing design they want using the AskUserQuestion tool with the 'landingDesignQuestion' object before calling mist_init. Do NOT assume the recommended option \u2014 the user may want a different style than we inferred. Recommended: ${re.map(g=>g.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_init. If they pick a specific preset title, look up its ID via mist_project action='landing-designs' and pass that. If they pick the recommended option, pass landingDesign='${re[0].id}' explicitly.`);let Xe="",qe=[],w=void 0,z=(j.audienceType??"b2c")==="b2c",te={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:z?"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:z?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},De=" 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.",ve="",E=[];for(let u of O){let g=u.name??u.title,x=u.integrationId;if(x){let C=ht(x);if(C){let W=gt(C.id);E.push({step:g,presetId:C.id,presetName:C.name,envVars:W?.envVars??[]})}}}if(E.length>0){let u=E.flatMap(C=>C.envVars),g=[...new Set(u.map(C=>C.key))];ve=` This plan uses integrations (${E.map(C=>C.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 d(JSON.stringify({planId:Fe,name:j.name,summary:j.summary,stepCount:O.length,steps:st,design:j.design,...N?{landingDesign:N}:{},...B?{appStyle:B}:{},...qe.length>0?{recommendedAppStyles:qe}:{},...w?{appStyleQuestion:w}:{},...be.length>0?{recommendedLandingDesigns:be}:{},...Ee?{landingDesignQuestion:Ee}:{},heroPhotoQuestion:te,...E.length>0?{integrations:E.map(u=>({step:u.step,preset:u.presetId,name:u.presetName,envVars:u.envVars}))}:{},message:`Plan generated for "${ie}" (${O.length} steps).${N?` Landing layout "${N}" set as default.`:""}${B?` App style "${B}" will be applied across all pages.`:""}${ve}${Xe}${it}${De}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,O.length*3)}\u2013${O.length*5} minutes total across ${O.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: '${Fe}' }). If the user says skip or "just build it", call mist_init({ planId: '${Fe}', path: '<absolute path>' }) immediately.`,...F?{warning:F}:{}}))}var go,Hl,Jl,as,ls=T(()=>{"use strict";ee();ge();bt();Jn();ur();so();Xn();ts();go="__mistflow_url_choice__",Hl=600*1e3;Jl=_.object({description:_.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:_.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."),conversationId:_.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:_.union([_.record(_.string()),_.array(_.object({question:_.string().optional(),decisionKey:_.string().optional(),answer:_.string()}))]).optional().describe("User's answers to the clarifying questions. Preferred shape: array of { question, decisionKey, answer } objects (supports duplicate decisionKeys). Legacy shape: { '<question text>': '<answer label>' } object map. Both are accepted; the server normalizes either."),existingPlan:_.record(_.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:_.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:_.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:_.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:_.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."),landingDesign:_.string().optional().describe("ID of a curated landing page design for the hero section. When set, the design's detailed blueprint (colors, fonts, layout, animations) is injected during the landing page implementation step. Use mist_project with action='landing-designs' to browse available landing designs."),appStyle:_.string().optional().describe("ID of a full-app style (e.g. 'stripe', 'linear', 'vercel', 'notion'). When set, the style's color palette, typography, component specs, shadows, and layout rules are injected during ALL implementation steps for consistent brand-quality design across every page. Use mist_project with action='app-styles' to browse available app styles."),language:_.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:_.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:_.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:_.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. The answers-dict magic key is deprecated and unreliable."),designConversationId:_.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:_.object({id:_.string().optional(),name:_.string().optional(),summary:_.string().optional(),heroHeadline:_.string().optional(),ctaText:_.string().optional(),bodySample:_.string().optional(),fontsHint:_.string().optional(),fonts:_.object({display:_.string(),body:_.string()}).partial().optional(),colorMood:_.string().optional(),colors:_.object({bg:_.string(),fg:_.string(),accent:_.string()}).partial().optional(),heroTreatment:_.string().optional(),shapeLang:_.string().optional(),texture:_.string().optional(),decorationHint:_.string().optional(),custom:_.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass the FULL direction object the user chose (all fields from the 'directions' array). If the user wrote their own description instead of picking one, pass { custom: '<their description>' } and omit the other fields.")});as={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').","","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). When that happens AND brandMentioned is not set, the handler 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 and confirmToken set to the token from the response.","\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. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","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. Pass appStyle (53 full-app design systems like 'stripe', 'linear') to apply a design system. Browse via mist_project action='app-styles'. Landing layout presets are auto-assigned based on app description."].join(`
2247
- `),inputSchema:Jl,handler:Zl}});function cs(e){if(!e)return"Item";let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return t.length===0?"Item":t.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}function ec(e){return e&&e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function tc(e){let t=cs(e);return t.charAt(0).toLowerCase()+t.slice(1)}function kr(){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(`
2248
- `)}function ds(){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(`
2249
- `)}function Sr(e){let t=ds();if(e.includes(xr)){let o=e.indexOf(xr),s=ps,i=e.indexOf(s,o);if(i===-1)return e.slice(0,o)+t;let n=e.slice(i+s.length);return e.slice(0,o)+t+n.replace(/^\n+/,"")}return e.replace(/\s+$/,"")+`
2250
-
2251
- `+t}function Tr(e,t){let r=cs(e),o=t??tc(e);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${o} } 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(${o});`,`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(${o}).omit({`," id: true,"," createdAt: true,","});",`export type Create${r}Input = z.infer<typeof Create${r}Input>;`,""].join(`
2252
- `)}function Pr(e){return`contracts/${ec(e)}.ts`}var xr,ps,Cr=T(()=>{"use strict";xr="<!-- mist:contracts:start -->",ps="<!-- mist:contracts:end -->"});import{z as Mt}from"zod";import{existsSync as ot,mkdirSync as Ir,writeFileSync as Ar,readFileSync as wo,readdirSync as hs,copyFileSync as oc}from"fs";import{join as Ie,resolve as gs,dirname as Lt,isAbsolute as rc}from"path";import{homedir as nc}from"os";import{spawn as vm}from"child_process";import{randomBytes as sc}from"crypto";import{simpleGit as ac}from"simple-git";function ic(e){let t=Ie(nc(),".mistflow","plans",`${e}.json`);if(!ot(t))return null;try{let r=JSON.parse(wo(t,"utf-8"));return r.plan?{plan:r.plan}:null}catch{return null}}function lc(e){let t=Lt(gs(e)),r=10,o=0;for(;o<r&&t!==Lt(t);){if(ot(Ie(t,"pnpm-workspace.yaml"))||ot(Ie(t,"lerna.json")))return t;let s=Ie(t,"package.json");if(ot(s))try{if(JSON.parse(wo(s,"utf-8")).workspaces)return t}catch{}t=Lt(t),o++}return null}function L(e,t,r){let o=Ie(e,t);Ir(Lt(o),{recursive:!0}),Ar(o,r)}function dc(e){if(!ot(e))return!0;let t;try{t=hs(e)}catch{return!1}return t.filter(o=>o!==".mistflow").length===0}function mc(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let r=t[1],o={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},s=r.split(`
2253
- `),i=null,n=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of s){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let p=a(c.slice(6).trim());(p==="dark"||p==="light")&&(o.theme=p);continue}let h=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(h){i=h[1],n=null;continue}if(i==="typography"){let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(p){n=p[1].replace(/-/g,"_"),o.typography[n]={};continue}let f=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(f&&n){o.typography[n][f[1]]=a(f[2]);continue}}let m=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(m&&i){let p=m[1].replace(/-/g,"_"),f=a(m[2]);i==="colors"?o.colors[p]=f:i==="rounded"?o.rounded[p]=f:i==="spacing"&&(o.spacing[p]=f)}}return o}function hc(e,t){let r=e.colors,s=[["--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(`
2254
- `),i=[` --radius-sm: ${e.rounded.sm??"0.25rem"};`,` --radius-md: ${e.rounded.md??t};`,` --radius-lg: ${e.rounded.lg??"0.5rem"};`,` --radius-xl: ${e.rounded.xl??"0.75rem"};`].join(`
2231
+ Default path: \`${B}\``);if(g.outcome==="submitted"){let k=g.answers?.[0]?.answer??"",N=k.toLowerCase(),K=k.startsWith("/")?k:null;if(K||N.startsWith("create at:")||N.startsWith("choose a different path")){let ee=K||(N.startsWith("choose a different path")?null:B);if(!ee)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);W=`Note: Mistflow will scaffold the new app at \`${ee}\`. The existing project at \`${o}\` is not modified. When the user runs mist_init later, pass path: "${ee}".`}else return N.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: ${k}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return g.outcome==="declined"||g.outcome==="cancelled"?d("User cancelled the scope confirmation. They didn't pick \u2014 ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.",!0):d(JSON.stringify({status:"confirm_new_project",projectPath:o,description:f,confirmToken:y,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 in this folder 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) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","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.",w?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
2232
+ `)}))}else return d(JSON.stringify({status:"confirm_new_project",projectPath:o,description:f,confirmToken:y,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 in this folder 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) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","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.",w?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
2233
+ `)}))}}if(l)try{if(!(await Wo(l)).plan)return d("This template has no plan to fork. Try a different template.",!0);let b=await Go(l),y=b.plan,v="";if(c&&b.has_source)try{let X=await qt(b.plan,c),P=X.plan??X,O=X.diff,Z=P?.steps??[],oe=new Set([...(O?.added??[]).map(ge=>ge.number),...(O?.modified??[]).map(ge=>ge.number)]),ne=Z.map(ge=>{let Ei=ge.number;return oe.has(Ei)?{...ge,status:"pending"}:{...ge,status:"completed",source:"forked"}});P.steps=ne,y=P;let se=ne.filter(ge=>ge.status==="pending").length;v=` Remixed: ${ne.filter(ge=>ge.status==="completed").length} steps unchanged, ${se} steps need re-implementation.`}catch(X){console.error("[plan] Remix failed, using original plan:",X),v=" (Remix failed \u2014 using original plan. You can modify it later.)"}let B=Ln(),g=le(Ue(),".mistflow","plans");to(g,{recursive:!0}),oo(le(g,`${B}.json`),JSON.stringify({plan:y,projectId:b.id,sourceDeploymentId:b.source_deployment_id,forkToken:b.fork_token,requiredEnvVars:b.required_env_vars,dbProvider:b.db_provider}));let k=y?.name??"forked-app",N=b.has_source,K=N?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",ee=b.deploy_url?` Instant deploy started \u2014 your app will be live at ${b.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:B,forkedFrom:b.forked_from,projectId:b.id,hasSource:N,deployUrl:b.deploy_url,message:`Forked "${b.forked_from}" into your workspace.${v}${ee} ${K} NEXT: Call mist_init, name='${k}', and planId='${B}' to create the project now.`}))}catch(h){let b=h instanceof Error?h.message:"Failed to fork template";return d(b,!0)}if(_){let h;try{h=await qt(_,f)}catch(g){let k=g instanceof Error?g.message:"Failed to modify plan";return d(k,!0)}let b=h.plan,y=h.diff,v=[];if(y?.added?.length){let g=y.added.map(k=>k.title);v.push(`Added ${g.length} step(s): ${g.join(", ")}`)}if(y?.removed?.length){let g=y.removed.map(k=>k.title);v.push(`Removed ${g.length} step(s): ${g.join(", ")}`)}if(y?.modified?.length){let g=y.modified.map(k=>k.title);v.push(`Modified ${g.length} step(s): ${g.join(", ")}`)}let B=v.length>0?v.join(". "):"No changes detected.";return d(JSON.stringify({plan:b,diff:y,message:`Plan modified. ${B}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let R=D?.trim()||void 0,J=i;if(Array.isArray(i)){let h=i.findIndex(b=>b&&typeof b=="object"&&b.decisionKey==="urlChoice");if(h>=0){let b=i[h];!R&&b.answer&&(R=b.answer);let y=i.slice(0,h).concat(i.slice(h+1));J=y.length>0?y:void 0}}else if(i!=null){let h=i;if(!R&&eo in h&&(R=h[eo]),!R&&"urlChoice"in h&&(R=h.urlChoice),eo in h||"urlChoice"in h){let{[eo]:b,urlChoice:y,...v}=h;J=Object.keys(v).length>0?v:void 0}}if(R&&(R=R.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),R){let h=R.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(h)?R=h:(console.error(`[mist_plan] Discarding urlChoice '${R}' \u2014 does not look like a subdomain. Backend will auto-generate.`),R=void 0)}let q;if(S){q={...S};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[b,y]of Object.entries(h))S[b]!==void 0&&q[y]===void 0&&(q[y]=S[b])}let T=i?"Generating plan with your answers (LLM call)":x?"Finalizing design direction":"Thinking through discovery questions",E=e?Te(e.server,e.progressToken,()=>T):{stop:()=>{}};e&&(e.cleanup=()=>E.stop());let C;try{L&&!J&&!x&&!_&&!a?C=await $t(L):C=await Ft(f,{conversationId:L,answers:J,autonomous:m,language:p,designConversationId:x,designDirection:q})}catch(h){E.stop();let b=h instanceof Error?h.message:"Failed to generate plan";return d(b,!0)}if(C.status==="clarify_pending"){E.stop();let h=C;return d(JSON.stringify({status:"running",conversationId:h.conversation_id,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.`}))}if(C.status==="plan_pending"){E.stop();let h=C;return d(JSON.stringify({status:"running",conversationId:h.conversation_id,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(C.status==="design_clarify_pending"&&(T="Generating creative design directions",C=await jl(C)),E.stop(),C.status==="clarify"){let h=C.reflection||"",b=C.suggestedName||"",y=C.suggestedFeatures??[],v=C.questions??[],B=v.some(O=>Array.isArray(O.options)&&typeof O.options[0]=="object"&&O.options[0]?.label),g={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"},k=v.map(O=>{let Z=O.decisionKey&&g[O.decisionKey]||Nl(O.question),oe;return B&&Array.isArray(O.options)?oe=O.options.map(ne=>({label:ne.label,description:ne.description??""})):Array.isArray(O.options)?oe=O.options.map((ne,se)=>({label:se===0?`${ne} (Recommended)`:String(ne),description:O.why??""})):oe=[{label:"Yes (Recommended)",description:O.why??""},{label:"No",description:""}],{question:O.question,header:Z,options:oe,multiSelect:!1}}),K=C.decisions?.audienceType??null,ee=y.length>0?Nn(f,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:K,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:b,suggestedFeatures:y,language:p}):null,X=ee?Dn(ee):"",P=Zt(b||"my-app").slice(0,32);try{let O=await Lt(P);!O.available&&O.suggestion&&(P=O.suggestion)}catch{}if(X&&(X+=`
2234
+
2235
+ **Your app URL (you can change this before scaffolding):** https://${P}.mistflow.app`),e?.server){let O=[b?`## ${b}`:"## Pick a few details","",`${v.length} quick question${v.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
2236
+ `),Z=await Xt(e.server,v,O);if(Z.outcome==="submitted"){E.stop();let oe={};for(let se of Z.answers??[])se.decisionKey?oe[se.decisionKey]=se.answer:oe[se.question]=se.answer;let ne=Z.urlChoice?.trim();ne&&(ne=ne.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let se=await Ft(f,{conversationId:C.conversation_id,answers:oe,autonomous:m,language:p});if(se.status==="plan_pending"){let lt=se;return d(JSON.stringify({status:"running",conversationId:lt.conversation_id,phase:"generating_plan",...ne?{urlChoice:ne}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${lt.conversation_id}"${ne?`, urlChoice: "${ne}"`:""} } 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.`}))}C=se}catch(se){let lt=se instanceof Error?se.message:String(se);return d(`Submitting your answers failed: ${lt}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(Z.outcome==="declined")return E.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(Z.outcome==="cancelled")return E.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);Z.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${Z.errorMessage}) \u2014 falling back to prose flow.`)}}return d(JSON.stringify({status:"clarify",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:C.conversation_id,questions:v,questionCount:v.length,suggestedFeatures:y,suggestedName:b,suggestedSubdomain:P,reflection:h,briefText:X,askUserQuestions:k,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: "${C.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: "${P}".`,'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||X?["","\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]:[],...X?["",X]:[]]:[],...W?["",W]:[]].join(`
2237
+ `)}))}if(C.status==="design_clarify"){let h=C.directions??[],b=C.plan.name??"your app",y;try{let N=h.map(P=>({id:P.id,name:P.name,summary:P.summary,hero_headline:P.hero_headline,cta_text:P.cta_text,body_sample:P.body_sample,fonts:P.fonts,colors:P.colors,hero_treatment:P.hero_treatment,shape_lang:P.shape_lang,texture:P.texture,decoration_hint:P.decoration_hint})),K=Mn(b,N),ee=le(o,".mistflow");to(ee,{recursive:!0});let X=le(ee,"design-directions.html");oo(X,K,"utf-8"),y=X}catch(N){console.error(`[mist_plan] design-directions preview render failed: ${N instanceof Error?N.message:String(N)}`)}let v=h.map(N=>({label:N.name,description:`${N.summary} \u2014 ${N.fonts?.display??""} + ${N.fonts?.body??""}`}));v.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let B={question:`${b} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:v,multiSelect:!1},g=y?[`A visual preview of all ${h.length} directions has been written to:`,` ${y}`,"Each card is rendered in its direction's own fonts + palette so the user can see what they're picking \u2014 the picker is meaningless without it.","","OPEN THE PREVIEW NOW. Pick whichever works in your host:",` \u2022 macOS: run open "${y}"`,` \u2022 Linux: run xdg-open "${y}"`,` \u2022 Windows: run start "" "${y}"`," \u2022 No shell access: tell the user the exact path and ask them to open it in their browser before they answer.",'Do NOT skip the preview. "I described the options in text" is NOT a replacement \u2014 the user needs to SEE the directions.'].join(`
2238
+ `):"No visual preview rendered (see server logs). The question options below carry fonts + mood so the user can still pick, but warn them the HTML preview didn't land.",k=y?`open "${y}"`:"";return d(JSON.stringify({status:"design_clarify",designConversationId:C.design_conversation_id,directions:h,previewPath:y,askUserQuestion:B,instruction:[`The plan for "${b}" is ready. I've proposed ${h.length} creative directions \u2014 each commits to a specific aesthetic (fonts, colors, voice).`,"","\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 PICK A DIRECTION YOURSELF. THE USER PICKS.","\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","",g,k?`Run this command to open the preview for the user: ${k}`:"","","Then ASK THE USER which direction they want. Use whichever your host supports:"," \u2022 Claude Code \u2192 AskUserQuestion tool with the directionQuestion payload above"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) OR any host without a native question tool:"," STOP your turn. Print the direction names + one-line summaries as a"," numbered chat message and wait for the user's reply. Do NOT resume.","","What NOT to do (these have all happened in production transcripts and are unacceptable):"," \u2717 'I'll go with a custom ops-focused brief that fits better than the default.'"," (auto-picking a direction the user never chose)"," \u2717 'Submitting a custom design brief now so we can keep moving.'"," \u2717 Calling mist_plan with designDirection: { custom: '<your own description>' }"," because the user didn't respond fast enough."," \u2717 Skipping this picker because you already decided on the design yourself."," \u2717 Opening the HTML preview but not actually asking the user anything.","","Once the user picks a direction, call mist_plan with:",` designConversationId: "${C.design_conversation_id}"`," designDirection: <the full direction object from the 'directions' array that the user picked>","(No description needed \u2014 server has it from the first call.)","","IF the user picks 'Describe your own direction':"," Ask them a short open question ('How should the app feel? Any fonts or colors in mind?'),"," wait for a real answer, then call mist_plan with"," designDirection: { custom: '<their exact words>' } + the same designConversationId.","","The next mist_plan call takes ~10-20s \u2014 that's the LLM generating the final DESIGN.md with the picked direction. Tell the user 'Locking in the direction now \u2014 this takes about 15 seconds.' before calling."].filter(Boolean).join(`
2239
+ `)}))}let I=C.plan,$=I.name??"Untitled App",U=C.methodology,j=I.steps;if(!Array.isArray(j)||j.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 F=I.suggestedSubdomain??Zt($).slice(0,32)??"my-app";if(!R&&e?.server){try{let b=await Lt(F);!b.available&&b.suggestion&&(F=b.suggestion)}catch{}let h=await Xt(e.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${F}.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 ${F}.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"}],`## ${$} \u2014 pick the URL
2240
+
2241
+ The plan is ready. One last decision before I scaffold: what's the app's URL?`);if(h.outcome==="submitted"){let b=h.urlChoice?.trim()||h.answers?.[0]?.answer.trim()||"";b=b.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(b)||!b)&&(b=F);let y=b.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(y)?R=y:(console.error(`[mist_plan] URL elicitation returned '${b}' \u2014 does not look like a subdomain. Using default '${F}'.`),R=F)}else h.outcome==="declined"||h.outcome,R=F}else R||(R=F);let H=I.publicPages;if(!H||Array.isArray(H)&&H.length===0){let h=I.pages,b=j.some(v=>typeof v.name=="string"&&v.name.toLowerCase().includes("landing")||typeof v.title=="string"&&v.title.toLowerCase().includes("landing")),y=Array.isArray(h)&&h.some(v=>v.path==="/"||v.route==="/");b||y?H=["/","/pricing"]:H=["/"]}let Y=I.primaryAction;if(!Y){let h=I.features;if(Array.isArray(h)&&h.length>0){let y=h.find(B=>typeof B.priority=="string"&&B.priority.toLowerCase()==="must-have")??h[0];Y={entity:y.name??y.title??"item",action:"create",fromPage:"/dashboard"}}}let te=I.nonNegotiables;(!te||Array.isArray(te)&&te.length===0)&&(te=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let xe=Ln(),Se=le(Ue(),".mistflow","plans");to(Se,{recursive:!0});try{let b=Date.now();for(let y of[Se,le(Ue(),".mistflow","mockup-state")])if(kt(y))for(let v of bl(y))try{let B=le(y,v),g=wl(B).mtimeMs;b-g>6048e5&&vl(B)}catch{}}catch{}let Q={name:I.name,summary:I.summary,dataModel:I.dataModel,pages:I.pages,features:I.features,steps:j.map(h=>({...h,name:h.name??h.title})),design:I.design,dbProvider:I.dbProvider??"neon",authModel:I.authModel,audienceType:I.audienceType??"b2c",roles:I.roles,defaultRole:I.defaultRole,publicPages:H,navStyle:I.navStyle,multiTenant:I.multiTenant,primaryAction:Y,nonNegotiables:te,requestedSubdomain:R,...p&&p.toLowerCase()!=="english"?{language:p}:{}};oo(le(Se,`${xe}.json`),JSON.stringify({plan:Q,methodology:U}));let Ce=j.map(h=>`${h.number}. ${h.name??h.title}`),Ae=(I.audienceType??"b2c")==="b2c",me={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:Ae?"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:Ae?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},Je=" 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.",Ye="",he=[];for(let h of j){let b=h.name??h.title,y=h.integrationId;if(y){let v=et(y);if(v){let B=tt(v.id);he.push({step:b,presetId:v.id,presetName:v.name,envVars:B?.envVars??[]})}}}if(he.length>0){let h=he.flatMap(v=>v.envVars),b=[...new Set(h.map(v=>v.key))];Ye=` This plan uses integrations (${he.map(v=>v.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${b.length>0?` The user will need these API keys: ${b.join(", ")}.`:""}`}return d(JSON.stringify({planId:xe,name:I.name,summary:I.summary,stepCount:j.length,steps:Ce,design:I.design,heroPhotoQuestion:me,...he.length>0?{integrations:he.map(h=>({step:h.step,preset:h.presetId,name:h.presetName,envVars:h.envVars}))}:{},message:`Plan generated for "${$}" (${j.length} steps).${Ye}${Je}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,j.length*3)}\u2013${j.length*5} minutes total across ${j.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: '${xe}' }). If the user says skip or "just build it", call mist_init({ planId: '${xe}', path: '<absolute path>' }) immediately.`,...W?{warning:W}:{}}))}var eo,Cl,El,zn,Hn=A(()=>{"use strict";re();de();nt();En();Wt();jn();Un();eo="__mistflow_url_choice__",Cl=600*1e3;El=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."),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.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. Preferred shape: array of { question, decisionKey, answer } objects (supports duplicate decisionKeys). Legacy shape: { '<question text>': '<answer label>' } object map. Both are accepted; the server normalizes either."),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. The answers-dict magic key is deprecated and unreliable."),designConversationId:M.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: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 the FULL direction object the user chose (all fields from the 'directions' array). If the user wrote their own description instead of picking one, pass { custom: '<their description>' } and omit the other fields.")});zn={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').","","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). When that happens AND brandMentioned is not set, the handler 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 and confirmToken set to the token from the response.","\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. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","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(`
2242
+ `),inputSchema:El,handler:Ol}});function Wn(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 Ml(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function Ul(t){let e=Wn(t);return e.charAt(0).toLowerCase()+e.slice(1)}function ar(){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(`
2243
+ `)}function Gn(){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(`
2244
+ `)}function lr(t){let e=Gn();if(t.includes(ir)){let o=t.indexOf(ir),s=Vn,i=t.indexOf(s,o);if(i===-1)return t.slice(0,o)+e;let n=t.slice(i+s.length);return t.slice(0,o)+e+n.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
2245
+
2246
+ `+e}function cr(t,e){let r=Wn(t),o=e??Ul(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${o} } 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(${o});`,`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(${o}).omit({`," id: true,"," createdAt: true,","});",`export type Create${r}Input = z.infer<typeof Create${r}Input>;`,""].join(`
2247
+ `)}function dr(t){return`contracts/${Ml(t)}.ts`}var ir,Vn,pr=A(()=>{"use strict";ir="<!-- mist:contracts:start -->",Vn="<!-- mist:contracts:end -->"});import{z as xt}from"zod";import{existsSync as Ve,mkdirSync as ur,writeFileSync as mr,readFileSync as no,readdirSync as Yn,copyFileSync as Ll}from"fs";import{join as we,resolve as Qn,dirname as St,isAbsolute as $l}from"path";import{homedir as Fl}from"os";import{spawn as nm}from"child_process";import{randomBytes as ql}from"crypto";import{simpleGit as zl}from"simple-git";function Bl(t){let e=we(Fl(),".mistflow","plans",`${t}.json`);if(!Ve(e))return null;try{let r=JSON.parse(no(e,"utf-8"));return r.plan?{plan:r.plan}:null}catch{return null}}function Hl(t){let e=St(Qn(t)),r=10,o=0;for(;o<r&&e!==St(e);){if(Ve(we(e,"pnpm-workspace.yaml"))||Ve(we(e,"lerna.json")))return e;let s=we(e,"package.json");if(Ve(s))try{if(JSON.parse(no(s,"utf-8")).workspaces)return e}catch{}e=St(e),o++}return null}function z(t,e,r){let o=we(t,e);ur(St(o),{recursive:!0}),mr(o,r)}function Gl(t){if(!Ve(t))return!0;let e;try{e=Yn(t)}catch{return!1}return e.filter(o=>o!==".mistflow").length===0}function Jl(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let r=e[1],o={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},s=r.split(`
2248
+ `),i=null,n=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of s){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")&&(o.theme=u);continue}let m=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(m){i=m[1],n=null;continue}if(i==="typography"){let u=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(u){n=u[1].replace(/-/g,"_"),o.typography[n]={};continue}let w=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(w&&n){o.typography[n][w[1]]=a(w[2]);continue}}let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(p&&i){let u=p[1].replace(/-/g,"_"),w=a(p[2]);i==="colors"?o.colors[u]=w:i==="rounded"?o.rounded[u]=w:i==="spacing"&&(o.spacing[u]=w)}}return o}function Yl(t,e){let r=t.colors,s=[["--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(`
2249
+ `),i=[` --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(`
2255
2250
  `);return`@import "tailwindcss";
2256
2251
  @import "tw-animate-css";
2257
2252
 
@@ -2307,11 +2302,11 @@ ${i}
2307
2302
 
2308
2303
  button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
2309
2304
  button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
2310
- `}function gc(e,t,r){let o=e?.borderRadius??"subtle",s=pc[o]??"0.375rem";if(r){let n=mc(r);if(n)return hc(n,s)}return`@import "tailwindcss";
2305
+ `}function Ql(t,e){let r=t?.borderRadius??"subtle",o=Vl[r]??"0.375rem";if(e){let i=Jl(e);if(i)return Yl(i,o)}return`@import "tailwindcss";
2311
2306
  @import "tw-animate-css";
2312
2307
 
2313
2308
  @theme {
2314
- ${[...uc.map(([n,a])=>` ${n}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md: ${s};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
2309
+ ${[...Kl.map(([i,n])=>` ${i}: ${n};`)," --radius-sm: 0.25rem;",` --radius-md: ${o};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
2315
2310
  `)}
2316
2311
  }
2317
2312
 
@@ -2361,7 +2356,7 @@ ${[...uc.map(([n,a])=>` ${n}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md:
2361
2356
 
2362
2357
  button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
2363
2358
  button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
2364
- `}function ms(e){let t=e.replace(/[^A-Za-z0-9_ -]/g,"");return us[t]?us[t]:t.replace(/\s+/g,"_")}function fc(e){return e?{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"}[e.toLowerCase()]??"en":"en"}function bc(e,t,r){let o=e.replace(/[\\"`$]/g,""),s=fc(r),n=yc.has(s)?`lang="${s}" dir="rtl"`:`lang="${s}"`,a=t?.fonts?.heading,l=t?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
2359
+ `}function Jn(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return Kn[e]?Kn[e]:e.replace(/\s+/g,"_")}function Xl(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 ec(t,e,r){let o=t.replace(/[\\"`$]/g,""),s=Xl(r),n=Zl.has(s)?`lang="${s}" dir="rtl"`:`lang="${s}"`,a=e?.fonts?.heading,l=e?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
2365
2360
  import { DM_Sans } from "next/font/google";
2366
2361
  import { Toaster } from "sonner";
2367
2362
  import "./globals.css";
@@ -2377,7 +2372,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2377
2372
  </html>
2378
2373
  );
2379
2374
  }
2380
- `;let c=ms(a??l),h=ms(l??a);return c===h?`import type { Metadata } from "next";
2375
+ `;let c=Jn(a??l),m=Jn(l??a);return c===m?`import type { Metadata } from "next";
2381
2376
  import { ${c} } from "next/font/google";
2382
2377
  import { Toaster } from "sonner";
2383
2378
  import "./globals.css";
@@ -2394,12 +2389,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2394
2389
  );
2395
2390
  }
2396
2391
  `:`import type { Metadata } from "next";
2397
- import { ${c}, ${h} } from "next/font/google";
2392
+ import { ${c}, ${m} } from "next/font/google";
2398
2393
  import { Toaster } from "sonner";
2399
2394
  import "./globals.css";
2400
2395
 
2401
2396
  const heading = ${c}({ subsets: ["latin"], variable: "--font-heading" });
2402
- const body = ${h}({ subsets: ["latin"], variable: "--font-body" });
2397
+ const body = ${m}({ subsets: ["latin"], variable: "--font-body" });
2403
2398
 
2404
2399
  export const metadata: Metadata = { title: "${o}", description: "Built with Mistflow" };
2405
2400
 
@@ -2410,63 +2405,63 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2410
2405
  </html>
2411
2406
  );
2412
2407
  }
2413
- `}function bo(e,...t){let r=JSON.stringify(e).toLowerCase();return t.some(o=>r.includes(o.toLowerCase()))}function _r(e){let t=e.toLowerCase().replace(/[^a-z]/g,"");for(let[r,o]of Object.entries(wc))if(t.includes(r))return o;return"Circle"}function Ut(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function vc(e){if(e.authModel==="none")return null;let t=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed"];if(e.publicPages&&Array.isArray(e.publicPages))for(let i of e.publicPages){if(typeof i!="string"||i.length<1)continue;let n=i.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!n)continue;let a=n.startsWith("/")?n:"/"+n;t.includes(a)||t.push(a)}let r=t.filter(i=>i==="/"),o=t.filter(i=>i!=="/"),s=[];s.push('import { NextRequest, NextResponse } from "next/server";'),s.push(""),s.push("const PUBLIC_PREFIXES = [");for(let i of o)s.push(' "'+i+'",');return s.push("];"),s.push(""),r.length>0&&(s.push('const PUBLIC_EXACT = ["'+r.join('", "')+'"];'),s.push("")),s.push("export function middleware(req: NextRequest) {"),s.push(" const { pathname, search } = req.nextUrl;"),s.push(""),r.length>0&&s.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),s.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),s.push(""),s.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),s.push(" if (!token) {"),s.push(' const loginUrl = new URL("/login", req.url);'),s.push(" const params = new URLSearchParams(search);"),s.push(' for (const key of ["verified", "error"]) {'),s.push(" const v = params.get(key);"),s.push(" if (v) loginUrl.searchParams.set(key, v);"),s.push(" }"),s.push(" return NextResponse.redirect(loginUrl);"),s.push(" }"),s.push(""),s.push(" return NextResponse.next();"),s.push("}"),s.push(""),s.push("export const config = {"),s.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),s.push("};"),s.push(""),s.join(`
2414
- `)}function xc(e){if(e.navStyle==="none")return null;let t=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],o=(e.pages??[]).filter(l=>{let c=l.path??l.route??"";return c==="/"||c===""||c.includes("[")||c.replace(/^\//,"").split("/").length>1?!1:!t.some(m=>c.startsWith(m))}).map(l=>{let c=l.path??l.route??"",h=c.startsWith("/")?c:"/"+c,m=l.name??Ut(c.replace(/^\//,"")),p=_r(m);return{label:m,href:h,icon:p}});o.some(l=>l.href==="/dashboard")||o.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let s=e.authModel==="none",i=[...new Set(o.map(l=>l.icon))];s||i.push("LogOut");let n=Ut(e.name);if(e.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),s||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 { "+i.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 o)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">'+n+"</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>"),s?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(`
2408
+ `}function ro(t,...e){let r=JSON.stringify(t).toLowerCase();return e.some(o=>r.includes(o.toLowerCase()))}function hr(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[r,o]of Object.entries(tc))if(e.includes(r))return o;return"Circle"}function Tt(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function oc(t){if(t.authModel==="none")return null;let e=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed"];if(t.publicPages&&Array.isArray(t.publicPages))for(let i of t.publicPages){if(typeof i!="string"||i.length<1)continue;let n=i.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!n)continue;let a=n.startsWith("/")?n:"/"+n;e.includes(a)||e.push(a)}let r=e.filter(i=>i==="/"),o=e.filter(i=>i!=="/"),s=[];s.push('import { NextRequest, NextResponse } from "next/server";'),s.push(""),s.push("const PUBLIC_PREFIXES = [");for(let i of o)s.push(' "'+i+'",');return s.push("];"),s.push(""),r.length>0&&(s.push('const PUBLIC_EXACT = ["'+r.join('", "')+'"];'),s.push("")),s.push("export function middleware(req: NextRequest) {"),s.push(" const { pathname, search } = req.nextUrl;"),s.push(""),r.length>0&&s.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),s.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),s.push(""),s.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),s.push(" if (!token) {"),s.push(' const loginUrl = new URL("/login", req.url);'),s.push(" const params = new URLSearchParams(search);"),s.push(' for (const key of ["verified", "error"]) {'),s.push(" const v = params.get(key);"),s.push(" if (v) loginUrl.searchParams.set(key, v);"),s.push(" }"),s.push(" return NextResponse.redirect(loginUrl);"),s.push(" }"),s.push(""),s.push(" return NextResponse.next();"),s.push("}"),s.push(""),s.push("export const config = {"),s.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),s.push("};"),s.push(""),s.join(`
2409
+ `)}function rc(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"],o=(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??Tt(c.replace(/^\//,"")),u=hr(p);return{label:p,href:m,icon:u}});o.some(l=>l.href==="/dashboard")||o.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let s=t.authModel==="none",i=[...new Set(o.map(l=>l.icon))];s||i.push("LogOut");let n=Tt(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";'),s||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 { "+i.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 o)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">'+n+"</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>"),s?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(`
2415
2410
  `)}}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";'),s||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, "+i.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 o)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">'+n+"</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>"),s||(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">'+n+"</span>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),{path:"components/sidebar.tsx",content:a.join(`
2416
- `)}}function kc(e){if(!e.roles||e.roles.length===0)return null;let t=e.roles,r=e.defaultRole??t[0],o=[];o.push("export type Role = "+t.map(s=>'"'+s+'"').join(" | ")+";"),o.push(""),o.push("export const ROLES = ["+t.map(s=>'"'+s+'"').join(", ")+"] as const;"),o.push(""),o.push('export const DEFAULT_ROLE: Role = "'+r+'";'),o.push(""),o.push("export const ROLE_LABELS: Record<Role, string> = {");for(let s of t){let i=s.charAt(0).toUpperCase()+s.slice(1);o.push(' "'+s+'": "'+i+'",')}return o.push("};"),o.push(""),o.push("export function getUserRole(user: Record<string, unknown>): Role {"),o.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),o.push(" if (ROLES.includes(role as Role)) return role as Role;"),o.push(" return DEFAULT_ROLE;"),o.push("}"),o.push(""),o.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),o.push(" if (!userRole) return false;"),o.push(" const allowed = Array.isArray(required) ? required : [required];"),o.push(" return allowed.includes(userRole as Role);"),o.push("}"),o.push(""),o.join(`
2417
- `)}function Sc(e){let t=Ut(e.name);if(e.authModel==="none"){let i=[];return i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),i.push(' <h1 className="text-4xl font-bold">'+t+"</h1>"),e.summary&&i.push(' <p className="mt-4 text-lg text-muted-foreground">'+e.summary+"</p>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
2418
- `)}let r=e.publicPages?.includes("/"),o=e.design?.landingTone;if(r&&o){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col">'),i.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),i.push(' <h1 className="text-5xl font-bold tracking-tight">'+t+"</h1>"),e.summary&&i.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+e.summary+"</p>"),i.push(' <div className="flex gap-4">'),i.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">'),i.push(" Get Started"),i.push(" </Link>"),i.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </div>"),i.push(" </section>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
2419
- `)}if(r){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),i.push(' <h1 className="text-4xl font-bold">'+t+"</h1>"),e.summary&&i.push(' <p className="text-lg text-muted-foreground">'+e.summary+"</p>"),i.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">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
2411
+ `)}}function nc(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,r=t.defaultRole??e[0],o=[];o.push("export type Role = "+e.map(s=>'"'+s+'"').join(" | ")+";"),o.push(""),o.push("export const ROLES = ["+e.map(s=>'"'+s+'"').join(", ")+"] as const;"),o.push(""),o.push('export const DEFAULT_ROLE: Role = "'+r+'";'),o.push(""),o.push("export const ROLE_LABELS: Record<Role, string> = {");for(let s of e){let i=s.charAt(0).toUpperCase()+s.slice(1);o.push(' "'+s+'": "'+i+'",')}return o.push("};"),o.push(""),o.push("export function getUserRole(user: Record<string, unknown>): Role {"),o.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),o.push(" if (ROLES.includes(role as Role)) return role as Role;"),o.push(" return DEFAULT_ROLE;"),o.push("}"),o.push(""),o.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),o.push(" if (!userRole) return false;"),o.push(" const allowed = Array.isArray(required) ? required : [required];"),o.push(" return allowed.includes(userRole as Role);"),o.push("}"),o.push(""),o.join(`
2412
+ `)}function sc(t){let e=Tt(t.name);if(t.authModel==="none"){let i=[];return i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),i.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&i.push(' <p className="mt-4 text-lg text-muted-foreground">'+t.summary+"</p>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
2413
+ `)}let r=t.publicPages?.includes("/"),o=t.design?.landingTone;if(r&&o){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col">'),i.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),i.push(' <h1 className="text-5xl font-bold tracking-tight">'+e+"</h1>"),t.summary&&i.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+t.summary+"</p>"),i.push(' <div className="flex gap-4">'),i.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">'),i.push(" Get Started"),i.push(" </Link>"),i.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </div>"),i.push(" </section>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
2414
+ `)}if(r){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),i.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&i.push(' <p className="text-lg text-muted-foreground">'+t.summary+"</p>"),i.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">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
2420
2415
  `)}let s=[];return s.push('import { headers } from "next/headers";'),s.push('import { redirect } from "next/navigation";'),s.push('import { auth } from "@/lib/auth";'),s.push(""),s.push("export default async function HomePage() {"),s.push(" const session = await auth.api.getSession({ headers: await headers() });"),s.push(' if (session) redirect("/dashboard");'),s.push(' redirect("/login");'),s.push("}"),s.push(""),s.join(`
2421
- `)}function Tc(e,t){let r=e.authModel==="none",o=[];r||(o.push('import { Suspense } from "react";'),o.push('import { headers } from "next/headers";'),o.push('import { redirect } from "next/navigation";'),o.push('import { auth } from "@/lib/auth";'),o.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),e.navStyle==="topbar"?o.push('import TopNav from "@/components/topnav";'):e.navStyle!=="none"&&o.push('import Sidebar from "@/components/sidebar";'),!r&&e.roles&&e.roles.length>0&&o.push('import { getUserRole } from "@/lib/roles";'),o.push(""),o.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),r?o.push(' const user = { name: "Guest", email: "" };'):(o.push(" const session = await auth.api.getSession({ headers: await headers() });"),o.push(' if (!session) redirect("/login");'),o.push(""),e.roles&&e.roles.length>0?(o.push(" const role = getUserRole(session.user as Record<string, unknown>);"),o.push(" const user = { name: session.user.name, email: session.user.email, role };")):(o.push(" const user = {"),o.push(" name: session.user.name,"),o.push(" email: session.user.email,"),o.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),o.push(" };"))),o.push("");let s=r?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return e.navStyle==="topbar"?(o.push(" return ("),o.push(' <div className="min-h-screen">'),o.push(" <TopNav user={user} />"),o.push(' <main className="mx-auto max-w-7xl p-6">'+s+"{children}</main>"),o.push(" </div>"),o.push(" );")):e.navStyle==="none"?(o.push(" return ("),o.push(' <div className="min-h-screen">'),o.push(' <main className="mx-auto max-w-5xl p-6">'+s+"{children}</main>"),o.push(" </div>"),o.push(" );")):(o.push(" return ("),o.push(' <div className="flex flex-col md:flex-row min-h-screen">'),o.push(" <Sidebar user={user} />"),o.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+s+"{children}</main>"),o.push(" </div>"),o.push(" );")),o.push("}"),o.push(""),o.join(`
2422
- `)}function Pc(e){let t=Ut(e.name),r=e.dataModel??[],o=[];if(r.length>0){let s=r.map(n=>_r(n.entity??n.name??"item")),i=[...new Set(s)];o.push('import { Card, CardContent } from "@/components/ui/card";'),o.push("import { "+i.join(", ")+' } from "lucide-react";'),o.push("")}if(o.push("export default function DashboardPage() {"),o.push(" return ("),o.push(' <div className="space-y-6">'),o.push(" <div>"),o.push(' <h1 className="text-3xl font-bold">'+t+"</h1>"),e.summary&&o.push(' <p className="mt-1 text-muted-foreground">'+e.summary+"</p>"),o.push(" </div>"),r.length>0){o.push(' <div className="rounded-lg border p-8 text-center">'),o.push(' <h2 className="text-lg font-semibold">Get started</h2>'),o.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),o.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let s of r){let i=s.entity??s.name??"Item",n=_r(i),a=Ut(i.replace(/_/g,"-"));o.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),o.push(" <"+n+' className="h-5 w-5 text-muted-foreground" />'),o.push(' <span className="text-sm font-medium">Add your first '+a+"</span>"),o.push(" </div>")}o.push(" </div>"),o.push(" </div>")}return o.push(" </div>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
2423
- `)}function Cc(e,t=!1){if(!e.multiTenant)return null;let r=[];return t?(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(),'),t?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(`
2424
- `)}function Ic(e){if(!e.multiTenant)return null;let t=[];return t.push('import { db } from "./db";'),t.push('import { organization, orgMember } from "@/db/schema/organization";'),t.push('import { eq } from "drizzle-orm";'),t.push(""),t.push("export async function getCurrentOrg(userId: string) {"),t.push(" const membership = await db"),t.push(" .select()"),t.push(" .from(orgMember)"),t.push(" .where(eq(orgMember.userId, userId))"),t.push(" .limit(1);"),t.push(" if (membership.length === 0) return null;"),t.push(" const org = await db"),t.push(" .select()"),t.push(" .from(organization)"),t.push(" .where(eq(organization.id, membership[0].orgId))"),t.push(" .limit(1);"),t.push(" return org[0] ?? null;"),t.push("}"),t.push(""),t.push("export async function getOrgMembers(orgId: string) {"),t.push(" return db"),t.push(" .select()"),t.push(" .from(orgMember)"),t.push(" .where(eq(orgMember.orgId, orgId));"),t.push("}"),t.push(""),t.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),t.push(" const id = crypto.randomUUID();"),t.push(" await db.insert(orgMember).values({"),t.push(" id,"),t.push(" orgId,"),t.push(" userId: email,"),t.push(" role,"),t.push(" });"),t.push(" return { id, orgId, email, role };"),t.push("}"),t.push(""),t.join(`
2425
- `)}function Ac(e){if(!e.multiTenant)return null;let t=[];return t.push('"use client";'),t.push(""),t.push("import {"),t.push(" DropdownMenu,"),t.push(" DropdownMenuContent,"),t.push(" DropdownMenuItem,"),t.push(" DropdownMenuTrigger,"),t.push('} from "@/components/ui/dropdown-menu";'),t.push('import { Button } from "@/components/ui/button";'),t.push('import { ChevronsUpDown } from "lucide-react";'),t.push(""),t.push("interface OrgSwitcherProps {"),t.push(" orgs: Array<{ id: string; name: string }>;"),t.push(" currentOrgId: string;"),t.push("}"),t.push(""),t.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),t.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),t.push(""),t.push(" return ("),t.push(" <DropdownMenu>"),t.push(" <DropdownMenuTrigger asChild>"),t.push(' <Button variant="outline" className="w-full justify-between">'),t.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),t.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),t.push(" </Button>"),t.push(" </DropdownMenuTrigger>"),t.push(' <DropdownMenuContent className="w-56">'),t.push(" {orgs.map((org) => ("),t.push(" <DropdownMenuItem key={org.id}>"),t.push(" {org.name}"),t.push(" </DropdownMenuItem>"),t.push(" ))}"),t.push(" </DropdownMenuContent>"),t.push(" </DropdownMenu>"),t.push(" );"),t.push("}"),t.push(""),t.join(`
2426
- `)}function _c(e,t,r){let o=[],s=e.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");o.push(`# ${s}`),o.push(""),t?.summary&&(o.push(t.summary),o.push(""));let i=t?.features??[];if(i.length>0){o.push("## Features"),o.push("");for(let l of i){let c=l.description?` \u2014 ${l.description}`:"";o.push(`- **${l.name}**${c}`)}o.push("")}o.push("## Tech Stack"),o.push(""),o.push("| Layer | Technology |"),o.push("|-------|------------|"),o.push("| Framework | Next.js 15 (App Router) |"),o.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),o.push("| Auth | Better Auth (email/password, social login) |"),o.push("| Styling | Tailwind CSS + shadcn/ui |"),o.push("| Deployment | Mistflow Cloud |"),r.hasStripe&&o.push("| Payments | Stripe |"),r.hasResend&&o.push("| Email | Resend + React Email |"),r.hasStorage&&o.push("| File Storage | Mistflow Cloud (managed blob storage) |"),r.hasAdmin&&o.push("| Admin | Better Auth admin plugin |"),r.hasAI&&o.push("| AI | Vercel AI SDK + OpenAI |"),o.push("");let n=t?.pages??[];if(n.length>0){o.push("## Pages"),o.push(""),o.push("| Route | Description |"),o.push("|-------|-------------|");for(let l of n){let c=l.path??l.route??l.name??"",h=l.description??"";o.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${h} |`)}o.push("")}let a=t?.dataModel??[];if(a.length>0){o.push("## Data Model"),o.push("");for(let l of a){let c=l.entity??l.name??"Unknown";if(o.push(`### ${c}`),o.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")o.push(`Fields: ${l.fields.join(", ")}`);else{o.push("| Field | Type |"),o.push("|-------|------|");for(let h of l.fields)o.push(`| ${h.name} | ${h.type} |`)}o.push("")}}}return o.push("## Getting Started"),o.push(""),o.push("### Prerequisites"),o.push(""),o.push("- Node.js 20+"),o.push("- npm"),o.push(""),o.push("### Install"),o.push(""),o.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),o.push(""),o.push("```bash"),o.push("npm install"),o.push("```"),o.push(""),o.push("### Set up environment"),o.push(""),o.push("Copy `.env.example` to `.env.local` and fill in the values:"),o.push(""),o.push("```bash"),o.push("cp .env.example .env.local"),o.push("```"),o.push(""),o.push("| Variable | Description | Required |"),o.push("|----------|-------------|----------|"),r.isNeon?o.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(o.push("| `TURSO_URL` | Database connection URL | Yes |"),o.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),o.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),r.hasStripe&&(o.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),o.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),o.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),r.hasResend&&(o.push("| `RESEND_API_KEY` | Resend API key | Yes |"),o.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),r.hasStorage&&(o.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),o.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),r.hasAI&&o.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),o.push(""),o.push("### Local database"),o.push(""),r.isNeon?(o.push("For local development, start a local Postgres server:"),o.push(""),o.push("```bash"),o.push("# Using Docker:"),o.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),o.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),o.push("```")):(o.push("For local development, start a local Turso server:"),o.push(""),o.push("```bash"),o.push("npx turso dev"),o.push("```")),o.push(""),o.push("Then set up the database:"),o.push(""),o.push("```bash"),o.push("npm run db:push"),o.push("```"),o.push(""),o.push("### Run"),o.push(""),o.push("```bash"),o.push("npm run dev"),o.push("```"),o.push(""),o.push("Open [http://localhost:3000](http://localhost:3000)."),o.push(""),o.push("## Project Structure"),o.push(""),o.push("```"),o.push("app/"),o.push(" (auth)/ Login and registration pages"),o.push(" (dashboard)/ Authenticated app pages"),r.hasAdmin&&o.push(" (admin)/ Admin panel pages"),o.push(" api/ API routes (auth, health, webhooks)"),o.push(" layout.tsx Root layout with fonts and providers"),o.push(" globals.css Design tokens and Tailwind config"),o.push("components/ Reusable UI components"),o.push("db/"),o.push(" schema/ Database table definitions"),o.push(" index.ts Schema exports"),o.push("lib/"),o.push(" auth.ts Better Auth server config"),o.push(" auth-client.ts Better Auth client config"),o.push(` db.ts ${r.isNeon?"Postgres":"SQLite"} database connection`),r.hasStripe&&o.push(" stripe.ts Stripe client"),r.hasResend&&(o.push(" resend.ts Resend client"),o.push(" email.ts Email send helpers")),r.hasStorage&&o.push(" storage.ts File upload/download helpers"),r.hasAI&&o.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),r.hasResend&&o.push("emails/ React Email templates"),o.push("```"),o.push(""),o.push("## Deploy"),o.push(""),o.push("Deploy to production with Mistflow:"),o.push(""),o.push("```"),o.push("# In your AI editor (Claude Code, Cursor, etc.):"),o.push("mist_deploy action='deploy'"),o.push("```"),o.push(""),o.push("Your app will be live at `https://<app-name>.mistflow.app`."),o.push(""),t?.design&&(o.push("## Design"),o.push(""),t.design.tone&&o.push(`- **Tone**: ${t.design.tone}`),t.design.fonts&&(o.push(`- **Heading font**: ${t.design.fonts.heading}`),o.push(`- **Body font**: ${t.design.fonts.body}`)),t.design.accentColor&&o.push(`- **Accent color**: ${t.design.accentColor}`),t.design.borderRadius&&o.push(`- **Border radius**: ${t.design.borderRadius}`),o.push("")),o.push("---"),o.push(""),o.push("Built with [Mistflow](https://mistflow.ai)"),o.push(""),o.join(`
2427
- `)}async function Rc(e,t){let{name:r,plan:o,path:s,planId:i}=e;if(!s)return d("mist_init requires an explicit 'path' \u2014 the absolute directory where the project should be scaffolded. Pass the user's project directory (e.g. /Users/alice/projects/my-app). Do not rely on a default.",!0);if(!rc(s))return d(`mist_init 'path' must be an absolute path \u2014 received '${s}'. Pass the full absolute path to the target directory.`,!0);let n=gs(s),a=o;if(!a&&i){let w=ic(i);if(!w)return d(`No plan found for planId '${i}'. Call mist_plan first, or pass the plan object inline.`,!0);a=w.plan}let l=a?.design,c=a?.appStyle,h=a?bo(a,"stripe","payment","billing","subscription","checkout","pricing"):!1,m=!0,p=a?bo(a,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,f=a?bo(a,"admin panel","admin dashboard","admin management"):!1,S=a?bo(a,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,b=a,y=!0;if(!dc(n))return d(`A project already exists at this location (${n}). Choose a different name, or delete the existing folder first. (A .mistflow/ folder left over from planning is fine \u2014 init will preserve it.)`,!0);Ir(n,{recursive:!0});try{let w=Ie(Lt(n),".mistflow","mockups");if(ot(w)){let A=hs(w).filter(z=>z.endsWith(".html"));if(A.length>0){let z=Ie(n,".mistflow","mockups");Ir(z,{recursive:!0});for(let te of A)oc(Ie(w,te),Ie(z,te));console.error(`Copied ${A.length} mockup file(s) into project`)}}}catch(w){console.error("Could not copy mockup files:",w instanceof Error?w.message:w)}let k=null;try{k=await er("nextjs")}catch(w){console.error("Could not fetch scaffold from API, using minimal scaffold:",w instanceof Error?w.message:w)}if(k){let w=r.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let E of k.files){if(E.path==="package.json"||E.path==="middleware.ts"||E.path==="components/sidebar.tsx"||E.path==="components/topnav.tsx"||E.path==="app/(dashboard)/layout.tsx"||E.path==="app/(dashboard)/page.tsx"||E.path==="app/(dashboard)/dashboard/page.tsx"||!h&&(E.path.includes("stripe")||E.path.includes("webhook/stripe"))||!m&&(E.path.includes("resend")||E.path.includes("emails/"))||!f&&(E.path.includes("(admin)")||E.path.includes("admin-sidebar"))||y&&(E.path==="lib/db.ts"||E.path==="lib/auth.ts"||E.path==="drizzle.config.ts"||E.path==="db/schema/auth.ts"))continue;let u=E.content.replace(/\{\{APP_NAME\}\}/g,r).replace(/\{\{WORKER_NAME\}\}/g,w);if(y&&E.path==="next.config.ts"&&(u=u.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),E.path==="next.config.ts"){let g=lc(n);g&&(console.error(`[init] Project is inside monorepo at ${g} \u2014 adding outputFileTracingRoot`),u.includes("outputFileTracingRoot")||(u=u.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
2416
+ `)}function ic(t,e){let r=t.authModel==="none",o=[];r||(o.push('import { Suspense } from "react";'),o.push('import { headers } from "next/headers";'),o.push('import { redirect } from "next/navigation";'),o.push('import { auth } from "@/lib/auth";'),o.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?o.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&o.push('import Sidebar from "@/components/sidebar";'),!r&&t.roles&&t.roles.length>0&&o.push('import { getUserRole } from "@/lib/roles";'),o.push(""),o.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),r?o.push(' const user = { name: "Guest", email: "" };'):(o.push(" const session = await auth.api.getSession({ headers: await headers() });"),o.push(' if (!session) redirect("/login");'),o.push(""),t.roles&&t.roles.length>0?(o.push(" const role = getUserRole(session.user as Record<string, unknown>);"),o.push(" const user = { name: session.user.name, email: session.user.email, role };")):(o.push(" const user = {"),o.push(" name: session.user.name,"),o.push(" email: session.user.email,"),o.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),o.push(" };"))),o.push("");let s=r?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(o.push(" return ("),o.push(' <div className="min-h-screen">'),o.push(" <TopNav user={user} />"),o.push(' <main className="mx-auto max-w-7xl p-6">'+s+"{children}</main>"),o.push(" </div>"),o.push(" );")):t.navStyle==="none"?(o.push(" return ("),o.push(' <div className="min-h-screen">'),o.push(' <main className="mx-auto max-w-5xl p-6">'+s+"{children}</main>"),o.push(" </div>"),o.push(" );")):(o.push(" return ("),o.push(' <div className="flex flex-col md:flex-row min-h-screen">'),o.push(" <Sidebar user={user} />"),o.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+s+"{children}</main>"),o.push(" </div>"),o.push(" );")),o.push("}"),o.push(""),o.join(`
2417
+ `)}function ac(t){let e=Tt(t.name),r=t.dataModel??[],o=[];if(r.length>0){let s=r.map(n=>hr(n.entity??n.name??"item")),i=[...new Set(s)];o.push('import { Card, CardContent } from "@/components/ui/card";'),o.push("import { "+i.join(", ")+' } from "lucide-react";'),o.push("")}if(o.push("export default function DashboardPage() {"),o.push(" return ("),o.push(' <div className="space-y-6">'),o.push(" <div>"),o.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),t.summary&&o.push(' <p className="mt-1 text-muted-foreground">'+t.summary+"</p>"),o.push(" </div>"),r.length>0){o.push(' <div className="rounded-lg border p-8 text-center">'),o.push(' <h2 className="text-lg font-semibold">Get started</h2>'),o.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),o.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let s of r){let i=s.entity??s.name??"Item",n=hr(i),a=Tt(i.replace(/_/g,"-"));o.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),o.push(" <"+n+' className="h-5 w-5 text-muted-foreground" />'),o.push(' <span className="text-sm font-medium">Add your first '+a+"</span>"),o.push(" </div>")}o.push(" </div>"),o.push(" </div>")}return o.push(" </div>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
2418
+ `)}function lc(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(`
2419
+ `)}function cc(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(`
2420
+ `)}function dc(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(`
2421
+ `)}function pc(t,e,r){let o=[],s=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");o.push(`# ${s}`),o.push(""),e?.summary&&(o.push(e.summary),o.push(""));let i=e?.features??[];if(i.length>0){o.push("## Features"),o.push("");for(let l of i){let c=l.description?` \u2014 ${l.description}`:"";o.push(`- **${l.name}**${c}`)}o.push("")}o.push("## Tech Stack"),o.push(""),o.push("| Layer | Technology |"),o.push("|-------|------------|"),o.push("| Framework | Next.js 15 (App Router) |"),o.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),o.push("| Auth | Better Auth (email/password, social login) |"),o.push("| Styling | Tailwind CSS + shadcn/ui |"),o.push("| Deployment | Mistflow Cloud |"),r.hasStripe&&o.push("| Payments | Stripe |"),r.hasResend&&o.push("| Email | Resend + React Email |"),r.hasStorage&&o.push("| File Storage | Mistflow Cloud (managed blob storage) |"),r.hasAdmin&&o.push("| Admin | Better Auth admin plugin |"),r.hasAI&&o.push("| AI | Vercel AI SDK + OpenAI |"),o.push("");let n=e?.pages??[];if(n.length>0){o.push("## Pages"),o.push(""),o.push("| Route | Description |"),o.push("|-------|-------------|");for(let l of n){let c=l.path??l.route??l.name??"",m=l.description??"";o.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${m} |`)}o.push("")}let a=e?.dataModel??[];if(a.length>0){o.push("## Data Model"),o.push("");for(let l of a){let c=l.entity??l.name??"Unknown";if(o.push(`### ${c}`),o.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")o.push(`Fields: ${l.fields.join(", ")}`);else{o.push("| Field | Type |"),o.push("|-------|------|");for(let m of l.fields)o.push(`| ${m.name} | ${m.type} |`)}o.push("")}}}return o.push("## Getting Started"),o.push(""),o.push("### Prerequisites"),o.push(""),o.push("- Node.js 20+"),o.push("- npm"),o.push(""),o.push("### Install"),o.push(""),o.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),o.push(""),o.push("```bash"),o.push("npm install"),o.push("```"),o.push(""),o.push("### Set up environment"),o.push(""),o.push("Copy `.env.example` to `.env.local` and fill in the values:"),o.push(""),o.push("```bash"),o.push("cp .env.example .env.local"),o.push("```"),o.push(""),o.push("| Variable | Description | Required |"),o.push("|----------|-------------|----------|"),r.isNeon?o.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(o.push("| `TURSO_URL` | Database connection URL | Yes |"),o.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),o.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),r.hasStripe&&(o.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),o.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),o.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),r.hasResend&&(o.push("| `RESEND_API_KEY` | Resend API key | Yes |"),o.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),r.hasStorage&&(o.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),o.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),r.hasAI&&o.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),o.push(""),o.push("### Local database"),o.push(""),r.isNeon?(o.push("For local development, start a local Postgres server:"),o.push(""),o.push("```bash"),o.push("# Using Docker:"),o.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),o.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),o.push("```")):(o.push("For local development, start a local Turso server:"),o.push(""),o.push("```bash"),o.push("npx turso dev"),o.push("```")),o.push(""),o.push("Then set up the database:"),o.push(""),o.push("```bash"),o.push("npm run db:push"),o.push("```"),o.push(""),o.push("### Run"),o.push(""),o.push("```bash"),o.push("npm run dev"),o.push("```"),o.push(""),o.push("Open [http://localhost:3000](http://localhost:3000)."),o.push(""),o.push("## Project Structure"),o.push(""),o.push("```"),o.push("app/"),o.push(" (auth)/ Login and registration pages"),o.push(" (dashboard)/ Authenticated app pages"),r.hasAdmin&&o.push(" (admin)/ Admin panel pages"),o.push(" api/ API routes (auth, health, webhooks)"),o.push(" layout.tsx Root layout with fonts and providers"),o.push(" globals.css Design tokens and Tailwind config"),o.push("components/ Reusable UI components"),o.push("db/"),o.push(" schema/ Database table definitions"),o.push(" index.ts Schema exports"),o.push("lib/"),o.push(" auth.ts Better Auth server config"),o.push(" auth-client.ts Better Auth client config"),o.push(` db.ts ${r.isNeon?"Postgres":"SQLite"} database connection`),r.hasStripe&&o.push(" stripe.ts Stripe client"),r.hasResend&&(o.push(" resend.ts Resend client"),o.push(" email.ts Email send helpers")),r.hasStorage&&o.push(" storage.ts File upload/download helpers"),r.hasAI&&o.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),r.hasResend&&o.push("emails/ React Email templates"),o.push("```"),o.push(""),o.push("## Deploy"),o.push(""),o.push("Deploy to production with Mistflow:"),o.push(""),o.push("```"),o.push("# In your AI editor (Claude Code, Cursor, etc.):"),o.push("mist_deploy action='deploy'"),o.push("```"),o.push(""),o.push("Your app will be live at `https://<app-name>.mistflow.app`."),o.push(""),e?.design&&(o.push("## Design"),o.push(""),e.design.tone&&o.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(o.push(`- **Heading font**: ${e.design.fonts.heading}`),o.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&o.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&o.push(`- **Border radius**: ${e.design.borderRadius}`),o.push("")),o.push("---"),o.push(""),o.push("Built with [Mistflow](https://mistflow.ai)"),o.push(""),o.join(`
2422
+ `)}async function uc(t,e){let{name:r,plan:o,path:s,planId:i}=t;if(!s)return d("mist_init requires an explicit 'path' \u2014 the absolute directory where the project should be scaffolded. Pass the user's project directory (e.g. /Users/alice/projects/my-app). Do not rely on a default.",!0);if(!$l(s))return d(`mist_init 'path' must be an absolute path \u2014 received '${s}'. Pass the full absolute path to the target directory.`,!0);let n=Qn(s),a=o;if(!a&&i){let g=Bl(i);if(!g)return d(`No plan found for planId '${i}'. Call mist_plan first, or pass the plan object inline.`,!0);a=g.plan}let l=a?.design,c=a?ro(a,"stripe","payment","billing","subscription","checkout","pricing"):!1,m=!0,p=a?ro(a,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,u=a?ro(a,"admin panel","admin dashboard","admin management"):!1,w=a?ro(a,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,D=a,x=!0;if(!Gl(n))return d(`A project already exists at this location (${n}). Choose a different name, or delete the existing folder first. (A .mistflow/ folder left over from planning is fine \u2014 init will preserve it.)`,!0);ur(n,{recursive:!0});try{let g=we(St(n),".mistflow","mockups");if(Ve(g)){let k=Yn(g).filter(N=>N.endsWith(".html"));if(k.length>0){let N=we(n,".mistflow","mockups");ur(N,{recursive:!0});for(let K of k)Ll(we(g,K),we(N,K));console.error(`Copied ${k.length} mockup file(s) into project`)}}}catch(g){console.error("Could not copy mockup files:",g instanceof Error?g.message:g)}let S=null;try{S=await Bo("nextjs")}catch(g){console.error("Could not fetch scaffold from API, using minimal scaffold:",g instanceof Error?g.message:g)}if(S){let g=r.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let P of S.files){if(P.path==="package.json"||P.path==="middleware.ts"||P.path==="components/sidebar.tsx"||P.path==="components/topnav.tsx"||P.path==="app/(dashboard)/layout.tsx"||P.path==="app/(dashboard)/page.tsx"||P.path==="app/(dashboard)/dashboard/page.tsx"||!c&&(P.path.includes("stripe")||P.path.includes("webhook/stripe"))||!m&&(P.path.includes("resend")||P.path.includes("emails/"))||!u&&(P.path.includes("(admin)")||P.path.includes("admin-sidebar"))||x&&(P.path==="lib/db.ts"||P.path==="lib/auth.ts"||P.path==="drizzle.config.ts"||P.path==="db/schema/auth.ts"))continue;let O=P.content.replace(/\{\{APP_NAME\}\}/g,r).replace(/\{\{WORKER_NAME\}\}/g,g);if(x&&P.path==="next.config.ts"&&(O=O.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),P.path==="next.config.ts"){let Z=Hl(n);Z&&(console.error(`[init] Project is inside monorepo at ${Z} \u2014 adding outputFileTracingRoot`),O.includes("outputFileTracingRoot")||(O=O.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
2428
2423
  import { dirname } from "path";
2429
2424
  import { fileURLToPath } from "url";
2430
2425
 
2431
- const __dirname = dirname(fileURLToPath(import.meta.url));`),u=u.replace("images: {",`outputFileTracingRoot: __dirname,
2432
- images: {`)))}!f&&E.path.includes("sidebar")&&(u=u.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),u=u.replace(/, Shield/g,"")),L(n,E.path,u)}let A={...k.dependencies},z={...k.devDependencies};if(A["drizzle-zod"]||(A["drizzle-zod"]="^0.5.1"),y&&(delete A["@libsql/client"],A["@neondatabase/serverless"]="^0.10.0",z["@electric-sql/pglite"]="^0.2.0"),h&&(A.stripe="^17.0.0"),m&&(A.resend="^4.0.0",A["@react-email/components"]="^0.0.31"),S&&(A.ai="^4.0.0",A["@ai-sdk/openai"]="^1.0.0",A.openai="^4.0.0"),L(n,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0,scripts:{dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"},dependencies:A,devDependencies:z,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"}},null,2)),k.methodology){let E=k.methodology;y&&(E=E.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres")),E=Sr(E),L(n,"AGENTS.md",E),L(n,"CLAUDE.md",E)}let ve=a?.designMd;ve&&L(n,"DESIGN.md",ve),y&&(L(n,"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 {"," // Local dev \u2014 PGlite (zero-install embedded Postgres). Lives in"," // lib/db-local.ts and is loaded through a runtime-only require"," // whose path is built from a variable, so esbuild's static"," // analysis can't follow it. Keeps pglite + its 30MB WASM out of"," // the Worker bundle.",' const localPath: string = "./" + "db-local";'," // eslint-disable-next-line @typescript-eslint/no-require-imports"," const { createLocalDb } = require(localPath);"," _db = createLocalDb();"," }"," }"," 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(`
2433
- `)),L(n,"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","// transitive 30MB WASM binary. Loaded via runtime-only require() from","// db.ts, where the path is built from a variable to defeat static analysis.","",'const pglitePkg: string = ["@electric-sql", "pglite"].join("/");',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { PGlite } = require(pglitePkg);","",'const drizzlePath: string = "drizzle-orm/" + "pglite";',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { drizzle } = require(drizzlePath);","","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
2434
- `)),L(n,"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(`
2435
- `)),L(n,"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(`
2436
- `)),L(n,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','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);"," // 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,"," trustedOrigins: [baseURL],",' 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: "user" }), 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.GOOGLE_CLIENT_ID ? {"," google: {"," clientId: process.env.GOOGLE_CLIENT_ID,"," clientSecret: process.env.GOOGLE_CLIENT_SECRET!,"," },"," } : {}),"," ...(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(`
2437
- `)))}else L(n,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0},null,2));let I=a?.designMd;L(n,"app/globals.css",gc(l,c,I)),L(n,"app/layout.tsx",bc(r,l,b?.language)),L(n,"README.md",_c(r,a,{hasStripe:h,hasResend:m,hasStorage:p,hasAdmin:f,hasAI:S,isNeon:y})),L(n,"contracts/README.md",kr());let R=a?.dataModel??[],P=new Set,M=0;for(let w of R){let A=w.entity??w.name;if(!A||typeof A!="string")continue;let z=Pr(A);P.has(z)||(P.add(z),L(n,z,Tr(A)),M++)}M===0&&L(n,"contracts/.gitkeep","");let F=[],v=a?.publicPages;if(Array.isArray(v))F=v;else if(typeof v=="string"){try{F=JSON.parse(v)}catch{F=[]}Array.isArray(F)||(F=[])}if(!F.includes("/")){let w=a?.steps?.some(z=>{let te=((z.name??"")+" "+(z.description??"")).toLowerCase();return te.includes("landing")||te.includes("marketing")||te.includes("homepage")}),A=a?.pages?.some(z=>z.path==="/");(w||A)&&(F=["/",...F])}let U={name:r,summary:a?.summary,authModel:a?.authModel,roles:a?.roles,defaultRole:a?.defaultRole,publicPages:F,navStyle:a?.navStyle,multiTenant:a?.multiTenant,pages:a?.pages,dataModel:a?.dataModel,design:a?.design},G=vc(U);G&&L(n,"middleware.ts",G);let V=xc(U);V&&L(n,V.path,V.content);let oe=kc(U);if(oe&&L(n,"lib/roles.ts",oe),L(n,"app/page.tsx",Sc(U)),L(n,"app/(dashboard)/layout.tsx",Tc(U,f)),L(n,"app/(dashboard)/dashboard/page.tsx",Pc(U)),U.multiTenant){let w=Cc(U,y);w&&L(n,"db/schema/organization.ts",w);let A=Ic(U);A&&L(n,"lib/org.ts",A);let z=Ac(U);z&&L(n,"components/org-switcher.tsx",z)}L(n,"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)),h&&L(n,"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(`
2438
- `)),m&&(L(n,"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(`
2439
- `)),L(n,"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(`
2440
- `))),p&&(L(n,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? "https://api.mistflow.ai";',"const MISTFLOW_API_KEY = process.env.MISTFLOW_API_KEY;","const PROJECT_ID = process.env.MISTFLOW_PROJECT_ID;","","interface UploadResult {"," upload_url: string;"," download_url: string;"," key: string;","}","","function authHeaders(): Record<string, string> {"," return {",' "Content-Type": "application/json",',' "Authorization": `ApiKey ${MISTFLOW_API_KEY}`,'," };","}","",'export async function getUploadUrl(filename: string, contentType: string = "application/octet-stream"): Promise<UploadResult> {'," const res = await fetch(`${MISTFLOW_API}/api/storage/upload-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename, content_type: contentType }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," return res.json();","}","","export async function getDownloadUrl(filename: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/download-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.download_url;","}","","export async function deleteFile(filename: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/delete`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });","}","","export async function uploadFile(file: File): Promise<string> {"," const { upload_url, download_url } = await getUploadUrl(file.name, file.type);",' await fetch(upload_url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });'," return download_url;","}",""].join(`
2441
- `)),L(n,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadUrl } from "@/lib/storage";',"","export async function POST(req: NextRequest) {"," const { filename, contentType } = await req.json();"," if (!filename) {",' return NextResponse.json({ error: "filename is required" }, { status: 400 });'," }"," try {",' const result = await getUploadUrl(filename, contentType ?? "application/octet-stream");'," return NextResponse.json(result);"," } catch {",' return NextResponse.json({ error: "Failed to get upload URL" }, { status: 500 });'," }","}",""].join(`
2442
- `))),S&&(L(n,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
2443
- `)),L(n,"app/api/chat/route.ts",['import { openai } from "@/lib/ai";','import { streamText } from "ai";',"","export async function POST(req: Request) {"," const { messages } = await req.json();",""," const result = streamText({",' model: openai("gpt-4o"),'," messages,"," });",""," return result.toDataStreamResponse();","}",""].join(`
2444
- `)));let D=Array.isArray(a?.integrations)?a.integrations.map(w=>({name:w.name,preset:w.preset,envVars:w.envVars??[]})):[],j={};S&&!D.some(w=>w.envVars?.some(A=>A.key==="OPENAI_API_KEY"))&&(j.OPENAI_API_KEY={description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"});for(let w of D)for(let A of w.envVars??[])j[A.key]||(j[A.key]={description:A.description,setupUrl:A.setupUrl,...w.name?{integration:w.name}:{}});let ie={name:r,methodologyVersion:k?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},plan:Array.isArray(a?.steps)?{...a,steps:a.steps.map(w=>({number:w.number,name:w.name??w.title,description:w.description,entities:w.entities,pages:w.pages,features:w.features,status:"pending"}))}:a,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...h?{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"}}:{},...m?{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"}}:{},...p?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...Object.keys(j).length>0?{required:j}:{}},authModel:a?.authModel??"email",roles:a?.roles??null,navStyle:a?.navStyle??"sidebar",multiTenant:a?.multiTenant??!1,hasAdmin:f,hasResend:m,hasStorage:p,hasAI:S,deploy:null};L(n,"mistflow.json",JSON.stringify(ie,null,2));let he=sc(32).toString("hex"),O=h?`
2426
+ const __dirname = dirname(fileURLToPath(import.meta.url));`),O=O.replace("images: {",`outputFileTracingRoot: __dirname,
2427
+ images: {`)))}!u&&P.path.includes("sidebar")&&(O=O.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),O=O.replace(/, Shield/g,"")),z(n,P.path,O)}let k={...S.dependencies},N={...S.devDependencies};if(k["drizzle-zod"]||(k["drizzle-zod"]="^0.5.1"),x&&(delete k["@libsql/client"],k["@neondatabase/serverless"]="^0.10.0",N["@electric-sql/pglite"]="^0.2.0"),c&&(k.stripe="^17.0.0"),m&&(k.resend="^4.0.0",k["@react-email/components"]="^0.0.31"),w&&(k.ai="^4.0.0",k["@ai-sdk/openai"]="^1.0.0",k.openai="^4.0.0"),z(n,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0,scripts:{dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"},dependencies:k,devDependencies:N,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"}},null,2)),S.methodology){let P=S.methodology;x&&(P=P.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres")),P=lr(P),z(n,"AGENTS.md",P),z(n,"CLAUDE.md",P)}let X=a?.designMd;if(X&&z(n,"DESIGN.md",X),x){z(n,"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 {"," // Local dev \u2014 PGlite (zero-install embedded Postgres). Lives in"," // lib/db-local.ts and is loaded through a runtime-only require"," // whose path is built from a variable, so esbuild's static"," // analysis can't follow it. Keeps pglite + its 30MB WASM out of"," // the Worker bundle.",' const localPath: string = "./" + "db-local";'," // eslint-disable-next-line @typescript-eslint/no-require-imports"," const { createLocalDb } = require(localPath);"," _db = createLocalDb();"," }"," }"," 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(`
2428
+ `)),z(n,"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","// transitive 30MB WASM binary. Loaded via runtime-only require() from","// db.ts, where the path is built from a variable to defeat static analysis.","",'const pglitePkg: string = ["@electric-sql", "pglite"].join("/");',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { PGlite } = require(pglitePkg);","",'const drizzlePath: string = "drizzle-orm/" + "pglite";',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { drizzle } = require(drizzlePath);","","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
2429
+ `)),z(n,"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(`
2430
+ `)),z(n,"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(`
2431
+ `));let P=a.defaultRole??"user";z(n,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','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);"," // 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,"," trustedOrigins: [baseURL],",' 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: "${P}" }), 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.GOOGLE_CLIENT_ID ? {"," google: {"," clientId: process.env.GOOGLE_CLIENT_ID,"," clientSecret: process.env.GOOGLE_CLIENT_SECRET!,"," },"," } : {}),"," ...(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(`
2432
+ `))}}else z(n,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0},null,2));let f=a?.designMd;z(n,"app/globals.css",Ql(l,f)),z(n,"app/layout.tsx",ec(r,l,D?.language)),z(n,"README.md",pc(r,a,{hasStripe:c,hasResend:m,hasStorage:p,hasAdmin:u,hasAI:w,isNeon:x})),z(n,"contracts/README.md",ar());let _=a?.dataModel??[],L=new Set,W=0;for(let g of _){let k=g.entity??g.name;if(!k||typeof k!="string")continue;let N=dr(k);L.has(N)||(L.add(N),z(n,N,cr(k)),W++)}W===0&&z(n,"contracts/.gitkeep","");let R=[],J=a?.publicPages;if(Array.isArray(J))R=J;else if(typeof J=="string"){try{R=JSON.parse(J)}catch{R=[]}Array.isArray(R)||(R=[])}if(!R.includes("/")){let g=a?.steps?.some(N=>{let K=((N.name??"")+" "+(N.description??"")).toLowerCase();return K.includes("landing")||K.includes("marketing")||K.includes("homepage")}),k=a?.pages?.some(N=>N.path==="/");(g||k)&&(R=["/",...R])}let q={name:r,summary:a?.summary,authModel:a?.authModel,roles:a?.roles,defaultRole:a?.defaultRole,publicPages:R,navStyle:a?.navStyle,multiTenant:a?.multiTenant,pages:a?.pages,dataModel:a?.dataModel,design:a?.design},T=oc(q);T&&z(n,"middleware.ts",T);let E=rc(q);E&&z(n,E.path,E.content);let C=nc(q);if(C&&z(n,"lib/roles.ts",C),z(n,"app/page.tsx",sc(q)),z(n,"app/(dashboard)/layout.tsx",ic(q,u)),z(n,"app/(dashboard)/dashboard/page.tsx",ac(q)),q.multiTenant){let g=lc(q,x);g&&z(n,"db/schema/organization.ts",g);let k=cc(q);k&&z(n,"lib/org.ts",k);let N=dc(q);N&&z(n,"components/org-switcher.tsx",N)}z(n,"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)),c&&z(n,"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(`
2433
+ `)),m&&(z(n,"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(`
2434
+ `)),z(n,"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(`
2435
+ `))),p&&(z(n,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? "https://api.mistflow.ai";',"const MISTFLOW_API_KEY = process.env.MISTFLOW_API_KEY;","const PROJECT_ID = process.env.MISTFLOW_PROJECT_ID;","","interface UploadResult {"," upload_url: string;"," download_url: string;"," key: string;","}","","function authHeaders(): Record<string, string> {"," return {",' "Content-Type": "application/json",',' "Authorization": `ApiKey ${MISTFLOW_API_KEY}`,'," };","}","",'export async function getUploadUrl(filename: string, contentType: string = "application/octet-stream"): Promise<UploadResult> {'," const res = await fetch(`${MISTFLOW_API}/api/storage/upload-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename, content_type: contentType }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," return res.json();","}","","export async function getDownloadUrl(filename: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/download-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.download_url;","}","","export async function deleteFile(filename: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/delete`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });","}","","export async function uploadFile(file: File): Promise<string> {"," const { upload_url, download_url } = await getUploadUrl(file.name, file.type);",' await fetch(upload_url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });'," return download_url;","}",""].join(`
2436
+ `)),z(n,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadUrl } from "@/lib/storage";',"","export async function POST(req: NextRequest) {"," const { filename, contentType } = await req.json();"," if (!filename) {",' return NextResponse.json({ error: "filename is required" }, { status: 400 });'," }"," try {",' const result = await getUploadUrl(filename, contentType ?? "application/octet-stream");'," return NextResponse.json(result);"," } catch {",' return NextResponse.json({ error: "Failed to get upload URL" }, { status: 500 });'," }","}",""].join(`
2437
+ `))),w&&(z(n,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
2438
+ `)),z(n,"app/api/chat/route.ts",['import { openai } from "@/lib/ai";','import { streamText } from "ai";',"","export async function POST(req: Request) {"," const { messages } = await req.json();",""," const result = streamText({",' model: openai("gpt-4o"),'," messages,"," });",""," return result.toDataStreamResponse();","}",""].join(`
2439
+ `)));let I=Array.isArray(a?.integrations)?a.integrations.map(g=>({name:g.name,preset:g.preset,envVars:g.envVars??[]})):[],$={};w&&!I.some(g=>g.envVars?.some(k=>k.key==="OPENAI_API_KEY"))&&($.OPENAI_API_KEY={description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"});for(let g of I)for(let k of g.envVars??[])$[k.key]||($[k.key]={description:k.description,setupUrl:k.setupUrl,...g.name?{integration:g.name}:{}});let U={name:r,methodologyVersion:S?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},plan:Array.isArray(a?.steps)?{...a,steps:a.steps.map(g=>({number:g.number,name:g.name??g.title,description:g.description,entities:g.entities,pages:g.pages,features:g.features,status:"pending"}))}:a,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...c?{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"}}:{},...m?{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"}}:{},...p?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...Object.keys($).length>0?{required:$}:{}},authModel:a?.authModel??"email",roles:a?.roles??null,navStyle:a?.navStyle??"sidebar",multiTenant:a?.multiTenant??!1,hasAdmin:u,hasResend:m,hasStorage:p,hasAI:w,deploy:null};z(n,"mistflow.json",JSON.stringify(U,null,2));let j=ql(32).toString("hex"),F=c?`
2445
2440
  # Stripe
2446
2441
  STRIPE_SECRET_KEY=
2447
2442
  STRIPE_WEBHOOK_SECRET=
2448
2443
  NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
2449
- `:"",X=m?`
2444
+ `:"",H=m?`
2450
2445
  # Email (Resend)
2451
2446
  RESEND_API_KEY=
2452
2447
  EMAIL_FROM=onboarding@resend.dev
2453
- `:"",fe=p?`
2448
+ `:"",Y=p?`
2454
2449
  # File Storage (Mistflow managed)
2455
2450
  MISTFLOW_API_KEY=
2456
2451
  MISTFLOW_PROJECT_ID=
2457
- `:"",Re=S?`
2452
+ `:"",te=w?`
2458
2453
  # AI (get your key at https://platform.openai.com/api-keys)
2459
2454
  OPENAI_API_KEY=
2460
- `:"",Ne=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2455
+ `:"",xe=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2461
2456
  # Set DATABASE_URL only for production or to use a remote Postgres
2462
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Fe=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2457
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Se=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2463
2458
  # Set DATABASE_URL only for production or to use a remote Postgres
2464
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;L(n,".env.local",`${Ne}
2465
- AUTH_SECRET=${he}
2466
- ${O}${X}${fe}${Re}`),L(n,".env.example",`${Fe}
2459
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;z(n,".env.local",`${xe}
2460
+ AUTH_SECRET=${j}
2461
+ ${F}${H}${Y}${te}`),z(n,".env.example",`${Se}
2467
2462
  AUTH_SECRET=your-secret-here
2468
- ${O}${X}${fe}${Re}`);let J=[],N=(w,A)=>{J.push({phase:w,message:A})},B=(w,A)=>{let z=J.find(te=>te.phase===w&&!te.durationMs);z&&(z.durationMs=A)};if(t){let w=Oe(t.server,t.progressToken,()=>J[J.length-1]?.message??"Setting up project...");t.cleanup=()=>w.stop()}let ye=b?.requestedSubdomain||void 0,pe,re;N("register","Registering project on Mistflow...");let Qe=Date.now();try{let w=await _t(r,void 0,"neon",ye);pe=w.id;let A=Ie(n,"mistflow.json"),z=JSON.parse(wo(A,"utf-8"));if(z.projectId=pe,Ar(A,JSON.stringify(z,null,2)),Nt(n,Et(pe,r)),w.managed_env&&Object.keys(w.managed_env).length>0){let te=Ie(n,".env.local"),De=ot(te)?wo(te,"utf-8"):"";for(let[ve,E]of Object.entries(w.managed_env)){let u=new RegExp(`^${ve}=.*$`,"m");u.test(De)?De=De.replace(u,`${ve}=${E}`):De+=`
2469
- ${ve}=${E}`}Ar(te,De)}try{let{getBaseUrl:te,getAuthHeaders:De}=await Promise.resolve().then(()=>(ge(),cn)),ve=De(),E=a?.features,u=a?.steps,g={};Array.isArray(E)&&E.length>0&&(g.features=E.map(x=>x.name)),a&&(g.plan=a),Array.isArray(u)&&u.length>0&&(g.provenance=u.map(x=>({feature:x.name??x.title??`Step ${x.number??"?"}`,user_intent:(x.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(g).length>0&&await fetch(`${te()}/api/projects/${encodeURIComponent(pe)}/state`,{method:"PUT",headers:{...ve,"Content-Type":"application/json"},body:JSON.stringify(g)})}catch{}J[J.length-1].message=`Registered as ${pe.slice(0,8)}`}catch(w){let A=w instanceof Error?w.message:String(w);console.error("Could not register project on backend:",A),re=`Project created locally but NOT registered on Mistflow servers (${A}). Deploy will auto-register it.`,J[J.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}B("register",Date.now()-Qe),N("git","Initializing git repository...");let st=Date.now();try{let w=ac(n);await w.init(),await w.add("."),await w.commit("Initial Mistflow project setup"),J[J.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),J[J.length-1].message="Git init skipped"}B("git",Date.now()-st);let it=J.reduce((w,A)=>w+(A.durationMs??0),0),be={projectPath:n,projectId:pe,status:"awaiting_install"},Ee=J.map(w=>{let A=w.durationMs?` (${(w.durationMs/1e3).toFixed(1)}s)`:"";return`${w.message}${A}`});be.progress=Ee,be.totalSetupTime=`${(it/1e3).toFixed(1)}s`;let Xe=[];pe||Xe.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),re&&(be.registrationWarning=re),Xe.length>0&&(be.warnings=Xe);let qe=`NEXT: Call mist_install({ projectPath: "${n}" }). 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: "${n}" }) to build the first plan step.`;return be.nextAction=pe?qe:`${qe} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,d(JSON.stringify(be))}var cc,pc,uc,us,yc,wc,fs,ys=T(()=>{"use strict";ee();bt();ge();et();Cr();Cr();cc=Mt.object({name:Mt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:Mt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Mt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Mt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});pc={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},uc=[["--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"]];us={"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"};yc=new Set(["ar","he","fa","ur"]);wc={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"};fs={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:cc,handler:Rc}});var ws,bs=T(()=>{ws="\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 xs,vs=T(()=>{xs=`# Consumer Warm Archetype
2463
+ ${F}${H}${Y}${te}`);let Q=[],Ce=(g,k)=>{Q.push({phase:g,message:k})},Ie=(g,k)=>{let N=Q.find(K=>K.phase===g&&!K.durationMs);N&&(N.durationMs=k)};if(e){let g=Te(e.server,e.progressToken,()=>Q[Q.length-1]?.message??"Setting up project...");e.cleanup=()=>g.stop()}let Ae=D?.requestedSubdomain||void 0,me,Je;Ce("register","Registering project on Mistflow...");let Ye=Date.now();try{let g=await gt(r,void 0,"neon",Ae);me=g.id;let k=we(n,"mistflow.json"),N=JSON.parse(no(k,"utf-8"));if(N.projectId=me,mr(k,JSON.stringify(N,null,2)),yt(n,bt(me,r)),g.managed_env&&Object.keys(g.managed_env).length>0){let K=we(n,".env.local"),ee=Ve(K)?no(K,"utf-8"):"";for(let[X,P]of Object.entries(g.managed_env)){let O=new RegExp(`^${X}=.*$`,"m");O.test(ee)?ee=ee.replace(O,`${X}=${P}`):ee+=`
2464
+ ${X}=${P}`}mr(K,ee)}try{let{getBaseUrl:K,getAuthHeaders:ee}=await Promise.resolve().then(()=>(de(),Kr)),X=ee(),P=a?.features,O=a?.steps,Z={};Array.isArray(P)&&P.length>0&&(Z.features=P.map(oe=>oe.name)),a&&(Z.plan=a),Array.isArray(O)&&O.length>0&&(Z.provenance=O.map(oe=>({feature:oe.name??oe.title??`Step ${oe.number??"?"}`,user_intent:(oe.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(Z).length>0&&await fetch(`${K()}/api/projects/${encodeURIComponent(me)}/state`,{method:"PUT",headers:{...X,"Content-Type":"application/json"},body:JSON.stringify(Z)})}catch{}Q[Q.length-1].message=`Registered as ${me.slice(0,8)}`}catch(g){let k=g instanceof Error?g.message:String(g);console.error("Could not register project on backend:",k),Je=`Project created locally but NOT registered on Mistflow servers (${k}). Deploy will auto-register it.`,Q[Q.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}Ie("register",Date.now()-Ye),Ce("git","Initializing git repository...");let he=Date.now();try{let g=zl(n);await g.init(),await g.add("."),await g.commit("Initial Mistflow project setup"),Q[Q.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),Q[Q.length-1].message="Git init skipped"}Ie("git",Date.now()-he);let h=Q.reduce((g,k)=>g+(k.durationMs??0),0),b={projectPath:n,projectId:me,status:"awaiting_install"},y=Q.map(g=>{let k=g.durationMs?` (${(g.durationMs/1e3).toFixed(1)}s)`:"";return`${g.message}${k}`});b.progress=y,b.totalSetupTime=`${(h/1e3).toFixed(1)}s`;let v=[];me||v.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),Je&&(b.registrationWarning=Je),v.length>0&&(b.warnings=v);let B=`NEXT: Call mist_install({ projectPath: "${n}" }). 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: "${n}" }) to build the first plan step.`;return b.nextAction=me?B:`${B} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,d(JSON.stringify(b))}var Wl,Vl,Kl,Kn,Zl,tc,Xn,Zn=A(()=>{"use strict";re();nt();de();We();pr();pr();Wl=xt.object({name:xt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:xt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:xt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:xt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});Vl={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Kl=[["--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"]];Kn={"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"};Zl=new Set(["ar","he","fa","ur"]);tc={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"};Xn={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:Wl,handler:uc}});var ts,es=A(()=>{ts="\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 rs,os=A(()=>{rs=`# Consumer Warm Archetype
2470
2465
 
2471
2466
  Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
2472
2467
 
@@ -2633,7 +2628,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
2633
2628
  - Small touch targets. Phone-first means \`h-12\` minimum.
2634
2629
  - Empty states that just say "No data." Be encouraging.
2635
2630
  - Dark theme as default. Consumer warm apps default to light.
2636
- `});var Ss,ks=T(()=>{Ss=`# Consumer Bold Archetype
2631
+ `});var ss,ns=A(()=>{ss=`# Consumer Bold Archetype
2637
2632
 
2638
2633
  Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
2639
2634
 
@@ -2804,7 +2799,7 @@ Social/competitive apps need an activity feed:
2804
2799
  - Card-only layouts with no hierarchy. Use hero cards + supporting cards.
2805
2800
  - Missing achievement/progress systems. The gamification IS the product.
2806
2801
  - Light-touch buttons. CTAs should be unmissable.
2807
- `});var Ps,Ts=T(()=>{Ps=`# Professional Clean Archetype
2802
+ `});var as,is=A(()=>{as=`# Professional Clean Archetype
2808
2803
 
2809
2804
  Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
2810
2805
 
@@ -3016,7 +3011,7 @@ h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
3016
3011
  - Missing status workflows. Every booking/appointment needs a clear state machine.
3017
3012
  - Dark theme as default. Clients associate light themes with professionalism.
3018
3013
  - Emoji in the UI. Professional context.
3019
- `});var Is,Cs=T(()=>{Is=`# Education Structured Archetype
3014
+ `});var cs,ls=A(()=>{cs=`# Education Structured Archetype
3020
3015
 
3021
3016
  Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
3022
3017
 
@@ -3216,7 +3211,7 @@ border-2 border-destructive bg-destructive/5 rounded-xl p-4
3216
3211
  - Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
3217
3212
  - Long lesson pages with no progress indicator. Users need to know where they are.
3218
3213
  - Multiple competing elements per view. One thing at a time. One question at a time.
3219
- `});var _s,As=T(()=>{_s=`# Marketplace Browse Archetype
3214
+ `});var ps,ds=A(()=>{ps=`# Marketplace Browse Archetype
3220
3215
 
3221
3216
  Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
3222
3217
 
@@ -3440,7 +3435,7 @@ border-b border-border/30 py-4
3440
3435
  - Small product images. The image is the primary decision-making element.
3441
3436
  - No empty state for zero search results. "No results for 'xyz'. Try broader terms."
3442
3437
  - Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
3443
- `});var Ns,Rs=T(()=>{Ns=`# SaaS Analytical Archetype
3438
+ `});var ms,us=A(()=>{ms=`# SaaS Analytical Archetype
3444
3439
 
3445
3440
  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.
3446
3441
 
@@ -3621,7 +3616,7 @@ The most recognizable B2B SaaS landing pattern.
3621
3616
  - **Inter as the only font.** Pair it with a distinctive heading font or swap it entirely.
3622
3617
  - **Centered text + centered image below.** The most overused AI hero. Use split or offset layouts.
3623
3618
  - **Animation on every element.** Efficient motion only: hero entrance, card reveals on scroll, number counters. Nothing else.
3624
- `});var Ds,Es=T(()=>{Ds=`# Content Editorial Archetype
3619
+ `});var gs,hs=A(()=>{gs=`# Content Editorial Archetype
3625
3620
 
3626
3621
  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.
3627
3622
 
@@ -3828,7 +3823,7 @@ Below the hero: 3 featured pieces laid out as a horizontal strip with **oversize
3828
3823
  - **Dark mode as default for a reading tool.** Offer it as a toggle, not the default.
3829
3824
  - **Flashy motion while reading.** Scroll hijacking, parallax on body text, animated backgrounds behind paragraphs \u2014 all break reading flow.
3830
3825
  - **More than 2 fonts.** Heading + body is enough. Adding a third font for captions or metadata dilutes the identity.
3831
- `});var Os,js=T(()=>{Os=`# Devtool Technical Archetype
3826
+ `});var ys,fs=A(()=>{ys=`# Devtool Technical Archetype
3832
3827
 
3833
3828
  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.
3834
3829
 
@@ -4017,7 +4012,7 @@ Numbers styled as terminal output: \`> 47,293 deploys this week\`, \`> 99.98% up
4017
4012
  - **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).
4018
4013
  - **Feature cards with rocket / lightning / puzzle icons.** Use technical icons (terminal, code, database, network) or skip icons entirely.
4019
4014
  - **Motion on code blocks** while the user is trying to read them. Type out ONCE on load, then leave them alone.
4020
- `});var Ls,Ms=T(()=>{Ls=`# Creative Showcase Archetype
4015
+ `});var ws,bs=A(()=>{ws=`# Creative Showcase Archetype
4021
4016
 
4022
4017
  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.
4023
4018
 
@@ -4234,7 +4229,7 @@ Premium agency touch: on first load, a full-screen loading component shows the s
4234
4229
  - **Scroll hijacking through the whole site.** Use sparingly \u2014 one or two scroll-pinned sections maximum.
4235
4230
  - **Mystery-meat navigation.** Clever is bad here. "Work / About / Contact" is fine. Don't make visitors guess.
4236
4231
  - **No contact info.** The primary purpose of this site is to generate inquiries. Make it stupid-easy to contact you.
4237
- `});var $s,Us=T(()=>{$s=`# Finance Clarity Archetype
4232
+ `});var ks,vs=A(()=>{ks=`# Finance Clarity Archetype
4238
4233
 
4239
4234
  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.
4240
4235
 
@@ -4453,7 +4448,7 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
4453
4448
  - **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
4454
4449
  - **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
4455
4450
  - **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.
4456
- `});function qs(e){let t=e?.archetype;if(!(!t||typeof t!="string"))return Fs[t]}var Fs,Qm,Bs=T(()=>{"use strict";vs();ks();Ts();Cs();As();Rs();Es();js();Ms();Us();Fs={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:xs},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:Ss},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Ps},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Is},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:_s},"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:Ns},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Ds},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:Os},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:Ls},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:$s}},Qm=Object.keys(Fs)});var Hs,zs=T(()=>{Hs=`# Landing Page Rules
4451
+ `});function Ss(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return xs[e]}var xs,Om,Ts=A(()=>{"use strict";os();ns();is();ls();ds();us();hs();fs();bs();vs();xs={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:rs},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:ss},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:as},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:cs},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:ps},"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:ms},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:gs},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:ys},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:ws},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:ks}},Om=Object.keys(xs)});var Cs,Ps=A(()=>{Cs=`# Landing Page Rules
4457
4452
 
4458
4453
  These rules apply to every landing page. They are non-negotiable.
4459
4454
 
@@ -4850,7 +4845,7 @@ app/
4850
4845
  \`\`\`
4851
4846
 
4852
4847
  Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
4853
- `});var Gs,Ws=T(()=>{Gs=`# Design Doctrine
4848
+ `});var As,Is=A(()=>{As=`# Design Doctrine
4854
4849
 
4855
4850
  This is the standard for every UI you generate. It is not aspirational. It is the floor.
4856
4851
 
@@ -4916,7 +4911,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
4916
4911
  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.**
4917
4912
 
4918
4913
  If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
4919
- `});var Ks,Vs=T(()=>{Ks=`# Typography
4914
+ `});var Rs,_s=A(()=>{Rs=`# Typography
4920
4915
 
4921
4916
  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.
4922
4917
 
@@ -5004,7 +4999,7 @@ Pick exactly one:
5004
4999
  - **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
5005
5000
 
5006
5001
  Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
5007
- `});var Ys,Js=T(()=>{Ys="# 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 the design system declared a theme direction. The appStyle 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 Xs,Qs=T(()=>{Xs=`# Motion
5002
+ `});var Ns,Es=A(()=>{Ns="# 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 js,Ds=A(()=>{js=`# Motion
5008
5003
 
5009
5004
  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.
5010
5005
 
@@ -5082,7 +5077,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
5082
5077
  ## One-Line Motion Rule
5083
5078
 
5084
5079
  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.
5085
- `});var ei,Zs=T(()=>{ei=`# Spatial Composition
5080
+ `});var Ms,Os=A(()=>{Ms=`# Spatial Composition
5086
5081
 
5087
5082
  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.
5088
5083
 
@@ -5152,7 +5147,7 @@ To signal "designed, not templated":
5152
5147
  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.
5153
5148
 
5154
5149
  Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
5155
- `});var oi,ti=T(()=>{oi=`# Interaction
5150
+ `});var Ls,Us=A(()=>{Ls=`# Interaction
5156
5151
 
5157
5152
  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.
5158
5153
 
@@ -5237,7 +5232,7 @@ Small moments that add up to "designed":
5237
5232
  - **Empty states** offer a specific next action, not "No data yet".
5238
5233
 
5239
5234
  These micro-interactions are the texture of a designed product. Ship them.
5240
- `});var ni,ri=T(()=>{ni=`# UX Writing
5235
+ `});var Fs,$s=A(()=>{Fs=`# UX Writing
5241
5236
 
5242
5237
  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.
5243
5238
 
@@ -5313,14 +5308,15 @@ If there's a pricing page:
5313
5308
  ## The Footer
5314
5309
 
5315
5310
  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."
5316
- `});import{z as Rr}from"zod";import{existsSync as $t,readFileSync as Er,writeFileSync as Nr,mkdirSync as Yc}from"fs";import{join as vt,resolve as Qc,dirname as Xc}from"path";import{createConnection as Zc}from"net";function ed(e){return new Promise(t=>{let r=Zc({port:e,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),t(!0)}),r.on("error",()=>{t(!1)})})}function od(e){let t=vt(e,"mistflow.json");if(!$t(t))return null;try{return JSON.parse(Er(t,"utf-8"))}catch{return null}}function si(e,t){let r=vt(e,"mistflow.json");Nr(r,JSON.stringify(t,null,2)+`
5317
- `)}function vo(e){return e.entity??e.name??"Unknown"}function rd(e){return e.length===0?"":typeof e[0]=="string"?e.join(", "):e.map(t=>`${t.name} (${t.type})`).join(", ")}function ii(e){return e.path??e.route??e.name??""}function nd(e){let t=(e||"text").toLowerCase();return t==="string"||t==="varchar"||t==="char"?"text":t==="integer"||t==="int"||t==="number"||t==="float"||t==="decimal"||t==="double"?"number":t==="boolean"||t==="bool"?"boolean":t==="date"||t==="datetime"||t==="timestamp"?"date":t==="email"?"email":t==="url"||t==="uri"?"url":t==="enum"||t==="select"?"select":t==="text"||t==="longtext"||t==="textarea"?"textarea":"text"}function ai(e,t){if(!e.entities||e.entities.length===0)return t;let r=e.entities.map(o=>o.toLowerCase());return t.filter(o=>{let s=vo(o).toLowerCase();return r.some(i=>s.includes(i)||i.includes(s))})}function sd(e,t){if(!e.pages||e.pages.length===0)return[];let r=e.pages.map(o=>o.toLowerCase());return t.filter(o=>{let s=(o.name??"").toLowerCase(),i=ii(o).toLowerCase();return r.some(n=>s.includes(n)||n.includes(s)||i.includes(n))})}function ad(e){let t=e.stepType;if(t&&id.has(t))return t;if(e.integrationId)return"integration";let r=`${e.name} ${e.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 ld(e){switch(e){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 cd(e,t){let r=[];if(r.push("### Design choices (decided at plan time \u2014 follow these exactly):"),e.tone&&r.push(`- **App tone**: ${e.tone}`),e.fonts&&(r.push(`- **Heading font**: ${e.fonts.heading} (load from Google Fonts)`),r.push(`- **Body font**: ${e.fonts.body} (load from Google Fonts)`)),r.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."),r.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)."),e.borderRadius){let o={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};r.push(`- **Border radius**: ${e.borderRadius} (${o[e.borderRadius]??e.borderRadius}) \u2014 set as --radius in globals.css`)}if(e.shadowStyle){let o={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"};r.push(`- **Shadow style**: ${e.shadowStyle} \u2014 ${o[e.shadowStyle]??e.shadowStyle}`)}if(e.cardStyle){let o={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"};r.push(`- **Card style**: ${e.cardStyle} \u2014 ${o[e.cardStyle]??e.cardStyle}`)}if(e.landingTone&&r.push(`- **Landing page tone**: ${e.landingTone}`),e.visualStrategy){let o=e.visualStrategy,s=e.heroPhoto!==!1,i=s&&!!o.heroImages?.length;if(r.push(""),r.push("### Visual strategy:"),i&&o.heroImages&&o.heroImages.length>0){r.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let a=o.heroImages[0];r.push(`- URL: ${a.url}`),r.push(`- Alt text for img tag: "${a.alt||"Hero image"} \u2014 Photo by ${a.photographer} on Unsplash"`),r.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 s&&!o.heroImages?.length?r.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/page.tsx.'"):s||r.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(o.sectionImages?.length){r.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let a of o.sectionImages)r.push(`- ${a.url} \u2014 alt: "${a.alt||"section image"} \u2014 Photo by ${a.photographer} on Unsplash"`)}(i||o.sectionImages?.length)&&r.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 n=qs(e);n?(r.push(""),r.push(`### Page composition \u2014 ${n.name} archetype`),r.push(`This plan was classified as **${n.id}** \u2014 ${n.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.`),r.push(""),r.push(n.content)):(r.push(""),r.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."),r.push(""),r.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),r.push("The hero uses a split layout with text on the left and a product preview on the right."),r.push(""),r.push("```"),r.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"),r.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),r.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"),r.push("\u2502 \u2502"),r.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"),r.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),r.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),r.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),r.push("\u2502 \u2502 real app data \u2502 \u2502"),r.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),r.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),r.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"),r.push("\u2502 \u2502"),r.push("\u2502 500+ 25K+ 99% \u2502"),r.push("\u2502 Label Label Label \u2502"),r.push("\u2502 \u2502"),i?r.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):r.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),r.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"),r.push("```"),r.push(""),r.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"),r.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."),r.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return r.push(""),r.push(ws),r.join(`
5318
- `)}async function dd(e){try{let t=await tr("nextjs",e);return{reminders:t.reminders,skill:t.skill}}catch{return{reminders:`### ${e} step
5311
+ `});import{existsSync as Nc,readFileSync as Dc,writeFileSync as jc}from"fs";import{join as Oc}from"path";import{z as Pt}from"zod";function io(t,e){if(e.length===0)return{added:[],skipped:[]};let r=Oc(t,"mistflow.json");if(!Nc(r))throw new Error(`mistflow.json not found at ${t}`);let o=Dc(r,"utf-8"),s=JSON.parse(o);s.env=s.env??{},s.env.required=s.env.required??{};let i=s.env.required,n=[],a=[];for(let l of e)if(!(!l?.key||typeof l.key!="string"||!Mc.test(l.key))){if(i[l.key]){a.push(l.key);continue}i[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}:{}},n.push(l.key)}return n.length>0&&jc(r,JSON.stringify(s,null,2)+`
5312
+ `),{added:n,skipped:a}}var so,Mc,gr=A(()=>{"use strict";so=Pt.object({key:Pt.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:Pt.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:Pt.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:Pt.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),Mc=/^[A-Z][A-Z0-9_]*$/});import{z as ao}from"zod";import{existsSync as Ct,readFileSync as yr,writeFileSync as fr,mkdirSync as Uc}from"fs";import{join as it,resolve as Lc,dirname as $c}from"path";import{createConnection as Fc}from"net";function qc(t){return new Promise(e=>{let r=Fc({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}function zc(t){let e=it(t,"mistflow.json");if(!Ct(e))return null;try{return JSON.parse(yr(e,"utf-8"))}catch{return null}}function qs(t,e){let r=it(t,"mistflow.json");fr(r,JSON.stringify(e,null,2)+`
5313
+ `)}function lo(t){return t.entity??t.name??"Unknown"}function Hc(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Bs(t){return t.path??t.route??t.name??""}function Wc(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 zs(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(o=>o.toLowerCase());return e.filter(o=>{let s=lo(o).toLowerCase();return r.some(i=>s.includes(i)||i.includes(s))})}function Gc(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(o=>o.toLowerCase());return e.filter(o=>{let s=(o.name??"").toLowerCase(),i=Bs(o).toLowerCase();return r.some(n=>s.includes(n)||n.includes(s)||i.includes(n))})}function Kc(t){let e=t.stepType;if(e&&Vc.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name} ${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 Jc(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 Yc(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,o=t.heroPhoto!==!1,s=o&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),s&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let n=r.heroImages[0];e.push(`- URL: ${n.url}`),e.push(`- Alt text for img tag: "${n.alt||"Hero image"} \u2014 Photo by ${n.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 o&&!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/page.tsx.'"):o||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 n of r.sectionImages)e.push(`- ${n.url} \u2014 alt: "${n.alt||"section image"} \u2014 Photo by ${n.photographer} on Unsplash"`)}(s||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 i=Ss(t);i?(e.push(""),e.push(`### Page composition \u2014 ${i.name} archetype`),e.push(`This plan was classified as **${i.id}** \u2014 ${i.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(i.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"),s?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.push(""),e.push(ts),e.join(`
5314
+ `)}async function Qc(t){try{let e=await zo("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
5319
5315
  - Follow existing patterns in the codebase
5320
- - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function pd(e,t,r,o,s,i){let n=[];n.push(`## Step ${e.number}: ${e.name}`),n.push(""),n.push("### What to build:"),n.push(e.description),n.push(""),t.primaryAction&&(n.push("### Primary user action (non-negotiable):"),n.push(`- **Core action**: ${t.primaryAction.action}`),n.push(`- **User flow**: ${t.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),n.push(""),n.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."),n.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(s);if(t.design&&l?(n.push(cd(t.design,{hasDesignPreset:!!t.landingDesign&&(s==="landing"||s==="design")})),n.push("")):t.design&&!l&&(n.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),t.design.fonts&&n.push(`- Fonts: ${t.design.fonts.heading} / ${t.design.fonts.body}`),n.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),n.push("")),i){let b=Gn(i);if(b.length>0){n.push("### Approved wireframe (MUST READ before writing any files):"),n.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let y of b){let k=y.replace(i,"").replace(/^\//,"");n.push(`- \`${k}\``)}n.push(""),n.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."),n.push(""),n.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),n.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),n.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),n.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),n.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),n.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"),n.push("")}}t.roles&&Array.isArray(t.roles)&&t.roles.length>0&&(n.push("### Role system (from plan):"),n.push(`- Roles: ${t.roles.join(", ")}`),n.push(`- Default role for new signups: ${t.defaultRole??t.roles[0]}`),n.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),n.push("")),t.multiTenant&&(n.push("### Multi-tenant (from plan):"),n.push("- Organization tables are in `db/schema/organization.ts`"),n.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),n.push("- All data queries MUST be scoped to the current org (filter by orgId)"),n.push("- Org switcher component is at `components/org-switcher.tsx`"),n.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."),n.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."),n.push("")),t.language&&(n.push(`### Language: ${t.language}`),n.push(`ALL user-facing text must be written in ${t.language}:`),n.push("- Page titles, headings, labels, button text, placeholder text"),n.push("- Navigation items, menu labels, footer text"),n.push("- Error messages, success messages, empty states"),n.push("- Landing page copy, marketing text, CTAs"),n.push("- Form labels and validation messages"),n.push("Code (variable names, comments, file names) stays in English."),n.push(`Set the HTML lang attribute to the appropriate locale code for ${t.language}.`),n.push(""));let c=["landing","design","auth","general","crud","dashboard"];t.audienceType&&c.includes(s)&&(t.audienceType==="b2c"?(n.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),n.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),n.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),n.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),n.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),n.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),n.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),n.push("")):t.audienceType==="b2b"?(n.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),n.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),n.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),n.push("- Testimonials: from business owners who use the platform"),n.push("- Features: business benefits ('Track dietary preferences across all orders')"),n.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),n.push("")):t.audienceType==="internal"&&(n.push("### Audience: internal staff tool. No marketing copy needed."),n.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),n.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),n.push(""))),r.length>0&&(n.push("### Already completed:"),r.forEach(b=>n.push(`- ${b}`)),n.push(""));let h=t.dataModel?ai(e,t.dataModel):[];h.length>0&&(n.push("### Data model (from plan):"),h.forEach(b=>{let y=vo(b),k=rd(b.fields);n.push(`- **${y}**: ${k}`),n.push(` Schema file: \`db/schema/${y.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),n.push(""));let m=t.pages?sd(e,t.pages):[];if(m.length>0&&(n.push("### Pages to create/update:"),m.forEach(b=>{let y=b.description?` \u2014 ${b.description}`:"";n.push(`- \`${ii(b)}\`${y}`)}),n.push("")),s==="crud"&&h.length>0&&h.forEach(b=>{let y=vo(b),k=y.toLowerCase().replace(/\s+/g,"-"),I=k.endsWith("s")?k:`${k}s`;n.push(`### Files for ${y} CRUD:`),n.push(`- List page: \`app/(dashboard)/${I}/page.tsx\` (Server Component)`),n.push(`- Detail page: \`app/(dashboard)/${I}/[id]/page.tsx\``),n.push(`- Create page: \`app/(dashboard)/${I}/new/page.tsx\``),n.push(`- Server Actions: \`app/(dashboard)/${I}/actions.ts\``),n.push(`- DataTable columns: \`components/${k}-table-columns.tsx\``),n.push(`- Form: \`components/${k}-form.tsx\``),n.push("")}),l){n.push("## Design Doctrine (the standard for every UI step)"),n.push(""),n.push(Gs),n.push(""),n.push("## Design Reference Library"),n.push(""),n.push("### Typography"),n.push(Ks),n.push(""),n.push("### Color"),n.push(Ys),n.push(""),n.push("### Motion"),n.push(Xs),n.push(""),n.push("### Spatial Composition"),n.push(ei),n.push(""),n.push("### Interaction"),n.push(oi),n.push(""),n.push("### UX Writing"),n.push(ni),n.push("");let b=i?vt(i,"DESIGN.md"):void 0,y=b&&$t(b)?(()=>{try{return Er(b,"utf-8")}catch{return null}})():null;y&&(n.push("### Design system (source of truth: DESIGN.md):"),n.push(""),n.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."),n.push(""),n.push(y),n.push(""))}(s==="landing"||s==="design")&&(n.push(Hs),n.push(""));let p=e.integrationId?ht(e.integrationId):void 0;if(p){let b=gt(p.id);if(n.push("### Integration blueprint (follow this closely):"),n.push(""),n.push(`Using integration: **${p.name}** (${p.category})`),b?.docsUrl&&n.push(`Official docs: ${b.docsUrl}`),b?.envVars?.length){n.push(""),n.push("**Required environment variables:**");for(let y of b.envVars)n.push(`- \`${y.key}\`: ${y.description} \u2014 Get it at ${y.setupUrl}`);n.push(""),n.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.")}b?.packages?.length&&(n.push(""),n.push(`**Packages to install:** \`npm install ${b.packages.join(" ")}\``)),n.push(""),n.push("---"),n.push(p.prompt),n.push("---"),n.push(""),n.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."),n.push("")}let{reminders:f,skill:S}=await dd(s);return n.push(f),n.push(""),S&&!(s==="landing"&&t.landingDesign==="freeform")&&(n.push(`### ${s} reference:`),n.push(S),n.push("")),l&&(n.push("## Self-Audit \u2014 run before submitting this file"),n.push(""),n.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.`),n.push(""),n.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.'),n.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."),n.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),n.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),n.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."),n.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),n.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),n.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.'),n.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).'),n.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)."),n.push(""),n.push(`If every answer is "no, I'm good" \u2014 then submit.`),n.push("")),n.join(`
5321
- `)}async function ud(e){let{projectPath:t,step:r}=e,o=Qc(t??process.cwd()),s=od(o);if(!s)return $e(o);if(!$t(vt(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:v,ensureShadcnComponents:U}=await Promise.resolve().then(()=>(cr(),lr));await v(o);let G=await U(o);G.failed?console.error(`[implement] ${G.failed}`):G.installed.length>0&&console.error(`[implement] installed ${G.installed.length} shadcn components`)}catch(v){console.error("[implement] self-heal skipped:",v instanceof Error?v.message:String(v))}let i=s.plan;if(!i||!i.steps||i.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 n,a=i.steps.find(v=>v.status==="in_progress");if(a){let v=i.steps.findIndex(U=>U.number===a.number);v!==-1&&(i.steps[v].status="completed",n=`Auto-completed step ${a.number} (${a.name})`,si(o,s))}let l;if(r!==void 0){if(l=i.steps.find(v=>v.number===r),!l)return d(`Step ${r} not found. The plan has ${i.steps.length} steps (numbered ${i.steps[0].number} to ${i.steps[i.steps.length-1].number}).`,!0)}else if(l=i.steps.find(v=>v.status!=="completed"),!l)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:i.steps.map(v=>v.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let c=i.steps.filter(v=>v.status==="completed").map(v=>`Step ${v.number}: ${v.name}`),{readLocalState:h}=await Promise.resolve().then(()=>(et(),Dt)),m=h(o),p=ad(l),f=[];if((p==="crud"||p==="schema")&&i.dataModel&&l.entities&&l.entities.length>0){let v=ai(l,i.dataModel);for(let U of v){let G=vo(U);try{let V=(U.fields||[]).map(O=>typeof O=="string"?{name:O,type:"text"}:{name:O.name,type:nd(O.type),required:O.required!==!1});if(V.length===0)continue;let oe=s.dbProvider==="neon"?"nextjs-neon":"nextjs",D=await or(oe,G,V),j=0,ie=0;for(let O of D.files){let X=vt(o,O.path);if($t(X)){ie++;continue}Yc(Xc(X),{recursive:!0}),Nr(X,O.content),j++}let he=vt(o,"db","index.ts");if($t(he)){let O=Er(he,"utf-8");O.includes(D.dbExport)||Nr(he,O.trimEnd()+`
5322
- `+D.dbExport+`
5323
- `)}j>0?f.push(`${D.entityPascal} CRUD (${j} new files${ie>0?`, ${ie} existing skipped`:""})`):ie>0&&f.push(`${D.entityPascal} CRUD (all ${ie} files already exist \u2014 skipped)`)}catch(V){console.error(`Module generation failed for ${G} (non-fatal):`,V instanceof Error?V.message:V)}}}let S=await pd(l,i,c,null,p,o),b=i.steps.findIndex(v=>v.number===l.number);if(b!==-1&&(s.plan.steps[b].status="in_progress",si(o,s)),m&&s.projectId){let{syncRemoteState:v}=await Promise.resolve().then(()=>(et(),Dt));v(s.projectId,m).catch(()=>{})}let y=i.steps.every(v=>v.status==="completed"||v.number===l.number),k;y?k=`THIS IS THE LAST STEP. Rules for speed:
5316
+ - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Xc(t,e,r,o,s,i){let n=[];n.push(`## Step ${t.number}: ${t.name}`),n.push(""),n.push("### What to build:"),n.push(t.description),n.push(""),e.primaryAction&&(n.push("### Primary user action (non-negotiable):"),n.push(`- **Core action**: ${e.primaryAction.action}`),n.push(`- **User flow**: ${e.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),n.push(""),n.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."),n.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(s);if(e.design&&l?(n.push(Yc(e.design)),n.push("")):e.design&&!l&&(n.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&n.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),n.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),n.push("")),i){let x=An(i);if(x.length>0){n.push("### Approved wireframe (MUST READ before writing any files):"),n.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let S of x){let f=S.replace(i,"").replace(/^\//,"");n.push(`- \`${f}\``)}n.push(""),n.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."),n.push(""),n.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),n.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),n.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),n.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),n.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),n.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"),n.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(n.push("### Role system (from plan):"),n.push(`- Roles: ${e.roles.join(", ")}`),n.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),n.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),n.push("")),e.multiTenant&&(n.push("### Multi-tenant (from plan):"),n.push("- Organization tables are in `db/schema/organization.ts`"),n.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),n.push("- All data queries MUST be scoped to the current org (filter by orgId)"),n.push("- Org switcher component is at `components/org-switcher.tsx`"),n.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."),n.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."),n.push("")),e.language&&(n.push(`### Language: ${e.language}`),n.push(`ALL user-facing text must be written in ${e.language}:`),n.push("- Page titles, headings, labels, button text, placeholder text"),n.push("- Navigation items, menu labels, footer text"),n.push("- Error messages, success messages, empty states"),n.push("- Landing page copy, marketing text, CTAs"),n.push("- Form labels and validation messages"),n.push("Code (variable names, comments, file names) stays in English."),n.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),n.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(s)&&(e.audienceType==="b2c"?(n.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),n.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),n.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),n.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),n.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),n.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),n.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),n.push("")):e.audienceType==="b2b"?(n.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),n.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),n.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),n.push("- Testimonials: from business owners who use the platform"),n.push("- Features: business benefits ('Track dietary preferences across all orders')"),n.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),n.push("")):e.audienceType==="internal"&&(n.push("### Audience: internal staff tool. No marketing copy needed."),n.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),n.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),n.push(""))),r.length>0&&(n.push("### Already completed:"),r.forEach(x=>n.push(`- ${x}`)),n.push(""));let m=e.dataModel?zs(t,e.dataModel):[];m.length>0&&(n.push("### Data model (from plan):"),m.forEach(x=>{let S=lo(x),f=Hc(x.fields);n.push(`- **${S}**: ${f}`),n.push(` Schema file: \`db/schema/${S.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),n.push(""));let p=e.pages?Gc(t,e.pages):[];if(p.length>0&&(n.push("### Pages to create/update:"),p.forEach(x=>{let S=x.description?` \u2014 ${x.description}`:"";n.push(`- \`${Bs(x)}\`${S}`)}),n.push("")),s==="crud"&&m.length>0&&m.forEach(x=>{let S=lo(x),f=S.toLowerCase().replace(/\s+/g,"-"),_=f.endsWith("s")?f:`${f}s`;n.push(`### Files for ${S} CRUD:`),n.push(`- List page: \`app/(dashboard)/${_}/page.tsx\` (Server Component)`),n.push(`- Detail page: \`app/(dashboard)/${_}/[id]/page.tsx\``),n.push(`- Create page: \`app/(dashboard)/${_}/new/page.tsx\``),n.push(`- Server Actions: \`app/(dashboard)/${_}/actions.ts\``),n.push(`- DataTable columns: \`components/${f}-table-columns.tsx\``),n.push(`- Form: \`components/${f}-form.tsx\``),n.push("")}),l){n.push("## Design Doctrine (the standard for every UI step)"),n.push(""),n.push(As),n.push(""),n.push("## Design Reference Library"),n.push(""),n.push("### Typography"),n.push(Rs),n.push(""),n.push("### Color"),n.push(Ns),n.push(""),n.push("### Motion"),n.push(js),n.push(""),n.push("### Spatial Composition"),n.push(Ms),n.push(""),n.push("### Interaction"),n.push(Ls),n.push(""),n.push("### UX Writing"),n.push(Fs),n.push("");let x=i?it(i,"DESIGN.md"):void 0,S=x&&Ct(x)?(()=>{try{return yr(x,"utf-8")}catch{return null}})():null;S&&(n.push("### Design system (source of truth: DESIGN.md):"),n.push(""),n.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."),n.push(""),n.push(S),n.push(""))}(s==="landing"||s==="design")&&(n.push(Cs),n.push(""));let u=t.integrationId?et(t.integrationId):void 0;if(u){let x=tt(u.id);if(n.push("### Integration blueprint (follow this closely):"),n.push(""),n.push(`Using integration: **${u.name}** (${u.category})`),x?.docsUrl&&n.push(`Official docs: ${x.docsUrl}`),x?.envVars?.length){n.push(""),n.push("**Required environment variables:**");for(let S of x.envVars)n.push(`- \`${S.key}\`: ${S.description} \u2014 Get it at ${S.setupUrl}`);n.push(""),n.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.")}x?.packages?.length&&(n.push(""),n.push(`**Packages to install:** \`npm install ${x.packages.join(" ")}\``)),n.push(""),n.push("---"),n.push(u.prompt),n.push("---"),n.push(""),n.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."),n.push("")}let{reminders:w,skill:D}=await Qc(s);return n.push(w),n.push(""),D&&(n.push(`### ${s} reference:`),n.push(D),n.push("")),l&&(n.push("## Self-Audit \u2014 run before submitting this file"),n.push(""),n.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.`),n.push(""),n.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.'),n.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."),n.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),n.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),n.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."),n.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),n.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),n.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.'),n.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).'),n.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)."),n.push(""),n.push(`If every answer is "no, I'm good" \u2014 then submit.`),n.push("")),n.join(`
5317
+ `)}async function Zc(t){let{projectPath:e,step:r,envVarsRequired:o}=t,s=Lc(e??process.cwd());if(o&&o.length>0)try{let T=io(s,o);T.added.length>0&&console.error(`[implement] declared env.required: ${T.added.join(", ")}`)}catch(T){console.error("[implement] env var merge skipped:",T instanceof Error?T.message:String(T))}let i=zc(s);if(!i)return Re(s);if(!Ct(it(s,"node_modules")))return d(`Dependencies are not installed at ${s}. Call mist_install and projectPath='${s}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:T,ensureShadcnComponents:E}=await Promise.resolve().then(()=>(Qo(),Yo));await T(s);let C=await E(s);C.failed?console.error(`[implement] ${C.failed}`):C.installed.length>0&&console.error(`[implement] installed ${C.installed.length} shadcn components`)}catch(T){console.error("[implement] self-heal skipped:",T instanceof Error?T.message:String(T))}let n=i.plan;if(!n||!n.steps||n.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 a,l=n.steps.find(T=>T.status==="in_progress");if(l){let T=n.steps.findIndex(E=>E.number===l.number);T!==-1&&(n.steps[T].status="completed",a=`Auto-completed step ${l.number} (${l.name})`,qs(s,i))}let c;if(r!==void 0){if(c=n.steps.find(T=>T.number===r),!c)return d(`Step ${r} not found. The plan has ${n.steps.length} steps (numbered ${n.steps[0].number} to ${n.steps[n.steps.length-1].number}).`,!0)}else if(c=n.steps.find(T=>T.status!=="completed"),!c)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:n.steps.map(T=>T.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let m=n.steps.filter(T=>T.status==="completed").map(T=>`Step ${T.number}: ${T.name}`),{readLocalState:p}=await Promise.resolve().then(()=>(We(),wt)),u=p(s),w=Kc(c),D=[];if((w==="crud"||w==="schema")&&n.dataModel&&c.entities&&c.entities.length>0){let T=zs(c,n.dataModel);for(let E of T){let C=lo(E);try{let I=(E.fields||[]).map(Y=>typeof Y=="string"?{name:Y,type:"text"}:{name:Y.name,type:Wc(Y.type),required:Y.required!==!1});if(I.length===0)continue;let $=i.dbProvider==="neon"?"nextjs-neon":"nextjs",U=await Ho($,C,I),j=0,F=0;for(let Y of U.files){let te=it(s,Y.path);if(Ct(te)){F++;continue}Uc($c(te),{recursive:!0}),fr(te,Y.content),j++}let H=it(s,"db","index.ts");if(Ct(H)){let Y=yr(H,"utf-8");Y.includes(U.dbExport)||fr(H,Y.trimEnd()+`
5318
+ `+U.dbExport+`
5319
+ `)}j>0?D.push(`${U.entityPascal} CRUD (${j} new files${F>0?`, ${F} existing skipped`:""})`):F>0&&D.push(`${U.entityPascal} CRUD (all ${F} files already exist \u2014 skipped)`)}catch(I){console.error(`Module generation failed for ${C} (non-fatal):`,I instanceof Error?I.message:I)}}}let x=await Xc(c,n,m,null,w,s),S=n.steps.findIndex(T=>T.number===c.number);if(S!==-1&&(i.plan.steps[S].status="in_progress",qs(s,i)),u&&i.projectId){let{syncRemoteState:T}=await Promise.resolve().then(()=>(We(),wt));T(i.projectId,u).catch(()=>{})}let f=n.steps.every(T=>T.status==="completed"||T.number===c.number),_;f?_=`THIS IS THE LAST STEP. Rules for speed:
5324
5320
 
5325
5321
  1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
5326
5322
  2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
@@ -5329,18 +5325,18 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
5329
5325
  - app/page.tsx must be a real landing page, NOT a redirect to /login
5330
5326
  - middleware.ts must have "/" in PUBLIC_EXACT or PUBLIC_PREFIXES
5331
5327
  - Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
5332
- 5. Call mist_build({ projectPath }) (fire-and-poll \u2014 re-call with the returned jobId until status 'complete'), then mist_deploy({ action: 'deploy', projectPath }). Do NOT pause between these two calls to ask the user \u2014 the build is expected, the deploy is expected, just chain them.`:k=`IMPLEMENT THIS STEP NOW. Rules for speed:
5328
+ 5. Call mist_build({ projectPath }) (fire-and-poll \u2014 re-call with the returned jobId until status 'complete'), then mist_deploy({ action: 'deploy', projectPath, envVarsRequired: [...] }). Pass envVarsRequired on the deploy call if your code uses any process.env.X that isn't already in mistflow.json env.required (skip keys covered by integration presets \u2014 those are pre-declared). Do NOT pause between these two calls to ask the user \u2014 the build is expected, the deploy is expected, just chain them.`:_=`IMPLEMENT THIS STEP NOW. Rules for speed:
5333
5329
 
5334
5330
  1. BEFORE writing any files, tell the user: "[stepTiming.announcement]" \u2014 use the exact announcement string from the stepTiming field so they know what's happening and how long it'll take. This is a one-line status update, NOT a request for permission.
5335
5331
  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.
5336
5332
  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.
5337
5333
  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).
5338
- 5. After writing ALL files, call mist_implement to move to the next step. 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 I=ld(p),R={stepNumber:l.number,totalSteps:i.steps.length,estimatedMinutes:I,announcement:`Starting step ${l.number} of ${i.steps.length}: ${l.name}. This step usually takes ${I.min}\u2013${I.max} minutes.`},M=JSON.stringify({instruction:S,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:R,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.",...n?{autoCompleted:n}:{},...f.length>0?{generatedModules:f,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:`${c.length}/${i.steps.length} steps done`,nextAction:k});return await ed(3e3)?Zr("http://localhost:3000",M):d(M)}var td,id,li,ci=T(()=>{"use strict";ee();ge();so();yr();bs();Bs();zs();Ws();Vs();Js();Qs();Zs();ti();ri();td=Rr.object({projectPath:Rr.string().optional().describe("Path to the project directory (default: cwd)"),step:Rr.number().optional().describe("Specific step number to implement (default: next incomplete step)")});id=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);li={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:td,handler:ud}});import{z as Je}from"zod";import{resolve as md}from"path";async function di(e){let{projectPath:t,action:r,key:o,value:s,category:i,description:n,setupUrl:a}=e,l=md(t??process.cwd());if(!ae())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let h=He(l)?.projectId;if(!h)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 o?s?(await Ko(h,o,s,{category:i,description:n,setupUrl:a}),d(JSON.stringify({set:!0,key:o,message:`Environment variable '${o}' 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 m=await Vo(h);return m.length===0?d(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):d(JSON.stringify({envVars:m.map(p=>({key:p.key,category:p.category,description:p.description,hasValue:p.has_value})),message:`${m.length} environment variable(s) configured.`}))}case"delete":return o?(await Jo(h,o),d(JSON.stringify({deleted:!0,key:o,message:`Environment variable '${o}' 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(m){if(m instanceof $)return d(m.message,!0);let p=m instanceof Error?m.message:"An unexpected error occurred";return d(p,!0)}}var Nh,pi=T(()=>{"use strict";ee();ge();lt();Nh=Je.object({projectPath:Je.string().optional().describe("Path to the project directory (default: cwd)"),action:Je.enum(["set","list","delete"]).describe("Action to perform"),key:Je.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:Je.string().optional().describe("Environment variable value (required for 'set')"),category:Je.string().optional().describe("Category for the env var (default: 'custom')"),description:Je.string().optional().describe("Description of what this env var is for"),setupUrl:Je.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as Ft}from"zod";import{resolve as hd,join as gd}from"path";import{existsSync as fd,readFileSync as yd,writeFileSync as bd}from"fs";function Dr(e,t){let r=gd(e,"mistflow.json");if(!fd(r))return;let o;try{o=JSON.parse(yd(r,"utf-8"))}catch{return}o.domains=t,bd(r,JSON.stringify(o,null,2)+`
5339
- `)}async function ui(e){let{projectPath:t,action:r,domain:o,domainId:s}=e,i=hd(t??process.cwd());if(!ae())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=He(i)?.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(!o)return d("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await zo(a,o),c=await We(a);return Dr(i,c.map(h=>({domain:h.domain,status:h.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 We(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(!s){if(o){let m=(await We(a)).find(p=>p.domain===o);if(m){let p=await to(a,m.id);return d(JSON.stringify({domain:p.domain,status:p.status,ssl:p.ssl_status,error:p.error_message,message:p.status==="active"?`Domain '${p.domain}' is active and serving traffic.`:`Domain '${p.domain}' is ${p.status}. Make sure DNS records are configured correctly.`}))}return d(`Domain '${o}' not found. Use action 'list' to see configured domains.`,!0)}return d("Provide either domainId or domain name to verify.",!0)}let l=await to(a,s),c=await We(a);return Dr(i,c.map(h=>({domain:h.domain,status:h.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(!s&&!o)return d("Provide either domainId or domain name to remove.",!0);let l=s;if(!l&&o){let m=(await We(a)).find(p=>p.domain===o);if(!m)return d(`Domain '${o}' not found.`,!0);l=m.id}await Ho(a,l);let c=await We(a);return Dr(i,c.map(h=>({domain:h.domain,status:h.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 $)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var $h,mi=T(()=>{"use strict";ee();ge();lt();$h=Ft.object({projectPath:Ft.string().optional().describe("Path to the project directory (default: cwd)"),action:Ft.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:Ft.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:Ft.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as Ae}from"zod";var wd,hi,gi=T(()=>{"use strict";ee();pi();mi();wd=Ae.object({resource:Ae.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Ae.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Ae.string().optional().describe("Path to the project directory (default: cwd)"),key:Ae.string().optional().describe("(env) Variable name"),value:Ae.string().optional().describe("(env set) Variable value"),category:Ae.string().optional().describe("(env set) Category"),description:Ae.string().optional().describe("(env set) Description"),setupUrl:Ae.string().optional().describe("(env set) URL to obtain the value"),domain:Ae.string().optional().describe("(domain) Domain name"),domainId:Ae.string().optional().describe("(domain) Domain ID")}),hi={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:wd,handler:async e=>{let t=e;switch(t.resource){case"env":return di({projectPath:t.projectPath,action:t.action,key:t.key,value:t.value,category:t.category,description:t.description,setupUrl:t.setupUrl});case"domain":return ui({projectPath:t.projectPath,action:t.action,domain:t.domain,domainId:t.domainId});default:return d(`Unknown resource: ${t.resource}. Use env or domain.`,!0)}}}});import{spawn as vd,execFileSync as xd}from"child_process";import{existsSync as xo,mkdirSync as bi,openSync as jr,closeSync as Or,readSync as kd,readFileSync as wi,writeFileSync as vi,renameSync as xi,unlinkSync as Sd,readdirSync as Kh,statSync as Td}from"fs";import{homedir as ki}from"os";import{join as we,dirname as Si}from"path";import{randomBytes as Ti,randomUUID as Pd}from"crypto";function ko(){return we(ki(),".mistflow","jobs")}function Id(){return we(ki(),".mistflow","job-wrapper.cjs")}function Ad(){let e=Id(),t=Si(e);xo(t)||bi(t,{recursive:!0});let r=`v${Pi}`;if(xo(e))try{if(wi(e,"utf-8").includes(r))return e}catch{}let o=we(t,`.job-wrapper.tmp.${Ti(6).toString("hex")}`);return vi(o,Cd),xi(o,e),e}function xt(e){return we(ko(),e)}function Ci(e){return we(xt(e),"status.json")}function fi(e,t){let r=Ci(e),o=we(Si(r),`.status.tmp.${Ti(6).toString("hex")}`);try{vi(o,JSON.stringify(t,null,2)+`
5340
- `),xi(o,r)}catch(s){try{Sd(o)}catch{}throw s}}function _d(e){let t=Ci(e);if(!xo(t))return null;try{return JSON.parse(wi(t,"utf-8"))}catch{return null}}async function So(e){let t=`job_${Pd().replace(/-/g,"").slice(0,12)}`,r=xt(t);bi(r,{recursive:!0}),Or(jr(we(r,"stdout.log"),"a")),Or(jr(we(r,"stderr.log"),"a"));let o=new Date().toISOString(),s={id:t,type:e.type,status:"starting",pid:0,wrapperPid:0,startedAt:o,cmd:e.cmd,args:e.args,cwd:e.cwd};fi(t,s);let i=Ad(),n={...process.env,...e.env??{}},a=vd("node",[i,r,e.cwd,e.cmd,...e.args],{detached:!0,stdio:"ignore",env:n});a.unref();let l={...s,wrapperPid:a.pid??0};return fi(t,l),l}function Rd(e){let t=e.trim();if(!t)return NaN;let r=Date.parse(t);return Number.isFinite(r)?r:NaN}function Nd(e){let t=e.pid||e.wrapperPid;if(!t)return!1;try{process.kill(t,0)}catch{return!1}try{let r=xd("ps",["-o","lstart=","-p",String(t)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),o=Rd(r),s=Date.parse(e.startedAt);if(Number.isFinite(o)&&Number.isFinite(s)&&Math.abs(o-s)>2e3)return!1}catch{}return!0}function Ed(e,t){let r=Date.parse(e),o=t?Date.parse(t):Date.now();if(!Number.isFinite(r)||!Number.isFinite(o))return"0s";let s=Math.max(0,o-r),i=Math.floor(s/1e3);if(i<60)return`${i}s`;let n=Math.floor(i/60),a=i%60;return n<60?`${n}m ${a}s`:`${Math.floor(n/60)}h ${n%60}m`}function yi(e,t){if(!xo(e))return"";let r=Td(e);if(r.size===0)return"";let o=r.size>t?r.size-t:0,s=r.size-o,i=jr(e,"r");try{let n=Buffer.alloc(s);return kd(i,n,0,s,o),n.toString("utf-8")}finally{Or(i)}}function Dd(e,t=200){let r=yi(we(xt(e),"stdout.log"),65536),o=yi(we(xt(e),"stderr.log"),64*1024),s=[];return r.trim()&&s.push(...r.split(`
5341
- `).slice(-t).map(i=>`[out] ${i}`)),o.trim()&&s.push(...o.split(`
5342
- `).slice(-t).map(i=>`[err] ${i}`)),s.filter(i=>i.trim().length>0).join(`
5343
- `)}function qt(e){return{stdout:we(xt(e),"stdout.log"),stderr:we(xt(e),"stderr.log")}}async function Bt(e){let t=_d(e);if(!t)return null;let r=t;return(t.status==="running"||t.status==="starting")&&!Nd(t)&&(r={...t,status:"unknown_exit",endedAt:t.endedAt??new Date().toISOString()}),{...r,elapsed:Ed(r.startedAt,r.endedAt),logTail:Dd(e)}}async function To(e,t){let r=Math.max(100,t.pollIntervalMs??500),o=Date.now()+Math.max(0,t.timeoutMs),s=["complete","failed","unknown_exit"];for(;;){let i=await Bt(e);if(!i)return null;try{t.onPoll?.(i)}catch{}if(s.includes(i.status))return i;let n=o-Date.now();if(n<=0)return i;await new Promise(a=>setTimeout(a,Math.min(r,n)))}}var Pi,Cd,Mr=T(()=>{"use strict";Pi=1,Cd=`// Generated by @mistflow-ai/mcp local-jobs (v${Pi}). Do not edit.
5334
+ 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 L=Jc(w),W={stepNumber:c.number,totalSteps:n.steps.length,estimatedMinutes:L,announcement:`Starting step ${c.number} of ${n.steps.length}: ${c.name}. This step usually takes ${L.min}\u2013${L.max} minutes.`},J=JSON.stringify({instruction:x,step:{number:c.number,name:c.name,description:c.description,status:"in_progress"},stepTiming:W,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.",...a?{autoCompleted:a}:{},...D.length>0?{generatedModules:D,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:`${m.length}/${n.steps.length} steps done`,nextAction:_});return await qc(3e3)?Lr("http://localhost:3000",J):d(J)}var Bc,Vc,Hs,Ws=A(()=>{"use strict";re();de();Wt();or();es();Ts();Ps();Is();_s();Es();Ds();Os();Us();$s();gr();Bc=ao.object({projectPath:ao.string().optional().describe("Path to the project directory (default: cwd)"),step:ao.number().optional().describe("Specific step number to implement (default: next incomplete step)"),envVarsRequired:ao.array(so).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.")});Vc=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);Hs={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:Bc,handler:Zc}});import{z as Le}from"zod";import{resolve as ed}from"path";async function Gs(t){let{projectPath:e,action:r,key:o,value:s,category:i,description:n,setupUrl:a}=t,l=ed(e??process.cwd());if(!ie())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let m=De(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 o?s?(await Mo(m,o,s,{category:i,description:n,setupUrl:a}),d(JSON.stringify({set:!0,key:o,message:`Environment variable '${o}' 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 Oo(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 o?(await Uo(m,o),d(JSON.stringify({deleted:!0,key:o,message:`Environment variable '${o}' 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 G)return d(p.message,!0);let u=p instanceof Error?p.message:"An unexpected error occurred";return d(u,!0)}}var vh,Vs=A(()=>{"use strict";re();de();ze();vh=Le.object({projectPath:Le.string().optional().describe("Path to the project directory (default: cwd)"),action:Le.enum(["set","list","delete"]).describe("Action to perform"),key:Le.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:Le.string().optional().describe("Environment variable value (required for 'set')"),category:Le.string().optional().describe("Category for the env var (default: 'custom')"),description:Le.string().optional().describe("Description of what this env var is for"),setupUrl:Le.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as It}from"zod";import{resolve as td,join as od}from"path";import{existsSync as rd,readFileSync as nd,writeFileSync as sd}from"fs";function br(t,e){let r=od(t,"mistflow.json");if(!rd(r))return;let o;try{o=JSON.parse(nd(r,"utf-8"))}catch{return}o.domains=e,sd(r,JSON.stringify(o,null,2)+`
5335
+ `)}async function Ks(t){let{projectPath:e,action:r,domain:o,domainId:s}=t,i=td(e??process.cwd());if(!ie())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=De(i)?.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(!o)return d("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Eo(a,o),c=await je(a);return br(i,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 je(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(!s){if(o){let p=(await je(a)).find(u=>u.domain===o);if(p){let u=await Bt(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 '${o}' not found. Use action 'list' to see configured domains.`,!0)}return d("Provide either domainId or domain name to verify.",!0)}let l=await Bt(a,s),c=await je(a);return br(i,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(!s&&!o)return d("Provide either domainId or domain name to remove.",!0);let l=s;if(!l&&o){let p=(await je(a)).find(u=>u.domain===o);if(!p)return d(`Domain '${o}' not found.`,!0);l=p.id}await No(a,l);let c=await je(a);return br(i,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 G)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var Ah,Js=A(()=>{"use strict";re();de();ze();Ah=It.object({projectPath:It.string().optional().describe("Path to the project directory (default: cwd)"),action:It.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:It.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:It.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as ve}from"zod";var id,Ys,Qs=A(()=>{"use strict";re();Vs();Js();id=ve.object({resource:ve.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:ve.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:ve.string().optional().describe("Path to the project directory (default: cwd)"),key:ve.string().optional().describe("(env) Variable name"),value:ve.string().optional().describe("(env set) Variable value"),category:ve.string().optional().describe("(env set) Category"),description:ve.string().optional().describe("(env set) Description"),setupUrl:ve.string().optional().describe("(env set) URL to obtain the value"),domain:ve.string().optional().describe("(domain) Domain name"),domainId:ve.string().optional().describe("(domain) Domain ID")}),Ys={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:id,handler:async t=>{let e=t;switch(e.resource){case"env":return Gs({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return Ks({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{spawn as ad,execFileSync as ld}from"child_process";import{existsSync as co,mkdirSync as ei,openSync as wr,closeSync as vr,readSync as cd,readFileSync as ti,writeFileSync as oi,renameSync as ri,unlinkSync as dd,readdirSync as Uh,statSync as pd}from"fs";import{homedir as ni}from"os";import{join as ue,dirname as si}from"path";import{randomBytes as ii,randomUUID as ud}from"crypto";function po(){return ue(ni(),".mistflow","jobs")}function hd(){return ue(ni(),".mistflow","job-wrapper.cjs")}function gd(){let t=hd(),e=si(t);co(e)||ei(e,{recursive:!0});let r=`v${ai}`;if(co(t))try{if(ti(t,"utf-8").includes(r))return t}catch{}let o=ue(e,`.job-wrapper.tmp.${ii(6).toString("hex")}`);return oi(o,md),ri(o,t),t}function at(t){return ue(po(),t)}function li(t){return ue(at(t),"status.json")}function Xs(t,e){let r=li(t),o=ue(si(r),`.status.tmp.${ii(6).toString("hex")}`);try{oi(o,JSON.stringify(e,null,2)+`
5336
+ `),ri(o,r)}catch(s){try{dd(o)}catch{}throw s}}function fd(t){let e=li(t);if(!co(e))return null;try{return JSON.parse(ti(e,"utf-8"))}catch{return null}}async function uo(t){let e=`job_${ud().replace(/-/g,"").slice(0,12)}`,r=at(e);ei(r,{recursive:!0}),vr(wr(ue(r,"stdout.log"),"a")),vr(wr(ue(r,"stderr.log"),"a"));let o=new Date().toISOString(),s={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:o,cmd:t.cmd,args:t.args,cwd:t.cwd};Xs(e,s);let i=gd(),n={...process.env,...t.env??{}},a=ad("node",[i,r,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:n});a.unref();let l={...s,wrapperPid:a.pid??0};return Xs(e,l),l}function yd(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function bd(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=ld("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),o=yd(r),s=Date.parse(t.startedAt);if(Number.isFinite(o)&&Number.isFinite(s)&&Math.abs(o-s)>2e3)return!1}catch{}return!0}function wd(t,e){let r=Date.parse(t),o=e?Date.parse(e):Date.now();if(!Number.isFinite(r)||!Number.isFinite(o))return"0s";let s=Math.max(0,o-r),i=Math.floor(s/1e3);if(i<60)return`${i}s`;let n=Math.floor(i/60),a=i%60;return n<60?`${n}m ${a}s`:`${Math.floor(n/60)}h ${n%60}m`}function Zs(t,e){if(!co(t))return"";let r=pd(t);if(r.size===0)return"";let o=r.size>e?r.size-e:0,s=r.size-o,i=wr(t,"r");try{let n=Buffer.alloc(s);return cd(i,n,0,s,o),n.toString("utf-8")}finally{vr(i)}}function vd(t,e=200){let r=Zs(ue(at(t),"stdout.log"),65536),o=Zs(ue(at(t),"stderr.log"),64*1024),s=[];return r.trim()&&s.push(...r.split(`
5337
+ `).slice(-e).map(i=>`[out] ${i}`)),o.trim()&&s.push(...o.split(`
5338
+ `).slice(-e).map(i=>`[err] ${i}`)),s.filter(i=>i.trim().length>0).join(`
5339
+ `)}function At(t){return{stdout:ue(at(t),"stdout.log"),stderr:ue(at(t),"stderr.log")}}async function _t(t){let e=fd(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!bd(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:wd(r.startedAt,r.endedAt),logTail:vd(t)}}async function mo(t,e){let r=Math.max(100,e.pollIntervalMs??500),o=Date.now()+Math.max(0,e.timeoutMs),s=["complete","failed","unknown_exit"];for(;;){let i=await _t(t);if(!i)return null;try{e.onPoll?.(i)}catch{}if(s.includes(i.status))return i;let n=o-Date.now();if(n<=0)return i;await new Promise(a=>setTimeout(a,Math.min(r,n)))}}var ai,md,kr=A(()=>{"use strict";ai=1,md=`// Generated by @mistflow-ai/mcp local-jobs (v${ai}). Do not edit.
5344
5340
  const { spawn } = require('node:child_process');
5345
5341
  const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
5346
5342
  const { join, dirname } = require('node:path');
@@ -5404,25 +5400,25 @@ child.on('error', (err) => {
5404
5400
  });
5405
5401
  process.exit(1);
5406
5402
  });
5407
- `});import{z as Po}from"zod";import{resolve as jd}from"path";import{existsSync as Od}from"fs";import{join as Md}from"path";function Ld(e,t=15){let r=e.split(`
5408
- `).filter(o=>o.length>0);return r.length<=t?e:r.slice(-t).join(`
5409
- `)}var Ud,Ii,Ai=T(()=>{"use strict";ee();Mr();bt();Ud=Po.object({projectPath:Po.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:Po.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:Po.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.")}).refine(e=>!!e.projectPath||!!e.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),Ii={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:Ud,handler:async(e,t)=>{let r=e;if(r.jobId){let l=await Bt(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 m=l.elapsed,p=t?Oe(t.server,t.progressToken,()=>`Install running (${m}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let f=await To(r.jobId,{timeoutMs:c*1e3,onPoll:S=>{m=S.elapsed}});f&&(l=f)}finally{p.stop()}}if(l.status==="running"||l.status==="starting")return d(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:Ld(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")return d(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,nextAction:"Dependencies installed. Run mist_implement next to start executing plan steps."}));let h=qt(l.id);return d(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:h,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 (${h.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let o=jd(r.projectPath);if(!Od(Md(o,"package.json")))return d(`No package.json at ${o}. Confirm the path and that mist_init has scaffolded the project.`,!0);let n=`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 So({type:"install",cmd:"sh",args:["-c",n],cwd:o,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return d(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:o,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 zt}from"zod";import{resolve as $d,join as _e}from"path";import{existsSync as Me,readFileSync as _i,statSync as Fd,readdirSync as qd}from"fs";function Bd(e){let t=0,r=0,o=[e];for(;o.length>0&&r<1e4;){let s=o.pop();r++;let i;try{i=qd(s)}catch{continue}for(let n of i){let a=_e(s,n),l;try{l=Fd(a)}catch{continue}l.isDirectory()?o.push(a):l.isFile()&&(t+=l.size)}}return t}function zd(e){if(!(Me(_e(e,"open-next.config.ts"))||Me(_e(e,"open-next.config.js"))))return null;let r=_e(e,".open-next","worker.js");if(!Me(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 o=_e(e,".open-next","server-functions","default");if(!Me(o))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 s=Bd(o);return s<Ri?`Build exited 0 but the server-functions bundle is only ${s} bytes (expected at least ${Ri}). 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 Wd(e){let t=_e(ko(),e,"stdout.log"),r=_e(ko(),e,"stderr.log"),o="";try{Me(t)&&(o+=_i(t,"utf-8"))}catch{}try{Me(r)&&(o+=`
5410
- `+_i(r,"utf-8"))}catch{}return o}function Gd(e,t=15){let r=e.split(`
5411
- `).filter(o=>o.length>0);return r.length<=t?e:r.slice(-t).join(`
5412
- `)}function Vd(e){let t=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let o of e.matchAll(t)){let s=o[1];if(s.startsWith(".")||s.startsWith("@/")||s.startsWith("~/"))continue;let i=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];i&&r.add(i)}return[...r]}var Ri,Hd,Ni,Ei=T(()=>{"use strict";ee();Mr();br();bt();Ri=100*1024;Hd=zt.object({projectPath:zt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:zt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:zt.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:zt.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.")}).refine(e=>!!e.projectPath||!!e.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});Ni={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:Hd,handler:async(e,t)=>{let r=e;if(r.jobId){let c=await Bt(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 h=r.waitSeconds??20;if(h>0&&(c.status==="running"||c.status==="starting")){let k=c.elapsed,I=t?Oe(t.server,t.progressToken,()=>`Build running (${k}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let R=await To(r.jobId,{timeoutMs:h*1e3,onPoll:P=>{k=P.elapsed}});R&&(c=R)}finally{I.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Gd(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 k=zd(c.cwd);if(k){let I=qt(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:I,error:k,nextAction:k+` Full build log: ${I.stdout} and ${I.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 m=Wd(c.id),p=uo(m),f=Vd(m),S=qt(c.id),b=` Full log: ${S.stdout} and ${S.stderr}.`,y=f.length>0?`Build failed with missing modules: ${f.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.${b}`:p.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${b}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${b}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:p,missingModules:f,logTail:c.logTail,logPaths:S,nextAction:y}),!0)}let o=$d(r.projectPath);if(!Me(_e(o,"package.json")))return d(`No package.json at ${o}. Run mist_init first.`,!0);if(!Me(_e(o,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${o}' } first.`,!0);let s,i,n,a=Me(_e(o,"open-next.config.ts"))||Me(_e(o,"open-next.config.js"));r.script?(s="npm",i=["run",r.script],n=r.script):a?(s="npx",i=["-y","@opennextjs/cloudflare","build"],n="@opennextjs/cloudflare build"):(s="npm",i=["run","build"],n="build");let l=await So({type:"build",cmd:s,args:i,cwd:o});return d(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:o,script:n,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 Kd,readFileSync as Jd}from"fs";import{join as Yd}from"path";import{z as Co}from"zod";function Xd(e){let t=Yd(e,"mistflow.json");if(!Kd(t))return null;try{return JSON.parse(Jd(t,"utf-8"))}catch{return null}}async function Di(e){try{let t=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await t.text();return{status:t.status,body:r}}catch(t){return{status:0,body:String(t)}}}async function Zd(e,t,r){try{let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(t),redirect:"follow",signal:AbortSignal.timeout(15e3)}),s=await o.text(),i;try{i=JSON.parse(s)}catch{}return{status:o.status,json:i}}catch{return{status:0}}}async function ji(e){try{let t=await e.screenshot({type:"png"});return Buffer.from(t).toString("base64")}catch{return}}async function kt(e,t,r){let o=[],s=i=>{i.type()==="error"&&o.push(i.text())};e.on("console",s);try{let i=await r(),n=await ji(e);return{name:t,status:i.pass?"pass":"fail",detail:i.detail,fix:i.fix,screenshot:n,consoleErrors:o.length>0?o:void 0}}catch(i){let n=await ji(e);return{name:t,status:"fail",detail:`Unexpected error: ${i instanceof Error?i.message:String(i)}`,screenshot:n,consoleErrors:o.length>0?o:void 0}}finally{e.removeListener("console",s)}}async function ep(e){let t=e.projectPath??process.cwd(),r=Xd(t),o=e.url;if(o||(o=r?.deploy?.url),!o)return d("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);o.startsWith("http")||(o=`https://${o}`);let s=r?.projectId,i=[],n=await Di(`${o}/api/health`);if(n.status!==200)return i.push({name:"Health endpoint",status:"fail",detail:`Returns ${n.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),Io(o,i);i.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Di(`${o}/api/auth/ok`);if(a.status!==200)return i.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."}),Io(o,i);i.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,c,h;if(s){let f=await Wo(s);if(f){console.error("[qa] Calling seed endpoint for session token");let S=await Zd(`${o}/api/admin/seed`,{token:f.seedToken,email:f.email,password:"QaTemp1!"});S.status===200&&S.json?(l=S.json.sessionToken,c=S.json.email,S.json.seeded?(h=S.json.password,console.error("[qa] New admin seeded \u2014 login form test available")):console.error("[qa] Admin already exists \u2014 session injection only")):console.error(`[qa] Seed endpoint returned ${S.status}`)}}if(!l)return i.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 process injects ADMIN_SEED_TOKEN into the worker env and stores the seed token on the backend. If the seed endpoint at /api/admin/seed is missing, ensure app/api/admin/seed/route.ts exists in the scaffold."}),Io(o,i);let m,p;try{let{getIsolatedContext:f}=await Promise.resolve().then(()=>(Kt(),Mo)),S=await f();m=S.context,p=S.page}catch(f){let S=f instanceof Error?f.message:String(f);return d(JSON.stringify({status:"cannot_verify",url:o,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:S,httpChecks:i.map(({screenshot:b,...y})=>y),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${o}. 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 ${o}. 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(`
5413
- `)}),!1)}try{let f=await kt(p,"Landing page",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:3e4}),await p.waitForLoadState("networkidle").catch(()=>{});let b=await p.evaluate(()=>{let k=document.body;if(!k)return"";let I=document.createTreeWalker(k,NodeFilter.SHOW_TEXT),R="",P;for(;P=I.nextNode();){let M=P.parentElement;if(M){let F=window.getComputedStyle(M);F.display!=="none"&&F.visibility!=="hidden"&&parseFloat(F.opacity)>0&&(R+=P.textContent?.trim()+" ")}}return R.trim()});if(b.length<50)return{pass:!1,detail:`Landing page appears blank (${b.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 y=p.url();return y.includes("/login")||y.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 (${b.length} chars)`}});i.push(f);let S=!1;if(h){let b=await kt(p,"Login",async()=>{await p.goto(`${o}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let y=p.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),k=p.locator('input[type="password"], input[name="password"]');try{await y.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 y.first().fill(c),await k.first().fill(h),await p.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await p.waitForURL(R=>!R.pathname.includes("/login"),{timeout:1e4})}catch{let R=await p.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:R?`Login failed: ${R}`:"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 admin account."}}return S=!0,{pass:!0,detail:`Logged in, redirected to ${p.url()}`}});i.push(b)}else i.push({name:"Login",status:"pass",detail:"Skipped form login (redeploy, password unavailable). Using session injection."});if(!S&&l){let b=new URL(o).hostname,y=o.startsWith("https");await m.addCookies([{name:y?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:b,path:"/",httpOnly:!0,secure:y,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let b=await kt(p,"Dashboard",async()=>{p.url().includes("/dashboard")||(await p.goto(`${o}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let R=await p.content();return R.length<1e3?{pass:!1,detail:`Dashboard page is very small (${R.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await p.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 (${R.length} bytes)`}});i.push(b);let y=await p.evaluate(()=>{let I=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(P=>{let M=P.getAttribute("href");M&&M.startsWith("/")&&!M.startsWith("/api")&&!M.includes("[")&&M!=="/dashboard"&&M!=="/"&&!M.includes("/login")&&!M.includes("/sign")&&I.push(M)}),[...new Set(I)]});if(y.length>0){let I=0,R=[];for(let P of y.slice(0,8)){let M=await kt(p,`Page: ${P}`,async()=>{await p.goto(`${o}${P}`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let F=await p.title(),v=await p.content();return F.toLowerCase().includes("500")||F.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."}:F.toLowerCase().includes("404")||F.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${P} not found. Create the page or remove the nav link.`}:await p.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."}:v.length<500?{pass:!1,detail:`Page is very small (${v.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});M.status==="fail"&&(I++,R.push(P)),i.push(M)}}let k=await kt(p,"Design quality",async()=>{let I=p.url().includes("/dashboard")?p.url():`${o}/dashboard`;p.url().includes("/dashboard")||(await p.goto(I,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let R=await p.evaluate(()=>{let P=[],M=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),F=new Set;M.forEach(N=>{F.add(window.getComputedStyle(N).fontSize)}),M.length>=3&&F.size<2&&P.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 v=Array.from(M).map(N=>parseInt(N.tagName.charAt(1),10));for(let N=1;N<v.length;N++)if(v[N]-v[N-1]>1){P.push(`TYPOGRAPHY: Heading level skipped (h${v[N-1]} -> h${v[N]}). Use sequential heading levels for accessibility.`);break}let U=document.querySelectorAll("*"),G=!1,V=!1;U.forEach(N=>{let B=window.getComputedStyle(N);B.backgroundColor==="rgb(0, 0, 0)"&&N.clientHeight>100&&N.clientWidth>200&&(G=!0);let ye=B.backgroundColor,pe=B.color;if(ye&&!ye.includes("0, 0, 0")&&!ye.includes("255, 255, 255")&&ye!=="rgba(0, 0, 0, 0)"&&ye!=="transparent"&&pe.match(/rgb\((\d+), (\d+), (\d+)\)/)){let re=pe.match(/rgb\((\d+), (\d+), (\d+)\)/);if(re){let[Qe,st,it]=[parseInt(re[1]),parseInt(re[2]),parseInt(re[3])],be=Math.abs(Qe-st)<10&&Math.abs(st-it)<10&&Qe>80&&Qe<180,Ee=ye.match(/rgb\((\d+), (\d+), (\d+)\)/);if(be&&Ee){let[Xe,qe,w]=[parseInt(Ee[1]),parseInt(Ee[2]),parseInt(Ee[3])];!(Math.abs(Xe-qe)<15&&Math.abs(qe-w)<15)&&N.textContent&&N.textContent.trim().length>0&&(V=!0)}}}}),G&&P.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)."),V&&P.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 oe=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),D=!1;oe.forEach(N=>{N.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(D=!0)}),D&&P.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let j=document.querySelectorAll("p, li, span, div"),ie=0,he=0;j.forEach(N=>{N.textContent&&N.textContent.trim().length>20&&N.clientHeight>0&&(he++,window.getComputedStyle(N).textAlign==="center"&&ie++)}),he>5&&ie/he>.7&&P.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let O=new Set;U.forEach(N=>{let B=window.getComputedStyle(N);B.gap&&B.gap!=="normal"&&B.gap!=="0px"&&O.add(B.gap)}),O.size===1&&U.length>20&&P.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let X=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(N=>{N.querySelectorAll("tbody tr").length===0&&(N.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||P.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 Re=document.querySelectorAll("style"),Ne=!1;Re.forEach(N=>{let B=N.textContent||"";(B.includes("bounce")||B.includes("elastic")||B.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Ne=!0)}),Ne&&P.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let Fe=document.querySelectorAll("button, a, input, select, [role='button']"),J=0;return Fe.forEach(N=>{let B=N.getBoundingClientRect();B.width>0&&B.height>0&&(B.width<32||B.height<32)&&J++}),J>3&&P.push(`ACCESSIBILITY: ${J} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),P});return R.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${R.length} design quality issue(s) found:
5414
- ${R.map((P,M)=>`${M+1}. ${P}`).join(`
5415
- `)}`,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."}});if(i.push(k),i.find(I=>I.name==="Landing page"&&I.status==="pass")){let I=await kt(p,"Landing design quality",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let R=await p.evaluate(()=>{let P=[];document.querySelectorAll("*").forEach(U=>{let G=window.getComputedStyle(U);(G.getPropertyValue("-webkit-background-clip")||G.getPropertyValue("background-clip"))==="text"&&U.textContent&&U.textContent.trim().length>0&&P.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let F=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(F){let U=(F.textContent||"").toLowerCase(),G=["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 V of G)if(U.match(new RegExp(V))){P.push(`COPY: Generic hero text detected ('${V}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(U=>{let V=window.getComputedStyle(U).gridTemplateColumns;if(V){let oe=V.split(" ").filter(j=>j!=="").length,D=U.children;if(oe===3&&D.length===3){let j=Array.from(D).map(O=>O.offsetHeight),ie=j.every(O=>Math.abs(O-j[0])<5),he=Array.from(D).every(O=>{let X=O.querySelectorAll("svg"),fe=O.querySelectorAll("h2, h3, h4"),Re=O.querySelectorAll("p");return X.length>=1&&fe.length>=1&&Re.length>=1});ie&&he&&P.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.")}}}),P});return R.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${R.length} landing design issue(s):
5416
- ${R.map((P,M)=>`${M+1}. ${P}`).join(`
5417
- `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(I)}}}finally{m&&await m.close().catch(()=>{})}if(e.deploymentId){let f=i.filter(y=>y.status==="fail"),S=i.filter(y=>y.status==="pass"),b=Date.now();await Go(e.deploymentId,{checks:i.map(({screenshot:y,...k})=>k),overall:f.length===0?"pass":"fail",passed:S.length,failed:f.length,duration_ms:Date.now()-b}).catch(()=>{})}return Io(o,i)}function Io(e,t){let r=t.filter(i=>i.status==="fail"),o=t.filter(i=>i.status==="pass"),s=[];if(r.length===0)s.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${t.length} checks OK. The app is working correctly.`,url:e,checks:t.map(({screenshot:i,...n})=>n)})});else{let i=r.map((n,a)=>`${a+1}. **${n.name}**: ${n.detail}
5403
+ `});import{z as ho}from"zod";import{resolve as kd}from"path";import{existsSync as xd}from"fs";import{join as Sd}from"path";function Td(t,e=15){let r=t.split(`
5404
+ `).filter(o=>o.length>0);return r.length<=e?t:r.slice(-e).join(`
5405
+ `)}var Pd,ci,di=A(()=>{"use strict";re();kr();nt();Pd=ho.object({projectPath:ho.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:ho.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:ho.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.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),ci={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:Pd,handler:async(t,e)=>{let r=t;if(r.jobId){let l=await _t(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?Te(e.server,e.progressToken,()=>`Install running (${p}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let w=await mo(r.jobId,{timeoutMs:c*1e3,onPoll:D=>{p=D.elapsed}});w&&(l=w)}finally{u.stop()}}if(l.status==="running"||l.status==="starting")return d(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:Td(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")return d(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,nextAction:"Dependencies installed. Run mist_implement next to start executing plan steps."}));let m=At(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 o=kd(r.projectPath);if(!xd(Sd(o,"package.json")))return d(`No package.json at ${o}. Confirm the path and that mist_init has scaffolded the project.`,!0);let n=`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 uo({type:"install",cmd:"sh",args:["-c",n],cwd:o,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return d(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:o,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 Rt}from"zod";import{resolve as Cd,join as ke}from"path";import{existsSync as Pe,readFileSync as pi,statSync as Id,readdirSync as Ad}from"fs";function _d(t){let e=0,r=0,o=[t];for(;o.length>0&&r<1e4;){let s=o.pop();r++;let i;try{i=Ad(s)}catch{continue}for(let n of i){let a=ke(s,n),l;try{l=Id(a)}catch{continue}l.isDirectory()?o.push(a):l.isFile()&&(e+=l.size)}}return e}function Rd(t){if(!(Pe(ke(t,"open-next.config.ts"))||Pe(ke(t,"open-next.config.js"))))return null;let r=ke(t,".open-next","worker.js");if(!Pe(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 o=ke(t,".open-next","server-functions","default");if(!Pe(o))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 s=_d(o);return s<ui?`Build exited 0 but the server-functions bundle is only ${s} bytes (expected at least ${ui}). 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 Nd(t){let e=ke(po(),t,"stdout.log"),r=ke(po(),t,"stderr.log"),o="";try{Pe(e)&&(o+=pi(e,"utf-8"))}catch{}try{Pe(r)&&(o+=`
5406
+ `+pi(r,"utf-8"))}catch{}return o}function Dd(t,e=15){let r=t.split(`
5407
+ `).filter(o=>o.length>0);return r.length<=e?t:r.slice(-e).join(`
5408
+ `)}function jd(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let o of t.matchAll(e)){let s=o[1];if(s.startsWith(".")||s.startsWith("@/")||s.startsWith("~/"))continue;let i=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];i&&r.add(i)}return[...r]}var ui,Ed,mi,hi=A(()=>{"use strict";re();kr();rr();nt();ui=100*1024;Ed=Rt.object({projectPath:Rt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Rt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Rt.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:Rt.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.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});mi={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:Ed,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await _t(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 f=c.elapsed,_=e?Te(e.server,e.progressToken,()=>`Build running (${f}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let L=await mo(r.jobId,{timeoutMs:m*1e3,onPoll:W=>{f=W.elapsed}});L&&(c=L)}finally{_.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Dd(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 f=Rd(c.cwd);if(f){let _=At(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:_,error:f,nextAction:f+` Full build log: ${_.stdout} and ${_.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=Nd(c.id),u=Qt(p),w=jd(p),D=At(c.id),x=` Full log: ${D.stdout} and ${D.stderr}.`,S=w.length>0?`Build failed with missing modules: ${w.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.${x}`:u.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${x}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${x}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:u,missingModules:w,logTail:c.logTail,logPaths:D,nextAction:S}),!0)}let o=Cd(r.projectPath);if(!Pe(ke(o,"package.json")))return d(`No package.json at ${o}. Run mist_init first.`,!0);if(!Pe(ke(o,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${o}' } first.`,!0);let s,i,n,a=Pe(ke(o,"open-next.config.ts"))||Pe(ke(o,"open-next.config.js"));r.script?(s="npm",i=["run",r.script],n=r.script):a?(s="npx",i=["-y","@opennextjs/cloudflare","build"],n="@opennextjs/cloudflare build"):(s="npm",i=["run","build"],n="build");let l=await uo({type:"build",cmd:s,args:i,cwd:o});return d(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:o,script:n,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 Od,readFileSync as Md}from"fs";import{join as Ud}from"path";import{z as go}from"zod";function $d(t){let e=Ud(t,"mistflow.json");if(!Od(e))return null;try{return JSON.parse(Md(e,"utf-8"))}catch{return null}}async function gi(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 Fd(t,e,r){try{let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),s=await o.text(),i;try{i=JSON.parse(s)}catch{}return{status:o.status,json:i}}catch{return{status:0}}}async function fi(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function $e(t,e,r){let o=[],s=i=>{i.type()==="error"&&o.push(i.text())};t.on("console",s);try{let i=await r(),n=await fi(t);return{name:e,status:i.pass?"pass":"fail",detail:i.detail,fix:i.fix,screenshot:n,consoleErrors:o.length>0?o:void 0}}catch(i){let n=await fi(t);return{name:e,status:"fail",detail:`Unexpected error: ${i instanceof Error?i.message:String(i)}`,screenshot:n,consoleErrors:o.length>0?o:void 0}}finally{t.removeListener("console",s)}}async function qd(t){let e=t.projectPath??process.cwd(),r=$d(e),o=t.url;if(o||(o=r?.deploy?.url),!o)return d("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);o.startsWith("http")||(o=`https://${o}`);let s=r?.projectId,i=[],n=await gi(`${o}/api/health`);if(n.status!==200)return i.push({name:"Health endpoint",status:"fail",detail:`Returns ${n.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),fo(o,i);i.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await gi(`${o}/api/auth/ok`);if(a.status!==200)return i.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."}),fo(o,i);i.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",w=[];async function D(_,L,W,R){let J=await Fd(`${o}/api/admin/seed`,{token:R,email:L,password:m,role:W});if(J.status!==200||!J.json)return console.error(`[qa] Seed (${_}) returned ${J.status}`),null;let q=J.json.sessionToken;if(!q)return null;let T=J.json.seeded===!0;return{role:_,email:L,sessionToken:q,password:T?m:void 0}}if(s){let _=await Do(s);if(_){if(p=_.authMode??"single",u=_.defaultRole??"user",console.error(`[qa] auth_mode=${p}, default_role=${u}`),p!=="none"){let W=await D("actor",l,p==="multi"?"admin":u,_.seedToken);if(W&&w.push(W),p==="multi"){let R=await D("user",c,u,_.seedToken);R?w.push(R):i.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"&&w.length===0)return i.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."}),fo(o,i);let x,S,f;try{let{getIsolatedContext:_}=await Promise.resolve().then(()=>(mt(),Ot)),L=await _();x=L.context,f=L.page}catch(_){let L=_ instanceof Error?_.message:String(_);return d(JSON.stringify({status:"cannot_verify",url:o,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:L,httpChecks:i.map(({screenshot:W,...R})=>R),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${o}. 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 ${o}. 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(`
5409
+ `)}),!1)}try{let _=await $e(f,"Landing page",async()=>{await f.goto(o,{waitUntil:"domcontentloaded",timeout:3e4}),await f.waitForLoadState("networkidle").catch(()=>{});let q=await f.evaluate(()=>{let E=document.body;if(!E)return"";let C=document.createTreeWalker(E,NodeFilter.SHOW_TEXT),I="",$;for(;$=C.nextNode();){let U=$.parentElement;if(U){let j=window.getComputedStyle(U);j.display!=="none"&&j.visibility!=="hidden"&&parseFloat(j.opacity)>0&&(I+=$.textContent?.trim()+" ")}}return I.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 T=f.url();return T.includes("/login")||T.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)`}});i.push(_),p==="none"&&i.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let L=w[0],W=(q,T)=>w.length>1&&q?`${T} (${q.role})`:T,R=!1;if(L?.password){let q=await $e(f,W(L,"Login"),async()=>{await f.goto(`${o}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{});let T=f.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),E=f.locator('input[type="password"], input[name="password"]');try{await T.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 T.first().fill(L.email),await E.first().fill(L.password),await f.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await f.waitForURL(I=>!I.pathname.includes("/login"),{timeout:1e4})}catch{let I=await f.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:I?`Login failed: ${I}`:"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 R=!0,{pass:!0,detail:`Logged in, redirected to ${f.url()}`}});i.push(q)}else L&&i.push({name:W(L,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!R&&L){let q=new URL(o).hostname,T=o.startsWith("https");await x.addCookies([{name:T?"__Secure-better-auth.session_token":"better-auth.session_token",value:L.sessionToken,domain:q,path:"/",httpOnly:!0,secure:T,sameSite:"Lax"}]),console.error(`[qa] Injected ${L.role} cookie for primary walk`)}if(L){let q=await $e(f,W(L,"Dashboard"),async()=>{f.url().includes("/dashboard")||(await f.goto(`${o}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{}),new URL(f.url()).pathname==="/"&&(await f.goto(`${o}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{})));let C=await f.content();return C.length<1e3?{pass:!1,detail:`Dashboard page is very small (${C.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await f.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 (${C.length} bytes)`}});i.push(q);let T=await f.evaluate(()=>{let C=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach($=>{let U=$.getAttribute("href");U&&U.startsWith("/")&&!U.startsWith("/api")&&!U.includes("[")&&U!=="/dashboard"&&U!=="/"&&!U.includes("/login")&&!U.includes("/sign")&&C.push(U)}),[...new Set(C)]});if(T.length>0){let C=0,I=[];for(let $ of T.slice(0,8)){let U=await $e(f,W(L,`Page: ${$}`),async()=>{await f.goto(`${o}${$}`,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{});let j=await f.title(),F=await f.content();return j.toLowerCase().includes("500")||j.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."}:j.toLowerCase().includes("404")||j.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${$} not found. Create the page or remove the nav link.`}:await f.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"}});U.status==="fail"&&(C++,I.push($)),i.push(U)}}let E=await $e(f,"Design quality",async()=>{let C=f.url().includes("/dashboard")?f.url():`${o}/dashboard`;f.url().includes("/dashboard")||(await f.goto(C,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{}));let I=await f.evaluate(()=>{let $=[],U=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),j=new Set;U.forEach(y=>{j.add(window.getComputedStyle(y).fontSize)}),U.length>=3&&j.size<2&&$.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(U).map(y=>parseInt(y.tagName.charAt(1),10));for(let y=1;y<F.length;y++)if(F[y]-F[y-1]>1){$.push(`TYPOGRAPHY: Heading level skipped (h${F[y-1]} -> h${F[y]}). Use sequential heading levels for accessibility.`);break}let H=document.querySelectorAll("*"),Y=!1,te=!1;H.forEach(y=>{let v=window.getComputedStyle(y);v.backgroundColor==="rgb(0, 0, 0)"&&y.clientHeight>100&&y.clientWidth>200&&(Y=!0);let B=v.backgroundColor,g=v.color;if(B&&!B.includes("0, 0, 0")&&!B.includes("255, 255, 255")&&B!=="rgba(0, 0, 0, 0)"&&B!=="transparent"&&g.match(/rgb\((\d+), (\d+), (\d+)\)/)){let k=g.match(/rgb\((\d+), (\d+), (\d+)\)/);if(k){let[N,K,ee]=[parseInt(k[1]),parseInt(k[2]),parseInt(k[3])],X=Math.abs(N-K)<10&&Math.abs(K-ee)<10&&N>80&&N<180,P=B.match(/rgb\((\d+), (\d+), (\d+)\)/);if(X&&P){let[O,Z,oe]=[parseInt(P[1]),parseInt(P[2]),parseInt(P[3])];!(Math.abs(O-Z)<15&&Math.abs(Z-oe)<15)&&y.textContent&&y.textContent.trim().length>0&&(te=!0)}}}}),Y&&$.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)."),te&&$.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 xe=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),Se=!1;xe.forEach(y=>{y.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(Se=!0)}),Se&&$.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let Q=document.querySelectorAll("p, li, span, div"),Ce=0,Ie=0;Q.forEach(y=>{y.textContent&&y.textContent.trim().length>20&&y.clientHeight>0&&(Ie++,window.getComputedStyle(y).textAlign==="center"&&Ce++)}),Ie>5&&Ce/Ie>.7&&$.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let Ae=new Set;H.forEach(y=>{let v=window.getComputedStyle(y);v.gap&&v.gap!=="normal"&&v.gap!=="0px"&&Ae.add(v.gap)}),Ae.size===1&&H.length>20&&$.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(y=>{y.querySelectorAll("tbody tr").length===0&&(y.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||$.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 Ye=document.querySelectorAll("style"),he=!1;Ye.forEach(y=>{let v=y.textContent||"";(v.includes("bounce")||v.includes("elastic")||v.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(he=!0)}),he&&$.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let h=document.querySelectorAll("button, a, input, select, [role='button']"),b=0;return h.forEach(y=>{let v=y.getBoundingClientRect();v.width>0&&v.height>0&&(v.width<32||v.height<32)&&b++}),b>3&&$.push(`ACCESSIBILITY: ${b} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),$});return I.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${I.length} design quality issue(s) found:
5410
+ ${I.map(($,U)=>`${U+1}. ${$}`).join(`
5411
+ `)}`,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."}});i.push(E)}if(i.find(q=>q.name==="Landing page"&&q.status==="pass")){let q=await $e(f,"Landing design quality",async()=>{await f.goto(o,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{});let T=await f.evaluate(()=>{let E=[];document.querySelectorAll("*").forEach(U=>{let j=window.getComputedStyle(U);(j.getPropertyValue("-webkit-background-clip")||j.getPropertyValue("background-clip"))==="text"&&U.textContent&&U.textContent.trim().length>0&&E.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let I=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(I){let U=(I.textContent||"").toLowerCase(),j=["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 j)if(U.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(U=>{let F=window.getComputedStyle(U).gridTemplateColumns;if(F){let H=F.split(" ").filter(te=>te!=="").length,Y=U.children;if(H===3&&Y.length===3){let te=Array.from(Y).map(Q=>Q.offsetHeight),xe=te.every(Q=>Math.abs(Q-te[0])<5),Se=Array.from(Y).every(Q=>{let Ce=Q.querySelectorAll("svg"),Ie=Q.querySelectorAll("h2, h3, h4"),Ae=Q.querySelectorAll("p");return Ce.length>=1&&Ie.length>=1&&Ae.length>=1});xe&&Se&&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 T.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${T.length} landing design issue(s):
5412
+ ${T.map((E,C)=>`${C+1}. ${E}`).join(`
5413
+ `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(q)}let J=w[1];if(J){let{getIsolatedContext:q}=await Promise.resolve().then(()=>(mt(),Ot)),T=await q();S=T.context;let E=T.page,C=new URL(o).hostname,I=o.startsWith("https");await S.addCookies([{name:I?"__Secure-better-auth.session_token":"better-auth.session_token",value:J.sessionToken,domain:C,path:"/",httpOnly:!0,secure:I,sameSite:"Lax"}]),console.error(`[qa] Injected ${J.role} cookie for secondary walk`);let $=await $e(E,W(J,"Dashboard"),async()=>{await E.goto(`${o}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await E.waitForLoadState("networkidle").catch(()=>{}),new URL(E.url()).pathname==="/"&&(await E.goto(`${o}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await E.waitForLoadState("networkidle").catch(()=>{}));let j=await E.content();return j.length<1e3?{pass:!1,detail:`Dashboard is very small (${j.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 (${j.length} bytes)`}});i.push($);let U=await E.evaluate(()=>{let j=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(F=>{let H=F.getAttribute("href");H&&H.startsWith("/")&&!H.startsWith("/api")&&!H.includes("[")&&H!=="/dashboard"&&H!=="/"&&!H.includes("/login")&&!H.includes("/sign")&&j.push(H)}),[...new Set(j)]});for(let j of U.slice(0,8)){let F=await $e(E,W(J,`Page: ${j}`),async()=>{await E.goto(`${o}${j}`,{waitUntil:"domcontentloaded",timeout:15e3}),await E.waitForLoadState("networkidle").catch(()=>{});let H=await E.title(),Y=await E.content();return H.toLowerCase().includes("500")||H.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."}:H.toLowerCase().includes("404")||H.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."}:Y.length<500?{pass:!1,detail:`Page very small (${Y.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});i.push(F)}}}finally{x&&await x.close().catch(()=>{}),S&&await S.close().catch(()=>{})}if(t.deploymentId){let _=i.filter(R=>R.status==="fail"),L=i.filter(R=>R.status==="pass"),W=Date.now();await jo(t.deploymentId,{checks:i.map(({screenshot:R,...J})=>J),overall:_.length===0?"pass":"fail",passed:L.length,failed:_.length,duration_ms:Date.now()-W}).catch(()=>{})}return fo(o,i)}function fo(t,e){let r=e.filter(i=>i.status==="fail"),o=e.filter(i=>i.status==="pass"),s=[];if(r.length===0)s.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:i,...n})=>n)})});else{let i=r.map((n,a)=>`${a+1}. **${n.name}**: ${n.detail}
5418
5414
  Fix: ${n.fix}`).join(`
5419
5415
 
5420
- `);s.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${r.length} issue(s) on the live app. Fix them and redeploy.`,url:e,passed:o.length,failed:r.length,checks:t.map(({screenshot:n,...a})=>a),fixInstructions:`The deployed app at ${e} has ${r.length} issue(s):
5416
+ `);s.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:o.length,failed:r.length,checks:e.map(({screenshot:n,...a})=>a),fixInstructions:`The deployed app at ${t} has ${r.length} issue(s):
5421
5417
 
5422
5418
  ${i}
5423
5419
 
5424
- Fix these issues in the source code, then call mist_deploy with action='deploy'${e.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let i of t)i.screenshot&&s.push({type:"image",data:i.screenshot,mimeType:"image/png"});return{content:s}}var Qd,Oi,Mi=T(()=>{"use strict";ee();ge();Qd=Co.object({projectPath:Co.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:Co.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:Co.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.")}),Oi={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:Qd,handler:async e=>ep(e)}});import{existsSync as Ao,readdirSync as tp,statSync as Li,unlinkSync as Ui}from"fs";import{join as rt}from"path";import{execFile as op}from"child_process";function rp(e,t){let r=0;for(let o of t){let s=rt(e,o);if(Ao(s))try{let i=Li(s);if(i.isFile())r++;else if(i.isDirectory()){let n=[s];for(;n.length;){let a=n.pop(),l=tp(a,{withFileTypes:!0});for(let c of l){let h=rt(a,c.name);c.isDirectory()?n.push(h):r++}}}}catch{}}return r}function $i(e,t,r){return new Promise(o=>{op("tar",e,{cwd:t,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(s,i,n)=>{o({success:!s,stderr:n?.toString()??""})})})}async function Fi(e){let t=rt(e,".open-next-build.tar.gz"),r=[".open-next"];Ao(rt(e,"db"))&&r.push("db"),Ao(rt(e,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),Ao(rt(e,"package.json"))&&r.push("package.json");let o=rp(e,r),s=await $i(["-czf",t,"-C",e,...r],e,12e4);if(!s.success){try{Ui(t)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(s.stderr?`
5425
- ${s.stderr.slice(-500)}`:""))}let i=0;try{i=Li(t).size}catch{}return{path:t,sizeBytes:i,fileCount:o}}async function qi(e){let t=rt(e,".mistflow-source.tar.gz");return(await $i(["-czf",t,"-C",e,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],e,12e4)).success?t:null}function Lr(e){if(e)try{Ui(e)}catch{}}function Bi(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function zi(e){switch(e){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: ${e}`}}var Hi=T(()=>{"use strict"});import{z as nt}from"zod";import{resolve as np,join as sp}from"path";import{existsSync as ip}from"fs";function lp(e){return ip(sp(e,".open-next"))}function cp(e){return He(e)?.deploy?.strategy==="staging"?"preview":null}async function dp(e){let t=np(e.projectPath);if(!ae())return d("Not signed in. Call mist_setup first.",!0);let o=He(t)?.projectId;if(!o)return d(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);if(!lp(t))return d(`No .open-next build output at ${t}. Run mist_build first \u2014 the deploy tool ships the build artifact, not the raw source.`,!0);let s=e.environment??cp(t)??"production",i=null,n=null;try{i=await Fi(t),n=await qi(t);let a=await qo(o,i.path,s,e.adminEmail,void 0,n??void 0,void 0);return d(JSON.stringify({status:"running",jobId:a.deployment_id,deploymentId:a.deployment_id,environment:a.environment??s,buildSize:Bi(i.sizeBytes),buildFileCount:i.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${a.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(a){let l=a instanceof $||a instanceof Error?a.message:String(a);return d(`Deploy upload failed: ${l}`,!0)}finally{Lr(i?.path),Lr(n)}}async function pp(e,t){let r=t.ctx?Oe(t.ctx.server,t.ctx.progressToken,()=>`Deploy ${e} \u2014 waiting for terminal state`):{stop:()=>{}};try{let o=await Rt(e,{waitSeconds:t.waitSeconds}),s=zi(o.status);return o.status==="live"?d(JSON.stringify({status:"complete",jobId:o.id,deploymentId:o.id,url:o.url,completedAt:o.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${o.url??""}', deploymentId: '${o.id??""}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`})):o.status==="failed"?d(JSON.stringify({status:"failed",jobId:o.id,deploymentId:o.id,error:o.error,phase:s,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.id,deploymentId:o.id,phase:s,phaseCode:o.status,nextAction:`Still ${o.status} after the ${t.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${o.id}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(o){let s=o instanceof $||o instanceof Error?o.message:String(o);return d(`Could not fetch deploy status: ${s}`,!0)}finally{r.stop()}}async function up(e,t){if(!ae())return d("Not signed in. Call mist_setup first.",!0);let o=He(e)?.projectId;if(!o)return d(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);let s=t;if(!s)try{let n=(await pt(o)).find(a=>a.environment==="preview"&&a.status==="live");if(!n)return d("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);s=n.id}catch(i){let n=i instanceof $?i.message:String(i);return d(`Could not list deployments: ${n}`,!0)}try{let i=await Xo(o,s);return d(JSON.stringify({status:"running",jobId:i.deployment_id,deploymentId:i.deployment_id,promotedFrom:s,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${i.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(i){let n=i instanceof $||i instanceof Error?i.message:String(i);return d(`Promote failed: ${n}`,!0)}}async function mp(e){if(!ae())return d("Not signed in. Call mist_setup first.",!0);try{let t=await Zo(e);return d(JSON.stringify({status:"running",jobId:t.deployment_id,deploymentId:t.deployment_id,rollbackFrom:t.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${t.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(t){let r=t instanceof $||t instanceof Error?t.message:String(t);return d(`Rollback failed: ${r}`,!0)}}var ap,Wi,Gi=T(()=>{"use strict";ee();ge();lt();Hi();bt();ap=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("Admin email injected as BETTER_AUTH_ADMIN_EMAIL on first deploy of an auth-enabled project."),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.")});Wi={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:ap,handler:async(e,t)=>{let r=e;switch(r.action??"deploy"){case"deploy":return r.projectPath?dp({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail}):d("projectPath is required for action='deploy'.",!0);case"status":return r.deploymentId?pp(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:t}):d("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?up(r.projectPath,r.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?mp(r.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}}});var vp={};import{Server as hp}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as gp}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as fp,ListToolsRequestSchema as yp}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as bp}from"zod-to-json-schema";async function wp(){let e=process.argv.indexOf("--api-url");e!==-1&&process.argv[e+1]&&(process.env.MISTFLOW_API_URL=process.argv[e+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let t=new gp;await _o.connect(t),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var _o,Vi,Ki=T(()=>{"use strict";Be();ee();hn();En();jn();Un();yr();Kn();ls();ys();ci();gi();Ai();Ei();Mi();Gi();_o=new hp({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Hr()}),Vi=[mn,Nn,Dn,Ln,as,fs,Wn,li,Vn,hi,Ii,Ni,Oi,Wi];_o.setRequestHandler(yp,async()=>({tools:Vi.map(e=>({name:e.name,description:e.description,inputSchema:bp(e.inputSchema)}))}));_o.setRequestHandler(fp,async e=>{let t=Vi.find(r=>r.name===e.params.name);if(!t)return d(`Unknown tool: ${e.params.name}`,!0);try{let r=t.inputSchema.safeParse(e.params.arguments);if(!r.success){let i=r.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join(", ");return d(`Invalid input: ${i}`,!0)}let o=e.params._meta?.progressToken,s={server:_o,progressToken:o};try{return await t.handler(r.data,s)}finally{s.cleanup?.()}}catch(r){let o=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),d(o,!0)}});wp().catch(e=>{console.error("Fatal error:",e),process.exit(1)})});import{readFileSync as xp}from"fs";import{dirname as kp,join as Sp}from"path";import{fileURLToPath as Tp}from"url";var Ye=process.argv[2];if(Ye==="--version"||Ye==="-v"){try{let e=kp(Tp(import.meta.url)),t=Sp(e,"..","package.json"),r=JSON.parse(xp(t,"utf-8"));console.log(r.version)}catch{console.log("unknown")}process.exit(0)}(Ye==="--help"||Ye==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
5420
+ 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 i of e)i.screenshot&&s.push({type:"image",data:i.screenshot,mimeType:"image/png"});return{content:s}}var Ld,yi,bi=A(()=>{"use strict";re();de();Ld=go.object({projectPath:go.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:go.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:go.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.")}),yi={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:Ld,handler:async t=>qd(t)}});import{existsSync as yo,readdirSync as Bd,statSync as wi,unlinkSync as vi}from"fs";import{join as Ke}from"path";import{execFile as zd}from"child_process";function Hd(t,e){let r=0;for(let o of e){let s=Ke(t,o);if(yo(s))try{let i=wi(s);if(i.isFile())r++;else if(i.isDirectory()){let n=[s];for(;n.length;){let a=n.pop(),l=Bd(a,{withFileTypes:!0});for(let c of l){let m=Ke(a,c.name);c.isDirectory()?n.push(m):r++}}}}catch{}}return r}function ki(t,e,r){return new Promise(o=>{zd("tar",t,{cwd:e,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(s,i,n)=>{o({success:!s,stderr:n?.toString()??""})})})}async function xi(t){let e=Ke(t,".open-next-build.tar.gz"),r=[".open-next"];yo(Ke(t,"db"))&&r.push("db"),yo(Ke(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),yo(Ke(t,"package.json"))&&r.push("package.json");let o=Hd(t,r),s=await ki(["-czf",e,"-C",t,...r],t,12e4);if(!s.success){try{vi(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(s.stderr?`
5421
+ ${s.stderr.slice(-500)}`:""))}let i=0;try{i=wi(e).size}catch{}return{path:e,sizeBytes:i,fileCount:o}}async function Si(t){let e=Ke(t,".mistflow-source.tar.gz");return(await ki(["-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 xr(t){if(t)try{vi(t)}catch{}}function Ti(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function Pi(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 Ci=A(()=>{"use strict"});import{z as Fe}from"zod";import{resolve as Wd,join as Gd}from"path";import{existsSync as Vd}from"fs";function Jd(t){return Vd(Gd(t,".open-next"))}function Yd(t){return De(t)?.deploy?.strategy==="staging"?"preview":null}async function Qd(t){let e=Wd(t.projectPath);if(!ie())return d("Not signed in. Call mist_setup first.",!0);let o=De(e)?.projectId;if(!o)return d(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);if(!Jd(e))return d(`No .open-next build output at ${e}. Run mist_build first \u2014 the deploy tool ships the build artifact, not the raw source.`,!0);let s=t.environment??Yd(e)??"production",i=t.adminEmail??Br()?.email,n=null,a=null;try{n=await xi(e),a=await Si(e);let l=await _o(o,n.path,s,i,void 0,a??void 0,void 0);return d(JSON.stringify({status:"running",jobId:l.deployment_id,deploymentId:l.deployment_id,environment:l.environment??s,buildSize:Ti(n.sizeBytes),buildFileCount:n.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 d(`Deploy upload failed: ${c}`,!0)}finally{xr(n?.path),xr(a)}}async function Xd(t,e){let r=e.ctx?Te(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let o=await ft(t,{waitSeconds:e.waitSeconds}),s=Pi(o.status);return o.status==="live"?d(JSON.stringify({status:"complete",jobId:o.id,deploymentId:o.id,url:o.url,completedAt:o.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${o.url??""}', deploymentId: '${o.id??""}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`})):o.status==="failed"?d(JSON.stringify({status:"failed",jobId:o.id,deploymentId:o.id,error:o.error,phase:s,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.id,deploymentId:o.id,phase:s,phaseCode:o.status,nextAction:`Still ${o.status} after the ${e.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${o.id}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(o){let s=o instanceof G||o instanceof Error?o.message:String(o);return d(`Could not fetch deploy status: ${s}`,!0)}finally{r.stop()}}async function Zd(t,e){if(!ie())return d("Not signed in. Call mist_setup first.",!0);let o=De(t)?.projectId;if(!o)return d(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let s=e;if(!s)try{let n=(await Xe(o)).find(a=>a.environment==="preview"&&a.status==="live");if(!n)return d("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);s=n.id}catch(i){let n=i instanceof G?i.message:String(i);return d(`Could not list deployments: ${n}`,!0)}try{let i=await Fo(o,s);return d(JSON.stringify({status:"running",jobId:i.deployment_id,deploymentId:i.deployment_id,promotedFrom:s,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${i.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(i){let n=i instanceof G||i instanceof Error?i.message:String(i);return d(`Promote failed: ${n}`,!0)}}async function ep(t){if(!ie())return d("Not signed in. Call mist_setup first.",!0);try{let e=await qo(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 G||e instanceof Error?e.message:String(e);return d(`Rollback failed: ${r}`,!0)}}var Kd,Ii,Ai=A(()=>{"use strict";re();de();ze();ze();Ci();nt();gr();Kd=Fe.object({action:Fe.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:Fe.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:Fe.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:Fe.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:Fe.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:Fe.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:Fe.array(so).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'.")});Ii={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:Kd,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 s=io(r.projectPath,r.envVarsRequired);s.added.length>0&&console.error(`[deploy] declared env.required: ${s.added.join(", ")}`)}catch(s){console.error("[deploy] env var merge skipped:",s instanceof Error?s.message:String(s))}return Qd({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail})}case"status":return r.deploymentId?Xd(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e}):d("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?Zd(r.projectPath,r.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?ep(r.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}}});var ap={};import{Server as tp}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as op}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as rp,ListToolsRequestSchema as np}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as sp}from"zod-to-json-schema";async function ip(){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 op;await bo.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var bo,_i,Ri=A(()=>{"use strict";Ee();re();Zr();hn();fn();vn();or();Rn();Hn();Zn();Ws();Qs();di();hi();bi();Ai();bo=new tp({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:_r()}),_i=[Xr,mn,gn,wn,zn,Xn,In,Hs,_n,Ys,ci,mi,yi,Ii];bo.setRequestHandler(np,async()=>({tools:_i.map(t=>({name:t.name,description:t.description,inputSchema:sp(t.inputSchema)}))}));bo.setRequestHandler(rp,async t=>{let e=_i.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 i=r.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join(", ");return d(`Invalid input: ${i}`,!0)}let o=t.params._meta?.progressToken,s={server:bo,progressToken:o};try{return await e.handler(r.data,s)}finally{s.cleanup?.()}}catch(r){let o=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),d(o,!0)}});ip().catch(t=>{console.error("Fatal error:",t),process.exit(1)})});import{readFileSync as lp}from"fs";import{dirname as cp,join as dp}from"path";import{fileURLToPath as pp}from"url";var qe=process.argv[2];if(qe==="--version"||qe==="-v"){try{let t=cp(pp(import.meta.url)),e=dp(t,"..","package.json"),r=JSON.parse(lp(e,"utf-8"));console.log(r.version)}catch{console.log("unknown")}process.exit(0)}(qe==="--help"||qe==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
5426
5422
 
5427
5423
  Usage:
5428
5424
  npx @mistflow-ai/mcp Start the MCP server on stdio (default; invoked by editors)
@@ -5430,8 +5426,8 @@ Usage:
5430
5426
 
5431
5427
  To install the server into your editor config, use the installer:
5432
5428
  npx -y mistflow-ai install
5433
- `),process.exit(0));(Ye==="install"||Ye==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${Ye}' is no longer supported.
5429
+ `),process.exit(0));(qe==="install"||qe==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${qe}' is no longer supported.
5434
5430
  Use the installer package instead:
5435
5431
 
5436
- npx -y mistflow-ai ${Ye}
5437
- `),process.exit(1));await Promise.resolve().then(()=>(Ki(),vp));
5432
+ npx -y mistflow-ai ${qe}
5433
+ `),process.exit(1));await Promise.resolve().then(()=>(Ri(),ap));