@mistflow-ai/mcp 1.0.11 → 1.0.13

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 +145 -141
  2. package/dist/index.js +142 -138
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,27 +1,27 @@
1
1
  #!/usr/bin/env node
2
- var Ki=Object.defineProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var $t=(t,e)=>{for(var r in e)Ki(t,r,{get:e[r],enumerable:!0})};function zr(){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(oa),t.push(""),t.push(Ji),t.push(""),t.push(Yi),t.push(""),t.push(Qi),t.push(""),t.push(Xi),t.push(""),t.push(ra),t.push(""),t.push(ea),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(Zi),t.push(""),t.push(ta),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 Ji,Yi,Qi,Xi,Zi,ea,ta,oa,ra,Lr,Ur,$r,Fr,qr,Br,Le=P(()=>{"use strict";Ji="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.",Yi='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"`.',Qi="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.",Xi="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.",Zi='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.',ea="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.",ta="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.",oa='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.',ra="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.",Lr="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).",Ur="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.",$r="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.",Fr="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.",qr="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).",Br="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 Io,readFileSync as Vr,writeFileSync as na,mkdirSync as sa}from"fs";import{join as To,dirname as Po}from"path";import{homedir as ia}from"os";import{fileURLToPath as aa}from"url";function xe(){if(Ft)return Ft;try{let t=aa(import.meta.url),e=Po(t);for(let r=0;r<6;r++){let o=To(e,"package.json");if(Io(o)){let i=JSON.parse(Vr(o,"utf-8"));if(i.name==="@mistflow-ai/mcp"&&typeof i.version=="string")return Ft=i.version,i.version}let s=Po(e);if(s===e)break;e=s}}catch{}return Ft="0.0.0","0.0.0"}function qt(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 Hr(t,e){let r=qt(t),o=qt(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 Kr(t,e,r){if(r&&Hr(t,r)<0)return"unsupported";if(!e||Hr(t,e)>=0)return"none";let s=qt(t),i=qt(e);return!s||!i?"none":s[0]<i[0]?"major":s[1]<i[1]?"minor":"patch"}function vt(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||(ke={latest:e,minSupported:r,changelogUrl:o})}function Jr(){let t=process.env.MISTFLOW_STATE_DIR||To(ia(),".mistflow");return To(t,"upgrade-state.json")}function la(){try{let t=Jr();return Io(t)?JSON.parse(Vr(t,"utf-8")):{}}catch{return{}}}function ca(t){try{let e=Jr(),r=Po(e);Io(r)||sa(r,{recursive:!0}),na(e,JSON.stringify(t,null,2)+`
4
- `,{mode:384})}catch{}}function da(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Yr(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!ke)return null;let t=xe();if(t==="0.0.0")return null;let e=Kr(t,ke.latest,ke.minSupported);if(e==="none")return null;if(e==="unsupported")return Gr(e,t,ke);if(Wr)return null;let r=la(),o=Date.now(),s=da(e);return r.dismissedForVersion===ke.latest&&e!=="major"||r.lastLatestSeen===ke.latest&&r.lastShownMs&&o-r.lastShownMs<s?null:(Wr=!0,ca({...r,lastShownMs:o,lastLatestSeen:ke.latest}),Gr(e,t,ke))}function Gr(t,e,r){let o="npx -y mistflow-ai install",s=r.changelogUrl?`
5
- What's new: ${r.changelogUrl}`:"";return t==="unsupported"?`
2
+ var Ji=Object.defineProperty;var P=(e,t)=>()=>(e&&(t=e(e=0)),t);var zt=(e,t)=>{for(var r in t)Ji(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(ra),e.push(""),e.push(Yi),e.push(""),e.push(Qi),e.push(""),e.push(Xi),e.push(""),e.push(Zi),e.push(""),e.push(na),e.push(""),e.push(ta),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(ea),e.push(""),e.push(oa),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 Yi,Qi,Xi,Zi,ea,ta,oa,ra,na,Ur,$r,Fr,qr,Br,zr,Ue=P(()=>{"use strict";Yi="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.",Qi='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"`.',Xi="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.",Zi="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.",ea='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.',ta="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.",oa="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.",ra='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.',na="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 _o,readFileSync as Kr,writeFileSync as sa,mkdirSync as ia}from"fs";import{join as Co,dirname as Ao}from"path";import{homedir as aa}from"os";import{fileURLToPath as la}from"url";function ke(){if(Ht)return Ht;try{let e=la(import.meta.url),t=Ao(e);for(let r=0;r<6;r++){let o=Co(t,"package.json");if(_o(o)){let i=JSON.parse(Kr(o,"utf-8"));if(i.name==="@mistflow-ai/mcp"&&typeof i.version=="string")return Ht=i.version,i.version}let s=Ao(t);if(s===t)break;t=s}}catch{}return Ht="0.0.0","0.0.0"}function Wt(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=Wt(e),o=Wt(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=Wt(e),i=Wt(t);return!s||!i?"none":s[0]<i[0]?"major":s[1]<i[1]?"minor":"patch"}function kt(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||(xe={latest:t,minSupported:r,changelogUrl:o})}function Yr(){let e=process.env.MISTFLOW_STATE_DIR||Co(aa(),".mistflow");return Co(e,"upgrade-state.json")}function ca(){try{let e=Yr();return _o(e)?JSON.parse(Kr(e,"utf-8")):{}}catch{return{}}}function da(e){try{let t=Yr(),r=Ao(t);_o(r)||ia(r,{recursive:!0}),sa(t,JSON.stringify(e,null,2)+`
4
+ `,{mode:384})}catch{}}function pa(e){return e==="patch"?7*864e5:e==="minor"?1*864e5:0}function Qr(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!xe)return null;let e=ke();if(e==="0.0.0")return null;let t=Jr(e,xe.latest,xe.minSupported);if(t==="none")return null;if(t==="unsupported")return Vr(t,e,xe);if(Gr)return null;let r=ca(),o=Date.now(),s=pa(t);return r.dismissedForVersion===xe.latest&&t!=="major"||r.lastLatestSeen===xe.latest&&r.lastShownMs&&o-r.lastShownMs<s?null:(Gr=!0,da({...r,lastShownMs:o,lastLatestSeen:xe.latest}),Vr(t,e,xe))}function Vr(e,t,r){let o="npx -y mistflow-ai install",s=r.changelogUrl?`
5
+ What's new: ${r.changelogUrl}`:"";return e==="unsupported"?`
6
6
 
7
7
  ---
8
- Mistflow ${e} is no longer supported.
8
+ Mistflow ${t} 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
- ---`:t==="major"?`
14
+ ---`:e==="major"?`
15
15
 
16
16
  ---
17
- Mistflow ${r.latest} is available (you have ${e}).
17
+ Mistflow ${r.latest} is available (you have ${t}).
18
18
  This is a major update. Run \`${o}\` and restart your editor.${s}
19
- ---`:t==="minor"?`
19
+ ---`:e==="minor"?`
20
20
 
21
- --- Mistflow update available: ${e} -> ${r.latest} ---
21
+ --- Mistflow update available: ${t} -> ${r.latest} ---
22
22
  Run \`${o}\` to upgrade, then restart your editor.${s}`:`
23
23
 
24
- (Mistflow ${r.latest} is out, you have ${e}. Run \`${o}\` when convenient.)`}function Co(){let t=xe(),e=ke??{latest:"",minSupported:"",changelogUrl:""},r=Kr(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:ke!==null}}var Ft,ke,Wr,kt=P(()=>{"use strict";Ft=null;ke=null;Wr=!1});var Ro={};$t(Ro,{closeBrowser:()=>_o,getIsolatedContext:()=>ua,getPage:()=>Ao,getSnapshot:()=>xt,takeScreenshot:()=>St});async function Qr(){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 pa(){let t=await Qr();return(!Se||!Se.isConnected())&&(Se=await t.chromium.launch({headless:!0})),Ue&&(await Ue.close().catch(()=>{}),Ue=null),Ue=await Se.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Re=await Ue.newPage(),Re}async function Ao(){return Re&&!Re.isClosed()?Re:(Bt||(Bt=pa().finally(()=>{Bt=null})),Bt)}async function _o(){Re&&!Re.isClosed()&&await Re.close().catch(()=>{}),Ue&&await Ue.close().catch(()=>{}),Se?.isConnected()&&await Se.close().catch(()=>{}),Re=null,Ue=null,Se=null}async function ua(){let t=await Qr();(!Se||!Se.isConnected())&&(Se=await t.chromium.launch({headless:!0}));let e=await Se.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function xt(t){return await t.locator("body").ariaSnapshot()}async function St(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var Se,Ue,Re,Bt,zt=P(()=>{"use strict";Se=null,Ue=null,Re=null,Bt=null;process.once("SIGTERM",()=>{_o().finally(()=>process.exit(0))});process.once("SIGINT",()=>{_o().finally(()=>process.exit(0))})});function c(t,e=!1){let r=t;try{let o=Yr();o&&(r=t+o)}catch{}return{content:[{type:"text",text:r}],isError:e}}function Ee(t){return c(`This is not a Mistflow project (no mistflow.json found at ${t}).
24
+ (Mistflow ${r.latest} is out, you have ${t}. Run \`${o}\` when convenient.)`}function Ro(){let e=ke(),t=xe??{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:xe!==null}}var Ht,xe,Gr,St=P(()=>{"use strict";Ht=null;xe=null;Gr=!1});var Do={};zt(Do,{closeBrowser:()=>No,getIsolatedContext:()=>ma,getPage:()=>Eo,getSnapshot:()=>Tt,takeScreenshot:()=>Pt});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 ua(){let e=await Xr();return(!Se||!Se.isConnected())&&(Se=await e.chromium.launch({headless:!0})),$e&&(await $e.close().catch(()=>{}),$e=null),$e=await Se.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Ee=await $e.newPage(),Ee}async function Eo(){return Ee&&!Ee.isClosed()?Ee:(Gt||(Gt=ua().finally(()=>{Gt=null})),Gt)}async function No(){Ee&&!Ee.isClosed()&&await Ee.close().catch(()=>{}),$e&&await $e.close().catch(()=>{}),Se?.isConnected()&&await Se.close().catch(()=>{}),Ee=null,$e=null,Se=null}async function ma(){let e=await Xr();(!Se||!Se.isConnected())&&(Se=await e.chromium.launch({headless:!0}));let t=await Se.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await t.newPage();return{context:t,page:r}}async function Tt(e){return await e.locator("body").ariaSnapshot()}async function Pt(e,t=!1){return await e.screenshot({fullPage:t,type:"png"})}var Se,$e,Ee,Gt,Vt=P(()=>{"use strict";Se=null,$e=null,Ee=null,Gt=null;process.once("SIGTERM",()=>{No().finally(()=>process.exit(0))});process.once("SIGINT",()=>{No().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 Ne(e){return d(`This is not a Mistflow project (no mistflow.json found at ${e}).
25
25
 
26
26
  Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
27
27
 
@@ -30,23 +30,23 @@ 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 Xr(t,e){try{let{getPage:r,takeScreenshot:o}=await Promise.resolve().then(()=>(zt(),Ro)),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 c(e)}}var Q=P(()=>{"use strict";kt()});import{readFileSync as Zr,existsSync as Eo,writeFileSync as ma,mkdirSync as ha,renameSync as ga,unlinkSync as fa}from"fs";import{join as No,dirname as ya}from"path";import{homedir as ba}from"os";import{randomBytes as wa}from"crypto";function en(){return No(ba(),".mistflow","credentials.json")}function Ht(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function tn(){let t=en();if(!Eo(t))return null;try{let e=JSON.parse(Zr(t,"utf-8"));return typeof e.apiKey=="string"?{[va]:e}:e}catch{return null}}function rt(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=tn();if(!e)return{ok:!1,reason:"missing"};let r=Ht(),o=e[r];return o&&typeof o.apiKey=="string"&&o.apiKey&&typeof o.orgId=="string"?{ok:!0,creds:o}:{ok:!1,reason:"missing"}}function Do(t){let e=en(),r=ya(e);Eo(r)||ha(r,{recursive:!0});let o=tn()??{},s=Ht();o[s]=t;let i=No(r,`.credentials.tmp.${wa(8).toString("hex")}`);try{ma(i,JSON.stringify(o,null,2)+`
34
- `,{mode:384}),ga(i,e)}catch(n){try{fa(i)}catch{}throw n}}function oe(){return rt().ok}function $e(t){let e=No(t,"mistflow.json");if(!Eo(e))return null;try{return JSON.parse(Zr(e,"utf-8"))}catch{return null}}var va,nt=P(()=>{"use strict";va="https://api.mistflow.ai"});var ln={};$t(ln,{MistflowApiError:()=>$,addDomain:()=>Uo,checkAuth:()=>Ta,checkAuthDetailed:()=>sn,checkSubdomain:()=>Oo,createDeployment:()=>Ia,createProject:()=>Pt,deleteEnvVar:()=>Ho,discoverDecisions:()=>Ca,downloadSource:()=>Ra,downloadSourceWithToken:()=>an,fetchDesignDirections:()=>Lo,fetchModule:()=>Qo,fetchPlanConversation:()=>Gt,fetchScaffold:()=>Jo,fetchStepContext:()=>Yo,forkTemplate:()=>Zo,generatePlan:()=>Vt,getAuthHeaders:()=>Qe,getBaseUrl:()=>re,getDashboardUrl:()=>ka,getDbCredentials:()=>Aa,getDeployLogs:()=>Wo,getDeploymentStatus:()=>It,getProject:()=>Pa,getProjectErrors:()=>Go,getSeedInfo:()=>Fo,getSiteUrl:()=>st,getTemplate:()=>Xo,hasCredentialsOnDisk:()=>oe,hasLocalCredentials:()=>nn,listDeployments:()=>at,listDomains:()=>Fe,listEnvVars:()=>Bo,markLocalSetupDone:()=>Ea,modifyPlan:()=>Kt,pingBackend:()=>jo,promotePreview:()=>Vo,redeployProject:()=>_a,removeDomain:()=>$o,rollbackDeployment:()=>Ko,shareProject:()=>er,uploadAndDeploy:()=>Mo,uploadQAResults:()=>qo,upsertEnvVar:()=>zo,verifyDomain:()=>Jt});function re(){return Ht()}function st(){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 ka(){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 Qe(){let t=rt();if(!t.ok)throw new $("auth_missing","No Mistflow credentials found.",401);return xa(t.creds)}function xa(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":xe()}}function it(t){try{vt(t.headers)}catch{}}async function jo(){try{let t=await fetch(`${re()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});it(t)}catch{}}async function rn(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 Tt(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 $(r,o,t.status,e?.details);let s=t.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",t.statusText||"Internal server error",s):new $("client_error",o,s)}async function F(t,e={}){let r=Qe(),{timeoutMs:o,idempotent:s,...i}=e,n=o??3e4,a=(i.method??"GET").toUpperCase(),l=s??(a==="GET"||a==="HEAD"),d;try{d=await rn(`${re()}${t}`,{...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(it(d),!d.ok)throw await Tt(d);return d.json()}function nn(){return rt().ok}async function Ta(){return(await sn()).ok}async function sn(){if(Wt!==null&&Date.now()<on)return Wt?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!nn())return{ok:!1,reason:"no_credentials"};try{return await F("/api/org"),Wt=!0,on=Date.now()+Sa,{ok:!0}}catch(t){if(Wt=null,!(t instanceof $))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 Pa(t){return F(`/api/projects/${encodeURIComponent(t)}`)}async function Oo(t){return F(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function Pt(t,e,r="neon",o){return F("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e,db_provider:r,requested_subdomain:o})})}async function Ia(t,e){return F("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function Mo(t,e,r="production",o,s,i,n){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),d=rt();if(!d.ok)throw new $("auth_missing","No Mistflow credentials found.",401);let h=d.creds,m=a(e),p=new Blob([m],{type:"application/gzip"}),y=new FormData;if(y.append("project_id",t),y.append("build",p,l(e)),r!=="production"&&y.append("environment",r),o&&y.append("admin_email",o),s&&y.append("schema_pushed","true"),i){let{existsSync:f}=await import("fs");if(f(i)){let T=a(i),_=new Blob([T],{type:"application/gzip"});y.append("source",_,"source.tar.gz")}}n&&y.append("git_commit_sha",n);let x;try{x=await fetch(`${re()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":xe()},body:y,signal:AbortSignal.timeout(3e5)})}catch{throw new $("network_error","Cannot reach Mistflow servers. Check your network.")}if(it(x),!x.ok)throw await Tt(x);let b=await x.json();return{...b,id:b.deployment_id}}async function It(t){return F(`/api/deploy/${encodeURIComponent(t)}/status`)}async function Lo(t){return F(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Gt(t,e){let r=e?.waitSeconds??20,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return F(`/api/plan/conversations/${encodeURIComponent(t)}${o}`,{timeoutMs:s})}async function Vt(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 F("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:o,idempotent:!1})}async function Kt(t,e){return F("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function Ca(t){return F("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Uo(t,e){return F(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function Fe(t){return F(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Jt(t,e){return F(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function $o(t,e){return F(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Aa(t){return F(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Fo(t){try{return await F(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof $&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function qo(t,e){try{return await F(`/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 Bo(t){return F(`/api/projects/${encodeURIComponent(t)}/env`)}async function zo(t,e,r,o){return F(`/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 Ho(t,e){return F(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Wo(t){return F(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Go(t,e="7d"){return F(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function at(t){return F(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function _a(t){return F(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Vo(t,e){let r=new URLSearchParams({preview_deployment_id:e});return F(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Ko(t){return F(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function Ra(t,e){let r=rt();if(!r.ok)throw new $("auth_missing","Not authenticated.",401);let o=r.creds,s=await fetch(`${re()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${o.apiKey}`,"X-Mistflow-MCP-Version":xe()},signal:AbortSignal.timeout(12e4)});if(it(s),!s.ok)throw await Tt(s);let{writeFileSync:i}=await import("fs"),n=Buffer.from(await s.arrayBuffer());i(e,n)}async function Yt(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 rn(`${re()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":xe()},...s},i,a)}catch(d){throw d instanceof Error&&d.name==="TimeoutError"?new $("network_error","Request timed out. Try again in a moment."):new $("network_error","Cannot reach Mistflow servers. Check your network.")}if(it(l),!l.ok)throw await Tt(l);return l.json()}async function Jo(t="nextjs"){return Yt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Yo(t,e){return Yt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Qo(t,e,r,o){return Yt(`/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 Xo(t){return Yt(`/api/templates/${encodeURIComponent(t)}`)}async function Zo(t){return F(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function an(t,e,r){let o;try{o=await fetch(`${re()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":xe()},signal:AbortSignal.timeout(12e4)})}catch{throw new $("network_error","Cannot reach Mistflow servers. Check your network.")}if(it(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 Tt(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(r,i)}async function Ea(t){await F(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function er(t,e){return F(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}var $,Wt,on,Sa,ge=P(()=>{"use strict";nt();kt();$=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"}};Wt=null,on=0,Sa=300*1e3});import{z as tr}from"zod";import{platform as Na}from"os";import{execFile as cn}from"child_process";function ja(t){return"error"in t}function pn(t){return new Promise(e=>setTimeout(e,t))}function Oa(t){return new Promise(e=>{let r=Na();r==="win32"?cn("cmd.exe",["/c","start","",t],o=>{o&&console.error("Could not open browser:",o.message),e(!o)}):cn(r==="darwin"?"open":"xdg-open",[t],s=>{s&&console.error("Could not open browser:",s.message),e(!s)}),setTimeout(()=>e(!1),5e3)})}async function dn(t,e,r,o){let s=r,i=o.sleep??pn;for(let n=0;n<e;n++){await i(s);let a;try{let d=await o.fetch(`${re()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!d.ok)continue;a=await d.json()}catch{continue}if(ja(a))switch(a.error){case"authorization_pending":continue;case"slow_down":s+=5e3;continue;case"expired_token":return c("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return c("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return c("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 Do({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}),c(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function La(t,e=Ma){let r=t;if(r?.apiKey)try{let n=await e.fetch(`${re()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!n.ok)return c("Invalid API key. Check the key and try again.",!0);let a=await n.json();return Do({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),c(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let n=await dn(r.deviceCode,6,5e3,e);return n||c(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(`${re()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok)return c("Cannot reach Mistflow servers. Check your internet connection.",!0);o=await n.json()}catch{return c("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 Zr(e,t){try{let{getPage:r,takeScreenshot:o}=await Promise.resolve().then(()=>(Vt(),Do)),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 Q=P(()=>{"use strict";St()});import{readFileSync as en,existsSync as jo,writeFileSync as ha,mkdirSync as ga,renameSync as fa,unlinkSync as ya}from"fs";import{join as Oo,dirname as ba}from"path";import{homedir as wa}from"os";import{randomBytes as va}from"crypto";function tn(){return Oo(wa(),".mistflow","credentials.json")}function Kt(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function on(){let e=tn();if(!jo(e))return null;try{let t=JSON.parse(en(e,"utf-8"));return typeof t.apiKey=="string"?{[xa]:t}:t}catch{return null}}function st(){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=Kt(),o=t[r];return o&&typeof o.apiKey=="string"&&o.apiKey&&typeof o.orgId=="string"?{ok:!0,creds:o}:{ok:!1,reason:"missing"}}function Mo(e){let t=tn(),r=ba(t);jo(r)||ga(r,{recursive:!0});let o=on()??{},s=Kt();o[s]=e;let i=Oo(r,`.credentials.tmp.${va(8).toString("hex")}`);try{ha(i,JSON.stringify(o,null,2)+`
34
+ `,{mode:384}),fa(i,t)}catch(n){try{ya(i)}catch{}throw n}}function oe(){return st().ok}function Fe(e){let t=Oo(e,"mistflow.json");if(!jo(t))return null;try{return JSON.parse(en(t,"utf-8"))}catch{return null}}var xa,it=P(()=>{"use strict";xa="https://api.mistflow.ai"});var cn={};zt(cn,{MistflowApiError:()=>$,addDomain:()=>qo,checkAuth:()=>Pa,checkAuthDetailed:()=>an,checkSubdomain:()=>Uo,createDeployment:()=>Ca,createProject:()=>Ct,deleteEnvVar:()=>Vo,discoverDecisions:()=>Aa,downloadSource:()=>Ea,downloadSourceWithToken:()=>ln,fetchDesignDirections:()=>Fo,fetchModule:()=>er,fetchPlanConversation:()=>Yt,fetchScaffold:()=>Xo,fetchStepContext:()=>Zo,forkTemplate:()=>or,generatePlan:()=>Qt,getAuthHeaders:()=>Xe,getBaseUrl:()=>re,getDashboardUrl:()=>ka,getDbCredentials:()=>_a,getDeployLogs:()=>Ko,getDeploymentStatus:()=>At,getProject:()=>Ia,getProjectErrors:()=>Jo,getSeedInfo:()=>zo,getSiteUrl:()=>at,getTemplate:()=>tr,hasCredentialsOnDisk:()=>oe,hasLocalCredentials:()=>sn,listDeployments:()=>ct,listDomains:()=>qe,listEnvVars:()=>Wo,markLocalSetupDone:()=>Na,modifyPlan:()=>Xt,pingBackend:()=>Lo,promotePreview:()=>Yo,redeployProject:()=>Ra,removeDomain:()=>Bo,rollbackDeployment:()=>Qo,shareProject:()=>rr,uploadAndDeploy:()=>$o,uploadQAResults:()=>Ho,upsertEnvVar:()=>Go,verifyDomain:()=>Zt});function re(){return Kt()}function at(){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 ka(){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 Xe(){let e=st();if(!e.ok)throw new $("auth_missing","No Mistflow credentials found.",401);return Sa(e.creds)}function Sa(e){return{Authorization:`ApiKey ${e.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":ke()}}function lt(e){try{kt(e.headers)}catch{}}async function Lo(){try{let e=await fetch(`${re()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});lt(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 It(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 F(e,t={}){let r=Xe(),{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(`${re()}${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(lt(c),!c.ok)throw await It(c);return c.json()}function sn(){return st().ok}async function Pa(){return(await an()).ok}async function an(){if(Jt!==null&&Date.now()<rn)return Jt?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!sn())return{ok:!1,reason:"no_credentials"};try{return await F("/api/org"),Jt=!0,rn=Date.now()+Ta,{ok:!0}}catch(e){if(Jt=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 F(`/api/projects/${encodeURIComponent(e)}`)}async function Uo(e){return F(`/api/projects/check-subdomain?name=${encodeURIComponent(e)}`)}async function Ct(e,t,r="neon",o){return F("/api/projects",{method:"POST",body:JSON.stringify({name:e,template:t,db_provider:r,requested_subdomain:o})})}async function Ca(e,t){return F("/api/deploy",{method:"POST",body:JSON.stringify({project_id:e,build_output_url:t})})}async function $o(e,t,r="production",o,s,i,n){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=st();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 v=a(i),A=new Blob([v],{type:"application/gzip"});f.append("source",A,"source.tar.gz")}}n&&f.append("git_commit_sha",n);let x;try{x=await fetch(`${re()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":ke()},body:f,signal:AbortSignal.timeout(3e5)})}catch{throw new $("network_error","Cannot reach Mistflow servers. Check your network.")}if(lt(x),!x.ok)throw await It(x);let b=await x.json();return{...b,id:b.deployment_id}}async function At(e,t){let r=t?.waitSeconds??0,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return F(`/api/deploy/${encodeURIComponent(e)}/status${o}`,r>0?{timeoutMs:s}:void 0)}async function Fo(e){return F(`/api/plan/design-directions/${encodeURIComponent(e)}`,{timeoutMs:15e3})}async function Yt(e,t){let r=t?.waitSeconds??20,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return F(`/api/plan/conversations/${encodeURIComponent(e)}${o}`,{timeoutMs:s})}async function Qt(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 F("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:o,idempotent:!1})}async function Xt(e,t){return F("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:e,modification:t})})}async function Aa(e){return F("/api/plan/discover",{method:"POST",body:JSON.stringify({description:e})})}async function qo(e,t){return F(`/api/projects/${encodeURIComponent(e)}/domains`,{method:"POST",body:JSON.stringify({domain:t})})}async function qe(e){return F(`/api/projects/${encodeURIComponent(e)}/domains`)}async function Zt(e,t){return F(`/api/projects/${encodeURIComponent(e)}/domains/${encodeURIComponent(t)}/verify`)}async function Bo(e,t){return F(`/api/projects/${encodeURIComponent(e)}/domains/${encodeURIComponent(t)}`,{method:"DELETE"})}async function _a(e){return F(`/api/projects/${encodeURIComponent(e)}/db-credentials`)}async function zo(e){try{return await F(`/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 Ho(e,t){try{return await F(`/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 Wo(e){return F(`/api/projects/${encodeURIComponent(e)}/env`)}async function Go(e,t,r,o){return F(`/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 Vo(e,t){return F(`/api/projects/${encodeURIComponent(e)}/env/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Ko(e){return F(`/api/deploy/${encodeURIComponent(e)}/logs`)}async function Jo(e,t="7d"){return F(`/api/projects/${encodeURIComponent(e)}/errors?period=${encodeURIComponent(t)}`)}async function ct(e){return F(`/api/projects/${encodeURIComponent(e)}/deployments`)}async function Ra(e){return F(`/api/deploy/${encodeURIComponent(e)}/redeploy`,{method:"POST"})}async function Yo(e,t){let r=new URLSearchParams({preview_deployment_id:t});return F(`/api/deploy/${encodeURIComponent(e)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Qo(e){return F(`/api/deploy/${encodeURIComponent(e)}/rollback`,{method:"POST"})}async function Ea(e,t){let r=st();if(!r.ok)throw new $("auth_missing","Not authenticated.",401);let o=r.creds,s=await fetch(`${re()}/api/deploy/${encodeURIComponent(e)}/source`,{headers:{Authorization:`ApiKey ${o.apiKey}`,"X-Mistflow-MCP-Version":ke()},signal:AbortSignal.timeout(12e4)});if(lt(s),!s.ok)throw await It(s);let{writeFileSync:i}=await import("fs"),n=Buffer.from(await s.arrayBuffer());i(t,n)}async function eo(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(`${re()}${e}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":ke()},...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(lt(l),!l.ok)throw await It(l);return l.json()}async function Xo(e="nextjs"){return eo(`/api/scaffold/${encodeURIComponent(e)}`)}async function Zo(e,t){return eo(`/api/scaffold/${encodeURIComponent(e)}/context?step_type=${encodeURIComponent(t)}`)}async function er(e,t,r,o){return eo(`/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 tr(e){return eo(`/api/templates/${encodeURIComponent(e)}`)}async function or(e){return F(`/api/templates/${encodeURIComponent(e)}/fork`,{method:"POST"})}async function ln(e,t,r){let o;try{o=await fetch(`${re()}/api/deploy/${encodeURIComponent(e)}/fork-source?fork_token=${encodeURIComponent(t)}`,{headers:{"X-Mistflow-MCP-Version":ke()},signal:AbortSignal.timeout(12e4)})}catch{throw new $("network_error","Cannot reach Mistflow servers. Check your network.")}if(lt(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 It(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(r,i)}async function Na(e){await F(`/api/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function rr(e,t){return F(`/api/projects/${encodeURIComponent(e)}/share`,{method:"POST",body:JSON.stringify({is_template:t?.isTemplate??!1,template_description:t?.description})})}var $,Jt,rn,Ta,ge=P(()=>{"use strict";it();St();$=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"}};Jt=null,rn=0,Ta=300*1e3});import{z as nr}from"zod";import{platform as Da}from"os";import{execFile as dn}from"child_process";function Oa(e){return"error"in e}function un(e){return new Promise(t=>setTimeout(t,e))}function Ma(e){return new Promise(t=>{let r=Da();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(`${re()}/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(Oa(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 Mo({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 Ua(e,t=La){let r=e;if(r?.apiKey)try{let n=await t.fetch(`${re()}/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 Mo({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(`${re()}/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 e.openBrowser(s)}catch{}let i=await dn(o.device_code,6,5e3,e);return i||c(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 Da,Ma,un,mn=P(()=>{"use strict";Le();Q();ge();nt();Da=tr.object({apiKey:tr.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:tr.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.")});Ma={fetch:globalThis.fetch,openBrowser:Oa,sleep:pn};un={name:"mist_setup",description:Lr,inputSchema:Da,handler:t=>La(t)}});import{existsSync as Ua,readFileSync as $a}from"fs";function hn(t){let e=new Set;if(!Ua(t))return e;let r=$a(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 gn=P(()=>{"use strict"});var _t={};$t(_t,{emptyState:()=>At,fetchRemoteState:()=>Ha,fuzzyMatch:()=>Ga,getLocalStatePath:()=>or,readLocalState:()=>za,syncRemoteState:()=>Wa,writeLocalState:()=>Ct});import{existsSync as fn,readFileSync as Fa,writeFileSync as qa,mkdirSync as Ba}from"fs";import{join as yn}from"path";function or(t){return yn(t,".mistflow","state.json")}function za(t){let e=or(t);if(!fn(e))return null;try{return JSON.parse(Fa(e,"utf-8"))}catch{return null}}function Ct(t,e){let r=yn(t,".mistflow");fn(r)||Ba(r,{recursive:!0}),qa(or(t),JSON.stringify(e,null,2)+`
39
- `)}function At(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Ha(t){let e;try{e=Qe()}catch{return null}try{let r=await fetch(`${re()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":xe()}});try{vt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function Wa(t,e){let r;try{r=Qe()}catch{return!1}try{let o=await fetch(`${re()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":xe()},body:JSON.stringify(e)});try{vt(o.headers)}catch{}return o.ok}catch{return!1}}function Ga(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 Xe=P(()=>{"use strict";ge();kt()});var rr={};$t(rr,{ensureBackendRegistered:()=>Za,ensureShadcnComponents:()=>el});import{existsSync as wn,readFileSync as Va,writeFileSync as Ka}from"fs";import{join as Qt}from"path";import{spawn as Ja}from"child_process";function Ya(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",d=>{a+=d.toString()}),n.stderr?.on("data",d=>{l+=d.toString()}),n.on("close",d=>i({success:d===0,stdout:a,stderr:l})),n.on("error",d=>i({success:!1,stdout:a,stderr:l+d.message}))})}function Qa(t){let e=Qt(t,"mistflow.json");if(!wn(e))return null;try{return JSON.parse(Va(e,"utf-8"))}catch{return null}}function Xa(t,e){Ka(Qt(t,"mistflow.json"),JSON.stringify(e,null,2))}async function bn(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(`${re()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...Qe(),"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 Za(t,e={}){let r=Qa(t);if(r){if(!oe())return r.projectId;if(!r.projectId)try{let s=r.plan?.requestedSubdomain,i=await Pt(r.name,void 0,r.dbProvider??"neon",s);return r.projectId=i.id,Xa(t,r),Ct(t,At(i.id,r.name)),r.plan&&await bn(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 bn(r.projectId,r.plan),r.projectId}}async function el(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=Qt(t,"components","ui"),i=[],n=[];for(let d of o)wn(Qt(s,`${d}.tsx`))?i.push(d):n.push(d);if(n.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Ya("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 nr=P(()=>{"use strict";ge();Xe()});import{z as qe}from"zod";import{resolve as tl,join as vn}from"path";import{existsSync as ol,readFileSync as kn,writeFileSync as rl}from"fs";var nl,xn,Sn=P(()=>{"use strict";Q();gn();nl=qe.object({action:qe.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:qe.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:qe.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:qe.object({key:qe.string(),description:qe.string().optional(),setupUrl:qe.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),xn={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:nl,handler:async t=>{let e=t,r=tl(e.projectPath??process.cwd()),o=vn(r,"mistflow.json");if(!ol(o))return Ee(r);let s;try{s=JSON.parse(kn(o,"utf-8"))}catch{return c("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!s.projectId)try{let{ensureBackendRegistered:f}=await Promise.resolve().then(()=>(nr(),rr));await f(r)&&(s=JSON.parse(kn(o,"utf-8")))}catch{}let a=s.plan,l=a?.steps?.filter(f=>f.status==="completed").length??0,d=a?.steps?.length??0,h=hn(vn(r,".env.local")),m=s.env?.required?Object.entries(s.env.required).map(([f,T])=>({name:f,description:T?.description,configured:h.has(f)})):[];s.projectId&&Promise.resolve().then(()=>(Xe(),_t)).then(({fetchRemoteState:f})=>f(s.projectId)).catch(()=>{});let p=[`Project: ${s.name}`];if(a){p.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${d} steps complete`);for(let f of a.steps){let T=f.status==="completed"?"\u2713":f.status==="in_progress"?"\u2192":" ";p.push(` [${T}] ${f.number}. ${f.name}`)}}let y=m.filter(f=>!f.configured);y.length>0&&p.push(`Missing env vars: ${y.map(f=>f.name).join(", ")}`),s.deploy?.url?p.push(`Deployed: ${s.deploy.url} (${s.deploy.count??0} deploys)`):p.push("Not deployed yet");let x=[],b=a?.steps?.find(f=>f.status!=="completed");return b?x.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${b.number} (${b.name}).`):a&&l===d&&(s.deploy?.url||x.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),y.length>0&&x.push(`Missing env vars in .env.local: ${y.map(f=>f.name).join(", ")}`),c(JSON.stringify({name:s.name,projectId:s.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:d,completedSteps:l,steps:a.steps}:null,envStatus:m,deploy:s.deploy??null,contextMessage:p.join(`
40
- `),nextSteps:x}))}let i=[];if(e.completedStep!==void 0){let a=s.plan;if(a?.steps){let l=a.steps.findIndex(d=>d.number===e.completedStep);if(l===-1)return c(`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}`)),rl(o,JSON.stringify(s,null,2)+`
41
- `),s.projectId&&Promise.resolve().then(()=>(Xe(),_t)).then(async({readLocalState:a,syncRemoteState:l})=>{let d=a(r);d&&await l(s.projectId,d)}).catch(()=>{});let n=[];if(e.completedStep!==void 0){let l=s.plan?.steps?.find(d=>d.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}`)),c(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 Xt(t){let e=lt.find(o=>o.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return lt.find(o=>{let s=o.title.toLowerCase().replace(/[^a-z0-9]/g,"");return s===r||s.includes(r)||r.includes(s)})}function Tn(t){return sr[t]}function ir(t){return t?lt.filter(e=>e.category.toLowerCase()===t.toLowerCase()):lt}function Pn(t){let e=t??lt;if(e.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 e){r[s.category]||(r[s.category]=[]);let i=sr[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}**:
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 ja,La,mn,hn=P(()=>{"use strict";Ue();Q();ge();it();ja=nr.object({apiKey:nr.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:nr.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.")});La={fetch:globalThis.fetch,openBrowser:Ma,sleep:un};mn={name:"mist_setup",description:Ur,inputSchema:ja,handler:e=>Ua(e)}});import{existsSync as $a,readFileSync as Fa}from"fs";function gn(e){let t=new Set;if(!$a(e))return t;let r=Fa(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=P(()=>{"use strict"});var Et={};zt(Et,{emptyState:()=>Rt,fetchRemoteState:()=>Wa,fuzzyMatch:()=>Va,getLocalStatePath:()=>sr,readLocalState:()=>Ha,syncRemoteState:()=>Ga,writeLocalState:()=>_t});import{existsSync as yn,readFileSync as qa,writeFileSync as Ba,mkdirSync as za}from"fs";import{join as bn}from"path";function sr(e){return bn(e,".mistflow","state.json")}function Ha(e){let t=sr(e);if(!yn(t))return null;try{return JSON.parse(qa(t,"utf-8"))}catch{return null}}function _t(e,t){let r=bn(e,".mistflow");yn(r)||za(r,{recursive:!0}),Ba(sr(e),JSON.stringify(t,null,2)+`
39
+ `)}function Rt(e,t){return{projectId:e,name:t,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Wa(e){let t;try{t=Xe()}catch{return null}try{let r=await fetch(`${re()}/api/projects/${encodeURIComponent(e)}/state`,{headers:{...t,"Content-Type":"application/json","X-Mistflow-MCP-Version":ke()}});try{kt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function Ga(e,t){let r;try{r=Xe()}catch{return!1}try{let o=await fetch(`${re()}/api/projects/${encodeURIComponent(e)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":ke()},body:JSON.stringify(t)});try{kt(o.headers)}catch{}return o.ok}catch{return!1}}function Va(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 Ze=P(()=>{"use strict";ge();St()});var ir={};zt(ir,{ensureBackendRegistered:()=>el,ensureShadcnComponents:()=>tl});import{existsSync as vn,readFileSync as Ka,writeFileSync as Ja}from"fs";import{join as to}from"path";import{spawn as Ya}from"child_process";function Qa(e,t,r,o,s){return new Promise(i=>{let n=Ya(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 Xa(e){let t=to(e,"mistflow.json");if(!vn(t))return null;try{return JSON.parse(Ka(t,"utf-8"))}catch{return null}}function Za(e,t){Ja(to(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(`${re()}/api/projects/${encodeURIComponent(e)}/state`,{method:"PUT",headers:{...Xe(),"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 el(e,t={}){let r=Xa(e);if(r){if(!oe())return r.projectId;if(!r.projectId)try{let s=r.plan?.requestedSubdomain,i=await Ct(r.name,void 0,r.dbProvider??"neon",s);return r.projectId=i.id,Za(e,r),_t(e,Rt(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 tl(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=to(e,"components","ui"),i=[],n=[];for(let c of o)vn(to(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 Qa("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 ar=P(()=>{"use strict";ge();Ze()});import{z as Be}from"zod";import{resolve as ol,join as xn}from"path";import{existsSync as rl,readFileSync as kn,writeFileSync as nl}from"fs";var sl,Sn,Tn=P(()=>{"use strict";Q();fn();sl=Be.object({action:Be.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:Be.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:Be.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:Be.object({key:Be.string(),description:Be.string().optional(),setupUrl:Be.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:sl,handler:async e=>{let t=e,r=ol(t.projectPath??process.cwd()),o=xn(r,"mistflow.json");if(!rl(o))return Ne(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(()=>(ar(),ir));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,v])=>({name:y,description:v?.description,configured:h.has(y)})):[];s.projectId&&Promise.resolve().then(()=>(Ze(),Et)).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 v=y.status==="completed"?"\u2713":y.status==="in_progress"?"\u2192":" ";p.push(` [${v}] ${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 x=[],b=a?.steps?.find(y=>y.status!=="completed");return b?x.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${b.number} (${b.name}).`):a&&l===c&&(s.deploy?.url||x.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&&x.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:x}))}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}`)),nl(o,JSON.stringify(s,null,2)+`
41
+ `),s.projectId&&Promise.resolve().then(()=>(Ze(),Et)).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 oo(e){let t=dt.find(o=>o.id===e);if(t)return t;let r=e.toLowerCase().replace(/[^a-z0-9]/g,"");return dt.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 lr[e]}function cr(e){return e?dt.filter(t=>t.category.toLowerCase()===e.toLowerCase()):dt}function In(e){let t=e??dt;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=lr[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
42
  ${i.map(n=>` \u2022 ${n}`).join(`
43
43
  `)}`);return o.join(`
44
44
 
45
- `)}function sl(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function In(t){return(t?ir(t):lt).map(r=>{let o=sr[r.id];return{id:r.id,slug:sl(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 Cn(t,e){return[]}var sr,lt,ar=P(()=>{"use strict";sr={},lt=[]});function il(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function dt(t){let e=ct.find(o=>o.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return ct.find(o=>{let s=o.name.toLowerCase().replace(/[^a-z0-9]/g,"");return s===r||s.includes(r)||r.includes(s)})}function pt(t){return lr[t]}function cr(t){return t?ct.filter(e=>e.category.toLowerCase()===t.toLowerCase()):ct}function An(t){let e=t??ct,r={};for(let s of e){r[s.category]||(r[s.category]=[]);let i=lr[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}**:
45
+ `)}function il(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Cn(e){return(e?cr(e):dt).map(r=>{let o=lr[r.id];return{id:r.id,slug:il(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 lr,dt,dr=P(()=>{"use strict";lr={},dt=[]});function al(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function ut(e){let t=pt.find(o=>o.id===e);if(t)return t;let r=e.toLowerCase().replace(/[^a-z0-9]/g,"");return pt.find(o=>{let s=o.name.toLowerCase().replace(/[^a-z0-9]/g,"");return s===r||s.includes(r)||r.includes(s)})}function mt(e){return pr[e]}function ur(e){return e?pt.filter(t=>t.category.toLowerCase()===e.toLowerCase()):pt}function _n(e){let t=e??pt,r={};for(let s of t){r[s.category]||(r[s.category]=[]);let i=pr[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
46
  ${i.map(n=>` - ${n}`).join(`
47
47
  `)}`);return o.join(`
48
48
 
49
- `)}function _n(t){return(t?cr(t):ct).map(r=>{let o=lr[r.id];return{id:r.id,slug:il(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 lr,ct,Zt=P(()=>{"use strict";lr={"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"}},ct=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
49
+ `)}function Rn(e){return(e?ur(e):pt).map(r=>{let o=pr[r.id];return{id:r.id,slug:al(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 pr,pt,ro=P(()=>{"use strict";pr={"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"}},pt=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
50
50
 
51
51
  ### File Structure
52
52
  \`\`\`
@@ -1466,12 +1466,12 @@ export function ImageGenerator() {
1466
1466
  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
1467
  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
1468
  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 de}from"zod";import{resolve as eo}from"path";import{existsSync as to,readFileSync as oo}from"fs";import{join as ro}from"path";var al,Rn,En=P(()=>{"use strict";Q();Le();Sn();ge();ar();kt();Zt();al=de.object({action:de.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:de.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:de.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:de.object({key:de.string(),description:de.string().optional(),setupUrl:de.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:de.string().optional().describe("(share) Short description of what this template builds"),category:de.string().optional().describe("(landing-designs) Filter by category"),presetId:de.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),integrationId:de.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:de.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:de.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),Rn={name:"mist_project",description:Ur,inputSchema:al,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!oe())return c("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return xn.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let o=eo(e.projectPath??process.cwd()),s=ro(o,"mistflow.json");if(!to(s))return Ee(o);let i;try{i=JSON.parse(oo(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return c("No project ID found. Deploy the project first to register it.",!0);try{let a=await er(n,{isTemplate:!0,description:e.templateDescription});return c(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
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 de}from"zod";import{resolve as no}from"path";import{existsSync as so,readFileSync as io}from"fs";import{join as ao}from"path";var ll,En,Nn=P(()=>{"use strict";Q();Ue();Tn();ge();dr();St();ro();ll=de.object({action:de.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:de.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:de.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:de.object({key:de.string(),description:de.string().optional(),setupUrl:de.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:de.string().optional().describe("(share) Short description of what this template builds"),category:de.string().optional().describe("(landing-designs) Filter by category"),presetId:de.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),integrationId:de.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:de.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:de.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),En={name:"mist_project",description:$r,inputSchema:ll,handler:async e=>{let t=e;if(["share","errors","logs","deployments"].includes(t.action)&&!oe())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=no(t.projectPath??process.cwd()),s=ao(o,"mistflow.json");if(!so(s))return Ne(o);let i;try{i=JSON.parse(io(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 rr(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!
1470
1470
 
1471
1471
  Anyone can fork it: ${a.share_url}
1472
1472
 
1473
1473
  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 c(l,!0)}}case"landing-designs":{if(e.presetId){let n=Xt(e.presetId);if(!n)return c(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let a=Tn(e.presetId);return c(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(e.category??void 0),s=ir(e.category),i=Pn(s);return c(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.${e.category?` Filtered by: ${e.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 ${st()}/designs?tab=landing-designs.`}))}case"integrations":{if(e.integrationId){let n=dt(e.integrationId);if(!n)return c(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=pt(n.id);return c(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=_n(e.category??void 0),s=cr(e.category??void 0),i=An(s);return c(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=eo(e.projectPath??process.cwd()),s=ro(o,"mistflow.json");if(!to(s))return Ee(o);let i;try{i=JSON.parse(oo(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return c("No project ID found. Deploy the project first.",!0);try{let a=await Go(n,e.period??"7d");return a.total===0?c(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):c(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 c(l,!0)}}case"logs":{let o=eo(e.projectPath??process.cwd()),s=ro(o,"mistflow.json");if(!to(s))return Ee(o);let i;try{i=JSON.parse(oo(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return c("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await at(n);if(l.length===0)return c("No deployments found for this project.",!0);a=l[0].id}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deployments";return c(d,!0)}try{let[l,d]=await Promise.all([Wo(a),It(a)]),h=l.filter(p=>p.level==="error"),m=l.filter(p=>p.level==="warn");return c(JSON.stringify({deploymentId:a,status:d.status,errorMessage:d.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:d.status==="failed"?`Deployment failed. ${h.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${d.status}. ${l.length} log entries (${h.length} errors, ${m.length} warnings).`}))}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deploy logs";return c(d,!0)}}case"deployments":{let o=eo(e.projectPath??process.cwd()),s=ro(o,"mistflow.json");if(!to(s))return Ee(o);let i;try{i=JSON.parse(oo(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return c("No project ID found. Deploy the project first.",!0);try{let a=await at(n);return c(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 c(l,!0)}}case"version":{Co().backendSignalReceived||await jo();let o=Co(),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 c(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 c(`Unknown action: ${e.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}}});import{z as Ze}from"zod";var ll,Nn,Dn=P(()=>{"use strict";Le();Q();zt();ll=Ze.object({action:Ze.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:Ze.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Ze.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:Ze.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:Ze.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Ze.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),Nn={name:"mist_browser",description:$r,inputSchema:ll,handler:async t=>{let e=t,r=await Ao();if(e.action==="navigate"){if(!e.url)return c("URL is required for 'navigate'.",!0);let i=[],n=d=>{d.type()==="error"&&i.push(d.text())};r.on("console",n),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=d=>a.push(d.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 d=await xt(r),h=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:d,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let m=await St(r);h.push({type:"image",data:m.toString("base64"),mimeType:"image/png"})}return{content:h}}}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 c("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 c("Selector is required for 'type'.",!0);if(!e.value)return c("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return c("Selector is required for 'fill'.",!0);if(!e.value)return c("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return c("Selector is required for 'select_option'.",!0);if(!e.value)return c("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return c("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return c("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 c(`Element not found: ${e.selector}`,!0);i=await n.screenshot({type:"png"})}else i=await St(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 xt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:i})}]}}let o=await xt(r),s=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}];if(e.includeScreenshot){let i=await St(r);s.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:s}}}});import{z as jn}from"zod";var On,Mn,Ln=P(()=>{"use strict";Le();Q();On=`# Mistflow MCP tool reference
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=oo(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=Cn(t.category??void 0),s=cr(t.category),i=In(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 ${at()}/designs?tab=landing-designs.`}))}case"integrations":{if(t.integrationId){let n=ut(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=mt(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=ur(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=no(t.projectPath??process.cwd()),s=ao(o,"mistflow.json");if(!so(s))return Ne(o);let i;try{i=JSON.parse(io(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 Jo(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=no(t.projectPath??process.cwd()),s=ao(o,"mistflow.json");if(!so(s))return Ne(o);let i;try{i=JSON.parse(io(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 ct(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([Ko(a),At(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=no(t.projectPath??process.cwd()),s=ao(o,"mistflow.json");if(!so(s))return Ne(o);let i;try{i=JSON.parse(io(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 ct(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":{Ro().backendSignalReceived||await Lo();let o=Ro(),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 et}from"zod";var cl,Dn,jn=P(()=>{"use strict";Ue();Q();Vt();cl=et.object({action:et.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:et.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:et.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:et.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:et.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:et.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),Dn={name:"mist_browser",description:Fr,inputSchema:cl,handler:async e=>{let t=e,r=await Eo();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 Tt(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 Pt(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 Pt(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 Tt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:i})}]}}let o=await Tt(r),s=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}];if(t.includeScreenshot){let i=await Pt(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=P(()=>{"use strict";Ue();Q();Mn=`# Mistflow MCP tool reference
1475
1475
 
1476
1476
  Every capability is an MCP tool. There is no companion CLI. Long-running tools
1477
1477
  (install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
@@ -1779,14 +1779,14 @@ is cheaper than building the wrong thing and iterating.
1779
1779
 
1780
1780
  mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
1781
1781
  mist_deploy({ action: "status", deploymentId }) # poll
1782
- `,Mn={name:"mist_help",description:Fr,inputSchema:jn.object({command:jn.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 c(On);let r=e.startsWith("mist_")?e:`mist_${e}`,o=On.split(`
1783
- `),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?c(`No tool named '${r}' found. Call mist_help with no args to see the full catalog.`,!0):c(o.slice(i,n).join(`
1784
- `).trim())}}});import{existsSync as no,mkdirSync as Fn,readFileSync as qn,readdirSync as Bn,writeFileSync as cl}from"fs";import{join as Be,resolve as dl}from"path";import{homedir as pr}from"os";import{z as Rt}from"zod";function ut(t){return t.entity??t.name??"Unknown"}function mt(t){return typeof t=="string"?t:t.name}function dr(t){return typeof t=="string"?"text":t.type}function Un(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[mt(n)]=pl(mt(n),dr(n),ut(t),s);o.push(i)}return o}function pl(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 ul(t){let e=t.dataModel??[],r=t.pages??[],o=t.design??{},s=r.map(m=>({label:m.name??m.path??"Page",route:m.path??m.route??"/"})),i=[],n=e.slice(0,3).map(m=>({name:ut(m),fields:(m.fields||[]).map(p=>({name:mt(p),type:dr(p)})),sampleData:Un(m)})),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(m=>ut(m)).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(m=>ut(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=e[0];if(l){let m=ut(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(y=>mt(y)).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(y=>({name:mt(y),type:dr(y)})),sampleData:Un(l)}]})}t.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 ${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 h=[];for(let m of e.slice(0,3)){let p=ut(m);(m.fields||[]).find(x=>{let b=mt(x).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 t.authModel&&t.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: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:h}}function ml(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(`
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**: ${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(`
1786
- `)}function zn(t){return Be(pr(),".mistflow","mockup-state",`${t}.json`)}function hl(t){let e=zn(t);if(!no(e))return null;try{return JSON.parse(qn(e,"utf-8"))}catch{return null}}function $n(t,e){let r=Be(pr(),".mistflow","mockup-state");Fn(r,{recursive:!0}),cl(zn(t),JSON.stringify(e,null,2))}function Wn(t){let e=Be(t,".mistflow","mockups");return no(e)?Bn(e).filter(r=>r.endsWith(".html")).map(r=>Be(e,r)):[]}var gl,Hn,ur=P(()=>{"use strict";Le();Q();gl=Rt.object({planId:Rt.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:Rt.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:Rt.string().optional().describe("User feedback to apply to the next iteration."),approved:Rt.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."}),Hn={name:"mist_mockup",description:Br,inputSchema:gl,handler:async t=>{let e=t,{planId:r,feedback:o,approved:s}=e,i=dl(e.projectPath??process.cwd()),n=Be(pr(),".mistflow","plans",`${r}.json`);if(!no(n))return c(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(qn(n,"utf-8"))}catch{return c("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return c("Plan data is empty. Call mist_plan again.",!0);let d=hl(r);d||(d={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let h=Be(i,".mistflow","mockups");Fn(h,{recursive:!0});let m=`mockup-${r}.html`,p=Be(h,m);if(s){d.approved=!0,$n(r,d);let T=no(h)?Bn(h).filter(_=>_.endsWith(".html")).map(_=>Be(".mistflow","mockups",_)):[];return c(JSON.stringify({status:"approved",message:`Wireframe approved after ${d.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:T,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.`}))}d.iterationCount++,o&&d.feedback.push(o);let y=ul(l);d.screens=y.screens.map(T=>T.name),$n(r,d);let x=ml(y,o??void 0,p),b=d.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,f=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 c(JSON.stringify({status:"wireframe",iterationCount:d.iterationCount,screens:y.screens.map(T=>({name:T.name,type:T.type,route:T.route})),wireframePrompt:x,designDirection:y.designDirection,...b?{nudge:b}:{},mockupFile:m,mockupPath:p,nextAction:f}))}}});function so(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,d,h,m,p]=a;e.push({file:l,line:parseInt(d,10),column:parseInt(h,10),message:`${m}: ${p}`,humanMessage:`There is a type error in ${l} on line ${d}: ${p}`,suggestion:`Check line ${d} 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 t.matchAll(o)){let[,l,d,h,m]=a;e.some(p=>p.file===l&&p.line===parseInt(d,10))||e.push({file:l,line:parseInt(d,10),column:parseInt(h,10),message:m,humanMessage:`There is an error in ${l} on line ${d}: ${m.trim()}`,suggestion:`Check line ${d} 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,d]=a;e.push({file:d,message:`Module not found: ${l}`,humanMessage:`The file ${d??"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,d]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${d}${l}`,humanMessage:`The package '${d}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${d}'.`,suggestion:`Add '${d}' 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,d,h,m]=a;e.some(p=>p.file===l&&p.line===parseInt(h,10))||e.push({file:l,line:parseInt(h,10),column:parseInt(m,10),message:`SyntaxError: ${d}`,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 e}var mr=P(()=>{"use strict"});import{z as hr}from"zod";import{resolve as fl}from"path";import{spawn as yl}from"child_process";function wl(t){return new Promise(e=>{let r=yl("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}
1787
- ${s.message}`})}),r.on("close",s=>{e({exitCode:s??1,combined:o})})})}var bl,Gn,Vn=P(()=>{"use strict";Le();Q();mr();bl=hr.object({projectPath:hr.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:hr.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});Gn={name:"mist_debug",description:qr,inputSchema:bl,handler:async t=>{let e=t,r=fl(e.projectPath??process.cwd()),o=e.buildOutput??"";if(!e.buildOutput){let n=await wl(r);if(n.exitCode===0)return c(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));o=n.combined}let s=so(o),i=o.slice(0,2e3);return s.length===0?c(JSON.stringify({errors:s,rawOutput:i,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):c(JSON.stringify({errors:s,rawOutput:i,message:`Found ${s.length} error${s.length===1?"":"s"} in the build output.`}))}}});function io(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 gr=P(()=>{"use strict"});function vl(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function kl(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function xl(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function Sl(t){let e={},r=[],o=[],s=new Set;for(let i=0;i<t.length;i++){let n=t[i],a=n.decisionKey?xl(n.decisionKey):`q_${i+1}`,l=a,d=2;for(;s.has(l);)l=`${a}_${d}`,d++;s.add(l);let h=`${l}_other`;s.add(h),o.push({primary:l,other:h,question:n});let m=(n.options??[]).map(y=>typeof y=="string"?y:y.label),p=[...m,"Other (specify in the 'Other' field below)"];e[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),e[h]={type:"string",title:"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 Tl(t,e){let r=[],o;for(let{primary:s,other:i,question:n}of e){let a=String(t[s]??"").trim(),l=String(t[i]??"").trim(),d=a.toLowerCase().startsWith("other"),h;l?h=l:d?h=n.recommended??(n.options?.[0]&&typeof n.options[0]=="object"?n.options[0].label:"")??a:h=a;let m=n.decisionKey??"";if(m==="urlChoice"){o=h;continue}r.push({question:n.question,decisionKey:m,answer:h})}return{answers:r,urlChoice:o}}async function fr(t,e,r){if(kl())return{outcome:"unsupported"};if(!vl(t))return{outcome:"unsupported"};if(e.length===0)return{outcome:"submitted",answers:[]};let{schema:o,fieldKeys:s}=Sl(e),i;try{i=await t.elicitInput({message:r,requestedSchema:o,mode:"form"},{timeout:300*1e3})}catch(l){let d=l instanceof Error?l.message:String(l);return d.toLowerCase().includes("not support")?{outcome:"unsupported"}:{outcome:"error",errorMessage:d}}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}=Tl(i.content,s);return{outcome:"submitted",answers:n,urlChoice:a}}var Kn=P(()=>{"use strict"});function Jn(t,e,r){let o=r?.suggestedName||Il(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 d of Pl){let h=d.keywords.test(l),m=d.condition(e);(h||m)&&a.push({name:d.name,description:d.description,checked:h,source:h?"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 Yn(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(`
1789
- `)}function Il(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return yr(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 yr(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Pl,Qn=P(()=>{"use strict";Pl=[{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 br(t,e,r){return e.includes(t)?t:r}function pe(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ht(t,e){return typeof t!="string"?e:/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(t.trim())?t.trim():e}function Rl(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 Xn(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 El(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 Nl(){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`
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(`
1783
+ `),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 lo,mkdirSync as qn,readFileSync as Bn,readdirSync as zn,writeFileSync as dl}from"fs";import{join as ze,resolve as pl}from"path";import{homedir as hr}from"os";import{z as Nt}from"zod";function ht(e){return e.entity??e.name??"Unknown"}function gt(e){return typeof e=="string"?e:e.name}function mr(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[gt(n)]=ul(gt(n),mr(n),ht(e),s);o.push(i)}return o}function ul(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 ml(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:ht(m),fields:(m.fields||[]).map(p=>({name:gt(p),type:mr(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=>ht(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=>ht(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=ht(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=>gt(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:gt(f),type:mr(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=ht(m);(m.fields||[]).find(x=>{let b=gt(x).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 hl(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 ze(hr(),".mistflow","mockup-state",`${e}.json`)}function gl(e){let t=Hn(e);if(!lo(t))return null;try{return JSON.parse(Bn(t,"utf-8"))}catch{return null}}function Fn(e,t){let r=ze(hr(),".mistflow","mockup-state");qn(r,{recursive:!0}),dl(Hn(e),JSON.stringify(t,null,2))}function Gn(e){let t=ze(e,".mistflow","mockups");return lo(t)?zn(t).filter(r=>r.endsWith(".html")).map(r=>ze(t,r)):[]}var fl,Wn,gr=P(()=>{"use strict";Ue();Q();fl=Nt.object({planId:Nt.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:Nt.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:Nt.string().optional().describe("User feedback to apply to the next iteration."),approved:Nt.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:fl,handler:async e=>{let t=e,{planId:r,feedback:o,approved:s}=t,i=pl(t.projectPath??process.cwd()),n=ze(hr(),".mistflow","plans",`${r}.json`);if(!lo(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=gl(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let h=ze(i,".mistflow","mockups");qn(h,{recursive:!0});let m=`mockup-${r}.html`,p=ze(h,m);if(s){c.approved=!0,Fn(r,c);let v=lo(h)?zn(h).filter(A=>A.endsWith(".html")).map(A=>ze(".mistflow","mockups",A)):[];return d(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:v,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=ml(l);c.screens=f.screens.map(v=>v.name),Fn(r,c);let x=hl(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(v=>({name:v.name,type:v.type,route:v.route})),wireframePrompt:x,designDirection:f.designDirection,...b?{nudge:b}:{},mockupFile:m,mockupPath:p,nextAction:y}))}}});function co(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 fr=P(()=>{"use strict"});import{z as yr}from"zod";import{resolve as yl}from"path";import{spawn as bl}from"child_process";function vl(e){return new Promise(t=>{let r=bl("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 wl,Vn,Kn=P(()=>{"use strict";Ue();Q();fr();wl=yr.object({projectPath:yr.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:yr.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});Vn={name:"mist_debug",description:Br,inputSchema:wl,handler:async e=>{let t=e,r=yl(t.projectPath??process.cwd()),o=t.buildOutput??"";if(!t.buildOutput){let n=await vl(r);if(n.exitCode===0)return d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));o=n.combined}let s=co(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 Ae(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 ft=P(()=>{"use strict"});function xl(e){try{return!!e.getClientCapabilities()?.elicitation}catch{return!1}}function kl(){let e=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return e==="off"||e==="false"||e==="0"||e==="disabled"}function Sl(e){let t=e.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(t)?t:`_${t}`}function Tl(e){let t={},r=[],o=[],s=new Set;for(let i=0;i<e.length;i++){let n=e[i],a=n.decisionKey?Sl(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=[...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:"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 Pl(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().startsWith("other");h?l=h:m?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 br(e,t,r){if(kl())return{outcome:"unsupported"};if(!xl(e))return{outcome:"unsupported"};if(t.length===0)return{outcome:"submitted",answers:[]};let{schema:o,fieldKeys:s}=Tl(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}=Pl(i.content,s);return{outcome:"submitted",answers:n,urlChoice:a}}var Jn=P(()=>{"use strict"});function Yn(e,t,r){let o=r?.suggestedName||Cl(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 Cl(e){let t=e.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(t)return wr(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 wr(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Il,Xn=P(()=>{"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 pe(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function yt(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 Nl(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 Dl(){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`
1790
1790
  .card-hero { position: relative; overflow: hidden; isolation: isolate; }
1791
1791
  .card-hero::before {
1792
1792
  content: "";
@@ -1803,17 +1803,17 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
1803
1803
 
1804
1804
  .card-hero.texture-paper-grain::before {
1805
1805
  opacity: 0.35;
1806
- background-image: ${t};
1806
+ background-image: ${e};
1807
1807
  mix-blend-mode: multiply;
1808
1808
  }
1809
1809
  .card-hero.texture-film-grain::before {
1810
1810
  opacity: 0.5;
1811
- background-image: ${t};
1811
+ background-image: ${e};
1812
1812
  mix-blend-mode: overlay;
1813
1813
  }
1814
1814
  .card-hero.texture-noise::before {
1815
1815
  opacity: 0.25;
1816
- background-image: ${t};
1816
+ background-image: ${e};
1817
1817
  mix-blend-mode: overlay;
1818
1818
  }
1819
1819
  .card-hero.texture-scanlines::before {
@@ -1844,26 +1844,26 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
1844
1844
  backdrop-filter: blur(14px);
1845
1845
  mix-blend-mode: normal;
1846
1846
  }
1847
- `}function Dl(t,e,r,o){let s=ht(t.colors?.bg??"","#0f0f0f"),i=ht(t.colors?.fg??"","#f5f5f5"),n=ht(t.colors?.accent??"","#7c9cff"),a=pe(t.name),l=pe(t.hero_headline||t.name),d=pe(t.body_sample||t.summary||""),h=pe(t.cta_text||"Continue"),m=`<div class="hero-eyebrow" style="font-family:${r}">${a.toUpperCase()}</div>`,p=`<h2 class="hero-headline" style="font-family:${e}">${l}</h2>`,y=`<p class="hero-body" style="font-family:${r}">${d}</p>`,x=`<button class="hero-cta" style="background:${n};color:${s};font-family:${r};border-radius:${o.button}">${h}</button>`,b=br(t.hero_treatment,Cl,"typographic");if(b==="terminal"){let f=`"${(t.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
1847
+ `}function jl(e,t,r,o){let s=yt(e.colors?.bg??"","#0f0f0f"),i=yt(e.colors?.fg??"","#f5f5f5"),n=yt(e.colors?.accent??"","#7c9cff"),a=pe(e.name),l=pe(e.hero_headline||e.name),c=pe(e.body_sample||e.summary||""),h=pe(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>`,x=`<button class="hero-cta" style="background:${n};color:${s};font-family:${r};border-radius:${o.button}">${h}</button>`,b=vr(e.hero_treatment,Al,"typographic");if(b==="terminal"){let y=`"${(e.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
1848
1848
  ${m}
1849
- <div class="hero-terminal-lines" style="font-family:${f};color:${i}">
1849
+ <div class="hero-terminal-lines" style="font-family:${y};color:${i}">
1850
1850
  <div>$ status --all</div>
1851
1851
  <div>api.service.......<span style="color:${n}">OK</span></div>
1852
1852
  <div>worker.queue......<span style="color:${n}">OK</span></div>
1853
1853
  <div>db.primary.......<span style="color:${n}">OK</span></div>
1854
1854
  </div>
1855
1855
  ${p}
1856
- ${y}
1856
+ ${f}
1857
1857
  <div class="hero-cta-row">${x}</div>
1858
1858
  `}return b==="split-panel"?`
1859
1859
  <div class="hero-split">
1860
- <div class="hero-split-left" style="background:${n};color:${s};font-family:${e}">
1860
+ <div class="hero-split-left" style="background:${n};color:${s};font-family:${t}">
1861
1861
  <div class="hero-split-mark" style="font-family:${r};color:${s}">${a[0]??"\xB7"}</div>
1862
1862
  </div>
1863
1863
  <div class="hero-split-right">
1864
1864
  ${m}
1865
1865
  ${p}
1866
- ${y}
1866
+ ${f}
1867
1867
  <div class="hero-cta-row">${x}</div>
1868
1868
  </div>
1869
1869
  </div>
@@ -1873,27 +1873,27 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
1873
1873
  </div>
1874
1874
  ${m}
1875
1875
  ${p}
1876
- ${y}
1876
+ ${f}
1877
1877
  <div class="hero-cta-row">${x}</div>
1878
1878
  `:b==="magazine-hero"?`
1879
1879
  ${m}
1880
- <h2 class="hero-headline hero-headline-mag" style="font-family:${e}">${l}</h2>
1880
+ <h2 class="hero-headline hero-headline-mag" style="font-family:${t}">${l}</h2>
1881
1881
  <div class="hero-rule" style="background:${i}"></div>
1882
- <p class="hero-body hero-body-mag" style="font-family:${r}">${d}</p>
1882
+ <p class="hero-body hero-body-mag" style="font-family:${r}">${c}</p>
1883
1883
  <div class="hero-byline" style="font-family:${r};color:${i}">\u2014 Volume 01 \xB7 Issue 01</div>
1884
1884
  <div class="hero-cta-row">${x}</div>
1885
1885
  `:`
1886
1886
  ${m}
1887
1887
  ${p}
1888
- ${y}
1888
+ ${f}
1889
1889
  <div class="hero-cta-row">${x}</div>
1890
- `}function Zn(t,e){let r=Rl(e),o=e.map(s=>{let i=ht(s.colors?.bg??"","#0f0f0f"),n=ht(s.colors?.fg??"","#f5f5f5"),a=ht(s.colors?.accent??"","#7c9cff"),l=Xn(s.fonts?.display??""),d=Xn(s.fonts?.body??""),h=br(s.shape_lang,Al,"soft"),m=br(s.texture,_l,"flat"),p=El(h),y=Dl(s,l,d,p),x=pe(s.name),b=pe(s.id),f=pe(s.fonts?.display??""),T=pe(s.fonts?.body??""),_=pe(s.summary||""),E=pe(s.decoration_hint||""),I=(O,U)=>`<div class="card-meta-row"><span class="card-meta-label">${O}</span><span class="card-meta-value">${U}</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}">${y}
1890
+ `}function es(e,t){let r=El(t),o=t.map(s=>{let i=yt(s.colors?.bg??"","#0f0f0f"),n=yt(s.colors?.fg??"","#f5f5f5"),a=yt(s.colors?.accent??"","#7c9cff"),l=Zn(s.fonts?.display??""),c=Zn(s.fonts?.body??""),h=vr(s.shape_lang,_l,"soft"),m=vr(s.texture,Rl,"flat"),p=Nl(h),f=jl(s,l,c,p),x=pe(s.name),b=pe(s.id),y=pe(s.fonts?.display??""),v=pe(s.fonts?.body??""),A=pe(s.summary||""),R=pe(s.decoration_hint||""),I=(O,U)=>`<div class="card-meta-row"><span class="card-meta-label">${O}</span><span class="card-meta-value">${U}</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}
1892
1892
  </div>
1893
1893
  <div class="card-meta" style="border-top-color:${n}14">
1894
1894
  <div class="card-meta-title">${x}</div>
1895
- <p class="card-meta-summary">${_}</p>
1896
- ${I("Fonts",`${f||"\u2014"} <span class="sep">\xB7</span> ${T||"\u2014"}`)}
1895
+ <p class="card-meta-summary">${A}</p>
1896
+ ${I("Fonts",`${y||"\u2014"} <span class="sep">\xB7</span> ${v||"\u2014"}`)}
1897
1897
  ${I("Palette",`
1898
1898
  <span class="card-meta-swatches">
1899
1899
  <span class="card-meta-swatch" title="${i}" style="background:${i}"></span>
@@ -1903,7 +1903,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
1903
1903
  `)}
1904
1904
  ${I("Shape",`<span class="chip" style="border-radius:${p.chip}">${h}</span>`)}
1905
1905
  ${I("Texture",`<span class="chip" style="border-radius:${p.chip}">${pe(m)}</span>`)}
1906
- ${E?I("Decoration",pe(E)):""}
1906
+ ${R?I("Decoration",pe(R)):""}
1907
1907
  ${I("Pick with",`<code>${x}</code>`)}
1908
1908
  </div>
1909
1909
  </article>`}).join(`
@@ -1912,7 +1912,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
1912
1912
  <head>
1913
1913
  <meta charset="UTF-8" />
1914
1914
  <meta name="viewport" content="width=device-width,initial-scale=1" />
1915
- <title>Design directions \u2014 ${pe(t)}</title>
1915
+ <title>Design directions \u2014 ${pe(e)}</title>
1916
1916
  <link rel="preconnect" href="https://fonts.googleapis.com" />
1917
1917
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
1918
1918
  ${r?`<link rel="stylesheet" href="${r}" />`:""}
@@ -2099,7 +2099,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
2099
2099
  margin-top: 4px;
2100
2100
  }
2101
2101
 
2102
- ${Nl()}
2102
+ ${Dl()}
2103
2103
 
2104
2104
  /* \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
2105
  .card-meta {
@@ -2208,7 +2208,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
2208
2208
  <div class="page">
2209
2209
  <header class="page-header">
2210
2210
  <div class="eyebrow"><span class="eyebrow-dot"></span>Mistflow \xB7 design direction</div>
2211
- <h1 class="page-title">How should <strong>${pe(t)}</strong> feel?</h1>
2211
+ <h1 class="page-title">How should <strong>${pe(e)}</strong> feel?</h1>
2212
2212
  <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
2213
  </header>
2214
2214
 
@@ -2228,24 +2228,24 @@ ${o}
2228
2228
  </div>
2229
2229
  </body>
2230
2230
  </html>
2231
- `}var Cl,Al,_l,es=P(()=>{"use strict";Cl=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],Al=["sharp","soft","pill","organic"],_l=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"]});import{z as A}from"zod";import{existsSync as Et,mkdirSync as lo,readFileSync as os,readdirSync as jl,statSync as Ol,unlinkSync as Ml,writeFileSync as co}from"fs";import{dirname as Ll,isAbsolute as Ul,join as ue}from"path";import{homedir as ze}from"os";import{createHash as $l,createHmac as rs,randomBytes as Fl,randomUUID as ts,timingSafeEqual as ql}from"crypto";function ns(){let t=ue(ze(),".mistflow","confirm-secret");if(Et(t))try{return Buffer.from(os(t,"utf-8").trim(),"hex")}catch{}let e=Fl(32);return lo(ue(ze(),".mistflow"),{recursive:!0}),co(t,e.toString("hex"),{mode:384}),e}function ss(t){return $l("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function zl(t,e){let r={cwd:t,d:ss(e),exp:Date.now()+Bl},o=Buffer.from(JSON.stringify(r)).toString("base64url"),s=rs("sha256",ns()).update(o).digest("base64url");return`${o}.${s}`}function Hl(t,e,r){let o=t.split(".");if(o.length!==2)return!1;let[s,i]=o,n=rs("sha256",ns()).update(s).digest("base64url"),a=Buffer.from(i),l=Buffer.from(n);if(a.length!==l.length||!ql(a,l))return!1;try{let d=JSON.parse(Buffer.from(s,"base64url").toString("utf-8"));return!(typeof d.exp!="number"||Date.now()>d.exp||d.cwd!==e||d.d!==ss(r))}catch{return!1}}function Wl(t){let e=t,r=ze(),o=!1;for(let s=0;s<64;s++){if(Et(ue(e,"mistflow.json")))return"mistflow";if(!o&&Et(ue(e,"package.json"))&&(o=!0),e===r)break;let i=Ll(e);if(i===e)break;e=i}return o?"foreign":"none"}function Gl(t){let e=ze(),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===ue(e,s))return!0;return!1}function Kl(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 Jl(t){let e=ue(ze(),".mistflow","plans",`${t}.json`);if(!Et(e))return null;try{return JSON.parse(os(e,"utf-8")).plan??null}catch{return null}}async function Yl(t){for(let o=0;o<60;o++){try{let s=await Lo(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 Ql(t,e){let{description:r,projectPath:o,conversationId:s,answers:i,existingPlan:n,existingPlanId:a,templateToken:l,remixDescription:d,autonomous:h,language:m,landingDesign:p,appStyle:y,brandMentioned:x,confirmToken:b,urlChoice:f,designConversationId:T,designDirection:_}=t;if(s&&!r&&!i&&!T&&!_&&!n&&!a&&!l)try{let u=await Gt(s);return u.status==="clarify_pending"?c(JSON.stringify({status:"running",conversationId:s,phase:"generating_questions",nextAction:`Still generating. 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 questions are ready.`})):u.status==="plan_pending"?c(JSON.stringify({status:"running",conversationId:s,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). 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 plan is ready.`})):c(JSON.stringify(u))}catch(u){let g=u instanceof Error?u.message:String(u);return c(`Could not poll plan conversation '${s}': ${g}`,!0)}let E=r??"";if(!E.trim()&&!s&&!T&&!n&&!a&&!l)return c("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(T&&!_&&!E.trim()&&!i)return c(`You passed designConversationId='${T}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${T}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let I=n;if(!I&&a&&(I=Jl(a)??void 0,!I))return c("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let O=s;if(!oe())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let U;if(!O&&!I&&!l){if(!Ul(o))return c(`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=Wl(o);if(u!=="mistflow"&&Gl(o))return c(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"&&!x){if(!(b?Hl(b,o,E):!1)){let k=zl(o,E);if(e?.server){let S=await fr(e.server,[{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",decisionKey:"scopeChoice",recommended:"Scaffold a new Mistflow app in a subdirectory",why:"Mistflow creates a NEW app in a subdirectory \u2014 it does not modify the existing codebase. Pick 'Edit existing' if you wanted to change files in the current project instead of creating a new Mistflow app.",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."}]}],"## Existing project detected\n\nYou're inside a directory that already has a project (no `mistflow.json` though). What do you want to do?");if(S.outcome==="submitted")if((S.answers?.[0]?.answer??"").toLowerCase().startsWith("scaffold"))U="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.";else return c("User chose to edit the existing codebase directly. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0);else return S.outcome==="declined"||S.outcome==="cancelled"?c("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):c(JSON.stringify({status:"confirm_new_project",projectPath:o,description:E,confirmToken:k,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(`
2233
- `)}))}else return c(JSON.stringify({status:"confirm_new_project",projectPath:o,description:E,confirmToken:k,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(`
2234
- `)}))}U="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else u==="foreign"&&x&&(U="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await Xo(l)).plan)return c("This template has no plan to fork. Try a different template.",!0);let g=await Zo(l),k=g.plan,S="";if(d&&g.has_source)try{let ie=await Kt(g.plan,d),z=ie.plan??ie,Ut=ie.diff,So=z?.steps??[],K=new Set([...(Ut?.added??[]).map(H=>H.number),...(Ut?.modified??[]).map(H=>H.number)]),he=So.map(H=>{let ot=H.number;return K.has(ot)?{...H,status:"pending"}:{...H,status:"completed",source:"forked"}});z.steps=he,k=z;let Ce=he.filter(H=>H.status==="pending").length;S=` Remixed: ${he.filter(H=>H.status==="completed").length} steps unchanged, ${Ce} steps need re-implementation.`}catch(ie){console.error("[plan] Remix failed, using original plan:",ie),S=" (Remix failed \u2014 using original plan. You can modify it later.)"}let Z=ts(),Y=ue(ze(),".mistflow","plans");lo(Y,{recursive:!0}),co(ue(Y,`${Z}.json`),JSON.stringify({plan:k,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let se=k?.name??"forked-app",le=g.has_source,wt=le?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Ye=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return c(JSON.stringify({planId:Z,forkedFrom:g.forked_from,projectId:g.id,hasSource:le,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${S}${Ye} ${wt} NEXT: Call mist_init, name='${se}', and planId='${Z}' to create the project now.`}))}catch(u){let g=u instanceof Error?u.message:"Failed to fork template";return c(g,!0)}if(I){let u;try{u=await Kt(I,E)}catch(Y){let se=Y instanceof Error?Y.message:"Failed to modify plan";return c(se,!0)}let g=u.plan,k=u.diff,S=[];if(k?.added?.length){let Y=k.added.map(se=>se.title);S.push(`Added ${Y.length} step(s): ${Y.join(", ")}`)}if(k?.removed?.length){let Y=k.removed.map(se=>se.title);S.push(`Removed ${Y.length} step(s): ${Y.join(", ")}`)}if(k?.modified?.length){let Y=k.modified.map(se=>se.title);S.push(`Modified ${Y.length} step(s): ${Y.join(", ")}`)}let Z=S.length>0?S.join(". "):"No changes detected.";return c(JSON.stringify({plan:g,diff:k,message:`Plan modified. ${Z}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let v=f?.trim()||void 0,L=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 k=i.slice(0,u).concat(i.slice(u+1));L=k.length>0?k:void 0}}else if(i!=null){let u=i;if(!v&&ao in u&&(v=u[ao]),!v&&"urlChoice"in u&&(v=u.urlChoice),ao in u||"urlChoice"in u){let{[ao]:g,urlChoice:k,...S}=u;L=Object.keys(S).length>0?S: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(_){G={..._};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,k]of Object.entries(u))_[g]!==void 0&&G[k]===void 0&&(G[k]=_[g])}let V=i?"Generating plan with your answers (LLM call)":T?"Finalizing design direction":"Thinking through discovery questions",ee=e?io(e.server,e.progressToken,()=>V):{stop:()=>{}};e&&(e.cleanup=()=>ee.stop());let R;try{O&&!L&&!T&&!I&&!a?R=await Gt(O):R=await Vt(E,{conversationId:O,answers:L,autonomous:h,language:m,designConversationId:T,designDirection:G})}catch(u){ee.stop();let g=u instanceof Error?u.message:"Failed to generate plan";return c(g,!0)}if(R.status==="clarify_pending"){ee.stop();let u=R;return c(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(R.status==="plan_pending"){ee.stop();let u=R;return c(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(R.status==="design_clarify_pending"&&(V="Generating creative design directions",R=await Yl(R)),ee.stop(),R.status==="clarify"){let u=R.reflection||"",g=R.suggestedName||"",k=R.suggestedFeatures??[],S=R.questions??[],Z=S.some(K=>Array.isArray(K.options)&&typeof K.options[0]=="object"&&K.options[0]?.label),Y={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"},se=S.map(K=>{let he=K.decisionKey&&Y[K.decisionKey]||Kl(K.question),Ce;return Z&&Array.isArray(K.options)?Ce=K.options.map(ce=>({label:ce.label,description:ce.description??""})):Array.isArray(K.options)?Ce=K.options.map((ce,H)=>({label:H===0?`${ce} (Recommended)`:String(ce),description:K.why??""})):Ce=[{label:"Yes (Recommended)",description:K.why??""},{label:"No",description:""}],{question:K.question,header:he,options:Ce,multiSelect:!1}}),wt=R.decisions?.audienceType??null,Ye=k.length>0?Jn(E,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:wt,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:k,language:m}):null,ie=Ye?Yn(Ye):"",z=yr(g||"my-app").slice(0,32);try{let K=await Oo(z);!K.available&&K.suggestion&&(z=K.suggestion)}catch{}ie&&(ie+=`
2235
-
2236
- **Your app URL:** https://${z}.mistflow.app`);let Ut={question:`Your app will be at ${z}.mistflow.app \u2014 want to customize the URL?`,decisionKey:"urlChoice",recommended:`Keep ${z}.mistflow.app`,why:"This URL matches your app name and is available. You can customize it now \u2014 subdomains are locked in at scaffold time.",options:[{label:`Keep ${z}.mistflow.app`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}]};S.push(Ut);let So={question:`Your app will be at ${z}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${z}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};if(se.push(So),e?.server){let K=[g?`## ${g}`:"## Pick a few details","",`${S.length} quick question${S.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
2237
- `),he=await fr(e.server,S,K);if(he.outcome==="submitted"){ee.stop();let Ce={};for(let H of he.answers??[])H.decisionKey?Ce[H.decisionKey]=H.answer:Ce[H.question]=H.answer;let ce=he.urlChoice?.trim();ce&&(ce=ce.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let H=await Vt(E,{conversationId:R.conversation_id,answers:Ce,autonomous:h,language:m});if(H.status==="plan_pending"){let ot=H;return c(JSON.stringify({status:"running",conversationId:ot.conversation_id,phase:"generating_plan",...ce?{urlChoice:ce}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${ot.conversation_id}"${ce?`, urlChoice: "${ce}"`:""} } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll up to ~10s and returns when the plan lands. Pass urlChoice on every poll so it threads through to the saved plan.`}))}R=H}catch(H){let ot=H instanceof Error?H.message:String(H);return c(`Submitting your answers failed: ${ot}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(he.outcome==="declined")return ee.stop(),c("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(he.outcome==="cancelled")return ee.stop(),c("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);he.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${he.errorMessage}) \u2014 falling back to prose flow.`)}}return c(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:R.conversation_id,questions:S,questionCount:S.length,suggestedFeatures:k,suggestedName:g,suggestedSubdomain:z,reflection:u,briefText:ie,askUserQuestions:se,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:["\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST ask the user via your host's native structured-question","tool (not a text prompt, not a bash echo, not a chat message).","The user has to actually choose. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","Per host (use whichever applies):"," \u2022 Claude Code \u2192 AskUserQuestion tool"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) \u2192 request_user_input returns"," 'unavailable in <mode> mode'. When you see that error, STOP"," your turn, print the questions as a numbered chat message"," with all options visible, and wait for the user's next"," message. Do NOT resume by picking answers yourself."," \u2022 Any host without a native question tool \u2192 same as above:"," stop your turn, print the questions, wait.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 'Locking in the defaults with X as the only override.'"," (inferring answers from the original spec)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping the question UI because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call the tool (when available): pass each object in the","`askUserQuestions` array below. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${R.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${z}".`,'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||ie?["","\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]:[],...ie?["",ie]:[]]:[],...U?["",U]:[]].join(`
2238
- `)}))}if(R.status==="design_clarify"){let u=R.directions??[],g=R.plan.name??"your app",k;try{let le=u.map(z=>({id:z.id,name:z.name,summary:z.summary,hero_headline:z.hero_headline,cta_text:z.cta_text,body_sample:z.body_sample,fonts:z.fonts,colors:z.colors,hero_treatment:z.hero_treatment,shape_lang:z.shape_lang,texture:z.texture,decoration_hint:z.decoration_hint})),wt=Zn(g,le),Ye=ue(o,".mistflow");lo(Ye,{recursive:!0});let ie=ue(Ye,"design-directions.html");co(ie,wt,"utf-8"),k=ie}catch(le){console.error(`[mist_plan] design-directions preview render failed: ${le instanceof Error?le.message:String(le)}`)}let S=u.map(le=>({label:le.name,description:`${le.summary} \u2014 ${le.fonts?.display??""} + ${le.fonts?.body??""}`}));S.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let Z={question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:S,multiSelect:!1},Y=k?[`A visual preview of all ${u.length} directions has been written to:`,` ${k}`,"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 "${k}"`,` \u2022 Linux: run xdg-open "${k}"`,` \u2022 Windows: run start "" "${k}"`," \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(`
2239
- `):"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.",se=k?`open "${k}"`:"";return c(JSON.stringify({status:"design_clarify",designConversationId:R.design_conversation_id,directions:u,previewPath:k,askUserQuestion:Z,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","",Y,se?`Run this command to open the preview for the user: ${se}`:"","","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: "${R.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(`
2240
- `)}))}let N=R.plan,ae=N.name??"Untitled App",me=R.methodology,j=N.steps;if(!Array.isArray(j)||j.length===0)return c("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let te=N.publicPages;if(!te||Array.isArray(te)&&te.length===0){let u=N.pages,g=j.some(S=>typeof S.name=="string"&&S.name.toLowerCase().includes("landing")||typeof S.title=="string"&&S.title.toLowerCase().includes("landing")),k=Array.isArray(u)&&u.some(S=>S.path==="/"||S.route==="/");g||k?te=["/","/pricing"]:te=["/"]}let Ae=N.primaryAction;if(!Ae){let u=N.features;if(Array.isArray(u)&&u.length>0){let k=u.find(Z=>typeof Z.priority=="string"&&Z.priority.toLowerCase()==="must-have")??u[0];Ae={entity:k.name??k.title??"item",action:"create",fromPage:"/dashboard"}}}let fe=N.nonNegotiables;(!fe||Array.isArray(fe)&&fe.length===0)&&(fe=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let _e=ts(),Ge=ue(ze(),".mistflow","plans");lo(Ge,{recursive:!0});try{let g=Date.now();for(let k of[Ge,ue(ze(),".mistflow","mockup-state")])if(Et(k))for(let S of jl(k))try{let Z=ue(k,S),Y=Ol(Z).mtimeMs;g-Y>6048e5&&Ml(Z)}catch{}}catch{}let q;if(p){let u=Xt(p);u?q=u.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let D=y||void 0,W=!!q,we=j.some(u=>{let g=`${u.name??u.title} ${u.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),J=!W&&we?Cn(E,{maxResults:2}):[];J.length>0&&(q=J[0].id,console.error(`Auto-assigned landing layout preset (default): ${J[0].title} (${q})`));let Ie={name:N.name,summary:N.summary,dataModel:N.dataModel,pages:N.pages,features:N.features,steps:j.map(u=>({...u,name:u.name??u.title})),design:N.design,landingDesign:q,appStyle:D,dbProvider:N.dbProvider??"neon",authModel:N.authModel,audienceType:N.audienceType??"b2c",roles:N.roles,defaultRole:N.defaultRole,publicPages:te,navStyle:N.navStyle,multiTenant:N.multiTenant,primaryAction:Ae,nonNegotiables:fe,requestedSubdomain:v,...m&&m.toLowerCase()!=="english"?{language:m}:{}};co(ue(Ge,`${_e}.json`),JSON.stringify({plan:Ie,methodology:me}));let Ve=j.map(u=>`${u.number}. ${u.name??u.title}`),Ke="",Je=[],ye;!W&&J.length>0&&(Je=J.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${st()}/designs?tab=landing-designs`})),ye={question:"What landing page style fits this app?",header:"Landing Design",options:[...J.map((g,k)=>({label:k===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 ${st()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},Ke=` 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: ${J.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='${J[0].id}' explicitly.`);let je="",Oe=[],Me=void 0,C=(N.audienceType??"b2c")==="b2c",B={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:C?"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:C?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},X=" 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="",ne=[];for(let u of j){let g=u.name??u.title,k=u.integrationId;if(k){let S=dt(k);if(S){let Z=pt(S.id);ne.push({step:g,presetId:S.id,presetName:S.name,envVars:Z?.envVars??[]})}}}if(ne.length>0){let u=ne.flatMap(S=>S.envVars),g=[...new Set(u.map(S=>S.key))];ve=` This plan uses integrations (${ne.map(S=>S.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 c(JSON.stringify({planId:_e,name:N.name,summary:N.summary,stepCount:j.length,steps:Ve,design:N.design,...q?{landingDesign:q}:{},...D?{appStyle:D}:{},...Oe.length>0?{recommendedAppStyles:Oe}:{},...Me?{appStyleQuestion:Me}:{},...Je.length>0?{recommendedLandingDesigns:Je}:{},...ye?{landingDesignQuestion:ye}:{},heroPhotoQuestion:B,...ne.length>0?{integrations:ne.map(u=>({step:u.step,preset:u.presetId,name:u.presetName,envVars:u.envVars}))}:{},message:`Plan generated for "${ae}" (${j.length} steps).${q?` Landing layout "${q}" set as default.`:""}${D?` App style "${D}" will be applied across all pages.`:""}${ve}${je}${Ke}${X}`,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: '${_e}' }). If the user says skip or "just build it", call mist_init({ planId: '${_e}', path: '<absolute path>' }) immediately.`,...U?{warning:U}:{}}))}var ao,Bl,Vl,is,as=P(()=>{"use strict";Q();ge();gr();Kn();ar();Zt();Qn();es();ao="__mistflow_url_choice__",Bl=600*1e3;Vl=A.object({description:A.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:A.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:A.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:A.union([A.record(A.string()),A.array(A.object({question:A.string().optional(),decisionKey:A.string().optional(),answer:A.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:A.record(A.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:A.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.object({id:A.string().optional(),name:A.string().optional(),summary:A.string().optional(),heroHeadline:A.string().optional(),ctaText:A.string().optional(),bodySample:A.string().optional(),fontsHint:A.string().optional(),fonts:A.object({display:A.string(),body:A.string()}).partial().optional(),colorMood:A.string().optional(),colors:A.object({bg:A.string(),fg:A.string(),accent:A.string()}).partial().optional(),heroTreatment:A.string().optional(),shapeLang:A.string().optional(),texture:A.string().optional(),decorationHint:A.string().optional(),custom:A.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.")});is={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(`
2241
- `),inputSchema:Vl,handler:Ql}});function ls(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 Xl(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function Zl(t){let e=ls(t);return e.charAt(0).toLowerCase()+e.slice(1)}function vr(){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(`
2242
- `)}function cs(){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(`
2243
- `)}function kr(t){let e=cs();if(t.includes(wr)){let o=t.indexOf(wr),s=ds,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+$/,"")+`
2244
-
2245
- `+e}function xr(t,e){let r=ls(t),o=e??Zl(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(`
2246
- `)}function Sr(t){return`contracts/${Xl(t)}.ts`}var wr,ds,Tr=P(()=>{"use strict";wr="<!-- mist:contracts:start -->",ds="<!-- mist:contracts:end -->"});import{z as Nt}from"zod";import{existsSync as et,mkdirSync as Pr,writeFileSync as Ir,readFileSync as uo,readdirSync as ms,copyFileSync as ec}from"fs";import{join as Te,resolve as hs,dirname as Dt,isAbsolute as tc}from"path";import{homedir as oc}from"os";import{spawn as hm}from"child_process";import{randomBytes as rc}from"crypto";import{simpleGit as sc}from"simple-git";function nc(t){let e=Te(oc(),".mistflow","plans",`${t}.json`);if(!et(e))return null;try{let r=JSON.parse(uo(e,"utf-8"));return r.plan?{plan:r.plan}:null}catch{return null}}function ic(t){let e=Dt(hs(t)),r=10,o=0;for(;o<r&&e!==Dt(e);){if(et(Te(e,"pnpm-workspace.yaml"))||et(Te(e,"lerna.json")))return e;let s=Te(e,"package.json");if(et(s))try{if(JSON.parse(uo(s,"utf-8")).workspaces)return e}catch{}e=Dt(e),o++}return null}function M(t,e,r){let o=Te(t,e);Pr(Dt(o),{recursive:!0}),Ir(o,r)}function lc(t){if(!et(t))return!0;let e;try{e=ms(t)}catch{return!1}return e.filter(o=>o!==".mistflow").length===0}function pc(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(`
2247
- `),i=null,n=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of s){let d=l.replace(/\r$/,"");if(!d.trim()||d.trim().startsWith("#"))continue;if(d.startsWith("theme:")){let p=a(d.slice(6).trim());(p==="dark"||p==="light")&&(o.theme=p);continue}let h=d.match(/^(colors|typography|rounded|spacing):\s*$/);if(h){i=h[1],n=null;continue}if(i==="typography"){let p=d.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(p){n=p[1].replace(/-/g,"_"),o.typography[n]={};continue}let y=d.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(y&&n){o.typography[n][y[1]]=a(y[2]);continue}}let m=d.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(m&&i){let p=m[1].replace(/-/g,"_"),y=a(m[2]);i==="colors"?o.colors[p]=y:i==="rounded"?o.rounded[p]=y:i==="spacing"&&(o.spacing[p]=y)}}return o}function uc(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(`
2248
- `),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(`
2231
+ `}var Al,_l,Rl,ts=P(()=>{"use strict";Al=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],_l=["sharp","soft","pill","organic"],Rl=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"]});import{z as _}from"zod";import{existsSync as Dt,mkdirSync as uo,readFileSync as rs,readdirSync as Ol,statSync as Ml,unlinkSync as Ll,writeFileSync as mo}from"fs";import{dirname as Ul,isAbsolute as $l,join as ue}from"path";import{homedir as He}from"os";import{createHash as Fl,createHmac as ns,randomBytes as ql,randomUUID as os,timingSafeEqual as Bl}from"crypto";function ss(){let e=ue(He(),".mistflow","confirm-secret");if(Dt(e))try{return Buffer.from(rs(e,"utf-8").trim(),"hex")}catch{}let t=ql(32);return uo(ue(He(),".mistflow"),{recursive:!0}),mo(e,t.toString("hex"),{mode:384}),t}function is(e){return Fl("sha256").update(e.trim().toLowerCase()).digest("hex").slice(0,16)}function Hl(e,t){let r={cwd:e,d:is(t),exp:Date.now()+zl},o=Buffer.from(JSON.stringify(r)).toString("base64url"),s=ns("sha256",ss()).update(o).digest("base64url");return`${o}.${s}`}function Wl(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||!Bl(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 Gl(e){let t=e,r=He(),o=!1;for(let s=0;s<64;s++){if(Dt(ue(t,"mistflow.json")))return"mistflow";if(!o&&Dt(ue(t,"package.json"))&&(o=!0),t===r)break;let i=Ul(t);if(i===t)break;t=i}return o?"foreign":"none"}function Vl(e){let t=He(),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===ue(t,s))return!0;return!1}function Jl(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 Yl(e){let t=ue(He(),".mistflow","plans",`${e}.json`);if(!Dt(t))return null;try{return JSON.parse(rs(t,"utf-8")).plan??null}catch{return null}}async function Ql(e){for(let o=0;o<60;o++){try{let s=await Fo(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 Xl(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:x,confirmToken:b,urlChoice:y,designConversationId:v,designDirection:A}=e;if(s&&!r&&!i&&!v&&!A&&!n&&!a&&!l)try{let u=await Yt(s);return u.status==="clarify_pending"?d(JSON.stringify({status:"running",conversationId:s,phase:"generating_questions",nextAction:`Still generating. 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 questions are ready.`})):u.status==="plan_pending"?d(JSON.stringify({status:"running",conversationId:s,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). 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 plan is ready.`})):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&&!v&&!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(v&&!A&&!R.trim()&&!i)return d(`You passed designConversationId='${v}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${v}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let I=n;if(!I&&a&&(I=Yl(a)??void 0,!I))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let O=s;if(!oe())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let U;if(!O&&!I&&!l){if(!$l(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=Gl(o);if(u!=="mistflow"&&Vl(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"&&!x){if(!(b?Wl(b,o,R):!1)){let S=Hl(o,R);if(t?.server){let T=await br(t.server,[{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",decisionKey:"scopeChoice",recommended:"Scaffold a new Mistflow app in a subdirectory",why:"Mistflow creates a NEW app in a subdirectory \u2014 it does not modify the existing codebase. Pick 'Edit existing' if you wanted to change files in the current project instead of creating a new Mistflow app.",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."}]}],"## Existing project detected\n\nYou're inside a directory that already has a project (no `mistflow.json` though). What do you want to do?");if(T.outcome==="submitted")if((T.answers?.[0]?.answer??"").toLowerCase().startsWith("scaffold"))U="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.";else return d("User chose to edit the existing codebase directly. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0);else return T.outcome==="declined"||T.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:S,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(`
2233
+ `)}))}else return d(JSON.stringify({status:"confirm_new_project",projectPath:o,description:R,confirmToken:S,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(`
2234
+ `)}))}U="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else u==="foreign"&&x&&(U="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await tr(l)).plan)return d("This template has no plan to fork. Try a different template.",!0);let g=await or(l),S=g.plan,T="";if(c&&g.has_source)try{let ie=await Xt(g.plan,c),z=ie.plan??ie,Bt=ie.diff,Io=z?.steps??[],K=new Set([...(Bt?.added??[]).map(H=>H.number),...(Bt?.modified??[]).map(H=>H.number)]),he=Io.map(H=>{let nt=H.number;return K.has(nt)?{...H,status:"pending"}:{...H,status:"completed",source:"forked"}});z.steps=he,S=z;let Ce=he.filter(H=>H.status==="pending").length;T=` Remixed: ${he.filter(H=>H.status==="completed").length} steps unchanged, ${Ce} steps need re-implementation.`}catch(ie){console.error("[plan] Remix failed, using original plan:",ie),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let Z=os(),Y=ue(He(),".mistflow","plans");uo(Y,{recursive:!0}),mo(ue(Y,`${Z}.json`),JSON.stringify({plan:S,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let se=S?.name??"forked-app",le=g.has_source,xt=le?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Qe=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:Z,forkedFrom:g.forked_from,projectId:g.id,hasSource:le,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${T}${Qe} ${xt} NEXT: Call mist_init, name='${se}', and planId='${Z}' to create the project now.`}))}catch(u){let g=u instanceof Error?u.message:"Failed to fork template";return d(g,!0)}if(I){let u;try{u=await Xt(I,R)}catch(Y){let se=Y instanceof Error?Y.message:"Failed to modify plan";return d(se,!0)}let g=u.plan,S=u.diff,T=[];if(S?.added?.length){let Y=S.added.map(se=>se.title);T.push(`Added ${Y.length} step(s): ${Y.join(", ")}`)}if(S?.removed?.length){let Y=S.removed.map(se=>se.title);T.push(`Removed ${Y.length} step(s): ${Y.join(", ")}`)}if(S?.modified?.length){let Y=S.modified.map(se=>se.title);T.push(`Modified ${Y.length} step(s): ${Y.join(", ")}`)}let Z=T.length>0?T.join(". "):"No changes detected.";return d(JSON.stringify({plan:g,diff:S,message:`Plan modified. ${Z}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let k=y?.trim()||void 0,L=i;if(Array.isArray(i)){let u=i.findIndex(g=>g&&typeof g=="object"&&g.decisionKey==="urlChoice");if(u>=0){let g=i[u];!k&&g.answer&&(k=g.answer);let S=i.slice(0,u).concat(i.slice(u+1));L=S.length>0?S:void 0}}else if(i!=null){let u=i;if(!k&&po in u&&(k=u[po]),!k&&"urlChoice"in u&&(k=u.urlChoice),po in u||"urlChoice"in u){let{[po]:g,urlChoice:S,...T}=u;L=Object.keys(T).length>0?T:void 0}}if(k&&(k=k.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),k){let u=k.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(u)?k=u:(console.error(`[mist_plan] Discarding urlChoice '${k}' \u2014 does not look like a subdomain. Backend will auto-generate.`),k=void 0)}let G;if(A){G={...A};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,S]of Object.entries(u))A[g]!==void 0&&G[S]===void 0&&(G[S]=A[g])}let V=i?"Generating plan with your answers (LLM call)":v?"Finalizing design direction":"Thinking through discovery questions",ee=t?Ae(t.server,t.progressToken,()=>V):{stop:()=>{}};t&&(t.cleanup=()=>ee.stop());let E;try{O&&!L&&!v&&!I&&!a?E=await Yt(O):E=await Qt(R,{conversationId:O,answers:L,autonomous:h,language:m,designConversationId:v,designDirection:G})}catch(u){ee.stop();let g=u instanceof Error?u.message:"Failed to generate plan";return d(g,!0)}if(E.status==="clarify_pending"){ee.stop();let u=E;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(E.status==="plan_pending"){ee.stop();let u=E;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(E.status==="design_clarify_pending"&&(V="Generating creative design directions",E=await Ql(E)),ee.stop(),E.status==="clarify"){let u=E.reflection||"",g=E.suggestedName||"",S=E.suggestedFeatures??[],T=E.questions??[],Z=T.some(K=>Array.isArray(K.options)&&typeof K.options[0]=="object"&&K.options[0]?.label),Y={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"},se=T.map(K=>{let he=K.decisionKey&&Y[K.decisionKey]||Jl(K.question),Ce;return Z&&Array.isArray(K.options)?Ce=K.options.map(ce=>({label:ce.label,description:ce.description??""})):Array.isArray(K.options)?Ce=K.options.map((ce,H)=>({label:H===0?`${ce} (Recommended)`:String(ce),description:K.why??""})):Ce=[{label:"Yes (Recommended)",description:K.why??""},{label:"No",description:""}],{question:K.question,header:he,options:Ce,multiSelect:!1}}),xt=E.decisions?.audienceType??null,Qe=S.length>0?Yn(R,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:xt,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:S,language:m}):null,ie=Qe?Qn(Qe):"",z=wr(g||"my-app").slice(0,32);try{let K=await Uo(z);!K.available&&K.suggestion&&(z=K.suggestion)}catch{}ie&&(ie+=`
2235
+
2236
+ **Your app URL:** https://${z}.mistflow.app`);let Bt={question:"Your app URL \u2014 keep the suggested subdomain or type your own",decisionKey:"urlChoice",freetext:!0,recommended:z,why:`Your app will be at <subdomain>.mistflow.app. Subdomains are locked at scaffold time. Keep '${z}' or type your preferred subdomain (lowercase, alphanumeric + hyphens, 3-32 chars).`,options:[{label:`Keep ${z}.mistflow.app`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}]};T.push(Bt);let Io={question:`Your app will be at ${z}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${z}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};if(se.push(Io),t?.server){let K=[g?`## ${g}`:"## Pick a few details","",`${T.length} quick question${T.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
2237
+ `),he=await br(t.server,T,K);if(he.outcome==="submitted"){ee.stop();let Ce={};for(let H of he.answers??[])H.decisionKey?Ce[H.decisionKey]=H.answer:Ce[H.question]=H.answer;let ce=he.urlChoice?.trim();ce&&(ce=ce.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let H=await Qt(R,{conversationId:E.conversation_id,answers:Ce,autonomous:h,language:m});if(H.status==="plan_pending"){let nt=H;return d(JSON.stringify({status:"running",conversationId:nt.conversation_id,phase:"generating_plan",...ce?{urlChoice:ce}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${nt.conversation_id}"${ce?`, urlChoice: "${ce}"`:""} } 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.`}))}E=H}catch(H){let nt=H instanceof Error?H.message:String(H);return d(`Submitting your answers failed: ${nt}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(he.outcome==="declined")return ee.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(he.outcome==="cancelled")return ee.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);he.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${he.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:E.conversation_id,questions:T,questionCount:T.length,suggestedFeatures:S,suggestedName:g,suggestedSubdomain:z,reflection:u,briefText:ie,askUserQuestions:se,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: "${E.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: "${z}".`,'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||ie?["","\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]:[],...ie?["",ie]:[]]:[],...U?["",U]:[]].join(`
2238
+ `)}))}if(E.status==="design_clarify"){let u=E.directions??[],g=E.plan.name??"your app",S;try{let le=u.map(z=>({id:z.id,name:z.name,summary:z.summary,hero_headline:z.hero_headline,cta_text:z.cta_text,body_sample:z.body_sample,fonts:z.fonts,colors:z.colors,hero_treatment:z.hero_treatment,shape_lang:z.shape_lang,texture:z.texture,decoration_hint:z.decoration_hint})),xt=es(g,le),Qe=ue(o,".mistflow");uo(Qe,{recursive:!0});let ie=ue(Qe,"design-directions.html");mo(ie,xt,"utf-8"),S=ie}catch(le){console.error(`[mist_plan] design-directions preview render failed: ${le instanceof Error?le.message:String(le)}`)}let T=u.map(le=>({label:le.name,description:`${le.summary} \u2014 ${le.fonts?.display??""} + ${le.fonts?.body??""}`}));T.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let Z={question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:T,multiSelect:!1},Y=S?[`A visual preview of all ${u.length} directions has been written to:`,` ${S}`,"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 "${S}"`,` \u2022 Linux: run xdg-open "${S}"`,` \u2022 Windows: run start "" "${S}"`," \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(`
2239
+ `):"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.",se=S?`open "${S}"`:"";return d(JSON.stringify({status:"design_clarify",designConversationId:E.design_conversation_id,directions:u,previewPath:S,askUserQuestion:Z,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","",Y,se?`Run this command to open the preview for the user: ${se}`:"","","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: "${E.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(`
2240
+ `)}))}let N=E.plan,ae=N.name??"Untitled App",me=E.methodology,j=N.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 te=N.publicPages;if(!te||Array.isArray(te)&&te.length===0){let u=N.pages,g=j.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),S=Array.isArray(u)&&u.some(T=>T.path==="/"||T.route==="/");g||S?te=["/","/pricing"]:te=["/"]}let _e=N.primaryAction;if(!_e){let u=N.features;if(Array.isArray(u)&&u.length>0){let S=u.find(Z=>typeof Z.priority=="string"&&Z.priority.toLowerCase()==="must-have")??u[0];_e={entity:S.name??S.title??"item",action:"create",fromPage:"/dashboard"}}}let fe=N.nonNegotiables;(!fe||Array.isArray(fe)&&fe.length===0)&&(fe=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Re=os(),Ve=ue(He(),".mistflow","plans");uo(Ve,{recursive:!0});try{let g=Date.now();for(let S of[Ve,ue(He(),".mistflow","mockup-state")])if(Dt(S))for(let T of Ol(S))try{let Z=ue(S,T),Y=Ml(Z).mtimeMs;g-Y>6048e5&&Ll(Z)}catch{}}catch{}let q;if(p){let u=oo(p);u?q=u.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let D=f||void 0,W=!!q,we=j.some(u=>{let g=`${u.name??u.title} ${u.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),J=!W&&we?An(R,{maxResults:2}):[];J.length>0&&(q=J[0].id,console.error(`Auto-assigned landing layout preset (default): ${J[0].title} (${q})`));let Ie={name:N.name,summary:N.summary,dataModel:N.dataModel,pages:N.pages,features:N.features,steps:j.map(u=>({...u,name:u.name??u.title})),design:N.design,landingDesign:q,appStyle:D,dbProvider:N.dbProvider??"neon",authModel:N.authModel,audienceType:N.audienceType??"b2c",roles:N.roles,defaultRole:N.defaultRole,publicPages:te,navStyle:N.navStyle,multiTenant:N.multiTenant,primaryAction:_e,nonNegotiables:fe,requestedSubdomain:k,...m&&m.toLowerCase()!=="english"?{language:m}:{}};mo(ue(Ve,`${Re}.json`),JSON.stringify({plan:Ie,methodology:me}));let Ke=j.map(u=>`${u.number}. ${u.name??u.title}`),Je="",Ye=[],ye;!W&&J.length>0&&(Ye=J.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${at()}/designs?tab=landing-designs`})),ye={question:"What landing page style fits this app?",header:"Landing Design",options:[...J.map((g,S)=>({label:S===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 ${at()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},Je=` 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: ${J.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='${J[0].id}' explicitly.`);let Oe="",Me=[],Le=void 0,C=(N.audienceType??"b2c")==="b2c",B={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:C?"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:C?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},X=" 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="",ne=[];for(let u of j){let g=u.name??u.title,S=u.integrationId;if(S){let T=ut(S);if(T){let Z=mt(T.id);ne.push({step:g,presetId:T.id,presetName:T.name,envVars:Z?.envVars??[]})}}}if(ne.length>0){let u=ne.flatMap(T=>T.envVars),g=[...new Set(u.map(T=>T.key))];ve=` This plan uses integrations (${ne.map(T=>T.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return d(JSON.stringify({planId:Re,name:N.name,summary:N.summary,stepCount:j.length,steps:Ke,design:N.design,...q?{landingDesign:q}:{},...D?{appStyle:D}:{},...Me.length>0?{recommendedAppStyles:Me}:{},...Le?{appStyleQuestion:Le}:{},...Ye.length>0?{recommendedLandingDesigns:Ye}:{},...ye?{landingDesignQuestion:ye}:{},heroPhotoQuestion:B,...ne.length>0?{integrations:ne.map(u=>({step:u.step,preset:u.presetId,name:u.presetName,envVars:u.envVars}))}:{},message:`Plan generated for "${ae}" (${j.length} steps).${q?` Landing layout "${q}" set as default.`:""}${D?` App style "${D}" will be applied across all pages.`:""}${ve}${Oe}${Je}${X}`,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: '${Re}' }). If the user says skip or "just build it", call mist_init({ planId: '${Re}', path: '<absolute path>' }) immediately.`,...U?{warning:U}:{}}))}var po,zl,Kl,as,ls=P(()=>{"use strict";Q();ge();ft();Jn();dr();ro();Xn();ts();po="__mistflow_url_choice__",zl=600*1e3;Kl=_.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(`
2241
+ `),inputSchema:Kl,handler:Xl}});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 Zl(e){return e&&e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function ec(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(`
2242
+ `)}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(`
2243
+ `)}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+$/,"")+`
2244
+
2245
+ `+t}function Tr(e,t){let r=cs(e),o=t??ec(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(`
2246
+ `)}function Pr(e){return`contracts/${Zl(e)}.ts`}var xr,ps,Ir=P(()=>{"use strict";xr="<!-- mist:contracts:start -->",ps="<!-- mist:contracts:end -->"});import{z as jt}from"zod";import{existsSync as tt,mkdirSync as Cr,writeFileSync as Ar,readFileSync as go,readdirSync as hs,copyFileSync as tc}from"fs";import{join as Te,resolve as gs,dirname as Ot,isAbsolute as oc}from"path";import{homedir as rc}from"os";import{spawn as ym}from"child_process";import{randomBytes as nc}from"crypto";import{simpleGit as ic}from"simple-git";function sc(e){let t=Te(rc(),".mistflow","plans",`${e}.json`);if(!tt(t))return null;try{let r=JSON.parse(go(t,"utf-8"));return r.plan?{plan:r.plan}:null}catch{return null}}function ac(e){let t=Ot(gs(e)),r=10,o=0;for(;o<r&&t!==Ot(t);){if(tt(Te(t,"pnpm-workspace.yaml"))||tt(Te(t,"lerna.json")))return t;let s=Te(t,"package.json");if(tt(s))try{if(JSON.parse(go(s,"utf-8")).workspaces)return t}catch{}t=Ot(t),o++}return null}function M(e,t,r){let o=Te(e,t);Cr(Ot(o),{recursive:!0}),Ar(o,r)}function cc(e){if(!tt(e))return!0;let t;try{t=hs(e)}catch{return!1}return t.filter(o=>o!==".mistflow").length===0}function uc(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(`
2247
+ `),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 mc(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(`
2248
+ `),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(`
2249
2249
  `);return`@import "tailwindcss";
2250
2250
  @import "tw-animate-css";
2251
2251
 
@@ -2301,11 +2301,11 @@ ${i}
2301
2301
 
2302
2302
  button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
2303
2303
  button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
2304
- `}function mc(t,e,r){let o=t?.borderRadius??"subtle",s=cc[o]??"0.375rem";if(r){let n=pc(r);if(n)return uc(n,s)}return`@import "tailwindcss";
2304
+ `}function hc(e,t,r){let o=e?.borderRadius??"subtle",s=dc[o]??"0.375rem";if(r){let n=uc(r);if(n)return mc(n,s)}return`@import "tailwindcss";
2305
2305
  @import "tw-animate-css";
2306
2306
 
2307
2307
  @theme {
2308
- ${[...dc.map(([n,a])=>` ${n}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md: ${s};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
2308
+ ${[...pc.map(([n,a])=>` ${n}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md: ${s};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
2309
2309
  `)}
2310
2310
  }
2311
2311
 
@@ -2355,7 +2355,7 @@ ${[...dc.map(([n,a])=>` ${n}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md:
2355
2355
 
2356
2356
  button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
2357
2357
  button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
2358
- `}function us(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return ps[e]?ps[e]:e.replace(/\s+/g,"_")}function hc(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 fc(t,e,r){let o=t.replace(/[\\"`$]/g,""),s=hc(r),n=gc.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";
2358
+ `}function ms(e){let t=e.replace(/[^A-Za-z0-9_ -]/g,"");return us[t]?us[t]:t.replace(/\s+/g,"_")}function gc(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 yc(e,t,r){let o=e.replace(/[\\"`$]/g,""),s=gc(r),n=fc.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
2359
  import { DM_Sans } from "next/font/google";
2360
2360
  import { Toaster } from "sonner";
2361
2361
  import "./globals.css";
@@ -2371,12 +2371,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2371
2371
  </html>
2372
2372
  );
2373
2373
  }
2374
- `;let d=us(a??l),h=us(l??a);return d===h?`import type { Metadata } from "next";
2375
- import { ${d} } from "next/font/google";
2374
+ `;let c=ms(a??l),h=ms(l??a);return c===h?`import type { Metadata } from "next";
2375
+ import { ${c} } from "next/font/google";
2376
2376
  import { Toaster } from "sonner";
2377
2377
  import "./globals.css";
2378
2378
 
2379
- const font = ${d}({ subsets: ["latin"], variable: "--font-body" });
2379
+ const font = ${c}({ subsets: ["latin"], variable: "--font-body" });
2380
2380
 
2381
2381
  export const metadata: Metadata = { title: "${o}", description: "Built with Mistflow" };
2382
2382
 
@@ -2388,11 +2388,11 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2388
2388
  );
2389
2389
  }
2390
2390
  `:`import type { Metadata } from "next";
2391
- import { ${d}, ${h} } from "next/font/google";
2391
+ import { ${c}, ${h} } from "next/font/google";
2392
2392
  import { Toaster } from "sonner";
2393
2393
  import "./globals.css";
2394
2394
 
2395
- const heading = ${d}({ subsets: ["latin"], variable: "--font-heading" });
2395
+ const heading = ${c}({ subsets: ["latin"], variable: "--font-heading" });
2396
2396
  const body = ${h}({ subsets: ["latin"], variable: "--font-body" });
2397
2397
 
2398
2398
  export const metadata: Metadata = { title: "${o}", description: "Built with Mistflow" };
@@ -2404,38 +2404,38 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2404
2404
  </html>
2405
2405
  );
2406
2406
  }
2407
- `}function po(t,...e){let r=JSON.stringify(t).toLowerCase();return e.some(o=>r.includes(o.toLowerCase()))}function Cr(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[r,o]of Object.entries(yc))if(e.includes(r))return o;return"Circle"}function jt(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function bc(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(`
2408
- `)}function wc(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 d=l.path??l.route??"";return d==="/"||d===""||d.includes("[")||d.replace(/^\//,"").split("/").length>1?!1:!e.some(m=>d.startsWith(m))}).map(l=>{let d=l.path??l.route??"",h=d.startsWith("/")?d:"/"+d,m=l.name??jt(d.replace(/^\//,"")),p=Cr(m);return{label:m,href:h,icon:p}});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=jt(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 d of o)l.push(' { label: "'+d.label+'", href: "'+d.href+'", icon: '+d.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(`
2407
+ `}function ho(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(bc))if(t.includes(r))return o;return"Circle"}function Mt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function wc(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(`
2408
+ `)}function vc(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??Mt(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=Mt(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(`
2409
2409
  `)}}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(`
2410
- `)}}function vc(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(`
2411
- `)}function kc(t){let e=jt(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(`
2412
- `)}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(`
2413
- `)}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(`
2410
+ `)}}function xc(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(`
2411
+ `)}function kc(e){let t=Mt(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(`
2412
+ `)}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(`
2413
+ `)}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(`
2414
2414
  `)}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(`
2415
- `)}function xc(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(`
2416
- `)}function Sc(t){let e=jt(t.name),r=t.dataModel??[],o=[];if(r.length>0){let s=r.map(n=>Cr(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=Cr(i),a=jt(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(`
2417
- `)}function Tc(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(`
2418
- `)}function Pc(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(`
2419
- `)}function Ic(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(`
2420
- `)}function Cc(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 d=l.description?` \u2014 ${l.description}`:"";o.push(`- **${l.name}**${d}`)}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 d=l.path??l.route??l.name??"",h=l.description??"";o.push(`| \`${d.startsWith("/")?d:"/"+d}\` | ${h} |`)}o.push("")}let a=e?.dataModel??[];if(a.length>0){o.push("## Data Model"),o.push("");for(let l of a){let d=l.entity??l.name??"Unknown";if(o.push(`### ${d}`),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(""),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(`
2421
- `)}async function Ac(t,e){let{name:r,plan:o,path:s,planId:i}=t;if(!s)return c("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(!tc(s))return c(`mist_init 'path' must be an absolute path \u2014 received '${s}'. Pass the full absolute path to the target directory.`,!0);let n=hs(s),a=o;if(!a&&i){let w=nc(i);if(!w)return c(`No plan found for planId '${i}'. Call mist_plan first, or pass the plan object inline.`,!0);a=w.plan}let l=a?.design,d=a?.appStyle,h=a?po(a,"stripe","payment","billing","subscription","checkout","pricing"):!1,m=!0,p=a?po(a,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,y=a?po(a,"admin panel","admin dashboard","admin management"):!1,x=a?po(a,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,b=a,f=!0;if(!lc(n))return c(`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);Pr(n,{recursive:!0});try{let w=Te(Dt(n),".mistflow","mockups");if(et(w)){let C=ms(w).filter(B=>B.endsWith(".html"));if(C.length>0){let B=Te(n,".mistflow","mockups");Pr(B,{recursive:!0});for(let X of C)ec(Te(w,X),Te(B,X));console.error(`Copied ${C.length} mockup file(s) into project`)}}}catch(w){console.error("Could not copy mockup files:",w instanceof Error?w.message:w)}let T=null;try{T=await Jo("nextjs")}catch(w){console.error("Could not fetch scaffold from API, using minimal scaffold:",w instanceof Error?w.message:w)}if(T){let w=r.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let u of T.files){if(u.path==="package.json"||u.path==="middleware.ts"||u.path==="components/sidebar.tsx"||u.path==="components/topnav.tsx"||u.path==="app/(dashboard)/layout.tsx"||u.path==="app/(dashboard)/page.tsx"||u.path==="app/(dashboard)/dashboard/page.tsx"||!h&&(u.path.includes("stripe")||u.path.includes("webhook/stripe"))||!m&&(u.path.includes("resend")||u.path.includes("emails/"))||!y&&(u.path.includes("(admin)")||u.path.includes("admin-sidebar"))||f&&(u.path==="lib/db.ts"||u.path==="lib/auth.ts"||u.path==="drizzle.config.ts"||u.path==="db/schema/auth.ts"))continue;let g=u.content.replace(/\{\{APP_NAME\}\}/g,r).replace(/\{\{WORKER_NAME\}\}/g,w);if(f&&u.path==="next.config.ts"&&(g=g.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),u.path==="next.config.ts"){let k=ic(n);k&&(console.error(`[init] Project is inside monorepo at ${k} \u2014 adding outputFileTracingRoot`),g.includes("outputFileTracingRoot")||(g=g.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
2415
+ `)}function Sc(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(`
2416
+ `)}function Tc(e){let t=Mt(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=Mt(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(`
2417
+ `)}function Pc(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(`
2418
+ `)}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(`
2419
+ `)}function Cc(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(`
2420
+ `)}function Ac(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(`
2421
+ `)}async function _c(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(!oc(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=sc(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?ho(a,"stripe","payment","billing","subscription","checkout","pricing"):!1,m=!0,p=a?ho(a,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,f=a?ho(a,"admin panel","admin dashboard","admin management"):!1,x=a?ho(a,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,b=a,y=!0;if(!cc(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);Cr(n,{recursive:!0});try{let w=Te(Ot(n),".mistflow","mockups");if(tt(w)){let C=hs(w).filter(B=>B.endsWith(".html"));if(C.length>0){let B=Te(n,".mistflow","mockups");Cr(B,{recursive:!0});for(let X of C)tc(Te(w,X),Te(B,X));console.error(`Copied ${C.length} mockup file(s) into project`)}}}catch(w){console.error("Could not copy mockup files:",w instanceof Error?w.message:w)}let v=null;try{v=await Xo("nextjs")}catch(w){console.error("Could not fetch scaffold from API, using minimal scaffold:",w instanceof Error?w.message:w)}if(v){let w=r.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let u of v.files){if(u.path==="package.json"||u.path==="middleware.ts"||u.path==="components/sidebar.tsx"||u.path==="components/topnav.tsx"||u.path==="app/(dashboard)/layout.tsx"||u.path==="app/(dashboard)/page.tsx"||u.path==="app/(dashboard)/dashboard/page.tsx"||!h&&(u.path.includes("stripe")||u.path.includes("webhook/stripe"))||!m&&(u.path.includes("resend")||u.path.includes("emails/"))||!f&&(u.path.includes("(admin)")||u.path.includes("admin-sidebar"))||y&&(u.path==="lib/db.ts"||u.path==="lib/auth.ts"||u.path==="drizzle.config.ts"||u.path==="db/schema/auth.ts"))continue;let g=u.content.replace(/\{\{APP_NAME\}\}/g,r).replace(/\{\{WORKER_NAME\}\}/g,w);if(y&&u.path==="next.config.ts"&&(g=g.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),u.path==="next.config.ts"){let S=ac(n);S&&(console.error(`[init] Project is inside monorepo at ${S} \u2014 adding outputFileTracingRoot`),g.includes("outputFileTracingRoot")||(g=g.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
2422
2422
  import { dirname } from "path";
2423
2423
  import { fileURLToPath } from "url";
2424
2424
 
2425
2425
  const __dirname = dirname(fileURLToPath(import.meta.url));`),g=g.replace("images: {",`outputFileTracingRoot: __dirname,
2426
- images: {`)))}!y&&u.path.includes("sidebar")&&(g=g.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),g=g.replace(/, Shield/g,"")),M(n,u.path,g)}let C={...T.dependencies},B={...T.devDependencies};if(C["drizzle-zod"]||(C["drizzle-zod"]="^0.5.1"),f&&(delete C["@libsql/client"],C["@neondatabase/serverless"]="^0.10.0",B["@electric-sql/pglite"]="^0.2.0"),h&&(C.stripe="^17.0.0"),m&&(C.resend="^4.0.0",C["@react-email/components"]="^0.0.31"),x&&(C.ai="^4.0.0",C["@ai-sdk/openai"]="^1.0.0",C.openai="^4.0.0"),M(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:C,devDependencies:B,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)),T.methodology){let u=T.methodology;f&&(u=u.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")),u=kr(u),M(n,"AGENTS.md",u),M(n,"CLAUDE.md",u)}let ne=a?.designMd;ne&&M(n,"DESIGN.md",ne),f&&(M(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(`
2426
+ images: {`)))}!f&&u.path.includes("sidebar")&&(g=g.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),g=g.replace(/, Shield/g,"")),M(n,u.path,g)}let C={...v.dependencies},B={...v.devDependencies};if(C["drizzle-zod"]||(C["drizzle-zod"]="^0.5.1"),y&&(delete C["@libsql/client"],C["@neondatabase/serverless"]="^0.10.0",B["@electric-sql/pglite"]="^0.2.0"),h&&(C.stripe="^17.0.0"),m&&(C.resend="^4.0.0",C["@react-email/components"]="^0.0.31"),x&&(C.ai="^4.0.0",C["@ai-sdk/openai"]="^1.0.0",C.openai="^4.0.0"),M(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:C,devDependencies:B,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)),v.methodology){let u=v.methodology;y&&(u=u.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")),u=Sr(u),M(n,"AGENTS.md",u),M(n,"CLAUDE.md",u)}let ne=a?.designMd;ne&&M(n,"DESIGN.md",ne),y&&(M(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(`
2427
2427
  `)),M(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(`
2428
2428
  `)),M(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(`
2429
2429
  `)),M(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(`
2430
2430
  `)),M(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(`
2431
- `)))}else M(n,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0},null,2));let _=a?.designMd;M(n,"app/globals.css",mc(l,d,_)),M(n,"app/layout.tsx",fc(r,l,b?.language)),M(n,"README.md",Cc(r,a,{hasStripe:h,hasResend:m,hasStorage:p,hasAdmin:y,hasAI:x,isNeon:f})),M(n,"contracts/README.md",vr());let E=a?.dataModel??[],I=new Set,O=0;for(let w of E){let C=w.entity??w.name;if(!C||typeof C!="string")continue;let B=Sr(C);I.has(B)||(I.add(B),M(n,B,xr(C)),O++)}O===0&&M(n,"contracts/.gitkeep","");let U=[],v=a?.publicPages;if(Array.isArray(v))U=v;else if(typeof v=="string"){try{U=JSON.parse(v)}catch{U=[]}Array.isArray(U)||(U=[])}if(!U.includes("/")){let w=a?.steps?.some(B=>{let X=((B.name??"")+" "+(B.description??"")).toLowerCase();return X.includes("landing")||X.includes("marketing")||X.includes("homepage")}),C=a?.pages?.some(B=>B.path==="/");(w||C)&&(U=["/",...U])}let L={name:r,summary:a?.summary,authModel:a?.authModel,roles:a?.roles,defaultRole:a?.defaultRole,publicPages:U,navStyle:a?.navStyle,multiTenant:a?.multiTenant,pages:a?.pages,dataModel:a?.dataModel,design:a?.design},G=bc(L);G&&M(n,"middleware.ts",G);let V=wc(L);V&&M(n,V.path,V.content);let ee=vc(L);if(ee&&M(n,"lib/roles.ts",ee),M(n,"app/page.tsx",kc(L)),M(n,"app/(dashboard)/layout.tsx",xc(L,y)),M(n,"app/(dashboard)/dashboard/page.tsx",Sc(L)),L.multiTenant){let w=Tc(L,f);w&&M(n,"db/schema/organization.ts",w);let C=Pc(L);C&&M(n,"lib/org.ts",C);let B=Ic(L);B&&M(n,"components/org-switcher.tsx",B)}M(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&&M(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(`
2431
+ `)))}else M(n,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0},null,2));let A=a?.designMd;M(n,"app/globals.css",hc(l,c,A)),M(n,"app/layout.tsx",yc(r,l,b?.language)),M(n,"README.md",Ac(r,a,{hasStripe:h,hasResend:m,hasStorage:p,hasAdmin:f,hasAI:x,isNeon:y})),M(n,"contracts/README.md",kr());let R=a?.dataModel??[],I=new Set,O=0;for(let w of R){let C=w.entity??w.name;if(!C||typeof C!="string")continue;let B=Pr(C);I.has(B)||(I.add(B),M(n,B,Tr(C)),O++)}O===0&&M(n,"contracts/.gitkeep","");let U=[],k=a?.publicPages;if(Array.isArray(k))U=k;else if(typeof k=="string"){try{U=JSON.parse(k)}catch{U=[]}Array.isArray(U)||(U=[])}if(!U.includes("/")){let w=a?.steps?.some(B=>{let X=((B.name??"")+" "+(B.description??"")).toLowerCase();return X.includes("landing")||X.includes("marketing")||X.includes("homepage")}),C=a?.pages?.some(B=>B.path==="/");(w||C)&&(U=["/",...U])}let L={name:r,summary:a?.summary,authModel:a?.authModel,roles:a?.roles,defaultRole:a?.defaultRole,publicPages:U,navStyle:a?.navStyle,multiTenant:a?.multiTenant,pages:a?.pages,dataModel:a?.dataModel,design:a?.design},G=wc(L);G&&M(n,"middleware.ts",G);let V=vc(L);V&&M(n,V.path,V.content);let ee=xc(L);if(ee&&M(n,"lib/roles.ts",ee),M(n,"app/page.tsx",kc(L)),M(n,"app/(dashboard)/layout.tsx",Sc(L,f)),M(n,"app/(dashboard)/dashboard/page.tsx",Tc(L)),L.multiTenant){let w=Pc(L,y);w&&M(n,"db/schema/organization.ts",w);let C=Ic(L);C&&M(n,"lib/org.ts",C);let B=Cc(L);B&&M(n,"components/org-switcher.tsx",B)}M(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&&M(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(`
2432
2432
  `)),m&&(M(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(`
2433
2433
  `)),M(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(`
2434
2434
  `))),p&&(M(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(`
2435
2435
  `)),M(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(`
2436
2436
  `))),x&&(M(n,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
2437
2437
  `)),M(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(`
2438
- `)));let R=Array.isArray(a?.integrations)?a.integrations.map(w=>({name:w.name,preset:w.preset,envVars:w.envVars??[]})):[],N={};x&&!R.some(w=>w.envVars?.some(C=>C.key==="OPENAI_API_KEY"))&&(N.OPENAI_API_KEY={description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"});for(let w of R)for(let C of w.envVars??[])N[C.key]||(N[C.key]={description:C.description,setupUrl:C.setupUrl,...w.name?{integration:w.name}:{}});let ae={name:r,methodologyVersion:T?.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(N).length>0?{required:N}:{}},authModel:a?.authModel??"email",roles:a?.roles??null,navStyle:a?.navStyle??"sidebar",multiTenant:a?.multiTenant??!1,hasAdmin:y,hasResend:m,hasStorage:p,hasAI:x,deploy:null};M(n,"mistflow.json",JSON.stringify(ae,null,2));let me=rc(32).toString("hex"),j=h?`
2438
+ `)));let E=Array.isArray(a?.integrations)?a.integrations.map(w=>({name:w.name,preset:w.preset,envVars:w.envVars??[]})):[],N={};x&&!E.some(w=>w.envVars?.some(C=>C.key==="OPENAI_API_KEY"))&&(N.OPENAI_API_KEY={description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"});for(let w of E)for(let C of w.envVars??[])N[C.key]||(N[C.key]={description:C.description,setupUrl:C.setupUrl,...w.name?{integration:w.name}:{}});let ae={name:r,methodologyVersion:v?.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(N).length>0?{required:N}:{}},authModel:a?.authModel??"email",roles:a?.roles??null,navStyle:a?.navStyle??"sidebar",multiTenant:a?.multiTenant??!1,hasAdmin:f,hasResend:m,hasStorage:p,hasAI:x,deploy:null};M(n,"mistflow.json",JSON.stringify(ae,null,2));let me=nc(32).toString("hex"),j=h?`
2439
2439
  # Stripe
2440
2440
  STRIPE_SECRET_KEY=
2441
2441
  STRIPE_WEBHOOK_SECRET=
@@ -2444,23 +2444,23 @@ NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
2444
2444
  # Email (Resend)
2445
2445
  RESEND_API_KEY=
2446
2446
  EMAIL_FROM=onboarding@resend.dev
2447
- `:"",Ae=p?`
2447
+ `:"",_e=p?`
2448
2448
  # File Storage (Mistflow managed)
2449
2449
  MISTFLOW_API_KEY=
2450
2450
  MISTFLOW_PROJECT_ID=
2451
2451
  `:"",fe=x?`
2452
2452
  # AI (get your key at https://platform.openai.com/api-keys)
2453
2453
  OPENAI_API_KEY=
2454
- `:"",_e=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2454
+ `:"",Re=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2455
2455
  # Set DATABASE_URL only for production or to use a remote Postgres
2456
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Ge=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2456
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Ve=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2457
2457
  # Set DATABASE_URL only for production or to use a remote Postgres
2458
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;M(n,".env.local",`${_e}
2458
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;M(n,".env.local",`${Re}
2459
2459
  AUTH_SECRET=${me}
2460
- ${j}${te}${Ae}${fe}`),M(n,".env.example",`${Ge}
2460
+ ${j}${te}${_e}${fe}`),M(n,".env.example",`${Ve}
2461
2461
  AUTH_SECRET=your-secret-here
2462
- ${j}${te}${Ae}${fe}`);let q=[],D=(w,C)=>{q.push({phase:w,message:C})},W=(w,C)=>{let B=q.find(X=>X.phase===w&&!X.durationMs);B&&(B.durationMs=C)};if(e){let w=io(e.server,e.progressToken,()=>q[q.length-1]?.message??"Setting up project...");e.cleanup=()=>w.stop()}let we=b?.requestedSubdomain||void 0,J,Ie;D("register","Registering project on Mistflow...");let Ve=Date.now();try{let w=await Pt(r,void 0,"neon",we);J=w.id;let C=Te(n,"mistflow.json"),B=JSON.parse(uo(C,"utf-8"));if(B.projectId=J,Ir(C,JSON.stringify(B,null,2)),Ct(n,At(J,r)),w.managed_env&&Object.keys(w.managed_env).length>0){let X=Te(n,".env.local"),ve=et(X)?uo(X,"utf-8"):"";for(let[ne,u]of Object.entries(w.managed_env)){let g=new RegExp(`^${ne}=.*$`,"m");g.test(ve)?ve=ve.replace(g,`${ne}=${u}`):ve+=`
2463
- ${ne}=${u}`}Ir(X,ve)}try{let{getBaseUrl:X,getAuthHeaders:ve}=await Promise.resolve().then(()=>(ge(),ln)),ne=ve(),u=a?.features,g=a?.steps,k={};Array.isArray(u)&&u.length>0&&(k.features=u.map(S=>S.name)),a&&(k.plan=a),Array.isArray(g)&&g.length>0&&(k.provenance=g.map(S=>({feature:S.name??S.title??`Step ${S.number??"?"}`,user_intent:(S.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(k).length>0&&await fetch(`${X()}/api/projects/${encodeURIComponent(J)}/state`,{method:"PUT",headers:{...ne,"Content-Type":"application/json"},body:JSON.stringify(k)})}catch{}q[q.length-1].message=`Registered as ${J.slice(0,8)}`}catch(w){let C=w instanceof Error?w.message:String(w);console.error("Could not register project on backend:",C),Ie=`Project created locally but NOT registered on Mistflow servers (${C}). Deploy will auto-register it.`,q[q.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}W("register",Date.now()-Ve),D("git","Initializing git repository...");let Ke=Date.now();try{let w=sc(n);await w.init(),await w.add("."),await w.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"}W("git",Date.now()-Ke);let Je=q.reduce((w,C)=>w+(C.durationMs??0),0),ye={projectPath:n,projectId:J,status:"awaiting_install"},je=q.map(w=>{let C=w.durationMs?` (${(w.durationMs/1e3).toFixed(1)}s)`:"";return`${w.message}${C}`});ye.progress=je,ye.totalSetupTime=`${(Je/1e3).toFixed(1)}s`;let Oe=[];J||Oe.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),Ie&&(ye.registrationWarning=Ie),Oe.length>0&&(ye.warnings=Oe);let Me=`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 ye.nextAction=J?Me:`${Me} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,c(JSON.stringify(ye))}var ac,cc,dc,ps,gc,yc,gs,fs=P(()=>{"use strict";Q();gr();ge();Xe();Tr();Tr();ac=Nt.object({name:Nt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:Nt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Nt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Nt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});cc={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},dc=[["--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"]];ps={"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"};gc=new Set(["ar","he","fa","ur"]);yc={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"};gs={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:ac,handler:Ac}});var bs,ys=P(()=>{bs="\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 vs,ws=P(()=>{vs=`# Consumer Warm Archetype
2462
+ ${j}${te}${_e}${fe}`);let q=[],D=(w,C)=>{q.push({phase:w,message:C})},W=(w,C)=>{let B=q.find(X=>X.phase===w&&!X.durationMs);B&&(B.durationMs=C)};if(t){let w=Ae(t.server,t.progressToken,()=>q[q.length-1]?.message??"Setting up project...");t.cleanup=()=>w.stop()}let we=b?.requestedSubdomain||void 0,J,Ie;D("register","Registering project on Mistflow...");let Ke=Date.now();try{let w=await Ct(r,void 0,"neon",we);J=w.id;let C=Te(n,"mistflow.json"),B=JSON.parse(go(C,"utf-8"));if(B.projectId=J,Ar(C,JSON.stringify(B,null,2)),_t(n,Rt(J,r)),w.managed_env&&Object.keys(w.managed_env).length>0){let X=Te(n,".env.local"),ve=tt(X)?go(X,"utf-8"):"";for(let[ne,u]of Object.entries(w.managed_env)){let g=new RegExp(`^${ne}=.*$`,"m");g.test(ve)?ve=ve.replace(g,`${ne}=${u}`):ve+=`
2463
+ ${ne}=${u}`}Ar(X,ve)}try{let{getBaseUrl:X,getAuthHeaders:ve}=await Promise.resolve().then(()=>(ge(),cn)),ne=ve(),u=a?.features,g=a?.steps,S={};Array.isArray(u)&&u.length>0&&(S.features=u.map(T=>T.name)),a&&(S.plan=a),Array.isArray(g)&&g.length>0&&(S.provenance=g.map(T=>({feature:T.name??T.title??`Step ${T.number??"?"}`,user_intent:(T.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(S).length>0&&await fetch(`${X()}/api/projects/${encodeURIComponent(J)}/state`,{method:"PUT",headers:{...ne,"Content-Type":"application/json"},body:JSON.stringify(S)})}catch{}q[q.length-1].message=`Registered as ${J.slice(0,8)}`}catch(w){let C=w instanceof Error?w.message:String(w);console.error("Could not register project on backend:",C),Ie=`Project created locally but NOT registered on Mistflow servers (${C}). Deploy will auto-register it.`,q[q.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}W("register",Date.now()-Ke),D("git","Initializing git repository...");let Je=Date.now();try{let w=ic(n);await w.init(),await w.add("."),await w.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"}W("git",Date.now()-Je);let Ye=q.reduce((w,C)=>w+(C.durationMs??0),0),ye={projectPath:n,projectId:J,status:"awaiting_install"},Oe=q.map(w=>{let C=w.durationMs?` (${(w.durationMs/1e3).toFixed(1)}s)`:"";return`${w.message}${C}`});ye.progress=Oe,ye.totalSetupTime=`${(Ye/1e3).toFixed(1)}s`;let Me=[];J||Me.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),Ie&&(ye.registrationWarning=Ie),Me.length>0&&(ye.warnings=Me);let Le=`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 ye.nextAction=J?Le:`${Le} 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(ye))}var lc,dc,pc,us,fc,bc,fs,ys=P(()=>{"use strict";Q();ft();ge();Ze();Ir();Ir();lc=jt.object({name:jt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:jt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:jt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:jt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});dc={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},pc=[["--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"};fc=new Set(["ar","he","fa","ur"]);bc={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:lc,handler:_c}});var ws,bs=P(()=>{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=P(()=>{xs=`# Consumer Warm Archetype
2464
2464
 
2465
2465
  Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
2466
2466
 
@@ -2627,7 +2627,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
2627
2627
  - Small touch targets. Phone-first means \`h-12\` minimum.
2628
2628
  - Empty states that just say "No data." Be encouraging.
2629
2629
  - Dark theme as default. Consumer warm apps default to light.
2630
- `});var xs,ks=P(()=>{xs=`# Consumer Bold Archetype
2630
+ `});var Ss,ks=P(()=>{Ss=`# Consumer Bold Archetype
2631
2631
 
2632
2632
  Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
2633
2633
 
@@ -2798,7 +2798,7 @@ Social/competitive apps need an activity feed:
2798
2798
  - Card-only layouts with no hierarchy. Use hero cards + supporting cards.
2799
2799
  - Missing achievement/progress systems. The gamification IS the product.
2800
2800
  - Light-touch buttons. CTAs should be unmissable.
2801
- `});var Ts,Ss=P(()=>{Ts=`# Professional Clean Archetype
2801
+ `});var Ps,Ts=P(()=>{Ps=`# Professional Clean Archetype
2802
2802
 
2803
2803
  Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
2804
2804
 
@@ -3010,7 +3010,7 @@ h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
3010
3010
  - Missing status workflows. Every booking/appointment needs a clear state machine.
3011
3011
  - Dark theme as default. Clients associate light themes with professionalism.
3012
3012
  - Emoji in the UI. Professional context.
3013
- `});var Is,Ps=P(()=>{Is=`# Education Structured Archetype
3013
+ `});var Cs,Is=P(()=>{Cs=`# Education Structured Archetype
3014
3014
 
3015
3015
  Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
3016
3016
 
@@ -3210,7 +3210,7 @@ border-2 border-destructive bg-destructive/5 rounded-xl p-4
3210
3210
  - Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
3211
3211
  - Long lesson pages with no progress indicator. Users need to know where they are.
3212
3212
  - Multiple competing elements per view. One thing at a time. One question at a time.
3213
- `});var As,Cs=P(()=>{As=`# Marketplace Browse Archetype
3213
+ `});var _s,As=P(()=>{_s=`# Marketplace Browse Archetype
3214
3214
 
3215
3215
  Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
3216
3216
 
@@ -3434,7 +3434,7 @@ border-b border-border/30 py-4
3434
3434
  - Small product images. The image is the primary decision-making element.
3435
3435
  - No empty state for zero search results. "No results for 'xyz'. Try broader terms."
3436
3436
  - Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
3437
- `});var Rs,_s=P(()=>{Rs=`# SaaS Analytical Archetype
3437
+ `});var Es,Rs=P(()=>{Es=`# SaaS Analytical Archetype
3438
3438
 
3439
3439
  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.
3440
3440
 
@@ -3615,7 +3615,7 @@ The most recognizable B2B SaaS landing pattern.
3615
3615
  - **Inter as the only font.** Pair it with a distinctive heading font or swap it entirely.
3616
3616
  - **Centered text + centered image below.** The most overused AI hero. Use split or offset layouts.
3617
3617
  - **Animation on every element.** Efficient motion only: hero entrance, card reveals on scroll, number counters. Nothing else.
3618
- `});var Ns,Es=P(()=>{Ns=`# Content Editorial Archetype
3618
+ `});var Ds,Ns=P(()=>{Ds=`# Content Editorial Archetype
3619
3619
 
3620
3620
  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.
3621
3621
 
@@ -3822,7 +3822,7 @@ Below the hero: 3 featured pieces laid out as a horizontal strip with **oversize
3822
3822
  - **Dark mode as default for a reading tool.** Offer it as a toggle, not the default.
3823
3823
  - **Flashy motion while reading.** Scroll hijacking, parallax on body text, animated backgrounds behind paragraphs \u2014 all break reading flow.
3824
3824
  - **More than 2 fonts.** Heading + body is enough. Adding a third font for captions or metadata dilutes the identity.
3825
- `});var js,Ds=P(()=>{js=`# Devtool Technical Archetype
3825
+ `});var Os,js=P(()=>{Os=`# Devtool Technical Archetype
3826
3826
 
3827
3827
  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.
3828
3828
 
@@ -4011,7 +4011,7 @@ Numbers styled as terminal output: \`> 47,293 deploys this week\`, \`> 99.98% up
4011
4011
  - **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).
4012
4012
  - **Feature cards with rocket / lightning / puzzle icons.** Use technical icons (terminal, code, database, network) or skip icons entirely.
4013
4013
  - **Motion on code blocks** while the user is trying to read them. Type out ONCE on load, then leave them alone.
4014
- `});var Ms,Os=P(()=>{Ms=`# Creative Showcase Archetype
4014
+ `});var Ls,Ms=P(()=>{Ls=`# Creative Showcase Archetype
4015
4015
 
4016
4016
  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.
4017
4017
 
@@ -4228,7 +4228,7 @@ Premium agency touch: on first load, a full-screen loading component shows the s
4228
4228
  - **Scroll hijacking through the whole site.** Use sparingly \u2014 one or two scroll-pinned sections maximum.
4229
4229
  - **Mystery-meat navigation.** Clever is bad here. "Work / About / Contact" is fine. Don't make visitors guess.
4230
4230
  - **No contact info.** The primary purpose of this site is to generate inquiries. Make it stupid-easy to contact you.
4231
- `});var Us,Ls=P(()=>{Us=`# Finance Clarity Archetype
4231
+ `});var $s,Us=P(()=>{$s=`# Finance Clarity Archetype
4232
4232
 
4233
4233
  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.
4234
4234
 
@@ -4447,7 +4447,7 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
4447
4447
  - **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
4448
4448
  - **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
4449
4449
  - **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.
4450
- `});function Fs(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return $s[e]}var $s,Wm,qs=P(()=>{"use strict";ws();ks();Ss();Ps();Cs();_s();Es();Ds();Os();Ls();$s={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:vs},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:xs},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Ts},"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:As},"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:Rs},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Ns},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:js},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:Ms},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:Us}},Wm=Object.keys($s)});var zs,Bs=P(()=>{zs=`# Landing Page Rules
4450
+ `});function qs(e){let t=e?.archetype;if(!(!t||typeof t!="string"))return Fs[t]}var Fs,Km,Bs=P(()=>{"use strict";vs();ks();Ts();Is();As();Rs();Ns();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:Cs},"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:Es},"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}},Km=Object.keys(Fs)});var Hs,zs=P(()=>{Hs=`# Landing Page Rules
4451
4451
 
4452
4452
  These rules apply to every landing page. They are non-negotiable.
4453
4453
 
@@ -4844,7 +4844,7 @@ app/
4844
4844
  \`\`\`
4845
4845
 
4846
4846
  Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
4847
- `});var Ws,Hs=P(()=>{Ws=`# Design Doctrine
4847
+ `});var Gs,Ws=P(()=>{Gs=`# Design Doctrine
4848
4848
 
4849
4849
  This is the standard for every UI you generate. It is not aspirational. It is the floor.
4850
4850
 
@@ -4910,7 +4910,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
4910
4910
  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.**
4911
4911
 
4912
4912
  If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
4913
- `});var Vs,Gs=P(()=>{Vs=`# Typography
4913
+ `});var Ks,Vs=P(()=>{Ks=`# Typography
4914
4914
 
4915
4915
  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.
4916
4916
 
@@ -4998,7 +4998,7 @@ Pick exactly one:
4998
4998
  - **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
4999
4999
 
5000
5000
  Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
5001
- `});var Js,Ks=P(()=>{Js="# 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 Qs,Ys=P(()=>{Qs=`# Motion
5001
+ `});var Ys,Js=P(()=>{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=P(()=>{Xs=`# Motion
5002
5002
 
5003
5003
  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.
5004
5004
 
@@ -5076,7 +5076,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
5076
5076
  ## One-Line Motion Rule
5077
5077
 
5078
5078
  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.
5079
- `});var Zs,Xs=P(()=>{Zs=`# Spatial Composition
5079
+ `});var ei,Zs=P(()=>{ei=`# Spatial Composition
5080
5080
 
5081
5081
  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.
5082
5082
 
@@ -5146,7 +5146,7 @@ To signal "designed, not templated":
5146
5146
  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.
5147
5147
 
5148
5148
  Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
5149
- `});var ti,ei=P(()=>{ti=`# Interaction
5149
+ `});var oi,ti=P(()=>{oi=`# Interaction
5150
5150
 
5151
5151
  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.
5152
5152
 
@@ -5231,7 +5231,7 @@ Small moments that add up to "designed":
5231
5231
  - **Empty states** offer a specific next action, not "No data yet".
5232
5232
 
5233
5233
  These micro-interactions are the texture of a designed product. Ship them.
5234
- `});var ri,oi=P(()=>{ri=`# UX Writing
5234
+ `});var ni,ri=P(()=>{ni=`# UX Writing
5235
5235
 
5236
5236
  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.
5237
5237
 
@@ -5307,14 +5307,14 @@ If there's a pricing page:
5307
5307
  ## The Footer
5308
5308
 
5309
5309
  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."
5310
- `});import{z as Ar}from"zod";import{existsSync as Ot,readFileSync as Rr,writeFileSync as _r,mkdirSync as Kc}from"fs";import{join as gt,resolve as Jc,dirname as Yc}from"path";import{createConnection as Qc}from"net";function Xc(t){return new Promise(e=>{let r=Qc({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}function ed(t){let e=gt(t,"mistflow.json");if(!Ot(e))return null;try{return JSON.parse(Rr(e,"utf-8"))}catch{return null}}function ni(t,e){let r=gt(t,"mistflow.json");_r(r,JSON.stringify(e,null,2)+`
5311
- `)}function mo(t){return t.entity??t.name??"Unknown"}function td(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function si(t){return t.path??t.route??t.name??""}function od(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 ii(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=mo(o).toLowerCase();return r.some(i=>s.includes(i)||i.includes(s))})}function rd(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=si(o).toLowerCase();return r.some(n=>s.includes(n)||n.includes(s)||i.includes(n))})}function sd(t){let e=t.stepType;if(e&&nd.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 id(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 ad(t,e){let r=[];if(r.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&r.push(`- **App tone**: ${t.tone}`),t.fonts&&(r.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),r.push(`- **Body font**: ${t.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)."),t.borderRadius){let o={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};r.push(`- **Border radius**: ${t.borderRadius} (${o[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.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**: ${t.shadowStyle} \u2014 ${o[t.shadowStyle]??t.shadowStyle}`)}if(t.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**: ${t.cardStyle} \u2014 ${o[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&r.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let o=t.visualStrategy,s=t.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=Fs(t);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(bs),r.join(`
5312
- `)}async function ld(t){try{let e=await Yo("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
5310
+ `});import{z as Rr}from"zod";import{existsSync as Lt,readFileSync as Nr,writeFileSync as Er,mkdirSync as Jc}from"fs";import{join as bt,resolve as Yc,dirname as Qc}from"path";import{createConnection as Xc}from"net";function Zc(e){return new Promise(t=>{let r=Xc({port:e,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),t(!0)}),r.on("error",()=>{t(!1)})})}function td(e){let t=bt(e,"mistflow.json");if(!Lt(t))return null;try{return JSON.parse(Nr(t,"utf-8"))}catch{return null}}function si(e,t){let r=bt(e,"mistflow.json");Er(r,JSON.stringify(t,null,2)+`
5311
+ `)}function fo(e){return e.entity??e.name??"Unknown"}function od(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 rd(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=fo(o).toLowerCase();return r.some(i=>s.includes(i)||i.includes(s))})}function nd(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 id(e){let t=e.stepType;if(t&&sd.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 ad(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 ld(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(`
5312
+ `)}async function cd(e){try{let t=await Zo("nextjs",e);return{reminders:t.reminders,skill:t.skill}}catch{return{reminders:`### ${e} step
5313
5313
  - Follow existing patterns in the codebase
5314
- - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function cd(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(ad(e.design,{hasDesignPreset:!!e.landingDesign&&(s==="landing"||s==="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 b=Wn(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 f of b){let T=f.replace(i,"").replace(/^\//,"");n.push(`- \`${T}\``)}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 d=["landing","design","auth","general","crud","dashboard"];e.audienceType&&d.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(b=>n.push(`- ${b}`)),n.push(""));let h=e.dataModel?ii(t,e.dataModel):[];h.length>0&&(n.push("### Data model (from plan):"),h.forEach(b=>{let f=mo(b),T=td(b.fields);n.push(`- **${f}**: ${T}`),n.push(` Schema file: \`db/schema/${f.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),n.push(""));let m=e.pages?rd(t,e.pages):[];if(m.length>0&&(n.push("### Pages to create/update:"),m.forEach(b=>{let f=b.description?` \u2014 ${b.description}`:"";n.push(`- \`${si(b)}\`${f}`)}),n.push("")),s==="crud"&&h.length>0&&h.forEach(b=>{let f=mo(b),T=f.toLowerCase().replace(/\s+/g,"-"),_=T.endsWith("s")?T:`${T}s`;n.push(`### Files for ${f} 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/${T}-table-columns.tsx\``),n.push(`- Form: \`components/${T}-form.tsx\``),n.push("")}),l){n.push("## Design Doctrine (the standard for every UI step)"),n.push(""),n.push(Ws),n.push(""),n.push("## Design Reference Library"),n.push(""),n.push("### Typography"),n.push(Vs),n.push(""),n.push("### Color"),n.push(Js),n.push(""),n.push("### Motion"),n.push(Qs),n.push(""),n.push("### Spatial Composition"),n.push(Zs),n.push(""),n.push("### Interaction"),n.push(ti),n.push(""),n.push("### UX Writing"),n.push(ri),n.push("");let b=i?gt(i,"DESIGN.md"):void 0,f=b&&Ot(b)?(()=>{try{return Rr(b,"utf-8")}catch{return null}})():null;f&&(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(f),n.push(""))}(s==="landing"||s==="design")&&(n.push(zs),n.push(""));let p=t.integrationId?dt(t.integrationId):void 0;if(p){let b=pt(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 f of b.envVars)n.push(`- \`${f.key}\`: ${f.description} \u2014 Get it at ${f.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:y,skill:x}=await ld(s);return n.push(y),n.push(""),x&&!(s==="landing"&&e.landingDesign==="freeform")&&(n.push(`### ${s} reference:`),n.push(x),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(`
5315
- `)}async function dd(t){let{projectPath:e,step:r}=t,o=Jc(e??process.cwd()),s=ed(o);if(!s)return Ee(o);if(!Ot(gt(o,"node_modules")))return c(`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:L}=await Promise.resolve().then(()=>(nr(),rr));await v(o);let G=await L(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 c("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(L=>L.number===a.number);v!==-1&&(i.steps[v].status="completed",n=`Auto-completed step ${a.number} (${a.name})`,ni(o,s))}let l;if(r!==void 0){if(l=i.steps.find(v=>v.number===r),!l)return c(`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 c(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 d=i.steps.filter(v=>v.status==="completed").map(v=>`Step ${v.number}: ${v.name}`),{readLocalState:h}=await Promise.resolve().then(()=>(Xe(),_t)),m=h(o),p=sd(l),y=[];if((p==="crud"||p==="schema")&&i.dataModel&&l.entities&&l.entities.length>0){let v=ii(l,i.dataModel);for(let L of v){let G=mo(L);try{let V=(L.fields||[]).map(j=>typeof j=="string"?{name:j,type:"text"}:{name:j.name,type:od(j.type),required:j.required!==!1});if(V.length===0)continue;let ee=s.dbProvider==="neon"?"nextjs-neon":"nextjs",R=await Qo(ee,G,V),N=0,ae=0;for(let j of R.files){let te=gt(o,j.path);if(Ot(te)){ae++;continue}Kc(Yc(te),{recursive:!0}),_r(te,j.content),N++}let me=gt(o,"db","index.ts");if(Ot(me)){let j=Rr(me,"utf-8");j.includes(R.dbExport)||_r(me,j.trimEnd()+`
5316
- `+R.dbExport+`
5317
- `)}N>0?y.push(`${R.entityPascal} CRUD (${N} new files${ae>0?`, ${ae} existing skipped`:""})`):ae>0&&y.push(`${R.entityPascal} CRUD (all ${ae} files already exist \u2014 skipped)`)}catch(V){console.error(`Module generation failed for ${G} (non-fatal):`,V instanceof Error?V.message:V)}}}let x=await cd(l,i,d,null,p,o),b=i.steps.findIndex(v=>v.number===l.number);if(b!==-1&&(s.plan.steps[b].status="in_progress",ni(o,s)),m&&s.projectId){let{syncRemoteState:v}=await Promise.resolve().then(()=>(Xe(),_t));v(s.projectId,m).catch(()=>{})}let f=i.steps.every(v=>v.status==="completed"||v.number===l.number),T;f?T=`THIS IS THE LAST STEP. Rules for speed:
5314
+ - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function dd(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(ld(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 v=y.replace(i,"").replace(/^\//,"");n.push(`- \`${v}\``)}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=fo(b),v=od(b.fields);n.push(`- **${y}**: ${v}`),n.push(` Schema file: \`db/schema/${y.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),n.push(""));let m=t.pages?nd(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=fo(b),v=y.toLowerCase().replace(/\s+/g,"-"),A=v.endsWith("s")?v:`${v}s`;n.push(`### Files for ${y} CRUD:`),n.push(`- List page: \`app/(dashboard)/${A}/page.tsx\` (Server Component)`),n.push(`- Detail page: \`app/(dashboard)/${A}/[id]/page.tsx\``),n.push(`- Create page: \`app/(dashboard)/${A}/new/page.tsx\``),n.push(`- Server Actions: \`app/(dashboard)/${A}/actions.ts\``),n.push(`- DataTable columns: \`components/${v}-table-columns.tsx\``),n.push(`- Form: \`components/${v}-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?bt(i,"DESIGN.md"):void 0,y=b&&Lt(b)?(()=>{try{return Nr(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?ut(e.integrationId):void 0;if(p){let b=mt(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:x}=await cd(s);return n.push(f),n.push(""),x&&!(s==="landing"&&t.landingDesign==="freeform")&&(n.push(`### ${s} reference:`),n.push(x),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(`
5315
+ `)}async function pd(e){let{projectPath:t,step:r}=e,o=Yc(t??process.cwd()),s=td(o);if(!s)return Ne(o);if(!Lt(bt(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:k,ensureShadcnComponents:L}=await Promise.resolve().then(()=>(ar(),ir));await k(o);let G=await L(o);G.failed?console.error(`[implement] ${G.failed}`):G.installed.length>0&&console.error(`[implement] installed ${G.installed.length} shadcn components`)}catch(k){console.error("[implement] self-heal skipped:",k instanceof Error?k.message:String(k))}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(k=>k.status==="in_progress");if(a){let k=i.steps.findIndex(L=>L.number===a.number);k!==-1&&(i.steps[k].status="completed",n=`Auto-completed step ${a.number} (${a.name})`,si(o,s))}let l;if(r!==void 0){if(l=i.steps.find(k=>k.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(k=>k.status!=="completed"),!l)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:i.steps.map(k=>k.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(k=>k.status==="completed").map(k=>`Step ${k.number}: ${k.name}`),{readLocalState:h}=await Promise.resolve().then(()=>(Ze(),Et)),m=h(o),p=id(l),f=[];if((p==="crud"||p==="schema")&&i.dataModel&&l.entities&&l.entities.length>0){let k=ai(l,i.dataModel);for(let L of k){let G=fo(L);try{let V=(L.fields||[]).map(j=>typeof j=="string"?{name:j,type:"text"}:{name:j.name,type:rd(j.type),required:j.required!==!1});if(V.length===0)continue;let ee=s.dbProvider==="neon"?"nextjs-neon":"nextjs",E=await er(ee,G,V),N=0,ae=0;for(let j of E.files){let te=bt(o,j.path);if(Lt(te)){ae++;continue}Jc(Qc(te),{recursive:!0}),Er(te,j.content),N++}let me=bt(o,"db","index.ts");if(Lt(me)){let j=Nr(me,"utf-8");j.includes(E.dbExport)||Er(me,j.trimEnd()+`
5316
+ `+E.dbExport+`
5317
+ `)}N>0?f.push(`${E.entityPascal} CRUD (${N} new files${ae>0?`, ${ae} existing skipped`:""})`):ae>0&&f.push(`${E.entityPascal} CRUD (all ${ae} files already exist \u2014 skipped)`)}catch(V){console.error(`Module generation failed for ${G} (non-fatal):`,V instanceof Error?V.message:V)}}}let x=await dd(l,i,c,null,p,o),b=i.steps.findIndex(k=>k.number===l.number);if(b!==-1&&(s.plan.steps[b].status="in_progress",si(o,s)),m&&s.projectId){let{syncRemoteState:k}=await Promise.resolve().then(()=>(Ze(),Et));k(s.projectId,m).catch(()=>{})}let y=i.steps.every(k=>k.status==="completed"||k.number===l.number),v;y?v=`THIS IS THE LAST STEP. Rules for speed:
5318
5318
 
5319
5319
  1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
5320
5320
  2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
@@ -5323,18 +5323,18 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
5323
5323
  - app/page.tsx must be a real landing page, NOT a redirect to /login
5324
5324
  - middleware.ts must have "/" in PUBLIC_EXACT or PUBLIC_PREFIXES
5325
5325
  - Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
5326
- 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.`:T=`IMPLEMENT THIS STEP NOW. Rules for speed:
5326
+ 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.`:v=`IMPLEMENT THIS STEP NOW. Rules for speed:
5327
5327
 
5328
5328
  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.
5329
5329
  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.
5330
5330
  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.
5331
5331
  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).
5332
- 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 _=id(p),E={stepNumber:l.number,totalSteps:i.steps.length,estimatedMinutes:_,announcement:`Starting step ${l.number} of ${i.steps.length}: ${l.name}. This step usually takes ${_.min}\u2013${_.max} minutes.`},O=JSON.stringify({instruction:x,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:E,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}:{},...y.length>0?{generatedModules:y,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:`${d.length}/${i.steps.length} steps done`,nextAction:T});return await Xc(3e3)?Xr("http://localhost:3000",O):c(O)}var Zc,nd,ai,li=P(()=>{"use strict";Q();ge();Zt();ur();ys();qs();Bs();Hs();Gs();Ks();Ys();Xs();ei();oi();Zc=Ar.object({projectPath:Ar.string().optional().describe("Path to the project directory (default: cwd)"),step:Ar.number().optional().describe("Specific step number to implement (default: next incomplete step)")});nd=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);ai={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:Zc,handler:dd}});import{z as He}from"zod";import{resolve as pd}from"path";async function ci(t){let{projectPath:e,action:r,key:o,value:s,category:i,description:n,setupUrl:a}=t,l=pd(e??process.cwd());if(!oe())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let h=$e(l)?.projectId;if(!h)return c("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 zo(h,o,s,{category:i,description:n,setupUrl:a}),c(JSON.stringify({set:!0,key:o,message:`Environment variable '${o}' has been set. It will be available on your next deployment.`}))):c("Value is required. Provide the env var value.",!0):c("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let m=await Bo(h);return m.length===0?c(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):c(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 Ho(h,o),c(JSON.stringify({deleted:!0,key:o,message:`Environment variable '${o}' has been removed.`}))):c("Key is required. Provide the env var name to delete.",!0);default:return c(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(m){if(m instanceof $)return c(m.message,!0);let p=m instanceof Error?m.message:"An unexpected error occurred";return c(p,!0)}}var Ph,di=P(()=>{"use strict";Q();ge();nt();Ph=He.object({projectPath:He.string().optional().describe("Path to the project directory (default: cwd)"),action:He.enum(["set","list","delete"]).describe("Action to perform"),key:He.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:He.string().optional().describe("Environment variable value (required for 'set')"),category:He.string().optional().describe("Category for the env var (default: 'custom')"),description:He.string().optional().describe("Description of what this env var is for"),setupUrl:He.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as Mt}from"zod";import{resolve as ud,join as md}from"path";import{existsSync as hd,readFileSync as gd,writeFileSync as fd}from"fs";function Er(t,e){let r=md(t,"mistflow.json");if(!hd(r))return;let o;try{o=JSON.parse(gd(r,"utf-8"))}catch{return}o.domains=e,fd(r,JSON.stringify(o,null,2)+`
5333
- `)}async function pi(t){let{projectPath:e,action:r,domain:o,domainId:s}=t,i=ud(e??process.cwd());if(!oe())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=$e(i)?.projectId;if(!a)return c("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 c("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Uo(a,o),d=await Fe(a);return Er(i,d.map(h=>({domain:h.domain,status:h.status}))),c(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 Fe(a);return l.length===0?c(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):c(JSON.stringify({domains:l.map(d=>({id:d.id,domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message}))}))}case"verify":{if(!s){if(o){let m=(await Fe(a)).find(p=>p.domain===o);if(m){let p=await Jt(a,m.id);return c(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 c(`Domain '${o}' not found. Use action 'list' to see configured domains.`,!0)}return c("Provide either domainId or domain name to verify.",!0)}let l=await Jt(a,s),d=await Fe(a);return Er(i,d.map(h=>({domain:h.domain,status:h.status}))),c(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 c("Provide either domainId or domain name to remove.",!0);let l=s;if(!l&&o){let m=(await Fe(a)).find(p=>p.domain===o);if(!m)return c(`Domain '${o}' not found.`,!0);l=m.id}await $o(a,l);let d=await Fe(a);return Er(i,d.map(h=>({domain:h.domain,status:h.status}))),c(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return c(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof $)return c(l.message,!0);let d=l instanceof Error?l.message:"An unexpected error occurred";return c(d,!0)}}var Dh,ui=P(()=>{"use strict";Q();ge();nt();Dh=Mt.object({projectPath:Mt.string().optional().describe("Path to the project directory (default: cwd)"),action:Mt.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:Mt.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:Mt.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as Pe}from"zod";var yd,mi,hi=P(()=>{"use strict";Q();di();ui();yd=Pe.object({resource:Pe.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Pe.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Pe.string().optional().describe("Path to the project directory (default: cwd)"),key:Pe.string().optional().describe("(env) Variable name"),value:Pe.string().optional().describe("(env set) Variable value"),category:Pe.string().optional().describe("(env set) Category"),description:Pe.string().optional().describe("(env set) Description"),setupUrl:Pe.string().optional().describe("(env set) URL to obtain the value"),domain:Pe.string().optional().describe("(domain) Domain name"),domainId:Pe.string().optional().describe("(domain) Domain ID")}),mi={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:yd,handler:async t=>{let e=t;switch(e.resource){case"env":return ci({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return pi({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return c(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}}});import{spawn as bd,execFileSync as wd}from"child_process";import{existsSync as ho,mkdirSync as yi,openSync as Nr,closeSync as Dr,readSync as vd,readFileSync as bi,writeFileSync as wi,renameSync as vi,unlinkSync as kd,readdirSync as Bh,statSync as xd}from"fs";import{homedir as ki}from"os";import{join as be,dirname as xi}from"path";import{randomBytes as Si,randomUUID as Sd}from"crypto";function go(){return be(ki(),".mistflow","jobs")}function Pd(){return be(ki(),".mistflow","job-wrapper.cjs")}function Id(){let t=Pd(),e=xi(t);ho(e)||yi(e,{recursive:!0});let r=`v${Ti}`;if(ho(t))try{if(bi(t,"utf-8").includes(r))return t}catch{}let o=be(e,`.job-wrapper.tmp.${Si(6).toString("hex")}`);return wi(o,Td),vi(o,t),t}function ft(t){return be(go(),t)}function Pi(t){return be(ft(t),"status.json")}function gi(t,e){let r=Pi(t),o=be(xi(r),`.status.tmp.${Si(6).toString("hex")}`);try{wi(o,JSON.stringify(e,null,2)+`
5334
- `),vi(o,r)}catch(s){try{kd(o)}catch{}throw s}}function Cd(t){let e=Pi(t);if(!ho(e))return null;try{return JSON.parse(bi(e,"utf-8"))}catch{return null}}async function fo(t){let e=`job_${Sd().replace(/-/g,"").slice(0,12)}`,r=ft(e);yi(r,{recursive:!0}),Dr(Nr(be(r,"stdout.log"),"a")),Dr(Nr(be(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};gi(e,s);let i=Id(),n={...process.env,...t.env??{}},a=bd("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 gi(e,l),l}function Ad(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function _d(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=wd("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),o=Ad(r),s=Date.parse(t.startedAt);if(Number.isFinite(o)&&Number.isFinite(s)&&Math.abs(o-s)>2e3)return!1}catch{}return!0}function Rd(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 fi(t,e){if(!ho(t))return"";let r=xd(t);if(r.size===0)return"";let o=r.size>e?r.size-e:0,s=r.size-o,i=Nr(t,"r");try{let n=Buffer.alloc(s);return vd(i,n,0,s,o),n.toString("utf-8")}finally{Dr(i)}}function Ed(t,e=200){let r=fi(be(ft(t),"stdout.log"),65536),o=fi(be(ft(t),"stderr.log"),64*1024),s=[];return r.trim()&&s.push(...r.split(`
5335
- `).slice(-e).map(i=>`[out] ${i}`)),o.trim()&&s.push(...o.split(`
5336
- `).slice(-e).map(i=>`[err] ${i}`)),s.filter(i=>i.trim().length>0).join(`
5337
- `)}function Lt(t){return{stdout:be(ft(t),"stdout.log"),stderr:be(ft(t),"stderr.log")}}async function yo(t){let e=Cd(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!_d(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:Rd(r.startedAt,r.endedAt),logTail:Ed(t)}}var Ti,Td,jr=P(()=>{"use strict";Ti=1,Td=`// Generated by @mistflow-ai/mcp local-jobs (v${Ti}). Do not edit.
5332
+ 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 A=ad(p),R={stepNumber:l.number,totalSteps:i.steps.length,estimatedMinutes:A,announcement:`Starting step ${l.number} of ${i.steps.length}: ${l.name}. This step usually takes ${A.min}\u2013${A.max} minutes.`},O=JSON.stringify({instruction:x,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:v});return await Zc(3e3)?Zr("http://localhost:3000",O):d(O)}var ed,sd,li,ci=P(()=>{"use strict";Q();ge();ro();gr();bs();Bs();zs();Ws();Vs();Js();Qs();Zs();ti();ri();ed=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)")});sd=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:ed,handler:pd}});import{z as We}from"zod";import{resolve as ud}from"path";async function di(e){let{projectPath:t,action:r,key:o,value:s,category:i,description:n,setupUrl:a}=e,l=ud(t??process.cwd());if(!oe())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let h=Fe(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 Go(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 Wo(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 Vo(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 Ah,pi=P(()=>{"use strict";Q();ge();it();Ah=We.object({projectPath:We.string().optional().describe("Path to the project directory (default: cwd)"),action:We.enum(["set","list","delete"]).describe("Action to perform"),key:We.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:We.string().optional().describe("Environment variable value (required for 'set')"),category:We.string().optional().describe("Category for the env var (default: 'custom')"),description:We.string().optional().describe("Description of what this env var is for"),setupUrl:We.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as Ut}from"zod";import{resolve as md,join as hd}from"path";import{existsSync as gd,readFileSync as fd,writeFileSync as yd}from"fs";function Dr(e,t){let r=hd(e,"mistflow.json");if(!gd(r))return;let o;try{o=JSON.parse(fd(r,"utf-8"))}catch{return}o.domains=t,yd(r,JSON.stringify(o,null,2)+`
5333
+ `)}async function ui(e){let{projectPath:t,action:r,domain:o,domainId:s}=e,i=md(t??process.cwd());if(!oe())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=Fe(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 qo(a,o),c=await qe(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 qe(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 qe(a)).find(p=>p.domain===o);if(m){let p=await Zt(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 Zt(a,s),c=await qe(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 qe(a)).find(p=>p.domain===o);if(!m)return d(`Domain '${o}' not found.`,!0);l=m.id}await Bo(a,l);let c=await qe(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 Mh,mi=P(()=>{"use strict";Q();ge();it();Mh=Ut.object({projectPath:Ut.string().optional().describe("Path to the project directory (default: cwd)"),action:Ut.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:Ut.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:Ut.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as Pe}from"zod";var bd,hi,gi=P(()=>{"use strict";Q();pi();mi();bd=Pe.object({resource:Pe.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Pe.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Pe.string().optional().describe("Path to the project directory (default: cwd)"),key:Pe.string().optional().describe("(env) Variable name"),value:Pe.string().optional().describe("(env set) Variable value"),category:Pe.string().optional().describe("(env set) Category"),description:Pe.string().optional().describe("(env set) Description"),setupUrl:Pe.string().optional().describe("(env set) URL to obtain the value"),domain:Pe.string().optional().describe("(domain) Domain name"),domainId:Pe.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:bd,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 wd,execFileSync as vd}from"child_process";import{existsSync as yo,mkdirSync as bi,openSync as jr,closeSync as Or,readSync as xd,readFileSync as wi,writeFileSync as vi,renameSync as xi,unlinkSync as kd,readdirSync as Wh,statSync as Sd}from"fs";import{homedir as ki}from"os";import{join as be,dirname as Si}from"path";import{randomBytes as Ti,randomUUID as Td}from"crypto";function bo(){return be(ki(),".mistflow","jobs")}function Id(){return be(ki(),".mistflow","job-wrapper.cjs")}function Cd(){let e=Id(),t=Si(e);yo(t)||bi(t,{recursive:!0});let r=`v${Pi}`;if(yo(e))try{if(wi(e,"utf-8").includes(r))return e}catch{}let o=be(t,`.job-wrapper.tmp.${Ti(6).toString("hex")}`);return vi(o,Pd),xi(o,e),e}function wt(e){return be(bo(),e)}function Ii(e){return be(wt(e),"status.json")}function fi(e,t){let r=Ii(e),o=be(Si(r),`.status.tmp.${Ti(6).toString("hex")}`);try{vi(o,JSON.stringify(t,null,2)+`
5334
+ `),xi(o,r)}catch(s){try{kd(o)}catch{}throw s}}function Ad(e){let t=Ii(e);if(!yo(t))return null;try{return JSON.parse(wi(t,"utf-8"))}catch{return null}}async function wo(e){let t=`job_${Td().replace(/-/g,"").slice(0,12)}`,r=wt(t);bi(r,{recursive:!0}),Or(jr(be(r,"stdout.log"),"a")),Or(jr(be(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=Cd(),n={...process.env,...e.env??{}},a=wd("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 _d(e){let t=e.trim();if(!t)return NaN;let r=Date.parse(t);return Number.isFinite(r)?r:NaN}function Rd(e){let t=e.pid||e.wrapperPid;if(!t)return!1;try{process.kill(t,0)}catch{return!1}try{let r=vd("ps",["-o","lstart=","-p",String(t)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),o=_d(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(!yo(e))return"";let r=Sd(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 xd(i,n,0,s,o),n.toString("utf-8")}finally{Or(i)}}function Nd(e,t=200){let r=yi(be(wt(e),"stdout.log"),65536),o=yi(be(wt(e),"stderr.log"),64*1024),s=[];return r.trim()&&s.push(...r.split(`
5335
+ `).slice(-t).map(i=>`[out] ${i}`)),o.trim()&&s.push(...o.split(`
5336
+ `).slice(-t).map(i=>`[err] ${i}`)),s.filter(i=>i.trim().length>0).join(`
5337
+ `)}function $t(e){return{stdout:be(wt(e),"stdout.log"),stderr:be(wt(e),"stderr.log")}}async function Ft(e){let t=Ad(e);if(!t)return null;let r=t;return(t.status==="running"||t.status==="starting")&&!Rd(t)&&(r={...t,status:"unknown_exit",endedAt:t.endedAt??new Date().toISOString()}),{...r,elapsed:Ed(r.startedAt,r.endedAt),logTail:Nd(e)}}async function vo(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 Ft(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,Pd,Mr=P(()=>{"use strict";Pi=1,Pd=`// Generated by @mistflow-ai/mcp local-jobs (v${Pi}). Do not edit.
5338
5338
  const { spawn } = require('node:child_process');
5339
5339
  const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
5340
5340
  const { join, dirname } = require('node:path');
@@ -5398,21 +5398,25 @@ child.on('error', (err) => {
5398
5398
  });
5399
5399
  process.exit(1);
5400
5400
  });
5401
- `});import{z as Or}from"zod";import{resolve as Nd}from"path";import{existsSync as Dd}from"fs";import{join as jd}from"path";var Od,Ii,Ci=P(()=>{"use strict";Q();jr();Od=Or.object({projectPath:Or.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:Or.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start.")}).refine(t=>!!t.projectPath||!!t.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:Od,handler:async t=>{let e=t;if(e.jobId){let a=await yo(e.jobId);if(!a)return c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No install job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0);if(a.status==="running"||a.status==="starting")return c(JSON.stringify({status:"running",jobId:a.id,elapsed:a.elapsed,logTail:a.logTail,nextAction:"Still running. Call mist_install with the same jobId in ~15-30s to check progress."}));if(a.status==="complete")return c(JSON.stringify({status:"complete",jobId:a.id,elapsed:a.elapsed,exitCode:a.exitCode,nextAction:"Dependencies installed. Run mist_implement next to start executing plan steps."}));let l=Lt(a.id);return c(JSON.stringify({status:a.status,jobId:a.id,elapsed:a.elapsed,exitCode:a.exitCode,logTail:a.logTail,logPaths:l,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 (${l.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let r=Nd(e.projectPath);if(!Dd(jd(r,"package.json")))return c(`No package.json at ${r}. Confirm the path and that mist_init has scaffolded the project.`,!0);let i=`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')`,n=await fo({type:"install",cmd:"sh",args:["-c",i],cwd:r,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return c(JSON.stringify({status:"running",jobId:n.id,startedAt:n.startedAt,cwd:r,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+n.id+"' } in ~15-30s to check progress. Typical duration: 30-90s."}))}}});import{z as bo}from"zod";import{resolve as Md,join as Ne}from"path";import{existsSync as De,readFileSync as Ai,statSync as Ld}from"fs";function Ud(t){if(!(De(Ne(t,"open-next.config.ts"))||De(Ne(t,"open-next.config.js"))))return null;let r=Ne(t,".open-next","worker.js");if(!De(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker bundle. 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.`;try{let o=Ld(r).size;if(o<_i)return`Build exited 0 but .open-next/worker.js is only ${o} bytes (expected at least ${_i}). The worker bundle is too small to be a working app \u2014 the adapter likely failed to bundle most of the code. Check open-next.config.ts and the logTail above for errors, fix them, and re-run mist_build.`}catch(o){return`Could not stat .open-next/worker.js: ${o instanceof Error?o.message:String(o)}. Re-run mist_build.`}return null}function Fd(t){let e=Ne(go(),t,"stdout.log"),r=Ne(go(),t,"stderr.log"),o="";try{De(e)&&(o+=Ai(e,"utf-8"))}catch{}try{De(r)&&(o+=`
5402
- `+Ai(r,"utf-8"))}catch{}return o}function qd(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 _i,$d,Ri,Ei=P(()=>{"use strict";Q();jr();mr();_i=10*1024;$d=bo.object({projectPath:bo.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:bo.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:bo.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.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});Ri={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:$d,handler:async t=>{let e=t;if(e.jobId){let l=await yo(e.jobId);if(!l)return c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No build job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0);if(l.status==="running"||l.status==="starting")return c(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:l.logTail,nextAction:"Build still running. Call mist_build again with the same jobId in ~20-40s."}));if(l.status==="complete"){let b=Ud(l.cwd);if(b){let f=Lt(l.id);return c(JSON.stringify({status:"failed",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:f,error:b,nextAction:b+` Full build log: ${f.stdout} and ${f.stderr}.`}),!0)}return c(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.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 d=Fd(l.id),h=so(d),m=qd(d),p=Lt(l.id),y=` Full log: ${p.stdout} and ${p.stderr}.`,x=m.length>0?`Build failed with missing modules: ${m.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.${y}`:h.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${y}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${y}`;return c(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,errors:h,missingModules:m,logTail:l.logTail,logPaths:p,nextAction:x}),!0)}let r=Md(e.projectPath);if(!De(Ne(r,"package.json")))return c(`No package.json at ${r}. Run mist_init first.`,!0);if(!De(Ne(r,"node_modules")))return c(`node_modules not installed. Run mist_install { projectPath: '${r}' } first.`,!0);let o,s,i,n=De(Ne(r,"open-next.config.ts"))||De(Ne(r,"open-next.config.js"));e.script?(o="npm",s=["run",e.script],i=e.script):n?(o="npx",s=["-y","@opennextjs/cloudflare","build"],i="@opennextjs/cloudflare build"):(o="npm",s=["run","build"],i="build");let a=await fo({type:"build",cmd:o,args:s,cwd:r});return c(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:r,script:i,nextAction:`Build started. Call mist_build again with { jobId: '${a.id}' } in ~30s to check progress. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}}});import{existsSync as Bd,readFileSync as zd}from"fs";import{join as Hd}from"path";import{z as wo}from"zod";function Gd(t){let e=Hd(t,"mistflow.json");if(!Bd(e))return null;try{return JSON.parse(zd(e,"utf-8"))}catch{return null}}async function Ni(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 Vd(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 Di(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function yt(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 Di(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 Di(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 Kd(t){let e=t.projectPath??process.cwd(),r=Gd(e),o=t.url;if(o||(o=r?.deploy?.url),!o)return c("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 Ni(`${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."}),vo(o,i);i.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Ni(`${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."}),vo(o,i);i.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,d,h;if(s){let y=await Fo(s);if(y){console.error("[qa] Calling seed endpoint for session token");let x=await Vd(`${o}/api/admin/seed`,{token:y.seedToken,email:y.email,password:"QaTemp1!"});x.status===200&&x.json?(l=x.json.sessionToken,d=x.json.email,x.json.seeded?(h=x.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 ${x.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."}),vo(o,i);let m,p;try{let{getIsolatedContext:y}=await Promise.resolve().then(()=>(zt(),Ro)),x=await y();m=x.context,p=x.page}catch(y){let x=y instanceof Error?y.message:String(y);return c(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:x,httpChecks:i.map(({screenshot:b,...f})=>f),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(`
5403
- `)}),!1)}try{let y=await yt(p,"Landing page",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:3e4}),await p.waitForLoadState("networkidle").catch(()=>{});let b=await p.evaluate(()=>{let T=document.body;if(!T)return"";let _=document.createTreeWalker(T,NodeFilter.SHOW_TEXT),E="",I;for(;I=_.nextNode();){let O=I.parentElement;if(O){let U=window.getComputedStyle(O);U.display!=="none"&&U.visibility!=="hidden"&&parseFloat(U.opacity)>0&&(E+=I.textContent?.trim()+" ")}}return E.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 f=p.url();return f.includes("/login")||f.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(y);let x=!1;if(h){let b=await yt(p,"Login",async()=>{await p.goto(`${o}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let f=p.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),T=p.locator('input[type="password"], input[name="password"]');try{await f.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 f.first().fill(d),await T.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(E=>!E.pathname.includes("/login"),{timeout:1e4})}catch{let E=await p.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:E?`Login failed: ${E}`:"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 x=!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(!x&&l){let b=new URL(o).hostname,f=o.startsWith("https");await m.addCookies([{name:f?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:b,path:"/",httpOnly:!0,secure:f,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let b=await yt(p,"Dashboard",async()=>{p.url().includes("/dashboard")||(await p.goto(`${o}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let E=await p.content();return E.length<1e3?{pass:!1,detail:`Dashboard page is very small (${E.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 (${E.length} bytes)`}});i.push(b);let f=await p.evaluate(()=>{let _=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(I=>{let O=I.getAttribute("href");O&&O.startsWith("/")&&!O.startsWith("/api")&&!O.includes("[")&&O!=="/dashboard"&&O!=="/"&&!O.includes("/login")&&!O.includes("/sign")&&_.push(O)}),[...new Set(_)]});if(f.length>0){let _=0,E=[];for(let I of f.slice(0,8)){let O=await yt(p,`Page: ${I}`,async()=>{await p.goto(`${o}${I}`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let U=await p.title(),v=await p.content();return U.toLowerCase().includes("500")||U.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."}:U.toLowerCase().includes("404")||U.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${I} 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"}});O.status==="fail"&&(_++,E.push(I)),i.push(O)}}let T=await yt(p,"Design quality",async()=>{let _=p.url().includes("/dashboard")?p.url():`${o}/dashboard`;p.url().includes("/dashboard")||(await p.goto(_,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let E=await p.evaluate(()=>{let I=[],O=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),U=new Set;O.forEach(D=>{U.add(window.getComputedStyle(D).fontSize)}),O.length>=3&&U.size<2&&I.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(O).map(D=>parseInt(D.tagName.charAt(1),10));for(let D=1;D<v.length;D++)if(v[D]-v[D-1]>1){I.push(`TYPOGRAPHY: Heading level skipped (h${v[D-1]} -> h${v[D]}). Use sequential heading levels for accessibility.`);break}let L=document.querySelectorAll("*"),G=!1,V=!1;L.forEach(D=>{let W=window.getComputedStyle(D);W.backgroundColor==="rgb(0, 0, 0)"&&D.clientHeight>100&&D.clientWidth>200&&(G=!0);let we=W.backgroundColor,J=W.color;if(we&&!we.includes("0, 0, 0")&&!we.includes("255, 255, 255")&&we!=="rgba(0, 0, 0, 0)"&&we!=="transparent"&&J.match(/rgb\((\d+), (\d+), (\d+)\)/)){let Ie=J.match(/rgb\((\d+), (\d+), (\d+)\)/);if(Ie){let[Ve,Ke,Je]=[parseInt(Ie[1]),parseInt(Ie[2]),parseInt(Ie[3])],ye=Math.abs(Ve-Ke)<10&&Math.abs(Ke-Je)<10&&Ve>80&&Ve<180,je=we.match(/rgb\((\d+), (\d+), (\d+)\)/);if(ye&&je){let[Oe,Me,w]=[parseInt(je[1]),parseInt(je[2]),parseInt(je[3])];!(Math.abs(Oe-Me)<15&&Math.abs(Me-w)<15)&&D.textContent&&D.textContent.trim().length>0&&(V=!0)}}}}),G&&I.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&&I.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 ee=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),R=!1;ee.forEach(D=>{D.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(R=!0)}),R&&I.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let N=document.querySelectorAll("p, li, span, div"),ae=0,me=0;N.forEach(D=>{D.textContent&&D.textContent.trim().length>20&&D.clientHeight>0&&(me++,window.getComputedStyle(D).textAlign==="center"&&ae++)}),me>5&&ae/me>.7&&I.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let j=new Set;L.forEach(D=>{let W=window.getComputedStyle(D);W.gap&&W.gap!=="normal"&&W.gap!=="0px"&&j.add(W.gap)}),j.size===1&&L.length>20&&I.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let te=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(D=>{D.querySelectorAll("tbody tr").length===0&&(D.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||I.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 fe=document.querySelectorAll("style"),_e=!1;fe.forEach(D=>{let W=D.textContent||"";(W.includes("bounce")||W.includes("elastic")||W.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(_e=!0)}),_e&&I.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let Ge=document.querySelectorAll("button, a, input, select, [role='button']"),q=0;return Ge.forEach(D=>{let W=D.getBoundingClientRect();W.width>0&&W.height>0&&(W.width<32||W.height<32)&&q++}),q>3&&I.push(`ACCESSIBILITY: ${q} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),I});return E.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${E.length} design quality issue(s) found:
5404
- ${E.map((I,O)=>`${O+1}. ${I}`).join(`
5405
- `)}`,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(T),i.find(_=>_.name==="Landing page"&&_.status==="pass")){let _=await yt(p,"Landing design quality",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let E=await p.evaluate(()=>{let I=[];document.querySelectorAll("*").forEach(L=>{let G=window.getComputedStyle(L);(G.getPropertyValue("-webkit-background-clip")||G.getPropertyValue("background-clip"))==="text"&&L.textContent&&L.textContent.trim().length>0&&I.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let U=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(U){let L=(U.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(L.match(new RegExp(V))){I.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(L=>{let V=window.getComputedStyle(L).gridTemplateColumns;if(V){let ee=V.split(" ").filter(N=>N!=="").length,R=L.children;if(ee===3&&R.length===3){let N=Array.from(R).map(j=>j.offsetHeight),ae=N.every(j=>Math.abs(j-N[0])<5),me=Array.from(R).every(j=>{let te=j.querySelectorAll("svg"),Ae=j.querySelectorAll("h2, h3, h4"),fe=j.querySelectorAll("p");return te.length>=1&&Ae.length>=1&&fe.length>=1});ae&&me&&I.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),I});return E.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${E.length} landing design issue(s):
5406
- ${E.map((I,O)=>`${O+1}. ${I}`).join(`
5407
- `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(_)}}}finally{m&&await m.close().catch(()=>{})}if(t.deploymentId){let y=i.filter(f=>f.status==="fail"),x=i.filter(f=>f.status==="pass"),b=Date.now();await qo(t.deploymentId,{checks:i.map(({screenshot:f,...T})=>T),overall:y.length===0?"pass":"fail",passed:x.length,failed:y.length,duration_ms:Date.now()-b}).catch(()=>{})}return vo(o,i)}function vo(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}
5401
+ `});import{z as xo}from"zod";import{resolve as Dd}from"path";import{existsSync as jd}from"fs";import{join as Od}from"path";function Md(e,t=15){let r=e.split(`
5402
+ `).filter(o=>o.length>0);return r.length<=t?e:r.slice(-t).join(`
5403
+ `)}var Ld,Ci,Ai=P(()=>{"use strict";Q();Mr();ft();Ld=xo.object({projectPath:xo.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:xo.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:xo.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."}),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:Ld,handler:async(e,t)=>{let r=e;if(r.jobId){let l=await Ft(r.jobId);if(!l)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No install job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let c=r.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let m=l.elapsed,p=t?Ae(t.server,t.progressToken,()=>`Install running (${m}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let f=await vo(r.jobId,{timeoutMs:c*1e3,onPoll:x=>{m=x.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:Md(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=$t(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=Dd(r.projectPath);if(!jd(Od(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 wo({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 qt}from"zod";import{resolve as Ud,join as De}from"path";import{existsSync as je,readFileSync as _i,statSync as $d}from"fs";function Fd(e){if(!(je(De(e,"open-next.config.ts"))||je(De(e,"open-next.config.js"))))return null;let r=De(e,".open-next","worker.js");if(!je(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker bundle. 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.`;try{let o=$d(r).size;if(o<Ri)return`Build exited 0 but .open-next/worker.js is only ${o} bytes (expected at least ${Ri}). The worker bundle is too small to be a working app \u2014 the adapter likely failed to bundle most of the code. Check open-next.config.ts and the logTail above for errors, fix them, and re-run mist_build.`}catch(o){return`Could not stat .open-next/worker.js: ${o instanceof Error?o.message:String(o)}. Re-run mist_build.`}return null}function Bd(e){let t=De(bo(),e,"stdout.log"),r=De(bo(),e,"stderr.log"),o="";try{je(t)&&(o+=_i(t,"utf-8"))}catch{}try{je(r)&&(o+=`
5404
+ `+_i(r,"utf-8"))}catch{}return o}function zd(e,t=15){let r=e.split(`
5405
+ `).filter(o=>o.length>0);return r.length<=t?e:r.slice(-t).join(`
5406
+ `)}function Hd(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,qd,Ei,Ni=P(()=>{"use strict";Q();Mr();fr();ft();Ri=10*1024;qd=qt.object({projectPath:qt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:qt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:qt.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:qt.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."});Ei={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:qd,handler:async(e,t)=>{let r=e;if(r.jobId){let c=await Ft(r.jobId);if(!c)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let h=r.waitSeconds??20;if(h>0&&(c.status==="running"||c.status==="starting")){let v=c.elapsed,A=t?Ae(t.server,t.progressToken,()=>`Build running (${v}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let R=await vo(r.jobId,{timeoutMs:h*1e3,onPoll:I=>{v=I.elapsed}});R&&(c=R)}finally{A.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:zd(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 v=Fd(c.cwd);if(v){let A=$t(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:A,error:v,nextAction:v+` Full build log: ${A.stdout} and ${A.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=Bd(c.id),p=co(m),f=Hd(m),x=$t(c.id),b=` Full log: ${x.stdout} and ${x.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:x,nextAction:y}),!0)}let o=Ud(r.projectPath);if(!je(De(o,"package.json")))return d(`No package.json at ${o}. Run mist_init first.`,!0);if(!je(De(o,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${o}' } first.`,!0);let s,i,n,a=je(De(o,"open-next.config.ts"))||je(De(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 wo({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 Wd,readFileSync as Gd}from"fs";import{join as Vd}from"path";import{z as ko}from"zod";function Jd(e){let t=Vd(e,"mistflow.json");if(!Wd(t))return null;try{return JSON.parse(Gd(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 Yd(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 vt(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 Qd(e){let t=e.projectPath??process.cwd(),r=Jd(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."}),So(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."}),So(o,i);i.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,c,h;if(s){let f=await zo(s);if(f){console.error("[qa] Calling seed endpoint for session token");let x=await Yd(`${o}/api/admin/seed`,{token:f.seedToken,email:f.email,password:"QaTemp1!"});x.status===200&&x.json?(l=x.json.sessionToken,c=x.json.email,x.json.seeded?(h=x.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 ${x.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."}),So(o,i);let m,p;try{let{getIsolatedContext:f}=await Promise.resolve().then(()=>(Vt(),Do)),x=await f();m=x.context,p=x.page}catch(f){let x=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:x,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(`
5407
+ `)}),!1)}try{let f=await vt(p,"Landing page",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:3e4}),await p.waitForLoadState("networkidle").catch(()=>{});let b=await p.evaluate(()=>{let v=document.body;if(!v)return"";let A=document.createTreeWalker(v,NodeFilter.SHOW_TEXT),R="",I;for(;I=A.nextNode();){let O=I.parentElement;if(O){let U=window.getComputedStyle(O);U.display!=="none"&&U.visibility!=="hidden"&&parseFloat(U.opacity)>0&&(R+=I.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 x=!1;if(h){let b=await vt(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]'),v=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 v.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 x=!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(!x&&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 vt(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 A=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(I=>{let O=I.getAttribute("href");O&&O.startsWith("/")&&!O.startsWith("/api")&&!O.includes("[")&&O!=="/dashboard"&&O!=="/"&&!O.includes("/login")&&!O.includes("/sign")&&A.push(O)}),[...new Set(A)]});if(y.length>0){let A=0,R=[];for(let I of y.slice(0,8)){let O=await vt(p,`Page: ${I}`,async()=>{await p.goto(`${o}${I}`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let U=await p.title(),k=await p.content();return U.toLowerCase().includes("500")||U.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."}:U.toLowerCase().includes("404")||U.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${I} 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."}:k.length<500?{pass:!1,detail:`Page is very small (${k.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});O.status==="fail"&&(A++,R.push(I)),i.push(O)}}let v=await vt(p,"Design quality",async()=>{let A=p.url().includes("/dashboard")?p.url():`${o}/dashboard`;p.url().includes("/dashboard")||(await p.goto(A,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let R=await p.evaluate(()=>{let I=[],O=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),U=new Set;O.forEach(D=>{U.add(window.getComputedStyle(D).fontSize)}),O.length>=3&&U.size<2&&I.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 k=Array.from(O).map(D=>parseInt(D.tagName.charAt(1),10));for(let D=1;D<k.length;D++)if(k[D]-k[D-1]>1){I.push(`TYPOGRAPHY: Heading level skipped (h${k[D-1]} -> h${k[D]}). Use sequential heading levels for accessibility.`);break}let L=document.querySelectorAll("*"),G=!1,V=!1;L.forEach(D=>{let W=window.getComputedStyle(D);W.backgroundColor==="rgb(0, 0, 0)"&&D.clientHeight>100&&D.clientWidth>200&&(G=!0);let we=W.backgroundColor,J=W.color;if(we&&!we.includes("0, 0, 0")&&!we.includes("255, 255, 255")&&we!=="rgba(0, 0, 0, 0)"&&we!=="transparent"&&J.match(/rgb\((\d+), (\d+), (\d+)\)/)){let Ie=J.match(/rgb\((\d+), (\d+), (\d+)\)/);if(Ie){let[Ke,Je,Ye]=[parseInt(Ie[1]),parseInt(Ie[2]),parseInt(Ie[3])],ye=Math.abs(Ke-Je)<10&&Math.abs(Je-Ye)<10&&Ke>80&&Ke<180,Oe=we.match(/rgb\((\d+), (\d+), (\d+)\)/);if(ye&&Oe){let[Me,Le,w]=[parseInt(Oe[1]),parseInt(Oe[2]),parseInt(Oe[3])];!(Math.abs(Me-Le)<15&&Math.abs(Le-w)<15)&&D.textContent&&D.textContent.trim().length>0&&(V=!0)}}}}),G&&I.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&&I.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 ee=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),E=!1;ee.forEach(D=>{D.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(E=!0)}),E&&I.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let N=document.querySelectorAll("p, li, span, div"),ae=0,me=0;N.forEach(D=>{D.textContent&&D.textContent.trim().length>20&&D.clientHeight>0&&(me++,window.getComputedStyle(D).textAlign==="center"&&ae++)}),me>5&&ae/me>.7&&I.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let j=new Set;L.forEach(D=>{let W=window.getComputedStyle(D);W.gap&&W.gap!=="normal"&&W.gap!=="0px"&&j.add(W.gap)}),j.size===1&&L.length>20&&I.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let te=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(D=>{D.querySelectorAll("tbody tr").length===0&&(D.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||I.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 fe=document.querySelectorAll("style"),Re=!1;fe.forEach(D=>{let W=D.textContent||"";(W.includes("bounce")||W.includes("elastic")||W.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Re=!0)}),Re&&I.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let Ve=document.querySelectorAll("button, a, input, select, [role='button']"),q=0;return Ve.forEach(D=>{let W=D.getBoundingClientRect();W.width>0&&W.height>0&&(W.width<32||W.height<32)&&q++}),q>3&&I.push(`ACCESSIBILITY: ${q} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),I});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:
5408
+ ${R.map((I,O)=>`${O+1}. ${I}`).join(`
5409
+ `)}`,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(v),i.find(A=>A.name==="Landing page"&&A.status==="pass")){let A=await vt(p,"Landing design quality",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let R=await p.evaluate(()=>{let I=[];document.querySelectorAll("*").forEach(L=>{let G=window.getComputedStyle(L);(G.getPropertyValue("-webkit-background-clip")||G.getPropertyValue("background-clip"))==="text"&&L.textContent&&L.textContent.trim().length>0&&I.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let U=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(U){let L=(U.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(L.match(new RegExp(V))){I.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(L=>{let V=window.getComputedStyle(L).gridTemplateColumns;if(V){let ee=V.split(" ").filter(N=>N!=="").length,E=L.children;if(ee===3&&E.length===3){let N=Array.from(E).map(j=>j.offsetHeight),ae=N.every(j=>Math.abs(j-N[0])<5),me=Array.from(E).every(j=>{let te=j.querySelectorAll("svg"),_e=j.querySelectorAll("h2, h3, h4"),fe=j.querySelectorAll("p");return te.length>=1&&_e.length>=1&&fe.length>=1});ae&&me&&I.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),I});return 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):
5410
+ ${R.map((I,O)=>`${O+1}. ${I}`).join(`
5411
+ `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(A)}}}finally{m&&await m.close().catch(()=>{})}if(e.deploymentId){let f=i.filter(y=>y.status==="fail"),x=i.filter(y=>y.status==="pass"),b=Date.now();await Ho(e.deploymentId,{checks:i.map(({screenshot:y,...v})=>v),overall:f.length===0?"pass":"fail",passed:x.length,failed:f.length,duration_ms:Date.now()-b}).catch(()=>{})}return So(o,i)}function So(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}
5408
5412
  Fix: ${n.fix}`).join(`
5409
5413
 
5410
- `);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):
5414
+ `);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):
5411
5415
 
5412
5416
  ${i}
5413
5417
 
5414
- 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 Wd,ji,Oi=P(()=>{"use strict";Q();ge();Wd=wo.object({projectPath:wo.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:wo.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:wo.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.")}),ji={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:Wd,handler:async t=>Kd(t)}});import{existsSync as ko,readdirSync as Jd,statSync as Mi,unlinkSync as Li}from"fs";import{join as tt}from"path";import{execFile as Yd}from"child_process";function Qd(t,e){let r=0;for(let o of e){let s=tt(t,o);if(ko(s))try{let i=Mi(s);if(i.isFile())r++;else if(i.isDirectory()){let n=[s];for(;n.length;){let a=n.pop(),l=Jd(a,{withFileTypes:!0});for(let d of l){let h=tt(a,d.name);d.isDirectory()?n.push(h):r++}}}}catch{}}return r}function Ui(t,e,r){return new Promise(o=>{Yd("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 $i(t){let e=tt(t,".open-next-build.tar.gz"),r=[".open-next"];ko(tt(t,"db"))&&r.push("db"),ko(tt(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),ko(tt(t,"package.json"))&&r.push("package.json");let o=Qd(t,r),s=await Ui(["-czf",e,"-C",t,...r],t,12e4);if(!s.success){try{Li(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(s.stderr?`
5415
- ${s.stderr.slice(-500)}`:""))}let i=0;try{i=Mi(e).size}catch{}return{path:e,sizeBytes:i,fileCount:o}}async function Fi(t){let e=tt(t,".mistflow-source.tar.gz");return(await Ui(["-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 Mr(t){if(t)try{Li(t)}catch{}}function qi(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function Bi(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 zi=P(()=>{"use strict"});import{z as bt}from"zod";import{resolve as Xd,join as Zd}from"path";import{existsSync as ep}from"fs";function op(t){return ep(Zd(t,".open-next"))}function rp(t){return $e(t)?.deploy?.strategy==="staging"?"preview":null}async function np(t){let e=Xd(t.projectPath);if(!oe())return c("Not signed in. Call mist_setup first.",!0);let o=$e(e)?.projectId;if(!o)return c(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);if(!op(e))return c(`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??rp(e)??"production",i=null,n=null;try{i=await $i(e),n=await Fi(e);let a=await Mo(o,i.path,s,t.adminEmail,void 0,n??void 0,void 0);return c(JSON.stringify({status:"running",jobId:a.deployment_id,deploymentId:a.deployment_id,environment:a.environment??s,buildSize:qi(i.sizeBytes),buildFileCount:i.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${a.deployment_id}' } in ~5-10s to poll deployment progress. 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 c(`Deploy upload failed: ${l}`,!0)}finally{Mr(i?.path),Mr(n)}}async function sp(t){try{let e=await It(t),r=Bi(e.status);return e.status==="live"?c(JSON.stringify({status:"complete",jobId:e.id,deploymentId:e.id,url:e.url,completedAt:e.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${e.url??""}', deploymentId: '${e.id??""}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`})):e.status==="failed"?c(JSON.stringify({status:"failed",jobId:e.id,deploymentId:e.id,error:e.error,phase:r,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):c(JSON.stringify({status:"running",jobId:e.id,deploymentId:e.id,phase:r,phaseCode:e.status,nextAction:`Still ${e.status}. Call mist_deploy { action: 'status', deploymentId: '${e.id}' } again in ~5-10s.`}))}catch(e){let r=e instanceof $||e instanceof Error?e.message:String(e);return c(`Could not fetch deploy status: ${r}`,!0)}}async function ip(t,e){if(!oe())return c("Not signed in. Call mist_setup first.",!0);let o=$e(t)?.projectId;if(!o)return c(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let s=e;if(!s)try{let n=(await at(o)).find(a=>a.environment==="preview"&&a.status==="live");if(!n)return c("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 c(`Could not list deployments: ${n}`,!0)}try{let i=await Vo(o,s);return c(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}' } to poll. Promotion re-uses the preview artifact so it typically completes in ~10s.`}))}catch(i){let n=i instanceof $||i instanceof Error?i.message:String(i);return c(`Promote failed: ${n}`,!0)}}async function ap(t){if(!oe())return c("Not signed in. Call mist_setup first.",!0);try{let e=await Ko(t);return c(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}' } to poll.`}))}catch(e){let r=e instanceof $||e instanceof Error?e.message:String(e);return c(`Rollback failed: ${r}`,!0)}}var tp,Hi,Wi=P(()=>{"use strict";Q();ge();nt();zi();tp=bt.object({action:bt.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:bt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:bt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:bt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:bt.string().optional().describe("Admin email injected as BETTER_AUTH_ADMIN_EMAIL on first deploy of an auth-enabled project.")});Hi={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:tp,handler:async t=>{let e=t;switch(e.action??"deploy"){case"deploy":return e.projectPath?np({projectPath:e.projectPath,environment:e.environment,adminEmail:e.adminEmail}):c("projectPath is required for action='deploy'.",!0);case"status":return e.deploymentId?sp(e.deploymentId):c("deploymentId is required for action='status'.",!0);case"promote":return e.projectPath?ip(e.projectPath,e.deploymentId):c("projectPath is required for action='promote'.",!0);case"rollback":return e.deploymentId?ap(e.deploymentId):c("deploymentId is required for action='rollback'.",!0)}}}});var hp={};import{Server as lp}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as cp}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as dp,ListToolsRequestSchema as pp}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as up}from"zod-to-json-schema";async function mp(){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 cp;await xo.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var xo,Gi,Vi=P(()=>{"use strict";Le();Q();mn();En();Dn();Ln();ur();Vn();as();fs();li();hi();Ci();Ei();Oi();Wi();xo=new lp({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:zr()}),Gi=[un,Rn,Nn,Mn,is,gs,Hn,ai,Gn,mi,Ii,Ri,ji,Hi];xo.setRequestHandler(pp,async()=>({tools:Gi.map(t=>({name:t.name,description:t.description,inputSchema:up(t.inputSchema)}))}));xo.setRequestHandler(dp,async t=>{let e=Gi.find(r=>r.name===t.params.name);if(!e)return c(`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 c(`Invalid input: ${i}`,!0)}let o=t.params._meta?.progressToken,s={server:xo,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),c(o,!0)}});mp().catch(t=>{console.error("Fatal error:",t),process.exit(1)})});import{readFileSync as gp}from"fs";import{dirname as fp,join as yp}from"path";import{fileURLToPath as bp}from"url";var We=process.argv[2];if(We==="--version"||We==="-v"){try{let t=fp(bp(import.meta.url)),e=yp(t,"..","package.json"),r=JSON.parse(gp(e,"utf-8"));console.log(r.version)}catch{console.log("unknown")}process.exit(0)}(We==="--help"||We==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
5418
+ 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 Kd,Oi,Mi=P(()=>{"use strict";Q();ge();Kd=ko.object({projectPath:ko.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:ko.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:ko.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:Kd,handler:async e=>Qd(e)}});import{existsSync as To,readdirSync as Xd,statSync as Li,unlinkSync as Ui}from"fs";import{join as ot}from"path";import{execFile as Zd}from"child_process";function ep(e,t){let r=0;for(let o of t){let s=ot(e,o);if(To(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=Xd(a,{withFileTypes:!0});for(let c of l){let h=ot(a,c.name);c.isDirectory()?n.push(h):r++}}}}catch{}}return r}function $i(e,t,r){return new Promise(o=>{Zd("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=ot(e,".open-next-build.tar.gz"),r=[".open-next"];To(ot(e,"db"))&&r.push("db"),To(ot(e,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),To(ot(e,"package.json"))&&r.push("package.json");let o=ep(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?`
5419
+ ${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=ot(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=P(()=>{"use strict"});import{z as rt}from"zod";import{resolve as tp,join as op}from"path";import{existsSync as rp}from"fs";function sp(e){return rp(op(e,".open-next"))}function ip(e){return Fe(e)?.deploy?.strategy==="staging"?"preview":null}async function ap(e){let t=tp(e.projectPath);if(!oe())return d("Not signed in. Call mist_setup first.",!0);let o=Fe(t)?.projectId;if(!o)return d(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);if(!sp(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??ip(t)??"production",i=null,n=null;try{i=await Fi(t),n=await qi(t);let a=await $o(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 lp(e,t){let r=t.ctx?Ae(t.ctx.server,t.ctx.progressToken,()=>`Deploy ${e} \u2014 waiting for terminal state`):{stop:()=>{}};try{let o=await At(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 cp(e,t){if(!oe())return d("Not signed in. Call mist_setup first.",!0);let o=Fe(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 ct(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 Yo(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 dp(e){if(!oe())return d("Not signed in. Call mist_setup first.",!0);try{let t=await Qo(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 np,Wi,Gi=P(()=>{"use strict";Q();ge();it();Hi();ft();np=rt.object({action:rt.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:rt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:rt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:rt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:rt.string().optional().describe("Admin email injected as BETTER_AUTH_ADMIN_EMAIL on first deploy of an auth-enabled project."),waitSeconds:rt.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:np,handler:async(e,t)=>{let r=e;switch(r.action??"deploy"){case"deploy":return r.projectPath?ap({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail}):d("projectPath is required for action='deploy'.",!0);case"status":return r.deploymentId?lp(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:t}):d("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?cp(r.projectPath,r.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?dp(r.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}}});var yp={};import{Server as pp}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as up}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as mp,ListToolsRequestSchema as hp}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as gp}from"zod-to-json-schema";async function fp(){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 up;await Po.connect(t),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var Po,Vi,Ki=P(()=>{"use strict";Ue();Q();hn();Nn();jn();Un();gr();Kn();ls();ys();ci();gi();Ai();Ni();Mi();Gi();Po=new pp({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Hr()}),Vi=[mn,En,Dn,Ln,as,fs,Wn,li,Vn,hi,Ci,Ei,Oi,Wi];Po.setRequestHandler(hp,async()=>({tools:Vi.map(e=>({name:e.name,description:e.description,inputSchema:gp(e.inputSchema)}))}));Po.setRequestHandler(mp,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:Po,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)}});fp().catch(e=>{console.error("Fatal error:",e),process.exit(1)})});import{readFileSync as bp}from"fs";import{dirname as wp,join as vp}from"path";import{fileURLToPath as xp}from"url";var Ge=process.argv[2];if(Ge==="--version"||Ge==="-v"){try{let e=wp(xp(import.meta.url)),t=vp(e,"..","package.json"),r=JSON.parse(bp(t,"utf-8"));console.log(r.version)}catch{console.log("unknown")}process.exit(0)}(Ge==="--help"||Ge==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
5416
5420
 
5417
5421
  Usage:
5418
5422
  npx @mistflow-ai/mcp Start the MCP server on stdio (default; invoked by editors)
@@ -5420,8 +5424,8 @@ Usage:
5420
5424
 
5421
5425
  To install the server into your editor config, use the installer:
5422
5426
  npx -y mistflow-ai install
5423
- `),process.exit(0));(We==="install"||We==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${We}' is no longer supported.
5427
+ `),process.exit(0));(Ge==="install"||Ge==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${Ge}' is no longer supported.
5424
5428
  Use the installer package instead:
5425
5429
 
5426
- npx -y mistflow-ai ${We}
5427
- `),process.exit(1));await Promise.resolve().then(()=>(Vi(),hp));
5430
+ npx -y mistflow-ai ${Ge}
5431
+ `),process.exit(1));await Promise.resolve().then(()=>(Ki(),yp));