@mistflow-ai/mcp 1.3.0 → 1.5.1
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.
- package/dist/cli.js +313 -684
- package/dist/index.js +310 -681
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}var Il,_l,Pl,Cl,Al,Rl,El,Nl,Ol,jo,Mo,$o,Lo,Uo,Fo,qo,Ke=T(()=>{"use strict";Il="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.",_l='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"`.',Pl="When submitting discovery answers back to `mist_plan` (conversationId + answers), pass `answers` as an ARRAY of objects directly: `answers: [{question, decisionKey, answer}, ...]`. Do NOT JSON-stringify the array \u2014 pass the raw array literal. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",Cl="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.",Al='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.',Rl="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.",El="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.",Nl='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.',Ol="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.",jo="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).",Mo="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'integrations' browses the curated integration blueprint catalog (pass integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",$o="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.",Lo="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.",Uo="Fetch a per-topic Mistflow methodology doc on demand. Two actions: `list` returns the catalog (id, title, kind, description) so you can discover what's available; `get` returns the full markdown for one topic. Topic kinds: 'stack' (framework patterns \u2014 Drizzle, Better Auth, server actions, components, styling), 'skill' (design + structural patterns \u2014 auth-design, app-design, admin-panel, blob-storage), 'integration' (third-party services \u2014 Stripe, Resend, OpenAI, Anthropic, Twilio, etc.). Call BEFORE writing or modifying code that touches an integration or a stack-specific pattern. Lazy-loaded \u2014 pulls only the topic you need instead of paying for the full AGENTS.md monolith every turn. Same content as AGENTS.md / .claude/skills/<topic>/SKILL.md / .cursor/rules/<topic>.mdc on disk; use this tool when those aren't auto-discovered by your host.",Fo="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).",qo="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 yr,readFileSync as Go,writeFileSync as Dl,mkdirSync as jl}from"fs";import{join as gr,dirname as fr}from"path";import{homedir as Ml}from"os";import{fileURLToPath as $l}from"url";function Le(){if(_n)return _n;try{let t=$l(import.meta.url),e=fr(t);for(let r=0;r<6;r++){let n=gr(e,"package.json");if(yr(n)){let o=JSON.parse(Go(n,"utf-8"));if(o.name==="@mistflow-ai/mcp"&&typeof o.version=="string")return _n=o.version,o.version}let i=fr(e);if(i===e)break;e=i}}catch{}return _n="0.0.0","0.0.0"}function Pn(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function zo(t,e){let r=Pn(t),n=Pn(e);if(!r||!n)return 0;for(let i=0;i<3;i++){if(r[i]<n[i])return-1;if(r[i]>n[i])return 1}return 0}function Vo(t,e,r){if(r&&zo(t,r)<0)return"unsupported";if(!e||zo(t,e)>=0)return"none";let i=Pn(t),o=Pn(e);return!i||!o?"none":i[0]<o[0]?"major":i[1]<o[1]?"minor":"patch"}function Xt(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||($e={latest:e,minSupported:r,changelogUrl:n})}function Ko(){let t=process.env.MISTFLOW_STATE_DIR||gr(Ml(),".mistflow");return gr(t,"upgrade-state.json")}function Ll(){try{let t=Ko();return yr(t)?JSON.parse(Go(t,"utf-8")):{}}catch{return{}}}function Ul(t){try{let e=Ko(),r=fr(e);yr(r)||jl(r,{recursive:!0}),Dl(e,JSON.stringify(t,null,2)+`
|
|
4
|
-
`,{mode:384})}catch{}}function
|
|
2
|
+
var fl=Object.defineProperty;var I=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tn=(t,e)=>{for(var r in e)fl(t,r,{get:e[r],enumerable:!0})};function Ls(){let t=[];return t.push("Mistflow is a full-stack app builder that creates and deploys web apps from natural language descriptions. When a user asks to build, create, or make a web app, website, landing page, dashboard, internal tool, marketplace, content site, or browser game, use Mistflow tools. Mistflow creates NEW apps from scratch. It does NOT modify existing non-Mistflow codebases."),t.push(""),t.push('Every capability is an MCP tool. There is no companion CLI. Long-running work (install, build, qa, deploy) uses the fire-and-poll pattern: the first call returns a jobId and `status: "running"`; subsequent calls with that jobId return fresh state. Each call responds in under a second \u2014 no 60s timeout risk.'),t.push(""),t.push(Tl),t.push(""),t.push(yl),t.push(""),t.push(bl),t.push(""),t.push(wl),t.push(""),t.push(vl),t.push(""),t.push(_l),t.push(""),t.push(xl),t.push(""),t.push("New app workflow:"),t.push("1. Choose destination: if the user didn't already give a path, ask whether to scaffold in the current folder or a new subfolder here. Resolve the absolute path before mist_init."),t.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via your host\'s native question tool (AskUserQuestion in Claude Code / request_user_input in Codex Plan mode / quick pick in Cursor / stop-and-wait for hosts without one \u2014 see RULE_SENTINEL_HANDLING), collect the user\'s actual answers, then submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick via mist_plan with `designConversationId` + `designDirection` (NOT `conversationId` alone).'),t.push("3. Mockup (optional, recommended): call mist_mockup with the planId \u2014 returns a wireframe prompt. Write the HTML to the returned path, open it for the user, wait for approval. Iterate with { feedback }, lock with { approved: true }."),t.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),t.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),t.push("6. Implement: mist_implement runs one plan step at a time and auto-marks the prior step complete. Call repeatedly until all steps are done."),t.push("7. Build: mist_build { projectPath } starts; poll with { jobId }. On failure, the response has `missingModules[]` \u2014 chain mist_install with those modules then mist_build again without asking."),t.push("8. Deploy: mist_deploy { projectPath } starts tar + upload; poll with { action: 'status', deploymentId }. On complete, response has `qaRequired: true` and a `url` \u2014 do NOT surface the URL to the user until mist_qa passes. Subsequent actions: 'promote' (staging \u2192 prod), 'rollback' (revert to a specific deploymentId)."),t.push("9. QA: mist_qa { projectPath } drives Playwright in-process against the live URL \u2014 single synchronous call (~20\u201345s), returns pass/fail and screenshots inline. Only surface the deploy URL to the user after mist_qa returns status: 'pass'."),t.push(""),t.push(kl),t.push(""),t.push(Sl),t.push(""),t.push("Updating an existing Mistflow app:"),t.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),t.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),t.push("- Feature needing new data model: ask product questions, call mist_project action='get' for context, call mist_plan with existingPlanId, then mist_implement, then mist_build \u2192 mist_deploy."),t.push("- Integration addition: ask product questions, mist_project action='get', mist_plan with existingPlanId, mist_implement, mist_config resource='env' for keys, mist_build \u2192 mist_deploy \u2192 mist_qa."),t.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),t.push(""),t.push("Tool summary:"),t.push("- mist_setup: authentication. Only call when the user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth."),t.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),t.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),t.push("- mist_help: returns the full tool reference. Call once per session."),t.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),t.push("- mist_install / mist_build / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),t.push("- mist_qa: synchronous single call. Drives Playwright in-process against the deployed URL. No jobId / no polling \u2014 one call returns the full QA result with screenshots."),t.join(`
|
|
3
|
+
`)}var yl,bl,wl,vl,kl,xl,Sl,Tl,_l,Rs,Es,Ns,Os,js,Ds,Ms,Ke=I(()=>{"use strict";yl="mist_plan uses the fire-and-poll shape: the first call returns quickly with status 'running' and a conversationId while the backend Sonnet ask_questions call runs in the background (that call alone can take 30-150s). Poll by calling mist_plan with just { conversationId } every ~10-15s until status is 'clarify' (questions arrived) or 'ready' (plan generated). Do NOT re-send description or answers while polling \u2014 the conversation is already tracked server-side.",bl='Treat the tool\'s returned JSON as authoritative. If `mist_plan` returns `status: "clarify"`, the planning call completed and is waiting on user answers. Do NOT rerun the same call or describe it as "still generating". Only poll again when `status: "design_clarify_pending"`.',wl="When submitting discovery answers back to `mist_plan` (conversationId + answers), pass `answers` as an ARRAY of objects directly: `answers: [{question, decisionKey, answer}, ...]`. Do NOT JSON-stringify the array \u2014 pass the raw array literal. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",vl="Before scaffolding a NEW app, resolve the destination path explicitly. If the user asked to create/build a new app and the current directory is not already that Mistflow project, ask whether to scaffold in the current folder or a new subfolder here (unless the user already gave a path). Do NOT inspect sibling directories and silently adopt one as the base just because it looks similar. Reuse an existing Mistflow project only when the user explicitly asks to continue/edit that project.",kl='Once the user approves the plan, the mist_init \u2192 mist_install \u2192 mist_implement (repeat) \u2192 mist_build \u2192 mist_deploy \u2192 mist_qa chain is expected. Do NOT pause between these calls to ask the user "should I continue?" or offer options like "full build vs step-by-step." A tool returns a status that requires user input when it genuinely needs one (e.g. confirm_new_project, awaiting promotion). Otherwise chain calls continuously. Brief one-line status updates are fine; permission requests are not.',xl="mist_init is all-or-nothing for normal users: it registers the cloud project first, scaffolds in a temp directory, then moves the finished app into place only after both steps succeed. If auth, quota, or network registration fails, stop before any app appears locally. Do NOT suggest reusing another app unless the user explicitly asks.",Sl="If mist_init fails, stop before any cloud command and explain why. Do NOT default to reusing some other existing app as recovery unless the user explicitly asked to continue that app.",Tl='Long-running tools (mist_plan, mist_install, mist_build, mist_qa, mist_deploy) use the fire-and-poll pattern. The first call returns `status: "running"` with a `jobId` or `conversationId`. Every subsequent call with that same id returns the current state \u2014 re-call IMMEDIATELY whenever you see `status: "running"`. DO NOT run `bash sleep`, `setTimeout`, or any wall-clock wait between polls \u2014 Claude Code\'s harness blocks standalone sleeps, and every MCP server poll endpoint holds the connection up to ~10-15s on its side already, returning as soon as state changes. Just call the tool again. Each response is well inside the 60s MCP ceiling. When `status: "complete"` or `"failed"` arrives, the tool is done. Never assume a job stalled because a single call took 10s \u2014 calls return fast, but the work keeps running in the background. Do not ask the user whether to keep polling; polling is how these tools work.',_l="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST ask the user and WAIT for their actual answer before submitting anything back. Use your host's native structured-question UI: `AskUserQuestion` in Claude Code, quick pick in Cursor, `request_user_input` in OpenAI Codex (available in Plan mode \u2014 if Codex returns 'request_user_input is unavailable in <mode> mode', you are in default mode; stop your turn and print the questions as a numbered chat message, then wait for the user's next message). For any host that does not expose a structured question tool, stop your turn immediately, print the questions verbatim as a numbered list with all options visible, and wait \u2014 the user's next message is the answer. The rule across every host: you never submit answers to `mist_plan` in the same turn you received the questions. That is always wrong, regardless of how obvious the `recommended` choice looks, regardless of whether you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode. The `recommended` field is a hint FOR the user, not permission FOR you. Anti-example from a real transcript: the host AI received 7 discovery questions, wrote 'I'll lock in the defaults with Azure OpenAI as the only override,' submitted answers the user never saw, and the user ended up with a plan they didn't choose. That behavior is a regression bug. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to perform that submission step; that is your job.",Rs="Connect the user's Mistflow account. Call this ONLY when: (a) the user has literally never signed in, or (b) a previous tool call returned error code 'auth_missing' or 'auth_revoked'. DO NOT call this tool in response to 500 errors, 404 errors, network errors, or any generic failure \u2014 those are backend issues, not auth issues. Running mist_setup when not needed wastes the user's time and creates login fatigue. Once signed in, the MCP persists a long-lived API key and never asks again. Two-phase device code flow: (1) Call without deviceCode \u2014 opens browser, returns status 'pending' with deviceCode and userCode. Tell the user the verification code and that they need to approve in the browser. (2) Call again with deviceCode after ~15 seconds \u2014 polls for approval. Also accepts an apiKey for headless auth (skips device code entirely).",Es="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'integrations' browses the curated integration blueprint catalog (pass integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",Ns="Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",Os="Returns the full Mistflow MCP tool reference. Call ONCE at session start (or whenever unsure which tool to pick) to learn the 14-tool surface, the fire-and-poll pattern, and how to chain end-to-end from mist_plan through mist_qa. Static \u2014 no backend round-trip, safe to call frequently.",js="Fetch a per-topic Mistflow methodology doc on demand. Two actions: `list` returns the catalog (id, title, kind, description) so you can discover what's available; `get` returns the full markdown for one topic. Topic kinds: 'stack' (framework patterns \u2014 Drizzle, Better Auth, server actions, components, styling), 'skill' (design + structural patterns \u2014 auth-design, app-design, admin-panel, blob-storage), 'integration' (third-party services \u2014 Stripe, Resend, OpenAI, Anthropic, Twilio, etc.). Call BEFORE writing or modifying code that touches an integration or a stack-specific pattern. Lazy-loaded \u2014 pulls only the topic you need instead of paying for the full AGENTS.md monolith every turn. Same content as AGENTS.md / .claude/skills/<topic>/SKILL.md / .cursor/rules/<topic>.mdc on disk; use this tool when those aren't auto-discovered by your host.",Ds="Analyze build errors from a Next.js / TypeScript project. Extracts structured errors with file, line, a human-readable message for the user, and an actionable suggestion. Call with { projectPath } to run `npm run build` and parse the failure; call with { buildOutput } to parse output captured elsewhere (e.g. from a failed mist_build job).",Ms="Generate a grayscale wireframe sketch of the planned app so the user can review layout + information hierarchy before any code is written. The server returns a structured spec + a wireframePrompt \u2014 the host AI writes the HTML file to .mistflow/mockups/mockup-<planId>.html and opens it. Pass { planId } for the first iteration, { planId, feedback: '...' } to iterate, { planId, approved: true } to lock the design before mist_init. Iterative by design \u2014 expect 1-3 rounds of feedback."});import{existsSync as br,readFileSync as qs,writeFileSync as Il,mkdirSync as Pl}from"fs";import{join as fr,dirname as yr}from"path";import{homedir as Cl}from"os";import{fileURLToPath as Al}from"url";function $e(){if(_n)return _n;try{let t=Al(import.meta.url),e=yr(t);for(let r=0;r<6;r++){let n=fr(e,"package.json");if(br(n)){let o=JSON.parse(qs(n,"utf-8"));if(o.name==="@mistflow-ai/mcp"&&typeof o.version=="string")return _n=o.version,o.version}let i=yr(e);if(i===e)break;e=i}}catch{}return _n="0.0.0","0.0.0"}function In(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function Us(t,e){let r=In(t),n=In(e);if(!r||!n)return 0;for(let i=0;i<3;i++){if(r[i]<n[i])return-1;if(r[i]>n[i])return 1}return 0}function Bs(t,e,r){if(r&&Us(t,r)<0)return"unsupported";if(!e||Us(t,e)>=0)return"none";let i=In(t),o=In(e);return!i||!o?"none":i[0]<o[0]?"major":i[1]<o[1]?"minor":"patch"}function Xt(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||(Ue={latest:e,minSupported:r,changelogUrl:n})}function zs(){let t=process.env.MISTFLOW_STATE_DIR||fr(Cl(),".mistflow");return fr(t,"upgrade-state.json")}function Rl(){try{let t=zs();return br(t)?JSON.parse(qs(t,"utf-8")):{}}catch{return{}}}function El(t){try{let e=zs(),r=yr(e);br(r)||Pl(r,{recursive:!0}),Il(e,JSON.stringify(t,null,2)+`
|
|
4
|
+
`,{mode:384})}catch{}}function Nl(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Hs(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!Ue)return null;let t=$e();if(t==="0.0.0")return null;let e=Bs(t,Ue.latest,Ue.minSupported);if(e==="none")return null;if(e==="unsupported")return Fs(e,t,Ue);if($s)return null;let r=Rl(),n=Date.now(),i=Nl(e);return r.dismissedForVersion===Ue.latest&&e!=="major"||r.lastLatestSeen===Ue.latest&&r.lastShownMs&&n-r.lastShownMs<i?null:($s=!0,El({...r,lastShownMs:n,lastLatestSeen:Ue.latest}),Fs(e,t,Ue))}function Fs(t,e,r){let n="npx -y mistflow-ai install",i=r.changelogUrl?`
|
|
5
5
|
What's new: ${r.changelogUrl}`:"";return t==="unsupported"?`
|
|
6
6
|
|
|
7
7
|
---
|
|
@@ -21,7 +21,7 @@ This is a major update. Run \`${n}\` and restart your editor.${i}
|
|
|
21
21
|
--- Mistflow update available: ${e} -> ${r.latest} ---
|
|
22
22
|
Run \`${n}\` to upgrade, then restart your editor.${i}`:`
|
|
23
23
|
|
|
24
|
-
(Mistflow ${r.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function
|
|
24
|
+
(Mistflow ${r.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function wr(){let t=$e(),e=Ue??{latest:"",minSupported:"",changelogUrl:""},r=Bs(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:Ue!==null}}var _n,Ue,$s,Zt=I(()=>{"use strict";_n=null;Ue=null;$s=!1});var nn={};Tn(nn,{closeBrowser:()=>kr,getIsolatedContext:()=>jl,getPage:()=>vr,getSnapshot:()=>en,takeScreenshot:()=>tn});async function Ws(){try{return await import("playwright")}catch{throw new Error("Playwright is not installed. Run: cd packages/mcp-server && pnpm add playwright && npx playwright install chromium")}}async function Ol(){let t=await Ws();return(!Fe||!Fe.isConnected())&&(Fe=await t.chromium.launch({headless:!0})),ot&&(await ot.close().catch(()=>{}),ot=null),ot=await Fe.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Je=await ot.newPage(),Je}async function vr(){return Je&&!Je.isClosed()?Je:(Pn||(Pn=Ol().finally(()=>{Pn=null})),Pn)}async function kr(){Je&&!Je.isClosed()&&await Je.close().catch(()=>{}),ot&&await ot.close().catch(()=>{}),Fe?.isConnected()&&await Fe.close().catch(()=>{}),Je=null,ot=null,Fe=null}async function jl(){let t=await Ws();(!Fe||!Fe.isConnected())&&(Fe=await t.chromium.launch({headless:!0}));let e=await Fe.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function en(t){return await t.locator("body").ariaSnapshot()}async function tn(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var Fe,ot,Je,Pn,Et=I(()=>{"use strict";Fe=null,ot=null,Je=null,Pn=null;process.once("SIGTERM",()=>{kr().finally(()=>process.exit(0))});process.once("SIGINT",()=>{kr().finally(()=>process.exit(0))})});function p(t,e=!1){let r=t;try{let n=Hs();n&&(r=t+n)}catch{}return{content:[{type:"text",text:r}],isError:e}}function Ee(t){let e={status:"setup_required",reason:"no_credentials",intent:t,instruction:`You must sign in to Mistflow before you can ${t}. Call mist_setup({}) \u2014 it walks the user through device-code authentication (typically <60s). Only retry the original call AFTER mist_setup has fully completed sign-in (status field is no longer "pending").`,nextAction:`Step 1: Call mist_setup({}) now. Do not ask the user for permission first \u2014 sign-in is a precondition for this flow, not a decision point. Step 2: mist_setup returns immediately with a signInUrl + userCode. Show the URL and code to the user and wait for them to approve in their browser. Step 3: If the response had status: "pending", call mist_setup again with the returned deviceCode every ~15s until it returns a non-pending status. Step 4: Only then retry the call that produced this response with the same arguments. Do NOT retry while mist_setup is still pending \u2014 the credentials aren't on disk yet and you'll loop right back into this same response.`};return p(JSON.stringify(e),!0)}function Ye(t){return p(`This is not a Mistflow project (no mistflow.json found at ${t}).
|
|
25
25
|
|
|
26
26
|
Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
|
|
27
27
|
|
|
@@ -30,20 +30,20 @@ To get started:
|
|
|
30
30
|
2. Call mist_init({ planId, path: "<absolute-path>" })
|
|
31
31
|
3. Call mist_install({ projectPath }), then mist_implement({ projectPath })
|
|
32
32
|
|
|
33
|
-
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function
|
|
34
|
-
`,{mode:384}),
|
|
35
|
-
`,"utf-8")}catch{}}var Ql,vt=T(()=>{"use strict";Ql="https://api.mistflow.ai"});var ls={};In(ls,{MistflowApiError:()=>W,addDomain:()=>Ar,bindWorkspace:()=>sn,cancelSession:()=>Kr,checkAuth:()=>nc,checkAuthDetailed:()=>ss,checkSubdomain:()=>On,checkToolGuard:()=>Jr,createDeployment:()=>oc,createProject:()=>xt,deleteEnvVar:()=>Dr,discoverDecisions:()=>sc,downloadImageryAsset:()=>Dn,downloadSource:()=>lc,downloadSourceWithToken:()=>is,fetchAcceptanceCriteria:()=>on,fetchActiveSessionPlan:()=>Yr,fetchDesignDirections:()=>jn,fetchDesignMockups:()=>Cr,fetchDesignPick:()=>Pr,fetchDoc:()=>Br,fetchDocsList:()=>qr,fetchModule:()=>zr,fetchPlanConversation:()=>$n,fetchProjectImagery:()=>Ir,fetchScaffold:()=>Ur,fetchSessionNext:()=>Dt,fetchSessionPlanRevisions:()=>as,fetchStepContext:()=>Fr,forkTemplate:()=>Wr,generatePlan:()=>Ln,getAuthHeaders:()=>kt,getBaseUrl:()=>_e,getDashboardUrl:()=>Zl,getDbCredentials:()=>ic,getDeployLogs:()=>jr,getDeploymentStatus:()=>at,getProject:()=>rc,getProjectErrors:()=>Mr,getSeedInfo:()=>qn,getSession:()=>Ot,getSiteUrl:()=>Xl,getTemplate:()=>Hr,hasCredentialsOnDisk:()=>ve,hasLocalCredentials:()=>os,listDeployments:()=>Et,listDomains:()=>lt,listEnvVars:()=>Nr,listSessionsForMachine:()=>an,markLocalSetupDone:()=>cc,modifyPlan:()=>Un,pingBackend:()=>Tr,promotePreview:()=>$r,redeployProject:()=>ac,removeDomain:()=>Rr,rollbackDeployment:()=>Lr,shareProject:()=>Gr,startSession:()=>Vr,submitAcceptanceResults:()=>Xr,submitDesignPick:()=>Mn,submitSessionAnswers:()=>dc,transitionSession:()=>Qr,uploadAndDeploy:()=>_r,uploadQAResults:()=>Er,upsertEnvVar:()=>Or,verifyDomain:()=>Fn});function _e(){return En()}function Xl(){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 Zl(){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 kt(){let t=wt();if(!t.ok)throw new W("auth_missing","No Mistflow credentials found.",401);return ec(t.creds)}function ec(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":Le()}}function Rt(t){try{Xt(t.headers)}catch{}}async function Tr(){try{let t=await fetch(`${_e()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Rt(t)}catch{}}async function rs(t,e,r,n){for(let i=0;i<2;i++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(o){let s=o instanceof Error&&o.name==="TimeoutError",a=o instanceof TypeError;if(n&&i===0&&(s||a)){console.error(`[api] Retrying ${t} after ${s?"timeout":"network error"}`);continue}throw o}throw new Error("fetchWithRetry: exhausted retries")}async function rn(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new W(r,n,t.status,e?.details);let i=t.status;return i===401?new W("auth_invalid",n,i):i===403?new W("permission_denied",n,i):i===404?new W("not_found",n,i):i===409?new W("conflict",n,i):i===422?new W("validation_error",n,i):i===429?new W("rate_limited",n,i):i>=500?new W("server_error",t.statusText||"Internal server error",i):new W("client_error",n,i)}async function F(t,e={}){let r=kt(),{timeoutMs:n,idempotent:i,...o}=e,s=n??3e4,a=(o.method??"GET").toUpperCase(),l=i??(a==="GET"||a==="HEAD"),c;try{c=await rs(`${_e()}${t}`,{...o,headers:{...r,...o.headers}},s,l)}catch(h){throw h instanceof Error&&h.name==="TimeoutError"?new W("network_error","Request timed out. Try again in a moment."):new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(c),!c.ok)throw await rn(c);return c.json()}function os(){return wt().ok}async function nc(){return(await ss()).ok}async function ss(){if(Nn!==null&&Date.now()<ns)return Nn?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!os())return{ok:!1,reason:"no_credentials"};try{return await F("/api/org"),Nn=!0,ns=Date.now()+tc,{ok:!0}}catch(t){if(Nn=null,!(t instanceof W))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 rc(t){return F(`/api/projects/${encodeURIComponent(t)}`)}async function On(t){return F(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function xt(t,e={}){return F("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e.template,db_provider:e.dbProvider??"neon",requested_subdomain:e.requestedSubdomain,picked_direction:e.pickedDirection,imagery_brief:e.imageryBrief,plan_context:e.planContext,design_conversation_id:e.designConversationId})})}async function Ir(t){return F(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function Dn(t){let e=await fetch(t);if(!e.ok)throw new Error(`Failed to download imagery asset: HTTP ${e.status} ${e.statusText}`);let r=await e.arrayBuffer();return Buffer.from(r)}async function oc(t,e){return F("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function _r(t,e,r="production",n,i,o,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=wt();if(!c.ok)throw new W("auth_missing","No Mistflow credentials found.",401);let h=c.creds,p=a(e),u=new Blob([p],{type:"application/gzip"}),w=new FormData;if(w.append("project_id",t),w.append("build",u,l(e)),r!=="production"&&w.append("environment",r),n&&w.append("admin_email",n),i&&w.append("schema_pushed","true"),o){let{existsSync:b}=await import("fs");if(b(o)){let y=a(o),I=new Blob([y],{type:"application/gzip"});w.append("source",I,"source.tar.gz")}}s&&w.append("git_commit_sha",s);let O;try{O=await fetch(`${_e()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":Le()},body:w,signal:AbortSignal.timeout(3e5)})}catch{throw new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(O),!O.ok)throw await rn(O);let k=await O.json();return{...k,id:k.deployment_id}}async function at(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return F(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:i}:void 0)}async function jn(t){return F(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Pr(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return F(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:i})}async function Mn(t,e){return F(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json"},timeoutMs:6e4})}async function Cr(t){try{return await F(`/api/plan/design-directions/${encodeURIComponent(t)}/mockups`,{timeoutMs:1e4})}catch{return{}}}async function $n(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return F(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:i})}async function Ln(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};if(e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&e?.designDirection){let i=e.designDirection,o=typeof i.id=="string"?i.id:void 0,s=typeof i.custom=="string"?i.custom:void 0,a=o?{direction_id:o}:s?{custom:s}:{custom:JSON.stringify(i)};e.conversationId&&(a.conversation_id=e.conversationId);let l=await Mn(e.designConversationId,a);return{status:"ready",plan:l.plan??{},methodology:l.methodology??"",...l.designMd?{designMd:l.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return F("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function Un(t,e){return F("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function sc(t){return F("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Ar(t,e){return F(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function lt(t){return F(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Fn(t,e){return F(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Rr(t,e){return F(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function ic(t){return F(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function qn(t){try{return await F(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof W&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Er(t,e){try{return await 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 Nr(t){return F(`/api/projects/${encodeURIComponent(t)}/env`)}async function Or(t,e,r,n){return F(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:r,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function Dr(t,e){return F(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function jr(t){return F(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Mr(t,e="7d"){return F(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Et(t){return F(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function ac(t){return F(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function $r(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 Lr(t){return F(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function lc(t,e){let r=wt();if(!r.ok)throw new W("auth_missing","Not authenticated.",401);let n=r.creds,i=await fetch(`${_e()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":Le()},signal:AbortSignal.timeout(12e4)});if(Rt(i),!i.ok)throw await rn(i);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await i.arrayBuffer());o(e,s)}async function Nt(t,e){let{timeoutMs:r,idempotent:n,...i}=e??{},o=r??3e4,s=(i.method??"GET").toUpperCase(),a=n??(s==="GET"||s==="HEAD"),l;try{l=await rs(`${_e()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":Le()},...i},o,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new W("network_error","Request timed out. Try again in a moment."):new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(l),!l.ok)throw await rn(l);return l.json()}async function Ur(t="nextjs"){return Nt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Fr(t,e){return Nt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function qr(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return Nt(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function Br(t,e){return Nt(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function zr(t,e,r,n){return Nt(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:r,entity_plural:n})})}async function Hr(t){return Nt(`/api/templates/${encodeURIComponent(t)}`)}async function Wr(t){return F(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function is(t,e,r){let n;try{n=await fetch(`${_e()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":Le()},signal:AbortSignal.timeout(12e4)})}catch{throw new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(n),!n.ok)throw n.status===401?new W("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await rn(n);let{writeFileSync:i}=await import("fs"),o=Buffer.from(await n.arrayBuffer());i(r,o)}async function cc(t){await F(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Gr(t,e){return F(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function Vr(t){return F("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function Ot(t){return F(`/api/sessions/${t}`)}async function Kr(t,e){return F(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Dt(t){return F(`/api/sessions/${t}/next`)}async function dc(t,e){return F(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Jr(t,e){return F(`/api/sessions/${t}/can/${e}`)}async function on(t){return F(`/api/sessions/${t}/acceptance`)}async function as(t){return F(`/api/sessions/${t}/revisions`)}async function Yr(t){let e=await as(t),r=[...e].reverse().find(n=>n.status==="active")??e.at(-1);return!r||!r.body||typeof r.body!="object"||Array.isArray(r.body)?null:{plan:r.body,planRevisionId:r.id}}async function sn(t,e){return F(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function an(t){let e=new URLSearchParams({machine_id:t}).toString();return F(`/api/sessions/me/workspaces?${e}`)}async function Qr(t,e){return F(`/api/sessions/${t}/transition`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!1})}async function Xr(t,e,r){return F(`/api/sessions/${t}/acceptance/results`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({results:e,plan_revision_id:r??null}),idempotent:!1})}var W,Nn,ns,tc,ke=T(()=>{"use strict";vt();Zt();W=class extends Error{constructor(r,n,i,o){super(n);this.code=r;this.statusCode=i;this.details=o;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};Nn=null,ns=0,tc=300*1e3});import{z as Zr}from"zod";import{platform as pc}from"os";import{execFile as cs}from"child_process";function mc(t){return"error"in t}function ps(t){return new Promise(e=>setTimeout(e,t))}function hc(t){return new Promise(e=>{let r=pc();r==="win32"?cs("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):cs(r==="darwin"?"open":"xdg-open",[t],i=>{i&&console.error("Could not open browser:",i.message),e(!i)}),setTimeout(()=>e(!1),5e3)})}async function ds(t,e,r,n){let i=r,o=n.sleep??ps;for(let s=0;s<e;s++){await o(i);let a;try{let c=await n.fetch(`${_e()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!c.ok)continue;a=await c.json()}catch{continue}if(mc(a))switch(a.error){case"authorization_pending":continue;case"slow_down":i+=5e3;continue;case"expired_token":return d("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return d("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return d("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=a.email||a.org_name||a.org_slug;return xr({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 fc(t,e=gc){let r=t;if(r?.apiKey)try{let s=await e.fetch(`${_e()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!s.ok)return d("Invalid API key. Check the key and try again.",!0);let a=await s.json();return xr({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),d(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let s=await ds(r.deviceCode,6,5e3,e);return s||d(JSON.stringify({status:"pending",deviceCode:r.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let s=await e.fetch(`${_e()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!s.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await s.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let i=`${n.verification_uri}?code=${n.user_code}`;console.error(`
|
|
33
|
+
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Gs(t,e){try{let{getPage:r,takeScreenshot:n}=await Promise.resolve().then(()=>(Et(),nn)),i=await r();await i.setViewportSize(Dl);try{await i.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await i.waitForLoadState("networkidle").catch(()=>{});let o=await n(i,!1);return{content:[{type:"text",text:e},{type:"image",data:o.toString("base64"),mimeType:"image/png"}]}}finally{await i.setViewportSize(Ml).catch(()=>{})}}catch{return p(e)}}var Dl,Ml,be=I(()=>{"use strict";Zt();Dl={width:1024,height:576},Ml={width:1280,height:720}});import{readFileSync as xr,existsSync as Cn,writeFileSync as Vs,mkdirSync as Ll,renameSync as Ul,unlinkSync as $l}from"fs";import{join as An,dirname as Fl}from"path";import{homedir as ql}from"os";import{randomBytes as Bl}from"crypto";function Ks(){return An(ql(),".mistflow","credentials.json")}function Rn(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function Js(){let t=Ks();if(!Cn(t))return null;try{let e=JSON.parse(xr(t,"utf-8"));return typeof e.apiKey=="string"?{[zl]:e}:e}catch{return null}}function vt(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=Js();if(!e)return{ok:!1,reason:"missing"};let r=Rn(),n=e[r];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function Sr(t){let e=Ks(),r=Fl(e);Cn(r)||Ll(r,{recursive:!0});let n=Js()??{},i=Rn();n[i]=t;let o=An(r,`.credentials.tmp.${Bl(8).toString("hex")}`);try{Vs(o,JSON.stringify(n,null,2)+`
|
|
34
|
+
`,{mode:384}),Ul(o,e)}catch(s){try{$l(o)}catch{}throw s}}function Ys(){let t=vt();return t.ok?t.creds:null}function Se(){return vt().ok}function it(t){let e=An(t,"mistflow.json");if(!Cn(e))return null;try{return JSON.parse(xr(e,"utf-8"))}catch{return null}}function Tr(t,e){let r=An(t,"mistflow.json");if(Cn(r))try{let i={...JSON.parse(xr(r,"utf-8")),...e};Vs(r,JSON.stringify(i,null,2)+`
|
|
35
|
+
`,"utf-8")}catch{}}var zl,kt=I(()=>{"use strict";zl="https://api.mistflow.ai"});var ro={};Tn(ro,{MistflowApiError:()=>G,addDomain:()=>Ar,bindWorkspace:()=>on,cancelSession:()=>Vr,checkAuth:()=>Kl,checkAuthDetailed:()=>eo,checkSubdomain:()=>Nn,checkToolGuard:()=>Kr,createDeployment:()=>Yl,createProject:()=>St,deleteEnvVar:()=>jr,discoverDecisions:()=>Xl,downloadImageryAsset:()=>Pr,downloadSource:()=>tc,downloadSourceWithToken:()=>to,fetchAcceptanceCriteria:()=>sn,fetchActiveSessionPlan:()=>oc,fetchDesignDirections:()=>On,fetchDesignPick:()=>Ql,fetchDesignRenders:()=>Dn,fetchDoc:()=>Br,fetchDocsList:()=>qr,fetchModule:()=>zr,fetchPlanConversation:()=>Mn,fetchProjectImagery:()=>Ir,fetchScaffold:()=>$r,fetchSessionNext:()=>Dt,fetchSessionPlanRevisions:()=>no,fetchStepContext:()=>Fr,forkTemplate:()=>Wr,generatePlan:()=>Ln,getAuthHeaders:()=>xt,getBaseUrl:()=>Ie,getDashboardUrl:()=>Wl,getDbCredentials:()=>Zl,getDeployLogs:()=>Dr,getDeploymentStatus:()=>at,getProject:()=>Jl,getProjectErrors:()=>Mr,getSeedInfo:()=>Fn,getSession:()=>qn,getSiteUrl:()=>Hl,getTemplate:()=>Hr,hasCredentialsOnDisk:()=>Se,hasLocalCredentials:()=>Zs,listDeployments:()=>Ot,listDomains:()=>lt,listEnvVars:()=>Nr,listSessionsForMachine:()=>an,markLocalSetupDone:()=>nc,modifyPlan:()=>Un,pingBackend:()=>_r,promotePreview:()=>Lr,redeployProject:()=>ec,removeDomain:()=>Rr,rollbackDeployment:()=>Ur,shareProject:()=>Gr,startSession:()=>rc,submitAcceptanceResults:()=>Jr,submitDesignPick:()=>jn,submitSessionAnswers:()=>sc,uploadAndDeploy:()=>Cr,uploadQAResults:()=>Er,upsertEnvVar:()=>Or,verifyDomain:()=>$n});function Ie(){return Rn()}function Hl(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9102")}return"https://mistflow.ai"}function Wl(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function xt(){let t=vt();if(!t.ok)throw new G("auth_missing","No Mistflow credentials found.",401);return Gl(t.creds)}function Gl(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":$e()}}function Nt(t){try{Xt(t.headers)}catch{}}async function _r(){try{let t=await fetch(`${Ie()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Nt(t)}catch{}}async function Xs(t,e,r,n){for(let i=0;i<2;i++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(o){let s=o instanceof Error&&o.name==="TimeoutError",a=o instanceof TypeError;if(n&&i===0&&(s||a)){console.error(`[api] Retrying ${t} after ${s?"timeout":"network error"}`);continue}throw o}throw new Error("fetchWithRetry: exhausted retries")}async function rn(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new G(r,n,t.status,e?.details);let i=t.status;return i===401?new G("auth_invalid",n,i):i===403?new G("permission_denied",n,i):i===404?new G("not_found",n,i):i===409?new G("conflict",n,i):i===422?new G("validation_error",n,i):i===429?new G("rate_limited",n,i):i>=500?new G("server_error",t.statusText||"Internal server error",i):new G("client_error",n,i)}async function U(t,e={}){let r=xt(),{timeoutMs:n,idempotent:i,...o}=e,s=n??3e4,a=(o.method??"GET").toUpperCase(),l=i??(a==="GET"||a==="HEAD"),c;try{c=await Xs(`${Ie()}${t}`,{...o,headers:{...r,...o.headers}},s,l)}catch(u){throw u instanceof Error&&u.name==="TimeoutError"?new G("network_error","Request timed out. Try again in a moment."):new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Nt(c),!c.ok)throw await rn(c);return c.json()}function Zs(){return vt().ok}async function Kl(){return(await eo()).ok}async function eo(){if(En!==null&&Date.now()<Qs)return En?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Zs())return{ok:!1,reason:"no_credentials"};try{return await U("/api/org"),En=!0,Qs=Date.now()+Vl,{ok:!0}}catch(t){if(En=null,!(t instanceof G))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function Jl(t){return U(`/api/projects/${encodeURIComponent(t)}`)}async function Nn(t){return U(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function St(t,e={}){return U("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e.template,db_provider:e.dbProvider??"neon",requested_subdomain:e.requestedSubdomain,picked_direction:e.pickedDirection,imagery_brief:e.imageryBrief,plan_context:e.planContext,design_conversation_id:e.designConversationId,session_id:e.sessionId})})}async function Ir(t){return U(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function Pr(t){let e=await fetch(t);if(!e.ok)throw new Error(`Failed to download imagery asset: HTTP ${e.status} ${e.statusText}`);let r=await e.arrayBuffer();return Buffer.from(r)}async function Yl(t,e){return U("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function Cr(t,e,r="production",n,i,o,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=vt();if(!c.ok)throw new G("auth_missing","No Mistflow credentials found.",401);let u=c.creds,h=a(e),d=new Blob([h],{type:"application/gzip"}),v=new FormData;if(v.append("project_id",t),v.append("build",d,l(e)),r!=="production"&&v.append("environment",r),n&&v.append("admin_email",n),i&&v.append("schema_pushed","true"),o){let{existsSync:k}=await import("fs");if(k(o)){let y=a(o),A=new Blob([y],{type:"application/gzip"});v.append("source",A,"source.tar.gz")}}s&&v.append("git_commit_sha",s);let W;try{W=await fetch(`${Ie()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${u.apiKey}`,"X-Mistflow-MCP-Version":$e()},body:v,signal:AbortSignal.timeout(3e5)})}catch{throw new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Nt(W),!W.ok)throw await rn(W);let _=await W.json();return{..._,id:_.deployment_id}}async function at(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return U(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:i}:void 0)}async function On(t){return U(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Ql(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return U(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:i})}async function jn(t,e){return U(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),timeoutMs:6e4})}async function Dn(t){try{return await U(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function Mn(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return U(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:i})}async function Ln(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};if(e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&e?.designDirection){let i=e.designDirection,o=256,s=4e3,a=typeof i.id=="string"?i.id:void 0,l=typeof i.custom=="string"?i.custom:void 0,c=a&&a.length>0&&a.length<=o?a:void 0,u=(()=>{if(l&&l.length>0)return l.length<=s?l:l.slice(0,s)+" (truncated)";if(!c){let v=JSON.stringify(i);return v.length<=s?v:v.slice(0,s)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${o}; falling back to custom`);let h=c?{direction_id:c}:{custom:u};e.conversationId&&(h.conversation_id=e.conversationId);let d=await jn(e.designConversationId,h);return{status:"ready",plan:d.plan??{},methodology:d.methodology??"",...d.designMd?{designMd:d.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return U("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function Un(t,e,r={}){return U("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function Xl(t){return U("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Ar(t,e){return U(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function lt(t){return U(`/api/projects/${encodeURIComponent(t)}/domains`)}async function $n(t,e){return U(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Rr(t,e){return U(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Zl(t){return U(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Fn(t){try{return await U(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof G&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Er(t,e){try{return await U(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(r){return console.error("[api] Failed to upload QA results:",r instanceof Error?r.message:r),null}}async function Nr(t){return U(`/api/projects/${encodeURIComponent(t)}/env`)}async function Or(t,e,r,n){return U(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:r,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function jr(t,e){return U(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Dr(t){return U(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Mr(t,e="7d"){return U(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Ot(t){return U(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function ec(t){return U(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Lr(t,e){let r=new URLSearchParams({preview_deployment_id:e});return U(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Ur(t){return U(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function tc(t,e){let r=vt();if(!r.ok)throw new G("auth_missing","Not authenticated.",401);let n=r.creds,i=await fetch(`${Ie()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":$e()},signal:AbortSignal.timeout(12e4)});if(Nt(i),!i.ok)throw await rn(i);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await i.arrayBuffer());o(e,s)}async function jt(t,e){let{timeoutMs:r,idempotent:n,...i}=e??{},o=r??3e4,s=(i.method??"GET").toUpperCase(),a=n??(s==="GET"||s==="HEAD"),l;try{l=await Xs(`${Ie()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":$e()},...i},o,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new G("network_error","Request timed out. Try again in a moment."):new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Nt(l),!l.ok)throw await rn(l);return l.json()}async function $r(t="nextjs"){return jt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Fr(t,e){return jt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function qr(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return jt(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function Br(t,e){return jt(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function zr(t,e,r,n){return jt(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:r,entity_plural:n})})}async function Hr(t){return jt(`/api/templates/${encodeURIComponent(t)}`)}async function Wr(t){return U(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function to(t,e,r){let n;try{n=await fetch(`${Ie()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":$e()},signal:AbortSignal.timeout(12e4)})}catch{throw new G("network_error","Cannot reach Mistflow servers. Check your network.")}if(Nt(n),!n.ok)throw n.status===401?new G("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await rn(n);let{writeFileSync:i}=await import("fs"),o=Buffer.from(await n.arrayBuffer());i(r,o)}async function nc(t){await U(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Gr(t,e){return U(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function rc(t){return U("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function qn(t){return U(`/api/sessions/${t}`)}async function Vr(t,e){return U(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Dt(t){return U(`/api/sessions/${t}/next`)}async function sc(t,e){return U(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Kr(t,e){return U(`/api/sessions/${t}/can/${e}`)}async function sn(t){return U(`/api/sessions/${t}/acceptance`)}async function no(t){return U(`/api/sessions/${t}/revisions`)}async function oc(t){let e=await no(t),r=[...e].reverse().find(n=>n.status==="active")??e.at(-1);return!r||!r.body||typeof r.body!="object"||Array.isArray(r.body)?null:{plan:r.body,planRevisionId:r.id}}async function on(t,e){return U(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function an(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return U(`/api/sessions/me/workspaces?${n}`)}async function Jr(t,e,r){return U(`/api/sessions/${t}/acceptance/results`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({results:e,plan_revision_id:r??null}),idempotent:!1})}var G,En,Qs,Vl,_e=I(()=>{"use strict";kt();Zt();G=class extends Error{constructor(r,n,i,o){super(n);this.code=r;this.statusCode=i;this.details=o;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};En=null,Qs=0,Vl=300*1e3});import{z as Yr}from"zod";import{platform as ic}from"os";import{execFile as so}from"child_process";function lc(t){return"error"in t}function io(t){return new Promise(e=>setTimeout(e,t))}function cc(t){return new Promise(e=>{let r=ic();r==="win32"?so("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):so(r==="darwin"?"open":"xdg-open",[t],i=>{i&&console.error("Could not open browser:",i.message),e(!i)}),setTimeout(()=>e(!1),5e3)})}async function oo(t,e,r,n){let i=r,o=n.sleep??io;for(let s=0;s<e;s++){await o(i);let a;try{let c=await n.fetch(`${Ie()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!c.ok)continue;a=await c.json()}catch{continue}if(lc(a))switch(a.error){case"authorization_pending":continue;case"slow_down":i+=5e3;continue;case"expired_token":return p("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return p("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return p("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=a.email||a.org_name||a.org_slug;return Sr({apiKey:a.api_key,apiKeyId:a.api_key_id,apiKeyName:a.api_key_name,orgId:a.org_id,orgSlug:a.org_slug,email:a.email}),p(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function pc(t,e=dc){let r=t;if(r?.apiKey)try{let s=await e.fetch(`${Ie()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!s.ok)return p("Invalid API key. Check the key and try again.",!0);let a=await s.json();return Sr({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),p(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let s=await oo(r.deviceCode,6,5e3,e);return s||p(JSON.stringify({status:"pending",deviceCode:r.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let s=await e.fetch(`${Ie()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!s.ok)return p("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await s.json()}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}let i=`${n.verification_uri}?code=${n.user_code}`;console.error(`
|
|
36
36
|
Sign in at: ${i}
|
|
37
37
|
Your code: ${n.user_code}
|
|
38
|
-
`);try{await e.openBrowser(i)}catch{}let o=await
|
|
39
|
-
`)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o>0){let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();a&&a!=='""'&&a!=="''"&&e.add(s)}}return e}var
|
|
40
|
-
`)}function cn(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function
|
|
41
|
-
`),nextSteps:
|
|
42
|
-
`),i.projectId&&Promise.resolve().then(()=>(
|
|
38
|
+
`);try{await e.openBrowser(i)}catch{}let o=await oo(n.device_code,6,5e3,e);return o||p(JSON.stringify({status:"pending",deviceCode:n.device_code,signInUrl:i,userCode:n.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+n.device_code+"' to check if they approved."}))}var ac,dc,ao,lo=I(()=>{"use strict";Ke();be();_e();kt();ac=Yr.object({apiKey:Yr.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:Yr.string().optional().describe("Resume polling for a pending device code. Returned by a previous mist_setup call with status 'pending'. Call mist_setup again with this value after ~15 seconds to check if the user approved.")});dc={fetch:globalThis.fetch,openBrowser:cc,sleep:io};ao={name:"mist_setup",description:Rs,inputSchema:ac,handler:t=>pc(t)}});import{existsSync as uc,readFileSync as mc}from"fs";function co(t){let e=new Set;if(!uc(t))return e;let r=mc(t,"utf-8");for(let n of r.split(`
|
|
39
|
+
`)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o>0){let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();a&&a!=='""'&&a!=="''"&&e.add(s)}}return e}var po=I(()=>{"use strict"});var dn={};Tn(dn,{emptyState:()=>cn,fetchRemoteState:()=>bc,fuzzyMatch:()=>vc,getLocalStatePath:()=>Qr,readLocalState:()=>yc,syncRemoteState:()=>wc,writeLocalState:()=>ln});import{existsSync as uo,readFileSync as hc,writeFileSync as gc,mkdirSync as fc}from"fs";import{join as mo}from"path";function Qr(t){return mo(t,".mistflow","state.json")}function yc(t){let e=Qr(t);if(!uo(e))return null;try{return JSON.parse(hc(e,"utf-8"))}catch{return null}}function ln(t,e){let r=mo(t,".mistflow");uo(r)||fc(r,{recursive:!0}),gc(Qr(t),JSON.stringify(e,null,2)+`
|
|
40
|
+
`)}function cn(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function bc(t){let e;try{e=xt()}catch{return null}try{let r=await fetch(`${Ie()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":$e()}});try{Xt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function wc(t,e){let r;try{r=xt()}catch{return!1}try{let n=await fetch(`${Ie()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":$e()},body:JSON.stringify(e)});try{Xt(n.headers)}catch{}return n.ok}catch{return!1}}function vc(t,e){let r=t.toLowerCase(),n=e.toLowerCase();return n.includes(r)||r.includes(n)?!0:r.split(/\s+/).some(o=>o.length>=3&&n.includes(o))}var Tt=I(()=>{"use strict";_e();Zt()});var Xr={};Tn(Xr,{ensureBackendRegistered:()=>Pc,ensureShadcnComponents:()=>Cc});import{existsSync as go,readFileSync as kc,writeFileSync as xc}from"fs";import{join as Bn}from"path";import{spawn as Sc}from"child_process";function Tc(t,e,r,n,i){return new Promise(o=>{let s=Sc(t,e,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:n,...i?{env:{...process.env,...i}}:{}}),a="",l="";s.stdout?.on("data",c=>{a+=c.toString()}),s.stderr?.on("data",c=>{l+=c.toString()}),s.on("close",c=>o({success:c===0,stdout:a,stderr:l})),s.on("error",c=>o({success:!1,stdout:a,stderr:l+c.message}))})}function _c(t){let e=Bn(t,"mistflow.json");if(!go(e))return null;try{return JSON.parse(kc(e,"utf-8"))}catch{return null}}function Ic(t,e){xc(Bn(t,"mistflow.json"),JSON.stringify(e,null,2))}async function ho(t,e){try{let r=e.features,n=e.steps,i={plan:e};Array.isArray(r)&&r.length>0&&(i.features=r.map(o=>o.name)),Array.isArray(n)&&n.length>0&&(i.provenance=n.map(o=>({feature:o.name??o.title??`Step ${o.number??"?"}`,user_intent:(o.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${Ie()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...xt(),"Content-Type":"application/json"},body:JSON.stringify(i)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function Pc(t,e={}){let r=_c(t);if(r){if(!Se())return r.projectId;if(!r.projectId)try{let i=r.plan?.requestedSubdomain,o=await St(r.name,{dbProvider:r.dbProvider??"neon",requestedSubdomain:i});return r.projectId=o.id,Ic(t,r),ln(t,cn(o.id,r.name)),r.plan&&await ho(o.id,r.plan),console.error(`[self-heal] registered project ${o.id.slice(0,8)} with backend`),o.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&r.plan&&r.projectId&&await ho(r.projectId,r.plan),r.projectId}}async function Cc(t,e){let r=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],n=e&&e.length>0?e:r,i=Bn(t,"components","ui"),o=[],s=[];for(let c of n)go(Bn(i,`${c}.tsx`))?o.push(c):s.push(c);if(s.length===0)return{installed:[],alreadyPresent:o};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Tc("npx",["--yes","shadcn@latest","add","-y","-o",...s],t,18e4,a);return l.success?{installed:s,alreadyPresent:o}:{installed:[],alreadyPresent:o,failed:`shadcn add failed for: ${s.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Zr=I(()=>{"use strict";_e();Tt()});import{z as ct}from"zod";import{resolve as Ac,join as fo}from"path";import{existsSync as Rc,readFileSync as yo,writeFileSync as Ec}from"fs";var Nc,bo,wo=I(()=>{"use strict";be();po();Nc=ct.object({action:ct.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:ct.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:ct.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:ct.object({key:ct.string(),description:ct.string().optional(),setupUrl:ct.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),bo={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Called internally by mist_project; host AIs should use mist_project directly.",inputSchema:Nc,handler:async t=>{let e=t,r=Ac(e.projectPath??process.cwd()),n=fo(r,"mistflow.json");if(!Rc(n))return Ye(r);let i;try{i=JSON.parse(yo(n,"utf-8"))}catch{return p("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!i.projectId)try{let{ensureBackendRegistered:k}=await Promise.resolve().then(()=>(Zr(),Xr));await k(r)&&(i=JSON.parse(yo(n,"utf-8")))}catch{}let a=i.plan,l=a?.steps?.filter(k=>k.status==="completed").length??0,c=a?.steps?.length??0,u=co(fo(r,".env.local")),h=i.env?.required?Object.entries(i.env.required).map(([k,y])=>({name:k,description:y?.description,configured:u.has(k)})):[];i.projectId&&Promise.resolve().then(()=>(Tt(),dn)).then(({fetchRemoteState:k})=>k(i.projectId)).catch(()=>{});let d=[`Project: ${i.name}`];if(a){d.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let k of a.steps){let y=k.status==="completed"?"\u2713":k.status==="in_progress"?"\u2192":" ";d.push(` [${y}] ${k.number}. ${k.name}`)}}let v=h.filter(k=>!k.configured);v.length>0&&d.push(`Missing env vars: ${v.map(k=>k.name).join(", ")}`),i.deploy?.url?d.push(`Deployed: ${i.deploy.url} (${i.deploy.count??0} deploys)`):d.push("Not deployed yet");let W=[],_=a?.steps?.find(k=>k.status!=="completed");return _?W.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${_.number} (${_.name}).`):a&&l===c&&(i.deploy?.url||W.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),v.length>0&&W.push(`Missing env vars in .env.local: ${v.map(k=>k.name).join(", ")}`),p(JSON.stringify({name:i.name,projectId:i.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:c,completedSteps:l,steps:a.steps}:null,envStatus:h,deploy:i.deploy??null,contextMessage:d.join(`
|
|
41
|
+
`),nextSteps:W}))}let o=[];if(e.completedStep!==void 0){let a=i.plan;if(a?.steps){let l=a.steps.findIndex(c=>c.number===e.completedStep);if(l===-1)return p(`Step ${e.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",o.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(i.env||(i.env={required:{}}),i.env.required||(i.env.required={}),i.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},o.push(`Added required env var: ${e.addEnvVar.key}`)),Ec(n,JSON.stringify(i,null,2)+`
|
|
42
|
+
`),i.projectId&&Promise.resolve().then(()=>(Tt(),dn)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(r);c&&await l(i.projectId,c)}).catch(()=>{});let s=[];if(e.completedStep!==void 0){let l=i.plan?.steps?.find(c=>c.status!=="completed");l?s.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):s.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }) to deploy the app. Do NOT suggest localhost.")}return e.addEnvVar&&(s.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&s.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),p(JSON.stringify({updated:!0,changes:o,message:o.length>0?`Project state saved. ${o.join(". ")}.`:"No changes made.",nextSteps:s.length>0?s:void 0}))}}});function Oc(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Lt(t){let e=Mt.find(n=>n.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Mt.find(n=>{let i=n.name.toLowerCase().replace(/[^a-z0-9]/g,"");return i===r||i.includes(r)||r.includes(i)})}function Ut(t){return es[t]}function ts(t){return t?Mt.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Mt}function vo(t){let e=t??Mt,r={};for(let i of e){r[i.category]||(r[i.category]=[]);let o=es[i.id],s=o?` \u2014 ${o.description}`:"",a=o?.packages.length?` (${o.packages.join(", ")})`:"";r[i.category].push(`${i.id} \u2014 "${i.name}"${s}${a}`)}let n=[];for(let[i,o]of Object.entries(r))n.push(`**${i}**:
|
|
43
43
|
${o.map(s=>` - ${s}`).join(`
|
|
44
44
|
`)}`);return n.join(`
|
|
45
45
|
|
|
46
|
-
`)}function
|
|
46
|
+
`)}function ko(t){return(t?ts(t):Mt).map(r=>{let n=es[r.id];return{id:r.id,slug:Oc(r.name),name:r.name,category:r.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var es,Mt,zn=I(()=>{"use strict";es={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"neon-smart-search":{description:"Semantic and hybrid search using Neon Postgres, pgvector, Postgres full-text search, and embeddings.",tags:["search","semantic","vector","embedding","hybrid","rag","knowledge-base","documents"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for generating embeddings",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://neon.com/docs/extensions/pgvector",packages:["openai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},Mt=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
|
|
47
47
|
|
|
48
48
|
### File Structure
|
|
49
49
|
\`\`\`
|
|
@@ -1592,12 +1592,12 @@ export async function searchDocumentsHybrid(query: string, limit = 10) {
|
|
|
1592
1592
|
3. **Do not regenerate embeddings on every render.** Generate on create/update or in an explicit reindex action.
|
|
1593
1593
|
4. **Chunk long content.** Store chunks of 500-1,000 tokens with stable \`sourceType\`, \`sourceId\`, and \`chunkIndex\`.
|
|
1594
1594
|
5. **Use hybrid search for user-facing search.** Vector search handles meaning; full-text search protects exact names, codes, and phrases.
|
|
1595
|
-
6. **Never ask the user to paste OPENAI_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}]});import{z as
|
|
1595
|
+
6. **Never ask the user to paste OPENAI_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}]});import{z as De}from"zod";import{resolve as Hn}from"path";import{existsSync as Wn,readFileSync as Gn}from"fs";import{join as Vn}from"path";var jc,xo,So=I(()=>{"use strict";be();Ke();wo();_e();Zt();zn();jc=De.object({action:De.enum(["get","update","share","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:De.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:De.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:De.object({key:De.string(),description:De.string().optional(),setupUrl:De.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:De.string().optional().describe("(share) Short description of what this template builds"),category:De.string().optional().describe("(integrations) Filter integrations by category"),integrationId:De.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:De.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:De.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),xo={name:"mist_project",description:Es,inputSchema:jc,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!Se())return Ee(`${e.action} project state`);switch(e.action){case"get":case"update":return bo.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let n=Hn(e.projectPath??process.cwd()),i=Vn(n,"mistflow.json");if(!Wn(i))return Ye(n);let o;try{o=JSON.parse(Gn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first to register it.",!0);try{let a=await Gr(s,{isTemplate:!0,description:e.templateDescription});return p(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
|
|
1596
1596
|
|
|
1597
1597
|
Anyone can fork it: ${a.share_url}
|
|
1598
1598
|
|
|
1599
1599
|
Others can use it in their AI editor:
|
|
1600
|
-
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return
|
|
1600
|
+
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return p(l,!0)}}case"integrations":{if(e.integrationId){let s=Lt(e.integrationId);if(!s)return p(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=Ut(s.id);return p(JSON.stringify({integration:{id:s.id,name:s.name,category:s.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${s.name}" (${s.category}) \u2014 ${a?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${a?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${a?.docsUrl??"n/a"}.`}))}let n=ko(e.category??void 0),i=ts(e.category??void 0),o=vo(i);return p(JSON.stringify({count:n.length,integrations:n.map(s=>({id:s.id,name:s.name,category:s.category,description:s.description,packages:s.packages,difficulty:s.difficulty,envVars:s.envVars.map(a=>a.key)})),formatted:o,message:`${n.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let n=Hn(e.projectPath??process.cwd()),i=Vn(n,"mistflow.json");if(!Wn(i))return Ye(n);let o;try{o=JSON.parse(Gn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first.",!0);try{let a=await Mr(s,e.period??"7d");return a.total===0?p(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):p(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return p(l,!0)}}case"logs":{let n=Hn(e.projectPath??process.cwd()),i=Vn(n,"mistflow.json");if(!Wn(i))return Ye(n);let o;try{o=JSON.parse(Gn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await Ot(s);if(l.length===0)return p("No deployments found for this project.",!0);a=l[0].id}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return p(c,!0)}try{let[l,c]=await Promise.all([Dr(a),at(a)]),u=l.filter(d=>d.level==="error"),h=l.filter(d=>d.level==="warn");return p(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:u.length,warnCount:h.length,logs:l.map(d=>({time:d.timestamp,level:d.level,phase:d.phase,message:d.message})),message:c.status==="failed"?`Deployment failed. ${u.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${u.length} errors, ${h.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return p(c,!0)}}case"deployments":{let n=Hn(e.projectPath??process.cwd()),i=Vn(n,"mistflow.json");if(!Wn(i))return Ye(n);let o;try{o=JSON.parse(Gn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first.",!0);try{let a=await Ot(s);return p(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return p(l,!0)}}case"version":{wr().backendSignalReceived||await _r();let n=wr(),i=n.severity==="none",o={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return p(JSON.stringify({current:n.current,latest:n.latest||"unknown",minSupported:n.minSupported||"unknown",severity:n.severity,upToDate:i,upgradeCmd:n.upgradeCmd,changelogUrl:n.changelogUrl,backendSignalReceived:n.backendSignalReceived,message:n.backendSignalReceived?`Mistflow MCP ${n.current} (${o[n.severity]??n.severity}). Latest: ${n.latest}.${i?"":` Run \`${n.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${n.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return p(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, or version.`,!0)}}}});import{z as _t}from"zod";var Dc,To,_o=I(()=>{"use strict";Ke();be();Et();Dc=_t.object({action:_t.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:_t.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:_t.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:_t.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:_t.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:_t.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),To={name:"mist_browser",description:Ns,inputSchema:Dc,handler:async t=>{let e=t,r=await vr();if(e.action==="navigate"){if(!e.url)return p("URL is required for 'navigate'.",!0);let o=[],s=c=>{c.type()==="error"&&o.push(c.text())};r.on("console",s),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=c=>a.push(c.message);if(r.on("pageerror",l),await r.waitForTimeout(500),r.removeListener("console",s),r.removeListener("pageerror",l),o.length>0||a.length>0){let c=await en(r),u=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:o,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let h=await tn(r);u.push({type:"image",data:h.toString("base64"),mimeType:"image/png"})}return{content:u}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return p("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return p("Selector is required for 'type'.",!0);if(!e.value)return p("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return p("Selector is required for 'fill'.",!0);if(!e.value)return p("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return p("Selector is required for 'select_option'.",!0);if(!e.value)return p("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return p("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return p("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let o;if(e.selector){let s=await r.$(e.selector);if(!s)return p(`Element not found: ${e.selector}`,!0);o=await s.screenshot({type:"png"})}else o=await tn(r,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:o.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let o=await en(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}]}}let n=await en(r),i=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:n})}];if(e.includeScreenshot){let o=await tn(r);i.push({type:"image",data:o.toString("base64"),mimeType:"image/png"})}return{content:i}}}});import{z as Io}from"zod";var Po,Co,Ao=I(()=>{"use strict";Ke();be();Po=`# Mistflow MCP tool reference
|
|
1601
1601
|
|
|
1602
1602
|
Every capability is an MCP tool. There is no companion CLI. Long-running tools
|
|
1603
1603
|
(install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
|
|
@@ -1914,557 +1914,165 @@ is cheaper than building the wrong thing and iterating.
|
|
|
1914
1914
|
|
|
1915
1915
|
mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
|
|
1916
1916
|
mist_deploy({ action: "status", deploymentId }) # poll
|
|
1917
|
-
`,
|
|
1918
|
-
`),i=new RegExp(`^### \`${r}`),o=-1,s=n.length;for(let a=0;a<n.length;a++)if(i.test(n[a]))o=a;else if(o>=0&&n[a].startsWith("### ")){s=a;break}else if(o>=0&&n[a].startsWith("## ")&&a>o){s=a;break}return o<0?
|
|
1919
|
-
`).trim())}}});import{z as pn}from"zod";var
|
|
1917
|
+
`,Co={name:"mist_help",description:Os,inputSchema:Io.object({command:Io.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return p(Po);let r=e.startsWith("mist_")?e:`mist_${e}`,n=Po.split(`
|
|
1918
|
+
`),i=new RegExp(`^### \`${r}`),o=-1,s=n.length;for(let a=0;a<n.length;a++)if(i.test(n[a]))o=a;else if(o>=0&&n[a].startsWith("### ")){s=a;break}else if(o>=0&&n[a].startsWith("## ")&&a>o){s=a;break}return o<0?p(`No tool named '${r}' found. Call mist_help with no args to see the full catalog.`,!0):p(n.slice(o,s).join(`
|
|
1919
|
+
`).trim())}}});import{z as pn}from"zod";var Ro,Eo,No=I(()=>{"use strict";Ke();_e();be();Ro=pn.object({action:pn.enum(["list","get"]).default("get").describe("'get' (default) returns the full markdown for one topic \u2014 pass `topic`. 'list' returns the topic catalog so you can discover what's available \u2014 use to answer 'is there a doc for X?' before falling back to web search."),topic:pn.string().optional().describe("Required for action='get'. Stable topic id (e.g. 'auth-design', 'stripe-integration', 'better-auth'). Call action='list' to discover ids."),kind:pn.enum(["stack","skill","integration"]).optional().describe("Optional filter for action='list'. 'stack' = framework methodology, 'skill' = design + structural patterns, 'integration' = third-party services."),stack:pn.string().optional().default("nextjs").describe("Stack slug. Defaults to 'nextjs' (currently the only supported stack).")}),Eo={name:"mist_docs",description:js,inputSchema:Ro,handler:async t=>{let{action:e,topic:r,kind:n,stack:i}=Ro.parse(t);try{if(e==="list"){let a=await qr(i,n),l=[];l.push(`# Mistflow docs catalog (${a.stack})
|
|
1920
1920
|
${a.topics.length} topics. Call \`mist_docs({ action: "get", topic: "<id>" })\` to fetch one.
|
|
1921
|
-
`);let c={};for(let
|
|
1922
|
-
`).trim())}if(!r)return
|
|
1921
|
+
`);let c={};for(let h of a.topics)(c[h.kind]??=[]).push(h);let u=["stack","skill","integration"];for(let h of u){let d=c[h];if(!(!d||d.length===0)){l.push(`## ${h}`);for(let v of d)l.push(`- **${v.id}** \u2014 ${v.title}: ${v.description}`);l.push("")}}return p(l.join(`
|
|
1922
|
+
`).trim())}if(!r)return p("Missing `topic`. Pass action='get' with a topic id, or action='list' to see available topics.",!0);let o=await Br(i,r),s=`<!-- mist_docs: topic=${o.topic} kind=${o.kind} stack=${o.stack} -->
|
|
1923
1923
|
# ${o.title}
|
|
1924
1924
|
|
|
1925
1925
|
${o.description}
|
|
1926
1926
|
|
|
1927
1927
|
---
|
|
1928
1928
|
|
|
1929
|
-
`;return
|
|
1929
|
+
`;return p(s+o.content)}catch(o){if(o instanceof G&&o.statusCode===404)return p(o.message,!0);let s=o instanceof Error?o.message:String(o);return p(`mist_docs failed: ${s}
|
|
1930
1930
|
|
|
1931
|
-
If this looks like a network issue, retry. If it persists, you can fall back to reading AGENTS.md / .claude/skills/ in the user's project for the same content.`,!0)}}}});import{existsSync as Kn,mkdirSync as
|
|
1931
|
+
If this looks like a network issue, retry. If it persists, you can fall back to reading AGENTS.md / .claude/skills/ in the user's project for the same content.`,!0)}}}});import{existsSync as Kn,mkdirSync as Do,readFileSync as Mo,readdirSync as Lo,writeFileSync as Mc}from"fs";import{join as dt,resolve as Lc}from"path";import{homedir as rs}from"os";import{z as un}from"zod";function $t(t){return t.entity??t.name??"Unknown"}function Ft(t){return typeof t=="string"?t:t.name}function ns(t){return typeof t=="string"?"text":t.type}function Oo(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(i=>{let o={};for(let[s,a]of Object.entries(i))o[s]=a==null?"":String(a);return o});let r=t.fields||[],n=[];for(let i=0;i<3;i++){let o={};for(let s of r)o[Ft(s)]=Uc(Ft(s),ns(s),$t(t),i);n.push(o)}return n}function Uc(t,e,r,n){let i=t.toLowerCase(),o=(e||"text").toLowerCase();return i==="name"||i==="title"?[`${r} Alpha`,`${r} Beta`,`${r} Gamma`][n]:i==="email"?["alice@example.com","bob@example.com","carol@example.com"][n]:i==="status"?["Active","Pending","Completed"][n]:i==="priority"?["High","Medium","Low"][n]:i.includes("date")||o==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][n]:i.includes("price")||i.includes("amount")||i.includes("cost")?["$29","$49","$99"][n]:i.includes("count")||i.includes("quantity")||o==="number"||o==="integer"?["12","34","56"][n]:o==="boolean"||o==="bool"?["Yes","No","Yes"][n]:i.includes("description")||o==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function $c(t){let e=t.dataModel??[],r=t.pages??[],n=t.design??{},i=r.map(h=>({label:h.name??h.path??"Page",route:h.path??h.route??"/"})),o=[],s=e.slice(0,3).map(h=>({name:$t(h),fields:(h.fields||[]).map(d=>({name:Ft(d),type:ns(d)})),sampleData:Oo(h)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(h=>$t(h)).join(", ")}`),a.push("RECENT: Latest activity or items"),o.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(h=>$t(h)).join(", ")} with key metrics.`,informationHierarchy:a,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:s});let l=e[0];if(l){let h=$t(l),d=h.toLowerCase().endsWith("s")?h:`${h}s`;o.push({name:`${h} List`,type:"detail",route:`/${d.toLowerCase()}`,purpose:`Browse, search, and manage ${d.toLowerCase()}. Create new ${h.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${d}" title + "Add ${h}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(v=>Ft(v)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${d.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${d.toLowerCase()} matching..." with clear filter`],entities:[{name:h,fields:(l.fields||[]).map(v=>({name:Ft(v),type:ns(v)})),sampleData:Oo(l)}]})}t.steps.some(h=>{let d=`${h.name??h.title??""} ${h.description??""}`.toLowerCase();return d.includes("landing")||d.includes("hero")||d.includes("marketing")||d.includes("homepage")})&&o.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let u=[];for(let h of e.slice(0,3)){let d=$t(h);(h.fields||[]).find(W=>{let _=Ft(W).toLowerCase();return _==="name"||_==="title"})&&u.push(`What if a ${d.toLowerCase()}'s name is 47 characters? Does the layout break?`),u.push(`What if there are 0 ${d.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&u.push("What does a brand-new user see? (no data, no setup)"),u.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:o,navigation:{style:t.navStyle??"sidebar",items:i},primaryAction:t.primaryAction??null,designDirection:{tone:n.tone??"professional",accentColor:n.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:n.fonts??{heading:"Inter",body:"Inter"}},edgeCases:u}}function Fc(t,e,r){let n=[];n.push(`# Wireframe sketch for ${t.appName}`),n.push(""),n.push(`**${t.appName}** \u2014 ${t.summary}`),n.push(""),e&&(n.push("## Feedback to apply"),n.push(e),n.push("")),n.push("## Design principles"),n.push(""),n.push("Apply these when deciding layout and hierarchy:"),n.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),n.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),n.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),n.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),n.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),n.push(""),n.push("## Wireframe rules (strict)"),n.push(""),n.push(`Write a **single self-contained HTML file** saved to \`${r}\`.`),n.push(""),n.push("The wireframe must:"),n.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),n.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),n.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),n.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),n.push("- Include **HTML comments** explaining design decisions"),n.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),n.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),n.push("- Include a small header bar showing: screen name tabs + the design direction summary"),n.push(""),n.push("The wireframe must NOT:"),n.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),n.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),n.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),n.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),n.push(""),n.push("## Screens to wireframe"),n.push("");for(let i of t.screens){n.push(`### ${i.name} (\`${i.route}\`)`),n.push(`**Purpose**: ${i.purpose}`),n.push(""),n.push("**Information hierarchy** (render in this order, top to bottom):");for(let o of i.informationHierarchy)n.push(`- ${o}`);n.push(""),n.push("**Interaction states** (add HTML comments for non-visible states):");for(let o of i.interactionStates)n.push(`- ${o}`);if(n.push(""),i.entities.length>0){n.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let o of i.entities)n.push(`
|
|
1932
1932
|
**${o.name}** \u2014 fields: ${o.fields.map(s=>`${s.name} (${s.type})`).join(", ")}`),n.push("```json"),n.push(JSON.stringify(o.sampleData,null,2)),n.push("```");n.push("")}}n.push("## Navigation"),n.push(`**Style**: ${t.navigation.style} (use this layout)`),n.push("**Items**:");for(let i of t.navigation.items)n.push(`- ${i.label} \u2192 \`${i.route}\``);if(n.push(""),t.primaryAction&&(n.push("## Primary action (this drives the layout)"),n.push(`- **Action**: ${t.primaryAction.action}`),n.push(`- **Flow**: ${t.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),n.push(""),n.push("The dashboard is an ACTION surface. The primary action should be the most prominent thing on the page \u2014 above the metrics, above the recent items. Users came here to DO something, not to look at numbers."),n.push("")),t.edgeCases.length>0){n.push("## Edge cases to consider"),n.push("Add HTML comments in the wireframe where these matter:");for(let i of t.edgeCases)n.push(`- ${i}`);n.push("")}return n.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),n.push(`The final app will use: ${t.designDirection.tone} tone, ${t.designDirection.accentColor} accent, ${t.designDirection.navStyle} nav, ${t.designDirection.fonts.heading} / ${t.designDirection.fonts.body} fonts.`),n.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),n.push(""),n.push("## After writing the wireframe"),n.push(`1. Write the file to \`${r}\``),n.push(`2. Open it for the user: \`open "${r}"\``),n.push(`3. Tell the user: "Here's a rough wireframe of your app. Does the layout feel right? Let me know what to change, or I can start building if it's close."`),n.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),n.join(`
|
|
1933
|
-
`)}function
|
|
1934
|
-
${i.message}`})}),r.on("close",i=>{e({exitCode:i??1,combined:n})})})}var
|
|
1935
|
-
Recommended: ${s.recommended}`:""}`:s.recommended?`Recommended: ${s.recommended}`:void 0,enum:
|
|
1936
|
-
`)}function
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
content: "";
|
|
1940
|
-
position: absolute;
|
|
1941
|
-
inset: 0;
|
|
1942
|
-
pointer-events: none;
|
|
1943
|
-
z-index: 0;
|
|
1944
|
-
opacity: 0;
|
|
1945
|
-
mix-blend-mode: overlay;
|
|
1946
|
-
}
|
|
1947
|
-
.card-hero > * { position: relative; z-index: 1; }
|
|
1948
|
-
|
|
1949
|
-
.card-hero.texture-flat::before { opacity: 0; }
|
|
1950
|
-
|
|
1951
|
-
.card-hero.texture-paper-grain::before {
|
|
1952
|
-
opacity: 0.35;
|
|
1953
|
-
background-image: ${t};
|
|
1954
|
-
mix-blend-mode: multiply;
|
|
1955
|
-
}
|
|
1956
|
-
.card-hero.texture-film-grain::before {
|
|
1957
|
-
opacity: 0.5;
|
|
1958
|
-
background-image: ${t};
|
|
1959
|
-
mix-blend-mode: overlay;
|
|
1960
|
-
}
|
|
1961
|
-
.card-hero.texture-noise::before {
|
|
1962
|
-
opacity: 0.25;
|
|
1963
|
-
background-image: ${t};
|
|
1964
|
-
mix-blend-mode: overlay;
|
|
1965
|
-
}
|
|
1966
|
-
.card-hero.texture-scanlines::before {
|
|
1967
|
-
opacity: 0.4;
|
|
1968
|
-
background: repeating-linear-gradient(
|
|
1969
|
-
to bottom,
|
|
1970
|
-
rgba(255,255,255,0.08) 0 1px,
|
|
1971
|
-
transparent 1px 3px
|
|
1972
|
-
);
|
|
1973
|
-
mix-blend-mode: screen;
|
|
1974
|
-
}
|
|
1975
|
-
.card-hero.texture-gradient-mesh::before {
|
|
1976
|
-
opacity: 1;
|
|
1977
|
-
background:
|
|
1978
|
-
radial-gradient(circle at 15% 20%, rgba(255,255,255,0.18), transparent 48%),
|
|
1979
|
-
radial-gradient(circle at 85% 80%, rgba(0,0,0,0.22), transparent 55%),
|
|
1980
|
-
radial-gradient(circle at 60% 10%, rgba(255,255,255,0.12), transparent 40%);
|
|
1981
|
-
mix-blend-mode: normal;
|
|
1982
|
-
}
|
|
1983
|
-
.card-hero.texture-glassmorphic {
|
|
1984
|
-
position: relative;
|
|
1985
|
-
}
|
|
1986
|
-
.card-hero.texture-glassmorphic::before {
|
|
1987
|
-
opacity: 1;
|
|
1988
|
-
background:
|
|
1989
|
-
radial-gradient(circle at 20% 30%, rgba(255,255,255,0.25), transparent 42%),
|
|
1990
|
-
radial-gradient(circle at 80% 70%, rgba(255,255,255,0.15), transparent 45%);
|
|
1991
|
-
backdrop-filter: blur(14px);
|
|
1992
|
-
mix-blend-mode: normal;
|
|
1993
|
-
}
|
|
1994
|
-
`}function md(t,e,r,n){let i=qt(t.colors?.bg??"","#0f0f0f"),o=qt(t.colors?.fg??"","#f5f5f5"),s=qt(t.colors?.accent??"","#7c9cff"),a=Se(t.name),l=Se(t.hero_headline||t.name),c=Se(t.body_sample||t.summary||""),h=Se(t.cta_text||"Continue"),p=`<div class="hero-eyebrow" style="font-family:${r}">${a.toUpperCase()}</div>`,u=`<h2 class="hero-headline" style="font-family:${e}">${l}</h2>`,w=`<p class="hero-body" style="font-family:${r}">${c}</p>`,O=`<button class="hero-cta" style="background:${s};color:${i};font-family:${r};border-radius:${n.button}">${h}</button>`,k=uo(t.hero_treatment,ad,"typographic");if(k==="terminal"){let b=`"${(t.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
|
|
1995
|
-
${p}
|
|
1996
|
-
<div class="hero-terminal-lines" style="font-family:${b};color:${o}">
|
|
1997
|
-
<div>$ status --all</div>
|
|
1998
|
-
<div>api.service.......<span style="color:${s}">OK</span></div>
|
|
1999
|
-
<div>worker.queue......<span style="color:${s}">OK</span></div>
|
|
2000
|
-
<div>db.primary.......<span style="color:${s}">OK</span></div>
|
|
2001
|
-
</div>
|
|
2002
|
-
${u}
|
|
2003
|
-
${w}
|
|
2004
|
-
<div class="hero-cta-row">${O}</div>
|
|
2005
|
-
`}return k==="split-panel"?`
|
|
2006
|
-
<div class="hero-split">
|
|
2007
|
-
<div class="hero-split-left" style="background:${s};color:${i};font-family:${e}">
|
|
2008
|
-
<div class="hero-split-mark" style="font-family:${r};color:${i}">${a[0]??"\xB7"}</div>
|
|
2009
|
-
</div>
|
|
2010
|
-
<div class="hero-split-right">
|
|
2011
|
-
${p}
|
|
2012
|
-
${u}
|
|
2013
|
-
${w}
|
|
2014
|
-
<div class="hero-cta-row">${O}</div>
|
|
2015
|
-
</div>
|
|
2016
|
-
</div>
|
|
2017
|
-
`:k==="full-bleed-photo"?`
|
|
2018
|
-
<div class="hero-photo" style="background: linear-gradient(160deg, ${s}30 0%, ${o}08 35%, ${i} 100%), ${i}">
|
|
2019
|
-
<span class="hero-photo-label" style="font-family:${r};color:${o}">photo slot</span>
|
|
2020
|
-
</div>
|
|
2021
|
-
${p}
|
|
2022
|
-
${u}
|
|
2023
|
-
${w}
|
|
2024
|
-
<div class="hero-cta-row">${O}</div>
|
|
2025
|
-
`:k==="magazine-hero"?`
|
|
2026
|
-
${p}
|
|
2027
|
-
<h2 class="hero-headline hero-headline-mag" style="font-family:${e}">${l}</h2>
|
|
2028
|
-
<div class="hero-rule" style="background:${o}"></div>
|
|
2029
|
-
<p class="hero-body hero-body-mag" style="font-family:${r}">${c}</p>
|
|
2030
|
-
<div class="hero-byline" style="font-family:${r};color:${o}">\u2014 Volume 01 \xB7 Issue 01</div>
|
|
2031
|
-
<div class="hero-cta-row">${O}</div>
|
|
2032
|
-
`:`
|
|
2033
|
-
${p}
|
|
2034
|
-
${u}
|
|
2035
|
-
${w}
|
|
2036
|
-
<div class="hero-cta-row">${O}</div>
|
|
2037
|
-
`}function Zs(t,e,r){let n=dd(e),i=e.map(o=>{let s=qt(o.colors?.bg??"","#0f0f0f"),a=qt(o.colors?.fg??"","#f5f5f5"),l=qt(o.colors?.accent??"","#7c9cff"),c=Xs(o.fonts?.display??""),h=Xs(o.fonts?.body??""),p=uo(o.shape_lang,ld,"soft"),u=uo(o.texture,cd,"flat"),w=pd(p),O=o.mockup_b64?`<img class="card-hero-mockup" src="data:image/png;base64,${o.mockup_b64}" alt="${Se(o.name)} mockup" />`:md(o,c,h,w),k=Se(o.name),b=Se(o.id),y=Se(o.fonts?.display??""),I=Se(o.fonts?.body??""),B=Se(o.summary||""),U=Se(o.decoration_hint||""),M=(de,K)=>`<div class="card-meta-row"><span class="card-meta-label">${de}</span><span class="card-meta-value">${K}</span></div>`;return` <article class="card" data-direction-id="${b}" style="border-radius:${w.card}">
|
|
2038
|
-
<div class="card-hero texture-${u}" style="background:${s};color:${a}">${O}
|
|
2039
|
-
</div>
|
|
2040
|
-
<div class="card-meta" style="border-top-color:${a}14">
|
|
2041
|
-
<div class="card-meta-title">${k}</div>
|
|
2042
|
-
<p class="card-meta-summary">${B}</p>
|
|
2043
|
-
${M("Fonts",`${y||"\u2014"} <span class="sep">\xB7</span> ${I||"\u2014"}`)}
|
|
2044
|
-
${M("Palette",`
|
|
2045
|
-
<span class="card-meta-swatches">
|
|
2046
|
-
<span class="card-meta-swatch" title="${s}" style="background:${s}"></span>
|
|
2047
|
-
<span class="card-meta-swatch" title="${a}" style="background:${a}"></span>
|
|
2048
|
-
<span class="card-meta-swatch" title="${l}" style="background:${l}"></span>
|
|
2049
|
-
</span>
|
|
2050
|
-
`)}
|
|
2051
|
-
${M("Shape",`<span class="chip" style="border-radius:${w.chip}">${p}</span>`)}
|
|
2052
|
-
${M("Texture",`<span class="chip" style="border-radius:${w.chip}">${Se(u)}</span>`)}
|
|
2053
|
-
${U?M("Decoration",Se(U)):""}
|
|
2054
|
-
${M("Pick with",`<code>${k}</code>`)}
|
|
2055
|
-
</div>
|
|
2056
|
-
</article>`}).join(`
|
|
2057
|
-
`);return`<!DOCTYPE html>
|
|
1933
|
+
`)}function Uo(t){return dt(rs(),".mistflow","mockup-state",`${t}.json`)}function qc(t){let e=Uo(t);if(!Kn(e))return null;try{return JSON.parse(Mo(e,"utf-8"))}catch{return null}}function jo(t,e){let r=dt(rs(),".mistflow","mockup-state");Do(r,{recursive:!0}),Mc(Uo(t),JSON.stringify(e,null,2))}function Fo(t){let e=dt(t,".mistflow","mockups");return Kn(e)?Lo(e).filter(r=>r.endsWith(".html")).map(r=>dt(e,r)):[]}var Bc,$o,ss=I(()=>{"use strict";Ke();be();Bc=un.object({planId:un.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:un.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:un.string().optional().describe("User feedback to apply to the next iteration."),approved:un.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(t=>!(t.feedback&&t.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),$o={name:"mist_mockup",description:Ms,inputSchema:Bc,handler:async t=>{let e=t,{planId:r,feedback:n,approved:i}=e,o=Lc(e.projectPath??process.cwd()),s=dt(rs(),".mistflow","plans",`${r}.json`);if(!Kn(s))return p(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(Mo(s,"utf-8"))}catch{return p("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return p("Plan data is empty. Call mist_plan again.",!0);let c=qc(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let u=dt(o,".mistflow","mockups");Do(u,{recursive:!0});let h=`mockup-${r}.html`,d=dt(u,h);if(i){c.approved=!0,jo(r,c);let y=Kn(u)?Lo(u).filter(A=>A.endsWith(".html")).map(A=>dt(".mistflow","mockups",A)):[];return p(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:y,nextAction:`Call mist_init with planId='${r}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}c.iterationCount++,n&&c.feedback.push(n);let v=$c(l);c.screens=v.screens.map(y=>y.name),jo(r,c);let W=Fc(v,n??void 0,d),_=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,k=n?`Apply the user's feedback to ${d}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${d}, then open it in the browser. Ask the user if the layout feels right.`;return p(JSON.stringify({status:"wireframe",requires_user_input:!0,iterationCount:c.iterationCount,screens:v.screens.map(y=>({name:y.name,type:y.type,route:y.route})),wireframePrompt:W,designDirection:v.designDirection,..._?{nudge:_}:{},mockupFile:h,mockupPath:d,nextAction:k}))}}});function Jn(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,c,u,h,d]=a;e.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:`${h}: ${d}`,humanMessage:`There is a type error in ${l} on line ${c}: ${d}`,suggestion:`Check line ${c} in ${l}. ${h==="TS2345"?"The types of the arguments do not match.":`Fix the ${h} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(n)){let[,l,c,u,h]=a;e.some(d=>d.file===l&&d.line===parseInt(c,10))||e.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:h,humanMessage:`There is an error in ${l} on line ${c}: ${h.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let i=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of t.matchAll(i)){let[,l,c]=a;e.push({file:c,message:`Module not found: ${l}`,humanMessage:`The file ${c??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let o=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(o)){let[,l,c]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${c}${l}`,humanMessage:`The package '${c}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${c}'.`,suggestion:`Add '${c}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let s=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of t.matchAll(s)){let[,l,c,u,h]=a;e.some(d=>d.file===l&&d.line===parseInt(u,10))||e.push({file:l,line:parseInt(u,10),column:parseInt(h,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${u}.`,suggestion:`Check line ${u} in ${l} for a missing closing bracket or unexpected token.`})}return e}var os=I(()=>{"use strict"});import{z as is}from"zod";import{resolve as zc}from"path";import{spawn as Hc}from"child_process";function Gc(t){return new Promise(e=>{let r=Hc("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),n="";r.stdout?.on("data",i=>{n+=i.toString()}),r.stderr?.on("data",i=>{n+=i.toString()}),r.on("error",i=>{e({exitCode:127,combined:`${n}
|
|
1934
|
+
${i.message}`})}),r.on("close",i=>{e({exitCode:i??1,combined:n})})})}var Wc,qo,Bo=I(()=>{"use strict";Ke();be();os();Wc=is.object({projectPath:is.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:is.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});qo={name:"mist_debug",description:Ds,inputSchema:Wc,handler:async t=>{let e=t,r=zc(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let s=await Gc(r);if(s.exitCode===0)return p(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=s.combined}let i=Jn(n),o=n.slice(0,2e3);return i.length===0?p(JSON.stringify({errors:i,rawOutput:o,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):p(JSON.stringify({errors:i,rawOutput:o,message:`Found ${i.length} error${i.length===1?"":"s"} in the build output.`}))}}});import{spawn as Vc}from"child_process";function as(t){if(process.env.MISTFLOW_AUTO_OPEN_PICKER==="false")return{opened:!1,reason:"MISTFLOW_AUTO_OPEN_PICKER=false"};let e;try{e=new URL(t)}catch{return{opened:!1,reason:"invalid URL"}}if(e.protocol!=="http:"&&e.protocol!=="https:"&&e.protocol!=="file:")return{opened:!1,reason:`unsupported protocol ${e.protocol}`};if(Kc())return{opened:!1,reason:"headless environment detected"};let r=process.platform,n,i;r==="darwin"?(n="open",i=[e.href]):r==="win32"?(n="cmd",i=["/c","start","",e.href]):(n="xdg-open",i=[e.href]);try{let o=Vc(n,i,{shell:!1,stdio:"ignore",detached:!0});return o.on("error",()=>{}),o.unref(),{opened:!0}}catch(o){return{opened:!1,reason:o instanceof Error?o.message:"spawn failed"}}}function Kc(){if(process.env.SSH_TTY||process.env.SSH_CONNECTION)return!0;for(let t of["CI","BUILDKITE","GITHUB_ACTIONS","CIRCLECI","GITLAB_CI"])if(process.env[t])return!0;return process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY&&!process.env.WSL_DISTRO_NAME}var zo=I(()=>{"use strict"});function qe(t,e,r,n=3e3){if(e===void 0)return{stop:()=>{}};let i=0,o=!1,a=setInterval(()=>{o||(i++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:i,message:r()}}).catch(()=>{}))},n);return{stop:()=>{o||(o=!0,clearInterval(a))}}}var qt=I(()=>{"use strict"});function Jc(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function Yc(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function Qc(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function Xc(t){let e={},r=[],n=[],i=new Set;for(let o=0;o<t.length;o++){let s=t[o],a=s.decisionKey?Qc(s.decisionKey):`q_${o+1}`,l=a,c=2;for(;i.has(l);)l=`${a}_${c}`,c++;i.add(l);let u=s.freetext?"":`${l}_other`;if(u&&i.add(u),n.push({primary:l,other:u,question:s}),s.freetext){e[l]={type:"string",title:s.question,description:s.why,...s.recommended?{default:s.recommended}:{}},r.push(l);continue}let h=(s.options??[]).map(v=>typeof v=="string"?v:v.label),d=s.noOtherSentinel?[...h]:[...h,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:s.question,description:s.why?`${s.why}${s.recommended?`
|
|
1935
|
+
Recommended: ${s.recommended}`:""}`:s.recommended?`Recommended: ${s.recommended}`:void 0,enum:d,enumNames:d,...s.recommended&&h.includes(s.recommended)?{default:s.recommended}:{}},r.push(l),e[u]={type:"string",title:s.otherFieldTitle??"If 'Other' selected above: type your answer",description:"Leave blank if you picked an option from the list."}}return{schema:{type:"object",properties:e,required:r},fieldKeys:n}}function Zc(t,e){let r=[],n;for(let{primary:i,other:o,question:s}of e){let a=String(t[i]??"").trim(),l;if(s.freetext)l=a||s.recommended||"";else{let u=o?String(t[o]??"").trim():"",h=a.toLowerCase(),d=h.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(h);u?l=u:d?l=s.recommended??(s.options?.[0]&&typeof s.options[0]=="object"?s.options[0].label:"")??a:l=a}let c=s.decisionKey??"";if(c==="urlChoice"){n=l;continue}r.push({question:s.question,decisionKey:c,answer:l})}return{answers:r,urlChoice:n}}function Qe(t,e,r){let n;switch(r.outcome){case"submitted":n=`submitted (${r.answers?.length??0} answers${r.urlChoice?`, urlChoice="${r.urlChoice}"`:""})`;break;case"error":n=`error (${r.errorMessage??"unknown"})`;break;case"unsupported":n=`unsupported (${e})`;break;default:n=r.outcome}console.error(`[mist_plan] elicitation/${t}: ${n}`)}async function mn(t,e,r,n="discovery"){if(Yc()){let u={outcome:"unsupported"};return Qe(n,"MISTFLOW_ELICITATION kill switch on",u),u}if(!Jc(t)){let u={outcome:"unsupported"};return Qe(n,"client did not declare elicitation capability",u),u}if(e.length===0){let u={outcome:"submitted",answers:[]};return Qe(n,"no questions to ask",u),u}let{schema:i,fieldKeys:o}=Xc(e),s;try{s=await t.elicitInput({message:r,requestedSchema:i,mode:"form"},{timeout:300*1e3})}catch(u){let h=u instanceof Error?u.message:String(u);if(h.toLowerCase().includes("not support")){let v={outcome:"unsupported"};return Qe(n,`SDK rejected form mode: ${h}`,v),v}let d={outcome:"error",errorMessage:h};return Qe(n,"",d),d}if(s.action==="decline"){let u={outcome:"declined"};return Qe(n,"",u),u}if(s.action==="cancel"){let u={outcome:"cancelled"};return Qe(n,"",u),u}if(s.action!=="accept"||!s.content){let u={outcome:"error",errorMessage:`Unexpected elicitation result: ${s.action}`};return Qe(n,"",u),u}let{answers:a,urlChoice:l}=Zc(s.content,o),c={outcome:"submitted",answers:a,urlChoice:l};return Qe(n,"",c),c}var Ho=I(()=>{"use strict"});function Wo(t,e,r){let n=r?.suggestedName||td(t),i=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",o=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),s=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",a;if(r?.suggestedFeatures&&r.suggestedFeatures.length>0)a=r.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;a=[];for(let c of ed){let u=c.keywords.test(l),h=c.condition(e);(u||h)&&a.push({name:c.name,description:c.description,checked:u,source:u?"explicit":"suggested"})}}return{name:n,audience:i,audienceType:o,surfaceType:s,primaryAction:e.primaryAction||"manage items",features:a,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:r?.language||"English"}}function Go(t){let e=t.features.filter(a=>a.checked),r=t.features.filter(a=>!a.checked),n={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},i={neon:"Postgres",turso:"SQLite (legacy)"},o={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},s=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${o[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${n[t.authModel]??t.authModel} | Database: ${i[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){s.push("**Included:**");for(let a of e)s.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(s.push(""),s.push(`**Integrations:** ${t.integrations.join(", ")}`)),r.length>0){s.push(""),s.push("**Available to add:**");for(let a of r)s.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return s.join(`
|
|
1936
|
+
`)}function td(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return Yn(e[1]);let r=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),i=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(o=>o.length>2&&!r.has(o)).slice(0,3);return i.length===0?"my-app":i.join("-")}function Yn(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var ed,Vo=I(()=>{"use strict";ed=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:t=>t.surfaceType==="internal-tool"||t.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:t=>t.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:t=>t.scheduling===!0,keywords:/\b(schedul|book|reserv|appointment|calendar|slot)\b/i},{name:"Payments / Billing",description:"Charge users, invoices, subscriptions (experimental \u2014 Stripe integration is early-stage)",condition:()=>!1,keywords:/\b(payment|billing|invoice|subscription|checkout|stripe)\b/i},{name:"Admin Panel",description:"Manage users, roles, and content",condition:t=>t.multiRole===!0||t.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:t=>t.primaryActor==="customers"||t.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:t=>t.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:t=>t.integrations?.includes("email")===!0,keywords:/\b(notification|alert|reminder|email.?notif|sms|welcome.?email)\b/i},{name:"Analytics / Reports",description:"Usage stats, trends, data exports",condition:()=>!1,keywords:/\b(analytics|report|chart|trend|insight|metric)\b/i},{name:"File Uploads",description:"Images, documents, attachments",condition:t=>t.integrations?.includes("file-uploads")===!0,keywords:/\b(upload|image|photo|attachment|document|gallery|file)\b/i},{name:"AI Features",description:"Chatbot, content generation, AI assistant",condition:t=>t.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:t=>t.integrations?.includes("maps")===!0,keywords:/\b(map|location|address|geo|places)\b/i},{name:"Voice / TTS",description:"Text-to-speech, voice notes, audio generation",condition:()=>!1,keywords:/\b(voice|tts|text.?to.?speech|audio|speak|narrat|podcast|elevenlabs)\b/i},{name:"SMS / Text Messages",description:"Send SMS notifications, OTP verification",condition:t=>t.integrations?.includes("sms")===!0,keywords:/\b(sms|text.?message|twilio|otp|verification.?code|phone.?verif)\b/i},{name:"Web Scraping",description:"Scrape URLs, crawl websites, extract structured data",condition:()=>!1,keywords:/\b(scrape|crawl|web.?scrap|extract.?from.?url|read.?url|ingest.?web|firecrawl)\b/i},{name:"Chat / Messaging",description:"Real-time messaging between users",condition:()=>!1,keywords:/\b(chat|messag|inbox|conversation|dm)\b/i},{name:"Events / Tournaments",description:"Create and manage events, registrations",condition:()=>!1,keywords:/\b(event|tournament|competition|league|registration)\b/i},{name:"High Scores",description:"Track and display top scores with a leaderboard",condition:t=>t.surfaceType==="game",keywords:/\b(high.?score|leaderboard|top.?score|ranking|scoreboard)\b/i},{name:"Save Progress",description:"Save and resume game state between sessions",condition:t=>t.surfaceType==="game",keywords:/\b(save|progress|resume|checkpoint|continue)\b/i},{name:"Guest Play",description:"Play immediately without signing up, optionally link account later",condition:t=>t.surfaceType==="game",keywords:/\b(guest|anonymous|no.?login|play.?now|instant.?play)\b/i},{name:"Levels / Stages",description:"Progressive difficulty with unlockable stages",condition:()=>!1,keywords:/\b(level|stage|unlock|difficult|progress|world)\b/i},{name:"Achievements",description:"Badges, trophies, and milestones for player accomplishments",condition:()=>!1,keywords:/\b(achieve|badge|trophy|milestone|reward|unlock)\b/i},{name:"Daily Challenge",description:"New puzzle or challenge every day to keep players coming back",condition:()=>!1,keywords:/\b(daily|challenge|streak|word.?of.?the.?day|puzzle.?of)\b/i}]});function ls(t,e,r){let n=hn(t||"your app"),i=e.map((s,a)=>{let l=Qn(s.id||`direction-${a}`),c=hn(s.name||`Direction ${a+1}`),u=hn(s.summary||"");return`<button class="tab${a===0?" active":""}" data-target="${l}" type="button"><span class="tab-name">${c}</span>${u?`<span class="tab-sub">${u}</span>`:""}</button>`}).join(`
|
|
1937
|
+
`),o=e.map((s,a)=>{let l=Qn(s.id||`direction-${a}`),c=r[s.id??""]??"";return`<iframe class="render-frame${a===0?" active":""}" data-id="${l}" srcdoc="${Qn(c)}" sandbox="allow-same-origin allow-scripts" title="${Qn(s.name||`Direction ${a+1}`)}"></iframe>`}).join(`
|
|
1938
|
+
`);return`<!doctype html>
|
|
2058
1939
|
<html lang="en">
|
|
2059
1940
|
<head>
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
:
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
}
|
|
2136
|
-
p.page-sub { color: var(--chrome-muted); font-size: 16px; margin: 0; max-width: 680px; }
|
|
2137
|
-
p.page-sub strong { color: var(--chrome-ink); font-weight: 600; }
|
|
2138
|
-
.grid {
|
|
2139
|
-
display: grid;
|
|
2140
|
-
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
2141
|
-
gap: 28px;
|
|
2142
|
-
}
|
|
2143
|
-
@media (max-width: 920px) {
|
|
2144
|
-
.grid { grid-template-columns: 1fr; gap: 20px; }
|
|
2145
|
-
.page { padding: 36px 18px 72px; }
|
|
2146
|
-
}
|
|
2147
|
-
|
|
2148
|
-
/* \u2500\u2500 Card shell \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2149
|
-
.card {
|
|
2150
|
-
background: #fff;
|
|
2151
|
-
box-shadow: var(--card-shadow);
|
|
2152
|
-
overflow: hidden;
|
|
2153
|
-
display: flex;
|
|
2154
|
-
flex-direction: column;
|
|
2155
|
-
transition: transform 180ms ease, box-shadow 180ms ease;
|
|
2156
|
-
}
|
|
2157
|
-
.card:hover {
|
|
2158
|
-
transform: translateY(-2px);
|
|
2159
|
-
box-shadow: 0 1px 2px rgba(0,0,0,0.05), 0 28px 56px -20px rgba(0,0,0,0.18);
|
|
2160
|
-
}
|
|
2161
|
-
|
|
2162
|
-
/* \u2500\u2500 Hero block \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2163
|
-
.card-hero {
|
|
2164
|
-
padding: 40px 36px 32px;
|
|
2165
|
-
min-height: 380px;
|
|
2166
|
-
display: flex;
|
|
2167
|
-
flex-direction: column;
|
|
2168
|
-
gap: 12px;
|
|
2169
|
-
}
|
|
2170
|
-
.hero-eyebrow {
|
|
2171
|
-
font-size: 11px;
|
|
2172
|
-
letter-spacing: 0.18em;
|
|
2173
|
-
opacity: 0.7;
|
|
2174
|
-
font-weight: 500;
|
|
2175
|
-
}
|
|
2176
|
-
.hero-headline {
|
|
2177
|
-
font-size: clamp(30px, 2.8vw, 42px);
|
|
2178
|
-
line-height: 1.05;
|
|
2179
|
-
letter-spacing: -0.01em;
|
|
2180
|
-
margin: 0;
|
|
2181
|
-
font-weight: 700;
|
|
2182
|
-
}
|
|
2183
|
-
.hero-body {
|
|
2184
|
-
font-size: 15px;
|
|
2185
|
-
line-height: 1.55;
|
|
2186
|
-
opacity: 0.85;
|
|
2187
|
-
margin: 0;
|
|
2188
|
-
max-width: 44ch;
|
|
2189
|
-
}
|
|
2190
|
-
.hero-cta-row {
|
|
2191
|
-
margin-top: auto;
|
|
2192
|
-
padding-top: 20px;
|
|
2193
|
-
display: flex;
|
|
2194
|
-
align-items: center;
|
|
2195
|
-
gap: 12px;
|
|
2196
|
-
flex-wrap: wrap;
|
|
2197
|
-
}
|
|
2198
|
-
.hero-cta {
|
|
2199
|
-
border: 0;
|
|
2200
|
-
padding: 12px 22px;
|
|
2201
|
-
font-size: 14px;
|
|
2202
|
-
font-weight: 600;
|
|
2203
|
-
cursor: default;
|
|
2204
|
-
letter-spacing: 0.01em;
|
|
2205
|
-
}
|
|
2206
|
-
|
|
2207
|
-
/* \u2500\u2500 Hero treatment: terminal \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2208
|
-
.hero-terminal-lines {
|
|
2209
|
-
font-size: 13px;
|
|
2210
|
-
line-height: 1.7;
|
|
2211
|
-
opacity: 0.85;
|
|
2212
|
-
padding: 12px 14px;
|
|
2213
|
-
border: 1px solid currentColor;
|
|
2214
|
-
border-opacity: 0.3;
|
|
2215
|
-
background: rgba(0,0,0,0.18);
|
|
2216
|
-
margin-bottom: 6px;
|
|
2217
|
-
}
|
|
2218
|
-
.hero-terminal-lines > div { white-space: pre; }
|
|
2219
|
-
|
|
2220
|
-
/* \u2500\u2500 Hero treatment: split-panel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2221
|
-
.hero-split {
|
|
2222
|
-
display: flex;
|
|
2223
|
-
flex: 1;
|
|
2224
|
-
margin: -40px -36px -32px;
|
|
2225
|
-
min-height: 380px;
|
|
2226
|
-
}
|
|
2227
|
-
.hero-split-left {
|
|
2228
|
-
width: 32%;
|
|
2229
|
-
display: flex;
|
|
2230
|
-
align-items: center;
|
|
2231
|
-
justify-content: center;
|
|
2232
|
-
padding: 24px;
|
|
2233
|
-
}
|
|
2234
|
-
.hero-split-mark {
|
|
2235
|
-
font-size: 96px;
|
|
2236
|
-
font-weight: 800;
|
|
2237
|
-
line-height: 1;
|
|
2238
|
-
}
|
|
2239
|
-
.hero-split-right {
|
|
2240
|
-
flex: 1;
|
|
2241
|
-
padding: 40px 36px 32px;
|
|
2242
|
-
display: flex;
|
|
2243
|
-
flex-direction: column;
|
|
2244
|
-
gap: 12px;
|
|
2245
|
-
}
|
|
2246
|
-
|
|
2247
|
-
/* \u2500\u2500 Hero treatment: full-bleed-photo \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2248
|
-
.hero-photo {
|
|
2249
|
-
height: 160px;
|
|
2250
|
-
margin: -40px -36px 20px;
|
|
2251
|
-
position: relative;
|
|
2252
|
-
display: flex;
|
|
2253
|
-
align-items: flex-end;
|
|
2254
|
-
justify-content: flex-start;
|
|
2255
|
-
padding: 18px;
|
|
2256
|
-
}
|
|
2257
|
-
.hero-photo-label {
|
|
2258
|
-
font-size: 10px;
|
|
2259
|
-
letter-spacing: 0.2em;
|
|
2260
|
-
text-transform: uppercase;
|
|
2261
|
-
opacity: 0.4;
|
|
2262
|
-
}
|
|
2263
|
-
|
|
2264
|
-
/* \u2500\u2500 Hero treatment: magazine-hero \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2265
|
-
.hero-headline-mag {
|
|
2266
|
-
font-size: clamp(34px, 3.2vw, 48px);
|
|
2267
|
-
font-weight: 700;
|
|
2268
|
-
letter-spacing: -0.02em;
|
|
2269
|
-
}
|
|
2270
|
-
.hero-rule {
|
|
2271
|
-
height: 2px;
|
|
2272
|
-
width: 48px;
|
|
2273
|
-
margin: 8px 0;
|
|
2274
|
-
opacity: 0.8;
|
|
2275
|
-
}
|
|
2276
|
-
.hero-body-mag {
|
|
2277
|
-
font-style: italic;
|
|
2278
|
-
max-width: 40ch;
|
|
2279
|
-
}
|
|
2280
|
-
.hero-byline {
|
|
2281
|
-
font-size: 11px;
|
|
2282
|
-
letter-spacing: 0.16em;
|
|
2283
|
-
text-transform: uppercase;
|
|
2284
|
-
opacity: 0.6;
|
|
2285
|
-
margin-top: 4px;
|
|
2286
|
-
}
|
|
2287
|
-
|
|
2288
|
-
${ud()}
|
|
2289
|
-
|
|
2290
|
-
/* \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 */
|
|
2291
|
-
.card-meta {
|
|
2292
|
-
padding: 22px 28px 26px;
|
|
2293
|
-
border-top: 1px solid var(--chrome-rule);
|
|
2294
|
-
display: flex;
|
|
2295
|
-
flex-direction: column;
|
|
2296
|
-
gap: 10px;
|
|
2297
|
-
background: #fff;
|
|
2298
|
-
font-family: var(--chrome-font);
|
|
2299
|
-
}
|
|
2300
|
-
.card-meta-title {
|
|
2301
|
-
font-size: 15px;
|
|
2302
|
-
font-weight: 600;
|
|
2303
|
-
color: var(--chrome-ink);
|
|
2304
|
-
letter-spacing: -0.01em;
|
|
2305
|
-
}
|
|
2306
|
-
.card-meta-summary {
|
|
2307
|
-
font-size: 13px;
|
|
2308
|
-
color: var(--chrome-muted);
|
|
2309
|
-
line-height: 1.5;
|
|
2310
|
-
margin: -2px 0 6px;
|
|
2311
|
-
}
|
|
2312
|
-
.card-meta-row {
|
|
2313
|
-
display: flex;
|
|
2314
|
-
align-items: center;
|
|
2315
|
-
gap: 14px;
|
|
2316
|
-
font-size: 13px;
|
|
2317
|
-
}
|
|
2318
|
-
.card-meta-label {
|
|
2319
|
-
flex-shrink: 0;
|
|
2320
|
-
width: 82px;
|
|
2321
|
-
color: var(--chrome-muted);
|
|
2322
|
-
font-size: 11px;
|
|
2323
|
-
letter-spacing: 0.1em;
|
|
2324
|
-
text-transform: uppercase;
|
|
2325
|
-
font-weight: 500;
|
|
2326
|
-
}
|
|
2327
|
-
.card-meta-value {
|
|
2328
|
-
color: var(--chrome-ink);
|
|
2329
|
-
font-size: 13px;
|
|
2330
|
-
display: inline-flex;
|
|
2331
|
-
align-items: center;
|
|
2332
|
-
gap: 8px;
|
|
2333
|
-
}
|
|
2334
|
-
.card-meta-value .sep { color: var(--chrome-muted); margin: 0 2px; }
|
|
2335
|
-
.card-meta-swatches {
|
|
2336
|
-
display: inline-flex;
|
|
2337
|
-
gap: 6px;
|
|
2338
|
-
}
|
|
2339
|
-
.card-meta-swatch {
|
|
2340
|
-
width: 20px;
|
|
2341
|
-
height: 20px;
|
|
2342
|
-
border-radius: 999px;
|
|
2343
|
-
display: inline-block;
|
|
2344
|
-
box-shadow: inset 0 0 0 1px rgba(0,0,0,0.08);
|
|
2345
|
-
}
|
|
2346
|
-
.chip {
|
|
2347
|
-
display: inline-block;
|
|
2348
|
-
background: #f0efe9;
|
|
2349
|
-
padding: 3px 10px;
|
|
2350
|
-
font-size: 11px;
|
|
2351
|
-
letter-spacing: 0.04em;
|
|
2352
|
-
font-weight: 500;
|
|
2353
|
-
color: var(--chrome-ink);
|
|
2354
|
-
}
|
|
2355
|
-
.card-meta code {
|
|
2356
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
2357
|
-
background: #f0efe9;
|
|
2358
|
-
padding: 2px 8px;
|
|
2359
|
-
border-radius: 6px;
|
|
2360
|
-
font-size: 12px;
|
|
2361
|
-
color: #222;
|
|
2362
|
-
}
|
|
2363
|
-
footer.page-footer {
|
|
2364
|
-
margin-top: 56px;
|
|
2365
|
-
padding-top: 28px;
|
|
2366
|
-
border-top: 1px solid var(--chrome-rule);
|
|
2367
|
-
color: var(--chrome-muted);
|
|
2368
|
-
font-size: 14px;
|
|
2369
|
-
line-height: 1.6;
|
|
2370
|
-
display: flex;
|
|
2371
|
-
gap: 28px;
|
|
2372
|
-
flex-wrap: wrap;
|
|
2373
|
-
align-items: flex-start;
|
|
2374
|
-
justify-content: space-between;
|
|
2375
|
-
}
|
|
2376
|
-
footer.page-footer .escape {
|
|
2377
|
-
padding: 10px 16px;
|
|
2378
|
-
border: 1px dashed var(--chrome-rule);
|
|
2379
|
-
border-radius: 10px;
|
|
2380
|
-
background: #fff;
|
|
2381
|
-
color: var(--chrome-ink);
|
|
2382
|
-
font-size: 13px;
|
|
2383
|
-
}
|
|
2384
|
-
footer .escape code {
|
|
2385
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
2386
|
-
font-size: 12px;
|
|
2387
|
-
background: #f0efe9;
|
|
2388
|
-
padding: 2px 6px;
|
|
2389
|
-
border-radius: 4px;
|
|
2390
|
-
}
|
|
2391
|
-
</style>
|
|
1941
|
+
<meta charset="utf-8">
|
|
1942
|
+
<title>${n} \u2014 Pick a design</title>
|
|
1943
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1944
|
+
<style>
|
|
1945
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
1946
|
+
html, body { height: 100%; }
|
|
1947
|
+
body {
|
|
1948
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
|
|
1949
|
+
background: #0a0a0a;
|
|
1950
|
+
color: #e5e5e5;
|
|
1951
|
+
display: grid;
|
|
1952
|
+
grid-template-rows: auto 1fr auto;
|
|
1953
|
+
height: 100vh;
|
|
1954
|
+
}
|
|
1955
|
+
header.picker-bar {
|
|
1956
|
+
background: #111;
|
|
1957
|
+
border-bottom: 1px solid #222;
|
|
1958
|
+
padding: 12px 20px;
|
|
1959
|
+
display: flex;
|
|
1960
|
+
flex-direction: column;
|
|
1961
|
+
gap: 8px;
|
|
1962
|
+
}
|
|
1963
|
+
.picker-title {
|
|
1964
|
+
font-size: 13px;
|
|
1965
|
+
color: #8b8b8b;
|
|
1966
|
+
text-transform: uppercase;
|
|
1967
|
+
letter-spacing: 0.08em;
|
|
1968
|
+
}
|
|
1969
|
+
.picker-title strong { color: #fff; font-weight: 600; letter-spacing: -0.01em; text-transform: none; font-size: 14px; }
|
|
1970
|
+
.tabs { display: flex; gap: 4px; flex-wrap: wrap; }
|
|
1971
|
+
.tab {
|
|
1972
|
+
background: transparent;
|
|
1973
|
+
color: #cdcdcd;
|
|
1974
|
+
border: 1px solid #222;
|
|
1975
|
+
border-radius: 6px;
|
|
1976
|
+
padding: 8px 14px;
|
|
1977
|
+
cursor: pointer;
|
|
1978
|
+
font-family: inherit;
|
|
1979
|
+
font-size: 13px;
|
|
1980
|
+
text-align: left;
|
|
1981
|
+
display: flex;
|
|
1982
|
+
flex-direction: column;
|
|
1983
|
+
gap: 2px;
|
|
1984
|
+
max-width: 280px;
|
|
1985
|
+
transition: background 120ms, border-color 120ms;
|
|
1986
|
+
}
|
|
1987
|
+
.tab:hover { background: #181818; border-color: #2c2c2c; }
|
|
1988
|
+
.tab.active { background: #1c1c1c; border-color: #4a4a4a; color: #fff; }
|
|
1989
|
+
.tab-name { font-weight: 600; font-size: 13px; }
|
|
1990
|
+
.tab-sub { font-size: 11px; color: #888; line-height: 1.4; max-width: 260px; }
|
|
1991
|
+
.tab.active .tab-sub { color: #b5b5b5; }
|
|
1992
|
+
.frames { position: relative; background: #fff; }
|
|
1993
|
+
.render-frame {
|
|
1994
|
+
position: absolute;
|
|
1995
|
+
inset: 0;
|
|
1996
|
+
width: 100%;
|
|
1997
|
+
height: 100%;
|
|
1998
|
+
border: 0;
|
|
1999
|
+
background: #fff;
|
|
2000
|
+
display: none;
|
|
2001
|
+
}
|
|
2002
|
+
.render-frame.active { display: block; }
|
|
2003
|
+
footer.picker-foot {
|
|
2004
|
+
background: #111;
|
|
2005
|
+
border-top: 1px solid #222;
|
|
2006
|
+
padding: 10px 20px;
|
|
2007
|
+
font-size: 12px;
|
|
2008
|
+
color: #9e9e9e;
|
|
2009
|
+
display: flex;
|
|
2010
|
+
justify-content: space-between;
|
|
2011
|
+
gap: 16px;
|
|
2012
|
+
flex-wrap: wrap;
|
|
2013
|
+
}
|
|
2014
|
+
footer.picker-foot strong { color: #f0f0f0; }
|
|
2015
|
+
</style>
|
|
2392
2016
|
</head>
|
|
2393
2017
|
<body>
|
|
2394
|
-
<
|
|
2395
|
-
|
|
2396
|
-
<div class="
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
<span>It streams the gpt-image-2 mockups live and has hover comparison. Open when you're online: <a href="${Se(r.dashboardPickerUrl)}" target="_blank" rel="noreferrer noopener">${Se(r.dashboardPickerUrl)}</a></span>
|
|
2401
|
-
</div>
|
|
2402
|
-
</div>
|
|
2403
|
-
`:""}
|
|
2404
|
-
<header class="page-header">
|
|
2405
|
-
<div class="eyebrow"><span class="eyebrow-dot"></span>Mistflow \xB7 design direction</div>
|
|
2406
|
-
<h1 class="page-title">How should <strong>${Se(t)}</strong> feel?</h1>
|
|
2407
|
-
<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>
|
|
2408
|
-
</header>
|
|
2409
|
-
|
|
2410
|
-
<div class="grid">
|
|
2411
|
-
${i}
|
|
2412
|
-
</div>
|
|
2413
|
-
|
|
2414
|
-
<footer class="page-footer">
|
|
2415
|
-
<div>
|
|
2416
|
-
<div><strong>How to pick</strong></div>
|
|
2417
|
-
<div>Reply to your assistant with the direction name \u2014 e.g. “pick <em>Morning Paper</em>.” The final DESIGN.md will honor the fonts, palette, layout, and voice you see here.</div>
|
|
2418
|
-
</div>
|
|
2419
|
-
<div class="escape">
|
|
2420
|
-
<strong>None fit?</strong> Tell your assistant <code>describe your own</code> and give a short description.
|
|
2421
|
-
</div>
|
|
2422
|
-
</footer>
|
|
2018
|
+
<header class="picker-bar">
|
|
2019
|
+
<div class="picker-title"><strong>${n}</strong> \u2014 pick a design direction</div>
|
|
2020
|
+
<div class="tabs">${i}</div>
|
|
2021
|
+
</header>
|
|
2022
|
+
<div class="frames">
|
|
2023
|
+
${o}
|
|
2423
2024
|
</div>
|
|
2025
|
+
<footer class="picker-foot">
|
|
2026
|
+
<div><strong>How to pick:</strong> click each tab to compare. When you've chosen, tell your AI assistant the direction name (e.g. “pick <em>${e[0]?.name?hn(e[0].name):"Morning Paper"}</em>”).</div>
|
|
2027
|
+
<div><strong>None fit?</strong> Tell your assistant <code>describe your own</code> and give a short description.</div>
|
|
2028
|
+
</footer>
|
|
2029
|
+
<script>
|
|
2030
|
+
(function() {
|
|
2031
|
+
const tabs = document.querySelectorAll(".tab");
|
|
2032
|
+
const frames = document.querySelectorAll(".render-frame");
|
|
2033
|
+
tabs.forEach(function (tab) {
|
|
2034
|
+
tab.addEventListener("click", function () {
|
|
2035
|
+
const target = tab.getAttribute("data-target");
|
|
2036
|
+
tabs.forEach(function (t) { t.classList.toggle("active", t === tab); });
|
|
2037
|
+
frames.forEach(function (f) { f.classList.toggle("active", f.getAttribute("data-id") === target); });
|
|
2038
|
+
});
|
|
2039
|
+
});
|
|
2040
|
+
})();
|
|
2041
|
+
</script>
|
|
2424
2042
|
</body>
|
|
2425
2043
|
</html>
|
|
2426
|
-
`}
|
|
2427
|
-
`)})}function
|
|
2428
|
-
`)}).join(`
|
|
2429
|
-
`)
|
|
2430
|
-
`)}
|
|
2431
|
-
`)
|
|
2432
|
-
|
|
2433
|
-
`));case"
|
|
2434
|
-
`))
|
|
2435
|
-
`))}
|
|
2436
|
-
|
|
2437
|
-
`));
|
|
2438
|
-
`));
|
|
2439
|
-
`));case"call_mist_build":return d([...g,Bt("mist_build",{sessionId:m.session_id,projectPath:n})].join(`
|
|
2440
|
-
`));case"call_mist_deploy":return d([...g,Bt("mist_deploy",{sessionId:m.session_id,projectPath:n})].join(`
|
|
2441
|
-
`));case"call_mist_qa":return d([...g,Bt("mist_qa",{sessionId:m.session_id,projectPath:n})].join(`
|
|
2442
|
-
`));case"done":return d([...g,Md(m)].join(`
|
|
2443
|
-
`))}}catch(m){let g=m instanceof Error?m.message:String(m);return d(`Could not poll session '${i}': ${g}`,!0)}if(o&&!r&&!s&&!b&&!y&&!a&&!l&&!c)try{let m=await $n(o);if(m.status==="clarify_pending"||m.status==="plan_pending"){let g=typeof m.phase_hint=="string"?m.phase_hint:null,x=typeof m.elapsed_seconds=="number"?m.elapsed_seconds:null,v=typeof m.progress=="number"?m.progress:null,H=m.status==="plan_pending",C=H?"generating_plan":"generating_questions",X=g?`${g}${x!==null?` (${x}s elapsed)`:""}`:H?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return d(JSON.stringify({status:"running",conversationId:o,phase:C,...g?{phaseHint:g}:{},...x!==null?{elapsedSeconds:x}:{},...v!==null?{progress:v}:{},nextAction:`${X}. Tell the user briefly what's happening (e.g. "${g??(H?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}return d(JSON.stringify(m))}catch(m){let g=m instanceof Error?m.message:String(m);return d(`Could not poll plan conversation '${o}': ${g}`,!0)}let U=r??"";if(!U.trim()&&!o&&!b&&!a&&!l&&!c)return d("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(b&&!y&&!U.trim()&&!s)return d(`You passed designConversationId='${b}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${b}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let M=a;if(!M&&l&&(M=Rd(l)??void 0,!M))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let de=o;if(!ve())return Ae("plan a new app");let K,D;if(!de&&!M&&!c&&!b){if(!fd(n))return d(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let m=Sd(n);if(m!=="mistflow"&&Td(n))return d(JSON.stringify({status:"unsafe_cwd",projectPath:n,instruction:[`The projectPath you passed (${n}) is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Create the subfolder at ${n}/<subfolder-name>.`," 3. Call mist_plan again with the SAME description and projectPath set to the new subfolder.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description."].join(`
|
|
2444
|
-
`)}),!0);if(m==="foreign"){let g=O?xd(O,n,U):!1,x=_d(n,U),v=Pd(U,w);if(v||g){D=x;let H=si(D);if(H)return d(`Mistflow could not create the scaffold directory at ${D}: ${H}`,!0);K=`Note: Mistflow will scaffold the new app at \`${D}\`. The existing project at \`${n}\` is not modified.`}if(!g&&!v){let H=kd(n,U);if(e?.server){let C=await mn(e.server,[{question:"You're inside an existing project. Where should Mistflow scaffold the new app?",decisionKey:"scopeChoice",recommended:`Create at: ${x}`,why:"Mistflow creates a NEW app and never modifies the surrounding codebase. The default puts it in a subdirectory of the current path, named after your description. You can pick a custom path or cancel if you actually want to edit the existing project instead.",options:[{label:`Create at: ${x}`,description:"Default \u2014 uses your description as the folder name."},{label:"Choose a different path",description:"Type a custom absolute path in the textbox below."},{label:"Cancel \u2014 I wanted to edit the existing project",description:"Stop Mistflow. Handle the request by editing files in the current project instead."}]}],`## Existing project detected
|
|
2044
|
+
`}function hn(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Qn(t){return hn(t)}var Ko=I(()=>{"use strict"});import{z as D}from"zod";import{existsSync as Xe,mkdirSync as It,readFileSync as gn,readdirSync as ti,statSync as ni,unlinkSync as nd,writeFileSync as pt}from"fs";import{dirname as rd,isAbsolute as sd,join as ye}from"path";import{homedir as ut,hostname as Jo}from"os";import{createHash as od,createHmac as ri,randomBytes as id,randomUUID as Yo,timingSafeEqual as ad}from"crypto";function si(){let t=ye(ut(),".mistflow","confirm-secret");if(Xe(t))try{return Buffer.from(gn(t,"utf-8").trim(),"hex")}catch{}let e=id(32);return It(ye(ut(),".mistflow"),{recursive:!0}),pt(t,e.toString("hex"),{mode:384}),e}function oi(t){return od("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function cd(t,e){let r={cwd:t,d:oi(e),exp:Date.now()+ld},n=Buffer.from(JSON.stringify(r)).toString("base64url"),i=ri("sha256",si()).update(n).digest("base64url");return`${n}.${i}`}function dd(t,e,r){let n=t.split(".");if(n.length!==2)return!1;let[i,o]=n,s=ri("sha256",si()).update(i).digest("base64url"),a=Buffer.from(o),l=Buffer.from(s);if(a.length!==l.length||!ad(a,l))return!1;try{let c=JSON.parse(Buffer.from(i,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==e||c.d!==oi(r))}catch{return!1}}function pd(t){let e=t,r=ut(),n=!1;for(let i=0;i<64;i++){if(Xe(ye(e,"mistflow.json")))return"mistflow";if(!n&&Xe(ye(e,"package.json"))&&(n=!0),e===r)break;let o=rd(e);if(o===e)break;e=o}return n?"foreign":"none"}function ud(t){let e=ut(),r=t.replace(/\/+$/,"");if(r===e||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let i of n)if(r===ye(e,i))return!0;return!1}function md(t){let e=new Set(["build","create","make","scaffold","start","using","with","mist","mistflow","a","an","the","for","me","my","new","app","application","website","site","web","tool","dashboard","landing","page","platform","please","can","you","i","want","need"]);return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).map(n=>n.trim()).filter(n=>n.length>1&&!e.has(n)).slice(0,4).join("-").slice(0,48)||"new-app"}function Qo(t){if(!Xe(t))return!0;try{return ni(t).isDirectory()?ti(t).filter(n=>n!==".mistflow").length===0:!1}catch{return!1}}function hd(t,e){let r=md(e),n=ye(t,r);if(Qo(n))return n;for(let i=2;i<=50;i++){let o=ye(t,`${r}-${i}`);if(Qo(o))return o}return ye(t,`${r}-${Date.now()}`)}function gd(t,e){if(e)return!0;let r=t.toLowerCase(),n=/\b(build|create|make|scaffold|start|generate)\b/.test(r),i=/\b(app|application|website|site|web\s+app|landing\s+page|dashboard|tool|marketplace|game|blog|portfolio|crm)\b/.test(r),o=/\b(add|change|fix|update|edit|refactor|debug|review)\b/.test(r)&&!n;return n&&i&&!o}function Xo(t){try{It(t,{recursive:!0});return}catch(e){return e instanceof Error?e.message:String(e)}}function Zo(t){let{projectPath:e,description:r,confirmToken:n,suggestedPath:i,previousTokenInvalid:o}=t;return JSON.stringify({status:"confirm_new_project",requires_user_input:!0,projectPath:e,description:r,confirmToken:n,suggestedScaffoldPath:i,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:`Creates a fresh project at \`${i}\` without touching the existing code.`},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json).","MANDATORY: Ask the user the provided askUserQuestion before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token returned above.",`Mistflow will create and remember the new app directory at \`${i}\`. Do not change projectPath to the child directory on the retry; the token is intentionally bound to the original directory.`,"If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",o?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
2045
|
+
`)})}function yd(t){let e=[[/payment/i,"Payments"],[/database/i,"Database"],[/auth|sign.?up|login|access/i,"Access"],[/landing.?page/i,"Landing page"],[/who.*using|user|role/i,"Users"],[/design|theme|style/i,"Design"],[/deploy/i,"Deploy"],[/domain/i,"Domain"],[/notification/i,"Notify"],[/email/i,"Email"],[/mobile|responsive/i,"Mobile"],[/integrat/i,"Integration"],[/field|info|propert|detail|contain/i,"Item shape"],[/view|layout|board|grid|list|timeline/i,"View"],[/scope|how many|one.*or.*many|multi/i,"Scope"],[/share|read.?only|viewer|stakeholder/i,"Sharing"],[/workflow|status|state|move|stage|pipeline/i,"Workflow"],[/avoid|bloat|simple|complex|minimal/i,"Constraints"],[/time.*period|quarter|month|sprint/i,"Time periods"],[/swimlane|column|group|categor/i,"Structure"]];for(let[n,i]of e)if(n.test(t))return i;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(n=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(n.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function bd(t){let e=ye(ut(),".mistflow","plans",`${t}.json`);if(!Xe(e))return null;try{return JSON.parse(gn(e,"utf-8")).plan??null}catch{return null}}async function wd(t){let e=Date.now(),r=5e4,n=2e3;for(;Date.now()-e<r;){try{let i=await On(t.design_conversation_id);if(i.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:i.directions,plan:i.plan,methodology:i.methodology};if(i.status==="failed")return{status:"ready",plan:i.plan,methodology:i.methodology}}catch(i){let o=i instanceof Error?i.message:String(i);if(o.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll failed: ${o}`)}await new Promise(i=>setTimeout(i,n))}return console.error("[plan] directions poll exhausted (50s) \u2014 preserving pending so host re-polls"),t}function vd(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function kd(t,e){for(let r of e){let n=vd(t[r]);if(n)return n}}function xd(t){return kd(t,["mockup_url","mockupUrl","preview_url","previewUrl","live_url","liveUrl","deploy_url","deployUrl","url"])}function ei(t,e){return`Next action: call ${t} with ${JSON.stringify(e)}. Do not omit sessionId.`}function Sd(t){let e=xd(t),r=t.reason?`
|
|
2046
|
+
Reason: ${t.reason}`:"";switch(t.state){case"COMPLETE":return`Session complete.${e?` Live URL: ${e}`:""}${r}`;case"CANCELLED":return`Session was cancelled.${r}`;case"FAILED":return`Session ended in FAILED.${e?` Last known URL: ${e}`:""}${r}`;case"ABANDONED":return`Session was abandoned.${r}`;case"EXPIRED":return`Session expired.${r}`;default:return`Session finished with state ${t.state}.${e?` URL: ${e}`:""}${r}`}}async function Td(t,e){let{description:r,projectPath:n,sessionId:i,conversationId:o,answers:s,existingPlan:a,existingPlanId:l,templateToken:c,remixDescription:u,autonomous:h,language:d,brandMentioned:v,confirmToken:W,urlChoice:_,designConversationId:k,designDirection:y,userConfirmedCustom:A,forceNew:z}=t;if(i&&!o&&!k)try{let m=await Dt(i),g=[`Session ID: ${m.session_id}`,`Status: ${m.status??"active"}`,`Instruction: ${m.instruction}`];switch(m.reason&&g.push(`Reason: ${m.reason}`),m.instruction){case"wait":return p([...g,`Next action: ${m.reason??"The backend is still preparing the next step."} Tell the user briefly what's happening, then call mist_plan with { projectPath, sessionId: "${m.session_id}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`].join(`
|
|
2047
|
+
`));case"resume_conversation":{let w=m.conversation_id;return p([...g,`In-flight conversation: ${w??"(missing \u2014 backend bug)"}`,`Next action: call mist_plan with { projectPath, conversationId: "${w??""}" } to continue the plan flow. The conversation poll renders questions / design directions in the same way it would have on the original mist_plan response.`].join(`
|
|
2048
|
+
`))}case"continue":return p([...g,`Next action: ${m.reason??"Continue from where you left off \u2014 read mistflow.json to find the next pending step, then call mist_install / mist_implement / mist_build / mist_deploy as appropriate."}`].join(`
|
|
2049
|
+
`));case"call_mist_init":return p([...g,ei("mist_init",{sessionId:m.session_id,path:n})].join(`
|
|
2050
|
+
`));case"call_mist_deploy":return p([...g,ei("mist_deploy",{sessionId:m.session_id,projectPath:n})].join(`
|
|
2051
|
+
`));case"review_plan":return p([...g,`Next action: ${m.reason??"User asked to review PLAN.md before scaffolding. Open <projectPath>/PLAN.md, let the user read / edit, then call mist_session({ resume }) and re-run mist_init."}`].join(`
|
|
2052
|
+
`));case"done":return p([...g,Sd(m)].join(`
|
|
2053
|
+
`))}}catch(m){let g=m instanceof Error?m.message:String(m);return p(`Could not poll session '${i}': ${g}`,!0)}if(o&&!r&&!s&&!k&&!y&&!a&&!l&&!c)try{let m=await Mn(o);if(m.status==="clarify_pending"||m.status==="plan_pending"){let g=typeof m.phase_hint=="string"?m.phase_hint:null,w=typeof m.elapsed_seconds=="number"?m.elapsed_seconds:null,T=typeof m.progress=="number"?m.progress:null,O=m.status==="plan_pending",F=O?"generating_plan":"generating_questions",oe=g?`${g}${w!==null?` (${w}s elapsed)`:""}`:O?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return p(JSON.stringify({status:"running",conversationId:o,phase:F,...g?{phaseHint:g}:{},...w!==null?{elapsedSeconds:w}:{},...T!==null?{progress:T}:{},nextAction:`${oe}. Tell the user briefly what's happening (e.g. "${g??(O?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}if(m.status==="design_clarify"&&Array.isArray(m.directions)){let w=m.directions.map((C,xe)=>({id:C.id??String(xe),name:C.name??`Direction ${xe+1}`,summary:C.summary,hero_headline:C.hero_headline,cta_text:C.cta_text,body_sample:C.body_sample,fonts:C.fonts,colors:C.colors,hero_treatment:C.hero_treatment,shape_lang:C.shape_lang,texture:C.texture,decoration_hint:C.decoration_hint})),T=m.plan?.name??"your app",O=m.design_conversation_id,F={},oe=!1;try{if(O){let f=Date.now();for(;Date.now()-f<5e4;){let E=await Dn(O),S=0;for(let de of w){let me=E[de.id];me&&((me.status==="done"||me.status==="ready")&&typeof me.html=="string"&&me.html.length>0?(F[de.id]=me.html,S+=1):me.status==="failed"&&(S+=1))}if(S===w.length){oe=!0;break}await new Promise(de=>setTimeout(de,5e3))}}}catch(C){console.error(`[mist_plan:design_clarify] render poll failed: ${C instanceof Error?C.message:String(C)}`)}if(!oe)return p(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:o,design_conversation_id:O,renderedSoFar:Object.keys(F).length,totalDirections:w.length,nextAction:`${Object.keys(F).length}/${w.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${o}" } again IMMEDIATELY \u2014 do NOT bash sleep. The render-poll holds the connection up to ~50s; each call returns as soon as state changes. Do NOT ask the user about design yet; the picker isn't ready.`}));let le=w.filter(C=>F[C.id]),ie,L,J=ye(n,".mistflow"),ve=ye(J,"design-directions.html"),re=ye(J,"picker-state.json"),ce=!1;if(O)try{Xe(re)&&JSON.parse(gn(re,"utf-8")).opened_for_design_cid===O&&(ce=!0)}catch{}try{if(It(J,{recursive:!0}),ce)ie=ve;else{let C=ls(T,le,F);pt(ve,C,"utf-8"),ie=ve;let xe=as(`file://${ve}`);xe.opened||(L=xe.reason),O&&pt(re,JSON.stringify({opened_for_design_cid:O,opened_at:new Date().toISOString()},null,2),"utf-8")}}catch(C){console.error(`[mist_plan:design_clarify] picker write/open failed: ${C instanceof Error?C.message:String(C)}`)}let Te=le.map(C=>({id:C.id,name:C.name})),ue=Te.map(C=>C.name).filter(Boolean);return p(JSON.stringify({status:"design_clarify",previewPath:ie,previewOpenError:L,directionRefs:Te,directionNames:ue,design_conversation_id:O,conversation_id:o,nextAction:[`The visual picker has been opened in the user's browser at file://${ie??"(path missing)"} \u2014 every direction is a real, rendered landing page. The user is looking at it now.`,L?`(auto-open suppressed: ${L} \u2014 tell the user to open file://${ie} manually)`:"",`Now use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names as options: ${ue.map(C=>`"${C}"`).join(", ")}. Do NOT invent extra options. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${o}", designConversationId: "${O}", designDirection: { id: "<map name \u2192 id from directionRefs>" } }. If the user types a custom description, pass designDirection: { custom: "<their exact words>" } and userConfirmedCustom: true.`].filter(Boolean).join(`
|
|
2054
|
+
|
|
2055
|
+
`)}))}return p(JSON.stringify(m))}catch(m){let g=m instanceof Error?m.message:String(m);return p(`Could not poll plan conversation '${o}': ${g}`,!0)}let H=r??"";if(!H.trim()&&!o&&!k&&!a&&!l&&!c)return p("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(k&&!y&&!H.trim()&&!s)return p(`You passed designConversationId='${k}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${k}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let ne=a;if(!ne&&l&&(ne=bd(l)??void 0,!ne))return p("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let ee=o;if(!Se())return Ee("plan a new app");let Q,q;if(!ee&&!ne&&!c&&!k){if(!sd(n))return p(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let m=pd(n);if(m!=="mistflow"&&ud(n))return p(JSON.stringify({status:"unsafe_cwd",projectPath:n,instruction:[`The projectPath you passed (${n}) is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Create the subfolder at ${n}/<subfolder-name>.`," 3. Call mist_plan again with the SAME description and projectPath set to the new subfolder.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description."].join(`
|
|
2056
|
+
`)}),!0);if(m==="foreign"){let g=W?dd(W,n,H):!1,w=hd(n,H),T=gd(H,v);if(T||g){q=w;let O=Xo(q);if(O)return p(`Mistflow could not create the scaffold directory at ${q}: ${O}`,!0);Q=`Note: Mistflow will scaffold the new app at \`${q}\`. The existing project at \`${n}\` is not modified.`}if(!g&&!T){let O=cd(n,H);if(e?.server){let F=await mn(e.server,[{question:"You're inside an existing project. Where should Mistflow scaffold the new app?",decisionKey:"scopeChoice",recommended:`Create at: ${w}`,why:"Mistflow creates a NEW app and never modifies the surrounding codebase. The default puts it in a subdirectory of the current path, named after your description. You can pick a custom path or cancel if you actually want to edit the existing project instead.",options:[{label:`Create at: ${w}`,description:"Default \u2014 uses your description as the folder name."},{label:"Choose a different path",description:"Type a custom absolute path in the textbox below."},{label:"Cancel \u2014 I wanted to edit the existing project",description:"Stop Mistflow. Handle the request by editing files in the current project instead."}]}],`## Existing project detected
|
|
2445
2057
|
|
|
2446
2058
|
You're inside \`${n}\` which has a \`package.json\`. Mistflow will create a NEW app in a subdirectory \u2014 it won't modify the existing code.
|
|
2447
2059
|
|
|
2448
|
-
Default path: \`${x}\``,"scope");if(C.outcome==="submitted"){let X=C.answers?.[0]?.answer??"",ae=X.toLowerCase(),ee=X.startsWith("/")?X:null;if(ee||ae.startsWith("create at:")||ae.startsWith("choose a different path")){let le=ee||(ae.startsWith("choose a different path")?null:x);if(!le)return d("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);D=le;let oe=si(D);if(oe)return d(`Mistflow could not create the scaffold directory at ${D}: ${oe}`,!0);K=`Note: Mistflow will scaffold the new app at \`${D}\`. The existing project at \`${n}\` is not modified.`}else return ae.startsWith("cancel")?d("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):d(`User submitted an unrecognized scope choice: ${X}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return C.outcome==="declined"?d("User declined the scope confirmation. They wanted to edit the existing project, not create a new Mistflow app. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):d(ii({projectPath:n,description:U,confirmToken:H,suggestedPath:x,previousTokenInvalid:!!O}))}else return d(ii({projectPath:n,description:U,confirmToken:H,suggestedPath:x,previousTokenInvalid:!!O}))}}}if(c)try{if(!(await Hr(c)).plan)return d("This template has no plan to fork. Try a different template.",!0);let g=await Wr(c),x=g.plan,v="";if(h&&g.has_source)try{let oe=await Un(g.plan,h),ye=oe.plan??oe,Z=oe.diff,V=ye?.steps??[],ce=new Set([...(Z?.added??[]).map(f=>f.number),...(Z?.modified??[]).map(f=>f.number)]),ue=V.map(f=>{let E=f.number;return ce.has(E)?{...f,status:"pending"}:{...f,status:"completed",source:"forked"}});ye.steps=ue,x=ye;let we=ue.filter(f=>f.status==="pending").length;v=` Remixed: ${ue.filter(f=>f.status==="completed").length} steps unchanged, ${we} steps need re-implementation.`}catch(oe){console.error("[plan] Remix failed, using original plan:",oe),v=" (Remix failed \u2014 using original plan. You can modify it later.)"}let H=ni(),C=Te(ut(),".mistflow","plans");hn(C,{recursive:!0}),Xn(Te(C,`${H}.json`),JSON.stringify({plan:x,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let X=x?.name??"forked-app",ae=g.has_source,ee=ae?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",le=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:H,forkedFrom:g.forked_from,projectId:g.id,hasSource:ae,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${v}${le} ${ee} NEXT: Call mist_init, name='${X}', and planId='${H}' to create the project now.`}))}catch(m){let g=m instanceof Error?m.message:"Failed to fork template";return d(g,!0)}if(M){let m;try{m=await Un(M,U)}catch(C){let X=C instanceof Error?C.message:"Failed to modify plan";return d(X,!0)}let g=m.plan,x=m.diff,v=[];if(x?.added?.length){let C=x.added.map(X=>X.title);v.push(`Added ${C.length} step(s): ${C.join(", ")}`)}if(x?.removed?.length){let C=x.removed.map(X=>X.title);v.push(`Removed ${C.length} step(s): ${C.join(", ")}`)}if(x?.modified?.length){let C=x.modified.map(X=>X.title);v.push(`Modified ${C.length} step(s): ${C.join(", ")}`)}let H=v.length>0?v.join(". "):"No changes detected.";return d(JSON.stringify({plan:g,diff:x,message:`Plan modified. ${H}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let A=k?.trim()||void 0,Q=s;if(Array.isArray(s)){let m=s.findIndex(g=>g&&typeof g=="object"&&g.decisionKey==="urlChoice");if(m>=0){let g=s[m];!A&&g.answer&&(A=g.answer);let x=s.slice(0,m).concat(s.slice(m+1));Q=x.length>0?x:void 0}}else if(s!=null){let m=s;if(!A&&Qn in m&&(A=m[Qn]),!A&&"urlChoice"in m&&(A=m.urlChoice),Qn in m||"urlChoice"in m){let{[Qn]:g,urlChoice:x,...v}=m;Q=Object.keys(v).length>0?v:void 0}}if(A&&(A=A.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),A){let m=A.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(m)?A=m:(console.error(`[mist_plan] Discarding urlChoice '${A}' \u2014 does not look like a subdomain. Backend will auto-generate.`),A=void 0)}let P;if(y){P={...y};let m={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[g,x]of Object.entries(m))y[g]!==void 0&&P[x]===void 0&&(P[x]=y[g])}if(P!==void 0&&typeof P.custom=="string"&&!P.id&&!P.name&&b)try{let m=await jn(b);if(m.status==="pending")return d(`Refusing to submit a custom design direction: the backend's direction-generation BG task is still running (status: pending). The user has not yet had the chance to see the real directions. Stop asking the user about aesthetic / fonts / colors / mood right now \u2014 the backend will produce 3-4 concrete options shortly. Re-call mist_plan with { projectPath, conversationId, designConversationId: '${b}' } to keep polling. When directions are ready (status: 'design_clarify'), surface them to the user via AskUserQuestion. Custom is only legitimate AFTER the user has seen the real options and explicitly rejected them \u2014 never as a workaround for a slow generation run.`,!0);if(m.status==="ready"&&Array.isArray(m.directions)&&m.directions.length>0&&!I){let g=m.directions.map(x=>x.name).join(", ");return d(`Refusing to submit a custom design direction: the backend has ${m.directions.length} real directions ready (${g}). The picker is mandatory \u2014 you must surface those exact directions to the user via AskUserQuestion before submitting any pick. Re-call mist_plan with { conversationId, designConversationId: '${b}' } to get the picker payload (status: 'design_clarify'), render the directions HTML preview at .mistflow/design-directions.html for the user, then submit the user's choice. If the user opens the preview, sees the ${m.directions.length} directions, rejects all of them, and types their own description, ONLY THEN retry this call with userConfirmedCustom: true. Never set userConfirmedCustom: true without first showing the user the real directions.`,!0)}}catch(m){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${m instanceof Error?m.message:String(m)}`)}let z=s?"Generating plan with your answers (LLM call)":b?"Finalizing design direction":"Thinking through discovery questions",L=e?Fe(e.server,e.progressToken,()=>z):{stop:()=>{}};if(e&&(e.cleanup=()=>L.stop()),!i&&!o&&!b&&!a&&!l&&!c&&!O&&U.trim().length>0&&!B)try{let m=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),g=336*60*60*1e3,x=Date.now()-g,H=(await an(ti())).filter(C=>!m.has(C.state)).filter(C=>{let X=Date.parse(C.updated_at);return Number.isFinite(X)&&X>=x}).sort((C,X)=>Date.parse(X.updated_at)-Date.parse(C.updated_at)).slice(0,5);if(H.length>0)return L.stop(),d(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:H.map(C=>({sessionId:C.id,state:C.state,description:C.description,currentStep:C.current_step,awaitingInput:C.awaiting_input,updatedAt:C.updated_at})),instruction:"This machine has unfinished Mistflow build(s) in flight. Before starting a new project, ask the user whether they want to resume one of these or start fresh. Show the description, state, and updatedAt for each candidate so they can pick.",nextAction:"Step 1: Show the candidates to the user via your host's question UI (AskUserQuestion in Claude Code, request_user_input in Codex Plan mode, quick pick in Cursor). Step 2a (resume): if they pick a candidate, call mist_session({ action: 'resume', sessionId: '<picked>', projectPath }) and follow the next instruction it returns. Step 2b (start fresh): if they want a new build, call mist_plan again with the SAME description and projectPath, plus forceNew: true. The forceNew flag suppresses this check so the new session can be minted."}))}catch(m){console.error("resume-offer check failed (falling through to bootstrap):",m instanceof Error?m.message:m)}let j=i;if(!j&&!de&&!b&&U.trim())try{let m=await Vr({description:U.trim()});j=m.id;try{await sn(m.id,{machine_id:ti(),local_path:n})}catch(g){console.error("workspace bind failed (resume offers will miss this session):",g instanceof Error?g.message:g)}}catch(m){console.error("session bootstrap failed:",m instanceof Error?m.message:m)}let R;try{de&&!Q&&!b&&!M&&!l?R=await $n(de):R=await Ln(U,{conversationId:de,answers:Q,autonomous:p,language:u,designConversationId:b,designDirection:P})}catch(m){L.stop();let g=m instanceof Error?m.message:"Failed to generate plan";return d(g,!0)}if(R.status==="clarify_pending"){L.stop();let m=R;return await me(j,"ASKING_QUESTIONS",["NEW"]),d(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:j,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.${j?` Carry sessionId="${j}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(R.status==="plan_pending"){L.stop();let m=R;return await me(j,"ASKING_QUESTIONS",["NEW"]),await me(j,"GENERATING_PLAN",["ASKING_QUESTIONS"]),d(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:j,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(R.status==="design_clarify_pending"&&(z="Generating creative design directions",R=await Ed(R)),R.status==="design_clarify_pending")return L.stop(),d(JSON.stringify({status:"running",conversationId:o,designConversationId:R.design_conversation_id,sessionId:j,phase:"generating_design_directions",nextAction:`Creative design directions are still generating (45-60s typical, can stretch on slow runs). Call mist_plan with { projectPath, conversationId: "${o??""}" } IMMEDIATELY to keep polling \u2014 do NOT run bash sleep, do NOT submit a designDirection of your own, do NOT mark the plan as ready, and DO NOT ASK THE USER about aesthetic / fonts / colors / mood / vibe / style while you wait. The backend is generating 3-4 concrete direction options the user will pick from \u2014 asking the user to invent one defeats the entire feature, and the server will reject any { custom } submission while directions are still pending. Just poll. The picker is mandatory; keep polling until status becomes 'design_clarify' with the directions array, then surface those exact directions to the user via AskUserQuestion.`}));if(L.stop(),R.status==="clarify"){let m=R.reflection||"",g=R.suggestedName||"",x=R.suggestedFeatures??[],v=R.questions??[],H=v.some(Z=>Array.isArray(Z.options)&&typeof Z.options[0]=="object"&&Z.options[0]?.label),C={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"},X=v.map(Z=>{let V=Z.decisionKey&&C[Z.decisionKey]||Ad(Z.question),ce;return H&&Array.isArray(Z.options)?ce=Z.options.map(ue=>({label:ue.label,description:ue.description??""})):Array.isArray(Z.options)?ce=Z.options.map((ue,we)=>({label:we===0?`${ue} (Recommended)`:String(ue),description:Z.why??""})):ce=[{label:"Yes (Recommended)",description:Z.why??""},{label:"No",description:""}],{question:Z.question,header:V,options:ce,multiSelect:!1}}),ee=R.decisions?.audienceType??null,le=x.length>0?Js(U,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:ee,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:x,language:u}):null,oe=le?Ys(le):"",ye=Yn(g||"my-app").slice(0,32);try{let Z=await On(ye);!Z.available&&Z.suggestion&&(ye=Z.suggestion)}catch{}if(oe&&(oe+=`
|
|
2449
|
-
|
|
2450
|
-
**Your app URL (you can change this before scaffolding):** https://${ye}.mistflow.app`),e?.server){let Z=[g?`## ${g}`:"## Pick a few details","",`${v.length} quick question${v.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
|
|
2451
|
-
`),V=await mn(e.server,v,Z,"clarify");if(V.outcome==="submitted"){L.stop();let ce={};for(let we of V.answers??[])we.decisionKey?ce[we.decisionKey]=we.answer:ce[we.question]=we.answer;let ue=V.urlChoice?.trim();ue&&(ue=ue.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let we=await Ln(U,{conversationId:R.conversation_id,answers:ce,autonomous:p,language:u});if(we.status==="plan_pending"){let ot=we;return d(JSON.stringify({status:"running",conversationId:ot.conversation_id,phase:"generating_plan",...ue?{urlChoice:ue}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${ot.conversation_id}"${ue?`, urlChoice: "${ue}"`:""} } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll up to ~10s and returns when the plan lands. Pass urlChoice on every poll so it threads through to the saved plan.`}))}R=we}catch(we){let ot=we instanceof Error?we.message:String(we);return d(`Submitting your answers failed: ${ot}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(V.outcome==="declined")return L.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(V.outcome==="cancelled")return L.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);V.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${V.errorMessage}) \u2014 falling back to prose flow.`)}}return d(JSON.stringify({status:"clarify",requires_user_input:!0,nextAction:"STOP \u2014 DO NOT submit answers yourself. Render every entry in `askUserQuestions` via your host's native question tool (AskUserQuestion in Claude Code, request_user_input in OpenAI Codex Plan mode, quick pick in Cursor) and WAIT for the user to actually answer. If your host has no native question tool, stop your turn, print the questions verbatim as a numbered list with all options visible, and wait for the user's next message. Calling mist_plan with answers in the same turn you received the questions is ALWAYS wrong, regardless of how obvious `recommended` looks.",conversation_id:R.conversation_id,questions:v,questionCount:v.length,suggestedFeatures:x,suggestedName:g,suggestedSubdomain:ye,reflection:m,briefText:oe,askUserQuestions:X,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: "${ye}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.',...m||oe?["","\u2500\u2500\u2500 BACKGROUND (not for you to summarize and proceed \u2014 it's what the user will see when you show them the questions) \u2500\u2500\u2500",...m?[m]:[],...oe?["",oe]:[]]:[],...K?["",K]:[]].join(`
|
|
2452
|
-
`)}))}if(R.status==="design_clarify"){let m=R.directions??[],g=R.plan.name??"your app",x=R.design_conversation_id,v;try{let C={};if(x)try{C=await Cr(x)}catch{}let X=m.map(V=>{let ce=V.id?C[V.id]:void 0;return{id:V.id,name:V.name,summary:V.summary,hero_headline:V.hero_headline,cta_text:V.cta_text,body_sample:V.body_sample,fonts:V.fonts,colors:V.colors,hero_treatment:V.hero_treatment,shape_lang:V.shape_lang,texture:V.texture,decoration_hint:V.decoration_hint,mockup_b64:ce?.status==="done"?ce.image_b64:void 0}}),ae=process.env.MISTFLOW_API_URL||"https://api.mistflow.ai",ee=ri(ae),le=x?`${ee}/picker/${encodeURIComponent(x)}`:void 0,oe=Zs(g,X,{dashboardPickerUrl:le}),ye=Te(n,".mistflow");hn(ye,{recursive:!0});let Z=Te(ye,"design-directions.html");Xn(Z,oe,"utf-8"),v=Z}catch(C){console.error(`[mist_plan] design-directions preview render failed: ${C instanceof Error?C.message:String(C)}`)}if(process.env.MISTFLOW_PICKER_USE_DASHBOARD==="true"&&process.env.MISTFLOW_PICKER_USE_HTML!=="true"&&R.design_conversation_id){let C=R.design_conversation_id,X=process.env.MISTFLOW_API_URL||"https://api.mistflow.ai",ee=`${ri(X)}/picker/${encodeURIComponent(C)}`;try{let le=await Pr(C,{waitSeconds:0});if(le.status==="picked")if(le.plan)R={status:"ready",plan:le.plan,methodology:le.methodology??"",...le.designMd?{designMd:le.designMd}:{}};else return d("Pick succeeded but the backend didn't return a finalized plan. Backend may be running an older build than this MCP expects. Re-run mist_plan to start over.",!0);else{let oe=po(ee);await me(j,"PICKING_DESIGN",["GENERATING_PLAN","ASKING_QUESTIONS"]);let ye=oe.opened?`Picker open in your browser at ${ee}
|
|
2060
|
+
Default path: \`${w}\``,"scope");if(F.outcome==="submitted"){let oe=F.answers?.[0]?.answer??"",le=oe.toLowerCase(),ie=oe.startsWith("/")?oe:null;if(ie||le.startsWith("create at:")||le.startsWith("choose a different path")){let L=ie||(le.startsWith("choose a different path")?null:w);if(!L)return p("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);q=L;let J=Xo(q);if(J)return p(`Mistflow could not create the scaffold directory at ${q}: ${J}`,!0);Q=`Note: Mistflow will scaffold the new app at \`${q}\`. The existing project at \`${n}\` is not modified.`}else return le.startsWith("cancel")?p("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(`User submitted an unrecognized scope choice: ${oe}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return F.outcome==="declined"?p("User declined the scope confirmation. They wanted to edit the existing project, not create a new Mistflow app. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(Zo({projectPath:n,description:H,confirmToken:O,suggestedPath:w,previousTokenInvalid:!!W}))}else return p(Zo({projectPath:n,description:H,confirmToken:O,suggestedPath:w,previousTokenInvalid:!!W}))}}}if(c)try{if(!(await Hr(c)).plan)return p("This template has no plan to fork. Try a different template.",!0);let g=await Wr(c),w=g.plan,T="";if(u&&g.has_source)try{let J=await Un(g.plan,u),ve=J.plan??J,re=J.diff,ce=ve?.steps??[],Te=new Set([...(re?.added??[]).map(f=>f.number),...(re?.modified??[]).map(f=>f.number)]),ue=ce.map(f=>{let E=f.number;return Te.has(E)?{...f,status:"pending"}:{...f,status:"completed",source:"forked"}});ve.steps=ue,w=ve;let C=ue.filter(f=>f.status==="pending").length;T=` Remixed: ${ue.filter(f=>f.status==="completed").length} steps unchanged, ${C} steps need re-implementation.`}catch(J){console.error("[plan] Remix failed, using original plan:",J),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let O=Yo(),F=ye(ut(),".mistflow","plans");It(F,{recursive:!0}),pt(ye(F,`${O}.json`),JSON.stringify({plan:w,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let oe=w?.name??"forked-app",le=g.has_source,ie=le?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",L=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return p(JSON.stringify({planId:O,forkedFrom:g.forked_from,projectId:g.id,hasSource:le,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${T}${L} ${ie} NEXT: Call mist_init, name='${oe}', and planId='${O}' to create the project now.`}))}catch(m){let g=m instanceof Error?m.message:"Failed to fork template";return p(g,!0)}if(ne){let m;if(n){let L=ye(n,"PLAN.md");if(Xe(L))try{m=gn(L,"utf-8")}catch(J){console.error(`[mist_plan:modify] PLAN.md read failed (${L}): ${J instanceof Error?J.message:String(J)}`)}}let g;try{g=await Un(ne,H,{planMd:m})}catch(L){let J=L instanceof Error?L.message:"Failed to modify plan";return p(J,!0)}let w=g.plan,T=g.diff,O=typeof g.plan_md=="string"?g.plan_md:null,F,oe;if(O&&n)try{let L=ye(n,"PLAN.md");pt(L,O,"utf-8"),F=L}catch(L){oe=L instanceof Error?L.message:String(L)}let le=[];if(T?.added?.length){let L=T.added.map(J=>J.title);le.push(`Added ${L.length} step(s): ${L.join(", ")}`)}if(T?.removed?.length){let L=T.removed.map(J=>J.title);le.push(`Removed ${L.length} step(s): ${L.join(", ")}`)}if(T?.modified?.length){let L=T.modified.map(J=>J.title);le.push(`Modified ${L.length} step(s): ${L.join(", ")}`)}let ie=le.length>0?le.join(". "):"No changes detected.";return p(JSON.stringify({plan:w,diff:T,planMdPath:F,planMdError:oe,message:`Plan modified. ${ie}. Update mistflow.json with the new plan${F?"; PLAN.md has been regenerated at "+F:""}, then continue with mist_implement.`}))}let P=_?.trim()||void 0,se=s;if(Array.isArray(s)){let m=s.findIndex(g=>g&&typeof g=="object"&&g.decisionKey==="urlChoice");if(m>=0){let g=s[m];!P&&g.answer&&(P=g.answer);let w=s.slice(0,m).concat(s.slice(m+1));se=w.length>0?w:void 0}}else if(s!=null){let m=s;if(!P&&Xn in m&&(P=m[Xn]),!P&&"urlChoice"in m&&(P=m.urlChoice),Xn in m||"urlChoice"in m){let{[Xn]:g,urlChoice:w,...T}=m;se=Object.keys(T).length>0?T:void 0}}if(P&&(P=P.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),P){let m=P.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(m)?P=m:(console.error(`[mist_plan] Discarding urlChoice '${P}' \u2014 does not look like a subdomain. Backend will auto-generate.`),P=void 0)}let B;if(y){B={...y},delete B.userConfirmedCustom,delete B.user_confirmed_custom;let m={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[g,w]of Object.entries(m))y[g]!==void 0&&B[w]===void 0&&(B[w]=y[g])}let b=B!==void 0&&typeof B.custom=="string"&&!B.id&&!B.name,$=A===!0||y!==void 0&&(y.userConfirmedCustom===!0||y.user_confirmed_custom===!0);if(b&&k)try{let m=await On(k);if(m.status==="pending")return p(`Refusing to submit a custom design direction: the backend's direction-generation BG task is still running (status: pending). The user has not yet had the chance to see the real directions. Stop asking the user about aesthetic / fonts / colors / mood right now \u2014 the backend will produce 3-4 concrete options shortly. Re-call mist_plan with { projectPath, conversationId, designConversationId: '${k}' } to keep polling. When directions are ready (status: 'design_clarify'), surface them to the user via AskUserQuestion. Custom is only legitimate AFTER the user has seen the real options and explicitly rejected them \u2014 never as a workaround for a slow generation run.`,!0);if(m.status==="ready"&&Array.isArray(m.directions)&&m.directions.length>0&&!$){let g=m.directions.map(w=>w.name).join(", ");return p(`Refusing to submit a custom design direction: the backend has ${m.directions.length} real directions ready (${g}). The picker is mandatory \u2014 you must surface those exact directions to the user via AskUserQuestion before submitting any pick. Re-call mist_plan with { conversationId, designConversationId: '${k}' } to get the picker payload (status: 'design_clarify'), render the directions HTML preview at .mistflow/design-directions.html for the user, then submit the user's choice. If the user opens the preview, sees the ${m.directions.length} directions, rejects all of them, and types their own description, ONLY THEN retry this call with userConfirmedCustom: true. Never set userConfirmedCustom: true without first showing the user the real directions.`,!0)}}catch(m){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${m instanceof Error?m.message:String(m)}`)}let V=s?"Generating plan with your answers (LLM call)":k?"Finalizing design direction":"Thinking through discovery questions",M=e?qe(e.server,e.progressToken,()=>V):{stop:()=>{}};if(e&&(e.cleanup=()=>M.stop()),!i&&!o&&!k&&!a&&!l&&!c&&!W&&H.trim().length>0&&!z)try{let m=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),g=336*60*60*1e3,w=Date.now()-g,O=(await an(Jo())).filter(F=>!m.has(F.state)).filter(F=>{let oe=Date.parse(F.updated_at);return Number.isFinite(oe)&&oe>=w}).sort((F,oe)=>Date.parse(oe.updated_at)-Date.parse(F.updated_at)).slice(0,5);if(O.length>0)return M.stop(),p(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:O.map(F=>({sessionId:F.id,state:F.state,description:F.description,currentStep:F.current_step,awaitingInput:F.awaiting_input,updatedAt:F.updated_at})),instruction:"This machine has unfinished Mistflow build(s) in flight. Before starting a new project, ask the user whether they want to resume one of these or start fresh. Show the description, state, and updatedAt for each candidate so they can pick.",nextAction:"Step 1: Show the candidates to the user via your host's question UI (AskUserQuestion in Claude Code, request_user_input in Codex Plan mode, quick pick in Cursor). Step 2a (resume): if they pick a candidate, call mist_session({ action: 'resume', sessionId: '<picked>', projectPath }) and follow the next instruction it returns. Step 2b (start fresh): if they want a new build, call mist_plan again with the SAME description and projectPath, plus forceNew: true. The forceNew flag suppresses this check so the new session can be minted."}))}catch(m){console.error("resume-offer check failed (falling through to bootstrap):",m instanceof Error?m.message:m)}let te=i,R;try{ee&&!se&&!k&&!ne&&!l?R=await Mn(ee):R=await Ln(H,{conversationId:ee,answers:se,autonomous:h,language:d,designConversationId:k,designDirection:B})}catch(m){M.stop();let g=m instanceof Error?m.message:"Failed to generate plan";return p(g,!0)}let ge=R.session_id;if(!te&&ge){te=ge;try{await on(ge,{machine_id:Jo(),local_path:n})}catch(m){console.error("workspace bind failed (resume offers will miss this session):",m instanceof Error?m.message:m)}}if(R.status==="clarify_pending"){M.stop();let m=R;return p(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:te,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.${te?` Carry sessionId="${te}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(R.status==="plan_pending"){M.stop();let m=R;return p(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:te,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(R.status==="design_clarify_pending"&&(V="Generating creative design directions",R=await wd(R)),R.status==="design_clarify_pending")return M.stop(),p(JSON.stringify({status:"running",conversationId:o,designConversationId:R.design_conversation_id,sessionId:te,phase:"generating_design_directions",nextAction:`Creative design directions are still generating (45-60s typical, can stretch on slow runs). Call mist_plan with { projectPath, conversationId: "${o??""}" } IMMEDIATELY to keep polling \u2014 do NOT run bash sleep, do NOT submit a designDirection of your own, do NOT mark the plan as ready, and DO NOT ASK THE USER about aesthetic / fonts / colors / mood / vibe / style while you wait. The backend is generating 3-4 concrete direction options the user will pick from \u2014 asking the user to invent one defeats the entire feature, and the server will reject any { custom } submission while directions are still pending. Just poll. The picker is mandatory; keep polling until status becomes 'design_clarify' with the directions array, then surface those exact directions to the user via AskUserQuestion.`}));if(M.stop(),R.status==="clarify"){let m=R.reflection||"",g=R.suggestedName||"",w=R.suggestedFeatures??[],T=R.questions??[],O=T.some(re=>Array.isArray(re.options)&&typeof re.options[0]=="object"&&re.options[0]?.label),F={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},oe=T.map(re=>{let ce=re.decisionKey&&F[re.decisionKey]||yd(re.question),Te;return O&&Array.isArray(re.options)?Te=re.options.map(ue=>({label:ue.label,description:ue.description??""})):Array.isArray(re.options)?Te=re.options.map((ue,C)=>({label:C===0?`${ue} (Recommended)`:String(ue),description:re.why??""})):Te=[{label:"Yes (Recommended)",description:re.why??""},{label:"No",description:""}],{question:re.question,header:ce,options:Te,multiSelect:!1}}),ie=R.decisions?.audienceType??null,L=w.length>0?Wo(H,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:ie,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:w,language:d}):null,J=L?Go(L):"",ve=Yn(g||"my-app").slice(0,32);try{let re=await Nn(ve);!re.available&&re.suggestion&&(ve=re.suggestion)}catch{}if(J&&(J+=`
|
|
2453
2061
|
|
|
2454
|
-
|
|
2455
|
-
${
|
|
2062
|
+
**Your app URL (you can change this before scaffolding):** https://${ve}.mistflow.app`),e?.server){let re=[g?`## ${g}`:"## Pick a few details","",`${T.length} quick question${T.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
|
|
2063
|
+
`),ce=await mn(e.server,T,re,"clarify");if(ce.outcome==="submitted"){M.stop();let Te={};for(let C of ce.answers??[])C.decisionKey?Te[C.decisionKey]=C.answer:Te[C.question]=C.answer;let ue=ce.urlChoice?.trim();ue&&(ue=ue.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let C=await Ln(H,{conversationId:R.conversation_id,answers:Te,autonomous:h,language:d});if(C.status==="plan_pending"){let xe=C;return p(JSON.stringify({status:"running",conversationId:xe.conversation_id,phase:"generating_plan",...ue?{urlChoice:ue}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${xe.conversation_id}"${ue?`, urlChoice: "${ue}"`:""} } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll up to ~10s and returns when the plan lands. Pass urlChoice on every poll so it threads through to the saved plan.`}))}R=C}catch(C){let xe=C instanceof Error?C.message:String(C);return p(`Submitting your answers failed: ${xe}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(ce.outcome==="declined")return M.stop(),p("User declined the planning flow via the form. They likely want a different approach \u2014 ask them what they'd prefer instead of re-running mist_plan.",!0);if(ce.outcome==="cancelled")return M.stop(),p("User cancelled the planning form without picking. The conversation is still alive \u2014 re-run mist_plan with the same conversationId if they want to retry, or start a fresh plan if they want to change the description.",!0);ce.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${ce.errorMessage}) \u2014 falling back to prose flow.`)}}return p(JSON.stringify({status:"clarify",requires_user_input:!0,nextAction:"STOP \u2014 DO NOT submit answers yourself. Render every entry in `askUserQuestions` via your host's native question tool (AskUserQuestion in Claude Code, request_user_input in OpenAI Codex Plan mode, quick pick in Cursor) and WAIT for the user to actually answer. If your host has no native question tool, stop your turn, print the questions verbatim as a numbered list with all options visible, and wait for the user's next message. Calling mist_plan with answers in the same turn you received the questions is ALWAYS wrong, regardless of how obvious `recommended` looks.",conversation_id:R.conversation_id,questions:T,questionCount:T.length,suggestedFeatures:w,suggestedName:g,suggestedSubdomain:ve,reflection:m,briefText:J,askUserQuestions:oe,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:["\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST ask the user via your host's native structured-question","tool (not a text prompt, not a bash echo, not a chat message).","The user has to actually choose. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","Per host (use whichever applies):"," \u2022 Claude Code \u2192 AskUserQuestion tool"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) \u2192 request_user_input returns"," 'unavailable in <mode> mode'. When you see that error, STOP"," your turn, print the questions as a numbered chat message"," with all options visible, and wait for the user's next"," message. Do NOT resume by picking answers yourself."," \u2022 Any host without a native question tool \u2192 same as above:"," stop your turn, print the questions, wait.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 'Locking in the defaults with X as the only override.'"," (inferring answers from the original spec)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping the question UI because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call the tool (when available): pass each object in the","`askUserQuestions` array below. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${R.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${ve}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.',...m||J?["","\u2500\u2500\u2500 BACKGROUND (not for you to summarize and proceed \u2014 it's what the user will see when you show them the questions) \u2500\u2500\u2500",...m?[m]:[],...J?["",J]:[]]:[],...Q?["",Q]:[]].join(`
|
|
2064
|
+
`)}))}if(R.status==="design_clarify"){let m=R.directions??[],g=R.plan.name??"your app",w=R.design_conversation_id,T=m.map(S=>({id:S.id,name:S.name,summary:S.summary,hero_headline:S.hero_headline,cta_text:S.cta_text,body_sample:S.body_sample,fonts:S.fonts,colors:S.colors,hero_treatment:S.hero_treatment,shape_lang:S.shape_lang,texture:S.texture,decoration_hint:S.decoration_hint})),O={},F=!1;try{if(w){let me=Date.now();for(;Date.now()-me<5e4;){let Z=await Dn(w),Y=0;for(let x of T){let j=Z[x.id];j&&((j.status==="done"||j.status==="ready")&&typeof j.html=="string"&&j.html.length>0?(O[x.id]=j.html,Y+=1):j.status==="failed"&&(Y+=1))}if(Y===T.length){F=!0;break}await new Promise(x=>setTimeout(x,5e3))}}}catch(S){console.error(`[mist_plan:design_clarify] render poll failed: ${S instanceof Error?S.message:String(S)}`)}if(!F)return p(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:R.conversation_id??o,design_conversation_id:w,renderedSoFar:Object.keys(O).length,totalDirections:T.length,nextAction:`${Object.keys(O).length}/${T.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${R.conversation_id??o??""}" } again IMMEDIATELY \u2014 do NOT bash sleep. Do NOT ask the user about design yet.`}));let oe=T.filter(S=>O[S.id]),le,ie,L=ye(n,".mistflow"),J=ye(L,"design-directions.html"),ve=ye(L,"picker-state.json"),re=()=>{try{if(Xe(ve))return JSON.parse(gn(ve,"utf-8"))}catch{}return{}},ce=S=>{try{It(L,{recursive:!0}),pt(ve,JSON.stringify(S,null,2),"utf-8")}catch(de){console.error(`[mist_plan:design_clarify] sidecar write failed: ${de instanceof Error?de.message:String(de)}`)}},Te=re(),ue=w&&Te.opened_for_design_cid===w;try{if(It(L,{recursive:!0}),ue)le=J;else{let S=ls(g,oe,O);pt(J,S,"utf-8"),le=J;let de=as(`file://${J}`);de.opened||(ie=de.reason),w&&ce({opened_for_design_cid:w,elicit_state:"pending",elicit_design_cid:w,opened_at:new Date().toISOString()})}}catch(S){console.error(`[mist_plan:design_clarify] picker write/open failed: ${S instanceof Error?S.message:String(S)}`)}let C=re(),xe=oe.map(S=>({id:S.id,name:S.name})),f=xe.map(S=>S.name).filter(Boolean);if(e?.server&&w&&C.elicit_design_cid===w&&C.elicit_state==="pending"){let S=le?[`## ${g} \u2014 pick a creative direction`,"",`${oe.length} directions, each with its own fonts, colors, and mood.`,"",`Visual preview (auto-opened in your browser): file://${le}`,"Each card shows what you'd be picking \u2014 fonts, colors, hero layout."].join(`
|
|
2065
|
+
`):`## ${g} \u2014 pick a creative direction
|
|
2456
2066
|
|
|
2457
|
-
|
|
2067
|
+
${oe.length} directions, each with its own fonts, colors, and mood. Pick one or describe your own.`,de=oe.map(me=>({label:me.name,description:me.summary??""}));de.push({label:"Describe your own direction",description:"Skip the proposed options and type a short description of how the app should feel."});try{let me=await mn(e.server,[{question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,decisionKey:"designDirection",options:de,noOtherSentinel:!0,otherFieldTitle:"If 'Describe your own direction' was picked: type how the app should feel (fonts, colors, mood \u2014 your words)."}],S,"design");if(me.outcome==="submitted"&&me.answers?.[0]){let Z=me.answers[0].answer.trim(),Y=oe.find(j=>j.name===Z),x=Y?{direction_id:Y.id}:{custom:Z};(R.conversation_id??o)&&(x.conversation_id=R.conversation_id??o);try{let j=await jn(w,x);ce({...C,elicit_state:"completed",elicit_design_cid:w}),R={status:"ready",plan:j.plan??{},methodology:j.methodology??"",...j.designMd?{designMd:j.designMd}:{}}}catch(j){return console.error(`[mist_plan:design_clarify] submitDesignPick failed: ${j instanceof Error?j.message:String(j)}`),ce({...C,elicit_state:"skipped"}),p(`Design submission failed: ${j instanceof Error?j.message:String(j)}. Ask the user to retry by re-running mist_plan with their pick.`,!0)}}else return ce({...C,elicit_state:"skipped"}),p(JSON.stringify({status:"design_clarify",previewPath:le,previewOpenError:ie,directionRefs:xe,directionNames:f,design_conversation_id:w,conversation_id:R.conversation_id??o,nextAction:[`The user closed the elicit picker without picking. The visual picker is still open at file://${le??"(path missing)"}.`,`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask which direction they pick. List EXACTLY these names: ${f.map(Z=>`"${Z}"`).join(", ")}.`,`When they pick, call mist_plan with { projectPath, conversationId: "${R.conversation_id??o??""}", designConversationId: "${w??""}", designDirection: { id: "<id from directionRefs>" } }.`].join(`
|
|
2458
2068
|
|
|
2459
|
-
|
|
2460
|
-
`):`## ${g} \u2014 pick a creative direction
|
|
2069
|
+
`)}))}catch(me){console.error(`[mist_plan:design_clarify] elicit failed: ${me instanceof Error?me.message:String(me)}`),ce({...C,elicit_state:"skipped"})}}if(R.status==="design_clarify")return p(JSON.stringify({status:"design_clarify",previewPath:le,previewOpenError:ie,directionRefs:xe,directionNames:f,design_conversation_id:w,conversation_id:R.conversation_id??o,nextAction:[`The visual picker is open in the user's browser at file://${le??"(path missing)"} \u2014 every direction is a real, rendered landing page.`,ie?`(auto-open suppressed: ${ie} \u2014 tell the user to open file://${le} manually)`:"",`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names: ${f.map(S=>`"${S}"`).join(", ")}. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${R.conversation_id??o??""}", designConversationId: "${w??""}", designDirection: { id: "<map name \u2192 id from directionRefs>" } }. If they describe their own, pass designDirection: { custom: "<their exact words>" } and userConfirmedCustom: true.`].filter(Boolean).join(`
|
|
2461
2070
|
|
|
2462
|
-
|
|
2463
|
-
`):"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.",ee=v?`open "${v}"`:"";return d(JSON.stringify({status:"design_clarify",requires_user_input:!0,designConversationId:R.design_conversation_id,directions:m,previewPath:v,askUserQuestion:X,instruction:[`The plan for "${g}" is ready. I've proposed ${m.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","",ae,ee?`Run this command to open the preview for the user: ${ee}`:"","","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(`
|
|
2464
|
-
`)}))}}}if(R.status!=="ready")return d(`Unexpected plan status after build: ${R.status}. Please retry by calling mist_plan with the same conversationId.`,!0);await me(j,"ASKING_QUESTIONS",["NEW"]),await me(j,"GENERATING_PLAN",["ASKING_QUESTIONS"]),await me(j,"READY_TO_SCAFFOLD",["GENERATING_PLAN","DESIGN_PICKING","DESIGN_DIRECTIONS_READY","MOCKUP_REVIEW"]);let N=R.plan,Ie=N.name??"Untitled App",Pe=R.methodology,Y=N.steps;if(!Array.isArray(Y)||Y.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 he=N.suggestedSubdomain??Yn(Ie).slice(0,32)??"my-app";if(!A&&e?.server){try{let g=await On(he);!g.available&&g.suggestion&&(he=g.suggestion)}catch{}let m=await mn(e.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${he}.mistflow.app`,why:"Subdomains lock in at scaffold time and are baked into auth callbacks, share links, and analytics. Pick the default to ship now, or type a custom subdomain in the textbox below.",options:[{label:`Keep ${he}.mistflow.app`,description:"Use the suggested subdomain"},{label:"Type a different subdomain",description:"Custom subdomain \u2014 fill the textbox below"}],noOtherSentinel:!0,otherFieldTitle:"Custom subdomain (e.g. 'sales-comm') \u2014 lowercase, alphanumeric + hyphens, 3-32 chars"}],`## ${Ie} \u2014 pick the URL
|
|
2071
|
+
`)}))}if(R.status!=="ready")return p(`Unexpected plan status after build: ${R.status}. Please retry by calling mist_plan with the same conversationId.`,!0);let K=R.plan,ae=K.name??"Untitled App",Oe=R.methodology,ke=K.steps;if(!Array.isArray(ke)||ke.length===0)return p("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let we=K.suggestedSubdomain??Yn(ae).slice(0,32)??"my-app";if(!P&&e?.server){try{let g=await Nn(we);!g.available&&g.suggestion&&(we=g.suggestion)}catch{}let m=await mn(e.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${we}.mistflow.app`,why:"Subdomains lock in at scaffold time and are baked into auth callbacks, share links, and analytics. Pick the default to ship now, or type a custom subdomain in the textbox below.",options:[{label:`Keep ${we}.mistflow.app`,description:"Use the suggested subdomain"},{label:"Type a different subdomain",description:"Custom subdomain \u2014 fill the textbox below"}],noOtherSentinel:!0,otherFieldTitle:"Custom subdomain (e.g. 'sales-comm') \u2014 lowercase, alphanumeric + hyphens, 3-32 chars"}],`## ${ae} \u2014 pick the URL
|
|
2465
2072
|
|
|
2466
|
-
The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(m.outcome==="submitted"){let g=m.urlChoice?.trim()||m.answers?.[0]?.answer.trim()||"";g=g.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(g)||!g)&&(g=he);let x=g.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(x)?A=x:(console.error(`[mist_plan] URL elicitation returned '${g}' \u2014 does not look like a subdomain. Using default '${he}'.`),A=he)}else m.outcome==="declined"||m.outcome,A=he}else A||(A=he);let xe=N.publicPages;if(!xe||Array.isArray(xe)&&xe.length===0){let m=N.pages,g=Y.some(v=>typeof v.name=="string"&&v.name.toLowerCase().includes("landing")||typeof v.title=="string"&&v.title.toLowerCase().includes("landing")),x=Array.isArray(m)&&m.some(v=>v.path==="/"||v.route==="/");g||x?xe=["/","/pricing"]:xe=["/"]}let Oe=N.primaryAction;if(!Oe){let m=N.features;if(Array.isArray(m)&&m.length>0){let x=m.find(H=>typeof H.priority=="string"&&H.priority.toLowerCase()==="must-have")??m[0];Oe={entity:x.name??x.title??"item",action:"create",fromPage:"/dashboard"}}}let et=N.nonNegotiables;(!et||Array.isArray(et)&&et.length===0)&&(et=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let bt=ni(),tt=Te(ut(),".mistflow","plans");hn(tt,{recursive:!0});try{let g=Date.now();for(let x of[tt,Te(ut(),".mistflow","mockup-state")])if(zt(x))for(let v of li(x))try{let H=Te(x,v),C=ci(H).mtimeMs;g-C>6048e5&&hd(H)}catch{}}catch{}let Ee=N,Ct={name:N.name,summary:N.summary,dataModel:N.dataModel,pages:N.pages,features:N.features,steps:Y.map(m=>({...m,name:m.name??m.title})),design:N.design,dbProvider:N.dbProvider??"neon",authModel:N.authModel,audienceType:N.audienceType??"b2c",roles:N.roles,defaultRole:N.defaultRole,publicPages:xe,navStyle:N.navStyle,multiTenant:N.multiTenant,primaryAction:Oe,nonNegotiables:et,requestedSubdomain:A,...u&&u.toLowerCase()!=="english"?{language:u}:{},...Ee.pickedDirection?{pickedDirection:Ee.pickedDirection}:{},...Ee.imageryBrief?{imageryBrief:Ee.imageryBrief}:{},...Ee.designConversationId?{designConversationId:Ee.designConversationId}:{}};Xn(Te(tt,`${bt}.json`),JSON.stringify({plan:Ct,methodology:Pe,...D?{scaffoldTargetPath:D}:{}}));let nt=Y.map(m=>`${m.number}. ${m.name??m.title}`),G,pe="";if(!!!Ee.pickedDirection){let g=(N.audienceType??"b2c")==="b2c";G={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:g?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:g?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},pe=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call."}let rt="",De=[];for(let m of Y){let g=m.name??m.title,x=m.integrationId;if(x){let v=Mt(x);if(v){let H=$t(v.id);De.push({step:g,presetId:v.id,presetName:v.name,envVars:H?.envVars??[]})}}}if(De.length>0){let m=De.flatMap(v=>v.envVars),g=[...new Set(m.map(v=>v.key))];rt=` This plan uses integrations (${De.map(v=>v.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:bt,name:N.name,summary:N.summary,stepCount:Y.length,steps:nt,design:N.design,...G?{heroPhotoQuestion:G}:{},...De.length>0?{integrations:De.map(m=>({step:m.step,preset:m.presetId,name:m.presetName,envVars:m.envVars}))}:{},message:`Plan generated for "${Ie}" (${Y.length} steps).${rt}${pe}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,Y.length*3)}\u2013${Y.length*5} minutes total across ${Y.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: '${bt}' }). If the user says skip or "just build it", call mist_init({ planId: '${bt}'${D?"":", path: '<absolute path>'"} }) immediately.`,...D?{scaffoldTargetPath:D}:{},...K?{warning:K}:{}}))}var Qn,vd,Cd,hi,gi=T(()=>{"use strict";fe();ke();Vs();pt();Ft();Ks();zn();Qs();ei();Qn="__mistflow_url_choice__",vd=600*1e3;Cd=$.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."),sessionId:$.string().uuid().optional().describe("Backend-owned session ID. When present, mist_plan polls GET /api/sessions/{id}/next and returns the next instruction (wait, ask_user, pick_design, call_mist_init, etc.). Pass it on every subsequent mist_* call to keep the same session."),conversationId:$.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:$.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("[")&&!e.startsWith("{"))return t;try{return JSON.parse(e)}catch{return t}},$.union([$.record($.string()),$.array($.object({question:$.string().optional(),decisionKey:$.string().optional(),answer:$.string()}))]).optional()).describe("User's answers to the clarifying questions. Pass an ARRAY of { question, decisionKey, answer } objects directly \u2014 do NOT stringify it as JSON. The schema also accepts a { '<question text>': '<answer label>' } object map for one-question-per-decisionKey rounds. Strings that look like JSON arrays/objects are auto-parsed for resilience."),existingPlan:$.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."),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."),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."),userConfirmedCustom:$.boolean().optional().describe("Set true ONLY when the user themselves typed a custom direction (via AskUserQuestion 'Other' or by explicitly describing the look in the chat). Required when submitting designDirection: { custom: ... } if the backend has real directions cached \u2014 the server rejects custom submissions otherwise to stop the AI from silently bypassing the picker. NEVER set this true unless the words in `custom` came directly from the user."),forceNew:$.boolean().optional().describe("Set to true ONLY after the user has explicitly chosen 'start fresh' from a previous mist_plan response with status 'resume_offer'. Suppresses the resume-offer check and lets a new session start even when this machine has unfinished work in flight. Do NOT set this preemptively on the first call \u2014 the resume-offer check needs to run so the user gets the chance to pick up where they left off.")});hi={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist'). Clear new-app requests inside an existing non-Mistflow repo are scaffolded into a remembered child directory; Mistflow does not edit the surrounding codebase.","",`DESIGN REFERENCES (screenshots, Figma, brand names): if the user drags a screenshot, pastes a Figma URL, or names a brand to match ("make it feel like Linear"), use your native vision/knowledge to extract design tokens and submit them via designDirection: { custom: '<your description>', ...extracted_tokens } with userConfirmedCustom: true. The flag is required because the user supplied the reference; without it the server rejects the submission to stop AIs from inventing custom directions. Full flow at docs/design-references.md.`,"","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). For clear new-app requests it automatically creates and remembers a child scaffold directory. For ambiguous requests, it returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token from the response. Do not change projectPath to the suggested child path; Mistflow stores that target for mist_init.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_init with the returned planId. If the response includes scaffoldTargetPath you do not need to pass path; mist_init loads it from the cached plan. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","SESSIONID FLOW (dumb-ai-proof, when the response includes sessionId): keep the sessionId and pass it on every subsequent mist_* call. Calling mist_plan with just { sessionId, projectPath } polls GET /api/sessions/{id}/next and returns the next instruction (wait | ask_user | pick_design | review_mockup | call_mist_init | call_mist_install | call_mist_implement | call_mist_build | call_mist_deploy | call_mist_qa | done). Do exactly what the instruction says \u2014 don't branch on raw state. The backend owns routing; the host relays.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. The aesthetic (fonts, colors, motion) is decided by the design-direction picker step \u2014 the host AI doesn't pick a catalog ID."].join(`
|
|
2467
|
-
`),inputSchema:Cd,handler:$d}});var Zn,mo=T(()=>{Zn="\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 er,ho=T(()=>{er=`# Landing Page Rules
|
|
2073
|
+
The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(m.outcome==="submitted"){let g=m.urlChoice?.trim()||m.answers?.[0]?.answer.trim()||"";g=g.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(g)||!g)&&(g=we);let w=g.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(w)?P=w:(console.error(`[mist_plan] URL elicitation returned '${g}' \u2014 does not look like a subdomain. Using default '${we}'.`),P=we)}else m.outcome==="declined"||m.outcome,P=we}else P||(P=we);let Le=K.publicPages;if(!Le||Array.isArray(Le)&&Le.length===0){let m=K.pages,g=ke.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),w=Array.isArray(m)&&m.some(T=>T.path==="/"||T.route==="/");g||w?Le=["/","/pricing"]:Le=["/"]}let Rt=K.primaryAction;if(!Rt){let m=K.features;if(Array.isArray(m)&&m.length>0){let w=m.find(O=>typeof O.priority=="string"&&O.priority.toLowerCase()==="must-have")??m[0];Rt={entity:w.name??w.title??"item",action:"create",fromPage:"/dashboard"}}}let Ve=K.nonNegotiables;(!Ve||Array.isArray(Ve)&&Ve.length===0)&&(Ve=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let He=Yo(),nt=ye(ut(),".mistflow","plans");It(nt,{recursive:!0});try{let g=Date.now();for(let w of[nt,ye(ut(),".mistflow","mockup-state")])if(Xe(w))for(let T of ti(w))try{let O=ye(w,T),F=ni(O).mtimeMs;g-F>6048e5&&nd(O)}catch{}}catch{}let Ce=K,X={name:K.name,summary:K.summary,dataModel:K.dataModel,pages:K.pages,features:K.features,steps:ke.map(m=>({...m,name:m.name??m.title})),design:K.design,dbProvider:K.dbProvider??"neon",authModel:K.authModel,audienceType:K.audienceType??"b2c",roles:K.roles,defaultRole:K.defaultRole,publicPages:Le,navStyle:K.navStyle,multiTenant:K.multiTenant,primaryAction:Rt,nonNegotiables:Ve,requestedSubdomain:P,...d&&d.toLowerCase()!=="english"?{language:d}:{},...Ce.pickedDirection?{pickedDirection:Ce.pickedDirection}:{},...Ce.imageryBrief?{imageryBrief:Ce.imageryBrief}:{},...Ce.designConversationId?{designConversationId:Ce.designConversationId}:{}};pt(ye(nt,`${He}.json`),JSON.stringify({plan:X,methodology:Oe,...q?{scaffoldTargetPath:q}:{}}));let fe=ke.map(m=>`${m.number}. ${m.name??m.title}`),je,rt="";if(!!!Ce.pickedDirection){let g=(K.audienceType??"b2c")==="b2c";je={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:g?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:g?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},rt=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call."}let st="",We=[];for(let m of ke){let g=m.name??m.title,w=m.integrationId;if(w){let T=Lt(w);if(T){let O=Ut(T.id);We.push({step:g,presetId:T.id,presetName:T.name,envVars:O?.envVars??[]})}}}if(We.length>0){let m=We.flatMap(T=>T.envVars),g=[...new Set(m.map(T=>T.key))];st=` This plan uses integrations (${We.map(T=>T.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return p(JSON.stringify({planId:He,name:K.name,summary:K.summary,stepCount:ke.length,steps:fe,design:K.design,...je?{heroPhotoQuestion:je}:{},...We.length>0?{integrations:We.map(m=>({step:m.step,preset:m.presetId,name:m.presetName,envVars:m.envVars}))}:{},message:`Plan generated for "${ae}" (${ke.length} steps).${st}${rt}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,ke.length*3)}\u2013${ke.length*5} minutes total across ${ke.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_mockup({ planId: '${He}' }). If the user says skip or "just build it", call mist_init({ planId: '${He}'${q?"":", path: '<absolute path>'"} }) immediately.`,...q?{scaffoldTargetPath:q}:{},...Q?{warning:Q}:{}}))}var Xn,ld,fd,ii,ai=I(()=>{"use strict";be();_e();zo();qt();Ho();zn();Vo();Ko();Xn="__mistflow_url_choice__",ld=600*1e3;fd=D.object({description:D.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:D.string().min(1).describe("REQUIRED. Absolute path to the user's current working directory \u2014 where the Mistflow app will be scaffolded. Pass the directory the user is actually working in (e.g. /Users/alice/projects). Do NOT pass '/', '~', $HOME, Desktop, Documents, Downloads, or /tmp \u2014 the tool will refuse to scaffold at those locations. If you are unsure of the user's working directory, ask them before calling this tool."),sessionId:D.string().uuid().optional().describe("Backend-owned session ID. When present, mist_plan polls GET /api/sessions/{id}/next and returns the next instruction (wait, ask_user, pick_design, call_mist_init, etc.). Pass it on every subsequent mist_* call to keep the same session."),conversationId:D.string().optional().describe("Returned by a previous mist_plan call with status 'clarify' or 'running'. Pass it back alone (no description) to poll an in-flight discovery call; pass with answers to submit responses."),answers:D.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("[")&&!e.startsWith("{"))return t;try{return JSON.parse(e)}catch{return t}},D.union([D.record(D.string()),D.array(D.object({question:D.string().optional(),decisionKey:D.string().optional(),answer:D.string()}))]).optional()).describe("User's answers to the clarifying questions. Pass an ARRAY of { question, decisionKey, answer } objects directly \u2014 do NOT stringify it as JSON. The schema also accepts a { '<question text>': '<answer label>' } object map for one-question-per-decisionKey rounds. Strings that look like JSON arrays/objects are auto-parsed for resilience."),existingPlan:D.record(D.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:D.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:D.string().optional().describe("Fork from a shared template. Pass the share token (from a mistflow.ai/t/... URL) to clone that project's plan into your workspace."),remixDescription:D.string().optional().describe("Optional remix request when forking a template. Describes how you want the template to be different. E.g. 'Make it for tracking books instead of habits, add a search feature.' Only used with templateToken."),autonomous:D.boolean().optional().describe("DANGER \u2014 only set this to `true` when the user has EXPLICITLY asked to skip discovery questions (phrases like 'no questions', 'just build it', 'autonomous mode', 'don't ask'). Default is `false` and should stay that way in every other case. Do NOT set autonomous=true as a retry strategy after a plan-gen failure \u2014 it doesn't make things more reliable, it just removes the user's control over discovery answers (roles, integrations, auth model, etc.) and Sonnet ends up guessing. If a plan call fails, retry the SAME call with the same parameters, not a more aggressive one. Do NOT set autonomous=true to speed things up \u2014 the server already runs plan-gen in the background and polls, so there is no speed benefit. When set, skips the clarify round and generates the plan straight from the description. The user loses the chance to pick any option."),language:D.string().optional().describe("UI language for the app. All user-facing text, labels, buttons, and content will be generated in this language. Use the language name in English (e.g. 'Spanish', 'French', 'Arabic', 'Japanese'). Defaults to English if not specified."),brandMentioned:D.boolean().optional().describe("Set to true ONLY when the user's original request explicitly invoked Mistflow by name (e.g. 'build me a CRM using mist', 'make a todo app with mistflow'). Skips the existing-project confirmation gate because the user clearly wants Mistflow. Do NOT set this for generic 'build me X' requests. Do NOT infer this \u2014 only set it when the user literally typed 'mist' or 'mistflow'."),confirmToken:D.string().optional().describe("The token returned in a previous mist_plan response with status 'confirm_new_project'. Only pass this AFTER asking the user via AskUserQuestion and they chose to scaffold a new Mistflow app in an existing-project directory. The token is bound to the projectPath and description \u2014 you must pass the SAME description AND projectPath on the retry."),urlChoice:D.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers."),designConversationId:D.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass this ONLY on the SUBMIT call after the user has picked a direction \u2014 i.e. ALWAYS together with `designDirection`. Do NOT include it on polling calls (status: 'rendering_directions' / 'design_clarify_pending') \u2014 for polling, send only `{ projectPath, conversationId }`. Including `designConversationId` without `designDirection` makes the backend respond 'you passed designConversationId but no designDirection' and wastes a round-trip. Decision rule: if the user has not yet typed/clicked a pick, omit this field; if they have, include both this field AND designDirection together in the same call."),designDirection:D.object({id:D.string().optional(),name:D.string().optional(),summary:D.string().optional(),heroHeadline:D.string().optional(),ctaText:D.string().optional(),bodySample:D.string().optional(),fontsHint:D.string().optional(),fonts:D.object({display:D.string(),body:D.string()}).partial().optional(),colorMood:D.string().optional(),colors:D.object({bg:D.string(),fg:D.string(),accent:D.string()}).partial().optional(),heroTreatment:D.string().optional(),shapeLang:D.string().optional(),texture:D.string().optional(),decorationHint:D.string().optional(),custom:D.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass ONLY the minimal shape: (a) `{ id: '<short-kebab-id-from-directionRefs>' }` when the user picked one of the proposed options \u2014 copy the id verbatim from `directionRefs[].id`, e.g. 'morning-paper' or 'quiet-utility'; or (b) `{ custom: '<the user\\'s exact words>' }` + `userConfirmedCustom: true` when the user typed their own description. Do NOT pass the full direction object (name, summary, fonts, colors, hero_headline, body_sample, etc.) \u2014 those fields are ignored and may exceed backend length limits, causing 422 rejections. ID values are short kebab-case strings (\u2264256 chars). Custom descriptions are user-typed prose (\u22644000 chars). Anything longer is wrong."),userConfirmedCustom:D.boolean().optional().describe("Set true ONLY when the user themselves typed a custom direction (via AskUserQuestion 'Other' or by explicitly describing the look in the chat). Required when submitting designDirection: { custom: ... } if the backend has real directions cached \u2014 the server rejects custom submissions otherwise to stop the AI from silently bypassing the picker. NEVER set this true unless the words in `custom` came directly from the user."),forceNew:D.boolean().optional().describe("Set to true ONLY after the user has explicitly chosen 'start fresh' from a previous mist_plan response with status 'resume_offer'. Suppresses the resume-offer check and lets a new session start even when this machine has unfinished work in flight. Do NOT set this preemptively on the first call \u2014 the resume-offer check needs to run so the user gets the chance to pick up where they left off.")});ii={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist'). Clear new-app requests inside an existing non-Mistflow repo are scaffolded into a remembered child directory; Mistflow does not edit the surrounding codebase.","",`DESIGN REFERENCES (screenshots, Figma, brand names): if the user drags a screenshot, pastes a Figma URL, or names a brand to match ("make it feel like Linear"), use your native vision/knowledge to extract design tokens and submit them via designDirection: { custom: '<your description>', ...extracted_tokens } with userConfirmedCustom: true. The flag is required because the user supplied the reference; without it the server rejects the submission to stop AIs from inventing custom directions. Full flow at docs/design-references.md.`,"","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). For clear new-app requests it automatically creates and remembers a child scaffold directory. For ambiguous requests, it returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token from the response. Do not change projectPath to the suggested child path; Mistflow stores that target for mist_init.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_init with the returned planId. If the response includes scaffoldTargetPath you do not need to pass path; mist_init loads it from the cached plan. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","SESSIONID FLOW (dumb-ai-proof, when the response includes sessionId): keep the sessionId and pass it on every subsequent mist_* call. Calling mist_plan with just { sessionId, projectPath } polls GET /api/sessions/{id}/next and returns the next instruction (wait | ask_user | pick_design | review_mockup | call_mist_init | call_mist_install | call_mist_implement | call_mist_build | call_mist_deploy | call_mist_qa | done). Do exactly what the instruction says \u2014 don't branch on raw state. The backend owns routing; the host relays.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. The aesthetic (fonts, colors, motion) is decided by the design-direction picker step \u2014 the host AI doesn't pick a catalog ID."].join(`
|
|
2074
|
+
`),inputSchema:fd,handler:Td}});function _d(t){let e=t.match(/^v?(\d+)\.(\d+)\.(\d+)/);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null}function Bt(t=process.version){let e=_d(t);return!e||e.major>=23?!0:e.major===22?e.minor>=12:e.major===20?e.minor>=19:!1}function Id(t=process.execPath){return t.includes("Library/pnpm/")||t.includes("AppData\\pnpm\\")||t.includes("/.pnpm/")?"pnpm":t.includes("/.fnm/")||process.env.FNM_DIR?"fnm":process.env.NVM_DIR||t.includes("/.nvm/")?"nvm":process.env.VOLTA_HOME||t.includes("/.volta/")?"volta":t.startsWith("/opt/homebrew/")||t.startsWith("/usr/local/")?"brew":t==="/usr/bin/node"?"system":"unknown"}function Pt(t=process.version,e=Id()){let r={pnpm:"Run: pnpm env use --global 22.12.0",fnm:"Run: fnm install 22.12 && fnm use 22.12",nvm:"Run: nvm install 22.12 && nvm use 22.12",volta:"Run: volta install node@22.12",brew:"Run: brew install node@22 && brew link node@22 --force --overwrite",system:"Install Node 22.12+ from https://nodejs.org/download",unknown:"Install Node 22.12+ from https://nodejs.org/download"};return[`OpenNext/Cloudflare builds require Node 20.19+, 22.12+, or 23+. The current MCP process is running ${t}.`,r[e],"Then quit and reopen your IDE so the MCP picks up the new Node."].join(`
|
|
2075
|
+
`)}var Zn=I(()=>{"use strict"});var er,cs=I(()=>{er="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n"});var tr,ds=I(()=>{tr=`# Landing Page Rules
|
|
2468
2076
|
|
|
2469
2077
|
These rules apply to every landing page. They are non-negotiable.
|
|
2470
2078
|
|
|
@@ -2582,13 +2190,15 @@ The most important section. Must have:
|
|
|
2582
2190
|
- One or two CTAs (primary filled button + optional secondary ghost/outline)
|
|
2583
2191
|
- A visual element: product screenshot, photo, abstract shape, or animated element
|
|
2584
2192
|
|
|
2585
|
-
**Hero sizing (must fit the viewport):**
|
|
2586
|
-
- The primary CTA must be visible on a 1280x800 laptop without scrolling.
|
|
2587
|
-
-
|
|
2193
|
+
**Hero sizing (must fit the viewport \u2014 non-negotiable):**
|
|
2194
|
+
- The primary CTA must be visible on a 1280x800 laptop without scrolling.
|
|
2195
|
+
- **Headline cap is \`lg:text-7xl\`. Period.** Do not use \`lg:text-[Nrem]\`, \`lg:text-[Npx]\`, or \`lg:text-8xl\`/\`9xl\` to bypass this \u2014 those all blow past the fold. If the headline still feels small, shorten the copy, don't enlarge the type.
|
|
2588
2196
|
- Cap the headline at 3 lines on desktop. Tighten \`max-w\` on the text column or shorten copy if it wraps to 4+.
|
|
2589
2197
|
- Vertical padding ceiling: \`py-16 lg:py-24\`. Avoid \`py-32\` and above.
|
|
2590
|
-
- Do NOT apply \`min-h-screen\` to the hero section.
|
|
2591
|
-
-
|
|
2198
|
+
- Do NOT apply \`min-h-screen\` to the hero section.
|
|
2199
|
+
- **One visual block in the hero column. ONE.** If you have a hero image, you do not also have a 3-up image grid / shelf / thumbnail strip / second media block stacked below it in the same hero section. Move the secondary block to its own section below the fold.
|
|
2200
|
+
- Split-layout side visual: use \`aspect-square\` or \`aspect-[3/4]\` at most. \`aspect-[4/5]\` is borderline; combined with a tall headline column it overflows. The visual must not dictate section height.
|
|
2201
|
+
- Smell test before declaring the hero done: count the vertical pixels on \`lg\` \u2014 text column (heading \u2264240px + sub \u226480px + CTA row \u226456px + gaps \u226480px \u2248 460px) and visual column (one block \u2264640px). Total section \u2264 720px content + \u2264200px padding. If your numbers exceed that, cut something.
|
|
2592
2202
|
|
|
2593
2203
|
**Hero anti-patterns (instant slop signals):**
|
|
2594
2204
|
- Centered text + centered image below = the most overused AI layout
|
|
@@ -2876,29 +2486,29 @@ app/
|
|
|
2876
2486
|
\`\`\`
|
|
2877
2487
|
|
|
2878
2488
|
Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
|
|
2879
|
-
`});import{existsSync as
|
|
2489
|
+
`});import{existsSync as Ad,readFileSync as Rd,writeFileSync as Ed}from"fs";import{join as li}from"path";function ps(t){return t?Nd[t]??"\u23ED\uFE0F":"\u23ED\uFE0F"}function us(t){return t.name??t.title??`Step ${t.number}`}function ci(t){return t.entity??t.name??"Unknown"}function Od(t){let e=t.fields??[];return e.length===0?"":typeof e[0]=="string"?e.join(", "):e.map(r=>r.name).filter(Boolean).join(", ")}function jd(t){let e=[],r=t.plan,n=(t.name??r?.name??"App").split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ");e.push(`# ${n}`),e.push(""),e.push("Per-app orientation doc for host AIs editing this Mistflow-scaffolded codebase. Pairs with AGENTS.md (stack methodology) and DESIGN.md (aesthetic). Auto-regenerated by mist_init, mist_implement, and mist_deploy."),e.push("");let i=r?.summary??r?.description;if(i){if(e.push("## What this is"),e.push(""),e.push(i),r?.audienceType&&(e.push(""),e.push(`Audience: **${r.audienceType}**.`)),r?.design?.archetype){let c=r.design.tone?` (${r.design.tone} tone)`:"";e.push(`Aesthetic: **${r.design.archetype}**${c} \u2014 see DESIGN.md.`)}e.push("")}let o=r?.steps??[];if(o.length>0){e.push("## Build progress"),e.push("");let c=o.filter(d=>d.status==="completed"||d.status==="done"),u=o.filter(d=>d.status==="in_progress"),h=o.filter(d=>d.status!=="completed"&&d.status!=="done"&&d.status!=="in_progress");if(c.length>0){e.push(`**Done (${c.length}/${o.length}):**`);for(let d of c)e.push(`- ${ps(d.status)} ${us(d)}`);e.push("")}if(u.length>0){e.push("**In progress:**");for(let d of u)e.push(`- ${ps(d.status)} ${us(d)}`);e.push("")}if(h.length>0){e.push("**Planned next:**");for(let d of h)e.push(`- ${ps(d.status)} ${us(d)}`);e.push("")}}let s=r?.dataModel??[];if(s.length>0){e.push("## Data model"),e.push("");for(let c of s){let u=Od(c);u?e.push(`- **${ci(c)}**(${u})`):e.push(`- **${ci(c)}**`)}e.push("")}let a=r?.integrations??[];if(a.length>0){e.push("## Active integrations"),e.push("");for(let c of a){let u=c.name??c.id??"integration";e.push(`- **${u}**`)}e.push(""),e.push('Per-integration patterns: load the matching skill via `mist_docs({ topic: "<id>-integration" })` or read `.claude/skills/<id>-integration/SKILL.md`.'),e.push("")}let l=t.deploy;return l?.url&&(e.push("## Deploy"),e.push(""),e.push(`- URL: ${l.url}`),l.completedAt&&e.push(`- Last deploy: ${l.completedAt}`),l.deploymentId&&e.push(`- Last deployment id: \`${l.deploymentId}\``),e.push("")),e.push("## For fresh state"),e.push(""),e.push("This file is a **snapshot** written at scaffold/implement/deploy time \u2014 it can lag the live state of the app by minutes. For authoritative state (current step statuses, env vars actually set, deployment history, runtime errors), call:"),e.push(""),e.push("```"),e.push('mist_project({ action: "get", projectPath })'),e.push("```"),e.push(""),e.join(`
|
|
2880
2490
|
`).trimEnd()+`
|
|
2881
|
-
`}function
|
|
2882
|
-
`)}function
|
|
2883
|
-
`)}function
|
|
2491
|
+
`}function zt(t){try{let e=li(t,"mistflow.json");if(!Ad(e))return;let r=Rd(e,"utf-8"),n=JSON.parse(r),i=jd(n);Ed(li(t,"PROJECT.md"),i,"utf-8")}catch{}}var Nd,nr=I(()=>{"use strict";Nd={completed:"\u2705",done:"\u2705",in_progress:"\u{1F7E1}",pending:"\u23ED\uFE0F",skipped:"\u23ED\uFE0F"}});function di(t){if(!t)return"Item";let e=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return e.length===0?"Item":e.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}function Dd(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function Md(t){let e=di(t);return e.charAt(0).toLowerCase()+e.slice(1)}function hs(){return["# Integration contracts","","This directory holds the single source of truth for every API shape in","this app. Frontend code and backend routes both import from here, so","drift becomes a compile error instead of a silent runtime bug.","","## The convention","","Every entity defined in `db/schema.ts` MUST have a matching contract","file in this directory. Each contract file exports three things:","","- `<Entity>Schema` \u2014 the Zod schema for reading the entity (derived from"," the Drizzle table via `createSelectSchema`).","- `Create<Entity>Input` \u2014 the Zod schema for creating a new row"," (derived via `createInsertSchema`, typically with `id` and"," `createdAt` omitted).","- `<Entity>` \u2014 the inferred TypeScript type from `<Entity>Schema`.","","File name is the kebab-case singular of the entity, e.g. `habit.ts`,","`blog-post.ts`. One entity per file.","","## Example","","```ts","// contracts/habit.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { habit } from "@/db/schema";',"","export const HabitSchema = createSelectSchema(habit);","export type Habit = z.infer<typeof HabitSchema>;","","export const CreateHabitInput = createInsertSchema(habit).omit({"," id: true,"," createdAt: true,","});","export type CreateHabitInput = z.infer<typeof CreateHabitInput>;","```","","## Usage","","Frontend fetch and backend route should BOTH import from `contracts/`:","","```ts","// app/api/habits/route.ts",'import { CreateHabitInput, HabitSchema } from "@/contracts/habit";',"","export async function POST(request: Request) {"," const body = CreateHabitInput.parse(await request.json());"," const row = await db.insert(habit).values(body).returning();"," return Response.json(HabitSchema.parse(row[0]));","}","```","","```ts","// app/habits/page.tsx",'import type { Habit } from "@/contracts/habit";',"",'const res = await fetch("/api/habits");',"const habits: Habit[] = await res.json();","```","","## Adding a new entity","","1. Add the Drizzle table to `db/schema.ts`.","2. Create the matching `contracts/<entity>.ts` file using the template above.","3. Import from `contracts/` in every route, server action, and client"," component that touches the entity. Never inline the type.","","Run `mist_doctor` to check for entities that are missing a contract.",""].join(`
|
|
2492
|
+
`)}function pi(){return["<!-- mist:contracts:start -->","## Integration contracts","","Every API shape in this app lives in `contracts/`. The directory holds","Zod schemas derived from `db/schema.ts` via `drizzle-zod`. Frontend and","backend both import from `contracts/`, so type drift becomes a compile","error instead of a runtime bug.","","### Rules for AI agents","","1. Every API route (`app/api/**/route.ts`) and server action MUST"," import its request + response types from `contracts/<entity>.ts`."," Never inline a Zod schema or a TypeScript type for an entity that"," already has a contract. Never `z.object({ ... })` inside a route"," handler for a known entity.","2. When you add a new entity to `db/schema.ts`, you MUST create the"," matching contract file BEFORE writing any route that uses it. Order"," matters: schema -> contract -> route.","3. Validate every request body with the contract's `.parse()` method."," If validation fails, return a 400 with the Zod error message \u2014 the"," contract is the boundary, not a decoration.","4. Validate every response body before returning it. Use the select"," schema's `.parse()` on the row(s) you read from the DB. This catches"," the case where the DB shape has drifted from the contract.","5. Client components that fetch an entity MUST import the inferred",' TypeScript type (`import type { Habit } from "@/contracts/habit"`)'," \u2014 never hand-write a duplicate type.","","### Contract file shape","","```ts","// contracts/<entity>.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { entityTable } from "@/db/schema";',"","export const EntitySchema = createSelectSchema(entityTable);","export type Entity = z.infer<typeof EntitySchema>;","","export const CreateEntityInput = createInsertSchema(entityTable).omit({"," id: true,"," createdAt: true,","});","export type CreateEntityInput = z.infer<typeof CreateEntityInput>;","```","","### Example route using a contract","","```ts","// app/api/entities/route.ts",'import { db } from "@/lib/db";','import { entityTable } from "@/db/schema";','import { CreateEntityInput, EntitySchema } from "@/contracts/entity";',"","export async function POST(request: Request) {"," const body = CreateEntityInput.parse(await request.json());"," const [row] = await db.insert(entityTable).values(body).returning();"," return Response.json(EntitySchema.parse(row));","}","```","","Run `mist_doctor` to check every entity in `db/schema.ts` has a","contract file. Missing contracts are reported as warnings.","<!-- mist:contracts:end -->",""].join(`
|
|
2493
|
+
`)}function gs(t){let e=pi();if(t.includes(ms)){let n=t.indexOf(ms),i=ui,o=t.indexOf(i,n);if(o===-1)return t.slice(0,n)+e;let s=t.slice(o+i.length);return t.slice(0,n)+e+s.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
|
|
2884
2494
|
|
|
2885
|
-
`+e}function
|
|
2886
|
-
`)}function
|
|
2495
|
+
`+e}function fs(t,e){let r=di(t),n=e??Md(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${n} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${r}Schema = createSelectSchema(${n});`,`export type ${r} = z.infer<typeof ${r}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${r}Input = createInsertSchema(${n}).omit({`," id: true,"," createdAt: true,","});",`export type Create${r}Input = z.infer<typeof Create${r}Input>;`,""].join(`
|
|
2496
|
+
`)}function ys(t){return`contracts/${Dd(t)}.ts`}var ms,ui,bs=I(()=>{"use strict";ms="<!-- mist:contracts:start -->",ui="<!-- mist:contracts:end -->"});import{z as Ht}from"zod";import{existsSync as Ne,mkdirSync as Wt,rmSync as Ld,writeFileSync as Ze,readFileSync as Gt,readdirSync as gi,copyFileSync as Ud}from"fs";import{join as he,resolve as fi,dirname as fn,isAbsolute as $d}from"path";import{homedir as Fd}from"os";import{spawn as $g}from"child_process";import{randomBytes as qd}from"crypto";import{simpleGit as zd}from"simple-git";function Bd(t){let e=he(Fd(),".mistflow","plans",`${t}.json`);if(!Ne(e))return null;try{let r=JSON.parse(Gt(e,"utf-8"));return r.plan?{plan:r.plan,...typeof r.scaffoldTargetPath=="string"?{scaffoldTargetPath:r.scaffoldTargetPath}:{}}:null}catch{return null}}function Wd(t){let e=fn(fi(t)),r=10,n=0;for(;n<r&&e!==fn(e);){if(Ne(he(e,"pnpm-workspace.yaml"))||Ne(he(e,"lerna.json"))||Ne(he(e,"pnpm-lock.yaml"))||Ne(he(e,"package-lock.json"))||Ne(he(e,"yarn.lock"))||Ne(he(e,"bun.lockb"))||Ne(he(e,"bun.lock")))return e;let i=he(e,"package.json");if(Ne(i))try{if(JSON.parse(Gt(i,"utf-8")).workspaces)return e}catch{}e=fn(e),n++}return null}function N(t,e,r){let n=he(t,e);Wt(fn(n),{recursive:!0}),Ze(n,r)}function Yd(t,e){N(t,".cursor/rules/mistflow.mdc",Vd),N(t,".github/copilot-instructions.md",Kd),N(t,".continue/rules/mistflow.md",rr),N(t,"CONVENTIONS.md",rr),N(t,".aider.conf.yml",Jd)}function Qd(t){if(!t.startsWith(`---
|
|
2887
2497
|
`))return{frontmatter:null,body:t};let e=t.indexOf(`
|
|
2888
2498
|
---
|
|
2889
2499
|
`,4);if(e<0)return{frontmatter:null,body:t};let r=t.slice(4,e),n={};for(let i of r.split(`
|
|
2890
|
-
`)){let o=i.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/);if(!o)continue;let[,s,a]=o;(s==="name"||s==="description")&&(n[s]=a.trim())}return{frontmatter:n,body:t.slice(e+5).replace(/^\n+/,"")}}function
|
|
2500
|
+
`)){let o=i.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/);if(!o)continue;let[,s,a]=o;(s==="name"||s==="description")&&(n[s]=a.trim())}return{frontmatter:n,body:t.slice(e+5).replace(/^\n+/,"")}}function Xd(t,e){for(let[r,n]of Object.entries(e)){if(!n||n.trim().length===0)continue;let{frontmatter:i,body:o}=Qd(n),s=i?.name??r,a=i?.description??`Mistflow skill: ${r}`,l=`---
|
|
2891
2501
|
name: ${s}
|
|
2892
2502
|
description: ${a}
|
|
2893
2503
|
---
|
|
2894
2504
|
|
|
2895
|
-
`;
|
|
2505
|
+
`;N(t,`.claude/skills/${r}/SKILL.md`,l+o);let c=`---
|
|
2896
2506
|
description: ${a}
|
|
2897
2507
|
alwaysApply: false
|
|
2898
2508
|
---
|
|
2899
2509
|
|
|
2900
|
-
`;
|
|
2901
|
-
`),o=null,s=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of i){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let
|
|
2510
|
+
`;N(t,`.cursor/rules/${r}.mdc`,c+o)}}function Zd(t){if(!Ne(t))return!0;let e;try{e=gi(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}function ep(t,e){let r=(e??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"new-app",n=he(t,r);return`${t} isn't empty, so we can't scaffold the project here without clobbering existing files. Retry mist_init with path: "${n}" (a subdirectory) \u2014 the user almost certainly meant "create a new app inside this folder," not "overwrite this folder." Confirm with the user once if you're not sure, but the suggested sub-path is usually right. (A leftover .mistflow/ from planning is fine \u2014 init preserves it.)`}function rp(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let r=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},i=r.split(`
|
|
2511
|
+
`),o=null,s=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of i){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let d=a(c.slice(6).trim());(d==="dark"||d==="light")&&(n.theme=d);continue}let u=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(u){o=u[1],s=null;continue}if(c.length>0&&!c.startsWith(" ")&&!c.startsWith(" ")&&c.match(/^[a-zA-Z0-9_-]+:(\s|$)/)){o=null,s=null;continue}if(o==="typography"){let d=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(d){s=d[1].replace(/-/g,"_"),n.typography[s]={};continue}let v=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(v&&s){n.typography[s][v[1]]=a(v[2]);continue}}let h=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(h&&o){let d=h[1].replace(/-/g,"_"),v=a(h[2]);o==="colors"?n.colors[d]=v:o==="rounded"?n.rounded[d]=v:o==="spacing"&&(n.spacing[d]=v)}}return n}function sp(t,e){let r=t.colors,i=[["--color-background",r.background],["--color-foreground",r.on_background??r.on_surface],["--color-card",r.surface??r.background],["--color-card-foreground",r.on_surface??r.on_background],["--color-popover",r.surface??r.background],["--color-popover-foreground",r.on_surface??r.on_background],["--color-muted",r.surface_variant??r.outline_variant??r.outline],["--color-muted-foreground",r.on_surface_variant??r.outline],["--color-border",r.outline_variant??r.outline],["--color-input",r.outline_variant??r.outline],["--color-primary",r.primary],["--color-primary-foreground",r.on_primary],["--color-ring",r.primary],["--color-secondary",r.secondary],["--color-secondary-foreground",r.on_secondary],["--color-accent",r.secondary],["--color-accent-foreground",r.on_secondary],["--color-destructive",r.error],["--color-destructive-foreground",r.on_error],["--color-success",r.success],["--color-success-foreground",r.on_success],["--color-warning",r.warning],["--color-warning-foreground",r.on_warning],["--color-info",r.info??r.primary],["--color-info-foreground",r.on_info??r.on_primary]].filter(a=>typeof a[1]=="string").map(([a,l])=>` ${a}: ${l};`).join(`
|
|
2902
2512
|
`),o=[` --radius-sm: ${t.rounded.sm??"0.25rem"};`,` --radius-md: ${t.rounded.md??e};`,` --radius-lg: ${t.rounded.lg??"0.5rem"};`,` --radius-xl: ${t.rounded.xl??"0.75rem"};`].join(`
|
|
2903
2513
|
`);return`@import "tailwindcss";
|
|
2904
2514
|
@import "tw-animate-css";
|
|
@@ -2955,11 +2565,11 @@ ${o}
|
|
|
2955
2565
|
|
|
2956
2566
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2957
2567
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2958
|
-
`}function
|
|
2568
|
+
`}function op(t,e){let r=t?.borderRadius??"subtle",n=tp[r]??"0.375rem";if(e){let o=rp(e);if(o)return sp(o,n)}return`@import "tailwindcss";
|
|
2959
2569
|
@import "tw-animate-css";
|
|
2960
2570
|
|
|
2961
2571
|
@theme {
|
|
2962
|
-
${[...
|
|
2572
|
+
${[...np.map(([o,s])=>` ${o}: ${s};`)," --radius-sm: 0.25rem;",` --radius-md: ${n};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
|
|
2963
2573
|
`)}
|
|
2964
2574
|
}
|
|
2965
2575
|
|
|
@@ -3009,7 +2619,7 @@ ${[...lp.map(([o,s])=>` ${o}: ${s};`)," --radius-sm: 0.25rem;",` --radius-md:
|
|
|
3009
2619
|
|
|
3010
2620
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
3011
2621
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
3012
|
-
`}function
|
|
2622
|
+
`}function hi(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return mi[e]?mi[e]:e.replace(/\s+/g,"_")}function ip(t){return t?{english:"en",spanish:"es",french:"fr",german:"de",italian:"it",portuguese:"pt",dutch:"nl",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",arabic:"ar",hebrew:"he",hindi:"hi",turkish:"tr",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",thai:"th",vietnamese:"vi",indonesian:"id",malay:"ms",farsi:"fa",persian:"fa",czech:"cs",greek:"el",romanian:"ro",hungarian:"hu",ukrainian:"uk",bengali:"bn",tamil:"ta",telugu:"te",urdu:"ur"}[t.toLowerCase()]??"en":"en"}function lp(t,e,r){let n=t.replace(/[\\"`$]/g,""),i=ip(r),s=ap.has(i)?`lang="${i}" dir="rtl"`:`lang="${i}"`,a=e?.fonts?.heading,l=e?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
|
|
3013
2623
|
import { DM_Sans } from "next/font/google";
|
|
3014
2624
|
import { Toaster } from "sonner";
|
|
3015
2625
|
import "./globals.css";
|
|
@@ -3025,7 +2635,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
3025
2635
|
</html>
|
|
3026
2636
|
);
|
|
3027
2637
|
}
|
|
3028
|
-
`;let c=
|
|
2638
|
+
`;let c=hi(a??l),u=hi(l??a);return c===u?`import type { Metadata } from "next";
|
|
3029
2639
|
import { ${c} } from "next/font/google";
|
|
3030
2640
|
import { Toaster } from "sonner";
|
|
3031
2641
|
import "./globals.css";
|
|
@@ -3042,12 +2652,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
3042
2652
|
);
|
|
3043
2653
|
}
|
|
3044
2654
|
`:`import type { Metadata } from "next";
|
|
3045
|
-
import { ${c}, ${
|
|
2655
|
+
import { ${c}, ${u} } from "next/font/google";
|
|
3046
2656
|
import { Toaster } from "sonner";
|
|
3047
2657
|
import "./globals.css";
|
|
3048
2658
|
|
|
3049
2659
|
const heading = ${c}({ subsets: ["latin"], variable: "--font-heading" });
|
|
3050
|
-
const body = ${
|
|
2660
|
+
const body = ${u}({ subsets: ["latin"], variable: "--font-body" });
|
|
3051
2661
|
|
|
3052
2662
|
export const metadata: Metadata = { title: "${n}", description: "Built with Mistflow" };
|
|
3053
2663
|
|
|
@@ -3058,89 +2668,119 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
3058
2668
|
</html>
|
|
3059
2669
|
);
|
|
3060
2670
|
}
|
|
3061
|
-
`}function
|
|
3062
|
-
`)}function
|
|
2671
|
+
`}function yn(t,...e){let r=JSON.stringify(t).toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function ws(t,...e){return(Array.isArray(t.integrations)?t.integrations:[]).some(n=>{let i=JSON.stringify(n).toLowerCase();return e.some(o=>i.includes(o.toLowerCase()))})}function cp(t){return t.realMoney===!1?!1:t.realMoney===!0||ws(t,"stripe")||yn(t,"stripe","payment","billing","subscription","checkout")}function dp(t,e){return e==="none"?ws(t,"resend","email"):e==="email"||e==="invite-only"||ws(t,"resend","email")||yn(t,"email notification","email reminder","send email","resend")}function vs(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[r,n]of Object.entries(pp))if(e.includes(r))return n;return"Circle"}function bn(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function up(t){if(t.authModel==="none")return null;let e=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed","/images","/assets"];if(t.publicPages&&Array.isArray(t.publicPages))for(let o of t.publicPages){if(typeof o!="string"||o.length<1)continue;let s=o.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!s)continue;let a=s.startsWith("/")?s:"/"+s;e.includes(a)||e.push(a)}let r=e.filter(o=>o==="/"),n=e.filter(o=>o!=="/"),i=[];i.push('import { NextRequest, NextResponse } from "next/server";'),i.push(""),i.push("const PUBLIC_PREFIXES = [");for(let o of n)i.push(' "'+o+'",');return i.push("];"),i.push(""),r.length>0&&(i.push('const PUBLIC_EXACT = ["'+r.join('", "')+'"];'),i.push("")),i.push("export function middleware(req: NextRequest) {"),i.push(" const { pathname, search } = req.nextUrl;"),i.push(""),r.length>0&&i.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),i.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),i.push(""),i.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),i.push(" if (!token) {"),i.push(' const loginUrl = new URL("/login", req.url);'),i.push(" const params = new URLSearchParams(search);"),i.push(' for (const key of ["verified", "error"]) {'),i.push(" const v = params.get(key);"),i.push(" if (v) loginUrl.searchParams.set(key, v);"),i.push(" }"),i.push(" return NextResponse.redirect(loginUrl);"),i.push(" }"),i.push(""),i.push(" return NextResponse.next();"),i.push("}"),i.push(""),i.push("export const config = {"),i.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),i.push("};"),i.push(""),i.join(`
|
|
2672
|
+
`)}function mp(t){if(t.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],n=(t.pages??[]).filter(l=>{let c=l.path??l.route??"";return c==="/"||c===""||c.includes("[")||c.replace(/^\//,"").split("/").length>1?!1:!e.some(h=>c.startsWith(h))}).map(l=>{let c=l.path??l.route??"",u=c.startsWith("/")?c:"/"+c,h=l.name??bn(c.replace(/^\//,"")),d=vs(h);return{label:h,href:u,icon:d}});n.some(l=>l.href==="/dashboard")||n.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let i=t.authModel==="none",o=[...new Set(n.map(l=>l.icon))];i||o.push("LogOut");let s=bn(t.name);if(t.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),i||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+o.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let c of n)l.push(' { label: "'+c.label+'", href: "'+c.href+'", icon: '+c.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+s+"</span>"),l.push(' <div className="flex items-center gap-1">'),l.push(" {NAV_ITEMS.map((item) => ("),l.push(" <Link"),l.push(" key={item.href}"),l.push(" href={item.href}"),l.push(' aria-current={pathname === item.href ? "page" : undefined}'),l.push(" className={cn("),l.push(' "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",'),l.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground"'),l.push(" )}"),l.push(" >"),l.push(' <item.icon className="h-4 w-4" />'),l.push(" {item.label}"),l.push(" </Link>"),l.push(" ))}"),l.push(" </div>"),l.push(" </div>"),i?l.push(' <span className="text-sm text-muted-foreground">{user.name}</span>'):(l.push(' <div className="flex items-center gap-2">'),l.push(' <span className="text-sm text-muted-foreground">{user.email}</span>'),l.push(" <Button"),l.push(' variant="ghost"'),l.push(' size="sm"'),l.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),l.push(" >"),l.push(' <LogOut className="h-4 w-4" />'),l.push(" </Button>"),l.push(" </div>")),l.push(" </div>"),l.push(" </nav>"),l.push(" );"),l.push("}"),l.push(""),{path:"components/topnav.tsx",content:l.join(`
|
|
3063
2673
|
`)}}let a=[];a.push('"use client";'),a.push(""),a.push('import { useState } from "react";'),a.push('import Link from "next/link";'),a.push('import { usePathname } from "next/navigation";'),i||a.push('import { authClient } from "@/lib/auth-client";'),a.push('import { Button } from "@/components/ui/button";'),a.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),a.push('import { cn } from "@/lib/utils";'),a.push("import { Menu, "+o.join(", ")+' } from "lucide-react";'),a.push(""),a.push("interface SidebarProps {"),a.push(" user: { name: string | null; email: string; role?: string | undefined };"),a.push("}"),a.push(""),a.push("const NAV_ITEMS = [");for(let l of n)a.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return a.push("];"),a.push(""),a.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),a.push(" return ("),a.push(" <>"),a.push(' <div className="flex h-14 items-center border-b px-4">'),a.push(' <span className="text-lg font-semibold">'+s+"</span>"),a.push(" </div>"),a.push(' <nav className="flex-1 space-y-1 p-2">'),a.push(" {NAV_ITEMS.map((item) => ("),a.push(" <Link"),a.push(" key={item.href}"),a.push(" href={item.href}"),a.push(" onClick={onNavigate}"),a.push(' aria-current={pathname === item.href ? "page" : undefined}'),a.push(" className={cn("),a.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),a.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),a.push(" )}"),a.push(" >"),a.push(' <item.icon className="h-4 w-4" />'),a.push(" {item.label}"),a.push(" </Link>"),a.push(" ))}"),a.push(" </nav>"),a.push(' <div className="border-t p-4">'),a.push(' <div className="flex items-center gap-3">'),a.push(' <div className="flex-1 truncate">'),a.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),a.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),a.push(" </div>"),i||(a.push(" <Button"),a.push(' variant="ghost"'),a.push(' size="icon"'),a.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),a.push(" >"),a.push(' <LogOut className="h-4 w-4" />'),a.push(" </Button>")),a.push(" </div>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),a.push("export default function Sidebar({ user }: SidebarProps) {"),a.push(" const pathname = usePathname();"),a.push(" const [open, setOpen] = useState(false);"),a.push(""),a.push(" return ("),a.push(" <>"),a.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),a.push(" <NavContent pathname={pathname} user={user} />"),a.push(" </aside>"),a.push(' <div className="sticky top-0 z-[var(--z-sticky)] flex h-14 items-center gap-3 border-b bg-card px-4 md:hidden">'),a.push(" <Sheet open={open} onOpenChange={setOpen}>"),a.push(" <SheetTrigger asChild>"),a.push(' <Button variant="ghost" size="icon" className="-ml-2">'),a.push(' <Menu className="h-5 w-5" />'),a.push(" </Button>"),a.push(" </SheetTrigger>"),a.push(' <SheetContent side="left" className="w-64 p-0">'),a.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),a.push(' <div className="flex h-full flex-col">'),a.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),a.push(" </div>"),a.push(" </SheetContent>"),a.push(" </Sheet>"),a.push(' <span className="text-lg font-semibold">'+s+"</span>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),{path:"components/sidebar.tsx",content:a.join(`
|
|
3064
|
-
`)}}function
|
|
3065
|
-
`)}function
|
|
2674
|
+
`)}}function hp(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,r=t.defaultRole??e[0],n=[];n.push("export type Role = "+e.map(i=>'"'+i+'"').join(" | ")+";"),n.push(""),n.push("export const ROLES = ["+e.map(i=>'"'+i+'"').join(", ")+"] as const;"),n.push(""),n.push('export const DEFAULT_ROLE: Role = "'+r+'";'),n.push(""),n.push("export const ROLE_LABELS: Record<Role, string> = {");for(let i of e){let o=i.charAt(0).toUpperCase()+i.slice(1);n.push(' "'+i+'": "'+o+'",')}return n.push("};"),n.push(""),n.push("export function getUserRole(user: Record<string, unknown>): Role {"),n.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),n.push(" if (ROLES.includes(role as Role)) return role as Role;"),n.push(" return DEFAULT_ROLE;"),n.push("}"),n.push(""),n.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),n.push(" if (!userRole) return false;"),n.push(" const allowed = Array.isArray(required) ? required : [required];"),n.push(" return allowed.includes(userRole as Role);"),n.push("}"),n.push(""),n.join(`
|
|
2675
|
+
`)}function gp(t){let e=bn(t.name);if(t.authModel==="none"){let o=[];return o.push("export default function HomePage() {"),o.push(" return ("),o.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),o.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&o.push(' <p className="mt-4 text-lg text-muted-foreground">'+t.summary+"</p>"),o.push(" </main>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
|
|
3066
2676
|
`)}let r=t.publicPages?.includes("/"),n=t.design?.landingTone;if(r&&n){let o=[];return o.push('import Link from "next/link";'),o.push(""),o.push("export default function HomePage() {"),o.push(" return ("),o.push(' <main className="flex min-h-screen flex-col">'),o.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),o.push(' <h1 className="text-5xl font-bold tracking-tight">'+e+"</h1>"),t.summary&&o.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+t.summary+"</p>"),o.push(' <div className="flex gap-4">'),o.push(' <Link href="/register" className="inline-flex h-11 items-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),o.push(" Get Started"),o.push(" </Link>"),o.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),o.push(" Sign In"),o.push(" </Link>"),o.push(" </div>"),o.push(" </section>"),o.push(" </main>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
|
|
3067
2677
|
`)}if(r){let o=[];return o.push('import Link from "next/link";'),o.push(""),o.push("export default function HomePage() {"),o.push(" return ("),o.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),o.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&o.push(' <p className="text-lg text-muted-foreground">'+t.summary+"</p>"),o.push(' <Link href="/login" className="inline-flex h-10 items-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),o.push(" Sign In"),o.push(" </Link>"),o.push(" </main>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
|
|
3068
2678
|
`)}let i=[];return i.push('import { headers } from "next/headers";'),i.push('import { redirect } from "next/navigation";'),i.push('import { auth } from "@/lib/auth";'),i.push(""),i.push("export default async function HomePage() {"),i.push(" const session = await auth.api.getSession({ headers: await headers() });"),i.push(' if (session) redirect("/dashboard");'),i.push(' redirect("/login");'),i.push("}"),i.push(""),i.join(`
|
|
3069
|
-
`)}function
|
|
3070
|
-
`)}function
|
|
3071
|
-
`)}function
|
|
3072
|
-
`)}function
|
|
3073
|
-
`)}function
|
|
3074
|
-
`)}function
|
|
3075
|
-
`)}async function
|
|
2679
|
+
`)}function fp(t,e){let r=t.authModel==="none",n=[];r||(n.push('import { Suspense } from "react";'),n.push('import { headers } from "next/headers";'),n.push('import { redirect } from "next/navigation";'),n.push('import { auth } from "@/lib/auth";'),n.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?n.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&n.push('import Sidebar from "@/components/sidebar";'),!r&&t.roles&&t.roles.length>0&&n.push('import { getUserRole } from "@/lib/roles";'),n.push(""),n.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),r?n.push(' const user = { name: "Guest", email: "" };'):(n.push(" const session = await auth.api.getSession({ headers: await headers() });"),n.push(' if (!session) redirect("/login");'),n.push(""),t.roles&&t.roles.length>0?(n.push(" const role = getUserRole(session.user as Record<string, unknown>);"),n.push(" const user = { name: session.user.name, email: session.user.email, role };")):(n.push(" const user = {"),n.push(" name: session.user.name,"),n.push(" email: session.user.email,"),n.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),n.push(" };"))),n.push("");let i=r?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(" <TopNav user={user} />"),n.push(' <main className="mx-auto max-w-7xl p-6">'+i+"{children}</main>"),n.push(" </div>"),n.push(" );")):t.navStyle==="none"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(' <main className="mx-auto max-w-5xl p-6">'+i+"{children}</main>"),n.push(" </div>"),n.push(" );")):(n.push(" return ("),n.push(' <div className="flex flex-col md:flex-row min-h-screen">'),n.push(" <Sidebar user={user} />"),n.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+i+"{children}</main>"),n.push(" </div>"),n.push(" );")),n.push("}"),n.push(""),n.join(`
|
|
2680
|
+
`)}function yp(t){let e=bn(t.name),r=t.dataModel??[],n=[];if(r.length>0){let i=r.map(s=>vs(s.entity??s.name??"item")),o=[...new Set(i)];n.push('import { Card, CardContent } from "@/components/ui/card";'),n.push("import { "+o.join(", ")+' } from "lucide-react";'),n.push("")}if(n.push("export default function DashboardPage() {"),n.push(" return ("),n.push(' <div className="space-y-6">'),n.push(" <div>"),n.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),t.summary&&n.push(' <p className="mt-1 text-muted-foreground">'+t.summary+"</p>"),n.push(" </div>"),r.length>0){n.push(' <div className="rounded-lg border p-8 text-center">'),n.push(' <h2 className="text-lg font-semibold">Get started</h2>'),n.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),n.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let i of r){let o=i.entity??i.name??"Item",s=vs(o),a=bn(o.replace(/_/g,"-"));n.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),n.push(" <"+s+' className="h-5 w-5 text-muted-foreground" />'),n.push(' <span className="text-sm font-medium">Add your first '+a+"</span>"),n.push(" </div>")}n.push(" </div>"),n.push(" </div>")}return n.push(" </div>"),n.push(" );"),n.push("}"),n.push(""),n.join(`
|
|
2681
|
+
`)}function bp(t,e=!1){if(!t.multiTenant)return null;let r=[];return e?(r.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = pgTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),r.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = pgTable(")):(r.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),r.push('import { sql } from "drizzle-orm";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = sqliteTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = sqliteTable(")),r.push(' "org_member",'),r.push(" {"),r.push(' id: text("id").primaryKey(),'),r.push(' orgId: text("org_id").notNull().references(() => organization.id),'),r.push(' userId: text("user_id").notNull().references(() => user.id),'),r.push(' role: text("role").notNull(),'),e?r.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):r.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(" },"),r.push(" (table) => ({"),r.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),r.push(' userIdx: index("org_member_user_idx").on(table.userId),'),r.push(" }),"),r.push(");"),r.push(""),r.join(`
|
|
2682
|
+
`)}function wp(t){if(!t.multiTenant)return null;let e=[];return e.push('import { db } from "./db";'),e.push('import { organization, orgMember } from "@/db/schema/organization";'),e.push('import { eq } from "drizzle-orm";'),e.push(""),e.push("export async function getCurrentOrg(userId: string) {"),e.push(" const membership = await db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.userId, userId))"),e.push(" .limit(1);"),e.push(" if (membership.length === 0) return null;"),e.push(" const org = await db"),e.push(" .select()"),e.push(" .from(organization)"),e.push(" .where(eq(organization.id, membership[0].orgId))"),e.push(" .limit(1);"),e.push(" return org[0] ?? null;"),e.push("}"),e.push(""),e.push("export async function getOrgMembers(orgId: string) {"),e.push(" return db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.orgId, orgId));"),e.push("}"),e.push(""),e.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),e.push(" const id = crypto.randomUUID();"),e.push(" await db.insert(orgMember).values({"),e.push(" id,"),e.push(" orgId,"),e.push(" userId: email,"),e.push(" role,"),e.push(" });"),e.push(" return { id, orgId, email, role };"),e.push("}"),e.push(""),e.join(`
|
|
2683
|
+
`)}function vp(t){if(!t.multiTenant)return null;let e=[];return e.push('"use client";'),e.push(""),e.push("import {"),e.push(" DropdownMenu,"),e.push(" DropdownMenuContent,"),e.push(" DropdownMenuItem,"),e.push(" DropdownMenuTrigger,"),e.push('} from "@/components/ui/dropdown-menu";'),e.push('import { Button } from "@/components/ui/button";'),e.push('import { ChevronsUpDown } from "lucide-react";'),e.push(""),e.push("interface OrgSwitcherProps {"),e.push(" orgs: Array<{ id: string; name: string }>;"),e.push(" currentOrgId: string;"),e.push("}"),e.push(""),e.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),e.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),e.push(""),e.push(" return ("),e.push(" <DropdownMenu>"),e.push(" <DropdownMenuTrigger asChild>"),e.push(' <Button variant="outline" className="w-full justify-between">'),e.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),e.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),e.push(" </Button>"),e.push(" </DropdownMenuTrigger>"),e.push(' <DropdownMenuContent className="w-56">'),e.push(" {orgs.map((org) => ("),e.push(" <DropdownMenuItem key={org.id}>"),e.push(" {org.name}"),e.push(" </DropdownMenuItem>"),e.push(" ))}"),e.push(" </DropdownMenuContent>"),e.push(" </DropdownMenu>"),e.push(" );"),e.push("}"),e.push(""),e.join(`
|
|
2684
|
+
`)}function kp(t,e,r){let n=[],i=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");n.push(`# ${i}`),n.push(""),e?.summary&&(n.push(e.summary),n.push(""));let o=e?.features??[];if(o.length>0){n.push("## Features"),n.push("");for(let l of o){let c=l.description?` \u2014 ${l.description}`:"";n.push(`- **${l.name}**${c}`)}n.push("")}n.push("## Tech Stack"),n.push(""),n.push("| Layer | Technology |"),n.push("|-------|------------|"),n.push("| Framework | Next.js 15 (App Router) |"),n.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),n.push("| Auth | Better Auth (email/password, social login) |"),n.push("| Styling | Tailwind CSS + shadcn/ui |"),n.push("| Deployment | Mistflow Cloud |"),r.hasStripe&&n.push("| Payments | Stripe |"),r.hasResend&&n.push("| Email | Resend + React Email |"),r.hasStorage&&n.push("| File Storage | Mistflow Cloud (managed blob storage) |"),r.hasAdmin&&n.push("| Admin | Better Auth admin plugin |"),r.hasAI&&n.push("| AI | Vercel AI SDK + OpenAI |"),n.push("");let s=e?.pages??[];if(s.length>0){n.push("## Pages"),n.push(""),n.push("| Route | Description |"),n.push("|-------|-------------|");for(let l of s){let c=l.path??l.route??l.name??"",u=l.description??"";n.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${u} |`)}n.push("")}let a=e?.dataModel??[];if(a.length>0){n.push("## Data Model"),n.push("");for(let l of a){let c=l.entity??l.name??"Unknown";if(n.push(`### ${c}`),n.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")n.push(`Fields: ${l.fields.join(", ")}`);else{n.push("| Field | Type |"),n.push("|-------|------|");for(let u of l.fields)n.push(`| ${u.name} | ${u.type} |`)}n.push("")}}}return n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),r.isNeon?n.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(n.push("| `TURSO_URL` | Database connection URL | Yes |"),n.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),n.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),r.hasStripe&&(n.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),n.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),n.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),r.hasResend&&(n.push("| `RESEND_API_KEY` | Resend API key | Yes |"),n.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),(r.hasAI||r.hasStorage)&&n.push("| `MISTFLOW_RUNTIME_KEY` | Mistflow Cloud runtime key \u2014 authenticates AI gateway, file storage, and other managed features | Auto-provisioned at `mist_init` |"),r.hasAI&&n.push("| `OPENROUTER_API_KEY` | OpenRouter key for your-key fallback (only used when `MISTFLOW_RUNTIME_KEY` is unset) | Optional |"),n.push(""),n.push("### Local database"),n.push(""),r.isNeon?(n.push("For local development, start a local Postgres server:"),n.push(""),n.push("```bash"),n.push("# Using Docker:"),n.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),n.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),n.push("```")):(n.push("For local development, start a local Turso server:"),n.push(""),n.push("```bash"),n.push("npx turso dev"),n.push("```")),n.push(""),n.push("Then set up the database:"),n.push(""),n.push("```bash"),n.push("npm run db:push"),n.push("```"),n.push(""),n.push("### Run"),n.push(""),n.push("```bash"),n.push("npm run dev"),n.push("```"),n.push(""),n.push("Open [http://localhost:3000](http://localhost:3000)."),n.push(""),n.push("## Project Structure"),n.push(""),n.push("```"),n.push("app/"),n.push(" (auth)/ Login and registration pages"),n.push(" (dashboard)/ Authenticated app pages"),r.hasAdmin&&n.push(" admin/ Admin panel pages (at /admin/...)"),n.push(" home/ Public landing page (served via / \u2192 /home redirect)"),n.push(" api/ API routes (auth, health, webhooks)"),n.push(" layout.tsx Root layout with fonts and providers"),n.push(" globals.css Design tokens and Tailwind config"),n.push("components/ Reusable UI components"),n.push("db/"),n.push(" schema/ Database table definitions"),n.push(" index.ts Schema exports"),n.push("lib/"),n.push(" auth.ts Better Auth server config"),n.push(" auth-client.ts Better Auth client config"),n.push(` db.ts ${r.isNeon?"Postgres":"SQLite"} database connection`),r.hasStripe&&n.push(" stripe.ts Stripe client"),r.hasResend&&(n.push(" resend.ts Resend client"),n.push(" email.ts Email send helpers")),r.hasStorage&&n.push(" storage.ts File upload/download helpers"),r.hasAI&&(n.push(" ai.ts Back-compat export for server AI helpers"),n.push(" server/ai.ts Server-only AI Gateway and provider helpers")),r.hasResend&&n.push("emails/ React Email templates"),n.push("```"),n.push(""),n.push("## Deploy"),n.push(""),n.push("Deploy to production with Mistflow:"),n.push(""),n.push("```"),n.push("# In your AI editor (Claude Code, Cursor, etc.):"),n.push("mist_deploy action='deploy'"),n.push("```"),n.push(""),n.push("Your app will be live at `https://<app-name>.mistflow.app`."),n.push(""),e?.design&&(n.push("## Design"),n.push(""),e.design.tone&&n.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(n.push(`- **Heading font**: ${e.design.fonts.heading}`),n.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&n.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&n.push(`- **Border radius**: ${e.design.borderRadius}`),n.push("")),n.push("---"),n.push(""),n.push("Built with [Mistflow](https://mistflow.ai)"),n.push(""),n.join(`
|
|
2685
|
+
`)}async function xp(t,e){if(!Se())return Ee("scaffold a new project");if(!Bt())return p(JSON.stringify({status:"node_version_unsupported",code:"node_version_unsupported",message:Pt(),nextAction:"Tell the user their Node version is too old, paste the upgrade command from `message`, and stop. Do NOT proceed with mist_init \u2014 the scaffolded app would build-fail at deploy time."}),!0);let{name:r,plan:n,path:i,planId:o,sessionId:s}=t,a,l,c=null,u=n;if(typeof u=="string")try{let b=JSON.parse(u);b&&typeof b=="object"&&!Array.isArray(b)&&"plan"in b?u=b.plan:u=b}catch{return p("mist_init received `plan` as a string, but it is not valid JSON. Pass the plan object directly or pass planId from mist_plan.",!0)}if(!u&&o){if(c=Bd(o),!c)return p(`No plan found for planId '${o}'. Call mist_plan first, or pass the plan object inline.`,!0);u=c.plan}if(!u||typeof u!="object"||Array.isArray(u))return p("mist_init requires a plan object or a valid planId from mist_plan. Refusing to scaffold without a structured plan because mist_implement would not know what to build.",!0);let h=i??c?.scaffoldTargetPath;if(!h)return p("mist_init requires an explicit 'path' unless the planId cache includes a scaffoldTargetPath. Call mist_init with the planId returned by mist_plan, pass the absolute scaffold directory, or pass { sessionId, path } in session mode.",!0);if(!$d(h))return p(`mist_init 'path' must be an absolute path \u2014 received '${h}'. Pass the full absolute path to the target directory.`,!0);let d=fi(h),v=r??(typeof u.name=="string"?u.name:void 0);if(!v)return p("mist_init requires a human-readable app name. Pass `name`, or call it with a planId whose cached plan includes a name.",!0);let W=u?.design,_=typeof u.authModel=="string"?u.authModel:void 0,k=_==="none",y=cp(u),A=dp(u,_),z=u?yn(u,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,H=u?yn(u,"admin panel","admin dashboard","admin management"):!1,ne=u?yn(u,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,ee=u,Q=typeof u.dbProvider=="string"?u.dbProvider:"neon",q=Array.isArray(u.dataModel)&&u.dataModel.length>0,P=Q==="none"||k&&!q&&!z,se=P?"none":Q,B=se==="neon";if(!Zd(d))return p(ep(d,u?.name),!0);Wt(d,{recursive:!0});try{try{let f=he(d,".mistflow","rules");Wt(f,{recursive:!0}),Ze(he(f,"design-quality.md"),er),Ze(he(f,"landing.md"),tr)}catch(f){console.error("Could not write design rule files:",f instanceof Error?f.message:f)}try{let f=he(fn(d),".mistflow","mockups");if(Ne(f)){let E=gi(f).filter(S=>S.endsWith(".html"));if(E.length>0){let S=he(d,".mistflow","mockups");Wt(S,{recursive:!0});for(let de of E)Ud(he(f,de),he(S,de));console.error(`Copied ${E.length} mockup file(s) into project`)}}}catch(f){console.error("Could not copy mockup files:",f instanceof Error?f.message:f)}let b=null;try{b=await $r("nextjs")}catch(f){console.error("Could not fetch scaffold from API, using minimal scaffold:",f instanceof Error?f.message:f)}if(b){let f=v.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let x of b.files){if(x.path==="package.json"||x.path==="middleware.ts"||x.path==="components/sidebar.tsx"||x.path==="components/topnav.tsx"||x.path==="app/(dashboard)/layout.tsx"||x.path==="app/(dashboard)/page.tsx"||x.path==="app/(dashboard)/dashboard/page.tsx"||P&&(x.path==="lib/db.ts"||x.path==="drizzle.config.ts"||x.path==="db/index.ts"||x.path.startsWith("db/schema/"))||k&&(x.path.includes("(auth)")||x.path.includes("(admin)")||x.path.startsWith("app/admin/")||x.path.includes("components/auth/")||x.path.includes("admin-sidebar")||x.path.includes("app/api/auth/")||x.path.includes("app/api/admin/seed")||x.path==="lib/auth.ts"||x.path==="lib/auth-client.ts"||x.path==="db/schema/auth.ts"||x.path==="db/schema/index.ts"||x.path==="db/index.ts")||!y&&(x.path.includes("stripe")||x.path.includes("webhook/stripe"))||!A&&(x.path.includes("resend")||x.path.includes("emails/"))||!H&&(x.path.includes("(admin)")||x.path.startsWith("app/admin/")||x.path.includes("admin-sidebar"))||B&&(x.path==="lib/db.ts"||x.path==="lib/auth.ts"||x.path==="drizzle.config.ts"||x.path==="db/schema/auth.ts"))continue;let j=x.content.replace(/\{\{APP_NAME\}\}/g,v).replace(/\{\{WORKER_NAME\}\}/g,f);if(B&&x.path==="next.config.ts"&&(j=j.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),x.path==="next.config.ts"){let Pe=Wd(d);Pe&&(console.error(`[init] Project is inside monorepo at ${Pe} \u2014 adding outputFileTracingRoot`),j.includes("outputFileTracingRoot")||(j=j.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
3076
2686
|
import { dirname } from "path";
|
|
3077
2687
|
import { fileURLToPath } from "url";
|
|
3078
2688
|
|
|
3079
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));`),
|
|
3080
|
-
images: {`)))}!
|
|
2689
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));`),j=j.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
2690
|
+
images: {`)))}!H&&x.path.includes("sidebar")&&(j=j.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),j=j.replace(/, Shield/g,"")),N(d,x.path,j)}let E={...b.dependencies},S={...b.devDependencies};E["drizzle-zod"]||(E["drizzle-zod"]="^0.5.1"),k&&delete E["better-auth"],P&&(delete E["drizzle-orm"],delete E["@libsql/client"],delete E["@neondatabase/serverless"],delete S["drizzle-kit"],delete S["@electric-sql/pglite"]),B&&(delete E["@libsql/client"],E["@neondatabase/serverless"]="^0.10.0",S["@electric-sql/pglite"]="^0.2.0"),y&&(E.stripe="^17.0.0"),A&&(E.resend="^4.0.0",E["@react-email/components"]="^0.0.31"),ne&&(E.ai="^4.0.0",E["@ai-sdk/openai"]="^1.0.0",E.openai="^4.0.0",E["server-only"]="^0.0.1",E["zod-to-json-schema"]="3.24.6");let de={"@noble/ciphers":"^1.3.0"},me={react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"},Z={dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint",...P?{}:{"db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"}};if(N(d,"package.json",JSON.stringify({name:v,version:"0.1.0",private:!0,scripts:Z,dependencies:E,devDependencies:S,optionalDependencies:de,overrides:me},null,2)),b.methodology){let x=b.methodology;B||(x=x.replace(/import \{ pgTable, text, timestamp(?:, boolean)? \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
|
3081
2691
|
import { sql } from "drizzle-orm";`).replace(/import \{ pgTable, text \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
3082
|
-
import { sql } from "drizzle-orm";`).replace(/pgTable/g,"sqliteTable").replace(/drizzle-orm\/pg-core/g,"drizzle-orm/sqlite-core").replace(/timestamp\("created_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("created_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("updated_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("updated_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("([a-z_]+)"\)/g,'text("$1")').replace(/boolean\("([a-z_]+)"\)\.default\(false\)/g,'integer("$1", { mode: "boolean" }).default(false)')),
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
`)),
|
|
3087
|
-
`))
|
|
3088
|
-
`)),
|
|
3089
|
-
`)),
|
|
3090
|
-
`));
|
|
3091
|
-
`))
|
|
3092
|
-
`)),
|
|
3093
|
-
`))
|
|
3094
|
-
`))
|
|
3095
|
-
`))
|
|
3096
|
-
`)),
|
|
3097
|
-
`)),
|
|
3098
|
-
`))),U&&(q(p,"lib/server/ai.ts",['import "server-only";',"",'import { createOpenAI } from "@ai-sdk/openai";','import { streamText, type CoreMessage } from "ai";','import type { z } from "zod";','import { zodToJsonSchema } from "zod-to-json-schema";',"","export const MISTFLOW_AI_HELPER_VERSION = 2;","","// \u2500\u2500 Typed error hierarchy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Catch the specific class to give the user actionable copy.",'export class AIConfigError extends Error { readonly code = "ai_config"; }','export class AIRateLimitError extends Error { readonly code = "ai_rate_limit"; }','export class AICreditExhaustedError extends Error { readonly code = "ai_credits_exhausted"; }','export class AIModelError extends Error { readonly code = "ai_model_error"; }',"export class AISchemaError extends Error {",' readonly code = "ai_schema_error";'," /** Raw model output that failed validation. Redacted by default; set"," * MISTFLOW_DEBUG=1 in dev to see full output. */"," readonly rawOutput?: string;"," constructor(message: string, rawOutput?: string) {"," super(message);"," this.rawOutput = rawOutput;"," }","}","","function redact(s: string | undefined): string | undefined {"," if (!s) return s;",' if (process.env.MISTFLOW_DEBUG === "1") return s;',' if (s.length <= 80) return "<redacted>";',' return s.slice(0, 40) + " ...<redacted>... " + s.slice(-20);',"}","","// \u2500\u2500 Env + dispatch helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",'const DEFAULT_MISTFLOW_AI_API_URL = "https://api.mistflow.ai";',"","function runtimeKey(): string | undefined {"," // Canonical name first; legacy alias for one release of compat."," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","","function mistflowAiApiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? DEFAULT_MISTFLOW_AI_API_URL).replace(/\\/$/, "");',"}","","function gatewayHeaders(): HeadersInit {"," const key = runtimeKey();"," if (!key) {",` throw new AIConfigError("MISTFLOW_RUNTIME_KEY not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY for BYOK.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": key,'," };","}","","function isManagedAvailable(): boolean { return !!runtimeKey(); }","function isBYOKAvailable(): boolean { return !!process.env.OPENROUTER_API_KEY; }","","function noConfigError(): AIConfigError {"," return new AIConfigError(",` "AI is not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY in .env.local."`," );","}","","async function callManaged(path: string, body: unknown): Promise<Response> {"," const response = await fetch(mistflowAiApiUrl() + path, {",' method: "POST",'," headers: gatewayHeaders(),"," body: JSON.stringify(body),"," });",' if (response.status === 401) throw new AIConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (response.status === 402) throw new AICreditExhaustedError("AI credits exhausted. Top up at https://app.mistflow.ai/ai-gateway");',' if (response.status === 429) throw new AIRateLimitError("Rate limited by gateway. Retry with backoff.");'," if (!response.ok) {",' const text = await response.text().catch(() => "");',' throw new AIModelError("AI gateway error " + response.status + ": " + redact(text));'," }"," return response;","}","","// BYOK direct OpenRouter \u2014 used when MISTFLOW_RUNTIME_KEY is not set.","export const openrouter = createOpenAI({"," apiKey: process.env.OPENROUTER_API_KEY,",' baseURL: "https://openrouter.ai/api/v1",'," headers: {",' "HTTP-Referer": process.env.NEXT_PUBLIC_APP_URL ?? "https://mistflow.app",',' "X-Title": "Mistflow App",'," },","});","","// \u2500\u2500 Public surface: the `ai` object \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Always import this. The wrapper handles all dispatch (managed-first,","// BYOK fallback). Never write process.env.OPENROUTER_API_KEY in feature code.","","export type TextOptions = {"," messages: CoreMessage[];"," model?: string;"," useCase?: string;"," idempotencyKey?: string;","};","","export type ImageOptions = { prompt: string; size?: string; model?: string; idempotencyKey?: string };","export type EmbedOptions = { model?: string };","export type TTSOptions = { text: string; voice?: string; model?: string };","export type STTOptions = { audio: Blob | ArrayBuffer; model?: string };","export type RealtimeOptions = { instructions?: string; useCase?: string };","","export const ai = {"," async text(opts: TextOptions): Promise<string> {"," if (isManagedAvailable()) {",' const r = await callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: false, messages: opts.messages,"," });"," const json = (await r.json()) as { text?: string };",' return json.text ?? "";'," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return await result.text;"," }"," throw noConfigError();"," },",""," async streamText(opts: TextOptions): Promise<Response> {"," if (isManagedAvailable()) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: true, messages: opts.messages,"," });"," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return result.toDataStreamResponse();"," }"," throw noConfigError();"," },",""," async extractJSON<T>(opts: { prompt: string; schema: z.ZodType<T>; model?: string; useCase?: string }): Promise<T> {"," // Per Codex review: no dedicated /runtime/extract-json endpoint."," // Wrapper uses /runtime/text + JSON-schema-mode + local Zod validation.",' const jsonSchema = zodToJsonSchema(opts.schema, { target: "openApi3" });'," const messages: CoreMessage[] = [",' { role: "system", content: "Respond ONLY with valid JSON matching this schema: " + JSON.stringify(jsonSchema) },',' { role: "user", content: opts.prompt },'," ];",' const text = await this.text({ messages, model: opts.model, useCase: opts.useCase ?? "extract" });'," let parsed: unknown;"," try { parsed = JSON.parse(text); }",' catch { throw new AISchemaError("Model returned non-JSON output", redact(text)); }'," const result = opts.schema.safeParse(parsed);"," if (!result.success) {",' throw new AISchemaError("Model output failed schema validation: " + result.error.message, redact(text));'," }"," return result.data;"," },",""," async embed(input: string | string[], opts: EmbedOptions = {}): Promise<number[][]> {"," if (!isManagedAvailable()) {"," // BYOK embed via OpenRouter is not in v1; require managed mode for embeddings."," throw noConfigError();"," }",' const r = await callManaged("/api/ai-gateway/runtime/embed", { input, model: opts.model });'," const json = (await r.json()) as { vectors: number[][] };"," return json.vectors;"," },",""," async generateImage(opts: ImageOptions): Promise<{ url: string }[]> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt: opts.prompt, model: opts.model, size: opts.size,"," idempotency_key: opts.idempotencyKey,"," });"," const json = (await r.json()) as { url?: string; image?: string };",' return [{ url: json.url ?? json.image ?? "" }];'," },",""," async speak(opts: TTSOptions): Promise<Blob> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/tts", {'," text: opts.text, voice: opts.voice, model: opts.model,"," });"," return await r.blob();"," },",""," async transcribe(opts: STTOptions): Promise<{ text: string }> {"," if (!isManagedAvailable()) throw noConfigError();"," const blob = opts.audio instanceof Blob ? opts.audio : new Blob([opts.audio]);"," const form = new FormData();",' form.append("audio", blob);',' if (opts.model) form.append("model", opts.model);'," const key = runtimeKey();"," if (!key) throw noConfigError();",' const response = await fetch(mistflowAiApiUrl() + "/api/ai-gateway/runtime/stt", {',' method: "POST", body: form, headers: { "X-Mistflow-AI-Key": key },'," });",' if (!response.ok) throw new AIModelError("STT failed: " + response.status);'," return (await response.json()) as { text: string };"," },",""," async createRealtimeSession(opts: RealtimeOptions = {}): Promise<Record<string, unknown>> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/realtime-session", {',' use_case: opts.useCase ?? "agent", instructions: opts.instructions,'," });"," return (await r.json()) as Record<string, unknown>;"," },","};","","// \u2500\u2500 Legacy named exports (back-compat for older scaffolds + chat route) \u2500\u2500","// These wrap the new `ai` object so existing call sites keep working.",'export type AiCapability = "llm" | "voice_realtime" | "tts" | "stt" | "image";',"type ManagedTextOptions = { capability?: AiCapability; useCase?: string; model?: string; idempotencyKey?: string; stream?: boolean };","",'export function openrouterModel(model = "openai/gpt-5-mini") { return openrouter(model); }',"",'export async function streamOpenRouterText(messages: CoreMessage[], model = "openai/gpt-5-mini") {'," return streamText({ model: openrouter(model), messages });","}","","export async function mistflowManagedText(messages: CoreMessage[], options: ManagedTextOptions = {}) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: options.capability ?? "llm", use_case: options.useCase ?? "chat",'," model: options.model, idempotency_key: options.idempotencyKey,"," stream: options.stream ?? false, messages,"," });","}","","export async function mistflowManagedImage(prompt: string, options: { model?: string; size?: string; idempotencyKey?: string } = {}) {",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt, model: options.model, idempotency_key: options.idempotencyKey, size: options.size,"," });"," return await r.json();","}","","export async function mistflowManagedRealtimeSession(instructions?: string) {"," return ai.createRealtimeSession({ instructions });","}","","export async function reportDirectAIUsage(report: Record<string, unknown>): Promise<void> {"," if (!isManagedAvailable()) return;",' try { await callManaged("/api/ai-gateway/runtime/report-usage", report); } catch { /* never break user request path */ }',"}",""].join(`
|
|
3099
|
-
`)),
|
|
3100
|
-
`)),
|
|
3101
|
-
`)));let he=Array.isArray(c?.integrations)?c.integrations.map(f=>({name:f.name,preset:f.preset,envVars:f.envVars??[]})):[],xe={};for(let f of he)for(let E of f.envVars??[])xe[E.key]||(xe[E.key]={description:E.description,setupUrl:E.setupUrl,...f.name?{integration:f.name}:{}});let Oe=M?.requestedSubdomain||void 0,et={name:u,methodologyVersion:P?.version??"1.0",createdAt:new Date().toISOString(),...o?{planId:o}:{},...Oe?{requestedSubdomain:Oe}:{},plan:Array.isArray(c?.steps)?{...c,steps:c.steps.map(f=>({number:f.number,name:f.name??f.title,description:f.description,entities:f.entities,pages:f.pages,features:f.features,status:"pending"}))}:c,dbProvider:A,env:{managed:{...!D&&Q?{DATABASE_URL:{description:"Postgres connection URL",scope:"production"}}:D?{}:{TURSO_URL:{description:"Turso database URL",scope:"production"},TURSO_AUTH_TOKEN:{description:"Turso database auth token",scope:"production"}},...k?{}:{AUTH_SECRET:{description:"Auth encryption secret",scope:"production"}},...b?{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"}}:{},...y?{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"}}:{},...I?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...Object.keys(xe).length>0?{required:xe}:{}},authModel:O??"email",roles:c?.roles??null,navStyle:c?.navStyle??"sidebar",multiTenant:c?.multiTenant??!1,hasAdmin:B,hasResend:y,hasStorage:I,hasAI:U,deploy:null};q(p,"mistflow.json",JSON.stringify(et,null,2)),Ht(p);let bt=Xd(32).toString("hex"),tt=b?`
|
|
2692
|
+
import { sql } from "drizzle-orm";`).replace(/pgTable/g,"sqliteTable").replace(/drizzle-orm\/pg-core/g,"drizzle-orm/sqlite-core").replace(/timestamp\("created_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("created_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("updated_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("updated_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("([a-z_]+)"\)/g,'text("$1")').replace(/boolean\("([a-z_]+)"\)\.default\(false\)/g,'integer("$1", { mode: "boolean" }).default(false)')),x=gs(x),x=x+`
|
|
2693
|
+
|
|
2694
|
+
`+Hd+`
|
|
2695
|
+
`,N(d,"AGENTS.md",x),N(d,"CLAUDE.md",x),Yd(d,x)}b.skills&&Object.keys(b.skills).length>0&&Xd(d,b.skills);let Y=a??u?.designMd;if(Y&&N(d,"DESIGN.md",Y),l&&N(d,"PLAN.md",l),B)if(N(d,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);",' } else if (process.env.NODE_ENV !== "production") {'," // Local dev \u2014 PGlite (zero-install embedded Postgres). Gating on"," // NODE_ENV !== 'production' lets webpack/esbuild dead-code-eliminate"," // this entire branch in `next build` and the Cloudflare Worker"," // bundle, so pglite + its 30MB WASM never reach prod. In `next dev`"," // the branch is live, the static require resolves ./db-local, and"," // pglite (declared in next.config.ts's serverExternalPackages) is"," // left as an external runtime import. No bundler-evasion tricks."," // eslint-disable-next-line @typescript-eslint/no-require-imports",' const { createLocalDb } = require("./db-local");'," _db = createLocalDb();"," } else {"," throw new Error(",` "DATABASE_URL is not set in production. The Mistflow deploy pipeline injects it automatically \u2014 check the project's env vars in the dashboard."`," );"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
|
|
2696
|
+
`)),N(d,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its 30MB","// WASM binary. db.ts only requires this file when NODE_ENV !==","// 'production', so esbuild dead-code-eliminates the import in prod and","// never reaches this file. In dev, pglite is declared as a server","// external package in next.config.ts so webpack leaves it alone too.","",'import { PGlite } from "@electric-sql/pglite";','import { drizzle } from "drizzle-orm/pglite";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
|
|
2697
|
+
`)),N(d,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
|
|
2698
|
+
`)),k)N(d,"db/schema/index.ts",["// Re-export schema tables here as they are added.",""].join(`
|
|
2699
|
+
`)),N(d,"db/index.ts",["// Re-export schema tables here as they are added.",'export * from "./schema";',""].join(`
|
|
2700
|
+
`));else{N(d,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
|
|
2701
|
+
`)),N(d,"db/schema/index.ts",['export * from "./auth";',""].join(`
|
|
2702
|
+
`)),N(d,"db/index.ts",['export * from "./schema/auth";',""].join(`
|
|
2703
|
+
`));let x=u.defaultRole??"user";N(d,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { genericOAuth } from "better-auth/plugins/generic-oauth";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"","async function sendEmail({ to, subject, html, fallbackUrl }: { to: string; subject: string; html: string; fallbackUrl?: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {"," if (fallbackUrl) {"," console.error(`\\n[auth] No RESEND_API_KEY set. Email to ${to} was not sent.`);"," console.error(`[auth] Dev fallback \u2014 use this link directly:\\n ${fallbackUrl}\\n`);"," } else {"," console.error(`[auth] RESEND_API_KEY not set \u2014 skipping email send to ${to}`);"," }"," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' const body = await res.text().catch(() => "unknown");'," console.error(`[auth] Email send failed (${res.status}): ${body}`);"," throw new Error(`Email send failed: ${res.status}`);"," }","}","","function createAuth() {",' const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',' const isLocal = baseURL.includes("localhost") || baseURL.includes("127.0.0.1");'," const canSendEmail = Boolean(process.env.RESEND_API_KEY);"," const mistflowAppId = process.env.MISTFLOW_APP_ID;"," const mistflowOAuthProxyURL = process.env.MISTFLOW_OAUTH_PROXY_URL;"," // Refuse to boot a production app with email auth but no mail sender. Mistflow's"," // deploy pipeline injects a managed Resend key automatically; if it's missing,"," // that's a real misconfig and silent fallbacks let unverified users sign up."," if (!isLocal && !canSendEmail) {",` throw new Error("[auth] RESEND_API_KEY is required in production. The Mistflow deploy pipeline injects one automatically \u2014 if you're seeing this, check the project's env vars in the dashboard, or set your own RESEND_API_KEY.");`," }"," return betterAuth({"," baseURL,"," // Include the Mistflow OAuth proxy in trustedOrigins so Better Auth"," // accepts the OAuth callback round-trip without 'invalid origin' errors."," trustedOrigins: [baseURL, mistflowOAuthProxyURL].filter((u): u is string => Boolean(u)),",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,"," requireEmailVerification: !isLocal && canSendEmail,"," sendResetPassword: async ({ user, token }: { user: { email: string; name: string }; url: string; token: string }) => {"," // Better Auth's default reset URL points at /reset-password/:token (path),"," // which our frontend doesn't route. We build our own pointing at our"," // /reset-password?token=xxx page which reads the token from the query."," const resetUrl = `${baseURL}/reset-password?token=${token}`;"," await sendEmail({"," to: user.email,",' subject: "Reset your password",',' html: `<p>Hi ${user.name},</p><p>Click the link below to reset your password:</p><p><a href="${resetUrl}">${resetUrl}</a></p>`,'," fallbackUrl: isLocal ? resetUrl : undefined,"," });"," },"," },"," emailVerification: {"," sendOnSignUp: canSendEmail,"," autoSignInAfterVerification: true,"," sendVerificationEmail: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Verify your email address",',' html: `<p>Hi ${user.name},</p><p>Click the link below to verify your email:</p><p><a href="${url}">${url}</a></p>`,'," fallbackUrl: isLocal ? url : undefined,"," });"," },"," },"," secret: process.env.AUTH_SECRET,"," plugins: [",` admin({ defaultRole: "${x}" }),`," ...(mistflowAppId && mistflowOAuthProxyURL ? ["," genericOAuth({"," config: [{",' providerId: "google",'," clientId: mistflowAppId,",' clientSecret: "pkce",'," discoveryUrl: `${mistflowOAuthProxyURL}/.well-known/openid-configuration`,",' scopes: ["openid", "email", "profile"],'," pkce: true,"," redirectURI: `${baseURL}/api/auth/oauth2/callback/google`,"," }],"," }),"," ] : []),"," nextCookies(),"," ],"," databaseHooks: {"," user: {"," create: {"," // Auto-promote the app owner to admin on first signup. ADMIN_EMAIL"," // is injected by the Mistflow deploy pipeline (the email of the"," // account that ran mist_deploy). Email verification still gates"," // login when Resend is configured, so a collision attempt can't"," // actually sign in without clicking a link delivered to the"," // owner's inbox."," before: async (user: { email?: string; [k: string]: unknown }) => {"," const adminEmail = process.env.ADMIN_EMAIL;"," if (adminEmail && user.email?.toLowerCase() === adminEmail.toLowerCase()) {",' return { data: { ...user, role: "admin" } };'," }"," return { data: user };"," },"," },"," },"," },"," socialProviders: {"," ...(process.env.GITHUB_CLIENT_ID ? {"," github: {"," clientId: process.env.GITHUB_CLIENT_ID,"," clientSecret: process.env.GITHUB_CLIENT_SECRET!,"," },"," } : {}),"," },"," });","}","","// Lazy init \u2014 process.env isn't populated at module scope on Cloudflare Workers.","// The `has` trap is required: better-auth's toNextJsHandler does",'// `"handler" in auth ? auth.handler(request) : auth(request)` \u2014 without a `has`',"// trap the default forwards to the empty target object, returns false, and the","// handler tries to call the Proxy as a function, which throws TypeError and","// returns 500 on every /api/auth/* request.","let _auth: ReturnType<typeof createAuth> | null = null;","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_target, prop, receiver) {"," if (!_auth) _auth = createAuth();"," const value = Reflect.get(_auth, prop, receiver);",' if (typeof value === "function") return value.bind(_auth);'," return value;"," },"," has(_target, prop) {"," if (!_auth) _auth = createAuth();"," return prop in _auth;"," },","});",""].join(`
|
|
2704
|
+
`))}}else N(d,"package.json",JSON.stringify({name:v,version:"0.1.0",private:!0},null,2));let $=a??u?.designMd;N(d,"app/globals.css",op(W,$)),N(d,"app/layout.tsx",lp(v,W,ee?.language)),N(d,"README.md",kp(v,u,{hasStripe:y,hasResend:A,hasStorage:z,hasAdmin:H,hasAI:ne,isNeon:B})),N(d,"contracts/README.md",hs());let V=u?.dataModel??[],M=new Set,pe=0;for(let f of V){let E=f.entity??f.name;if(!E||typeof E!="string")continue;let S=ys(E);M.has(S)||(M.add(S),N(d,S,fs(E)),pe++)}pe===0&&N(d,"contracts/.gitkeep","");let te=[],R=u?.publicPages;if(Array.isArray(R))te=R;else if(typeof R=="string"){try{te=JSON.parse(R)}catch{te=[]}Array.isArray(te)||(te=[])}if(!te.includes("/")){let f=u?.steps?.some(S=>{let de=((S.name??"")+" "+(S.description??"")).toLowerCase();return de.includes("landing")||de.includes("marketing")||de.includes("homepage")}),E=u?.pages?.some(S=>S.path==="/");(f||E)&&(te=["/",...te])}let ge={name:v,summary:u?.summary,authModel:_,roles:u?.roles,defaultRole:u?.defaultRole,publicPages:te,navStyle:u?.navStyle,multiTenant:u?.multiTenant,pages:u?.pages,dataModel:u?.dataModel,design:u?.design},K=up(ge);K&&N(d,"middleware.ts",K);let ae=mp(ge);ae&&N(d,ae.path,ae.content);let Oe=hp(ge);if(Oe&&N(d,"lib/roles.ts",Oe),N(d,"app/page.tsx",gp(ge)),N(d,"app/(dashboard)/layout.tsx",fp(ge,H)),N(d,"app/(dashboard)/dashboard/page.tsx",yp(ge)),ge.multiTenant){let f=bp(ge,B);f&&N(d,"db/schema/organization.ts",f);let E=wp(ge);E&&N(d,"lib/org.ts",E);let S=vp(ge);S&&N(d,"components/org-switcher.tsx",S)}N(d,"tsconfig.json",JSON.stringify({compilerOptions:{target:"ES2017",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!1,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,plugins:[{name:"next"}],paths:{"@/*":["./*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],exclude:["node_modules"]},null,2)),y&&N(d,"lib/stripe.ts",['import Stripe from "stripe";',"","let _stripe: Stripe | null = null;","","function getStripe(): Stripe {"," if (!_stripe) {"," if (!process.env.STRIPE_SECRET_KEY) {",' throw new Error("STRIPE_SECRET_KEY is not set");'," }"," _stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {"," typescript: true,"," });"," }"," return _stripe;","}","","// Lazy proxy \u2014 Stripe isn't initialized at import/build time","export const stripe = new Proxy({} as Stripe, {"," get(_target, prop) {"," return (getStripe() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
|
|
2705
|
+
`)),A&&(N(d,"lib/resend.ts",['import { Resend } from "resend";',"","let _resend: Resend | null = null;","","function getResend(): Resend {"," if (!_resend) {"," if (!process.env.RESEND_API_KEY) {",' throw new Error("RESEND_API_KEY is not set");'," }"," _resend = new Resend(process.env.RESEND_API_KEY);"," }"," return _resend;","}","","// Lazy proxy \u2014 Resend isn't initialized at import/build time","export const resend = new Proxy({} as Resend, {"," get(_target, prop) {"," return (getResend() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
|
|
2706
|
+
`)),N(d,"lib/email.ts",['import { resend } from "./resend";',"",'const FROM = process.env.EMAIL_FROM ?? "onboarding@resend.dev";',"","export async function sendEmail({"," to,"," subject,"," react,","}: {"," to: string;"," subject: string;"," react: React.ReactElement;","}) {"," return resend.emails.send({ from: FROM, to, subject, react });","}",""].join(`
|
|
2707
|
+
`)),N(d,"lib/server/email.ts",['import "server-only";','import { render } from "@react-email/render";','import type { ReactElement } from "react";',"",'export class EmailConfigError extends Error { readonly code = "email_config"; }','export class EmailRateLimitError extends Error { readonly code = "email_rate_limit"; }','export class EmailCreditExhaustedError extends Error { readonly code = "email_credits_exhausted"; }','export class EmailUpstreamError extends Error { readonly code = "email_upstream_error"; }','export class EmailValidationError extends Error { readonly code = "email_validation"; }',"","function runtimeKey(): string | undefined {"," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","","export type EmailSendOptions = {"," to: string | string[];"," subject: string;"," html?: string;"," text?: string;"," react?: ReactElement;"," cc?: string[];"," bcc?: string[];"," replyTo?: string;"," idempotencyKey?: string;"," tags?: Record<string, string>;","};","","export const email = {"," /** Send an email. Sandbox decision is server-enforced via the runtime key's"," * environment field \u2014 your app cannot accidentally email real users from"," * dev or preview deploys. Real sends only fire when the key is",' * environment="production".'," *"," * React components are rendered to HTML locally before the gateway call"," * (React doesn't serialize over HTTP). */"," async send(opts: EmailSendOptions): Promise<{ id: string; sandbox?: boolean }> {"," if (!opts.to || (Array.isArray(opts.to) && opts.to.length === 0)) {",' throw new EmailValidationError("Recipient (to) is required");'," }"," if (!opts.subject) {",' throw new EmailValidationError("Subject is required");'," }"," let html = opts.html;"," if (opts.react && !html) {"," html = await render(opts.react);"," }",""," const key = runtimeKey();"," if (key) {"," // Managed mode \u2014 gateway handles sandbox enforcement, idempotency, billing."," const body = {"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, replyTo: opts.replyTo,"," idempotencyKey: opts.idempotencyKey, tags: opts.tags,"," };",' const r = await fetch(apiUrl() + "/api/email/send", {',' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": key },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new EmailConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (r.status === 402) throw new EmailCreditExhaustedError("Email/AI credits exhausted.");',' if (r.status === 429) throw new EmailRateLimitError("Rate limited.");'," if (r.status === 422) throw new EmailValidationError(await r.text());",' if (!r.ok) throw new EmailUpstreamError("Email gateway error " + r.status);'," return (await r.json()) as { id: string; sandbox?: boolean };"," }",""," if (process.env.RESEND_API_KEY) {"," // BYOK direct \u2014 no sandbox enforcement, user is responsible.",' const { Resend } = await import("resend");'," const client = new Resend(process.env.RESEND_API_KEY);",' const fromAddr = process.env.EMAIL_FROM ?? "onboarding@resend.dev";'," const result = await client.emails.send({"," from: fromAddr,"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, reply_to: opts.replyTo,",' ...(opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}),'," });"," if (result.error) throw new EmailUpstreamError(result.error.message);",' return { id: result.data?.id ?? "unknown", sandbox: false };'," }",""," throw new EmailConfigError(",` "Email is not configured. Run 'mist_setup' for managed mode (sandbox-safe in dev) or set RESEND_API_KEY."`," );"," },","};",""].join(`
|
|
2708
|
+
`))),z&&(N(d,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai";',"const RUNTIME_KEY = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","",'export type UploadMode = "rename" | "overwrite" | "fail";',"","export interface UploadIntent {"," /** Pre-signed PUT URL \u2014 client uploads bytes here directly. Short-lived (15 min). */"," uploadUrl: string;"," /** The fully-qualified storage key the file ends up at. Use this when persisting attachment refs. */"," finalKey: string;"," /** ISO8601 timestamp when the signed URL expires. */"," expiresAt: string;"," /** Hard upload size cap, in bytes (storage-edge enforced). */"," maxSize: number;","}","","function authHeaders(): Record<string, string> {"," if (!RUNTIME_KEY) {",` throw new Error("Storage requires MISTFLOW_RUNTIME_KEY. Run 'mist_setup' or check your .env.local.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": RUNTIME_KEY,'," };","}","","// 100MB hard cap matches the backend's storage_gateway.MAX_UPLOAD_SIZE_BYTES.","const MAX_UPLOAD_SIZE = 100 * 1024 * 1024;","","/**"," * Ask Mistflow for a pre-signed PUT URL."," *"," * The runtime key scopes the upload to this project's storage prefix on R2 \u2014"," * other projects can't read/write each other's files. The signed URL is good"," * for 15 minutes; the client PUTs the bytes directly to R2 (no proxy through"," * Mistflow). Persist `finalKey` (not `file.name`) when storing the attachment"," * reference, since the backend may have prefixed it for project isolation."," */","export async function getUploadIntent("," key: string,",' contentType: string = "application/octet-stream",'," contentLength: number,","): Promise<UploadIntent> {"," if (contentLength > MAX_UPLOAD_SIZE) {"," throw new Error(`File is over the 100MB upload limit (${contentLength} bytes)`);"," }"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-upload`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key, contentType, contentLength }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return { ...data, maxSize: MAX_UPLOAD_SIZE };","}","","/** Get a short-lived signed download URL for a previously-uploaded key. */","export async function getDownloadUrl(finalKey: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-download`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.downloadUrl as string;","}","","export async function deleteFile(finalKey: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/object`, {",' method: "DELETE",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });","}","","/**"," * Upload a file directly from the client to R2 using the pre-signed PUT URL."," * Returns { finalKey } \u2014 persist this when storing the attachment reference;"," * pair it with `getDownloadUrl(finalKey)` to render the file later."," */","export async function uploadFile(file: File): Promise<{ finalKey: string }> {"," const intent = await getUploadIntent(file.name, file.type, file.size);"," const res = await fetch(intent.uploadUrl, {",' method: "PUT",',' headers: { "Content-Type": file.type || "application/octet-stream" },'," body: file,"," });"," if (!res.ok) throw new Error(`Upload failed (${res.status})`);"," return { finalKey: intent.finalKey };","}",""].join(`
|
|
2709
|
+
`)),N(d,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadIntent } from "@/lib/storage";',"","// Server-side intent broker. The route receives the client's filename +","// content type, asks Mistflow for a signed PUT URL using the project's","// runtime key, and hands the URL back to the client. The client then PUTs","// the bytes directly to R2 \u2014 bytes never proxy through this server.","export async function POST(req: NextRequest) {"," const { key, filename, contentType, contentLength } = await req.json();"," // Backwards-compat: older client code sent { filename } without { key }."," const finalKeyHint = key ?? filename;"," if (!finalKeyHint) {",' return NextResponse.json({ error: "key (or filename) is required" }, { status: 400 });'," }",' if (typeof contentLength !== "number" || contentLength < 1) {',' return NextResponse.json({ error: "contentLength is required (file size in bytes)" }, { status: 400 });'," }"," try {"," const intent = await getUploadIntent("," finalKeyHint,",' contentType ?? "application/octet-stream",'," contentLength,"," );"," return NextResponse.json(intent);"," } catch (err) {",' const msg = err instanceof Error ? err.message : "Failed to prepare upload";'," return NextResponse.json({ error: msg }, { status: 500 });"," }","}",""].join(`
|
|
2710
|
+
`)),N(d,"lib/server/storage.ts",['import "server-only";',"",'export class StorageConfigError extends Error { readonly code = "storage_config"; }','export class StorageUpstreamError extends Error { readonly code = "storage_upstream_error"; }','export class StorageQuotaError extends Error { readonly code = "storage_quota"; }',"","function runtimeKey(): string {"," const k = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;",` if (!k) throw new StorageConfigError("Storage requires managed mode. Run 'mist_setup' to enable.");`," return k;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","async function callGateway<T>(path: string, body: unknown): Promise<T> {"," const r = await fetch(apiUrl() + path, {",' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new StorageConfigError("Runtime key rejected. Re-run mist_setup.");',' if (r.status === 402) throw new StorageQuotaError("Storage quota exhausted.");',' if (r.status === 413) throw new StorageQuotaError("File exceeds the 100MB upload limit.");',' if (!r.ok) throw new StorageUpstreamError("Storage gateway error " + r.status);'," return (await r.json()) as T;","}","","export const storage = {"," /** Upload a Blob/File. Backend mints a signed URL; client PUTs directly to R2. */"," async put(opts: { key: string; blob: Blob; contentType: string; expiresIn?: number }): Promise<{ finalKey: string }> {"," const signed = await callGateway<{ uploadUrl: string; finalKey: string; expiresAt: string }>(",' "/api/storage/sign-upload",'," {"," key: opts.key,"," contentType: opts.contentType,"," contentLength: opts.blob.size,"," expiresIn: opts.expiresIn,"," },"," );"," const res = await fetch(signed.uploadUrl, {",' method: "PUT",'," body: opts.blob,",' headers: { "Content-Type": opts.contentType },'," });"," if (!res.ok) {",' throw new StorageUpstreamError("Direct R2 upload failed: " + res.status);'," }"," return { finalKey: signed.finalKey };"," },",""," /** Get a short-lived signed download URL for a stored object. */"," async get(opts: { key: string; expiresIn?: number }): Promise<{ url: string; expiresAt: string }> {"," const signed = await callGateway<{ downloadUrl: string; expiresAt: string }>(",' "/api/storage/sign-download",'," { key: opts.key, expiresIn: opts.expiresIn },"," );"," return { url: signed.downloadUrl, expiresAt: signed.expiresAt };"," },",""," /** Delete an object. Server-side delete via R2 SDK. */"," async delete(opts: { key: string }): Promise<void> {",' const r = await fetch(apiUrl() + "/api/storage/object", {',' method: "DELETE",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify({ key: opts.key }),"," });"," if (!r.ok && r.status !== 204) {",' throw new StorageUpstreamError("Delete failed: " + r.status);'," }"," },",""," /** List objects under an optional prefix. Always scoped to your project. */"," async list(opts: { prefix?: string; limit?: number; cursor?: string } = {}): Promise<{ keys: { key: string; size: number }[]; cursor?: string }> {",' return callGateway("/api/storage/list", opts);'," },","};",""].join(`
|
|
2711
|
+
`))),ne&&(N(d,"lib/server/ai.ts",['import "server-only";',"",'import { createOpenAI } from "@ai-sdk/openai";','import { streamText, type CoreMessage } from "ai";','import type { z } from "zod";','import { zodToJsonSchema } from "zod-to-json-schema";',"","export const MISTFLOW_AI_HELPER_VERSION = 2;","","// \u2500\u2500 Typed error hierarchy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Catch the specific class to give the user actionable copy.",'export class AIConfigError extends Error { readonly code = "ai_config"; }','export class AIRateLimitError extends Error { readonly code = "ai_rate_limit"; }','export class AICreditExhaustedError extends Error { readonly code = "ai_credits_exhausted"; }','export class AIModelError extends Error { readonly code = "ai_model_error"; }',"export class AISchemaError extends Error {",' readonly code = "ai_schema_error";'," /** Raw model output that failed validation. Redacted by default; set"," * MISTFLOW_DEBUG=1 in dev to see full output. */"," readonly rawOutput?: string;"," constructor(message: string, rawOutput?: string) {"," super(message);"," this.rawOutput = rawOutput;"," }","}","","function redact(s: string | undefined): string | undefined {"," if (!s) return s;",' if (process.env.MISTFLOW_DEBUG === "1") return s;',' if (s.length <= 80) return "<redacted>";',' return s.slice(0, 40) + " ...<redacted>... " + s.slice(-20);',"}","","// \u2500\u2500 Env + dispatch helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",'const DEFAULT_MISTFLOW_AI_API_URL = "https://api.mistflow.ai";',"","function runtimeKey(): string | undefined {"," // Canonical name first; legacy alias for one release of compat."," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","","function mistflowAiApiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? DEFAULT_MISTFLOW_AI_API_URL).replace(/\\/$/, "");',"}","","function gatewayHeaders(): HeadersInit {"," const key = runtimeKey();"," if (!key) {",` throw new AIConfigError("MISTFLOW_RUNTIME_KEY not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY for BYOK.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": key,'," };","}","","function isManagedAvailable(): boolean { return !!runtimeKey(); }","function isBYOKAvailable(): boolean { return !!process.env.OPENROUTER_API_KEY; }","","function noConfigError(): AIConfigError {"," return new AIConfigError(",` "AI is not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY in .env.local."`," );","}","","async function callManaged(path: string, body: unknown): Promise<Response> {"," const response = await fetch(mistflowAiApiUrl() + path, {",' method: "POST",'," headers: gatewayHeaders(),"," body: JSON.stringify(body),"," });",' if (response.status === 401) throw new AIConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (response.status === 402) throw new AICreditExhaustedError("AI credits exhausted. Top up at https://app.mistflow.ai/ai-gateway");',' if (response.status === 429) throw new AIRateLimitError("Rate limited by gateway. Retry with backoff.");'," if (!response.ok) {",' const text = await response.text().catch(() => "");',' throw new AIModelError("AI gateway error " + response.status + ": " + redact(text));'," }"," return response;","}","","// BYOK direct OpenRouter \u2014 used when MISTFLOW_RUNTIME_KEY is not set.","export const openrouter = createOpenAI({"," apiKey: process.env.OPENROUTER_API_KEY,",' baseURL: "https://openrouter.ai/api/v1",'," headers: {",' "HTTP-Referer": process.env.NEXT_PUBLIC_APP_URL ?? "https://mistflow.app",',' "X-Title": "Mistflow App",'," },","});","","// \u2500\u2500 Public surface: the `ai` object \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Always import this. The wrapper handles all dispatch (managed-first,","// BYOK fallback). Never write process.env.OPENROUTER_API_KEY in feature code.","","export type TextOptions = {"," messages: CoreMessage[];"," model?: string;"," useCase?: string;"," idempotencyKey?: string;","};","","export type ImageOptions = { prompt: string; size?: string; model?: string; idempotencyKey?: string };","export type EmbedOptions = { model?: string };","export type TTSOptions = { text: string; voice?: string; model?: string };","export type STTOptions = { audio: Blob | ArrayBuffer; model?: string };","export type RealtimeOptions = { instructions?: string; useCase?: string };","","export const ai = {"," async text(opts: TextOptions): Promise<string> {"," if (isManagedAvailable()) {",' const r = await callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: false, messages: opts.messages,"," });"," const json = (await r.json()) as { text?: string };",' return json.text ?? "";'," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return await result.text;"," }"," throw noConfigError();"," },",""," async streamText(opts: TextOptions): Promise<Response> {"," if (isManagedAvailable()) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: true, messages: opts.messages,"," });"," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return result.toDataStreamResponse();"," }"," throw noConfigError();"," },",""," async extractJSON<T>(opts: { prompt: string; schema: z.ZodType<T>; model?: string; useCase?: string }): Promise<T> {"," // Per Codex review: no dedicated /runtime/extract-json endpoint."," // Wrapper uses /runtime/text + JSON-schema-mode + local Zod validation.",' const jsonSchema = zodToJsonSchema(opts.schema, { target: "openApi3" });'," const messages: CoreMessage[] = [",' { role: "system", content: "Respond ONLY with valid JSON matching this schema: " + JSON.stringify(jsonSchema) },',' { role: "user", content: opts.prompt },'," ];",' const text = await this.text({ messages, model: opts.model, useCase: opts.useCase ?? "extract" });'," let parsed: unknown;"," try { parsed = JSON.parse(text); }",' catch { throw new AISchemaError("Model returned non-JSON output", redact(text)); }'," const result = opts.schema.safeParse(parsed);"," if (!result.success) {",' throw new AISchemaError("Model output failed schema validation: " + result.error.message, redact(text));'," }"," return result.data;"," },",""," async embed(input: string | string[], opts: EmbedOptions = {}): Promise<number[][]> {"," if (!isManagedAvailable()) {"," // BYOK embed via OpenRouter is not in v1; require managed mode for embeddings."," throw noConfigError();"," }",' const r = await callManaged("/api/ai-gateway/runtime/embed", { input, model: opts.model });'," const json = (await r.json()) as { vectors: number[][] };"," return json.vectors;"," },",""," async generateImage(opts: ImageOptions): Promise<{ url: string }[]> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt: opts.prompt, model: opts.model, size: opts.size,"," idempotency_key: opts.idempotencyKey,"," });"," const json = (await r.json()) as { url?: string; image?: string };",' return [{ url: json.url ?? json.image ?? "" }];'," },",""," async speak(opts: TTSOptions): Promise<Blob> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/tts", {'," text: opts.text, voice: opts.voice, model: opts.model,"," });"," return await r.blob();"," },",""," async transcribe(opts: STTOptions): Promise<{ text: string }> {"," if (!isManagedAvailable()) throw noConfigError();"," const blob = opts.audio instanceof Blob ? opts.audio : new Blob([opts.audio]);"," const form = new FormData();",' form.append("audio", blob);',' if (opts.model) form.append("model", opts.model);'," const key = runtimeKey();"," if (!key) throw noConfigError();",' const response = await fetch(mistflowAiApiUrl() + "/api/ai-gateway/runtime/stt", {',' method: "POST", body: form, headers: { "X-Mistflow-AI-Key": key },'," });",' if (!response.ok) throw new AIModelError("STT failed: " + response.status);'," return (await response.json()) as { text: string };"," },",""," async createRealtimeSession(opts: RealtimeOptions = {}): Promise<Record<string, unknown>> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/realtime-session", {',' use_case: opts.useCase ?? "agent", instructions: opts.instructions,'," });"," return (await r.json()) as Record<string, unknown>;"," },","};","","// \u2500\u2500 Legacy named exports (back-compat for older scaffolds + chat route) \u2500\u2500","// These wrap the new `ai` object so existing call sites keep working.",'export type AiCapability = "llm" | "voice_realtime" | "tts" | "stt" | "image";',"type ManagedTextOptions = { capability?: AiCapability; useCase?: string; model?: string; idempotencyKey?: string; stream?: boolean };","",'export function openrouterModel(model = "openai/gpt-5-mini") { return openrouter(model); }',"",'export async function streamOpenRouterText(messages: CoreMessage[], model = "openai/gpt-5-mini") {'," return streamText({ model: openrouter(model), messages });","}","","export async function mistflowManagedText(messages: CoreMessage[], options: ManagedTextOptions = {}) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: options.capability ?? "llm", use_case: options.useCase ?? "chat",'," model: options.model, idempotency_key: options.idempotencyKey,"," stream: options.stream ?? false, messages,"," });","}","","export async function mistflowManagedImage(prompt: string, options: { model?: string; size?: string; idempotencyKey?: string } = {}) {",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt, model: options.model, idempotency_key: options.idempotencyKey, size: options.size,"," });"," return await r.json();","}","","export async function mistflowManagedRealtimeSession(instructions?: string) {"," return ai.createRealtimeSession({ instructions });","}","","export async function reportDirectAIUsage(report: Record<string, unknown>): Promise<void> {"," if (!isManagedAvailable()) return;",' try { await callManaged("/api/ai-gateway/runtime/report-usage", report); } catch { /* never break user request path */ }',"}",""].join(`
|
|
2712
|
+
`)),N(d,"lib/ai.ts",['import "server-only";',"",'export * from "./server/ai";',""].join(`
|
|
2713
|
+
`)),N(d,"app/api/chat/route.ts",['import { ai, AIConfigError, AICreditExhaustedError } from "@/lib/server/ai";','import type { CoreMessage } from "ai";',"","export async function POST(req: Request) {"," const { messages } = (await req.json()) as { messages?: CoreMessage[] };"," if (!messages) {",' return Response.json({ error: "messages is required" }, { status: 400 });'," }"," try {"," return await ai.streamText({ messages });"," } catch (e) {"," if (e instanceof AIConfigError) return Response.json({ error: e.message }, { status: 503 });"," if (e instanceof AICreditExhaustedError) return Response.json({ error: e.message }, { status: 402 });",' return Response.json({ error: "AI request failed" }, { status: 500 });'," }","}",""].join(`
|
|
2714
|
+
`)));let ke=Array.isArray(u?.integrations)?u.integrations.map(f=>({name:f.name,preset:f.preset,envVars:f.envVars??[]})):[],we={};for(let f of ke)for(let E of f.envVars??[])we[E.key]||(we[E.key]={description:E.description,setupUrl:E.setupUrl,...f.name?{integration:f.name}:{}});let Le=ee?.requestedSubdomain||void 0,Rt={name:v,methodologyVersion:b?.version??"1.0",createdAt:new Date().toISOString(),...o?{planId:o}:{},...Le?{requestedSubdomain:Le}:{},plan:Array.isArray(u?.steps)?{...u,steps:u.steps.map(f=>({number:f.number,name:f.name??f.title,description:f.description,entities:f.entities,pages:f.pages,features:f.features,status:"pending"}))}:u,dbProvider:se,env:{managed:{...!P&&B?{DATABASE_URL:{description:"Postgres connection URL",scope:"production"}}:P?{}:{TURSO_URL:{description:"Turso database URL",scope:"production"},TURSO_AUTH_TOKEN:{description:"Turso database auth token",scope:"production"}},...k?{}:{AUTH_SECRET:{description:"Auth encryption secret",scope:"production"}},...y?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...A?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{}},...Object.keys(we).length>0?{required:we}:{}},authModel:_??"email",roles:u?.roles??null,navStyle:u?.navStyle??"sidebar",multiTenant:u?.multiTenant??!1,hasAdmin:H,hasResend:A,hasStorage:z,hasAI:ne,deploy:null};N(d,"mistflow.json",JSON.stringify(Rt,null,2)),zt(d);let Ve=qd(32).toString("hex"),He=y?`
|
|
3102
2715
|
# Stripe
|
|
3103
2716
|
STRIPE_SECRET_KEY=
|
|
3104
2717
|
STRIPE_WEBHOOK_SECRET=
|
|
3105
2718
|
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
|
3106
|
-
`:"",
|
|
2719
|
+
`:"",nt=A?`
|
|
3107
2720
|
# Email (Resend)
|
|
3108
2721
|
RESEND_API_KEY=
|
|
3109
2722
|
EMAIL_FROM=onboarding@resend.dev
|
|
3110
|
-
`:"",
|
|
3111
|
-
#
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
`:"",nt=U?`
|
|
3115
|
-
# AI (server-only; do not prefix with NEXT_PUBLIC_)
|
|
3116
|
-
# Managed mode (default) \u2014 Mistflow AI Gateway with credits.
|
|
3117
|
-
# Auto-provisioned by \`mist_init\` when the plan triggers AI features.
|
|
2723
|
+
`:"",Ce="",fe=ne||z?`
|
|
2724
|
+
# Mistflow Cloud (server-only; never prefix with NEXT_PUBLIC_).
|
|
2725
|
+
# One runtime key authenticates every managed feature: AI gateway, file storage,
|
|
2726
|
+
# and future cloud-powered features. Auto-provisioned by \`mist_init\`.
|
|
3118
2727
|
MISTFLOW_RUNTIME_KEY=
|
|
3119
2728
|
MISTFLOW_AI_RUNTIME_KEY=
|
|
3120
2729
|
MISTFLOW_API_URL=https://api.mistflow.ai
|
|
3121
2730
|
MISTFLOW_AI_API_URL=https://api.mistflow.ai
|
|
3122
|
-
# BYOK fallback
|
|
2731
|
+
# BYOK fallback for AI only (used when MISTFLOW_RUNTIME_KEY is unset).
|
|
3123
2732
|
OPENROUTER_API_KEY=
|
|
3124
|
-
`:"",
|
|
3125
|
-
AUTH_SECRET=${
|
|
3126
|
-
AUTH_SECRET=your-secret-here`,
|
|
2733
|
+
`:"",je=k?"":`
|
|
2734
|
+
AUTH_SECRET=${Ve}`,rt=k?"":`
|
|
2735
|
+
AUTH_SECRET=your-secret-here`,wt=P?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
3127
2736
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
3128
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,
|
|
2737
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,st=P?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
3129
2738
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
3130
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;
|
|
2739
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;N(d,".env.local",`${wt}${je}
|
|
3131
2740
|
${k?"":`
|
|
3132
2741
|
# Mistflow-hosted Google sign-in (zero Google Cloud setup)
|
|
3133
2742
|
MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
|
|
3134
|
-
`}${
|
|
3135
|
-
${
|
|
3136
|
-
${
|
|
3137
|
-
${
|
|
2743
|
+
`}${He}${nt}${Ce}${fe}`),N(d,".env.example",`${st}${rt}
|
|
2744
|
+
${He}${nt}${Ce}${fe}`);let m=[],g=(f,E)=>{m.push({phase:f,message:E})},w=(f,E)=>{let S=m.find(de=>de.phase===f&&!de.durationMs);S&&(S.durationMs=E)};if(e){let f=qe(e.server,e.progressToken,()=>m[m.length-1]?.message??"Setting up project...");e.cleanup=()=>f.stop()}let T=Le,O=ee?.pickedDirection??ee?.designDirection??void 0,F=ee?.imageryBrief??O?.imagery??void 0,oe=ee?.designConversationId??void 0,le=ee?{name:ee.name,summary:ee.summary,audienceType:ee.audienceType,authModel:ee.authModel,dbProvider:se,dataModel:ee.dataModel,design:ee.design,publicLanding:ee.publicLanding}:void 0,ie,L;g("register","Registering project on Mistflow...");let J=Date.now();try{let f=await St(v,{template:void 0,dbProvider:se,requestedSubdomain:T,pickedDirection:O,imageryBrief:F,planContext:le,designConversationId:oe,sessionId:s});if(ie=f.id,f.design_md&&(a=f.design_md),f.plan_md&&(l=f.plan_md),f.layout_spec&&u&&typeof u=="object"&&(u.layoutSpec=f.layout_spec),f.picker_render_html&&typeof f.picker_render_html=="string")try{let Z=he(d,".mistflow");Wt(Z,{recursive:!0}),Ze(he(Z,"picker-render.html"),f.picker_render_html),console.error(`[mist_init] picker render written to .mistflow/picker-render.html (${f.picker_render_html.length} chars)`)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);console.error(`[mist_init] picker render write failed: ${Y}`)}if(F)try{let Z=await Ir(ie),Y=he(d,"public","images");Wt(Y,{recursive:!0});let x=0,j=0;for(let[Pe,Ae]of Object.entries(Z.slots))if(Ae.status==="done"&&Ae.signed_url)try{let Re=await Pr(Ae.signed_url);Ze(he(Y,`${Pe}.png`),Re),x++}catch(Re){let gl=Re instanceof Error?Re.message:String(Re);console.error(`[mist_init] imagery: ${Pe} download failed: ${gl}`)}else(Ae.status==="queued"||Ae.status==="running")&&j++;(x>0||j>0)&&console.error(`[mist_init] imagery: ${x} ready, ${j} still rendering`)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);console.error(`[mist_init] imagery manifest fetch failed: ${Y}`)}let E=he(d,"mistflow.json"),S=JSON.parse(Gt(E,"utf-8"));if(S.projectId=ie,f.layout_spec&&S.plan&&typeof S.plan=="object"&&(S.plan.layoutSpec=f.layout_spec),Ze(E,JSON.stringify(S,null,2)),ln(d,cn(ie,v)),f.managed_env&&Object.keys(f.managed_env).length>0){let Z=he(d,".env.local"),Y=Ne(Z)?Gt(Z,"utf-8"):"";for(let[x,j]of Object.entries(f.managed_env)){let Pe=new RegExp(`^${x}=.*$`,"m");Pe.test(Y)?Y=Y.replace(Pe,`${x}=${j}`):Y+=`
|
|
2745
|
+
${x}=${j}`}Ze(Z,Y)}let me=f.runtimeKey;if(me?.rawKey){let Z=he(d,".env.local"),Y=Ne(Z)?Gt(Z,"utf-8"):"",x=(j,Pe)=>{let Ae=new RegExp(`^${j}=\\s*$`,"m"),Re=new RegExp(`^${j}=`,"m");Ae.test(Y)?Y=Y.replace(Ae,`${j}=${Pe}`):Re.test(Y)||(Y+=`
|
|
2746
|
+
${j}=${Pe}`)};x("MISTFLOW_RUNTIME_KEY",me.rawKey),x("MISTFLOW_AI_RUNTIME_KEY",me.rawKey),Ze(Z,Y)}if(!k&&f.mistflow_app_id){let Z=he(d,".env.local"),Y=Ne(Z)?Gt(Z,"utf-8"):"";/^MISTFLOW_OAUTH_PROXY_URL=/m.test(Y)||(Y+=`
|
|
3138
2747
|
# Mistflow-hosted Google sign-in (zero Google Cloud setup)
|
|
3139
2748
|
MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
|
|
3140
|
-
`),/^MISTFLOW_APP_ID=/m.test(
|
|
2749
|
+
`),/^MISTFLOW_APP_ID=/m.test(Y)||(Y+=`
|
|
3141
2750
|
# Mistflow-hosted Google sign-in (zero GCP setup)
|
|
3142
2751
|
MISTFLOW_APP_ID=${f.mistflow_app_id}
|
|
3143
|
-
`),
|
|
2752
|
+
`),Ze(Z,Y)}try{let{getBaseUrl:Z,getAuthHeaders:Y}=await Promise.resolve().then(()=>(_e(),ro)),x=Y(),j=u?.features,Pe=u?.steps,Ae={};Array.isArray(j)&&j.length>0&&(Ae.features=j.map(Re=>Re.name)),u&&(Ae.plan=u),Array.isArray(Pe)&&Pe.length>0&&(Ae.provenance=Pe.map(Re=>({feature:Re.name??Re.title??`Step ${Re.number??"?"}`,user_intent:(Re.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(Ae).length>0&&await fetch(`${Z()}/api/projects/${encodeURIComponent(ie)}/state`,{method:"PUT",headers:{...x,"Content-Type":"application/json"},body:JSON.stringify(Ae)})}catch{}m[m.length-1].message=`Registered as ${ie.slice(0,8)}`}catch(f){let E=f instanceof Error?f.message:String(f);console.error("Could not register project on backend:",E),L=`Project created locally but NOT registered on Mistflow servers (${E}). Deploy will auto-register it.`,m[m.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}w("register",Date.now()-J),g("git","Initializing git repository...");let ve=Date.now();try{let f=zd(d);await f.init(),await f.add("."),await f.commit("Initial Mistflow project setup"),m[m.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),m[m.length-1].message="Git init skipped"}w("git",Date.now()-ve);let re=m.reduce((f,E)=>f+(E.durationMs??0),0),ce={projectPath:d,projectId:ie,status:"awaiting_install"};T&&(ce.requestedSubdomain=T,ce.productionUrl=`https://${T}.mistflow.app`);let Te=m.map(f=>{let E=f.durationMs?` (${(f.durationMs/1e3).toFixed(1)}s)`:"";return`${f.message}${E}`});ce.progress=Te,ce.totalSetupTime=`${(re/1e3).toFixed(1)}s`;let ue=[];ie||ue.push("Project was not registered with Mistflow (backend error during create). mist_deploy will retry registration automatically on the first deploy."),L&&(ce.registrationWarning=L),ue.length>0&&(ce.warnings=ue);let xe=`${T?`TELL THE USER: "Your app's URL is reserved: https://${T}.mistflow.app \u2014 it goes live when you deploy. While it's being built, you'll get a local preview to watch your app come together in real time." `:""}NEXT: Call mist_install({ projectPath: "${d}" }). This is fire-and-poll \u2014 the first call returns a jobId and status: "running"; re-call with the same jobId every ~15-30s until status is "complete". Typical duration 30-90s. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. After install completes, call mist_implement({ projectPath: "${d}" }) to build the first plan step.`;return ce.nextAction=ie?xe:`${xe} NOTE: The project could not be registered with the backend during init (${L??"see registrationWarning"}). mist_deploy will retry the registration automatically on the first deploy \u2014 no manual recovery needed.`,p(JSON.stringify(ce))}catch(b){try{Ld(d,{recursive:!0,force:!0})}catch{}throw b}}var Hd,Gd,rr,Vd,Kd,Jd,tp,np,mi,ap,pp,yi,bi=I(()=>{"use strict";be();qt();Zn();cs();ds();_e();Tt();nr();bs();bs();Hd=`## Project plan (PLAN.md)
|
|
2753
|
+
|
|
2754
|
+
This project ships with a \`PLAN.md\` at the root \u2014 a PRD-style
|
|
2755
|
+
projection of the plan with the data model, pages, steps, and per-step
|
|
2756
|
+
acceptance criteria. **Read it for context before each implementation
|
|
2757
|
+
step**; it tells you what to build and what "done" looks like.
|
|
2758
|
+
|
|
2759
|
+
\`PLAN.md\` is render-only. **Do not edit it manually.** It is
|
|
2760
|
+
regenerated from the canonical plan in \`mistflow.json\` whenever the
|
|
2761
|
+
plan changes (e.g. when you call \`mist_plan({ modify })\` to add a
|
|
2762
|
+
feature). Hand-edits will be overwritten.
|
|
2763
|
+
|
|
2764
|
+
Step status (\`pending | in_progress | completed\`) lives in
|
|
2765
|
+
\`mistflow.json\` under \`plan.steps[].status\` and is updated by
|
|
2766
|
+
\`mist_implement\` automatically \u2014 you don't need to manage it. The
|
|
2767
|
+
acceptance criteria checkboxes in PLAN.md are documentation, not
|
|
2768
|
+
control plane.
|
|
2769
|
+
|
|
2770
|
+
To change the plan (new feature, missed requirement, scope shift),
|
|
2771
|
+
call \`mist_plan\` with \`modify: true\` and a description. The backend
|
|
2772
|
+
generates a new plan revision and regenerates PLAN.md.
|
|
2773
|
+
`;Gd=Ht.object({name:Ht.string().min(1).optional().describe("Human-readable app name (e.g. 'Task Flow'). Optional when planId is provided \u2014 the cached plan's name is used."),plan:Ht.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Ht.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Ht.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted."),sessionId:Ht.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")});rr="# Mistflow project\n\nThis is a Mistflow-generated app. The full conventions, stack guide, and\nintegration contracts are in `AGENTS.md` (universal) and `CLAUDE.md`\n(identical copy for Claude Code).\n\nThe current build plan is in `PLAN.md` \u2014 read it for the data model,\npages, steps, and acceptance criteria. The plan is render-only; do\nnot hand-edit step status or check boxes. Step status lives in\n`mistflow.json` and is updated by `mist_implement` automatically.\n\nTo change the plan, call `mist_plan` with `modify: true` \u2014 never edit\nPLAN.md's structure manually.\n",Vd=`---
|
|
2774
|
+
description: Mistflow project conventions \u2014 read AGENTS.md + PLAN.md first
|
|
2775
|
+
alwaysApply: false
|
|
2776
|
+
---
|
|
2777
|
+
|
|
2778
|
+
${rr}`,Kd=`# VS Code Copilot instructions
|
|
2779
|
+
|
|
2780
|
+
This is the project's primary instruction file for VS Code Copilot.
|
|
2781
|
+
|
|
2782
|
+
${rr}`,Jd=`read: ["CONVENTIONS.md", "AGENTS.md", "PLAN.md"]
|
|
2783
|
+
`;tp={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},np=[["--color-background","#ffffff"],["--color-foreground","#0a0a0a"],["--color-card","#ffffff"],["--color-card-foreground","#0a0a0a"],["--color-popover","#ffffff"],["--color-popover-foreground","#0a0a0a"],["--color-muted","#f5f5f5"],["--color-muted-foreground","#525252"],["--color-border","#e5e5e5"],["--color-input","#e5e5e5"],["--color-primary","#0a0a0a"],["--color-primary-foreground","#ffffff"],["--color-ring","#0a0a0a"],["--color-secondary","#f5f5f5"],["--color-secondary-foreground","#0a0a0a"],["--color-accent","#f5f5f5"],["--color-accent-foreground","#0a0a0a"],["--color-destructive","#b91c1c"],["--color-destructive-foreground","#ffffff"],["--color-success","#15803d"],["--color-success-foreground","#ffffff"],["--color-warning","#a16207"],["--color-warning-foreground","#ffffff"],["--color-info","#0369a1"],["--color-info-foreground","#ffffff"]];mi={"Fredoka One":"Fredoka","Source Sans Pro":"Source_Sans_3","Source Serif Pro":"Source_Serif_4","Open Sans Condensed":"Open_Sans","Baloo 2":"Baloo_2","DM Serif Display":"DM_Serif_Display","DM Serif Text":"DM_Serif_Text","IBM Plex Mono":"IBM_Plex_Mono","IBM Plex Sans":"IBM_Plex_Sans","IBM Plex Serif":"IBM_Plex_Serif","Fira Code":"Fira_Code","Fira Sans":"Fira_Sans","Noto Sans JP":"Noto_Sans_JP","PT Sans":"PT_Sans","PT Serif":"PT_Serif","Work Sans":"Work_Sans","Space Mono":"Space_Mono","Space Grotesk":"Space_Grotesk","Plus Jakarta Sans":"Plus_Jakarta_Sans"};ap=new Set(["ar","he","fa","ur"]);pp={dashboard:"Home",home:"Home",overview:"Home",patient:"Users",member:"Users",user:"Users",people:"Users",team:"Users",client:"Users",contact:"Users",customer:"Users",appointment:"Calendar",schedule:"Calendar",booking:"Calendar",event:"Calendar",billing:"CreditCard",invoice:"CreditCard",payment:"CreditCard",pricing:"CreditCard",treatment:"ClipboardList",plan:"ClipboardList",task:"CheckSquare",exercise:"Dumbbell",workout:"Dumbbell",report:"BarChart3",analytics:"BarChart3",stats:"BarChart3",setting:"Settings",config:"Settings",profile:"User",account:"User",message:"MessageSquare",chat:"MessageSquare",inbox:"MessageSquare",product:"Package",item:"Package",catalog:"Package",order:"ShoppingCart",cart:"ShoppingCart",file:"FileText",document:"FileText",upload:"Upload",notification:"Bell",alert:"Bell",project:"FolderKanban",board:"FolderKanban",post:"PenSquare",blog:"PenSquare",article:"PenSquare",course:"GraduationCap",lesson:"GraduationCap",class:"GraduationCap",habit:"Target",goal:"Target",streak:"Flame",progress:"TrendingUp",feature:"Sparkles",subscription:"CreditCard",price:"CreditCard",recipe:"ChefHat",food:"UtensilsCrossed",meal:"UtensilsCrossed",pet:"PawPrint",animal:"PawPrint",music:"Music",playlist:"ListMusic",song:"Music",photo:"Image",image:"Image",gallery:"Images",video:"Video",movie:"Film",map:"MapPin",location:"MapPin",place:"MapPin",search:"Search",explore:"Compass",inventory:"Boxes",stock:"Boxes",warehouse:"Warehouse",review:"Star",rating:"Star",feedback:"Star",log:"ScrollText",history:"Clock",activity:"Activity"};yi={name:"mist_init",description:"Initialize a new Next.js project using the Mistflow stack. Downloads templates from the Mistflow registry, installs dependencies, sets up auth, and initializes git. Use this after mist_plan to create the project.",inputSchema:Gd,handler:xp}});var vi,wi=I(()=>{vi=`# Consumer Warm Archetype
|
|
3144
2784
|
|
|
3145
2785
|
Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
|
|
3146
2786
|
|
|
@@ -3307,7 +2947,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
|
|
|
3307
2947
|
- Small touch targets. Phone-first means \`h-12\` minimum.
|
|
3308
2948
|
- Empty states that just say "No data." Be encouraging.
|
|
3309
2949
|
- Dark theme as default. Consumer warm apps default to light.
|
|
3310
|
-
`});var
|
|
2950
|
+
`});var xi,ki=I(()=>{xi=`# Consumer Bold Archetype
|
|
3311
2951
|
|
|
3312
2952
|
Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
|
|
3313
2953
|
|
|
@@ -3478,7 +3118,7 @@ Social/competitive apps need an activity feed:
|
|
|
3478
3118
|
- Card-only layouts with no hierarchy. Use hero cards + supporting cards.
|
|
3479
3119
|
- Missing achievement/progress systems. The gamification IS the product.
|
|
3480
3120
|
- Light-touch buttons. CTAs should be unmissable.
|
|
3481
|
-
`});var
|
|
3121
|
+
`});var Ti,Si=I(()=>{Ti=`# Professional Clean Archetype
|
|
3482
3122
|
|
|
3483
3123
|
Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
|
|
3484
3124
|
|
|
@@ -3690,7 +3330,7 @@ h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
|
|
|
3690
3330
|
- Missing status workflows. Every booking/appointment needs a clear state machine.
|
|
3691
3331
|
- Dark theme as default. Clients associate light themes with professionalism.
|
|
3692
3332
|
- Emoji in the UI. Professional context.
|
|
3693
|
-
`});var
|
|
3333
|
+
`});var Ii,_i=I(()=>{Ii=`# Education Structured Archetype
|
|
3694
3334
|
|
|
3695
3335
|
Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
|
|
3696
3336
|
|
|
@@ -3890,7 +3530,7 @@ border-2 border-destructive bg-destructive/5 rounded-xl p-4
|
|
|
3890
3530
|
- Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
|
|
3891
3531
|
- Long lesson pages with no progress indicator. Users need to know where they are.
|
|
3892
3532
|
- Multiple competing elements per view. One thing at a time. One question at a time.
|
|
3893
|
-
`});var
|
|
3533
|
+
`});var Ci,Pi=I(()=>{Ci=`# Marketplace Browse Archetype
|
|
3894
3534
|
|
|
3895
3535
|
Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
|
|
3896
3536
|
|
|
@@ -4114,7 +3754,7 @@ border-b border-border/30 py-4
|
|
|
4114
3754
|
- Small product images. The image is the primary decision-making element.
|
|
4115
3755
|
- No empty state for zero search results. "No results for 'xyz'. Try broader terms."
|
|
4116
3756
|
- Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
|
|
4117
|
-
`});var
|
|
3757
|
+
`});var Ri,Ai=I(()=>{Ri=`# SaaS Analytical Archetype
|
|
4118
3758
|
|
|
4119
3759
|
Component-level design guidance for B2B SaaS tools, CRMs, analytics dashboards, admin panels, ops tooling, and team productivity apps. This is the biggest category \u2014 most apps that don't fit consumer, marketplace, or booking archetypes land here.
|
|
4120
3760
|
|
|
@@ -4295,7 +3935,7 @@ The most recognizable B2B SaaS landing pattern.
|
|
|
4295
3935
|
- **Inter as the only font.** Pair it with a distinctive heading font or swap it entirely.
|
|
4296
3936
|
- **Centered text + centered image below.** The most overused AI hero. Use split or offset layouts.
|
|
4297
3937
|
- **Animation on every element.** Efficient motion only: hero entrance, card reveals on scroll, number counters. Nothing else.
|
|
4298
|
-
`});var
|
|
3938
|
+
`});var Ni,Ei=I(()=>{Ni=`# Content Editorial Archetype
|
|
4299
3939
|
|
|
4300
3940
|
Component-level design guidance for blogs, newsletters, magazines, publications, documentation sites, knowledge bases, and wiki-style content tools. Substack, The Verge, Medium, Linear's changelog, Stripe's docs are the reference bar.
|
|
4301
3941
|
|
|
@@ -4502,7 +4142,7 @@ Below the hero: 3 featured pieces laid out as a horizontal strip with **oversize
|
|
|
4502
4142
|
- **Dark mode as default for a reading tool.** Offer it as a toggle, not the default.
|
|
4503
4143
|
- **Flashy motion while reading.** Scroll hijacking, parallax on body text, animated backgrounds behind paragraphs \u2014 all break reading flow.
|
|
4504
4144
|
- **More than 2 fonts.** Heading + body is enough. Adding a third font for captions or metadata dilutes the identity.
|
|
4505
|
-
`});var
|
|
4145
|
+
`});var ji,Oi=I(()=>{ji=`# Devtool Technical Archetype
|
|
4506
4146
|
|
|
4507
4147
|
Component-level design guidance for developer tools, APIs, CLIs, SDKs, infrastructure platforms, monitoring/observability, AI/ML platforms, deployment targets, and CI/CD tooling. Vercel, Linear, Supabase, Sentry, Warp, Raycast, Cursor, Neon, Anthropic Console are the reference bar.
|
|
4508
4148
|
|
|
@@ -4691,7 +4331,7 @@ Numbers styled as terminal output: \`> 47,293 deploys this week\`, \`> 99.98% up
|
|
|
4691
4331
|
- **Marketing testimonials.** Replace with GitHub star count, StackOverflow mentions, a few short founder-quoted specifics ("Cut our deploy time from 12min to 18sec" from a named engineer at a known company).
|
|
4692
4332
|
- **Feature cards with rocket / lightning / puzzle icons.** Use technical icons (terminal, code, database, network) or skip icons entirely.
|
|
4693
4333
|
- **Motion on code blocks** while the user is trying to read them. Type out ONCE on load, then leave them alone.
|
|
4694
|
-
`});var
|
|
4334
|
+
`});var Mi,Di=I(()=>{Mi=`# Creative Showcase Archetype
|
|
4695
4335
|
|
|
4696
4336
|
Component-level design guidance for portfolios, design agencies, creative studios, photographers, artists, architects, filmmakers, and any brand whose primary selling point is "look at the work we've made." Apple, Dribbble, Behance, Pentagram, IDEO are the reference bar.
|
|
4697
4337
|
|
|
@@ -4908,7 +4548,7 @@ Premium agency touch: on first load, a full-screen loading component shows the s
|
|
|
4908
4548
|
- **Scroll hijacking through the whole site.** Use sparingly \u2014 one or two scroll-pinned sections maximum.
|
|
4909
4549
|
- **Mystery-meat navigation.** Clever is bad here. "Work / About / Contact" is fine. Don't make visitors guess.
|
|
4910
4550
|
- **No contact info.** The primary purpose of this site is to generate inquiries. Make it stupid-easy to contact you.
|
|
4911
|
-
`});var
|
|
4551
|
+
`});var Ui,Li=I(()=>{Ui=`# Finance Clarity Archetype
|
|
4912
4552
|
|
|
4913
4553
|
Component-level design guidance for fintech apps, invoicing tools, expense trackers, budget apps, payroll, accounting software, banking dashboards, and any product where **money is the primary data type**. Stripe, Wise, Revolut, Mercury, Brex, QuickBooks, Ramp are the reference bar.
|
|
4914
4554
|
|
|
@@ -5127,11 +4767,11 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
|
|
|
5127
4767
|
- **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
|
|
5128
4768
|
- **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
|
|
5129
4769
|
- **Confidence-shaking UX:** progress bars that stall, skeletons that flash between states, tiny fonts for fine print. Users are nervous about their money; give them stability.
|
|
5130
|
-
`});function
|
|
5131
|
-
`),
|
|
4770
|
+
`});function Fi(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return $i[e]}var $i,vf,qi=I(()=>{"use strict";wi();ki();Si();_i();Pi();Ai();Ei();Oi();Di();Li();$i={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:vi},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:xi},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Ti},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Ii},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Ci},"saas-analytical":{id:"saas-analytical",name:"SaaS Analytical",description:"B2B SaaS, CRM, analytics, admin panels, ops tooling, team productivity (Linear, Notion, Stripe reference bar)",content:Ri},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Ni},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:ji},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:Mi},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:Ui}},vf=Object.keys($i)});import{spawn as Op,execFileSync as jp}from"child_process";import{existsSync as sr,mkdirSync as Hi,openSync as ks,closeSync as xs,readSync as Dp,readFileSync as Wi,writeFileSync as Gi,renameSync as Vi,unlinkSync as Mp,readdirSync as Tf,statSync as Lp}from"fs";import{homedir as Ki}from"os";import{join as Me,dirname as Ji}from"path";import{randomBytes as Yi,randomUUID as Up}from"crypto";function or(){return Me(Ki(),".mistflow","jobs")}function Fp(){return Me(Ki(),".mistflow","job-wrapper.cjs")}function qp(){let t=Fp(),e=Ji(t);sr(e)||Hi(e,{recursive:!0});let r=`v${Qi}`;if(sr(t))try{if(Wi(t,"utf-8").includes(r))return t}catch{}let n=Me(e,`.job-wrapper.tmp.${Yi(6).toString("hex")}`);return Gi(n,$p),Vi(n,t),t}function Vt(t){return Me(or(),t)}function Xi(t){return Me(Vt(t),"status.json")}function Bi(t,e){let r=Xi(t),n=Me(Ji(r),`.status.tmp.${Yi(6).toString("hex")}`);try{Gi(n,JSON.stringify(e,null,2)+`
|
|
4771
|
+
`),Vi(n,r)}catch(i){try{Mp(n)}catch{}throw i}}function Bp(t){let e=Xi(t);if(!sr(e))return null;try{return JSON.parse(Wi(e,"utf-8"))}catch{return null}}async function mt(t){let e=`job_${Up().replace(/-/g,"").slice(0,12)}`,r=Vt(e);Hi(r,{recursive:!0}),xs(ks(Me(r,"stdout.log"),"a")),xs(ks(Me(r,"stderr.log"),"a"));let n=new Date().toISOString(),i={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:n,cmd:t.cmd,args:t.args,cwd:t.cwd};Bi(e,i);let o=qp(),s={...process.env,...t.env??{}},a=Op("node",[o,r,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:s});a.unref();let l={...i,wrapperPid:a.pid??0};return Bi(e,l),l}function zp(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function Hp(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=jp("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=zp(r),i=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(i)&&Math.abs(n-i)>2e3)return!1}catch{}return!0}function Wp(t,e){let r=Date.parse(t),n=e?Date.parse(e):Date.now();if(!Number.isFinite(r)||!Number.isFinite(n))return"0s";let i=Math.max(0,n-r),o=Math.floor(i/1e3);if(o<60)return`${o}s`;let s=Math.floor(o/60),a=o%60;return s<60?`${s}m ${a}s`:`${Math.floor(s/60)}h ${s%60}m`}function zi(t,e){if(!sr(t))return"";let r=Lp(t);if(r.size===0)return"";let n=r.size>e?r.size-e:0,i=r.size-n,o=ks(t,"r");try{let s=Buffer.alloc(i);return Dp(o,s,0,i,n),s.toString("utf-8")}finally{xs(o)}}function Gp(t,e=200){let r=zi(Me(Vt(t),"stdout.log"),65536),n=zi(Me(Vt(t),"stderr.log"),64*1024),i=[];return r.trim()&&i.push(...r.split(`
|
|
5132
4772
|
`).slice(-e).map(o=>`[out] ${o}`)),n.trim()&&i.push(...n.split(`
|
|
5133
4773
|
`).slice(-e).map(o=>`[err] ${o}`)),i.filter(o=>o.trim().length>0).join(`
|
|
5134
|
-
`)}function
|
|
4774
|
+
`)}function Ct(t){return{stdout:Me(Vt(t),"stdout.log"),stderr:Me(Vt(t),"stderr.log")}}async function ht(t){let e=Bp(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!Hp(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:Wp(r.startedAt,r.endedAt),logTail:Gp(t)}}async function Kt(t,e){let r=Math.max(100,e.pollIntervalMs??500),n=Date.now()+Math.max(0,e.timeoutMs),i=["complete","failed","unknown_exit"];for(;;){let o=await ht(t);if(!o)return null;try{e.onPoll?.(o)}catch{}if(i.includes(o.status))return o;let s=n-Date.now();if(s<=0)return o;await new Promise(a=>setTimeout(a,Math.min(r,s)))}}var Qi,$p,wn=I(()=>{"use strict";Qi=1,$p=`// Generated by @mistflow-ai/mcp local-jobs (v${Qi}). Do not edit.
|
|
5135
4775
|
const { spawn } = require('node:child_process');
|
|
5136
4776
|
const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
|
|
5137
4777
|
const { join, dirname } = require('node:path');
|
|
@@ -5195,9 +4835,9 @@ child.on('error', (err) => {
|
|
|
5195
4835
|
});
|
|
5196
4836
|
process.exit(1);
|
|
5197
4837
|
});
|
|
5198
|
-
`});import{createServer as
|
|
5199
|
-
`)}function
|
|
5200
|
-
`)}async function
|
|
4838
|
+
`});import{createServer as Vp}from"net";import{existsSync as ir,readFileSync as Zi,writeFileSync as ea,mkdirSync as ta}from"fs";import{join as ar}from"path";import{spawn as Kp}from"child_process";function na(){let t=(process.env.MISTFLOW_VISUAL_CONTEXT??"full").toLowerCase();return t==="off"||t==="preview"||t==="full"?t:"full"}function ra(t){return ar(t,".mistflow","visual-context.json")}function sa(t){let e=ra(t);if(!ir(e))return{screenshotsTaken:0,lastScreenshotStep:0};try{return JSON.parse(Zi(e,"utf-8"))}catch{return{screenshotsTaken:0,lastScreenshotStep:0}}}function Jp(t,e){let r=ar(t,".mistflow");ir(r)||ta(r,{recursive:!0}),ea(ra(t),JSON.stringify(e,null,2)+`
|
|
4839
|
+
`)}function oa(t,e,r){if(na()!=="full")return!1;let n=sa(t);return n.screenshotsTaken>=Yp?!1:n.screenshotsTaken===0||r>0&&e>=r||e>0&&e!==n.lastScreenshotStep&&e%3===0}function ia(t,e){let r=sa(t);Jp(t,{screenshotsTaken:r.screenshotsTaken+1,lastScreenshotStep:e})}async function Qp(){return new Promise((t,e)=>{let r=Vp();r.unref(),r.on("error",e),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(n&&typeof n=="object"){let i=n.port;r.close(()=>t(i))}else r.close(()=>e(new Error("could not read assigned port")))})})}async function aa(t,e=15e3,r=500){let n=Date.now()+e;for(;Date.now()<n;){try{let i=new AbortController,o=setTimeout(()=>i.abort(),Math.min(r*2,2e3)),s=await fetch(t,{method:"HEAD",signal:i.signal});if(clearTimeout(o),s)return!0}catch{}await new Promise(i=>setTimeout(i,r))}return!1}function la(t){return ar(t,".mistflow","preview.json")}function ca(t){let e=la(t);if(!ir(e))return null;try{return JSON.parse(Zi(e,"utf-8"))}catch{return null}}function da(t){return ca(t)}function Xp(t,e){let r=ar(t,".mistflow");ir(r)||ta(r,{recursive:!0}),ea(la(t),JSON.stringify(e,null,2)+`
|
|
4840
|
+
`)}async function pa(t){if(na()==="off")return null;let e=ca(t);if(e){let n=await ht(e.jobId);if(n&&(n.status==="running"||n.status==="starting"))return{state:e,freshlyStarted:!1}}let r;try{r=await Qp()}catch{return null}try{let n=await mt({type:"preview",cmd:"sh",args:["-c",`npm run dev -- --port ${r}`],cwd:t});await new Promise(a=>setTimeout(a,600));let i=await ht(n.id);if(i&&(i.status==="failed"||i.status==="unknown_exit"))return null;let o=`http://localhost:${r}`,s={port:r,url:o,jobId:n.id,startedAt:n.startedAt};return Xp(t,s),{state:s,freshlyStarted:!0}}catch{return null}}function ua(t){try{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];Kp(e,r,{detached:!0,stdio:"ignore"}).unref()}catch{}}var Yp,Ss=I(()=>{"use strict";wn();Yp=5});var ha,ma=I(()=>{ha=`# Design Doctrine
|
|
5201
4841
|
|
|
5202
4842
|
This is the standard for every UI you generate. It is not aspirational. It is the floor.
|
|
5203
4843
|
|
|
@@ -5263,7 +4903,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
|
|
|
5263
4903
|
8. Is there ONE memorable moment on the page (signature typography / orchestrated motion / unexpected layout)? **If zero, add one. If three, keep the strongest one.**
|
|
5264
4904
|
|
|
5265
4905
|
If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
|
|
5266
|
-
`});var
|
|
4906
|
+
`});var fa,ga=I(()=>{fa=`# Typography
|
|
5267
4907
|
|
|
5268
4908
|
Typography is the cheapest way to escape AI slop and the most visible place it shows up. Every generic landing uses Inter. Every remarkable landing picks something you'd notice.
|
|
5269
4909
|
|
|
@@ -5351,7 +4991,7 @@ Pick exactly one:
|
|
|
5351
4991
|
- **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
|
|
5352
4992
|
|
|
5353
4993
|
Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
|
|
5354
|
-
`});var
|
|
4994
|
+
`});var ba,ya=I(()=>{ba="# Color\n\nColor is a commitment, not a palette swatch. The #1 failure mode in AI-generated landings is an evenly-distributed palette: a little emerald here, a little amber there, a gradient, a badge. That's visual hedging \u2014 it signals \"I couldn't pick a point of view.\"\n\nPick one color. Use it with intent.\n\n## The Token System\n\nEvery color on every screen goes through a CSS variable defined in `globals.css`. You do not hand-pick hex values in JSX. You do not use Tailwind palette utilities (`bg-emerald-500`, `text-blue-600`, `border-slate-200`). If a color isn't in the token scheme, it doesn't exist for this app.\n\n### Core tokens\n\n- `--color-background` \u2014 page background\n- `--color-foreground` \u2014 default body text\n- `--color-card` \u2014 elevated surface (cards, panels)\n- `--color-card-foreground` \u2014 text on cards\n- `--color-muted` \u2014 low-emphasis surface fill\n- `--color-muted-foreground` \u2014 secondary text (\u2265 WCAG AA contrast vs background)\n- `--color-border` \u2014 subtle dividers\n- `--color-input` \u2014 form input borders\n- `--color-popover` / `--color-popover-foreground` \u2014 dropdowns, tooltips, menus\n\n### Interactive tokens\n\n- `--color-primary` \u2014 primary CTAs, links, active tab, focus ring\n- `--color-primary-foreground` \u2014 text on primary (derived for WCAG AA contrast)\n- `--color-ring` \u2014 focus outline (same hue as primary)\n- `--color-secondary` / `--color-secondary-foreground` \u2014 quieter than primary, more than muted\n- `--color-accent` / `--color-accent-foreground` \u2014 hover states on neutrals\n\n### Semantic tokens\n\n- `--color-success` \u2014 confirmation, \"verified\" banners, positive states\n- `--color-warning` \u2014 pending states, attention, non-destructive caution\n- `--color-destructive` / `--color-destructive-foreground` \u2014 errors, irreversible actions\n- `--color-info` \u2014 neutral system messages, tips\n\n**You use these semantic tokens for all status UI.** When you need a \"green checkmark\" you reach for `text-success`, not `text-emerald-500`. When you need an amber alert you reach for `bg-warning/10 text-warning`, not `bg-amber-50 text-amber-700`.\n\n## Usage Rules\n\n**Primary color:**\n- Primary CTAs, links, the active navigation tab, focus rings.\n- NOT for headings. Black or foreground-colored headings are stronger.\n- NOT for large surface fills (it's a splash of color, not a wash).\n- NOT for borders except focus rings.\n- One bold use of primary beats twenty sprinkled uses.\n\n**Neutrals do the structural work:**\n- Background, cards, borders \u2014 all come from the neutral scale.\n- Text hierarchy via opacity on foreground (`text-foreground`, `text-foreground/80`, `text-muted-foreground`) \u2014 not different colors.\n\n**Semantic colors:**\n- Use `bg-success/10 text-success border border-success/30` for success banners (reproducibility: a light-tinted version of the success color for surface, the solid version for text and border).\n- Same shape for warning, info, destructive.\n\n## Dark Mode\n\nCommit to one theme. If DESIGN.md says the app is dark-themed, make it unambiguously dark \u2014 `#0c0c0c` / near-black base, not neutral-900. If light-themed, commit to light.\n\nDo NOT auto-swap based on `prefers-color-scheme` when DESIGN.md declared a theme direction. It chose a theme for a reason; respect it.\n\n## Forbidden\n\n- Palette utilities: `bg-emerald-500`, `text-blue-600`, `border-slate-200`, `from-purple-500`, `via-pink-300`, `to-amber-400`. Every one of these in your output is a slop indicator.\n- Hex literals inside `className` or inline `style` props.\n- Named colors from CSS (`red`, `lightgrey`, `rebeccapurple`) \u2014 never used in production UI; always a sign of rushed work.\n- Purple gradients on white. The single most overused AI-design pattern.\n- Three-color gradient pills. Rainbow badges. \"Vibrant\" anything.\n\n## Contrast\n\nEvery text/surface pair in DESIGN.md is already WCAG AA-verified by Mistflow's contrast test. You do not need to re-check \u2014 the tokens are safe by construction. You DO need to:\n\n- Not override token combinations with hardcoded classes that might fail contrast.\n- Maintain contrast for overlays (text on images, modals on scrims). When stacking text over a gradient or image, include a scrim (`bg-background/80 backdrop-blur-sm`) so body text stays \u2265 4.5:1.\n\n## Getting Color Wrong\n\nThe specific failure mode to avoid: a page where primary is used in five places, all small and incidental \u2014 a checkmark, a hover state, a tiny badge. That's AI hedging. Either use primary confidently on a hero CTA and mean it, OR don't use primary on the page at all and let neutrals carry the identity.\n"});var va,wa=I(()=>{va=`# Motion
|
|
5355
4995
|
|
|
5356
4996
|
Motion is the most-ignored dimension of AI-generated UI. Generic landings either have no motion or sprinkle tiny fades on everything. Remarkable landings pick ONE orchestrated moment and execute it precisely.
|
|
5357
4997
|
|
|
@@ -5429,7 +5069,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
|
|
|
5429
5069
|
## One-Line Motion Rule
|
|
5430
5070
|
|
|
5431
5071
|
If the motion you're about to add could be described as "subtle animation on scroll", delete it. Design motion is specific, named, and described in one sentence: "the headline lines drop in from above with a 50ms stagger at page load." If you can't describe it that specifically, you don't have a motion design \u2014 you have motion noise.
|
|
5432
|
-
`});var
|
|
5072
|
+
`});var xa,ka=I(()=>{xa=`# Spatial Composition
|
|
5433
5073
|
|
|
5434
5074
|
Layout is where AI-slop is most visible. A centered single-column hero with a pill, headline, subhead, and two CTAs is the most-recognizable generic-SaaS pattern on the internet. It is the layout you must not use.
|
|
5435
5075
|
|
|
@@ -5499,7 +5139,7 @@ To signal "designed, not templated":
|
|
|
5499
5139
|
Negative space is a design element. A hero with \`py-32\` and a tight \`max-w-2xl\` text block in a wide viewport reads as confident. A hero that fills every pixel with checkmarks, logos, and counters reads as scared.
|
|
5500
5140
|
|
|
5501
5141
|
Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
|
|
5502
|
-
`});var
|
|
5142
|
+
`});var Ta,Sa=I(()=>{Ta=`# Interaction
|
|
5503
5143
|
|
|
5504
5144
|
Every interactive element has a designed state for every phase: rest, hover, focus, active, disabled. The difference between remarkable and adequate lives in these states.
|
|
5505
5145
|
|
|
@@ -5584,7 +5224,7 @@ Small moments that add up to "designed":
|
|
|
5584
5224
|
- **Empty states** offer a specific next action, not "No data yet".
|
|
5585
5225
|
|
|
5586
5226
|
These micro-interactions are the texture of a designed product. Ship them.
|
|
5587
|
-
`});var
|
|
5227
|
+
`});var Ia,_a=I(()=>{Ia=`# UX Writing
|
|
5588
5228
|
|
|
5589
5229
|
Copy is design. A remarkable page has copy that could only be about this specific product. A generic page has copy that could describe a hundred.
|
|
5590
5230
|
|
|
@@ -5660,26 +5300,17 @@ If there's a pricing page:
|
|
|
5660
5300
|
## The Footer
|
|
5661
5301
|
|
|
5662
5302
|
A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is fine, but the company name / tagline should be specific. "StandupSync \u2014 async updates, human-sized" is better than "\xA9 2026 StandupSync Inc."
|
|
5663
|
-
`});import{existsSync as
|
|
5664
|
-
`),{added:s,skipped:a}}var
|
|
5665
|
-
`),Ht(t)}function lr(t){return t.entity??t.name??"Unknown"}function Tu(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Ma(t){return t.path??t.route??t.name??""}function Iu(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 $a(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let i=lr(n).toLowerCase();return r.some(o=>i.includes(o)||o.includes(i))})}function _u(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let i=(n.name??"").toLowerCase(),o=Ma(n).toLowerCase();return r.some(s=>i.includes(s)||s.includes(i)||o.includes(s))})}function Cu(t){let e=t.stepType;if(e&&Pu.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name??t.title??""} ${t.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function Au(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 Ru(t){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&e.push(`- **App tone**: ${t.tone}`),t.fonts&&(e.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let r={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${t.borderRadius} (${r[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let r={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${r[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let r={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${t.cardStyle} \u2014 ${r[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&e.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let r=t.visualStrategy,n=t.heroPhoto!==!1,i=n&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),i&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let s=r.heroImages[0];e.push(`- URL: ${s.url}`),e.push(`- Alt text for img tag: "${s.alt||"Hero image"} \u2014 Photo by ${s.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!r.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/home/page.tsx.'"):n||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(r.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let s of r.sectionImages)e.push(`- ${s.url} \u2014 alt: "${s.alt||"section image"} \u2014 Photo by ${s.photographer} on Unsplash"`)}(i||r.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let o=Ki(t);o?(e.push(""),e.push(`### Page composition \u2014 ${o.name} archetype`),e.push(`This plan was classified as **${o.id}** \u2014 ${o.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),e.push(""),e.push(o.content)):(e.push(""),e.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),i?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows. Must be DOMAIN-SPECIFIC."),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return e.join(`
|
|
5666
|
-
`)}function
|
|
5303
|
+
`});import{existsSync as iu,readFileSync as au,writeFileSync as lu}from"fs";import{join as cu}from"path";import{z as vn}from"zod";function cr(t,e){if(e.length===0)return{added:[],skipped:[]};let r=cu(t,"mistflow.json");if(!iu(r))throw new Error(`mistflow.json not found at ${t}`);let n=au(r,"utf-8"),i=JSON.parse(n);i.env=i.env??{},i.env.required=i.env.required??{};let o=i.env.required,s=[],a=[];for(let l of e)if(!(!l?.key||typeof l.key!="string"||!du.test(l.key))){if(o[l.key]){a.push(l.key);continue}o[l.key]={description:typeof l.description=="string"?l.description:"",...typeof l.setupUrl=="string"&&l.setupUrl?{setupUrl:l.setupUrl}:{},...typeof l.integration=="string"&&l.integration?{integration:l.integration}:{}},s.push(l.key)}return s.length>0&&lu(r,JSON.stringify(i,null,2)+`
|
|
5304
|
+
`),{added:s,skipped:a}}var lr,du,Ts=I(()=>{"use strict";lr=vn.object({key:vn.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:vn.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:vn.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:vn.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),du=/^[A-Z][A-Z0-9_]*$/});import{z as kn}from"zod";import{existsSync as gt,readFileSync as Is,writeFileSync as _s,mkdirSync as pu}from"fs";import{join as et,resolve as uu,dirname as mu}from"path";import{createConnection as hu}from"net";function gu(t){return new Promise(e=>{let r=hu({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}function yu(t){let e=et(t,"mistflow.json");if(!gt(e))return null;try{return JSON.parse(Is(e,"utf-8"))}catch{return null}}function Pa(t,e){let r=et(t,"mistflow.json");_s(r,JSON.stringify(e,null,2)+`
|
|
5305
|
+
`),zt(t)}function dr(t){return t.entity??t.name??"Unknown"}function bu(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Ca(t){return t.path??t.route??t.name??""}function wu(t){let e=(t||"text").toLowerCase();return e==="string"||e==="varchar"||e==="char"?"text":e==="integer"||e==="int"||e==="number"||e==="float"||e==="decimal"||e==="double"?"number":e==="boolean"||e==="bool"?"boolean":e==="date"||e==="datetime"||e==="timestamp"?"date":e==="email"?"email":e==="url"||e==="uri"?"url":e==="enum"||e==="select"?"select":e==="text"||e==="longtext"||e==="textarea"?"textarea":"text"}function Aa(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let i=dr(n).toLowerCase();return r.some(o=>i.includes(o)||o.includes(i))})}function vu(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let i=(n.name??"").toLowerCase(),o=Ca(n).toLowerCase();return r.some(s=>i.includes(s)||s.includes(i)||o.includes(s))})}function xu(t){let e=t.stepType;if(e&&ku.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name??t.title??""} ${t.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function Su(t){switch(t){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function Tu(t){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&e.push(`- **App tone**: ${t.tone}`),t.fonts&&(e.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let r={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${t.borderRadius} (${r[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let r={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${r[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let r={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${t.cardStyle} \u2014 ${r[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&e.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let r=t.visualStrategy,n=t.heroPhoto!==!1,i=n&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),i&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let s=r.heroImages[0];e.push(`- URL: ${s.url}`),e.push(`- Alt text for img tag: "${s.alt||"Hero image"} \u2014 Photo by ${s.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!r.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/home/page.tsx.'"):n||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(r.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let s of r.sectionImages)e.push(`- ${s.url} \u2014 alt: "${s.alt||"section image"} \u2014 Photo by ${s.photographer} on Unsplash"`)}(i||r.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let o=Fi(t);o?(e.push(""),e.push(`### Page composition \u2014 ${o.name} archetype`),e.push(`This plan was classified as **${o.id}** \u2014 ${o.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),e.push(""),e.push(o.content)):(e.push(""),e.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),i?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows. Must be DOMAIN-SPECIFIC."),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return e.join(`
|
|
5306
|
+
`)}function _u(t){let e=[];return e.push("### Landing layout (Plan G IR \u2014 STRUCTURAL AUTHORITY for this page):"),e.push(""),e.push("Build the landing page with EXACTLY these sections, in this order. Each section's `type` names a primitive \u2014 render it using the picked direction's fonts + colors + shape language. The `intent` explains WHY the section exists; the `props` are the content."),e.push(""),e.push(`- **Page intent**: ${t.page_intent}`),e.push(`- **Narrative arc**: ${t.narrative_arc}`),e.push(`- **Audience**: ${t.audience_persona}`),t.primary_cta&&e.push(`- **Primary CTA**: \`${t.primary_cta.label}\` \u2014 ${t.primary_cta.intent}`),e.push(""),e.push("**Sections (build in order):**"),e.push(""),t.sections.forEach((r,n)=>{let i=n+1;e.push(`${i}. \`${r.type}\` (id: \`${r.id}\`, role: \`${r.narrative_role}\`)`),e.push(` - **Intent**: ${r.intent}`),r.answers_section_id&&e.push(` - **Answers**: section \`${r.answers_section_id}\` (use visual cues \u2014 paired typography, matching accent, sequential numbering \u2014 to make the relationship readable)`),e.push(" - **Props** (JSON):"),e.push(" ```json");let o=JSON.stringify(r.props,null,2).split(`
|
|
5667
5307
|
`).map(s=>` ${s}`);e.push(...o),e.push(" ```"),e.push("")}),e.push("**Rules:**"),e.push("- Render sections in the order above. Do not add, remove, or reorder."),e.push("- Each section's `type` is a known primitive \u2014 implement it as a real component with the props as content. Field names in `props` are descriptive of the role (e.g. `hero_magazine.pullquote` is an italicized 15-40 word quote with a left-rule mark)."),e.push("- Use the picked direction's `fonts.display` / `fonts.body` / `colors.bg/fg/accent` / `shape_lang` (border radius scale) / `texture` (background overlay) \u2014 those are in the design choices block above."),e.push("- The IR is the structural authority for THIS page; landing-rules.md still applies for anti-slop / motion choreography / general quality. If they conflict on structure, the IR wins."),e.push("- Don't invent placeholder content \u2014 every `props` value here is what the section should display."),e.join(`
|
|
5668
|
-
`)}async function
|
|
5308
|
+
`)}async function Iu(t){try{let e=await Fr("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
|
|
5669
5309
|
- Follow existing patterns in the codebase
|
|
5670
|
-
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Ou(t,e,r,n,i,o){let s=[];s.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),s.push(""),s.push("### What to build:"),s.push(t.description),s.push(""),e.primaryAction&&(s.push("### Primary user action (non-negotiable):"),s.push(`- **Core action**: ${e.primaryAction.action}`),s.push(`- **User flow**: ${e.primaryAction.flow}`),s.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),s.push(""),s.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),s.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l){s.push(Ru(e.design)),s.push("");let k=o?Ge(o,".mistflow","rules","design-quality.md"):null;k&&Xe(k)?(s.push("### Design quality rules (non-negotiable):"),s.push("**Read `.mistflow/rules/design-quality.md` BEFORE writing any code for this step.** That file contains the full rule set (shadcn usage, routes, typography, color, layout, motion, responsive, UX writing, cognitive load, production hardening, anti-patterns). It's been written to disk to keep this prompt under the per-tool-result token cap \u2014 read it once, then write your code."),s.push("")):(s.push(Zn),s.push(""))}else e.design&&!l&&(s.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&s.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),s.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),s.push(""));if(o){let k=Hs(o);if(k.length>0){s.push("### Approved wireframe (MUST READ before writing any files):"),s.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let b of k){let y=b.replace(o,"").replace(/^\//,"");s.push(`- \`${y}\``)}s.push(""),s.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),s.push(""),s.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),s.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),s.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),s.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),s.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),s.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),s.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(s.push("### Role system (from plan):"),s.push(`- Roles: ${e.roles.join(", ")}`),s.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),s.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),s.push("")),e.multiTenant&&(s.push("### Multi-tenant (from plan):"),s.push("- Organization tables are in `db/schema/organization.ts`"),s.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),s.push("- All data queries MUST be scoped to the current org (filter by orgId)"),s.push("- Org switcher component is at `components/org-switcher.tsx`"),s.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),s.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),s.push("")),e.language&&(s.push(`### Language: ${e.language}`),s.push(`ALL user-facing text must be written in ${e.language}:`),s.push("- Page titles, headings, labels, button text, placeholder text"),s.push("- Navigation items, menu labels, footer text"),s.push("- Error messages, success messages, empty states"),s.push("- Landing page copy, marketing text, CTAs"),s.push("- Form labels and validation messages"),s.push("Code (variable names, comments, file names) stays in English."),s.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),s.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(i)&&(e.audienceType==="b2c"?(s.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),s.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),s.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),s.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),s.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),s.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),s.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),s.push("")):e.audienceType==="b2b"?(s.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),s.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),s.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),s.push("- Testimonials: from business owners who use the platform"),s.push("- Features: business benefits ('Track dietary preferences across all orders')"),s.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),s.push("")):e.audienceType==="internal"&&(s.push("### Audience: internal staff tool. No marketing copy needed."),s.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),s.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),s.push(""))),r.length>0&&(s.push("### Already completed:"),r.forEach(k=>s.push(`- ${k}`)),s.push(""));let h=e.dataModel?$a(t,e.dataModel):[];h.length>0&&(s.push("### Data model (from plan):"),h.forEach(k=>{let b=lr(k),y=Tu(k.fields);s.push(`- **${b}**: ${y}`),s.push(` Schema file: \`db/schema/${b.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let p=e.pages?_u(t,e.pages):[];if(p.length>0&&(s.push("### Pages to create/update:"),p.forEach(k=>{let b=k.description?` \u2014 ${k.description}`:"";s.push(`- \`${Ma(k)}\`${b}`)}),s.push("")),i==="crud"&&h.length>0&&h.forEach(k=>{let b=lr(k),y=b.toLowerCase().replace(/\s+/g,"-"),I=y.endsWith("s")?y:`${y}s`;s.push(`### Files for ${b} CRUD:`),s.push(`- List page: \`app/(dashboard)/${I}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${I}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${I}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${I}/actions.ts\``),s.push(`- DataTable columns: \`components/${y}-table-columns.tsx\``),s.push(`- Form: \`components/${y}-form.tsx\``),s.push("")}),l){s.push("## Design Doctrine (the standard for every UI step)"),s.push(""),s.push(xa),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(Ta),s.push(""),s.push("### Color"),s.push(_a),s.push(""),s.push("### Motion"),s.push(Ca),s.push(""),s.push("### Spatial Composition"),s.push(Ra),s.push(""),s.push("### Interaction"),s.push(Na),s.push(""),s.push("### UX Writing"),s.push(Da),s.push("");let k=o?Ge(o,"DESIGN.md"):void 0,b=k&&Xe(k)?(()=>{try{return Ro(k,"utf-8")}catch{return null}})():null;b&&(s.push("### Design system (source of truth: DESIGN.md):"),s.push(""),s.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),s.push(""),s.push(b),s.push(""));let y=o?Ge(o,".mistflow","picker-render.html"):void 0,I=o?Ge(o,".mistflow","picker-mockup.png"):void 0;!!((i==="landing"||i==="design")&&y&&Xe(y))?(s.push("### Picked landing page render \u2014 ground-truth design contract"),s.push(""),s.push("The user picked their direction from a **fully-rendered HTML preview** of this landing page. That render is at `.mistflow/picker-render.html` (relative to the project root). **Read it** \u2014 it is the design contract the user agreed to."),s.push(""),s.push("Your job for this step is **mechanical translation**: convert that standalone HTML to Next.js Server Components + Client Components in `app/home/page.tsx` (and `components/landing/*.tsx` for any sections you split out). You are NOT redesigning. The user already picked the design \u2014 colors, fonts, composition, copy, and section order are LOCKED."),s.push(""),s.push("How to translate:\n1. **Preserve every voice sample exactly.** The H1 in the rendered HTML is the headline the user picked. The CTA button text is the CTA the user picked. Do NOT paraphrase, shorten, or 'improve' them. The picker is a contract.\n2. **Preserve the section order.** Each `<section data-section-id=\"X\">` in the rendered HTML maps to a TSX section in the SAME order. You may split each section into its own component file (`components/landing/{section-id}.tsx`) for readability \u2014 that's the only structural transformation allowed.\n3. **Migrate inline `<style>` to globals.css**. The render uses one inline `<style>` block; move those rules to `app/globals.css` so the rest of the app shares the design tokens. CSS custom properties (`--color-bg` / `--color-fg` / `--color-accent`) become the canonical design tokens.\n4. **Tailwind utility classes are FORBIDDEN in this step**, the same way they were forbidden in the render. The render already emits raw CSS; keep it that way in the TSX (use `className` to attach classes defined in globals.css, not Tailwind utilities).\n5. **Image slots:** each `<img data-image-slot=\"hero|feature-1|feature-2|feature-3|og|favicon\">` in the render points at picsum placeholder URLs. Replace each `src` with `/images/{slot}.png` \u2014 those files arrive in `public/images/` from the imagery pipeline (see Plan F A.6.1; check `mist_project action='imagery'` for status during the build). For the favicon slot, also wire `app/icon.png` to the same asset.\n6. **Do not add or remove sections.** If the render has 6 sections, the deployed page has 6 sections in the same order. Adding a CTA the user didn't pick is a bug; dropping a feature card the user did pick is also a bug.\n"),s.push("Bar: a designer comparing the picker iframe and the deployed /home page side by side should not be able to tell them apart at first glance. The HTML\u2192TSX translation is mechanical. Anything creative belongs in a separate refinement step the user explicitly asks for."),s.push("")):(i==="landing"||i==="design")&&I&&Xe(I)&&(s.push("### Picker mockup as design reference"),s.push(""),s.push("The user picked their direction from a fully-rendered mockup. That mockup is at `.mistflow/picker-mockup.png` (relative to the project root). **Read it** before implementing this step \u2014 it's the visual contract."),s.push(""),s.push(`What's in the mockup:
|
|
5671
|
-
-
|
|
5672
|
-
|
|
5673
|
-
|
|
5674
|
-
`),s.push(`How to use it:
|
|
5675
|
-
1. Use \`public/images/hero.png\` as the actual \`<img>\` source in the deployed page (NOT the mockup PNG \u2014 the mockup has text baked in; the production hero photo is text-free).
|
|
5676
|
-
2. Recreate the mockup's typography placement, headline overlay treatment, and CTA position in HTML \u2014 match the typographic hierarchy exactly.
|
|
5677
|
-
3. Recreate the mockup's decorative beats \u2014 sprigs, hairline rules, badges, custom dividers, custom-shaped CTAs \u2014 as inline SVG or HTML elements with token-based colors. **Don't skip them.** Skipping decoration is what makes AI-built pages feel like templates.
|
|
5678
|
-
4. Match the mockup's design density \u2014 the deployed page should have the same visual weight per section, not a stripped-down version with only the photo.
|
|
5679
|
-
`),s.push("Bar: a designer comparing the mockup and the deployed page side by side should be able to say 'yes, this is the same brand realized in code.' Anything less leaves the picker promise unfulfilled."),s.push(""))}if(i==="landing"||i==="design"){s.push("### File location for the landing page (non-negotiable):"),s.push('Write the landing page to **`app/home/page.tsx`** \u2014 NOT `app/page.tsx`. The scaffold\'s `middleware.ts` 308-redirects `/` to `/home` as a workaround for an OpenNext Cloudflare bug. Visitors land at `/` and end up on `/home` transparently. Internal links like `<Link href="/">` still work because the middleware does the redirect on every request.'),s.push("");let k=o?Ge(o,".mistflow","rules","landing.md"):null;k&&Xe(k)?(s.push("### Landing page rules:"),s.push("**Read `.mistflow/rules/landing.md` BEFORE writing the landing page.** That file contains the full conversion structure, section catalog, motion menu, and anti-slop audit. Written to disk to keep this prompt under the per-tool-result token cap \u2014 read once, then write your code."),s.push("")):(s.push(er),s.push(""))}i==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(s.push(Eu(e.layoutSpec)),s.push(""));let u=t.integrationId?Mt(t.integrationId):void 0;if(u){let k=$t(u.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${u.name}** (${u.category})`),k?.docsUrl&&s.push(`Official docs: ${k.docsUrl}`),k?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let b of k.envVars)s.push(`- \`${b.key}\`: ${b.description} \u2014 Get it at ${b.setupUrl}`);s.push(""),s.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}k?.packages?.length&&(s.push(""),s.push(`**Packages to install:** \`npm install ${k.packages.join(" ")}\``)),s.push(""),s.push("---"),s.push(u.prompt),s.push("---"),s.push(""),s.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),s.push("")}let{reminders:w,skill:O}=await Nu(i);return s.push(w),s.push(""),O&&(s.push(`### ${i} reference:`),s.push(O),s.push("")),l&&(s.push("## Self-Audit \u2014 run before submitting this file"),s.push(""),s.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),s.push(""),s.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),s.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),s.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),s.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),s.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),s.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),s.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),s.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),s.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),s.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),s.push(""),s.push(`If every answer is "no, I'm good" \u2014 then submit.`),s.push("")),s.join(`
|
|
5680
|
-
`)}async function Du(t){let{projectPath:e,step:r,envVarsRequired:n,sessionId:i}=t,o=bu(e??process.cwd());if(n&&n.length>0)try{let S=ar(o,n);S.added.length>0&&console.error(`[implement] declared env.required: ${S.added.join(", ")}`)}catch(S){console.error("[implement] env var merge skipped:",S instanceof Error?S.message:String(S))}let s=Su(o);if(!s)return Ye(o);if(!Xe(Ge(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:S,ensureShadcnComponents:z}=await Promise.resolve().then(()=>(no(),to)),L=await S(o);L&&!s.projectId&&(s.projectId=L);let J=await z(o);J.failed?console.error(`[implement] ${J.failed}`):J.installed.length>0&&console.error(`[implement] installed ${J.installed.length} shadcn components`)}catch(S){console.error("[implement] self-heal skipped:",S instanceof Error?S.message:String(S))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return d("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let l,c=a.steps.find(S=>S.status==="in_progress");if(c){let S=a.steps.findIndex(z=>z.number===c.number);S!==-1&&(a.steps[S].status="completed",l=`Auto-completed step ${c.number} (${c.name})`,ja(o,s))}let h;if(r!==void 0){if(h=a.steps.find(S=>S.number===r),!h)return d(`Step ${r} not found. The plan has ${a.steps.length} steps (numbered ${a.steps[0].number} to ${a.steps[a.steps.length-1].number}).`,!0)}else if(h=a.steps.find(S=>S.status!=="completed"),!h)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(S=>S.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let p=a.steps.filter(S=>S.status==="completed").map(S=>`Step ${S.number}: ${S.name}`),{readLocalState:u}=await Promise.resolve().then(()=>(St(),dn)),w=u(o),O=Cu(h),k=[];if((O==="crud"||O==="schema")&&a.dataModel&&h.entities&&h.entities.length>0){let S=$a(h,a.dataModel);for(let z of S){let L=lr(z);try{let J=(z.fields||[]).map(Y=>typeof Y=="string"?{name:Y,type:"text"}:{name:Y.name,type:Iu(Y.type),required:Y.required!==!1});if(J.length===0)continue;let j=s.dbProvider==="neon"?"nextjs-neon":"nextjs",R=await zr(j,L,J),N=0,Ie=0;for(let Y of R.files){let he=Ge(o,Y.path);if(Xe(he)){Ie++;continue}yu(wu(he),{recursive:!0}),Ao(he,Y.content),N++}let Pe=Ge(o,"db","index.ts");if(Xe(Pe)){let Y=Ro(Pe,"utf-8");Y.includes(R.dbExport)||Ao(Pe,Y.trimEnd()+`
|
|
5681
|
-
`+R.dbExport+`
|
|
5682
|
-
`)}N>0?k.push(`${R.entityPascal} CRUD (${N} new files${Ie>0?`, ${Ie} existing skipped`:""})`):Ie>0&&k.push(`${R.entityPascal} CRUD (all ${Ie} files already exist \u2014 skipped)`)}catch(J){console.error(`Module generation failed for ${L} (non-fatal):`,J instanceof Error?J.message:J)}}}let b=await Ou(h,a,p,null,O,o),y=a.steps.findIndex(S=>S.number===h.number);if(y!==-1&&(s.plan.steps[y].status="in_progress",ja(o,s)),w&&s.projectId){let{syncRemoteState:S}=await Promise.resolve().then(()=>(St(),dn));S(s.projectId,w).catch(()=>{})}let I=a.steps.every(S=>S.status==="completed"||S.number===h.number),B;I?B=`THIS IS THE LAST STEP. Rules for speed:
|
|
5310
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Pu(t,e,r,n,i,o){let s=[];s.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),s.push(""),s.push("### What to build:"),s.push(t.description),s.push(""),e.primaryAction&&(s.push("### Primary user action (non-negotiable):"),s.push(`- **Core action**: ${e.primaryAction.action}`),s.push(`- **User flow**: ${e.primaryAction.flow}`),s.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),s.push(""),s.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),s.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l){s.push(Tu(e.design)),s.push("");let _=o?et(o,".mistflow","rules","design-quality.md"):null;_&>(_)?(s.push("### Design quality rules (non-negotiable):"),s.push("**Read `.mistflow/rules/design-quality.md` BEFORE writing any code for this step.** That file contains the full rule set (shadcn usage, routes, typography, color, layout, motion, responsive, UX writing, cognitive load, production hardening, anti-patterns). It's been written to disk to keep this prompt under the per-tool-result token cap \u2014 read it once, then write your code."),s.push("")):(s.push(er),s.push(""))}else e.design&&!l&&(s.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&s.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),s.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),s.push(""));if(o){let _=Fo(o);if(_.length>0){s.push("### Approved wireframe (MUST READ before writing any files):"),s.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let k of _){let y=k.replace(o,"").replace(/^\//,"");s.push(`- \`${y}\``)}s.push(""),s.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),s.push(""),s.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),s.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),s.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),s.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),s.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),s.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),s.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(s.push("### Role system (from plan):"),s.push(`- Roles: ${e.roles.join(", ")}`),s.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),s.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),s.push("")),e.multiTenant&&(s.push("### Multi-tenant (from plan):"),s.push("- Organization tables are in `db/schema/organization.ts`"),s.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),s.push("- All data queries MUST be scoped to the current org (filter by orgId)"),s.push("- Org switcher component is at `components/org-switcher.tsx`"),s.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),s.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),s.push("")),e.language&&(s.push(`### Language: ${e.language}`),s.push(`ALL user-facing text must be written in ${e.language}:`),s.push("- Page titles, headings, labels, button text, placeholder text"),s.push("- Navigation items, menu labels, footer text"),s.push("- Error messages, success messages, empty states"),s.push("- Landing page copy, marketing text, CTAs"),s.push("- Form labels and validation messages"),s.push("Code (variable names, comments, file names) stays in English."),s.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),s.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(i)&&(e.audienceType==="b2c"?(s.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),s.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),s.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),s.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),s.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),s.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),s.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),s.push("")):e.audienceType==="b2b"?(s.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),s.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),s.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),s.push("- Testimonials: from business owners who use the platform"),s.push("- Features: business benefits ('Track dietary preferences across all orders')"),s.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),s.push("")):e.audienceType==="internal"&&(s.push("### Audience: internal staff tool. No marketing copy needed."),s.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),s.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),s.push(""))),r.length>0&&(s.push("### Already completed:"),r.forEach(_=>s.push(`- ${_}`)),s.push(""));let u=e.dataModel?Aa(t,e.dataModel):[];u.length>0&&(s.push("### Data model (from plan):"),u.forEach(_=>{let k=dr(_),y=bu(_.fields);s.push(`- **${k}**: ${y}`),s.push(` Schema file: \`db/schema/${k.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let h=e.pages?vu(t,e.pages):[];if(h.length>0&&(s.push("### Pages to create/update:"),h.forEach(_=>{let k=_.description?` \u2014 ${_.description}`:"";s.push(`- \`${Ca(_)}\`${k}`)}),s.push("")),i==="crud"&&u.length>0&&u.forEach(_=>{let k=dr(_),y=k.toLowerCase().replace(/\s+/g,"-"),A=y.endsWith("s")?y:`${y}s`;s.push(`### Files for ${k} CRUD:`),s.push(`- List page: \`app/(dashboard)/${A}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${A}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${A}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${A}/actions.ts\``),s.push(`- DataTable columns: \`components/${y}-table-columns.tsx\``),s.push(`- Form: \`components/${y}-form.tsx\``),s.push("")}),l){s.push("## Design Doctrine (the standard for every UI step)"),s.push(""),s.push(ha),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(fa),s.push(""),s.push("### Color"),s.push(ba),s.push(""),s.push("### Motion"),s.push(va),s.push(""),s.push("### Spatial Composition"),s.push(xa),s.push(""),s.push("### Interaction"),s.push(Ta),s.push(""),s.push("### UX Writing"),s.push(Ia),s.push("");let _=o?et(o,"DESIGN.md"):void 0,k=_&>(_)?(()=>{try{return Is(_,"utf-8")}catch{return null}})():null;k&&(s.push("### Design system (source of truth: DESIGN.md):"),s.push(""),s.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),s.push(""),s.push(k),s.push(""));let y=o?et(o,".mistflow","picker-render.html"):void 0;(i==="landing"||i==="design")&&y&>(y)&&(s.push("### Picked landing page render \u2014 ground-truth design contract"),s.push(""),s.push("The user picked their direction from a **fully-rendered HTML preview** of this landing page. That render is at `.mistflow/picker-render.html` (relative to the project root). **Read it** \u2014 it is the design contract the user agreed to."),s.push(""),s.push("Your job for this step is **mechanical translation**: convert that standalone HTML to Next.js Server Components + Client Components in `app/home/page.tsx` (and `components/landing/*.tsx` for any sections you split out). You are NOT redesigning. The user already picked the design \u2014 colors, fonts, composition, copy, and section order are LOCKED."),s.push(""),s.push("How to translate:\n1. **Preserve every voice sample exactly.** The H1 in the rendered HTML is the headline the user picked. The CTA button text is the CTA the user picked. Do NOT paraphrase, shorten, or 'improve' them. The picker is a contract.\n2. **Preserve the section order.** Each `<section data-section-id=\"X\">` in the rendered HTML maps to a TSX section in the SAME order. You may split each section into its own component file (`components/landing/{section-id}.tsx`) for readability \u2014 that's the only structural transformation allowed.\n3. **Migrate inline `<style>` to globals.css**. The render uses one inline `<style>` block; move those rules to `app/globals.css` so the rest of the app shares the design tokens. CSS custom properties (`--color-bg` / `--color-fg` / `--color-accent`) become the canonical design tokens.\n4. **Tailwind utility classes are FORBIDDEN in this step**, the same way they were forbidden in the render. The render already emits raw CSS; keep it that way in the TSX (use `className` to attach classes defined in globals.css, not Tailwind utilities).\n5. **Image slots:** each `<img data-image-slot=\"hero|feature-1|feature-2|feature-3|og|favicon\">` in the render points at picsum placeholder URLs. Replace each `src` with `/images/{slot}.png` \u2014 those files arrive in `public/images/` from the imagery pipeline (see Plan F A.6.1; check `mist_project action='imagery'` for status during the build). For the favicon slot, also wire `app/icon.png` to the same asset.\n6. **Do not add or remove sections.** If the render has 6 sections, the deployed page has 6 sections in the same order. Adding a CTA the user didn't pick is a bug; dropping a feature card the user did pick is also a bug.\n"),s.push("Bar: a designer comparing the picker iframe and the deployed /home page side by side should not be able to tell them apart at first glance. The HTML\u2192TSX translation is mechanical. Anything creative belongs in a separate refinement step the user explicitly asks for."),s.push(""))}if(i==="landing"||i==="design"){s.push("### File location for the landing page (non-negotiable):"),s.push('Write the landing page to **`app/home/page.tsx`** \u2014 NOT `app/page.tsx`. The scaffold\'s `middleware.ts` 308-redirects `/` to `/home` as a workaround for an OpenNext Cloudflare bug. Visitors land at `/` and end up on `/home` transparently. Internal links like `<Link href="/">` still work because the middleware does the redirect on every request.'),s.push("");let _=o?et(o,".mistflow","rules","landing.md"):null;_&>(_)?(s.push("### Landing page rules:"),s.push("**Read `.mistflow/rules/landing.md` BEFORE writing the landing page.** That file contains the full conversion structure, section catalog, motion menu, and anti-slop audit. Written to disk to keep this prompt under the per-tool-result token cap \u2014 read once, then write your code."),s.push("")):(s.push(tr),s.push(""))}i==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(s.push(_u(e.layoutSpec)),s.push(""));let d=t.integrationId?Lt(t.integrationId):void 0;if(d){let _=Ut(d.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${d.name}** (${d.category})`),_?.docsUrl&&s.push(`Official docs: ${_.docsUrl}`),_?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let k of _.envVars)s.push(`- \`${k.key}\`: ${k.description} \u2014 Get it at ${k.setupUrl}`);s.push(""),s.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}_?.packages?.length&&(s.push(""),s.push(`**Packages to install:** \`npm install ${_.packages.join(" ")}\``)),s.push(""),s.push("---"),s.push(d.prompt),s.push("---"),s.push(""),s.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),s.push("")}let{reminders:v,skill:W}=await Iu(i);return s.push(v),s.push(""),W&&(s.push(`### ${i} reference:`),s.push(W),s.push("")),l&&(s.push("## Self-Audit \u2014 run before submitting this file"),s.push(""),s.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),s.push(""),s.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),s.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),s.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),s.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),s.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),s.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),s.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),s.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),s.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),s.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),s.push(""),s.push(`If every answer is "no, I'm good" \u2014 then submit.`),s.push("")),s.join(`
|
|
5311
|
+
`)}async function Cu(t){let{projectPath:e,step:r,envVarsRequired:n,sessionId:i}=t,o=uu(e??process.cwd());if(n&&n.length>0)try{let b=cr(o,n);b.added.length>0&&console.error(`[implement] declared env.required: ${b.added.join(", ")}`)}catch(b){console.error("[implement] env var merge skipped:",b instanceof Error?b.message:String(b))}let s=yu(o);if(!s)return Ye(o);if(!gt(et(o,"node_modules")))return p(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:b,ensureShadcnComponents:$}=await Promise.resolve().then(()=>(Zr(),Xr)),V=await b(o);V&&!s.projectId&&(s.projectId=V);let M=await $(o);M.failed?console.error(`[implement] ${M.failed}`):M.installed.length>0&&console.error(`[implement] installed ${M.installed.length} shadcn components`)}catch(b){console.error("[implement] self-heal skipped:",b instanceof Error?b.message:String(b))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return p("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let l,c=a.steps.find(b=>b.status==="in_progress");if(c){let b=a.steps.findIndex($=>$.number===c.number);b!==-1&&(a.steps[b].status="completed",l=`Auto-completed step ${c.number} (${c.name})`,Pa(o,s))}let u;if(r!==void 0){if(u=a.steps.find(b=>b.number===r),!u)return p(`Step ${r} not found. The plan has ${a.steps.length} steps (numbered ${a.steps[0].number} to ${a.steps[a.steps.length-1].number}).`,!0)}else if(u=a.steps.find(b=>b.status!=="completed"),!u)return p(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(b=>b.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let h=a.steps.filter(b=>b.status==="completed").map(b=>`Step ${b.number}: ${b.name}`),{readLocalState:d}=await Promise.resolve().then(()=>(Tt(),dn)),v=d(o),W=xu(u),_=[];if((W==="crud"||W==="schema")&&a.dataModel&&u.entities&&u.entities.length>0){let b=Aa(u,a.dataModel);for(let $ of b){let V=dr($);try{let M=($.fields||[]).map(ae=>typeof ae=="string"?{name:ae,type:"text"}:{name:ae.name,type:wu(ae.type),required:ae.required!==!1});if(M.length===0)continue;let pe=s.dbProvider==="neon"?"nextjs-neon":"nextjs",te=await zr(pe,V,M),R=0,ge=0;for(let ae of te.files){let Oe=et(o,ae.path);if(gt(Oe)){ge++;continue}pu(mu(Oe),{recursive:!0}),_s(Oe,ae.content),R++}let K=et(o,"db","index.ts");if(gt(K)){let ae=Is(K,"utf-8");ae.includes(te.dbExport)||_s(K,ae.trimEnd()+`
|
|
5312
|
+
`+te.dbExport+`
|
|
5313
|
+
`)}R>0?_.push(`${te.entityPascal} CRUD (${R} new files${ge>0?`, ${ge} existing skipped`:""})`):ge>0&&_.push(`${te.entityPascal} CRUD (all ${ge} files already exist \u2014 skipped)`)}catch(M){console.error(`Module generation failed for ${V} (non-fatal):`,M instanceof Error?M.message:M)}}}let k=await Pu(u,a,h,null,W,o),y=a.steps.findIndex(b=>b.number===u.number);if(y!==-1&&(s.plan.steps[y].status="in_progress",Pa(o,s)),v&&s.projectId){let{syncRemoteState:b}=await Promise.resolve().then(()=>(Tt(),dn));b(s.projectId,v).catch(()=>{})}let A=a.steps.every(b=>b.status==="completed"||b.number===u.number),z;A?z=`THIS IS THE LAST STEP. Rules for speed:
|
|
5683
5314
|
|
|
5684
5315
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
5685
5316
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -5690,54 +5321,52 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
5690
5321
|
- Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
|
|
5691
5322
|
5. Call mist_build({ projectPath }) (fire-and-poll \u2014 re-call with the returned jobId until status 'complete'), then mist_deploy({ action: 'deploy', projectPath, envVarsRequired: [...] }). Pass envVarsRequired on the deploy call if your code uses any process.env.X that isn't already in mistflow.json env.required (skip keys covered by integration presets \u2014 those are pre-declared).
|
|
5692
5323
|
6. SHIP THE APP. This IS the ship moment, not a "ready when you are" checkpoint. Do NOT tell the user "when ready to ship", "next moves you can run", "you can deploy when ready", or list out manual commands like \`npm run db:push\` / \`npm run dev\` \u2014 Mistflow's pitch is "describe an app, get a live URL," and that contract is fulfilled by chaining mist_build \u2192 mist_deploy automatically. The user already approved the build when they approved the plan.
|
|
5693
|
-
7. If mist_build reports type errors in files you did NOT modify in this build (e.g. lib/auth.ts, app/api/admin/seed/route.ts, scaffold-origin code), DO NOT stop \u2014 Mistflow apps do not typecheck before deploy and these errors don't block production. Proceed to mist_deploy. Only halt if mist_build reports an actual compile/runtime failure (a missing import, a syntax error, a runtime error you introduced).`:
|
|
5324
|
+
7. If mist_build reports type errors in files you did NOT modify in this build (e.g. lib/auth.ts, app/api/admin/seed/route.ts, scaffold-origin code), DO NOT stop \u2014 Mistflow apps do not typecheck before deploy and these errors don't block production. Proceed to mist_deploy. Only halt if mist_build reports an actual compile/runtime failure (a missing import, a syntax error, a runtime error you introduced).`:z=`IMPLEMENT THIS STEP NOW. Rules for speed:
|
|
5694
5325
|
|
|
5695
5326
|
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.
|
|
5696
5327
|
2. Write ALL files for this step using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message. Do NOT write one file at a time.
|
|
5697
5328
|
3. Do NOT read files you already know: AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts, drizzle.config.ts \u2014 these haven't changed.
|
|
5698
5329
|
4. Only read a file if you need to MODIFY it (e.g. sidebar.tsx to add a nav link, db/index.ts to add an export).
|
|
5699
|
-
5. After writing ALL files, call mist_implement to move to the next step. If you used any process.env.X that isn't already in mistflow.json env.required, pass it via envVarsRequired on this call so the dashboard can prompt the user for it (skip keys covered by integration presets \u2014 those are pre-declared). Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let
|
|
5700
|
-
`)}async function
|
|
5330
|
+
5. After writing ALL files, call mist_implement to move to the next step. If you used any process.env.X that isn't already in mistflow.json env.required, pass it via envVarsRequired on this call so the dashboard can prompt the user for it (skip keys covered by integration presets \u2014 those are pre-declared). Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let H=Su(W),ne={stepNumber:u.number,totalSteps:a.steps.length,estimatedMinutes:H,announcement:`Starting step ${u.number} of ${a.steps.length}: ${u.name}. This step usually takes ${H.min}\u2013${H.max} minutes.`},Q=JSON.stringify({instruction:k,step:{number:u.number,name:u.name,description:u.description,status:"in_progress"},stepTiming:ne,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_implement again immediately after the compaction finishes. The tool finds the in-progress step and returns fresh context \u2014 you don't need to re-read files or re-derive state.",...l?{autoCompleted:l}:{},..._.length>0?{generatedModules:_,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${h.length}/${a.steps.length} steps done`,nextAction:z}),q=da(o),P=q?.url??"http://localhost:3000",se=q?.port??3e3;return await gu(se)&&oa(o,u.number,a.steps.length)?(ia(o,u.number),Gs(P,Q)):p(Q)}var fu,ku,Ra,Ea=I(()=>{"use strict";be();_e();zn();ss();cs();qi();ds();Ss();nr();ma();ga();ya();wa();ka();Sa();_a();Ts();fu=kn.object({projectPath:kn.string().optional().describe("Path to the project directory (default: cwd)"),step:kn.number().optional().describe("Specific step number to implement (default: next incomplete step)"),sessionId:kn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),envVarsRequired:kn.array(lr).optional().describe("Declare any env vars the code you just wrote uses (process.env.X) that aren't already in mistflow.json env.required. Server merges these into the manifest so missing values surface as warnings on deploy. Skip keys already covered by integration presets (Stripe, Resend, etc. \u2014 those are pre-declared). Only declare ad-hoc keys you introduced. First declaration wins; re-declaring is a no-op.")});ku=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);Ra={name:"mist_implement",description:"Execute the next step (or a specific step) from the app plan. Reads mistflow.json, finds the target step, and returns rich context and detailed implementation instructions for the host AI. Auto-commits a checkpoint before changes for safe undo. Use when the user says 'mist implement' or 'mist next step'.",inputSchema:fu,handler:Cu}});import{z as ft}from"zod";import{resolve as Au}from"path";async function Na(t){let{projectPath:e,action:r,key:n,value:i,category:o,description:s,setupUrl:a}=t,l=Au(e??process.cwd());if(!Se())return Ee("manage env vars");let u=it(l)?.projectId;if(!u)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"set":return n?i?(await Or(u,n,i,{category:o,description:s,setupUrl:a}),p(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):p("Value is required. Provide the env var value.",!0):p("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let h=await Nr(u);return h.length===0?p(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):p(JSON.stringify({envVars:h.map(d=>({key:d.key,category:d.category,description:d.description,hasValue:d.has_value})),message:`${h.length} environment variable(s) configured.`}))}case"delete":return n?(await jr(u,n),p(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):p("Key is required. Provide the env var name to delete.",!0);default:return p(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(h){if(h instanceof G)return p(h.message,!0);let d=h instanceof Error?h.message:"An unexpected error occurred";return p(d,!0)}}var wy,Oa=I(()=>{"use strict";be();_e();kt();wy=ft.object({projectPath:ft.string().optional().describe("Path to the project directory (default: cwd)"),action:ft.enum(["set","list","delete"]).describe("Action to perform"),key:ft.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:ft.string().optional().describe("Environment variable value (required for 'set')"),category:ft.string().optional().describe("Category for the env var (default: 'custom')"),description:ft.string().optional().describe("Description of what this env var is for"),setupUrl:ft.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as xn}from"zod";import{resolve as Ru,join as Eu}from"path";import{existsSync as Nu,readFileSync as Ou,writeFileSync as ju}from"fs";function Ps(t,e){let r=Eu(t,"mistflow.json");if(!Nu(r))return;let n;try{n=JSON.parse(Ou(r,"utf-8"))}catch{return}n.domains=e,ju(r,JSON.stringify(n,null,2)+`
|
|
5331
|
+
`)}async function ja(t){let{projectPath:e,action:r,domain:n,domainId:i}=t,o=Ru(e??process.cwd());if(!Se())return Ee("manage custom domains");let a=it(o)?.projectId;if(!a)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!n)return p("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Ar(a,n),c=await lt(a);return Ps(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await lt(a);return l.length===0?p(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):p(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!i){if(n){let h=(await lt(a)).find(d=>d.domain===n);if(h){let d=await $n(a,h.id);return p(JSON.stringify({domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message,message:d.status==="active"?`Domain '${d.domain}' is active and serving traffic.`:`Domain '${d.domain}' is ${d.status}. Make sure DNS records are configured correctly.`}))}return p(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return p("Provide either domainId or domain name to verify.",!0)}let l=await $n(a,i),c=await lt(a);return Ps(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!i&&!n)return p("Provide either domainId or domain name to remove.",!0);let l=i;if(!l&&n){let h=(await lt(a)).find(d=>d.domain===n);if(!h)return p(`Domain '${n}' not found.`,!0);l=h.id}await Rr(a,l);let c=await lt(a);return Ps(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return p(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof G)return p(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return p(c,!0)}}var Py,Da=I(()=>{"use strict";be();_e();kt();Py=xn.object({projectPath:xn.string().optional().describe("Path to the project directory (default: cwd)"),action:xn.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:xn.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:xn.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as Be}from"zod";var Du,Ma,La=I(()=>{"use strict";be();Oa();Da();Du=Be.object({resource:Be.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Be.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Be.string().optional().describe("Path to the project directory (default: cwd)"),key:Be.string().optional().describe("(env) Variable name"),value:Be.string().optional().describe("(env set) Variable value"),category:Be.string().optional().describe("(env set) Category"),description:Be.string().optional().describe("(env set) Description"),setupUrl:Be.string().optional().describe("(env set) URL to obtain the value"),domain:Be.string().optional().describe("(domain) Domain name"),domainId:Be.string().optional().describe("(domain) Domain ID")}),Ma={name:"mist_config",description:"Manage project configuration: app secrets and custom domains. Set resource='env' to manage encrypted app secrets (set, list, delete). Set resource='domain' to manage custom domains (add, list, verify, remove). Use when the user says 'mist env' or 'mist domain'.",inputSchema:Du,handler:async t=>{let e=t;switch(e.resource){case"env":return Na({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return ja({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return p(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}}});import{z as Sn}from"zod";import{resolve as Mu}from"path";import{existsSync as Lu}from"fs";import{join as Uu}from"path";function $u(t,e=15){let r=t.split(`
|
|
5701
5332
|
`).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
|
|
5702
|
-
`)}var
|
|
5703
|
-
|
|
5704
|
-
`+Ka(r,"utf-8"))}catch{}return n}function nm(t,e=15){let r=t.split(`
|
|
5333
|
+
`)}var Fu,Ua,$a=I(()=>{"use strict";be();wn();qt();Ss();Fu=Sn.object({projectPath:Sn.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:Sn.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:Sn.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical install fits in 2 round-trips instead of 5-6. Default 20. Set 0 to disable."),sessionId:Sn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),Ua={name:"mist_install",description:"Install a Mistflow project's npm dependencies with the fire-and-poll pattern. First call with { projectPath } starts the install and returns a jobId. Subsequent calls with { jobId } poll for progress (status: 'running' | 'complete' | 'failed'). Re-call while status is 'running' \u2014 each response is <1s so there is no 60s timeout risk.",inputSchema:Fu,handler:async(t,e)=>{let r=t;if(r.jobId){let l=await ht(r.jobId);if(!l)return p(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No install job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let c=r.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let h=l.elapsed,d=e?qe(e.server,e.progressToken,()=>`Install running (${h}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let v=await Kt(r.jobId,{timeoutMs:c*1e3,onPoll:W=>{h=W.elapsed}});v&&(l=v)}finally{d.stop()}}if(l.status==="running"||l.status==="starting")return p(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:$u(l.logTail),nextAction:"Install still running after long-poll window. Call mist_install again with the same jobId to continue waiting."}));if(l.status==="complete"){let h=await pa(l.cwd),d=!1;h&&h.freshlyStarted?(d=await aa(h.state.url,15e3),d&&ua(h.state.url)):h&&(d=!0);let v=h?d?` PREVIEW: Live dev server at ${h.state.url} (browser opened). TELL THE USER: "Your app is rendering at ${h.state.url} \u2014 it'll refresh live as it's built."`:` PREVIEW: Dev server starting at ${h.state.url} (still compiling). TELL THE USER: "Open ${h.state.url} in your browser in ~30s \u2014 your app will appear there and refresh live as it's built."`:"";return p(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,...h?{previewUrl:h.state.url,previewReady:d}:{},nextAction:`Dependencies installed.${v} Run mist_implement next to start executing plan steps.`}))}let u=Ct(l.id);return p(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:u,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${u.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let n=Mu(r.projectPath);if(!Lu(Uu(n,"package.json")))return p(`No package.json at ${n}. Confirm the path and that mist_init has scaffolded the project.`,!0);let s=`npm install && (${`npx --yes shadcn@latest add -y -o ${["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"].join(" ")}`} || echo 'shadcn add failed \u2014 implement will retry lazily')`,a=await mt({type:"install",cmd:"sh",args:["-c",s],cwd:n,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return p(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:n,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+a.id+"' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s."}))}}});import{z as Jt}from"zod";import{resolve as qu,join as ze}from"path";import{existsSync as Ge,readFileSync as Fa,statSync as Bu,readdirSync as zu}from"fs";function Hu(t){let e=0,r=0,n=[t];for(;n.length>0&&r<1e4;){let i=n.pop();r++;let o;try{o=zu(i)}catch{continue}for(let s of o){let a=ze(i,s),l;try{l=Bu(a)}catch{continue}l.isDirectory()?n.push(a):l.isFile()&&(e+=l.size)}}return e}function Wu(t){if(!(Ge(ze(t,"open-next.config.ts"))||Ge(ze(t,"open-next.config.js"))))return null;let r=ze(t,".open-next","worker.js");if(!Ge(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker entrypoint. Common causes: (1) open-next.config.ts is misconfigured, (2) a client component imports a Node-only API (fs, path, crypto node:* imports in 'use client' files), (3) the adapter crashed silently mid-build. Check the logTail above for "error"/"failed" messages, fix the offending file, and re-run mist_build.`;let n=ze(t,".open-next","server-functions","default");if(!Ge(n))return'Build exited 0 and .open-next/worker.js exists, but .open-next/server-functions/default/ is missing. The OpenNext adapter produced an orchestrator with no server bundle to import. Check the logTail above for "error"/"failed" messages near "Building server function: default..." and re-run mist_build.';let i=Hu(n);return i<qa?`Build exited 0 but the server-functions bundle is only ${i} bytes (expected at least ${qa}). A healthy Next.js + OpenNext bundle is 5-50MB. This size suggests the adapter failed to bundle most of the app. Check the logTail for bundling errors and re-run mist_build.`:null}function Vu(t){let e=ze(or(),t,"stdout.log"),r=ze(or(),t,"stderr.log"),n="";try{Ge(e)&&(n+=Fa(e,"utf-8"))}catch{}try{Ge(r)&&(n+=`
|
|
5334
|
+
`+Fa(r,"utf-8"))}catch{}return n}function Ku(t,e=15){let r=t.split(`
|
|
5705
5335
|
`).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
|
|
5706
|
-
`)}function rm(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let n of t.matchAll(e)){let i=n[1];if(i.startsWith(".")||i.startsWith("@/")||i.startsWith("~/"))continue;let o=i.startsWith("@")?i.split("/").slice(0,2).join("/"):i.split("/")[0];o&&r.add(o)}return[...r]}function om(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${Sn()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var Ja,em,Ya,Qa=T(()=>{"use strict";fe();bn();lo();Ft();pt();No();Ja=100*1024;em=Jt.object({projectPath:Jt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Jt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Jt.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls."),waitSeconds:Jt.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical build fits in 2 round-trips instead of 6-8. Default 20. Set 0 to disable."),sessionId:Jt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});Ya={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:em,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await ht(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 I=c.elapsed,B=e?Fe(e.server,e.progressToken,()=>`Build running (${I}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let U=await Kt(r.jobId,{timeoutMs:h*1e3,onPoll:M=>{I=M.elapsed}});U&&(c=U)}finally{B.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:nm(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 I=Zu(c.cwd);if(I){let B=_t(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:B,error:I,nextAction:I+` Full build log: ${B.stdout} and ${B.stderr}.`}),!0)}return await me(r.sessionId,"BUILDING",["IMPLEMENTING"]),await me(r.sessionId,"DEPLOYING",["BUILDING"]),d(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let p=tm(c.id),u=Jn(p),w=rm(p),O=om(p),k=_t(c.id),b=` Full log: ${k.stdout} and ${k.stderr}.`,y=w.length>0?`Build failed with missing modules: ${w.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${b}`:O?`${O}${b}`:u.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:u,missingModules:w,logTail:c.logTail,logPaths:k,nextAction:y}),!0)}let n=Ju(r.projectPath);if(!Ve(Be(n,"package.json")))return d(`No package.json at ${n}. Run mist_init first.`,!0);if(!Ve(Be(n,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let i,o,s,a=Ve(Be(n,"open-next.config.ts"))||Ve(Be(n,"open-next.config.js"));if(r.script)i="npm",o=["run",r.script],s=r.script;else if(a){if(!cr())return d(Sn(),!0);i="npx",o=["-y","@opennextjs/cloudflare","build"],s="@opennextjs/cloudflare build"}else i="npm",o=["run","build"],s="build";let l=await mt({type:"build",cmd:i,args:o,cwd:n});return d(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:s,nextAction:`Build started. Call mist_build again with { jobId: '${l.id}' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}}});import{existsSync as sm,readdirSync as im}from"fs";import{join as Xa}from"path";import{pathToFileURL as am}from"url";async function lm(t){let e=Xa(t,".mistflow","acceptance"),r=new Map;if(!sm(e))return r;let n=im(e).filter(i=>i.endsWith(".spec.ts")||i.endsWith(".spec.js")||i.endsWith(".spec.mjs"));for(let i of n){let o=i.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!o)continue;let s=Xa(e,i);try{let a=await import(am(s).href),l=a.default??a.run;typeof l=="function"?r.set(o,l):console.error(`Probe ${i} doesn't export a default function (or named 'run'). Skipping.`)}catch(a){console.error(`Failed to load probe ${i}:`,a instanceof Error?a.message:a)}}return r}async function Za(t,e){let{sessionId:r,projectPath:n,deployUrl:i,seedCredentials:o}=e,a=(await on(r)).criteria,l=await lm(n),c=[];for(let h of a){let p=l.get(h.id);if(!p){c.push({criterion_id:h.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${h.id}.spec.ts`}});continue}try{await t.goto(i,{waitUntil:"domcontentloaded"});let u=await p(t,{url:i,criterion:h,seedCredentials:o});c.push({criterion_id:h.id,status:u.pass?"pass":"fail",evidence:{...u.detail?{detail:u.detail}:{},...u.screenshot?{screenshot:u.screenshot}:{}}})}catch(u){c.push({criterion_id:h.id,status:"fail",evidence:{error:u instanceof Error?u.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var el=T(()=>{"use strict";ke()});import{existsSync as cm,readFileSync as dm}from"fs";import{join as pm}from"path";import{z as Yt}from"zod";function ol(t){let e=pm(t,"mistflow.json");if(!cm(e))return null;try{return JSON.parse(dm(e,"utf-8"))}catch{return null}}async function tl(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 mm(t,e,r){try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),i=await n.text(),o;try{o=JSON.parse(i)}catch{}return{status:n.status,json:o}}catch{return{status:0}}}async function nl(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function ft(t,e,r){let n=[],i=o=>{o.type()==="error"&&n.push(o.text())};t.on("console",i);try{let o=await r(),s=await nl(t);return{name:e,status:o.pass?"pass":"fail",detail:o.detail,fix:o.fix,screenshot:s,consoleErrors:n.length>0?n:void 0}}catch(o){let s=await nl(t);return{name:e,status:"fail",detail:`Unexpected error: ${o instanceof Error?o.message:String(o)}`,screenshot:s,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",i)}}async function hm(t){if(!t.sessionId)return d("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=ol(e),n=t.url;if(!n&&t.deploymentId)try{let a=await at(t.deploymentId);a.url&&(n=a.url)}catch(a){console.error(`[acceptance] Could not resolve URL from deploymentId ${t.deploymentId}:`,a instanceof Error?a.message:String(a))}if(n||(n=r?.deploy?.url),!n)return d("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa action='acceptance'.",!0);let i;if(t.deploymentId)try{let l=await qn(t.deploymentId);l?.adminEmail&&l?.adminPassword&&(i={email:l.adminEmail,password:l.adminPassword})}catch(a){console.error("[acceptance] getSeedInfo failed (continuing without):",a instanceof Error?a.message:String(a))}let o,s;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(At(),nn)),l=await a();o=l.context,s=l.page}catch(a){return d(`Playwright not available locally \u2014 install it with \`npx playwright install chromium\`. Detail: ${a instanceof Error?a.message:String(a)}`,!0)}try{let{criteria:a,results:l}=await Za(s,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:i});try{await Xr(t.sessionId,l)}catch(u){console.error("[acceptance] submitAcceptanceResults failed:",u instanceof Error?u.message:String(u))}let c=l.filter(u=>u.status==="pass").length,h=l.filter(u=>u.status==="fail").length,p=l.filter(u=>u.status==="skipped").length;return d(JSON.stringify({status:h===0?"pass":"fail",url:n,totals:{passed:c,failed:h,skipped:p,total:a.length},results:l.map(u=>({criterion_id:u.criterion_id,status:u.status,detail:u.evidence&&typeof u.evidence=="object"&&"detail"in u.evidence?u.evidence.detail:u.evidence&&typeof u.evidence=="object"&&"reason"in u.evidence?u.evidence.reason:void 0})),nextAction:h===0?"All required acceptance criteria passed. The app is shippable.":"Some criteria failed. Read the per-criterion detail, fix the underlying code, then re-run mist_qa action='acceptance'."}),h>0)}finally{if(o)try{await o.close()}catch{}}}async function gm(t){let e=t.projectPath??process.cwd(),r=ol(e),n=t.url;if(!n&&t.deploymentId)try{let I=await at(t.deploymentId);I.url&&(n=I.url)}catch(I){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,I instanceof Error?I.message:String(I))}if(n||(n=r?.deploy?.url),!n)return d("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);n.startsWith("http")||(n=`https://${n}`);let i=r?.projectId,o=[],s=await tl(`${n}/api/health`);if(s.status!==200)return o.push({name:"Health endpoint",status:"fail",detail:`Returns ${s.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),dr(n,o);o.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await tl(`${n}/api/auth/ok`);if(a.status!==200)return o.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${a.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),dr(n,o);o.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",h="QaTemp1!",p="single",u="user",w=[];async function O(I,B,U,M){let de=await mm(`${n}/api/admin/seed`,{token:M,email:B,password:h,role:U});if(de.status!==200||!de.json)return console.error(`[qa] Seed (${I}) returned ${de.status}`),null;let K=de.json.sessionToken;if(!K)return null;let D=de.json.seeded===!0;return{role:I,email:B,sessionToken:K,password:D?h:void 0}}if(i){let I=await qn(i);if(I){if(p=I.authMode??"single",u=I.defaultRole??"user",console.error(`[qa] auth_mode=${p}, default_role=${u}`),p!=="none"){let U=await O("actor",l,p==="multi"?"admin":u,I.seedToken);if(U&&w.push(U),p==="multi"){let M=await O("user",c,u,I.seedToken);M?w.push(M):o.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${u}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),p="none"}if(p!=="none"&&w.length===0)return o.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy injects ADMIN_SEED_TOKEN and stores it on the backend; the scaffold's /api/admin/seed route accepts { token, email, password, role } and creates synthetic QA users with the requested role."}),dr(n,o);let k,b,y;try{let{getIsolatedContext:I}=await Promise.resolve().then(()=>(At(),nn)),B=await I();k=B.context,y=B.page}catch(I){let B=I instanceof Error?I.message:String(I);return d(JSON.stringify({status:"cannot_verify",url:n,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:B,httpChecks:o.map(({screenshot:U,...M})=>M),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${n}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${n}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_qa again for full verification."].join(`
|
|
5707
|
-
`)}),!1)}try{let
|
|
5708
|
-
${
|
|
5709
|
-
`)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});o.push(
|
|
5710
|
-
${
|
|
5711
|
-
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});o.push(
|
|
5336
|
+
`)}function Ju(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let n of t.matchAll(e)){let i=n[1];if(i.startsWith(".")||i.startsWith("@/")||i.startsWith("~/"))continue;let o=i.startsWith("@")?i.split("/").slice(0,2).join("/"):i.split("/")[0];o&&r.add(o)}return[...r]}function Yu(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${Pt()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var qa,Gu,Ba,za=I(()=>{"use strict";be();wn();os();qt();Zn();qa=100*1024;Gu=Jt.object({projectPath:Jt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Jt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Jt.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls."),waitSeconds:Jt.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical build fits in 2 round-trips instead of 6-8. Default 20. Set 0 to disable."),sessionId:Jt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});Ba={name:"mist_build",description:"Run a Mistflow project's production build with the fire-and-poll pattern. First call with { projectPath } starts `npm run build` and returns a jobId. Subsequent calls with { jobId } poll status. On failure, the response surfaces structured errors (from parseBuildErrors) and any missingModules[] \u2014 chain into mist_install with those modules, then mist_build again, without asking the user.",inputSchema:Gu,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await ht(r.jobId);if(!c)return p(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let u=r.waitSeconds??20;if(u>0&&(c.status==="running"||c.status==="starting")){let A=c.elapsed,z=e?qe(e.server,e.progressToken,()=>`Build running (${A}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let H=await Kt(r.jobId,{timeoutMs:u*1e3,onPoll:ne=>{A=ne.elapsed}});H&&(c=H)}finally{z.stop()}}if(c.status==="running"||c.status==="starting")return p(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Ku(c.logTail),nextAction:"Build still running after long-poll window. Call mist_build again with the same jobId to continue waiting."}));if(c.status==="complete"){let A=Wu(c.cwd);if(A){let z=Ct(c.id);return p(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:z,error:A,nextAction:A+` Full build log: ${z.stdout} and ${z.stderr}.`}),!0)}return p(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let h=Vu(c.id),d=Jn(h),v=Ju(h),W=Yu(h),_=Ct(c.id),k=` Full log: ${_.stdout} and ${_.stderr}.`,y=v.length>0?`Build failed with missing modules: ${v.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${k}`:W?`${W}${k}`:d.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${k}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${k}`;return p(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:d,missingModules:v,logTail:c.logTail,logPaths:_,nextAction:y}),!0)}let n=qu(r.projectPath);if(!Ge(ze(n,"package.json")))return p(`No package.json at ${n}. Run mist_init first.`,!0);if(!Ge(ze(n,"node_modules")))return p(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let i,o,s,a=Ge(ze(n,"open-next.config.ts"))||Ge(ze(n,"open-next.config.js"));if(r.script)i="npm",o=["run",r.script],s=r.script;else if(a){if(!Bt())return p(Pt(),!0);i="npx",o=["-y","@opennextjs/cloudflare","build"],s="@opennextjs/cloudflare build"}else i="npm",o=["run","build"],s="build";let l=await mt({type:"build",cmd:i,args:o,cwd:n});return p(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:s,nextAction:`Build started. Call mist_build again with { jobId: '${l.id}' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}}});import{existsSync as Qu,readdirSync as Xu}from"fs";import{join as Ha}from"path";import{pathToFileURL as Zu}from"url";async function em(t){let e=Ha(t,".mistflow","acceptance"),r=new Map;if(!Qu(e))return r;let n=Xu(e).filter(i=>i.endsWith(".spec.ts")||i.endsWith(".spec.js")||i.endsWith(".spec.mjs"));for(let i of n){let o=i.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!o)continue;let s=Ha(e,i);try{let a=await import(Zu(s).href),l=a.default??a.run;typeof l=="function"?r.set(o,l):console.error(`Probe ${i} doesn't export a default function (or named 'run'). Skipping.`)}catch(a){console.error(`Failed to load probe ${i}:`,a instanceof Error?a.message:a)}}return r}async function Wa(t,e){let{sessionId:r,projectPath:n,deployUrl:i,seedCredentials:o}=e,a=(await sn(r)).criteria,l=await em(n),c=[];for(let u of a){let h=l.get(u.id);if(!h){c.push({criterion_id:u.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${u.id}.spec.ts`}});continue}try{await t.goto(i,{waitUntil:"domcontentloaded"});let d=await h(t,{url:i,criterion:u,seedCredentials:o});c.push({criterion_id:u.id,status:d.pass?"pass":"fail",evidence:{...d.detail?{detail:d.detail}:{},...d.screenshot?{screenshot:d.screenshot}:{}}})}catch(d){c.push({criterion_id:u.id,status:"fail",evidence:{error:d instanceof Error?d.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var Ga=I(()=>{"use strict";_e()});import{existsSync as tm,readFileSync as nm}from"fs";import{join as rm}from"path";import{z as Yt}from"zod";function Ya(t){let e=rm(t,"mistflow.json");if(!tm(e))return null;try{return JSON.parse(nm(e,"utf-8"))}catch{return null}}async function Va(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await e.text();return{status:e.status,body:r}}catch(e){return{status:0,body:String(e)}}}async function om(t,e,r){try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),i=await n.text(),o;try{o=JSON.parse(i)}catch{}return{status:n.status,json:o}}catch{return{status:0}}}async function Ka(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function yt(t,e,r){let n=[],i=o=>{o.type()==="error"&&n.push(o.text())};t.on("console",i);try{let o=await r(),s=await Ka(t);return{name:e,status:o.pass?"pass":"fail",detail:o.detail,fix:o.fix,screenshot:s,consoleErrors:n.length>0?n:void 0}}catch(o){let s=await Ka(t);return{name:e,status:"fail",detail:`Unexpected error: ${o instanceof Error?o.message:String(o)}`,screenshot:s,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",i)}}async function im(t){if(!t.sessionId)return p("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=Ya(e),n=t.url;if(!n&&t.deploymentId)try{let a=await at(t.deploymentId);a.url&&(n=a.url)}catch(a){console.error(`[acceptance] Could not resolve URL from deploymentId ${t.deploymentId}:`,a instanceof Error?a.message:String(a))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa action='acceptance'.",!0);let i;if(t.deploymentId)try{let l=await Fn(t.deploymentId);l?.adminEmail&&l?.adminPassword&&(i={email:l.adminEmail,password:l.adminPassword})}catch(a){console.error("[acceptance] getSeedInfo failed (continuing without):",a instanceof Error?a.message:String(a))}let o,s;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(Et(),nn)),l=await a();o=l.context,s=l.page}catch(a){return p(`Playwright not available locally \u2014 install it with \`npx playwright install chromium\`. Detail: ${a instanceof Error?a.message:String(a)}`,!0)}try{let{criteria:a,results:l}=await Wa(s,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:i});try{await Jr(t.sessionId,l)}catch(d){console.error("[acceptance] submitAcceptanceResults failed:",d instanceof Error?d.message:String(d))}let c=l.filter(d=>d.status==="pass").length,u=l.filter(d=>d.status==="fail").length,h=l.filter(d=>d.status==="skipped").length;return p(JSON.stringify({status:u===0?"pass":"fail",url:n,totals:{passed:c,failed:u,skipped:h,total:a.length},results:l.map(d=>({criterion_id:d.criterion_id,status:d.status,detail:d.evidence&&typeof d.evidence=="object"&&"detail"in d.evidence?d.evidence.detail:d.evidence&&typeof d.evidence=="object"&&"reason"in d.evidence?d.evidence.reason:void 0})),nextAction:u===0?"All required acceptance criteria passed. The app is shippable.":"Some criteria failed. Read the per-criterion detail, fix the underlying code, then re-run mist_qa action='acceptance'."}),u>0)}finally{if(o)try{await o.close()}catch{}}}async function am(t){let e=t.projectPath??process.cwd(),r=Ya(e),n=t.url;if(!n&&t.deploymentId)try{let A=await at(t.deploymentId);A.url&&(n=A.url)}catch(A){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,A instanceof Error?A.message:String(A))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);n.startsWith("http")||(n=`https://${n}`);let i=r?.projectId,o=[],s=await Va(`${n}/api/health`);if(s.status!==200)return o.push({name:"Health endpoint",status:"fail",detail:`Returns ${s.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),pr(n,o);o.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Va(`${n}/api/auth/ok`);if(a.status!==200)return o.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${a.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),pr(n,o);o.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",u="QaTemp1!",h="single",d="user",v=[];async function W(A,z,H,ne){let ee=await om(`${n}/api/admin/seed`,{token:ne,email:z,password:u,role:H});if(ee.status!==200||!ee.json)return console.error(`[qa] Seed (${A}) returned ${ee.status}`),null;let Q=ee.json.sessionToken;if(!Q)return null;let q=ee.json.seeded===!0;return{role:A,email:z,sessionToken:Q,password:q?u:void 0}}if(i){let A=await Fn(i);if(A){if(h=A.authMode??"single",d=A.defaultRole??"user",console.error(`[qa] auth_mode=${h}, default_role=${d}`),h!=="none"){let H=await W("actor",l,h==="multi"?"admin":d,A.seedToken);if(H&&v.push(H),h==="multi"){let ne=await W("user",c,d,A.seedToken);ne?v.push(ne):o.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${d}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),h="none"}if(h!=="none"&&v.length===0)return o.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy injects ADMIN_SEED_TOKEN and stores it on the backend; the scaffold's /api/admin/seed route accepts { token, email, password, role } and creates synthetic QA users with the requested role."}),pr(n,o);let _,k,y;try{let{getIsolatedContext:A}=await Promise.resolve().then(()=>(Et(),nn)),z=await A();_=z.context,y=z.page}catch(A){let z=A instanceof Error?A.message:String(A);return p(JSON.stringify({status:"cannot_verify",url:n,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:z,httpChecks:o.map(({screenshot:H,...ne})=>ne),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${n}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${n}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_qa again for full verification."].join(`
|
|
5337
|
+
`)}),!1)}try{let A=await yt(y,"Landing page",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await y.waitForLoadState("networkidle").catch(()=>{});let Q=await y.evaluate(()=>{let P=document.body;if(!P)return"";let se=document.createTreeWalker(P,NodeFilter.SHOW_TEXT),B="",b;for(;b=se.nextNode();){let $=b.parentElement;if($){let V=window.getComputedStyle($);V.display!=="none"&&V.visibility!=="hidden"&&parseFloat(V.opacity)>0&&(B+=b.textContent?.trim()+" ")}}return B.trim()});if(Q.length<50)return{pass:!1,detail:`Landing page appears blank (${Q.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let q=y.url();return q.includes("/login")||q.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${Q.length} chars)`}});o.push(A),h==="none"&&o.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let z=v[0],H=(Q,q)=>v.length>1&&Q?`${q} (${Q.role})`:q,ne=!1;if(z?.password){let Q=await yt(y,H(z,"Login"),async()=>{await y.goto(`${n}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let q=y.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),P=y.locator('input[type="password"], input[name="password"]');try{await q.first().waitFor({state:"visible",timeout:1e4})}catch{return{pass:!1,detail:"Login page has no visible email input field",fix:"Check app/(auth)/login/page.tsx renders a login form with email and password inputs."}}await q.first().fill(z.email),await P.first().fill(z.password),await y.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await y.waitForURL(B=>!B.pathname.includes("/login"),{timeout:1e4})}catch{let B=await y.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:B?`Login failed: ${B}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified QA accounts."}}return ne=!0,{pass:!0,detail:`Logged in, redirected to ${y.url()}`}});o.push(Q)}else z&&o.push({name:H(z,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!ne&&z){let Q=new URL(n).hostname,q=n.startsWith("https");await _.addCookies([{name:q?"__Secure-better-auth.session_token":"better-auth.session_token",value:z.sessionToken,domain:Q,path:"/",httpOnly:!0,secure:q,sameSite:"Lax"}]),console.error(`[qa] Injected ${z.role} cookie for primary walk`)}if(z){let Q=await yt(y,H(z,"Dashboard"),async()=>{y.url().includes("/dashboard")||(await y.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}),new URL(y.url()).pathname==="/"&&(await y.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{})));let se=await y.content();return se.length<1e3?{pass:!1,detail:`Dashboard page is very small (${se.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await y.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled null/undefined or missing database tables."}:{pass:!0,detail:`Loads (${se.length} bytes)`}});o.push(Q);let q=await y.evaluate(()=>{let se=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(b=>{let $=b.getAttribute("href");$&&$.startsWith("/")&&!$.startsWith("/api")&&!$.includes("[")&&$!=="/dashboard"&&$!=="/"&&!$.includes("/login")&&!$.includes("/sign")&&se.push($)}),[...new Set(se)]});if(q.length>0){let se=0,B=[];for(let b of q.slice(0,8)){let $=await yt(y,H(z,`Page: ${b}`),async()=>{await y.goto(`${n}${b}`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let V=await y.title(),M=await y.content();return V.toLowerCase().includes("500")||V.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 server error",fix:"Server component crashed. Common causes: 1) Database tables missing. 2) Wrong ORM dialect (pgTable vs sqliteTable). 3) Unhandled null/undefined in server component."}:V.toLowerCase().includes("404")||V.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${b} not found. Create the page or remove the nav link.`}:await y.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:M.length<500?{pass:!1,detail:`Page is very small (${M.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});$.status==="fail"&&(se++,B.push(b)),o.push($)}}let P=await yt(y,"Design quality",async()=>{let se=y.url().includes("/dashboard")?y.url():`${n}/dashboard`;y.url().includes("/dashboard")||(await y.goto(se,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}));let B=await y.evaluate(()=>{let b=[],$=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),V=new Set;$.forEach(X=>{V.add(window.getComputedStyle(X).fontSize)}),$.length>=3&&V.size<2&&b.push("TYPOGRAPHY: All headings appear the same size. Create clear hierarchy with 3+ distinct sizes using a modular scale (1.25-1.5x ratio).");let M=Array.from($).map(X=>parseInt(X.tagName.charAt(1),10));for(let X=1;X<M.length;X++)if(M[X]-M[X-1]>1){b.push(`TYPOGRAPHY: Heading level skipped (h${M[X-1]} -> h${M[X]}). Use sequential heading levels for accessibility.`);break}let pe=document.querySelectorAll("*"),te=!1,R=!1;pe.forEach(X=>{let fe=window.getComputedStyle(X);fe.backgroundColor==="rgb(0, 0, 0)"&&X.clientHeight>100&&X.clientWidth>200&&(te=!0);let je=fe.backgroundColor,rt=fe.color;if(je&&!je.includes("0, 0, 0")&&!je.includes("255, 255, 255")&&je!=="rgba(0, 0, 0, 0)"&&je!=="transparent"&&rt.match(/rgb\((\d+), (\d+), (\d+)\)/)){let wt=rt.match(/rgb\((\d+), (\d+), (\d+)\)/);if(wt){let[st,We,m]=[parseInt(wt[1]),parseInt(wt[2]),parseInt(wt[3])],g=Math.abs(st-We)<10&&Math.abs(We-m)<10&&st>80&&st<180,w=je.match(/rgb\((\d+), (\d+), (\d+)\)/);if(g&&w){let[T,O,F]=[parseInt(w[1]),parseInt(w[2]),parseInt(w[3])];!(Math.abs(T-O)<15&&Math.abs(O-F)<15)&&X.textContent&&X.textContent.trim().length>0&&(R=!0)}}}}),te&&b.push("COLOR: Pure black (#000) background detected on a large element. Use a tinted dark color instead (e.g. oklch(15% 0.01 hue) or a deep navy/charcoal)."),R&&b.push("COLOR: Gray text on a colored background detected. Gray looks washed out on color. Use a darker shade of the background color or white instead.");let ge=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),K=!1;ge.forEach(X=>{X.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(K=!0)}),K&&b.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let ae=document.querySelectorAll("p, li, span, div"),Oe=0,ke=0;ae.forEach(X=>{X.textContent&&X.textContent.trim().length>20&&X.clientHeight>0&&(ke++,window.getComputedStyle(X).textAlign==="center"&&Oe++)}),ke>5&&Oe/ke>.7&&b.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let we=new Set;pe.forEach(X=>{let fe=window.getComputedStyle(X);fe.gap&&fe.gap!=="normal"&&fe.gap!=="0px"&&we.add(fe.gap)}),we.size===1&&pe.length>20&&b.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let Le=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(X=>{X.querySelectorAll("tbody tr").length===0&&(X.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||b.push("UX: Empty table with no empty state. Add a helpful message explaining what will appear here and a CTA to create the first item."))});let Ve=document.querySelectorAll("style"),He=!1;Ve.forEach(X=>{let fe=X.textContent||"";(fe.includes("bounce")||fe.includes("elastic")||fe.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(He=!0)}),He&&b.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let nt=document.querySelectorAll("button, a, input, select, [role='button']"),Ce=0;return nt.forEach(X=>{let fe=X.getBoundingClientRect();fe.width>0&&fe.height>0&&(fe.width<32||fe.height<32)&&Ce++}),Ce>3&&b.push(`ACCESSIBILITY: ${Ce} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),b});return B.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${B.length} design quality issue(s) found:
|
|
5338
|
+
${B.map((b,$)=>`${$+1}. ${b}`).join(`
|
|
5339
|
+
`)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});o.push(P)}if(o.find(Q=>Q.name==="Landing page"&&Q.status==="pass")){let Q=await yt(y,"Landing design quality",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let q=await y.evaluate(()=>{let P=[];document.querySelectorAll("*").forEach($=>{let V=window.getComputedStyle($);(V.getPropertyValue("-webkit-background-clip")||V.getPropertyValue("background-clip"))==="text"&&$.textContent&&$.textContent.trim().length>0&&P.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let B=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(B){let $=(B.textContent||"").toLowerCase(),V=["transform your","unlock the power","revolutionize your","take your .* to the next level","the future of","welcome to","get started today","join thousands","powerful analytics","seamless integration","lightning fast"];for(let M of V)if($.match(new RegExp(M))){P.push(`COPY: Generic hero text detected ('${M}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach($=>{let M=window.getComputedStyle($).gridTemplateColumns;if(M){let pe=M.split(" ").filter(R=>R!=="").length,te=$.children;if(pe===3&&te.length===3){let R=Array.from(te).map(ae=>ae.offsetHeight),ge=R.every(ae=>Math.abs(ae-R[0])<5),K=Array.from(te).every(ae=>{let Oe=ae.querySelectorAll("svg"),ke=ae.querySelectorAll("h2, h3, h4"),we=ae.querySelectorAll("p");return Oe.length>=1&&ke.length>=1&&we.length>=1});ge&&K&&P.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),P});return q.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${q.length} landing design issue(s):
|
|
5340
|
+
${q.map((P,se)=>`${se+1}. ${P}`).join(`
|
|
5341
|
+
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});o.push(Q)}let ee=v[1];if(ee){let{getIsolatedContext:Q}=await Promise.resolve().then(()=>(Et(),nn)),q=await Q();k=q.context;let P=q.page,se=new URL(n).hostname,B=n.startsWith("https");await k.addCookies([{name:B?"__Secure-better-auth.session_token":"better-auth.session_token",value:ee.sessionToken,domain:se,path:"/",httpOnly:!0,secure:B,sameSite:"Lax"}]),console.error(`[qa] Injected ${ee.role} cookie for secondary walk`);let b=await yt(P,H(ee,"Dashboard"),async()=>{await P.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await P.waitForLoadState("networkidle").catch(()=>{}),new URL(P.url()).pathname==="/"&&(await P.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await P.waitForLoadState("networkidle").catch(()=>{}));let V=await P.content();return V.length<1e3?{pass:!1,detail:`Dashboard is very small (${V.length} bytes) for the default-role user`,fix:"The default-role user dashboard crashed or rendered empty. Check that role-gated server components handle non-admin roles without throwing."}:await P.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary for the default-role user",fix:"A server component crashed under the non-admin role. Likely a role check that throws instead of redirecting."}:{pass:!0,detail:`Loads (${V.length} bytes)`}});o.push(b);let $=await P.evaluate(()=>{let V=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(M=>{let pe=M.getAttribute("href");pe&&pe.startsWith("/")&&!pe.startsWith("/api")&&!pe.includes("[")&&pe!=="/dashboard"&&pe!=="/"&&!pe.includes("/login")&&!pe.includes("/sign")&&V.push(pe)}),[...new Set(V)]});for(let V of $.slice(0,8)){let M=await yt(P,H(ee,`Page: ${V}`),async()=>{await P.goto(`${n}${V}`,{waitUntil:"domcontentloaded",timeout:15e3}),await P.waitForLoadState("networkidle").catch(()=>{});let pe=await P.title(),te=await P.content();return pe.toLowerCase().includes("500")||pe.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 for the default-role user",fix:"Server component crashed under the non-admin role. Check role gates use redirect() not throw."}:pe.toLowerCase().includes("404")||pe.toLowerCase().includes("not found")?{pass:!0,detail:"404 (likely admin-only \u2014 acceptable)"}:await P.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Error boundary on page for default-role user",fix:"Role-gated content crashed. Use a graceful fallback."}:te.length<500?{pass:!1,detail:`Page very small (${te.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});o.push(M)}}}finally{_&&await _.close().catch(()=>{}),k&&await k.close().catch(()=>{})}if(t.deploymentId){let A=o.filter(ne=>ne.status==="fail"),z=o.filter(ne=>ne.status==="pass"),H=Date.now();await Er(t.deploymentId,{checks:o.map(({screenshot:ne,...ee})=>ee),overall:A.length===0?"pass":"fail",passed:z.length,failed:A.length,duration_ms:Date.now()-H}).catch(()=>{})}return pr(n,o)}function pr(t,e){let r=e.filter(o=>o.status==="fail"),n=e.filter(o=>o.status==="pass"),i=[];if(r.length===0)i.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${e.length} checks OK. The app is working correctly.`,url:t,checks:e.map(({screenshot:o,...s})=>s)})});else{let o=r.map((s,a)=>`${a+1}. **${s.name}**: ${s.detail}
|
|
5712
5342
|
Fix: ${s.fix}`).join(`
|
|
5713
5343
|
|
|
5714
5344
|
`);i.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${r.length} issue(s) on the live app. Fix them and redeploy.`,url:t,passed:n.length,failed:r.length,checks:e.map(({screenshot:s,...a})=>a),fixInstructions:`The deployed app at ${t} has ${r.length} issue(s):
|
|
5715
5345
|
|
|
5716
5346
|
${o}
|
|
5717
5347
|
|
|
5718
|
-
Fix these issues in the source code, then call mist_deploy with action='deploy'${t.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let o of e)o.screenshot&&i.push({type:"image",data:o.screenshot,mimeType:"image/png"});return{content:i}}var
|
|
5719
|
-
${i.stderr.slice(-500)}`:""))}let o=0;try{o=
|
|
5348
|
+
Fix these issues in the source code, then call mist_deploy with action='deploy'${t.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let o of e)o.screenshot&&i.push({type:"image",data:o.screenshot,mimeType:"image/png"});return{content:i}}var sm,Ja,Qa=I(()=>{"use strict";be();_e();Ga();sm=Yt.object({projectPath:Yt.string().optional().describe("Absolute path to the Mistflow project. Defaults to the current working directory. Used to read mistflow.json for the deploy URL + projectId."),url:Yt.string().optional().describe("Override the deploy URL to QA. Useful for previews or when mistflow.json doesn't yet have the URL recorded. Defaults to mistflow.json's deploy.url."),deploymentId:Yt.string().optional().describe("Deployment ID to associate QA results with. When set, results are uploaded to the backend and surfaced on the dashboard deployment card."),sessionId:Yt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),action:Yt.enum(["full","acceptance"]).default("full").describe("'full' (default) runs the standard post-deploy QA suite: HTTP pre-flight, landing render, login, sidebar pages, design audits. 'acceptance' runs only the per-criterion Playwright probes from .mistflow/acceptance/<criterion-id>.spec.ts against the deploy URL and uploads pass/fail results to the backend. Requires sessionId.")}),Ja={name:"mist_qa",description:"Post-deploy QA: drives Playwright in-process against the live deploy URL. Checks health + auth endpoints, logs in with a seeded admin account, walks the dashboard and sidebar pages, and runs design-quality audits (typography, color, layout, slop patterns). Returns pass/fail + screenshots inline. Call ONCE after mist_deploy completes. Do NOT surface the deploy URL to the user until mist_qa returns status: 'pass'.",inputSchema:sm,handler:async t=>{let e=t;if(e.action==="acceptance"){let n=await im(e);return n.isError,n}let r=await am(e);return r.isError,r}}});import{existsSync as ur,readdirSync as lm,statSync as Xa,unlinkSync as Za}from"fs";import{join as At}from"path";import{execFile as cm}from"child_process";function dm(t,e){let r=0;for(let n of e){let i=At(t,n);if(ur(i))try{let o=Xa(i);if(o.isFile())r++;else if(o.isDirectory()){let s=[i];for(;s.length;){let a=s.pop(),l=lm(a,{withFileTypes:!0});for(let c of l){let u=At(a,c.name);c.isDirectory()?s.push(u):r++}}}}catch{}}return r}function el(t,e,r){return new Promise(n=>{cm("tar",t,{cwd:e,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(i,o,s)=>{n({success:!i,stderr:s?.toString()??""})})})}async function tl(t){let e=At(t,".open-next-build.tar.gz"),r=[".open-next"];ur(At(t,"db"))&&r.push("db"),ur(At(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),ur(At(t,"package.json"))&&r.push("package.json");let n=dm(t,r),i=await el(["-czf",e,"-C",t,...r],t,12e4);if(!i.success){try{Za(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(i.stderr?`
|
|
5349
|
+
${i.stderr.slice(-500)}`:""))}let o=0;try{o=Xa(e).size}catch{}return{path:e,sizeBytes:o,fileCount:n}}async function nl(t){let e=At(t,".mistflow-source.tar.gz");return(await el(["-czf",e,"-C",t,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],t,12e4)).success?e:null}function Cs(t){if(t)try{Za(t)}catch{}}function rl(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function sl(t){switch(t){case"pending":return"Provisioning...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";case"live":return"Live!";case"failed":return"Failed";default:return`Status: ${t}`}}var ol=I(()=>{"use strict"});import{z as tt}from"zod";import{resolve as pm,join as mr}from"path";import{existsSync as hr}from"fs";function il(t){return hr(mr(t,".open-next"))}function mm(t){return it(t)?.deploy?.strategy==="staging"?"preview":null}async function hm(t,e){if(!(hr(mr(t,"open-next.config.ts"))||hr(mr(t,"open-next.config.js"))))return{kind:"failed",result:p(`No .open-next/ build output at ${t}, and no open-next.config.* either. This project is not configured for the Cloudflare adapter \u2014 mist_deploy ships the .open-next/ artifact, not raw source. If this is a Mistflow project, re-run mist_init to restore the OpenNext config.`,!0)};if(!hr(mr(t,"node_modules")))return{kind:"failed",result:p(`node_modules is missing at ${t}. Call mist_install { projectPath } first, then mist_deploy.`,!0)};if(!Bt())return{kind:"failed",result:p(Pt(),!0)};let n=await mt({type:"build",cmd:"npx",args:["-y","@opennextjs/cloudflare","build"],cwd:t}),i=e?qe(e.server,e.progressToken,()=>`Auto-building before deploy \u2014 OpenNext adapter (${n.id})`):{stop:()=>{}},o;try{o=await Kt(n.id,{timeoutMs:45e3})}finally{i.stop()}if(!o)return{kind:"failed",result:p(`Auto-build job ${n.id} disappeared. Run mist_build { projectPath } manually, then mist_deploy.`,!0)};if(o.status==="running"||o.status==="starting")return{kind:"running",result:p(JSON.stringify({status:"building",buildJobId:n.id,phase:"auto-build",nextAction:`Build is still running after the 45s inline window. Call mist_build { jobId: '${n.id}' } to keep waiting (long-polls server-side), then call mist_deploy { action: 'deploy', projectPath } again. Do NOT ask the user \u2014 the build is in flight, just keep going.`}))};if(o.status==="complete"&&il(t))return{kind:"ok"};let s=Ct(n.id),a=(o.logTail??"").split(`
|
|
5720
5350
|
`).slice(-30).join(`
|
|
5721
|
-
`);return{kind:"failed",result:
|
|
5722
|
-
`)}async function
|
|
5723
|
-
`))}if(r.action==="cancel"){let s=r.sessionId,a=await
|
|
5724
|
-
${
|
|
5351
|
+
`);return{kind:"failed",result:p(JSON.stringify({status:"build_failed",buildJobId:n.id,exitCode:o.exitCode,logTail:a,logPaths:s,nextAction:`Auto-build before deploy failed (exit ${o.exitCode??"?"}). Read the logTail or run mist_debug { projectPath, jobId: '${n.id}' } to extract structured errors. Fix the code, then call mist_deploy { action: 'deploy', projectPath } again.`}),!0)}}async function gm(t){let e=pm(t.projectPath);if(!Se())return Ee("deploy");let r=it(e),n=r?.projectId;if(!n){if(!r?.name)return p(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);try{n=(await St(r.name,{dbProvider:r.dbProvider,requestedSubdomain:r.requestedSubdomain})).id,Tr(e,{projectId:n}),console.error(`[deploy] auto-registered project ${n.slice(0,8)} (${r.name})`+(r.requestedSubdomain?` at ${r.requestedSubdomain}.mistflow.app`:""))}catch(l){let c=l instanceof G||l instanceof Error?l.message:String(l);return p(`Auto-register before deploy failed: ${c}. mistflow.json has no projectId \u2014 mist_init couldn't register the project earlier (likely offline or backend timeout). Try again in a moment, or check Mistflow status.`,!0)}}if(!il(e)){let l=await hm(e,t.ctx);if(l.kind==="running"||l.kind==="failed")return l.result}let i=t.environment??mm(e)??"production",o=t.adminEmail??Ys()?.email,s=null,a=null;try{s=await tl(e),a=await nl(e);let l=await Cr(n,s.path,i,o,void 0,a??void 0,void 0);return p(JSON.stringify({status:"running",jobId:l.deployment_id,deploymentId:l.deployment_id,environment:l.environment??i,buildSize:rl(s.sizeBytes),buildFileCount:s.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${l.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side, so there's no need to sleep between calls. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(l){let c=l instanceof G||l instanceof Error?l.message:String(l);return p(`Deploy upload failed: ${c}`,!0)}finally{Cs(s?.path),Cs(a)}}async function fm(t,e){let r=e.ctx?qe(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let n=await at(t,{waitSeconds:e.waitSeconds}),i=sl(n.status),o=n.id??t;return n.status==="live"?(e.projectPath&&n.url&&(Tr(e.projectPath,{deploy:{url:n.url,deploymentId:o,completedAt:n.completedAt}}),zt(e.projectPath)),p(JSON.stringify({status:"complete",jobId:o,deploymentId:o,url:n.url,completedAt:n.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${n.url??""}', deploymentId: '${o}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`}))):n.status==="failed"?p(JSON.stringify({status:"failed",jobId:o,deploymentId:o,error:n.error,phase:i,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):p(JSON.stringify({status:"running",jobId:o,deploymentId:o,phase:i,phaseCode:n.status,nextAction:`Still ${n.status} after the ${e.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${o}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(n){let i=n instanceof G||n instanceof Error?n.message:String(n);return p(`Could not fetch deploy status: ${i}`,!0)}finally{r.stop()}}async function ym(t,e){if(!Se())return Ee("promote a preview deployment");let n=it(t)?.projectId;if(!n)return p(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let i=e;if(!i)try{let s=(await Ot(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!s)return p("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);i=s.id}catch(o){let s=o instanceof G?o.message:String(o);return p(`Could not list deployments: ${s}`,!0)}try{let o=await Lr(n,i);return p(JSON.stringify({status:"running",jobId:o.deployment_id,deploymentId:o.deployment_id,promotedFrom:i,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${o.deployment_id}' } immediately \u2014 long-polls for up to 20s. Promotion re-uses the preview artifact and typically completes in ~10s, so one poll usually finishes the job.`}))}catch(o){let s=o instanceof G||o instanceof Error?o.message:String(o);return p(`Promote failed: ${s}`,!0)}}async function bm(t){if(!Se())return Ee("roll back a deployment");try{let e=await Ur(t);return p(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let r=e instanceof G||e instanceof Error?e.message:String(e);return p(`Rollback failed: ${r}`,!0)}}var um,al,ll=I(()=>{"use strict";be();_e();kt();kt();nr();ol();qt();Ts();wn();Zn();um=tt.object({action:tt.enum(["deploy","promote","rollback","status"]).default("deploy").describe("'deploy' (default) tars + uploads + starts a deployment. 'promote' promotes a staging preview to production. 'rollback' rolls back to a specific deployment. 'status' polls an in-flight deployment by id."),projectPath:tt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:tt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:tt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:tt.string().optional().describe("Optional override for the owner email. Defaults to the email of whoever ran mist_setup (read from ~/.mistflow/credentials.json). Multi-role apps auto-promote this email to admin on first signup; single-role apps just attach it to the project for the dashboard's Owner Access card. Pass explicitly only when the deploying user is not the intended owner."),waitSeconds:tt.number().min(0).max(20).optional().describe("On action='status' calls: long-poll the backend for up to N seconds (0-20) before returning, so a typical deploy fits in 1-2 round-trips instead of 6-12. Default 20. Ignored for non-status actions."),envVarsRequired:tt.array(lr).optional().describe("Last chance to declare env vars introduced since the last implement call. Merged into mistflow.json env.required before the build is tarred, so the backend's deploy-time check picks them up. Skip keys covered by integration presets (Stripe, Resend, etc.). Only used for action='deploy'."),sessionId:tt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")});al={name:"mist_deploy",description:"Deploy a Mistflow project. action='deploy' (default) tars + uploads + starts backend orchestration; action='status' polls an in-flight deployment; action='promote' ships a staging preview to prod; action='rollback' reverts to a previous deployment. Fire-and-poll: deploy/promote/rollback return a jobId immediately; poll with { action: 'status', deploymentId }. Do NOT show the deploy URL to the user until mist_qa passes \u2014 qaRequired=true is returned on completion.",inputSchema:um,handler:async(t,e)=>{let r=t;switch(r.action??"deploy"){case"deploy":{if(!r.projectPath)return p("projectPath is required for action='deploy'.",!0);if(r.envVarsRequired&&r.envVarsRequired.length>0)try{let i=cr(r.projectPath,r.envVarsRequired);i.added.length>0&&console.error(`[deploy] declared env.required: ${i.added.join(", ")}`)}catch(i){console.error("[deploy] env var merge skipped:",i instanceof Error?i.message:String(i))}return gm({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail,ctx:e})}case"status":return r.deploymentId?fm(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e,projectPath:r.projectPath,sessionId:r.sessionId}):p("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?ym(r.projectPath,r.deploymentId):p("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?bm(r.deploymentId):p("deploymentId is required for action='rollback'.",!0)}}}});import{z as Qt}from"zod";import{hostname as wm}from"os";function cl(){return wm()}function As(t){let e=[`Session: ${t.id}`,`Status: ${t.status}`,`Deploy strategy: ${t.deploy_strategy}`];return t.paused_after_plan&&e.push("Paused: yes (awaiting PLAN.md review \u2014 call mist_session({resume}) when done)"),t.description&&e.push(`Description: ${t.description}`),t.cancelled_at&&e.push(`Cancelled at: ${t.cancelled_at}`),t.completed_at&&e.push(`Completed at: ${t.completed_at}`),e.join(`
|
|
5352
|
+
`)}async function vm(t){let e=dl.safeParse(t);if(!e.success){let s=e.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return p(`Invalid input: ${s}`,!0)}let r=e.data;if((r.action==="status"||r.action==="cancel"||r.action==="resume")&&!r.sessionId)return p(`Invalid input: action="${r.action}" requires sessionId.`,!0);if(r.action==="resume"&&!r.projectPath)return p('Invalid input: action="resume" requires projectPath.',!0);if(r.action==="status"){let s=r.sessionId,[a,l,c]=await Promise.all([qn(s),Dt(s).catch(()=>null),sn(s).catch(()=>null)]),u=[As(a),"",l?`Next instruction: ${l.instruction}${l.reason?` (${l.reason})`:""}`:"Next instruction: (unavailable)"];if(c&&c.criteria.length>0){u.push("",`Acceptance criteria (${c.criteria.length}):`);for(let h of c.criteria)u.push(` - [${h.priority}] ${h.id}: ${h.description}`)}return p(u.join(`
|
|
5353
|
+
`))}if(r.action==="cancel"){let s=r.sessionId,a=await Vr(s,r.reason);return p(`Session cancelled.
|
|
5354
|
+
${As(a)}
|
|
5725
5355
|
|
|
5726
|
-
Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(r.action==="resume"){let s=r.sessionId,a=r.projectPath,l=
|
|
5356
|
+
Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(r.action==="resume"){let s=r.sessionId,a=r.projectPath,l=cl(),c=await on(s,{machine_id:l,local_path:a}),u=await qn(s),h=await Dt(s).catch(()=>null);return p(`Resumed session on this machine.
|
|
5727
5357
|
Machine: ${l}
|
|
5728
5358
|
Local path: ${c.local_path}
|
|
5729
5359
|
Last seen: ${c.last_seen_at}
|
|
5730
5360
|
|
|
5731
|
-
`+
|
|
5361
|
+
`+As(u)+(h?`
|
|
5732
5362
|
|
|
5733
|
-
Next instruction: ${
|
|
5734
|
-
Run mist_plan to start a new one,
|
|
5735
|
-
`))}var
|
|
5363
|
+
Next instruction: ${h.instruction}${h.reason?` (${h.reason})`:""}`:""))}let n=cl(),i=await an(n,{includeIdle:r.includeIdle===!0});if(i.length===0){let s=r.includeIdle?"this machine has no sessions bound at all":"no active sessions touched in the last 24h on this machine";return p(`${s} (${n}).
|
|
5364
|
+
`+(r.includeIdle?"Run mist_plan to start a new one.":'Run mist_plan to start a new one, mist_session action="resume" with a sessionId, or mist_session action="list" includeIdle=true to see older sessions.'))}let o=[`Sessions bound on this machine (${n}):`,"",...i.map(s=>` - ${s.id} status=${s.status}${s.paused_after_plan?" (paused)":""} ${s.description?`"${s.description.slice(0,60)}"`:"(no description)"}`)];return p(o.join(`
|
|
5365
|
+
`))}var dl,pl,ul=I(()=>{"use strict";be();_e();dl=Qt.object({action:Qt.enum(["status","cancel","resume","list"]).describe("status = read current state + acceptance criteria; cancel = terminal CANCELLED transition; resume = bind this machine + path to a session; list = sessions this machine has bound (no sessionId needed)."),sessionId:Qt.string().uuid().optional().describe("Required for status / cancel / resume. Omit for list."),reason:Qt.string().max(500).optional().describe("Optional cancellation reason (used with action=cancel)."),projectPath:Qt.string().min(1).optional().describe("Absolute path to the project directory on this machine. Required for action=resume."),includeIdle:Qt.boolean().optional().describe("For action=list. Default false: only active sessions touched in the last 24h are returned. Set true to see every session ever bound on this machine, including cancelled / completed / stale ones.")});pl={name:"mist_session",description:"Read or correct a Mistflow session. Actions: status (current state + criteria), cancel (terminal), resume (bind this machine to a session for multi-machine work), list (sessions this machine has worked on). All state changes go through the backend so the host AI never directly mutates session state.",inputSchema:dl,handler:vm}});var Pm={};import{Server as km}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as xm}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Sm,ListToolsRequestSchema as Tm}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as _m}from"zod-to-json-schema";async function Im(){let t=process.argv.indexOf("--api-url");t!==-1&&process.argv[t+1]&&(process.env.MISTFLOW_API_URL=process.argv[t+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let e=new xm;await gr.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var gr,ml,hl=I(()=>{"use strict";Ke();be();lo();So();_o();Ao();No();ss();Bo();ai();bi();Ea();La();$a();za();Qa();ll();ul();_e();gr=new km({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Ls()}),ml=[ao,xo,To,Co,Eo,ii,yi,$o,Ra,qo,Ma,Ua,Ba,Ja,al,pl];gr.setRequestHandler(Tm,async()=>({tools:ml.map(t=>({name:t.name,description:t.description,inputSchema:_m(t.inputSchema)}))}));gr.setRequestHandler(Sm,async t=>{let e=ml.find(r=>r.name===t.params.name);if(!e)return p(`Unknown tool: ${t.params.name}`,!0);try{let r=e.inputSchema.safeParse(t.params.arguments);if(!r.success){let s=r.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return p(`Invalid input: ${s}`,!0)}let n=typeof r.data=="object"&&r.data!==null&&"sessionId"in r.data&&typeof r.data.sessionId=="string"?r.data.sessionId:void 0;if(n&&e.name!=="mist_session")try{let s=await Kr(n,e.name);if(!s.allowed)return p(`Tool ${e.name} not allowed for this session.
|
|
5736
5366
|
Reason: ${s.reason}
|
|
5737
|
-
|
|
5738
|
-
Allowed states: ${s.allowed_states.join(", ")}
|
|
5367
|
+
Status: ${s.status}
|
|
5739
5368
|
|
|
5740
|
-
Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(s){if(s instanceof
|
|
5369
|
+
Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(s){if(s instanceof G&&s.code==="not_found")console.error(`Guard check 404 for tool ${e.name}: ${s.message}`);else throw s}let i=t.params._meta?.progressToken,o={server:gr,progressToken:i};try{return await e.handler(r.data,o)}finally{o.cleanup?.()}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),p(n,!0)}});Im().catch(t=>{console.error("Fatal error:",t),process.exit(1)})});import{readFileSync as Cm}from"fs";import{dirname as Am,join as Rm}from"path";import{fileURLToPath as Em}from"url";var bt=process.argv[2];if(bt==="--version"||bt==="-v"){try{let t=Am(Em(import.meta.url)),e=Rm(t,"..","package.json"),r=JSON.parse(Cm(e,"utf-8"));console.log(r.version)}catch{console.log("unknown")}process.exit(0)}(bt==="--help"||bt==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
|
|
5741
5370
|
|
|
5742
5371
|
Usage:
|
|
5743
5372
|
npx @mistflow-ai/mcp Start the MCP server on stdio (default; invoked by editors)
|
|
@@ -5745,8 +5374,8 @@ Usage:
|
|
|
5745
5374
|
|
|
5746
5375
|
To install the server into your editor config, use the installer:
|
|
5747
5376
|
npx -y mistflow-ai install
|
|
5748
|
-
`),process.exit(0));(
|
|
5377
|
+
`),process.exit(0));(bt==="install"||bt==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${bt}' is no longer supported.
|
|
5749
5378
|
Use the installer package instead:
|
|
5750
5379
|
|
|
5751
|
-
npx -y mistflow-ai ${
|
|
5752
|
-
`),process.exit(1));await Promise.resolve().then(()=>(
|
|
5380
|
+
npx -y mistflow-ai ${bt}
|
|
5381
|
+
`),process.exit(1));await Promise.resolve().then(()=>(hl(),Pm));
|