@mistflow-ai/mcp 1.5.5 → 1.6.0
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 +1176 -320
- package/dist/index.js +1173 -317
- package/package.json +2 -1
package/dist/cli.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}var wl,vl,kl,xl,Sl,Tl,_l,Il,Pl,Es,Ns,Os,js,Ds,Ms,Ls,Ze=_(()=>{"use strict";wl="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.",vl='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"`.',kl="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.",xl="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.",Sl='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.',Tl="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.",_l="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.",Il='Long-running tools (mist_plan, mist_install, mist_build, mist_qa, mist_deploy) use the fire-and-poll pattern. The first call returns `status: "running"` with a `jobId` or `conversationId`. Every subsequent call with that same id returns the current state \u2014 re-call IMMEDIATELY whenever you see `status: "running"`. DO NOT run `bash sleep`, `setTimeout`, or any wall-clock wait between polls \u2014 Claude Code\'s harness blocks standalone sleeps, and every MCP server poll endpoint holds the connection up to ~10-15s on its side already, returning as soon as state changes. Just call the tool again. Each response is well inside the 60s MCP ceiling. When `status: "complete"` or `"failed"` arrives, the tool is done. Never assume a job stalled because a single call took 10s \u2014 calls return fast, but the work keeps running in the background. Do not ask the user whether to keep polling; polling is how these tools work.',Pl="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST ask the user and WAIT for their actual answer before submitting anything back. Use your host's native structured-question UI: `AskUserQuestion` in Claude Code, quick pick in Cursor, `request_user_input` in OpenAI Codex (available in Plan mode \u2014 if Codex returns 'request_user_input is unavailable in <mode> mode', you are in default mode; stop your turn and print the questions as a numbered chat message, then wait for the user's next message). For any host that does not expose a structured question tool, stop your turn immediately, print the questions verbatim as a numbered list with all options visible, and wait \u2014 the user's next message is the answer. The rule across every host: you never submit answers to `mist_plan` in the same turn you received the questions. That is always wrong, regardless of how obvious the `recommended` choice looks, regardless of whether you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode. The `recommended` field is a hint FOR the user, not permission FOR you. Anti-example from a real transcript: the host AI received 7 discovery questions, wrote 'I'll lock in the defaults with Azure OpenAI as the only override,' submitted answers the user never saw, and the user ended up with a plan they didn't choose. That behavior is a regression bug. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to perform that submission step; that is your job.",Es="Connect the user's Mistflow account. Call this ONLY when: (a) the user has literally never signed in, or (b) a previous tool call returned error code 'auth_missing' or 'auth_revoked'. DO NOT call this tool in response to 500 errors, 404 errors, network errors, or any generic failure \u2014 those are backend issues, not auth issues. Running mist_setup when not needed wastes the user's time and creates login fatigue. Once signed in, the MCP persists a long-lived API key and never asks again. Two-phase device code flow: (1) Call without deviceCode \u2014 opens browser, returns status 'pending' with deviceCode and userCode. Tell the user the verification code and that they need to approve in the browser. (2) Call again with deviceCode after ~15 seconds \u2014 polls for approval. Also accepts an apiKey for headless auth (skips device code entirely).",Ns="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'integrations' browses the curated integration blueprint catalog (pass integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",Os="Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",js="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.",Ds="Fetch a per-topic Mistflow methodology doc on demand. Two actions: `list` returns the catalog (id, title, kind, description) so you can discover what's available; `get` returns the full markdown for one topic. Topic kinds: 'stack' (framework patterns \u2014 Drizzle, Better Auth, server actions, components, styling), 'skill' (design + structural patterns \u2014 auth-design, app-design, admin-panel, blob-storage), 'integration' (third-party services \u2014 Stripe, Resend, OpenAI, Anthropic, Twilio, etc.). Call BEFORE writing or modifying code that touches an integration or a stack-specific pattern. Lazy-loaded \u2014 pulls only the topic you need instead of paying for the full AGENTS.md monolith every turn. Same content as AGENTS.md / .claude/skills/<topic>/SKILL.md / .cursor/rules/<topic>.mdc on disk; use this tool when those aren't auto-discovered by your host.",Ms="Analyze build errors from a Next.js / TypeScript project. Extracts structured errors with file, line, a human-readable message for the user, and an actionable suggestion. Call with { projectPath } to run `npm run build` and parse the failure; call with { buildOutput } to parse output captured elsewhere (e.g. from a failed mist_build job).",Ls="Generate a grayscale wireframe sketch of the planned app so the user can review layout + information hierarchy before any code is written. The server returns a structured spec + a wireframePrompt \u2014 the host AI writes the HTML file to .mistflow/mockups/mockup-<planId>.html and opens it. Pass { planId } for the first iteration, { planId, feedback: '...' } to iterate, { planId, approved: true } to lock the design before mist_init. Iterative by design \u2014 expect 1-3 rounds of feedback."});import{existsSync as vr,readFileSync as Bs,writeFileSync as Cl,mkdirSync as Al}from"fs";import{join as br,dirname as wr}from"path";import{homedir as Rl}from"os";import{fileURLToPath as El}from"url";function ze(){if(Cn)return Cn;try{let t=El(import.meta.url),e=wr(t);for(let r=0;r<6;r++){let n=br(e,"package.json");if(vr(n)){let o=JSON.parse(Bs(n,"utf-8"));if(o.name==="@mistflow-ai/mcp"&&typeof o.version=="string")return Cn=o.version,o.version}let i=wr(e);if(i===e)break;e=i}}catch{}return Cn="0.0.0","0.0.0"}function An(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=An(t),n=An(e);if(!r||!n)return 0;for(let i=0;i<3;i++){if(r[i]<n[i])return-1;if(r[i]>n[i])return 1}return 0}function zs(t,e,r){if(r&&Us(t,r)<0)return"unsupported";if(!e||Us(t,e)>=0)return"none";let i=An(t),o=An(e);return!i||!o?"none":i[0]<o[0]?"major":i[1]<o[1]?"minor":"patch"}function Zt(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||(Be={latest:e,minSupported:r,changelogUrl:n})}function Hs(){let t=process.env.MISTFLOW_STATE_DIR||br(Rl(),".mistflow");return br(t,"upgrade-state.json")}function Nl(){try{let t=Hs();return vr(t)?JSON.parse(Bs(t,"utf-8")):{}}catch{return{}}}function Ol(t){try{let e=Hs(),r=wr(e);vr(r)||Al(r,{recursive:!0}),Cl(e,JSON.stringify(t,null,2)+`
|
|
4
|
-
`,{mode:384})}catch{}}function
|
|
5
|
-
What's new: ${
|
|
2
|
+
var Dl=Object.defineProperty;var I=(t,e)=>()=>(t&&(e=t(t=0)),e);var on=(t,e)=>{for(var s in e)Dl(t,s,{get:e[s],enumerable:!0})};function Xo(){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(zl),t.push(""),t.push(Ml),t.push(""),t.push(Ll),t.push(""),t.push($l),t.push(""),t.push(Ul),t.push(""),t.push(Hl),t.push(""),t.push(ql),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(Fl),t.push(""),t.push(Bl),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 Ml,Ll,$l,Ul,Fl,ql,Bl,zl,Hl,Wo,Go,Vo,Ko,Jo,Yo,Qo,tt=I(()=>{"use strict";Ml="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.",Ll='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"`.',$l="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.",Ul="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.",Fl='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.',ql="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.",Bl="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.",zl='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.',Hl="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.",Wo="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).",Go="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.",Vo="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.",Ko="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.",Jo="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.",Yo="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 Cs,readFileSync as nr,writeFileSync as Wl,mkdirSync as Gl}from"fs";import{join as Is,dirname as Ps}from"path";import{homedir as Vl}from"os";import{fileURLToPath as Kl}from"url";function We(){if(On)return On;try{let t=Kl(import.meta.url),e=Ps(t);for(let s=0;s<6;s++){let n=Is(e,"package.json");if(Cs(n)){let i=JSON.parse(nr(n,"utf-8"));if(i.name==="@mistflow-ai/mcp"&&typeof i.version=="string")return On=i.version,i.version}let o=Ps(e);if(o===e)break;e=o}}catch{}return On="0.0.0","0.0.0"}function jn(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 s=jn(t),n=jn(e);if(!s||!n)return 0;for(let o=0;o<3;o++){if(s[o]<n[o])return-1;if(s[o]>n[o])return 1}return 0}function sr(t,e,s){if(s&&Zo(t,s)<0)return"unsupported";if(!e||Zo(t,e)>=0)return"none";let o=jn(t),i=jn(e);return!o||!i?"none":o[0]<i[0]?"major":o[1]<i[1]?"minor":"patch"}function rn(t){let e=t.get("x-mistflow-mcp-latest")??"",s=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!s||(He={latest:e,minSupported:s,changelogUrl:n})}function or(){let t=process.env.MISTFLOW_STATE_DIR||Is(Vl(),".mistflow");return Is(t,"upgrade-state.json")}function Jl(){try{let t=or();return Cs(t)?JSON.parse(nr(t,"utf-8")):{}}catch{return{}}}function Yl(t){try{let e=or(),s=Ps(e);Cs(s)||Gl(s,{recursive:!0}),Wl(e,JSON.stringify(t,null,2)+`
|
|
4
|
+
`,{mode:384})}catch{}}function Ql(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function rr(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!He)return null;let t=We();if(t==="0.0.0")return null;let e=sr(t,He.latest,He.minSupported);if(e==="none")return null;if(e==="unsupported")return tr(e,t,He);if(er)return null;let s=Jl(),n=Date.now(),o=Ql(e);return s.dismissedForVersion===He.latest&&e!=="major"||s.lastLatestSeen===He.latest&&s.lastShownMs&&n-s.lastShownMs<o?null:(er=!0,Yl({...s,lastShownMs:n,lastLatestSeen:He.latest}),tr(e,t,He))}function tr(t,e,s){let n="npx -y mistflow-ai install",o=s.changelogUrl?`
|
|
5
|
+
What's new: ${s.changelogUrl}`:"";return t==="unsupported"?`
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
Mistflow ${e} is no longer supported.
|
|
9
|
-
You must upgrade to ${
|
|
9
|
+
You must upgrade to ${s.latest} or newer to continue:
|
|
10
10
|
|
|
11
11
|
${n}
|
|
12
12
|
|
|
13
|
-
After upgrading, restart your AI editor.${
|
|
13
|
+
After upgrading, restart your AI editor.${o}
|
|
14
14
|
---`:t==="major"?`
|
|
15
15
|
|
|
16
16
|
---
|
|
17
|
-
Mistflow ${
|
|
18
|
-
This is a major update. Run \`${n}\` and restart your editor.${
|
|
17
|
+
Mistflow ${s.latest} is available (you have ${e}).
|
|
18
|
+
This is a major update. Run \`${n}\` and restart your editor.${o}
|
|
19
19
|
---`:t==="minor"?`
|
|
20
20
|
|
|
21
|
-
--- Mistflow update available: ${e} -> ${
|
|
22
|
-
Run \`${n}\` to upgrade, then restart your editor.${
|
|
21
|
+
--- Mistflow update available: ${e} -> ${s.latest} ---
|
|
22
|
+
Run \`${n}\` to upgrade, then restart your editor.${o}`:`
|
|
23
23
|
|
|
24
|
-
(Mistflow ${
|
|
24
|
+
(Mistflow ${s.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function As(){let t=We(),e=He??{latest:"",minSupported:"",changelogUrl:""},s=sr(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:s,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:He!==null}}var On,He,er,an=I(()=>{"use strict";On=null;He=null;er=!1});var dn={};on(dn,{closeBrowser:()=>Es,getIsolatedContext:()=>Zl,getPage:()=>Rs,getSnapshot:()=>ln,takeScreenshot:()=>cn});async function ir(){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 Xl(){let t=await ir();return(!Ge||!Ge.isConnected())&&(Ge=await t.chromium.launch({headless:!0})),ct&&(await ct.close().catch(()=>{}),ct=null),ct=await Ge.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),nt=await ct.newPage(),nt}async function Rs(){return nt&&!nt.isClosed()?nt:(Dn||(Dn=Xl().finally(()=>{Dn=null})),Dn)}async function Es(){nt&&!nt.isClosed()&&await nt.close().catch(()=>{}),ct&&await ct.close().catch(()=>{}),Ge?.isConnected()&&await Ge.close().catch(()=>{}),nt=null,ct=null,Ge=null}async function Zl(){let t=await ir();(!Ge||!Ge.isConnected())&&(Ge=await t.chromium.launch({headless:!0}));let e=await Ge.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),s=await e.newPage();return{context:e,page:s}}async function ln(t){return await t.locator("body").ariaSnapshot()}async function cn(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var Ge,ct,nt,Dn,Dt=I(()=>{"use strict";Ge=null,ct=null,nt=null,Dn=null;process.once("SIGTERM",()=>{Es().finally(()=>process.exit(0))});process.once("SIGINT",()=>{Es().finally(()=>process.exit(0))})});function d(t,e=!1){let s=t;try{let n=rr();n&&(s=t+n)}catch{}return{content:[{type:"text",text:s}],isError:e}}function Me(t){let e={status:"setup_required",reason:"no_credentials",intent:t,instruction:`You must sign in to Mistflow before you can ${t}. Call mist_setup({}) \u2014 it walks the user through device-code authentication (typically <60s). Only retry the original call AFTER mist_setup has fully completed sign-in (status field is no longer "pending").`,nextAction:`Step 1: Call mist_setup({}) now. Do not ask the user for permission first \u2014 sign-in is a precondition for this flow, not a decision point. Step 2: mist_setup returns immediately with a signInUrl + userCode. Show the URL and code to the user and wait for them to approve in their browser. Step 3: If the response had status: "pending", call mist_setup again with the returned deviceCode every ~15s until it returns a non-pending status. Step 4: Only then retry the call that produced this response with the same arguments. Do NOT retry while mist_setup is still pending \u2014 the credentials aren't on disk yet and you'll loop right back into this same response.`};return d(JSON.stringify(e),!0)}function st(t){return d(`This is not a Mistflow project (no mistflow.json found at ${t}).
|
|
25
25
|
|
|
26
26
|
Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
|
|
27
27
|
|
|
@@ -30,20 +30,20 @@ To get started:
|
|
|
30
30
|
2. Call mist_init({ planId, path: "<absolute-path>" })
|
|
31
31
|
3. Call mist_install({ projectPath }), then mist_implement({ projectPath })
|
|
32
32
|
|
|
33
|
-
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function
|
|
34
|
-
`,{mode:384}),
|
|
35
|
-
`,"utf-8")}catch{}}var Wl,St=_(()=>{"use strict";Wl="https://api.mistflow.ai"});var so={};Pn(so,{MistflowApiError:()=>Y,addDomain:()=>Er,bindWorkspace:()=>an,cancelSession:()=>Jr,checkAuth:()=>Yl,checkAuthDetailed:()=>to,checkSubdomain:()=>Dn,checkToolGuard:()=>Yr,createDeployment:()=>Xl,createProject:()=>_t,deleteEnvVar:()=>Mr,discoverDecisions:()=>ec,downloadImageryAsset:()=>Ar,downloadSource:()=>rc,downloadSourceWithToken:()=>no,fetchAcceptanceCriteria:()=>on,fetchActiveSessionPlan:()=>ac,fetchDesignDirections:()=>Mn,fetchDesignPick:()=>Zl,fetchDesignRenders:()=>$n,fetchDoc:()=>Hr,fetchDocsList:()=>zr,fetchModule:()=>Wr,fetchPlanConversation:()=>Un,fetchProjectImagery:()=>Cr,fetchScaffold:()=>qr,fetchSessionNext:()=>Mt,fetchSessionPlanRevisions:()=>ro,fetchStepContext:()=>Br,forkTemplate:()=>Vr,generatePlan:()=>Fn,getAuthHeaders:()=>Tt,getBaseUrl:()=>Ce,getDashboardUrl:()=>Vl,getDbCredentials:()=>tc,getDeployLogs:()=>Lr,getDeploymentStatus:()=>dt,getProject:()=>Ql,getProjectErrors:()=>$r,getSeedInfo:()=>zn,getSession:()=>Hn,getSiteUrl:()=>Gl,getTemplate:()=>Gr,hasCredentialsOnDisk:()=>Te,hasLocalCredentials:()=>eo,listDeployments:()=>jt,listDomains:()=>pt,listEnvVars:()=>jr,listSessionsForMachine:()=>ln,markLocalSetupDone:()=>sc,modifyPlan:()=>qn,pingBackend:()=>Pr,promotePreview:()=>Ur,redeployProject:()=>nc,removeDomain:()=>Nr,rollbackDeployment:()=>Fr,shareProject:()=>Kr,startSession:()=>oc,submitAcceptanceResults:()=>Qr,submitDesignPick:()=>Ln,submitSessionAnswers:()=>ic,uploadAndDeploy:()=>Rr,uploadQAResults:()=>Or,upsertEnvVar:()=>Dr,verifyDomain:()=>Bn});function Ce(){return On()}function Gl(){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 Vl(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function Tt(){let t=xt();if(!t.ok)throw new Y("auth_missing","No Mistflow credentials found.",401);return Kl(t.creds)}function Kl(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":ze()}}function Ot(t){try{Zt(t.headers)}catch{}}async function Pr(){try{let t=await fetch(`${Ce()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Ot(t)}catch{}}async function Zs(t,e,r,n){for(let i=0;i<2;i++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(o){let s=o instanceof Error&&o.name==="TimeoutError",a=o instanceof TypeError;if(n&&i===0&&(s||a)){console.error(`[api] Retrying ${t} after ${s?"timeout":"network error"}`);continue}throw o}throw new Error("fetchWithRetry: exhausted retries")}async function sn(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new Y(r,n,t.status,e?.details);let i=t.status;return i===401?new Y("auth_invalid",n,i):i===403?new Y("permission_denied",n,i):i===404?new Y("not_found",n,i):i===409?new Y("conflict",n,i):i===422?new Y("validation_error",n,i):i===429?new Y("rate_limited",n,i):i>=500?new Y("server_error",t.statusText||"Internal server error",i):new Y("client_error",n,i)}async function B(t,e={}){let r=Tt(),{timeoutMs:n,idempotent:i,...o}=e,s=n??3e4,a=(o.method??"GET").toUpperCase(),l=i??(a==="GET"||a==="HEAD"),c;try{c=await Zs(`${Ce()}${t}`,{...o,headers:{...r,...o.headers}},s,l)}catch(m){throw m instanceof Error&&m.name==="TimeoutError"?new Y("network_error","Request timed out. Try again in a moment."):new Y("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ot(c),!c.ok)throw await sn(c);return c.json()}function eo(){return xt().ok}async function Yl(){return(await to()).ok}async function to(){if(jn!==null&&Date.now()<Xs)return jn?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!eo())return{ok:!1,reason:"no_credentials"};try{return await B("/api/org"),jn=!0,Xs=Date.now()+Jl,{ok:!0}}catch(t){if(jn=null,!(t instanceof Y))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 Ql(t){return B(`/api/projects/${encodeURIComponent(t)}`)}async function Dn(t){return B(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function _t(t,e={}){return B("/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 Cr(t){return B(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function Ar(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 Xl(t,e){return B("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function Rr(t,e,r="production",n,i,o,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=xt();if(!c.ok)throw new Y("auth_missing","No Mistflow credentials found.",401);let m=c.creds,p=a(e),u=new Blob([p],{type:"application/gzip"}),h=new FormData;if(h.append("project_id",t),h.append("build",u,l(e)),r!=="production"&&h.append("environment",r),n&&h.append("admin_email",n),i&&h.append("schema_pushed","true"),o){let{existsSync:x}=await import("fs");if(x(o)){let y=a(o),C=new Blob([y],{type:"application/gzip"});h.append("source",C,"source.tar.gz")}}s&&h.append("git_commit_sha",s);let j;try{j=await fetch(`${Ce()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":ze()},body:h,signal:AbortSignal.timeout(3e5)})}catch{throw new Y("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ot(j),!j.ok)throw await sn(j);let I=await j.json();return{...I,id:I.deployment_id}}async function dt(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return B(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:i}:void 0)}async function Mn(t){return B(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Zl(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return B(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:i})}async function Ln(t,e){return B(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),timeoutMs:6e4})}async function $n(t){try{return await B(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function Un(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return B(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:i})}async function Fn(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};if(e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&e?.designDirection){let i=e.designDirection,o=256,s=4e3,a=typeof i.id=="string"?i.id:void 0,l=typeof i.custom=="string"?i.custom:void 0,c=a&&a.length>0&&a.length<=o?a:void 0,m=(()=>{if(l&&l.length>0)return l.length<=s?l:l.slice(0,s)+" (truncated)";if(!c){let h=JSON.stringify(i);return h.length<=s?h:h.slice(0,s)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${o}; falling back to custom`);let p=c?{direction_id:c}:{custom:m};e.conversationId&&(p.conversation_id=e.conversationId);let u=await Ln(e.designConversationId,p);return{status:"ready",plan:u.plan??{},methodology:u.methodology??"",...u.designMd?{designMd:u.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return B("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function qn(t,e,r={}){return B("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function ec(t){return B("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Er(t,e){return B(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function pt(t){return B(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Bn(t,e){return B(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Nr(t,e){return B(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function tc(t){return B(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function zn(t){try{return await B(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof Y&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Or(t,e){try{return await B(`/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 jr(t){return B(`/api/projects/${encodeURIComponent(t)}/env`)}async function Dr(t,e,r,n){return B(`/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 Mr(t,e){return B(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Lr(t){return B(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function $r(t,e="7d"){return B(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function jt(t){return B(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function nc(t){return B(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Ur(t,e){let r=new URLSearchParams({preview_deployment_id:e});return B(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Fr(t){return B(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function rc(t,e){let r=xt();if(!r.ok)throw new Y("auth_missing","Not authenticated.",401);let n=r.creds,i=await fetch(`${Ce()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":ze()},signal:AbortSignal.timeout(12e4)});if(Ot(i),!i.ok)throw await sn(i);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await i.arrayBuffer());o(e,s)}async function Dt(t,e){let{timeoutMs:r,idempotent:n,...i}=e??{},o=r??3e4,s=(i.method??"GET").toUpperCase(),a=n??(s==="GET"||s==="HEAD"),l;try{l=await Zs(`${Ce()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":ze()},...i},o,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new Y("network_error","Request timed out. Try again in a moment."):new Y("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ot(l),!l.ok)throw await sn(l);return l.json()}async function qr(t="nextjs"){return Dt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Br(t,e){return Dt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function zr(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return Dt(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function Hr(t,e){return Dt(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function Wr(t,e,r,n){return Dt(`/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 Gr(t){return Dt(`/api/templates/${encodeURIComponent(t)}`)}async function Vr(t){return B(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function no(t,e,r){let n;try{n=await fetch(`${Ce()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":ze()},signal:AbortSignal.timeout(12e4)})}catch{throw new Y("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ot(n),!n.ok)throw n.status===401?new Y("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await sn(n);let{writeFileSync:i}=await import("fs"),o=Buffer.from(await n.arrayBuffer());i(r,o)}async function sc(t){await B(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Kr(t,e){return B(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function oc(t){return B("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function Hn(t){return B(`/api/sessions/${t}`)}async function Jr(t,e){return B(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Mt(t){return B(`/api/sessions/${t}/next`)}async function ic(t,e){return B(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Yr(t,e){return B(`/api/sessions/${t}/can/${e}`)}async function on(t){return B(`/api/sessions/${t}/acceptance`)}async function ro(t){return B(`/api/sessions/${t}/revisions`)}async function ac(t){let e=await ro(t),r=[...e].reverse().find(n=>n.status==="active")??e.at(-1);return!r||!r.body||typeof r.body!="object"||Array.isArray(r.body)?null:{plan:r.body,planRevisionId:r.id}}async function an(t,e){return B(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function ln(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return B(`/api/sessions/me/workspaces?${n}`)}async function Qr(t,e,r){return B(`/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 Y,jn,Xs,Jl,Pe=_(()=>{"use strict";St();en();Y=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"}};jn=null,Xs=0,Jl=300*1e3});import{z as Xr}from"zod";import{platform as lc}from"os";import{execFile as oo}from"child_process";function dc(t){return"error"in t}function ao(t){return new Promise(e=>setTimeout(e,t))}function pc(t){return new Promise(e=>{let r=lc();r==="win32"?oo("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):oo(r==="darwin"?"open":"xdg-open",[t],i=>{i&&console.error("Could not open browser:",i.message),e(!i)}),setTimeout(()=>e(!1),5e3)})}async function io(t,e,r,n){let i=r,o=n.sleep??ao;for(let s=0;s<e;s++){await o(i);let a;try{let c=await n.fetch(`${Ce()}/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(dc(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 _r({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 mc(t,e=uc){let r=t;if(r?.apiKey)try{let s=await e.fetch(`${Ce()}/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 _r({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),d(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let s=await io(r.deviceCode,6,5e3,e);return s||d(JSON.stringify({status:"pending",deviceCode:r.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let s=await e.fetch(`${Ce()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!s.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await s.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let i=`${n.verification_uri}?code=${n.user_code}`;console.error(`
|
|
36
|
-
Sign in at: ${
|
|
33
|
+
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function ar(t,e){try{let{getPage:s,takeScreenshot:n}=await Promise.resolve().then(()=>(Dt(),dn)),o=await s();await o.setViewportSize(ec);try{await o.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{});let i=await n(o,!1);return{content:[{type:"text",text:e},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}finally{await o.setViewportSize(tc).catch(()=>{})}}catch{return d(e)}}var ec,tc,ve=I(()=>{"use strict";an();ec={width:1024,height:576},tc={width:1280,height:720}});import{readFileSync as Ns,existsSync as Mn,writeFileSync as lr,mkdirSync as nc,renameSync as sc,unlinkSync as oc}from"fs";import{join as Ln,dirname as rc}from"path";import{homedir as ic}from"os";import{randomBytes as ac}from"crypto";function cr(){return Ln(ic(),".mistflow","credentials.json")}function $n(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function dr(){let t=cr();if(!Mn(t))return null;try{let e=JSON.parse(Ns(t,"utf-8"));return typeof e.apiKey=="string"?{[lc]:e}:e}catch{return null}}function _t(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=dr();if(!e)return{ok:!1,reason:"missing"};let s=$n(),n=e[s];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function Os(t){let e=cr(),s=rc(e);Mn(s)||nc(s,{recursive:!0});let n=dr()??{},o=$n();n[o]=t;let i=Ln(s,`.credentials.tmp.${ac(8).toString("hex")}`);try{lr(i,JSON.stringify(n,null,2)+`
|
|
34
|
+
`,{mode:384}),sc(i,e)}catch(r){try{oc(i)}catch{}throw r}}function pr(){let t=_t();return t.ok?t.creds:null}function Te(){return _t().ok}function dt(t){let e=Ln(t,"mistflow.json");if(!Mn(e))return null;try{return JSON.parse(Ns(e,"utf-8"))}catch{return null}}function js(t,e){let s=Ln(t,"mistflow.json");if(Mn(s))try{let o={...JSON.parse(Ns(s,"utf-8")),...e};lr(s,JSON.stringify(o,null,2)+`
|
|
35
|
+
`,"utf-8")}catch{}}var lc,It=I(()=>{"use strict";lc="https://api.mistflow.ai"});var br={};on(br,{MistflowApiError:()=>X,addDomain:()=>Us,bindWorkspace:()=>mn,cancelSession:()=>so,checkAuth:()=>mc,checkAuthDetailed:()=>gr,checkSubdomain:()=>Fn,checkToolGuard:()=>oo,createDeployment:()=>gc,createProject:()=>Ct,deleteEnvVar:()=>Hs,discoverDecisions:()=>yc,downloadImageryAsset:()=>Ls,downloadSource:()=>vc,downloadSourceWithToken:()=>fr,fetchAcceptanceCriteria:()=>un,fetchActiveSessionPlan:()=>ro,fetchDesignDirections:()=>qn,fetchDesignPick:()=>fc,fetchDesignRenders:()=>zn,fetchDoc:()=>Xs,fetchDocsList:()=>Qs,fetchModule:()=>Zs,fetchPlanConversation:()=>Hn,fetchProjectImagery:()=>Ms,fetchScaffold:()=>Js,fetchSessionNext:()=>Ut,fetchSessionPlanRevisions:()=>yr,fetchStepContext:()=>Ys,forkTemplate:()=>to,generatePlan:()=>Wn,getAuthHeaders:()=>Pt,getBaseUrl:()=>Re,getDashboardUrl:()=>dc,getDbCredentials:()=>bc,getDeployLogs:()=>Ws,getDeploymentStatus:()=>pt,getProject:()=>hc,getProjectErrors:()=>Gs,getSeedInfo:()=>Kn,getSession:()=>Jn,getSiteUrl:()=>cc,getTemplate:()=>eo,hasCredentialsOnDisk:()=>Te,hasLocalCredentials:()=>hr,listDeployments:()=>Lt,listDomains:()=>ut,listEnvVars:()=>Bs,listSessionsForMachine:()=>hn,markLocalSetupDone:()=>kc,modifyPlan:()=>Gn,pingBackend:()=>Ds,promotePreview:()=>Vs,redeployProject:()=>wc,removeDomain:()=>Fs,rollbackDeployment:()=>Ks,shareProject:()=>no,startSession:()=>xc,submitAcceptanceResults:()=>io,submitDesignPick:()=>Bn,submitSessionAnswers:()=>Sc,uploadAndDeploy:()=>$s,uploadQAResults:()=>qs,upsertEnvVar:()=>zs,verifyDomain:()=>Vn});function Re(){return $n()}function cc(){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 dc(){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 Pt(){let t=_t();if(!t.ok)throw new X("auth_missing","No Mistflow credentials found.",401);return pc(t.creds)}function pc(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":We()}}function Mt(t){try{rn(t.headers)}catch{}}async function Ds(){try{let t=await fetch(`${Re()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Mt(t)}catch{}}async function mr(t,e,s,n){for(let o=0;o<2;o++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(s)})}catch(i){let r=i instanceof Error&&i.name==="TimeoutError",a=i instanceof TypeError;if(n&&o===0&&(r||a)){console.error(`[api] Retrying ${t} after ${r?"timeout":"network error"}`);continue}throw i}throw new Error("fetchWithRetry: exhausted retries")}async function pn(t){let e=null;try{e=await t.json()}catch{e=null}let s=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(s)return new X(s,n,t.status,e?.details);let o=t.status;return o===401?new X("auth_invalid",n,o):o===403?new X("permission_denied",n,o):o===404?new X("not_found",n,o):o===409?new X("conflict",n,o):o===422?new X("validation_error",n,o):o===429?new X("rate_limited",n,o):o>=500?new X("server_error",t.statusText||"Internal server error",o):new X("client_error",n,o)}async function q(t,e={}){let s=Pt(),{timeoutMs:n,idempotent:o,...i}=e,r=n??3e4,a=(i.method??"GET").toUpperCase(),l=o??(a==="GET"||a==="HEAD"),c;try{c=await mr(`${Re()}${t}`,{...i,headers:{...s,...i.headers}},r,l)}catch(m){throw m instanceof Error&&m.name==="TimeoutError"?new X("network_error","Request timed out. Try again in a moment."):new X("network_error","Cannot reach Mistflow servers. Check your network.")}if(Mt(c),!c.ok)throw await pn(c);return c.json()}function hr(){return _t().ok}async function mc(){return(await gr()).ok}async function gr(){if(Un!==null&&Date.now()<ur)return Un?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!hr())return{ok:!1,reason:"no_credentials"};try{return await q("/api/org"),Un=!0,ur=Date.now()+uc,{ok:!0}}catch(t){if(Un=null,!(t instanceof X))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 hc(t){return q(`/api/projects/${encodeURIComponent(t)}`)}async function Fn(t){return q(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function Ct(t,e={}){return q("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e.template,db_provider:e.dbProvider??"neon",requested_subdomain:e.requestedSubdomain,picked_direction:e.pickedDirection,imagery_brief:e.imageryBrief,plan_context:e.planContext,design_conversation_id:e.designConversationId,session_id:e.sessionId})})}async function Ms(t){return q(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function Ls(t){let e=await fetch(t);if(!e.ok)throw new Error(`Failed to download imagery asset: HTTP ${e.status} ${e.statusText}`);let s=await e.arrayBuffer();return Buffer.from(s)}async function gc(t,e){return q("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function $s(t,e,s="production",n,o,i,r){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=_t();if(!c.ok)throw new X("auth_missing","No Mistflow credentials found.",401);let m=c.creds,p=a(e),u=new Blob([p],{type:"application/gzip"}),g=new FormData;if(g.append("project_id",t),g.append("build",u,l(e)),s!=="production"&&g.append("environment",s),n&&g.append("admin_email",n),o&&g.append("schema_pushed","true"),i){let{existsSync:x}=await import("fs");if(x(i)){let v=a(i),R=new Blob([v],{type:"application/gzip"});g.append("source",R,"source.tar.gz")}}r&&g.append("git_commit_sha",r);let D;try{D=await fetch(`${Re()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":We()},body:g,signal:AbortSignal.timeout(3e5)})}catch{throw new X("network_error","Cannot reach Mistflow servers. Check your network.")}if(Mt(D),!D.ok)throw await pn(D);let _=await D.json();return{..._,id:_.deployment_id}}async function pt(t,e){let s=e?.waitSeconds??0,n=s>0?`?wait=${s}`:"",o=Math.min(6e4,(s+5)*1e3);return q(`/api/deploy/${encodeURIComponent(t)}/status${n}`,s>0?{timeoutMs:o}:void 0)}async function qn(t){return q(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function fc(t,e){let s=e?.waitSeconds??45,n=s>0?`?wait=${s}`:"",o=Math.min(6e4,(s+5)*1e3);return q(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:o})}async function Bn(t,e){return q(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),timeoutMs:6e4})}async function zn(t){try{return await q(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function Hn(t,e){let s=e?.waitSeconds??45,n=s>0?`?wait=${s}`:"",o=Math.min(6e4,(s+5)*1e3);return q(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:o})}async function Wn(t,e){let s={description:t,conversation_id:e?.conversationId,answers:e?.answers};if(e?.autonomous&&(s.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(s.language=e.language),e?.designConversationId&&e?.designDirection){let o=e.designDirection,i=256,r=4e3,a=typeof o.id=="string"?o.id:void 0,l=typeof o.custom=="string"?o.custom:void 0,c=a&&a.length>0&&a.length<=i?a:void 0,m=(()=>{if(l&&l.length>0)return l.length<=r?l:l.slice(0,r)+" (truncated)";if(!c){let g=JSON.stringify(o);return g.length<=r?g:g.slice(0,r)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${i}; falling back to custom`);let p=c?{direction_id:c}:{custom:m};e.conversationId&&(p.conversation_id=e.conversationId);let u=await Bn(e.designConversationId,p);return{status:"ready",plan:u.plan??{},methodology:u.methodology??"",...u.designMd?{designMd:u.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return q("/api/plan",{method:"POST",body:JSON.stringify(s),timeoutMs:n,idempotent:!1})}async function Gn(t,e,s={}){return q("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:s.planMd})})}async function yc(t){return q("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Us(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function ut(t){return q(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Vn(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Fs(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function bc(t){return q(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Kn(t){try{return await q(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof X&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function qs(t,e){try{return await q(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(s){return console.error("[api] Failed to upload QA results:",s instanceof Error?s.message:s),null}}async function Bs(t){return q(`/api/projects/${encodeURIComponent(t)}/env`)}async function zs(t,e,s,n){return q(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:s,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function Hs(t,e){return q(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ws(t){return q(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Gs(t,e="7d"){return q(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Lt(t){return q(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function wc(t){return q(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Vs(t,e){let s=new URLSearchParams({preview_deployment_id:e});return q(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:s.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Ks(t){return q(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function vc(t,e){let s=_t();if(!s.ok)throw new X("auth_missing","Not authenticated.",401);let n=s.creds,o=await fetch(`${Re()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":We()},signal:AbortSignal.timeout(12e4)});if(Mt(o),!o.ok)throw await pn(o);let{writeFileSync:i}=await import("fs"),r=Buffer.from(await o.arrayBuffer());i(e,r)}async function $t(t,e){let{timeoutMs:s,idempotent:n,...o}=e??{},i=s??3e4,r=(o.method??"GET").toUpperCase(),a=n??(r==="GET"||r==="HEAD"),l;try{l=await mr(`${Re()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":We()},...o},i,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new X("network_error","Request timed out. Try again in a moment."):new X("network_error","Cannot reach Mistflow servers. Check your network.")}if(Mt(l),!l.ok)throw await pn(l);return l.json()}async function Js(t="nextjs"){return $t(`/api/scaffold/${encodeURIComponent(t)}`)}async function Ys(t,e){return $t(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Qs(t="nextjs",e){let s=e?`?kind=${encodeURIComponent(e)}`:"";return $t(`/api/scaffold/${encodeURIComponent(t)}/docs${s}`)}async function Xs(t,e){return $t(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function Zs(t,e,s,n){return $t(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:s,entity_plural:n})})}async function eo(t){return $t(`/api/templates/${encodeURIComponent(t)}`)}async function to(t){return q(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function fr(t,e,s){let n;try{n=await fetch(`${Re()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":We()},signal:AbortSignal.timeout(12e4)})}catch{throw new X("network_error","Cannot reach Mistflow servers. Check your network.")}if(Mt(n),!n.ok)throw n.status===401?new X("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await pn(n);let{writeFileSync:o}=await import("fs"),i=Buffer.from(await n.arrayBuffer());o(s,i)}async function kc(t){await q(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function no(t,e){return q(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function xc(t){return q("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function Jn(t){return q(`/api/sessions/${t}`)}async function so(t,e){return q(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Ut(t){return q(`/api/sessions/${t}/next`)}async function Sc(t,e){return q(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function oo(t,e){return q(`/api/sessions/${t}/can/${e}`)}async function un(t){return q(`/api/sessions/${t}/acceptance`)}async function yr(t){return q(`/api/sessions/${t}/revisions`)}async function ro(t){let e=await yr(t),s=[...e].reverse().find(n=>n.status==="active")??e.at(-1);return!s||!s.body||typeof s.body!="object"||Array.isArray(s.body)?null:{plan:s.body,planRevisionId:s.id}}async function mn(t,e){return q(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function hn(t,e={}){let s={machine_id:t};e.includeIdle&&(s.include_idle="true");let n=new URLSearchParams(s).toString();return q(`/api/sessions/me/workspaces?${n}`)}async function io(t,e,s){return q(`/api/sessions/${t}/acceptance/results`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({results:e,plan_revision_id:s??null}),idempotent:!1})}var X,Un,ur,uc,Pe=I(()=>{"use strict";It();an();X=class extends Error{constructor(s,n,o,i){super(n);this.code=s;this.statusCode=o;this.details=i;this.name="MistflowApiError"}code;statusCode;details;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"}};Un=null,ur=0,uc=300*1e3});import{z as ao}from"zod";import{platform as Tc}from"os";import{execFile as wr}from"child_process";function Ic(t){return"error"in t}function kr(t){return new Promise(e=>setTimeout(e,t))}function Pc(t){return new Promise(e=>{let s=Tc();s==="win32"?wr("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):wr(s==="darwin"?"open":"xdg-open",[t],o=>{o&&console.error("Could not open browser:",o.message),e(!o)}),setTimeout(()=>e(!1),5e3)})}async function vr(t,e,s,n){let o=s,i=n.sleep??kr;for(let r=0;r<e;r++){await i(o);let a;try{let c=await n.fetch(`${Re()}/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(Ic(a))switch(a.error){case"authorization_pending":continue;case"slow_down":o+=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 Os({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 Ac(t,e=Cc){let s=t;if(s?.apiKey)try{let r=await e.fetch(`${Re()}/api/org`,{headers:{Authorization:`ApiKey ${s.apiKey}`}});if(!r.ok)return d("Invalid API key. Check the key and try again.",!0);let a=await r.json();return Os({apiKey:s.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(s?.deviceCode){let r=await vr(s.deviceCode,6,5e3,e);return r||d(JSON.stringify({status:"pending",deviceCode:s.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let r=await e.fetch(`${Re()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!r.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await r.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let o=`${n.verification_uri}?code=${n.user_code}`;console.error(`
|
|
36
|
+
Sign in at: ${o}
|
|
37
37
|
Your code: ${n.user_code}
|
|
38
|
-
`);try{await e.openBrowser(
|
|
39
|
-
`)){let
|
|
40
|
-
`)}function
|
|
41
|
-
`),nextSteps:
|
|
42
|
-
`),
|
|
43
|
-
${
|
|
38
|
+
`);try{await e.openBrowser(o)}catch{}let i=await vr(n.device_code,6,5e3,e);return i||d(JSON.stringify({status:"pending",deviceCode:n.device_code,signInUrl:o,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 _c,Cc,xr,Sr=I(()=>{"use strict";tt();ve();Pe();It();_c=ao.object({apiKey:ao.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:ao.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.")});Cc={fetch:globalThis.fetch,openBrowser:Pc,sleep:kr};xr={name:"mist_setup",description:Wo,inputSchema:_c,handler:t=>Ac(t)}});import{existsSync as Rc,readFileSync as Ec}from"fs";function Tr(t){let e=new Set;if(!Rc(t))return e;let s=Ec(t,"utf-8");for(let n of s.split(`
|
|
39
|
+
`)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i>0){let r=o.slice(0,i).trim(),a=o.slice(i+1).trim();a&&a!=='""'&&a!=="''"&&e.add(r)}}return e}var _r=I(()=>{"use strict"});var yn={};on(yn,{emptyState:()=>fn,fetchRemoteState:()=>Mc,fuzzyMatch:()=>$c,getLocalStatePath:()=>lo,readLocalState:()=>Dc,syncRemoteState:()=>Lc,writeLocalState:()=>gn});import{existsSync as Ir,readFileSync as Nc,writeFileSync as Oc,mkdirSync as jc}from"fs";import{join as Pr}from"path";function lo(t){return Pr(t,".mistflow","state.json")}function Dc(t){let e=lo(t);if(!Ir(e))return null;try{return JSON.parse(Nc(e,"utf-8"))}catch{return null}}function gn(t,e){let s=Pr(t,".mistflow");Ir(s)||jc(s,{recursive:!0}),Oc(lo(t),JSON.stringify(e,null,2)+`
|
|
40
|
+
`)}function fn(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Mc(t){let e;try{e=Pt()}catch{return null}try{let s=await fetch(`${Re()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":We()}});try{rn(s.headers)}catch{}return s.ok?await s.json():null}catch{return null}}async function Lc(t,e){let s;try{s=Pt()}catch{return!1}try{let n=await fetch(`${Re()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...s,"Content-Type":"application/json","X-Mistflow-MCP-Version":We()},body:JSON.stringify(e)});try{rn(n.headers)}catch{}return n.ok}catch{return!1}}function $c(t,e){let s=t.toLowerCase(),n=e.toLowerCase();return n.includes(s)||s.includes(n)?!0:s.split(/\s+/).some(i=>i.length>=3&&n.includes(i))}var At=I(()=>{"use strict";Pe();an()});var co={};on(co,{ensureBackendRegistered:()=>Wc,ensureShadcnComponents:()=>Gc});import{existsSync as Ar,readFileSync as Uc,writeFileSync as Fc}from"fs";import{join as Yn}from"path";import{spawn as qc}from"child_process";function Bc(t,e,s,n,o){return new Promise(i=>{let r=qc(t,e,{cwd:s,stdio:["pipe","pipe","pipe"],timeout:n,...o?{env:{...process.env,...o}}:{}}),a="",l="";r.stdout?.on("data",c=>{a+=c.toString()}),r.stderr?.on("data",c=>{l+=c.toString()}),r.on("close",c=>i({success:c===0,stdout:a,stderr:l})),r.on("error",c=>i({success:!1,stdout:a,stderr:l+c.message}))})}function zc(t){let e=Yn(t,"mistflow.json");if(!Ar(e))return null;try{return JSON.parse(Uc(e,"utf-8"))}catch{return null}}function Hc(t,e){Fc(Yn(t,"mistflow.json"),JSON.stringify(e,null,2))}async function Cr(t,e){try{let s=e.features,n=e.steps,o={plan:e};Array.isArray(s)&&s.length>0&&(o.features=s.map(i=>i.name)),Array.isArray(n)&&n.length>0&&(o.provenance=n.map(i=>({feature:i.name??i.title??`Step ${i.number??"?"}`,user_intent:(i.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${Re()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...Pt(),"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(s){console.error("[self-heal] state sync failed:",s instanceof Error?s.message:String(s))}}async function Wc(t,e={}){let s=zc(t);if(s){if(!Te())return s.projectId;if(!s.projectId)try{let o=s.plan?.requestedSubdomain,i=await Ct(s.name,{dbProvider:s.dbProvider??"neon",requestedSubdomain:o});return s.projectId=i.id,Hc(t,s),gn(t,fn(i.id,s.name)),s.plan&&await Cr(i.id,s.plan),console.error(`[self-heal] registered project ${i.id.slice(0,8)} with backend`),i.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&s.plan&&s.projectId&&await Cr(s.projectId,s.plan),s.projectId}}async function Gc(t,e){let s=["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:s,o=Yn(t,"components","ui"),i=[],r=[];for(let c of n)Ar(Yn(o,`${c}.tsx`))?i.push(c):r.push(c);if(r.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Bc("npx",["--yes","shadcn@latest","add","-y","-o",...r],t,18e4,a);return l.success?{installed:r,alreadyPresent:i}:{installed:[],alreadyPresent:i,failed:`shadcn add failed for: ${r.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var po=I(()=>{"use strict";Pe();At()});import{z as mt}from"zod";import{resolve as Vc,join as Rr}from"path";import{existsSync as Kc,readFileSync as Er,writeFileSync as Jc}from"fs";var Yc,Nr,Or=I(()=>{"use strict";ve();_r();Yc=mt.object({action:mt.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:mt.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:mt.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:mt.object({key:mt.string(),description:mt.string().optional(),setupUrl:mt.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),Nr={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:Yc,handler:async t=>{let e=t,s=Vc(e.projectPath??process.cwd()),n=Rr(s,"mistflow.json");if(!Kc(n))return st(s);let o;try{o=JSON.parse(Er(n,"utf-8"))}catch{return d("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!o.projectId)try{let{ensureBackendRegistered:x}=await Promise.resolve().then(()=>(po(),co));await x(s)&&(o=JSON.parse(Er(n,"utf-8")))}catch{}let a=o.plan,l=a?.steps?.filter(x=>x.status==="completed").length??0,c=a?.steps?.length??0,m=Tr(Rr(s,".env.local")),p=o.env?.required?Object.entries(o.env.required).map(([x,v])=>({name:x,description:v?.description,configured:m.has(x)})):[];o.projectId&&Promise.resolve().then(()=>(At(),yn)).then(({fetchRemoteState:x})=>x(o.projectId)).catch(()=>{});let u=[`Project: ${o.name}`];if(a){u.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let x of a.steps){let v=x.status==="completed"?"\u2713":x.status==="in_progress"?"\u2192":" ";u.push(` [${v}] ${x.number}. ${x.name}`)}}let g=p.filter(x=>!x.configured);g.length>0&&u.push(`Missing env vars: ${g.map(x=>x.name).join(", ")}`),o.deploy?.url?u.push(`Deployed: ${o.deploy.url} (${o.deploy.count??0} deploys)`):u.push("Not deployed yet");let D=[],_=a?.steps?.find(x=>x.status!=="completed");return _?D.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${_.number} (${_.name}).`):a&&l===c&&(o.deploy?.url||D.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),g.length>0&&D.push(`Missing env vars in .env.local: ${g.map(x=>x.name).join(", ")}`),d(JSON.stringify({name:o.name,projectId:o.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:c,completedSteps:l,steps:a.steps}:null,envStatus:p,deploy:o.deploy??null,contextMessage:u.join(`
|
|
41
|
+
`),nextSteps:D}))}let i=[];if(e.completedStep!==void 0){let a=o.plan;if(a?.steps){let l=a.steps.findIndex(c=>c.number===e.completedStep);if(l===-1)return d(`Step ${e.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",i.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(o.env||(o.env={required:{}}),o.env.required||(o.env.required={}),o.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},i.push(`Added required env var: ${e.addEnvVar.key}`)),Jc(n,JSON.stringify(o,null,2)+`
|
|
42
|
+
`),o.projectId&&Promise.resolve().then(()=>(At(),yn)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(s);c&&await l(o.projectId,c)}).catch(()=>{});let r=[];if(e.completedStep!==void 0){let l=o.plan?.steps?.find(c=>c.status!=="completed");l?r.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):r.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&&(r.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&r.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),d(JSON.stringify({updated:!0,changes:i,message:i.length>0?`Project state saved. ${i.join(". ")}.`:"No changes made.",nextSteps:r.length>0?r:void 0}))}}});function Qc(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function qt(t){let e=Ft.find(n=>n.id===t);if(e)return e;let s=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Ft.find(n=>{let o=n.name.toLowerCase().replace(/[^a-z0-9]/g,"");return o===s||o.includes(s)||s.includes(o)})}function Bt(t){return uo[t]}function mo(t){return t?Ft.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Ft}function jr(t){let e=t??Ft,s={};for(let o of e){s[o.category]||(s[o.category]=[]);let i=uo[o.id],r=i?` \u2014 ${i.description}`:"",a=i?.packages.length?` (${i.packages.join(", ")})`:"";s[o.category].push(`${o.id} \u2014 "${o.name}"${r}${a}`)}let n=[];for(let[o,i]of Object.entries(s))n.push(`**${o}**:
|
|
43
|
+
${i.map(r=>` - ${r}`).join(`
|
|
44
44
|
`)}`);return n.join(`
|
|
45
45
|
|
|
46
|
-
`)}function
|
|
46
|
+
`)}function Dr(t){return(t?mo(t):Ft).map(s=>{let n=uo[s.id];return{id:s.id,slug:Qc(s.name),name:s.name,category:s.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var uo,Ft,Qn=I(()=>{"use strict";uo={"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"},"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"},"agent-ui":{description:"World-class agent UX: rich tool cards with streaming logs, approval gates for risky actions, cost badges, plan checklists, contextual suggestions. Optional add-on for chat / agent apps.",tags:["agent","chat","tools","ui","tool-call","approval","agent-ux","streaming"],envVars:[],docsUrl:"https://mistflow.ai/docs/agent-ui",packages:["framer-motion","recharts","clsx","tailwind-merge"],difficulty:"easy"},"code-runner":{description:"Lets the agent run Python on user-uploaded data (CSV analysis, charting, transformations). Stub backend for v1; real sandbox lands later.",tags:["agent","tools","python","sandbox","code","csv","data-analysis","chart"],envVars:[],docsUrl:"https://mistflow.ai/docs/agent-tools",packages:["ai","zod"],difficulty:"medium"}},Ft=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
|
|
47
47
|
|
|
48
48
|
### File Structure
|
|
49
49
|
\`\`\`
|
|
@@ -134,108 +134,7 @@ export async function POST(req: NextRequest) {
|
|
|
134
134
|
3. **From address must match a verified domain** or use onboarding@resend.dev for testing.
|
|
135
135
|
4. **Webhooks need a public URL.** Use ngrok or similar for local webhook testing.
|
|
136
136
|
5. **React Email templates must be Server Components.** Do not add "use client" to email templates.
|
|
137
|
-
6. **Never ask the user to paste RESEND_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"
|
|
138
|
-
|
|
139
|
-
Files are stored in Mistflow Cloud's managed blob storage. No extra setup needed for Mistflow-deployed apps.
|
|
140
|
-
|
|
141
|
-
### File Structure
|
|
142
|
-
\`\`\`
|
|
143
|
-
lib/storage.ts \u2014 Upload/download helpers
|
|
144
|
-
app/api/upload/route.ts \u2014 Upload API route (server-side)
|
|
145
|
-
components/file-upload.tsx \u2014 Drag-and-drop upload component
|
|
146
|
-
\`\`\`
|
|
147
|
-
|
|
148
|
-
### Upload API Route (app/api/upload/route.ts)
|
|
149
|
-
\`\`\`typescript
|
|
150
|
-
import { NextRequest, NextResponse } from "next/server";
|
|
151
|
-
|
|
152
|
-
export async function POST(req: NextRequest) {
|
|
153
|
-
const formData = await req.formData();
|
|
154
|
-
const file = formData.get("file") as File;
|
|
155
|
-
if (!file) return NextResponse.json({ error: "No file provided" }, { status: 400 });
|
|
156
|
-
|
|
157
|
-
// Validate file size (10MB max)
|
|
158
|
-
if (file.size > 10 * 1024 * 1024) {
|
|
159
|
-
return NextResponse.json({ error: "File too large (max 10MB)" }, { status: 400 });
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// Validate MIME type
|
|
163
|
-
const allowedTypes = ["image/jpeg", "image/png", "image/webp", "application/pdf"];
|
|
164
|
-
if (!allowedTypes.includes(file.type)) {
|
|
165
|
-
return NextResponse.json({ error: "File type not allowed" }, { status: 400 });
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
const bytes = await file.arrayBuffer();
|
|
169
|
-
const buffer = Buffer.from(bytes);
|
|
170
|
-
|
|
171
|
-
// Upload to R2 via Mistflow's storage endpoint
|
|
172
|
-
const key = \`uploads/\${Date.now()}-\${file.name.replace(/[^a-zA-Z0-9.-]/g, "_")}\`;
|
|
173
|
-
// Store buffer with key \u2014 implementation depends on R2 binding or S3-compatible client
|
|
174
|
-
// For Mistflow apps: the deploy pipeline auto-configures R2 bindings
|
|
175
|
-
|
|
176
|
-
return NextResponse.json({ url: \`/api/files/\${key}\`, key });
|
|
177
|
-
}
|
|
178
|
-
\`\`\`
|
|
179
|
-
|
|
180
|
-
### Drag-and-Drop Upload Component (components/file-upload.tsx)
|
|
181
|
-
\`\`\`tsx
|
|
182
|
-
"use client";
|
|
183
|
-
import { useState, useCallback } from "react";
|
|
184
|
-
|
|
185
|
-
interface FileUploadProps {
|
|
186
|
-
onUpload: (url: string) => void;
|
|
187
|
-
accept?: string;
|
|
188
|
-
maxSizeMB?: number;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
export function FileUpload({ onUpload, accept = "image/*", maxSizeMB = 10 }: FileUploadProps) {
|
|
192
|
-
const [isDragging, setIsDragging] = useState(false);
|
|
193
|
-
const [uploading, setUploading] = useState(false);
|
|
194
|
-
|
|
195
|
-
const handleUpload = useCallback(async (file: File) => {
|
|
196
|
-
setUploading(true);
|
|
197
|
-
try {
|
|
198
|
-
const formData = new FormData();
|
|
199
|
-
formData.append("file", file);
|
|
200
|
-
const res = await fetch("/api/upload", { method: "POST", body: formData });
|
|
201
|
-
if (!res.ok) throw new Error("Upload failed");
|
|
202
|
-
const { url } = await res.json();
|
|
203
|
-
onUpload(url);
|
|
204
|
-
} finally {
|
|
205
|
-
setUploading(false);
|
|
206
|
-
}
|
|
207
|
-
}, [onUpload]);
|
|
208
|
-
|
|
209
|
-
return (
|
|
210
|
-
<div
|
|
211
|
-
onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
|
|
212
|
-
onDragLeave={() => setIsDragging(false)}
|
|
213
|
-
onDrop={(e) => {
|
|
214
|
-
e.preventDefault();
|
|
215
|
-
setIsDragging(false);
|
|
216
|
-
const file = e.dataTransfer.files[0];
|
|
217
|
-
if (file) handleUpload(file);
|
|
218
|
-
}}
|
|
219
|
-
className={\`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors \${
|
|
220
|
-
isDragging ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50"
|
|
221
|
-
}\`}
|
|
222
|
-
>
|
|
223
|
-
<input type="file" accept={accept} className="hidden" id="file-upload"
|
|
224
|
-
onChange={(e) => { const f = e.target.files?.[0]; if (f) handleUpload(f); }} />
|
|
225
|
-
<label htmlFor="file-upload" className="cursor-pointer">
|
|
226
|
-
{uploading ? "Uploading..." : "Drop a file here or click to browse"}
|
|
227
|
-
</label>
|
|
228
|
-
</div>
|
|
229
|
-
);
|
|
230
|
-
}
|
|
231
|
-
\`\`\`
|
|
232
|
-
|
|
233
|
-
### Common Pitfalls
|
|
234
|
-
1. **Always validate file type and size server-side.** Client-side validation can be bypassed.
|
|
235
|
-
2. **Sanitize filenames.** Strip special characters to avoid path traversal.
|
|
236
|
-
3. **Use unique keys.** Prefix with timestamp or UUID to avoid collisions.
|
|
237
|
-
4. **Set appropriate CORS headers** if the upload API is called from a different origin.
|
|
238
|
-
5. **For Mistflow apps, R2 bindings are auto-configured.** No env vars needed.`},{id:"openai-ai",name:"OpenAI / AI Integration",category:"ai",prompt:`## OpenAI / AI Integration
|
|
137
|
+
6. **Never ask the user to paste RESEND_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"openai-ai",name:"OpenAI / AI Integration",category:"ai",prompt:`## OpenAI / AI Integration
|
|
239
138
|
|
|
240
139
|
### File Structure
|
|
241
140
|
\`\`\`
|
|
@@ -1592,12 +1491,216 @@ export async function searchDocumentsHybrid(query: string, limit = 10) {
|
|
|
1592
1491
|
3. **Do not regenerate embeddings on every render.** Generate on create/update or in an explicit reindex action.
|
|
1593
1492
|
4. **Chunk long content.** Store chunks of 500-1,000 tokens with stable \`sourceType\`, \`sourceId\`, and \`chunkIndex\`.
|
|
1594
1493
|
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).`}
|
|
1494
|
+
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).`},{id:"agent-ui",name:"Agent UI Components",category:"ai",prompt:`## Agent UI Components
|
|
1495
|
+
|
|
1496
|
+
Mistflow ships a small set of React components that give chat / agent apps
|
|
1497
|
+
ChatGPT-grade tool-call rendering by default. When this integration is
|
|
1498
|
+
selected on a project, \`mist_init\` writes them to \`components/agent/\` and
|
|
1499
|
+
adds the runtime deps to \`package.json\`. You do NOT generate these files \u2014
|
|
1500
|
+
they are materialized by the scaffold from the monorepo package
|
|
1501
|
+
\`@mistflow-ai/agent-ui-components\`.
|
|
1502
|
+
|
|
1503
|
+
### What lands in the project
|
|
1504
|
+
|
|
1505
|
+
\`\`\`
|
|
1506
|
+
components/agent/
|
|
1507
|
+
ApprovalGate.tsx \u2014 confirmation card before external-write or destructive tool calls
|
|
1508
|
+
CostBadge.tsx \u2014 subtle per-tool-call cost indicator (reads X-Mistflow-Cost-Cents header)
|
|
1509
|
+
PlanSteps.tsx \u2014 staggered checklist for multi-step turns
|
|
1510
|
+
SuggestedPrompts.tsx \u2014 contextual follow-up chips after an assistant turn
|
|
1511
|
+
ToolStream.tsx \u2014 rich tool card: streaming stdout + embedded result + expandable raw args
|
|
1512
|
+
lib/
|
|
1513
|
+
cn.ts \u2014 clsx + tailwind-merge (skipped if already present)
|
|
1514
|
+
agent-types.ts \u2014 canonical AgentEvent union the reducer consumes
|
|
1515
|
+
\`\`\`
|
|
1516
|
+
|
|
1517
|
+
Plus runtime deps: \`framer-motion\`, \`recharts\`, \`clsx\`, \`tailwind-merge\`.
|
|
1518
|
+
|
|
1519
|
+
### Wiring up
|
|
1520
|
+
|
|
1521
|
+
These components are presentation primitives that need a chat-route + reducer
|
|
1522
|
+
to feed them. The recommended pattern:
|
|
1523
|
+
|
|
1524
|
+
1. \`app/api/chat/route.ts\` uses \`ai.textFull({ messages, tools })\` from
|
|
1525
|
+
\`lib/server/ai.ts\` (the standard Mistflow wrapper, which now supports
|
|
1526
|
+
tool calling \u2014 see \`methodologies/model-guide.md\` for the tool loop).
|
|
1527
|
+
|
|
1528
|
+
2. The page-level component uses \`@ai-sdk/react\`'s \`useChat()\` to stream
|
|
1529
|
+
from that route. Map the AI SDK 6 events into the local \`AgentEvent\`
|
|
1530
|
+
reducer state:
|
|
1531
|
+
|
|
1532
|
+
- \`tool-input-available\` -> dispatch \`tool-start\` (status pending/running)
|
|
1533
|
+
- tool result returned (next assistant turn) -> dispatch \`tool-complete\`
|
|
1534
|
+
- \`finish_reason === "tool_calls"\` -> render approvals BEFORE executing
|
|
1535
|
+
side-effectful tools (see ApprovalGate below)
|
|
1536
|
+
|
|
1537
|
+
3. For tools the agent flags with \`riskLevel: "external-write"\` or
|
|
1538
|
+
\`"destructive"\`, the chat route pauses before execution and dispatches
|
|
1539
|
+
\`approval-request\`. \`<ApprovalGate>\` renders. The user clicks
|
|
1540
|
+
Approve/Cancel, the route resumes accordingly.
|
|
1541
|
+
|
|
1542
|
+
### Branding
|
|
1543
|
+
|
|
1544
|
+
Every component reads CSS variables (\`var(--color-accent)\`,
|
|
1545
|
+
\`var(--color-foreground)\`, etc.). Customize branding by editing the project's
|
|
1546
|
+
\`globals.css\` once \u2014 the components re-theme automatically. Do NOT pass
|
|
1547
|
+
per-component color props.
|
|
1548
|
+
|
|
1549
|
+
### Full reference
|
|
1550
|
+
|
|
1551
|
+
See \`methodologies/agent-ui-components.md\` for the prop API of each
|
|
1552
|
+
component, the AgentEvent vocabulary, and a runnable code example of the
|
|
1553
|
+
tool loop.
|
|
1554
|
+
|
|
1555
|
+
### Common pitfalls
|
|
1556
|
+
|
|
1557
|
+
1. **Don't generate these components from scratch.** They already exist on
|
|
1558
|
+
disk after \`mist_init\` \u2014 import from \`components/agent/\`. Generating
|
|
1559
|
+
parallel copies leaves the upgrade path broken.
|
|
1560
|
+
2. **Tool execution lives in the route, not the gateway.** The Mistflow AI
|
|
1561
|
+
gateway forwards tool definitions and surfaces the model's chosen call;
|
|
1562
|
+
your route runs the function and loops with a \`tool\` role message.
|
|
1563
|
+
3. **ApprovalGate must intercept BEFORE the tool runs**, not after. The
|
|
1564
|
+
gate exists to let the user veto a side effect \u2014 once the email's sent,
|
|
1565
|
+
confirmation is theater.`},{id:"code-runner",name:"Code Runner Tool",category:"ai",prompt:`## Code Runner Tool
|
|
1566
|
+
|
|
1567
|
+
A canonical agent tool: the agent decides to run Python (or another language)
|
|
1568
|
+
to analyze user-uploaded data, then renders the result inside a
|
|
1569
|
+
\`<ToolStream>\` card. This preset pairs with \`agent-ui\` \u2014 the components
|
|
1570
|
+
render the tool call; this preset wires the tool definition and the route.
|
|
1571
|
+
|
|
1572
|
+
### V1 scope (stub)
|
|
1573
|
+
|
|
1574
|
+
The route returns canned output. The point of v1 is to demonstrate the full
|
|
1575
|
+
UX loop: model decides to call \`runPython\` -> route returns output ->
|
|
1576
|
+
\`<ToolStream>\` renders the result. Real sandbox execution lands later.
|
|
1577
|
+
When it does, only the \`execute\` function in the route changes; the tool
|
|
1578
|
+
definition, UI rendering, and event flow stay the same.
|
|
1579
|
+
|
|
1580
|
+
### File structure
|
|
1581
|
+
|
|
1582
|
+
\`\`\`
|
|
1583
|
+
lib/tools/run-python.ts \u2014 AI SDK 6 tool({ inputSchema, execute }) definition
|
|
1584
|
+
app/api/chat/route.ts \u2014 chat handler that wires the tool into ai.textFull()
|
|
1585
|
+
\`\`\`
|
|
1586
|
+
|
|
1587
|
+
### Tool definition (lib/tools/run-python.ts)
|
|
1588
|
+
|
|
1589
|
+
\`\`\`typescript
|
|
1590
|
+
import { tool } from "ai";
|
|
1591
|
+
import { z } from "zod";
|
|
1592
|
+
|
|
1593
|
+
export const runPython = tool({
|
|
1594
|
+
description:
|
|
1595
|
+
"Execute Python code in a sandboxed environment. Use for data analysis, " +
|
|
1596
|
+
"transformations, or computations the model can't do directly. Has " +
|
|
1597
|
+
"pandas, numpy, matplotlib available. Returns stdout, stderr, and any " +
|
|
1598
|
+
"files written to /tmp/.",
|
|
1599
|
+
inputSchema: z.object({
|
|
1600
|
+
code: z.string().describe("Python source to run. Multi-line OK."),
|
|
1601
|
+
description: z.string().optional().describe(
|
|
1602
|
+
"One-line plain-English description of what this code does. " +
|
|
1603
|
+
"Surfaced in the ToolStream card."
|
|
1604
|
+
),
|
|
1605
|
+
}),
|
|
1606
|
+
execute: async ({ code, description }) => {
|
|
1607
|
+
// V1 stub: returns canned output. Real sandbox call replaces this.
|
|
1608
|
+
// See methodologies/agent-ui-components.md for the migration path.
|
|
1609
|
+
const lines = code.split("\\n").slice(0, 3).join(" / ");
|
|
1610
|
+
return {
|
|
1611
|
+
stdout: \`# Stub output \u2014 real sandbox not yet wired\\n# code: \${lines}\\n(0, 0)\`,
|
|
1612
|
+
stderr: "",
|
|
1613
|
+
files: [] as string[],
|
|
1614
|
+
durationMs: 120,
|
|
1615
|
+
};
|
|
1616
|
+
},
|
|
1617
|
+
});
|
|
1618
|
+
\`\`\`
|
|
1619
|
+
|
|
1620
|
+
### Chat route (app/api/chat/route.ts)
|
|
1621
|
+
|
|
1622
|
+
\`\`\`typescript
|
|
1623
|
+
import { ai } from "@/lib/server/ai";
|
|
1624
|
+
import { runPython } from "@/lib/tools/run-python";
|
|
1625
|
+
|
|
1626
|
+
export async function POST(req: Request) {
|
|
1627
|
+
const { messages } = await req.json();
|
|
1628
|
+
|
|
1629
|
+
// Loop until the model is done with tool calls.
|
|
1630
|
+
let turn = messages;
|
|
1631
|
+
while (true) {
|
|
1632
|
+
const result = await ai.textFull({
|
|
1633
|
+
role: "chat",
|
|
1634
|
+
messages: turn,
|
|
1635
|
+
tools: [
|
|
1636
|
+
// The AI SDK tool() returns the SDK shape; convert to OpenAI shape
|
|
1637
|
+
// for the Mistflow wrapper. (Phase 2 of the gateway streams natively
|
|
1638
|
+
// and this conversion goes away.)
|
|
1639
|
+
{
|
|
1640
|
+
type: "function",
|
|
1641
|
+
function: {
|
|
1642
|
+
name: "runPython",
|
|
1643
|
+
description: runPython.description ?? "",
|
|
1644
|
+
parameters: runPython.inputSchema as Record<string, unknown>,
|
|
1645
|
+
},
|
|
1646
|
+
},
|
|
1647
|
+
],
|
|
1648
|
+
});
|
|
1649
|
+
|
|
1650
|
+
// No tool calls -> we're done; return the assistant turn.
|
|
1651
|
+
if (!result.toolCalls?.length) {
|
|
1652
|
+
return Response.json({ ...result, messages: turn });
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
// Append the assistant's tool calls, then execute and append the
|
|
1656
|
+
// tool-role results.
|
|
1657
|
+
turn = [
|
|
1658
|
+
...turn,
|
|
1659
|
+
{ role: "assistant", content: result.text, tool_calls: result.toolCalls },
|
|
1660
|
+
];
|
|
1661
|
+
for (const call of result.toolCalls) {
|
|
1662
|
+
const args = JSON.parse(call.function.arguments);
|
|
1663
|
+
const output = await runPython.execute(args);
|
|
1664
|
+
turn.push({
|
|
1665
|
+
role: "tool",
|
|
1666
|
+
tool_call_id: call.id,
|
|
1667
|
+
content: JSON.stringify(output),
|
|
1668
|
+
});
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
\`\`\`
|
|
1673
|
+
|
|
1674
|
+
### Pairing with agent-ui
|
|
1675
|
+
|
|
1676
|
+
The page-level component uses \`@ai-sdk/react\`'s \`useChat()\` against
|
|
1677
|
+
\`/api/chat\` and renders each tool call with \`<ToolStream>\` from
|
|
1678
|
+
\`components/agent/ToolStream.tsx\`. See
|
|
1679
|
+
\`methodologies/agent-ui-components.md\` for the end-to-end tool-loop recipe.
|
|
1680
|
+
|
|
1681
|
+
### When to mark the tool as needing approval
|
|
1682
|
+
|
|
1683
|
+
\`runPython\` is generally safe \u2014 it's sandboxed. Mark a tool with
|
|
1684
|
+
\`riskLevel: "external-write"\` only when it writes outside the sandbox
|
|
1685
|
+
(sends email, calls an external API, persists to the user's DB). The
|
|
1686
|
+
\`<ApprovalGate>\` component reads that level and pauses execution before
|
|
1687
|
+
the tool fires.
|
|
1688
|
+
|
|
1689
|
+
### Common pitfalls
|
|
1690
|
+
|
|
1691
|
+
1. **Don't return raw code in the tool result.** The tool result should be
|
|
1692
|
+
structured data (stdout, files written, exit code). The agent reads
|
|
1693
|
+
the result; the user sees it through \`<ToolStream>\`.
|
|
1694
|
+
2. **Don't loop forever.** Cap at ~10 tool calls per turn. Models can get
|
|
1695
|
+
stuck; a hard cap is the cheapest safety net.
|
|
1696
|
+
3. **Don't echo user prompts back to the model as tool output.** The model
|
|
1697
|
+
will get confused about whose turn it is. Tool output is OUTPUT from
|
|
1698
|
+
the tool, not from the user.`}]});import{z as Fe}from"zod";import{resolve as Xn}from"path";import{existsSync as Zn,readFileSync as es}from"fs";import{join as ts}from"path";var Xc,Mr,Lr=I(()=>{"use strict";ve();tt();Or();Pe();an();Qn();Xc=Fe.object({action:Fe.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:Fe.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:Fe.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:Fe.object({key:Fe.string(),description:Fe.string().optional(),setupUrl:Fe.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:Fe.string().optional().describe("(share) Short description of what this template builds"),category:Fe.string().optional().describe("(integrations) Filter integrations by category"),integrationId:Fe.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:Fe.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:Fe.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),Mr={name:"mist_project",description:Go,inputSchema:Xc,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!Te())return Me(`${e.action} project state`);switch(e.action){case"get":case"update":return Nr.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let n=Xn(e.projectPath??process.cwd()),o=ts(n,"mistflow.json");if(!Zn(o))return st(n);let i;try{i=JSON.parse(es(o,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return d("No project ID found. Deploy the project first to register it.",!0);try{let a=await no(r,{isTemplate:!0,description:e.templateDescription});return d(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
|
|
1596
1699
|
|
|
1597
1700
|
Anyone can fork it: ${a.share_url}
|
|
1598
1701
|
|
|
1599
1702
|
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 d(l,!0)}}case"integrations":{if(e.integrationId){let
|
|
1703
|
+
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return d(l,!0)}}case"integrations":{if(e.integrationId){let r=qt(e.integrationId);if(!r)return d(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=Bt(r.id);return d(JSON.stringify({integration:{id:r.id,name:r.name,category:r.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${r.name}" (${r.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=Dr(e.category??void 0),o=mo(e.category??void 0),i=jr(o);return d(JSON.stringify({count:n.length,integrations:n.map(r=>({id:r.id,name:r.name,category:r.category,description:r.description,packages:r.packages,difficulty:r.difficulty,envVars:r.envVars.map(a=>a.key)})),formatted:i,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=Xn(e.projectPath??process.cwd()),o=ts(n,"mistflow.json");if(!Zn(o))return st(n);let i;try{i=JSON.parse(es(o,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return d("No project ID found. Deploy the project first.",!0);try{let a=await Gs(r,e.period??"7d");return a.total===0?d(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):d(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return d(l,!0)}}case"logs":{let n=Xn(e.projectPath??process.cwd()),o=ts(n,"mistflow.json");if(!Zn(o))return st(n);let i;try{i=JSON.parse(es(o,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return d("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await Lt(r);if(l.length===0)return d("No deployments found for this project.",!0);a=l[0].id}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return d(c,!0)}try{let[l,c]=await Promise.all([Ws(a),pt(a)]),m=l.filter(u=>u.level==="error"),p=l.filter(u=>u.level==="warn");return d(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:m.length,warnCount:p.length,logs:l.map(u=>({time:u.timestamp,level:u.level,phase:u.phase,message:u.message})),message:c.status==="failed"?`Deployment failed. ${m.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${m.length} errors, ${p.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return d(c,!0)}}case"deployments":{let n=Xn(e.projectPath??process.cwd()),o=ts(n,"mistflow.json");if(!Zn(o))return st(n);let i;try{i=JSON.parse(es(o,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return d("No project ID found. Deploy the project first.",!0);try{let a=await Lt(r);return d(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return d(l,!0)}}case"version":{As().backendSignalReceived||await Ds();let n=As(),o=n.severity==="none",i={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return d(JSON.stringify({current:n.current,latest:n.latest||"unknown",minSupported:n.minSupported||"unknown",severity:n.severity,upToDate:o,upgradeCmd:n.upgradeCmd,changelogUrl:n.changelogUrl,backendSignalReceived:n.backendSignalReceived,message:n.backendSignalReceived?`Mistflow MCP ${n.current} (${i[n.severity]??n.severity}). Latest: ${n.latest}.${o?"":` Run \`${n.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${n.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return d(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, or version.`,!0)}}}});import{z as Rt}from"zod";var Zc,$r,Ur=I(()=>{"use strict";tt();ve();Dt();Zc=Rt.object({action:Rt.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:Rt.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Rt.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:Rt.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:Rt.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Rt.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),$r={name:"mist_browser",description:Vo,inputSchema:Zc,handler:async t=>{let e=t,s=await Rs();if(e.action==="navigate"){if(!e.url)return d("URL is required for 'navigate'.",!0);let i=[],r=c=>{c.type()==="error"&&i.push(c.text())};s.on("console",r),await s.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await s.waitForLoadState("networkidle").catch(()=>{});let a=[],l=c=>a.push(c.message);if(s.on("pageerror",l),await s.waitForTimeout(500),s.removeListener("console",r),s.removeListener("pageerror",l),i.length>0||a.length>0){let c=await ln(s),m=[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),snapshot:c,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let p=await cn(s);m.push({type:"image",data:p.toString("base64"),mimeType:"image/png"})}return{content:m}}}else if(e.action==="go_back")await s.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await s.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return d("Selector is required for 'click'.",!0);await s.click(e.selector,{timeout:1e4}),await s.waitForLoadState("domcontentloaded").catch(()=>{}),await s.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return d("Selector is required for 'type'.",!0);if(!e.value)return d("Value is required for 'type'.",!0);await s.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return d("Selector is required for 'fill'.",!0);if(!e.value)return d("Value is required for 'fill'.",!0);await s.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return d("Selector is required for 'select_option'.",!0);if(!e.value)return d("Value is required for 'select_option'.",!0);await s.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return d("Selector is required for 'hover'.",!0);await s.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await s.keyboard.press(e.value),await s.waitForLoadState("domcontentloaded").catch(()=>{}),await s.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await s.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await s.waitForLoadState("networkidle").catch(()=>{}));let i;if(e.selector){let r=await s.$(e.selector);if(!r)return d(`Element not found: ${e.selector}`,!0);i=await r.screenshot({type:"png"})}else i=await cn(s,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let i=await ln(s);return{content:[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),snapshot:i})}]}}let n=await ln(s),o=[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),snapshot:n})}];if(e.includeScreenshot){let i=await cn(s);o.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:o}}}});import{z as Fr}from"zod";var qr,Br,zr=I(()=>{"use strict";tt();ve();qr=`# Mistflow MCP tool reference
|
|
1601
1704
|
|
|
1602
1705
|
Every capability is an MCP tool. There is no companion CLI. Long-running tools
|
|
1603
1706
|
(install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
|
|
@@ -1914,27 +2017,27 @@ is cheaper than building the wrong thing and iterating.
|
|
|
1914
2017
|
|
|
1915
2018
|
mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
|
|
1916
2019
|
mist_deploy({ action: "status", deploymentId }) # poll
|
|
1917
|
-
`,
|
|
1918
|
-
`),
|
|
1919
|
-
`).trim())}}});import{z as
|
|
2020
|
+
`,Br={name:"mist_help",description:Ko,inputSchema:Fr.object({command:Fr.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return d(qr);let s=e.startsWith("mist_")?e:`mist_${e}`,n=qr.split(`
|
|
2021
|
+
`),o=new RegExp(`^### \`${s}`),i=-1,r=n.length;for(let a=0;a<n.length;a++)if(o.test(n[a]))i=a;else if(i>=0&&n[a].startsWith("### ")){r=a;break}else if(i>=0&&n[a].startsWith("## ")&&a>i){r=a;break}return i<0?d(`No tool named '${s}' found. Call mist_help with no args to see the full catalog.`,!0):d(n.slice(i,r).join(`
|
|
2022
|
+
`).trim())}}});import{z as bn}from"zod";var Hr,Wr,Gr=I(()=>{"use strict";tt();Pe();ve();Hr=bn.object({action:bn.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:bn.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:bn.enum(["stack","skill","integration"]).optional().describe("Optional filter for action='list'. 'stack' = framework methodology, 'skill' = design + structural patterns, 'integration' = third-party services."),stack:bn.string().optional().default("nextjs").describe("Stack slug. Defaults to 'nextjs' (currently the only supported stack).")}),Wr={name:"mist_docs",description:Jo,inputSchema:Hr,handler:async t=>{let{action:e,topic:s,kind:n,stack:o}=Hr.parse(t);try{if(e==="list"){let a=await Qs(o,n),l=[];l.push(`# Mistflow docs catalog (${a.stack})
|
|
1920
2023
|
${a.topics.length} topics. Call \`mist_docs({ action: "get", topic: "<id>" })\` to fetch one.
|
|
1921
|
-
`);let c={};for(let p of a.topics)(c[p.kind]??=[]).push(p);let m=["stack","skill","integration"];for(let p of m){let u=c[p];if(!(!u||u.length===0)){l.push(`## ${p}`);for(let
|
|
1922
|
-
`).trim())}if(!
|
|
1923
|
-
# ${
|
|
2024
|
+
`);let c={};for(let p of a.topics)(c[p.kind]??=[]).push(p);let m=["stack","skill","integration"];for(let p of m){let u=c[p];if(!(!u||u.length===0)){l.push(`## ${p}`);for(let g of u)l.push(`- **${g.id}** \u2014 ${g.title}: ${g.description}`);l.push("")}}return d(l.join(`
|
|
2025
|
+
`).trim())}if(!s)return d("Missing `topic`. Pass action='get' with a topic id, or action='list' to see available topics.",!0);let i=await Xs(o,s),r=`<!-- mist_docs: topic=${i.topic} kind=${i.kind} stack=${i.stack} -->
|
|
2026
|
+
# ${i.title}
|
|
1924
2027
|
|
|
1925
|
-
${
|
|
2028
|
+
${i.description}
|
|
1926
2029
|
|
|
1927
2030
|
---
|
|
1928
2031
|
|
|
1929
|
-
`;return d(
|
|
2032
|
+
`;return d(r+i.content)}catch(i){if(i instanceof X&&i.statusCode===404)return d(i.message,!0);let r=i instanceof Error?i.message:String(i);return d(`mist_docs failed: ${r}
|
|
1930
2033
|
|
|
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
|
|
1932
|
-
**${
|
|
1933
|
-
`)}function
|
|
1934
|
-
${
|
|
1935
|
-
Recommended: ${
|
|
1936
|
-
`)}function
|
|
1937
|
-
`),
|
|
2034
|
+
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 ns,mkdirSync as Jr,readFileSync as Yr,readdirSync as Qr,writeFileSync as ed}from"fs";import{join as ht,resolve as td}from"path";import{homedir as go}from"os";import{z as wn}from"zod";function zt(t){return t.entity??t.name??"Unknown"}function Ht(t){return typeof t=="string"?t:t.name}function ho(t){return typeof t=="string"?"text":t.type}function Vr(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(o=>{let i={};for(let[r,a]of Object.entries(o))i[r]=a==null?"":String(a);return i});let s=t.fields||[],n=[];for(let o=0;o<3;o++){let i={};for(let r of s)i[Ht(r)]=nd(Ht(r),ho(r),zt(t),o);n.push(i)}return n}function nd(t,e,s,n){let o=t.toLowerCase(),i=(e||"text").toLowerCase();return o==="name"||o==="title"?[`${s} Alpha`,`${s} Beta`,`${s} Gamma`][n]:o==="email"?["alice@example.com","bob@example.com","carol@example.com"][n]:o==="status"?["Active","Pending","Completed"][n]:o==="priority"?["High","Medium","Low"][n]:o.includes("date")||i==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][n]:o.includes("price")||o.includes("amount")||o.includes("cost")?["$29","$49","$99"][n]:o.includes("count")||o.includes("quantity")||i==="number"||i==="integer"?["12","34","56"][n]:i==="boolean"||i==="bool"?["Yes","No","Yes"][n]:o.includes("description")||i==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function sd(t){let e=t.dataModel??[],s=t.pages??[],n=t.design??{},o=s.map(p=>({label:p.name??p.path??"Page",route:p.path??p.route??"/"})),i=[],r=e.slice(0,3).map(p=>({name:zt(p),fields:(p.fields||[]).map(u=>({name:Ht(u),type:ho(u)})),sampleData:Vr(p)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(p=>zt(p)).join(", ")}`),a.push("RECENT: Latest activity or items"),i.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(p=>zt(p)).join(", ")} with key metrics.`,informationHierarchy:a,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:r});let l=e[0];if(l){let p=zt(l),u=p.toLowerCase().endsWith("s")?p:`${p}s`;i.push({name:`${p} List`,type:"detail",route:`/${u.toLowerCase()}`,purpose:`Browse, search, and manage ${u.toLowerCase()}. Create new ${p.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${u}" title + "Add ${p}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(g=>Ht(g)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${u.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${u.toLowerCase()} matching..." with clear filter`],entities:[{name:p,fields:(l.fields||[]).map(g=>({name:Ht(g),type:ho(g)})),sampleData:Vr(l)}]})}t.steps.some(p=>{let u=`${p.name??p.title??""} ${p.description??""}`.toLowerCase();return u.includes("landing")||u.includes("hero")||u.includes("marketing")||u.includes("homepage")})&&i.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let m=[];for(let p of e.slice(0,3)){let u=zt(p);(p.fields||[]).find(D=>{let _=Ht(D).toLowerCase();return _==="name"||_==="title"})&&m.push(`What if a ${u.toLowerCase()}'s name is 47 characters? Does the layout break?`),m.push(`What if there are 0 ${u.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&m.push("What does a brand-new user see? (no data, no setup)"),m.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:i,navigation:{style:t.navStyle??"sidebar",items:o},primaryAction:t.primaryAction??null,designDirection:{tone:n.tone??"professional",accentColor:n.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:n.fonts??{heading:"Inter",body:"Inter"}},edgeCases:m}}function od(t,e,s){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 \`${s}\`.`),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 o of t.screens){n.push(`### ${o.name} (\`${o.route}\`)`),n.push(`**Purpose**: ${o.purpose}`),n.push(""),n.push("**Information hierarchy** (render in this order, top to bottom):");for(let i of o.informationHierarchy)n.push(`- ${i}`);n.push(""),n.push("**Interaction states** (add HTML comments for non-visible states):");for(let i of o.interactionStates)n.push(`- ${i}`);if(n.push(""),o.entities.length>0){n.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let i of o.entities)n.push(`
|
|
2035
|
+
**${i.name}** \u2014 fields: ${i.fields.map(r=>`${r.name} (${r.type})`).join(", ")}`),n.push("```json"),n.push(JSON.stringify(i.sampleData,null,2)),n.push("```");n.push("")}}n.push("## Navigation"),n.push(`**Style**: ${t.navigation.style} (use this layout)`),n.push("**Items**:");for(let o of t.navigation.items)n.push(`- ${o.label} \u2192 \`${o.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 o of t.edgeCases)n.push(`- ${o}`);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 \`${s}\``),n.push(`2. Open it for the user: \`open "${s}"\``),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(`
|
|
2036
|
+
`)}function Xr(t){return ht(go(),".mistflow","mockup-state",`${t}.json`)}function rd(t){let e=Xr(t);if(!ns(e))return null;try{return JSON.parse(Yr(e,"utf-8"))}catch{return null}}function Kr(t,e){let s=ht(go(),".mistflow","mockup-state");Jr(s,{recursive:!0}),ed(Xr(t),JSON.stringify(e,null,2))}function ei(t){let e=ht(t,".mistflow","mockups");return ns(e)?Qr(e).filter(s=>s.endsWith(".html")).map(s=>ht(e,s)):[]}var id,Zr,fo=I(()=>{"use strict";tt();ve();id=wn.object({planId:wn.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:wn.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:wn.string().optional().describe("User feedback to apply to the next iteration."),approved:wn.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."}),Zr={name:"mist_mockup",description:Qo,inputSchema:id,handler:async t=>{let e=t,{planId:s,feedback:n,approved:o}=e,i=td(e.projectPath??process.cwd()),r=ht(go(),".mistflow","plans",`${s}.json`);if(!ns(r))return d(`Plan not found for planId '${s}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(Yr(r,"utf-8"))}catch{return d("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return d("Plan data is empty. Call mist_plan again.",!0);let c=rd(s);c||(c={planId:s,iterationCount:0,approved:!1,screens:[],feedback:[]});let m=ht(i,".mistflow","mockups");Jr(m,{recursive:!0});let p=`mockup-${s}.html`,u=ht(m,p);if(o){c.approved=!0,Kr(s,c);let v=ns(m)?Qr(m).filter(R=>R.endsWith(".html")).map(R=>ht(".mistflow","mockups",R)):[];return d(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:v,nextAction:`Call mist_init with planId='${s}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}c.iterationCount++,n&&c.feedback.push(n);let g=sd(l);c.screens=g.screens.map(v=>v.name),Kr(s,c);let D=od(g,n??void 0,u),_=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,x=n?`Apply the user's feedback to ${u}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${u}, then open it in the browser. Ask the user if the layout feels right.`;return d(JSON.stringify({status:"wireframe",requires_user_input:!0,iterationCount:c.iterationCount,screens:g.screens.map(v=>({name:v.name,type:v.type,route:v.route})),wireframePrompt:D,designDirection:g.designDirection,..._?{nudge:_}:{},mockupFile:p,mockupPath:u,nextAction:x}))}}});function ss(t){let e=[],s=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(s)){let[,l,c,m,p,u]=a;e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:`${p}: ${u}`,humanMessage:`There is a type error in ${l} on line ${c}: ${u}`,suggestion:`Check line ${c} in ${l}. ${p==="TS2345"?"The types of the arguments do not match.":`Fix the ${p} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(n)){let[,l,c,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(c,10))||e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:p,humanMessage:`There is an error in ${l} on line ${c}: ${p.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let o=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of t.matchAll(o)){let[,l,c]=a;e.push({file:c,message:`Module not found: ${l}`,humanMessage:`The file ${c??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let i=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(i)){let[,l,c]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${c}${l}`,humanMessage:`The package '${c}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${c}'.`,suggestion:`Add '${c}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let r=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of t.matchAll(r)){let[,l,c,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(m,10))||e.push({file:l,line:parseInt(m,10),column:parseInt(p,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${m}.`,suggestion:`Check line ${m} in ${l} for a missing closing bracket or unexpected token.`})}return e}var yo=I(()=>{"use strict"});import{z as bo}from"zod";import{resolve as ad}from"path";import{spawn as ld}from"child_process";function dd(t){return new Promise(e=>{let s=ld("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),n="";s.stdout?.on("data",o=>{n+=o.toString()}),s.stderr?.on("data",o=>{n+=o.toString()}),s.on("error",o=>{e({exitCode:127,combined:`${n}
|
|
2037
|
+
${o.message}`})}),s.on("close",o=>{e({exitCode:o??1,combined:n})})})}var cd,ti,ni=I(()=>{"use strict";tt();ve();yo();cd=bo.object({projectPath:bo.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:bo.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});ti={name:"mist_debug",description:Yo,inputSchema:cd,handler:async t=>{let e=t,s=ad(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let r=await dd(s);if(r.exitCode===0)return d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=r.combined}let o=ss(n),i=n.slice(0,2e3);return o.length===0?d(JSON.stringify({errors:o,rawOutput:i,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):d(JSON.stringify({errors:o,rawOutput:i,message:`Found ${o.length} error${o.length===1?"":"s"} in the build output.`}))}}});import{spawn as pd}from"child_process";function wo(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(ud())return{opened:!1,reason:"headless environment detected"};let s=process.platform,n,o;s==="darwin"?(n="open",o=[e.href]):s==="win32"?(n="cmd",o=["/c","start","",e.href]):(n="xdg-open",o=[e.href]);try{let i=pd(n,o,{shell:!1,stdio:"ignore",detached:!0});return i.on("error",()=>{}),i.unref(),{opened:!0}}catch(i){return{opened:!1,reason:i instanceof Error?i.message:"spawn failed"}}}function ud(){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 si=I(()=>{"use strict"});function Ve(t,e,s,n=3e3){if(e===void 0)return{stop:()=>{}};let o=0,i=!1,a=setInterval(()=>{i||(o++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:o,message:s()}}).catch(()=>{}))},n);return{stop:()=>{i||(i=!0,clearInterval(a))}}}var Wt=I(()=>{"use strict"});function md(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function hd(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function gd(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function fd(t){let e={},s=[],n=[],o=new Set;for(let i=0;i<t.length;i++){let r=t[i],a=r.decisionKey?gd(r.decisionKey):`q_${i+1}`,l=a,c=2;for(;o.has(l);)l=`${a}_${c}`,c++;o.add(l);let m=r.freetext?"":`${l}_other`;if(m&&o.add(m),n.push({primary:l,other:m,question:r}),r.freetext){e[l]={type:"string",title:r.question,description:r.why,...r.recommended?{default:r.recommended}:{}},s.push(l);continue}let p=(r.options??[]).map(g=>typeof g=="string"?g:g.label),u=r.noOtherSentinel?[...p]:[...p,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:r.question,description:r.why?`${r.why}${r.recommended?`
|
|
2038
|
+
Recommended: ${r.recommended}`:""}`:r.recommended?`Recommended: ${r.recommended}`:void 0,enum:u,enumNames:u,...r.recommended&&p.includes(r.recommended)?{default:r.recommended}:{}},s.push(l),e[m]={type:"string",title:r.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:s},fieldKeys:n}}function yd(t,e){let s=[],n;for(let{primary:o,other:i,question:r}of e){let a=String(t[o]??"").trim(),l;if(r.freetext)l=a||r.recommended||"";else{let m=i?String(t[i]??"").trim():"",p=a.toLowerCase(),u=p.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(p);m?l=m:u?l=r.recommended??(r.options?.[0]&&typeof r.options[0]=="object"?r.options[0].label:"")??a:l=a}let c=r.decisionKey??"";if(c==="urlChoice"){n=l;continue}s.push({question:r.question,decisionKey:c,answer:l})}return{answers:s,urlChoice:n}}function ot(t,e,s){let n;switch(s.outcome){case"submitted":n=`submitted (${s.answers?.length??0} answers${s.urlChoice?`, urlChoice="${s.urlChoice}"`:""})`;break;case"error":n=`error (${s.errorMessage??"unknown"})`;break;case"unsupported":n=`unsupported (${e})`;break;default:n=s.outcome}console.error(`[mist_plan] elicitation/${t}: ${n}`)}async function vn(t,e,s,n="discovery"){if(hd()){let m={outcome:"unsupported"};return ot(n,"MISTFLOW_ELICITATION kill switch on",m),m}if(!md(t)){let m={outcome:"unsupported"};return ot(n,"client did not declare elicitation capability",m),m}if(e.length===0){let m={outcome:"submitted",answers:[]};return ot(n,"no questions to ask",m),m}let{schema:o,fieldKeys:i}=fd(e),r;try{r=await t.elicitInput({message:s,requestedSchema:o,mode:"form"},{timeout:300*1e3})}catch(m){let p=m instanceof Error?m.message:String(m);if(p.toLowerCase().includes("not support")){let g={outcome:"unsupported"};return ot(n,`SDK rejected form mode: ${p}`,g),g}let u={outcome:"error",errorMessage:p};return ot(n,"",u),u}if(r.action==="decline"){let m={outcome:"declined"};return ot(n,"",m),m}if(r.action==="cancel"){let m={outcome:"cancelled"};return ot(n,"",m),m}if(r.action!=="accept"||!r.content){let m={outcome:"error",errorMessage:`Unexpected elicitation result: ${r.action}`};return ot(n,"",m),m}let{answers:a,urlChoice:l}=yd(r.content,i),c={outcome:"submitted",answers:a,urlChoice:l};return ot(n,"",c),c}var oi=I(()=>{"use strict"});function ri(t,e,s){let n=s?.suggestedName||wd(t),o=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",i=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),r=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",a;if(s?.suggestedFeatures&&s.suggestedFeatures.length>0)a=s.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 bd){let m=c.keywords.test(l),p=c.condition(e);(m||p)&&a.push({name:c.name,description:c.description,checked:m,source:m?"explicit":"suggested"})}}return{name:n,audience:o,audienceType:i,surfaceType:r,primaryAction:e.primaryAction||"manage items",features:a,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:s?.language||"English"}}function ii(t){let e=t.features.filter(a=>a.checked),s=t.features.filter(a=>!a.checked),n={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},o={neon:"Postgres",turso:"SQLite (legacy)"},i={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},r=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${i[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${n[t.authModel]??t.authModel} | Database: ${o[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){r.push("**Included:**");for(let a of e)r.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(r.push(""),r.push(`**Integrations:** ${t.integrations.join(", ")}`)),s.length>0){r.push(""),r.push("**Available to add:**");for(let a of s)r.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return r.join(`
|
|
2039
|
+
`)}function wd(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return os(e[1]);let s=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"]),o=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(i=>i.length>2&&!s.has(i)).slice(0,3);return o.length===0?"my-app":o.join("-")}function os(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var bd,ai=I(()=>{"use strict";bd=[{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 vo(t,e,s){let n=kn(t||"your app"),o=e.map((r,a)=>{let l=rs(r.id||`direction-${a}`),c=kn(r.name||`Direction ${a+1}`),m=kn(r.summary||"");return`<button class="tab${a===0?" active":""}" data-target="${l}" type="button"><span class="tab-name">${c}</span>${m?`<span class="tab-sub">${m}</span>`:""}</button>`}).join(`
|
|
2040
|
+
`),i=e.map((r,a)=>{let l=rs(r.id||`direction-${a}`),c=s[r.id??""]??"";return`<iframe class="render-frame${a===0?" active":""}" data-id="${l}" srcdoc="${rs(c)}" sandbox="allow-same-origin allow-scripts" title="${rs(r.name||`Direction ${a+1}`)}"></iframe>`}).join(`
|
|
1938
2041
|
`);return`<!doctype html>
|
|
1939
2042
|
<html lang="en">
|
|
1940
2043
|
<head>
|
|
@@ -2017,13 +2120,13 @@ Recommended: ${s.recommended}`:""}`:s.recommended?`Recommended: ${s.recommended}
|
|
|
2017
2120
|
<body>
|
|
2018
2121
|
<header class="picker-bar">
|
|
2019
2122
|
<div class="picker-title"><strong>${n}</strong> \u2014 pick a design direction</div>
|
|
2020
|
-
<div class="tabs">${
|
|
2123
|
+
<div class="tabs">${o}</div>
|
|
2021
2124
|
</header>
|
|
2022
2125
|
<div class="frames">
|
|
2023
|
-
${
|
|
2126
|
+
${i}
|
|
2024
2127
|
</div>
|
|
2025
2128
|
<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?
|
|
2129
|
+
<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?kn(e[0].name):"Morning Paper"}</em>”).</div>
|
|
2027
2130
|
<div><strong>None fit?</strong> Tell your assistant <code>describe your own</code> and give a short description.</div>
|
|
2028
2131
|
</footer>
|
|
2029
2132
|
<script>
|
|
@@ -2041,38 +2144,791 @@ ${o}
|
|
|
2041
2144
|
</script>
|
|
2042
2145
|
</body>
|
|
2043
2146
|
</html>
|
|
2044
|
-
`}function
|
|
2045
|
-
`)})}function
|
|
2046
|
-
Reason: ${t.reason}`:"";switch(t.state){case"COMPLETE":return`Session complete.${e?` Live URL: ${e}`:""}${
|
|
2047
|
-
`));case"resume_conversation":{let
|
|
2048
|
-
`))}case"continue":return d([...f,`Next action: ${
|
|
2049
|
-
`));case"call_mist_init":return d([...f,
|
|
2050
|
-
`));case"call_mist_deploy":return d([...f,
|
|
2051
|
-
`));case"
|
|
2052
|
-
`));case"
|
|
2053
|
-
`))
|
|
2054
|
-
|
|
2055
|
-
`)
|
|
2056
|
-
`)
|
|
2147
|
+
`}function kn(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function rs(t){return kn(t)}var li=I(()=>{"use strict"});import{z as L}from"zod";import{existsSync as rt,mkdirSync as Nt,readFileSync as xn,readdirSync as gi,statSync as fi,unlinkSync as vd,writeFileSync as gt}from"fs";import{dirname as kd,isAbsolute as xd,join as ye}from"path";import{homedir as ft,hostname as ci}from"os";import{createHash as Sd,createHmac as yi,randomBytes as Td,randomUUID as di,timingSafeEqual as _d}from"crypto";function bi(){let t=ye(ft(),".mistflow","confirm-secret");if(rt(t))try{return Buffer.from(xn(t,"utf-8").trim(),"hex")}catch{}let e=Td(32);return Nt(ye(ft(),".mistflow"),{recursive:!0}),gt(t,e.toString("hex"),{mode:384}),e}function wi(t){return Sd("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function Pd(t,e){let s={cwd:t,d:wi(e),exp:Date.now()+Id},n=Buffer.from(JSON.stringify(s)).toString("base64url"),o=yi("sha256",bi()).update(n).digest("base64url");return`${n}.${o}`}function Cd(t,e,s){let n=t.split(".");if(n.length!==2)return!1;let[o,i]=n,r=yi("sha256",bi()).update(o).digest("base64url"),a=Buffer.from(i),l=Buffer.from(r);if(a.length!==l.length||!_d(a,l))return!1;try{let c=JSON.parse(Buffer.from(o,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==e||c.d!==wi(s))}catch{return!1}}function Ad(t){let e=t,s=ft(),n=!1;for(let o=0;o<64;o++){if(rt(ye(e,"mistflow.json")))return"mistflow";if(!n&&rt(ye(e,"package.json"))&&(n=!0),e===s)break;let i=kd(e);if(i===e)break;e=i}return n?"foreign":"none"}function Rd(t){let e=ft(),s=t.replace(/\/+$/,"");if(s===e||s==="/"||s===""||s==="/tmp"||s==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let o of n)if(s===ye(e,o))return!0;return!1}function Ed(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 pi(t){if(!rt(t))return!0;try{return fi(t).isDirectory()?gi(t).filter(n=>n!==".mistflow").length===0:!1}catch{return!1}}function Nd(t,e){let s=Ed(e),n=ye(t,s);if(pi(n))return n;for(let o=2;o<=50;o++){let i=ye(t,`${s}-${o}`);if(pi(i))return i}return ye(t,`${s}-${Date.now()}`)}function Od(t,e){if(e)return!0;let s=t.toLowerCase(),n=/\b(build|create|make|scaffold|start|generate)\b/.test(s),o=/\b(app|application|website|site|web\s+app|landing\s+page|dashboard|tool|marketplace|game|blog|portfolio|crm)\b/.test(s),i=/\b(add|change|fix|update|edit|refactor|debug|review)\b/.test(s)&&!n;return n&&o&&!i}function ui(t){try{Nt(t,{recursive:!0});return}catch(e){return e instanceof Error?e.message:String(e)}}function mi(t){let{projectPath:e,description:s,confirmToken:n,suggestedPath:o,previousTokenInvalid:i}=t;return JSON.stringify({status:"confirm_new_project",requires_user_input:!0,projectPath:e,description:s,confirmToken:n,suggestedScaffoldPath:o,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 \`${o}\` 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 \`${o}\`. 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.",i?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
2148
|
+
`)})}function Dd(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,o]of e)if(n.test(t))return o;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 Md(t){let e=ye(ft(),".mistflow","plans",`${t}.json`);if(!rt(e))return null;try{return JSON.parse(xn(e,"utf-8")).plan??null}catch{return null}}async function Ld(t){let e=Date.now(),s=5e4,n=2e3;for(;Date.now()-e<s;){try{let o=await qn(t.design_conversation_id);if(o.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:o.directions,plan:o.plan,methodology:o.methodology};if(o.status==="failed")return{status:"ready",plan:o.plan,methodology:o.methodology}}catch(o){let i=o instanceof Error?o.message:String(o);if(i.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll failed: ${i}`)}await new Promise(o=>setTimeout(o,n))}return console.error("[plan] directions poll exhausted (50s) \u2014 preserving pending so host re-polls"),t}function $d(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function Ud(t,e){for(let s of e){let n=$d(t[s]);if(n)return n}}function Fd(t){return Ud(t,["mockup_url","mockupUrl","preview_url","previewUrl","live_url","liveUrl","deploy_url","deployUrl","url"])}function Et(t,e){return`Next action: call ${t} with ${JSON.stringify(e)}. Do not omit sessionId.`}function hi(t){return t?.length?t.map((e,s)=>{let n=typeof e.text=="string"?e.text:typeof e.question=="string"?e.question:`Question ${s+1}`,o=Array.isArray(e.options)?e.options.map(i=>{if(i&&typeof i=="object"&&"label"in i){let r=i.label;return typeof r=="string"?r:null}return typeof i=="string"?i:null}).filter(i=>!!i):[];return o.length?`${s+1}. ${n} Options: ${o.join(", ")}`:`${s+1}. ${n}`}):["No questions were returned by the backend."]}function qd(t){let e=Fd(t),s=t.reason?`
|
|
2149
|
+
Reason: ${t.reason}`:"";switch(t.state){case"COMPLETE":return`Session complete.${e?` Live URL: ${e}`:""}${s}`;case"CANCELLED":return`Session was cancelled.${s}`;case"FAILED":return`Session ended in FAILED.${e?` Last known URL: ${e}`:""}${s}`;case"ABANDONED":return`Session was abandoned.${s}`;case"EXPIRED":return`Session expired.${s}`;default:return`Session finished with state ${t.state}.${e?` URL: ${e}`:""}${s}`}}async function Bd(t,e){let{description:s,projectPath:n,sessionId:o,conversationId:i,answers:r,existingPlan:a,existingPlanId:l,templateToken:c,remixDescription:m,autonomous:p,language:u,brandMentioned:g,confirmToken:D,urlChoice:_,designConversationId:x,designDirection:v,userConfirmedCustom:R,forceNew:G}=t;if(o&&!i&&!x)try{let h=await Ut(o),f=[`Session ID: ${h.session_id}`,`Status: ${h.status??"active"}`,`Instruction: ${h.instruction}`];switch(h.reason&&f.push(`Reason: ${h.reason}`),h.instruction){case"wait":return d([...f,`Next action: ${h.reason??"The backend is still preparing the next step."} Tell the user briefly what's happening, then call mist_plan with { projectPath, sessionId: "${h.session_id}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`].join(`
|
|
2150
|
+
`));case"resume_conversation":{let w=h.conversation_id;return d([...f,`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(`
|
|
2151
|
+
`))}case"continue":return d([...f,`Next action: ${h.reason??"Continue from where you left off \u2014 read mistflow.json to find the next pending step, then call mist_install / mist_implement / mist_build / mist_deploy as appropriate."}`].join(`
|
|
2152
|
+
`));case"call_mist_init":return d([...f,Et("mist_init",{sessionId:h.session_id,path:n})].join(`
|
|
2153
|
+
`));case"call_mist_deploy":return d([...f,Et("mist_deploy",{sessionId:h.session_id,projectPath:n})].join(`
|
|
2154
|
+
`));case"ask_user":return d([...f,"Next action: ask the user these questions, then submit the answers through the session flow.",...hi(h.questions)].join(`
|
|
2155
|
+
`));case"pick_design":return d([...f,"Next action: ask the user to pick one of these design directions, then submit the choice through the session flow.",...hi(h.directions??h.questions)].join(`
|
|
2156
|
+
`));case"review_mockup":return d([...f,Et("mist_mockup",{sessionId:h.session_id,projectPath:n})].join(`
|
|
2157
|
+
`));case"call_mist_install":return d([...f,Et("mist_install",{sessionId:h.session_id,projectPath:n})].join(`
|
|
2158
|
+
`));case"call_mist_implement":return d([...f,Et("mist_implement",{sessionId:h.session_id,projectPath:n})].join(`
|
|
2159
|
+
`));case"call_mist_build":return d([...f,Et("mist_build",{sessionId:h.session_id,projectPath:n})].join(`
|
|
2160
|
+
`));case"call_mist_qa":return d([...f,Et("mist_qa",{sessionId:h.session_id,projectPath:n})].join(`
|
|
2161
|
+
`));case"review_plan":return d([...f,`Next action: ${h.reason??"User asked to review PLAN.md before scaffolding. Open <projectPath>/PLAN.md, let the user read / edit, then call mist_session({ resume }) and re-run mist_init."}`].join(`
|
|
2162
|
+
`));case"done":return d([...f,qd(h)].join(`
|
|
2163
|
+
`))}}catch(h){let f=h instanceof Error?h.message:String(h);return d(`Could not poll session '${o}': ${f}`,!0)}if(i&&!s&&!r&&!x&&!v&&!a&&!l&&!c)try{let h=await Hn(i);if(h.status==="clarify_pending"||h.status==="plan_pending"){let f=typeof h.phase_hint=="string"?h.phase_hint:null,w=typeof h.elapsed_seconds=="number"?h.elapsed_seconds:null,A=typeof h.progress=="number"?h.progress:null,C=h.status==="plan_pending",M=C?"generating_plan":"generating_questions",ne=f?`${f}${w!==null?` (${w}s elapsed)`:""}`:C?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return d(JSON.stringify({status:"running",conversationId:i,phase:M,...f?{phaseHint:f}:{},...w!==null?{elapsedSeconds:w}:{},...A!==null?{progress:A}:{},nextAction:`${ne}. Tell the user briefly what's happening (e.g. "${f??(C?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${i}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}if(h.status==="design_clarify"&&Array.isArray(h.directions)){let w=h.directions.map((T,Se)=>({id:T.id??String(Se),name:T.name??`Direction ${Se+1}`,summary:T.summary,hero_headline:T.hero_headline,cta_text:T.cta_text,body_sample:T.body_sample,fonts:T.fonts,colors:T.colors,hero_treatment:T.hero_treatment,shape_lang:T.shape_lang,texture:T.texture,decoration_hint:T.decoration_hint})),A=h.plan?.name??"your app",C=h.design_conversation_id,M={},ne=!1;try{if(C){let be=Date.now();for(;Date.now()-be<5e4;){let sn=await zn(C),z=0;for(let y of w){let k=sn[y.id];k&&((k.status==="done"||k.status==="ready")&&typeof k.html=="string"&&k.html.length>0?(M[y.id]=k.html,z+=1):k.status==="failed"&&(z+=1))}if(z===w.length){ne=!0;break}await new Promise(y=>setTimeout(y,5e3))}}}catch(T){console.error(`[mist_plan:design_clarify] render poll failed: ${T instanceof Error?T.message:String(T)}`)}if(!ne)return d(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:i,design_conversation_id:C,renderedSoFar:Object.keys(M).length,totalDirections:w.length,nextAction:`${Object.keys(M).length}/${w.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${i}" } 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 oe=w.filter(T=>M[T.id]),ge,H,F=ye(n,".mistflow"),fe=ye(F,"design-directions.html"),se=ye(F,"picker-state.json"),de=!1;if(C)try{rt(se)&&JSON.parse(xn(se,"utf-8")).opened_for_design_cid===C&&(de=!0)}catch{}try{if(Nt(F,{recursive:!0}),de)ge=fe;else{let T=vo(A,oe,M);gt(fe,T,"utf-8"),ge=fe;let Se=wo(`file://${fe}`);Se.opened||(H=Se.reason),C&>(se,JSON.stringify({opened_for_design_cid:C,opened_at:new Date().toISOString()},null,2),"utf-8")}}catch(T){console.error(`[mist_plan:design_clarify] picker write/open failed: ${T instanceof Error?T.message:String(T)}`)}let Ie=oe.map(T=>({id:T.id,name:T.name})),he=Ie.map(T=>T.name).filter(Boolean);return d(JSON.stringify({status:"design_clarify",previewPath:ge,previewOpenError:H,directionRefs:Ie,directionNames:he,design_conversation_id:C,conversation_id:i,nextAction:[`The visual picker has been opened in the user's browser at file://${ge??"(path missing)"} \u2014 every direction is a real, rendered landing page. The user is looking at it now.`,H?`(auto-open suppressed: ${H} \u2014 tell the user to open file://${ge} 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: ${he.map(T=>`"${T}"`).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: "${i}", designConversationId: "${C}", 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(`
|
|
2164
|
+
|
|
2165
|
+
`)}))}return d(JSON.stringify(h))}catch(h){let f=h instanceof Error?h.message:String(h);return d(`Could not poll plan conversation '${i}': ${f}`,!0)}let K=s??"";if(!K.trim()&&!i&&!x&&!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(x&&!v&&!K.trim()&&!r)return d(`You passed designConversationId='${x}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${x}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let te=a;if(!te&&l&&(te=Md(l)??void 0,!te))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let ce=i;if(!Te())return Me("plan a new app");let E,B;if(!ce&&!te&&!c&&!x){if(!xd(n))return d(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let h=Ad(n);if(h!=="mistflow"&&Rd(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(`
|
|
2166
|
+
`)}),!0);if(h==="foreign"){let f=D?Cd(D,n,K):!1,w=Nd(n,K),A=Od(K,g);if(A||f){B=w;let C=ui(B);if(C)return d(`Mistflow could not create the scaffold directory at ${B}: ${C}`,!0);E=`Note: Mistflow will scaffold the new app at \`${B}\`. The existing project at \`${n}\` is not modified.`}if(!f&&!A){let C=Pd(n,K);if(e?.server){let M=await vn(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
|
|
2057
2167
|
|
|
2058
2168
|
You're inside \`${n}\` which has a \`package.json\`. Mistflow will create a NEW app in a subdirectory \u2014 it won't modify the existing code.
|
|
2059
2169
|
|
|
2060
|
-
Default path: \`${k}\``,"scope");if(z.outcome==="submitted"){let oe=z.answers?.[0]?.answer??"",ae=oe.toLowerCase(),he=oe.startsWith("/")?oe:null;if(he||ae.startsWith("create at:")||ae.startsWith("choose a different path")){let M=he||(ae.startsWith("choose a different path")?null:k);if(!M)return d("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);W=M;let V=Zo(W);if(V)return d(`Mistflow could not create the scaffold directory at ${W}: ${V}`,!0);R=`Note: Mistflow will scaffold the new app at \`${W}\`. 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: ${oe}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return z.outcome==="declined"?d("User declined the scope confirmation. They wanted to edit the existing project, not create a new Mistflow app. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):d(ei({projectPath:n,description:K,confirmToken:O,suggestedPath:k,previousTokenInvalid:!!j}))}else return d(ei({projectPath:n,description:K,confirmToken:O,suggestedPath:k,previousTokenInvalid:!!j}))}}}if(c)try{if(!(await Gr(c)).plan)return d("This template has no plan to fork. Try a different template.",!0);let f=await Vr(c),k=f.plan,T="";if(m&&f.has_source)try{let V=await qn(f.plan,m),ke=V.plan??V,ie=V.diff,ye=ke?.steps??[],pe=new Set([...(ie?.added??[]).map(we=>we.number),...(ie?.modified??[]).map(we=>we.number)]),me=ye.map(we=>{let b=we.number;return pe.has(b)?{...we,status:"pending"}:{...we,status:"completed",source:"forked"}});ke.steps=me,k=ke;let P=me.filter(we=>we.status==="pending").length;T=` Remixed: ${me.filter(we=>we.status==="completed").length} steps unchanged, ${P} steps need re-implementation.`}catch(V){console.error("[plan] Remix failed, using original plan:",V),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let O=Qo(),z=ge(gt(),".mistflow","plans");Ct(z,{recursive:!0}),ht(ge(z,`${O}.json`),JSON.stringify({plan:k,projectId:f.id,sourceDeploymentId:f.source_deployment_id,forkToken:f.fork_token,requiredEnvVars:f.required_env_vars,dbProvider:f.db_provider}));let oe=k?.name??"forked-app",ae=f.has_source,he=ae?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",M=f.deploy_url?` Instant deploy started \u2014 your app will be live at ${f.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:O,forkedFrom:f.forked_from,projectId:f.id,hasSource:ae,deployUrl:f.deploy_url,message:`Forked "${f.forked_from}" into your workspace.${T}${M} ${he} NEXT: Call mist_init, name='${oe}', and planId='${O}' to create the project now.`}))}catch(g){let f=g instanceof Error?g.message:"Failed to fork template";return d(f,!0)}if(ee){let g;if(n){let M=ge(n,"PLAN.md");if(rt(M))try{g=fn(M,"utf-8")}catch(V){console.error(`[mist_plan:modify] PLAN.md read failed (${M}): ${V instanceof Error?V.message:String(V)}`)}}let f;try{f=await qn(ee,K,{planMd:g})}catch(M){let V=M instanceof Error?M.message:"Failed to modify plan";return d(V,!0)}let k=f.plan,T=f.diff,O=typeof f.plan_md=="string"?f.plan_md:null,z,oe;if(O&&n)try{let M=ge(n,"PLAN.md");ht(M,O,"utf-8"),z=M}catch(M){oe=M instanceof Error?M.message:String(M)}let ae=[];if(T?.added?.length){let M=T.added.map(V=>V.title);ae.push(`Added ${M.length} step(s): ${M.join(", ")}`)}if(T?.removed?.length){let M=T.removed.map(V=>V.title);ae.push(`Removed ${M.length} step(s): ${M.join(", ")}`)}if(T?.modified?.length){let M=T.modified.map(V=>V.title);ae.push(`Modified ${M.length} step(s): ${M.join(", ")}`)}let he=ae.length>0?ae.join(". "):"No changes detected.";return d(JSON.stringify({plan:k,diff:T,planMdPath:z,planMdError:oe,message:`Plan modified. ${he}. Update mistflow.json with the new plan${z?"; PLAN.md has been regenerated at "+z:""}, then continue with mist_implement.`}))}let E=I?.trim()||void 0,Z=s;if(Array.isArray(s)){let g=s.findIndex(f=>f&&typeof f=="object"&&f.decisionKey==="urlChoice");if(g>=0){let f=s[g];!E&&f.answer&&(E=f.answer);let k=s.slice(0,g).concat(s.slice(g+1));Z=k.length>0?k:void 0}}else if(s!=null){let g=s;if(!E&&tr in g&&(E=g[tr]),!E&&"urlChoice"in g&&(E=g.urlChoice),tr in g||"urlChoice"in g){let{[tr]:f,urlChoice:k,...T}=g;Z=Object.keys(T).length>0?T:void 0}}if(E&&(E=E.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),E){let g=E.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(g)?E=g:(console.error(`[mist_plan] Discarding urlChoice '${E}' \u2014 does not look like a subdomain. Backend will auto-generate.`),E=void 0)}let J;if(y){J={...y},delete J.userConfirmedCustom,delete J.user_confirmed_custom;let g={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[f,k]of Object.entries(g))y[f]!==void 0&&J[k]===void 0&&(J[k]=y[f])}let G=J!==void 0&&typeof J.custom=="string"&&!J.id&&!J.name,N=C===!0||y!==void 0&&(y.userConfirmedCustom===!0||y.user_confirmed_custom===!0);if(G&&x)try{let g=await Mn(x);if(g.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: '${x}' } 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(g.status==="ready"&&Array.isArray(g.directions)&&g.directions.length>0&&!N){let f=g.directions.map(k=>k.name).join(", ");return d(`Refusing to submit a custom design direction: the backend has ${g.directions.length} real directions ready (${f}). The picker is mandatory \u2014 you must surface those exact directions to the user via AskUserQuestion before submitting any pick. Re-call mist_plan with { conversationId, designConversationId: '${x}' } 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 ${g.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(g){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${g instanceof Error?g.message:String(g)}`)}let S=s?"Generating plan with your answers (LLM call)":x?"Finalizing design direction":"Thinking through discovery questions",$=e?We(e.server,e.progressToken,()=>S):{stop:()=>{}};if(e&&(e.cleanup=()=>$.stop()),!i&&!o&&!x&&!a&&!l&&!c&&!j&&K.trim().length>0&&!H)try{let g=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),f=336*60*60*1e3,k=Date.now()-f,O=(await ln(Yo())).filter(z=>!g.has(z.state)).filter(z=>{let oe=Date.parse(z.updated_at);return Number.isFinite(oe)&&oe>=k}).sort((z,oe)=>Date.parse(oe.updated_at)-Date.parse(z.updated_at)).slice(0,5);if(O.length>0)return $.stop(),d(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:O.map(z=>({sessionId:z.id,state:z.state,description:z.description,currentStep:z.current_step,awaitingInput:z.awaiting_input,updatedAt:z.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(g){console.error("resume-offer check failed (falling through to bootstrap):",g instanceof Error?g.message:g)}let ne=i,A;try{le&&!Z&&!x&&!ee&&!l?A=await Un(le):A=await Fn(K,{conversationId:le,answers:Z,autonomous:p,language:u,designConversationId:x,designDirection:J})}catch(g){$.stop();let f=g instanceof Error?g.message:"Failed to generate plan";return d(f,!0)}let xe=A.session_id;if(!ne&&xe){ne=xe;try{await an(xe,{machine_id:Yo(),local_path:n})}catch(g){console.error("workspace bind failed (resume offers will miss this session):",g instanceof Error?g.message:g)}}if(A.status==="clarify_pending"){$.stop();let g=A;return d(JSON.stringify({status:"running",conversationId:g.conversation_id,sessionId:ne,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${g.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.${ne?` Carry sessionId="${ne}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(A.status==="plan_pending"){$.stop();let g=A;return d(JSON.stringify({status:"running",conversationId:g.conversation_id,sessionId:ne,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${g.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(A.status==="design_clarify_pending"&&(S="Generating creative design directions",A=await kd(A)),A.status==="design_clarify_pending")return $.stop(),d(JSON.stringify({status:"running",conversationId:o,designConversationId:A.design_conversation_id,sessionId:ne,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($.stop(),A.status==="clarify"){let g=A.reflection||"",f=A.suggestedName||"",k=A.suggestedFeatures??[],T=A.questions??[],O=T.some(ie=>Array.isArray(ie.options)&&typeof ie.options[0]=="object"&&ie.options[0]?.label),z={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(ie=>{let ye=ie.decisionKey&&z[ie.decisionKey]||wd(ie.question),pe;return O&&Array.isArray(ie.options)?pe=ie.options.map(me=>({label:me.label,description:me.description??""})):Array.isArray(ie.options)?pe=ie.options.map((me,P)=>({label:P===0?`${me} (Recommended)`:String(me),description:ie.why??""})):pe=[{label:"Yes (Recommended)",description:ie.why??""},{label:"No",description:""}],{question:ie.question,header:ye,options:pe,multiSelect:!1}}),he=A.decisions?.audienceType??null,M=k.length>0?Go(K,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:he,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:f,suggestedFeatures:k,language:u}):null,V=M?Vo(M):"",ke=Zn(f||"my-app").slice(0,32);try{let ie=await Dn(ke);!ie.available&&ie.suggestion&&(ke=ie.suggestion)}catch{}if(V&&(V+=`
|
|
2170
|
+
Default path: \`${w}\``,"scope");if(M.outcome==="submitted"){let ne=M.answers?.[0]?.answer??"",oe=ne.toLowerCase(),ge=ne.startsWith("/")?ne:null;if(ge||oe.startsWith("create at:")||oe.startsWith("choose a different path")){let H=ge||(oe.startsWith("choose a different path")?null:w);if(!H)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);B=H;let F=ui(B);if(F)return d(`Mistflow could not create the scaffold directory at ${B}: ${F}`,!0);E=`Note: Mistflow will scaffold the new app at \`${B}\`. The existing project at \`${n}\` is not modified.`}else return oe.startsWith("cancel")?d("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):d(`User submitted an unrecognized scope choice: ${ne}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return M.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(mi({projectPath:n,description:K,confirmToken:C,suggestedPath:w,previousTokenInvalid:!!D}))}else return d(mi({projectPath:n,description:K,confirmToken:C,suggestedPath:w,previousTokenInvalid:!!D}))}}}if(c)try{if(!(await eo(c)).plan)return d("This template has no plan to fork. Try a different template.",!0);let f=await to(c),w=f.plan,A="";if(m&&f.has_source)try{let F=await Gn(f.plan,m),fe=F.plan??F,se=F.diff,de=fe?.steps??[],Ie=new Set([...(se?.added??[]).map(be=>be.number),...(se?.modified??[]).map(be=>be.number)]),he=de.map(be=>{let sn=be.number;return Ie.has(sn)?{...be,status:"pending"}:{...be,status:"completed",source:"forked"}});fe.steps=he,w=fe;let T=he.filter(be=>be.status==="pending").length;A=` Remixed: ${he.filter(be=>be.status==="completed").length} steps unchanged, ${T} steps need re-implementation.`}catch(F){console.error("[plan] Remix failed, using original plan:",F),A=" (Remix failed \u2014 using original plan. You can modify it later.)"}let C=di(),M=ye(ft(),".mistflow","plans");Nt(M,{recursive:!0}),gt(ye(M,`${C}.json`),JSON.stringify({plan:w,projectId:f.id,sourceDeploymentId:f.source_deployment_id,forkToken:f.fork_token,requiredEnvVars:f.required_env_vars,dbProvider:f.db_provider}));let ne=w?.name??"forked-app",oe=f.has_source,ge=oe?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",H=f.deploy_url?` Instant deploy started \u2014 your app will be live at ${f.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:C,forkedFrom:f.forked_from,projectId:f.id,hasSource:oe,deployUrl:f.deploy_url,message:`Forked "${f.forked_from}" into your workspace.${A}${H} ${ge} NEXT: Call mist_init, name='${ne}', and planId='${C}' to create the project now.`}))}catch(h){let f=h instanceof Error?h.message:"Failed to fork template";return d(f,!0)}if(te){let h;if(n){let H=ye(n,"PLAN.md");if(rt(H))try{h=xn(H,"utf-8")}catch(F){console.error(`[mist_plan:modify] PLAN.md read failed (${H}): ${F instanceof Error?F.message:String(F)}`)}}let f;try{f=await Gn(te,K,{planMd:h})}catch(H){let F=H instanceof Error?H.message:"Failed to modify plan";return d(F,!0)}let w=f.plan,A=f.diff,C=typeof f.plan_md=="string"?f.plan_md:null,M,ne;if(C&&n)try{let H=ye(n,"PLAN.md");gt(H,C,"utf-8"),M=H}catch(H){ne=H instanceof Error?H.message:String(H)}let oe=[];if(A?.added?.length){let H=A.added.map(F=>F.title);oe.push(`Added ${H.length} step(s): ${H.join(", ")}`)}if(A?.removed?.length){let H=A.removed.map(F=>F.title);oe.push(`Removed ${H.length} step(s): ${H.join(", ")}`)}if(A?.modified?.length){let H=A.modified.map(F=>F.title);oe.push(`Modified ${H.length} step(s): ${H.join(", ")}`)}let ge=oe.length>0?oe.join(". "):"No changes detected.";return d(JSON.stringify({plan:w,diff:A,planMdPath:M,planMdError:ne,message:`Plan modified. ${ge}. Update mistflow.json with the new plan${M?"; PLAN.md has been regenerated at "+M:""}, then continue with mist_implement.`}))}let N=_?.trim()||void 0,ee=r;if(Array.isArray(r)){let h=r.findIndex(f=>f&&typeof f=="object"&&f.decisionKey==="urlChoice");if(h>=0){let f=r[h];!N&&f.answer&&(N=f.answer);let w=r.slice(0,h).concat(r.slice(h+1));ee=w.length>0?w:void 0}}else if(r!=null){let h=r;if(!N&&is in h&&(N=h[is]),!N&&"urlChoice"in h&&(N=h.urlChoice),is in h||"urlChoice"in h){let{[is]:f,urlChoice:w,...A}=h;ee=Object.keys(A).length>0?A:void 0}}if(N&&(N=N.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),N){let h=N.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(h)?N=h:(console.error(`[mist_plan] Discarding urlChoice '${N}' \u2014 does not look like a subdomain. Backend will auto-generate.`),N=void 0)}let Q;if(v){Q={...v},delete Q.userConfirmedCustom,delete Q.user_confirmed_custom;let h={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[f,w]of Object.entries(h))v[f]!==void 0&&Q[w]===void 0&&(Q[w]=v[f])}let J=Q!==void 0&&typeof Q.custom=="string"&&!Q.id&&!Q.name,b=R===!0||v!==void 0&&(v.userConfirmedCustom===!0||v.user_confirmed_custom===!0);if(J&&x)try{let h=await qn(x);if(h.status==="pending")return d(`Refusing to submit a custom design direction: the backend's direction-generation BG task is still running (status: pending). The user has not yet had the chance to see the real directions. Stop asking the user about aesthetic / fonts / colors / mood right now \u2014 the backend will produce 3-4 concrete options shortly. Re-call mist_plan with { projectPath, conversationId, designConversationId: '${x}' } to keep polling. When directions are ready (status: 'design_clarify'), surface them to the user via AskUserQuestion. Custom is only legitimate AFTER the user has seen the real options and explicitly rejected them \u2014 never as a workaround for a slow generation run.`,!0);if(h.status==="ready"&&Array.isArray(h.directions)&&h.directions.length>0&&!b){let f=h.directions.map(w=>w.name).join(", ");return d(`Refusing to submit a custom design direction: the backend has ${h.directions.length} real directions ready (${f}). The picker is mandatory \u2014 you must surface those exact directions to the user via AskUserQuestion before submitting any pick. Re-call mist_plan with { conversationId, designConversationId: '${x}' } to get the picker payload (status: 'design_clarify'), render the directions HTML preview at .mistflow/design-directions.html for the user, then submit the user's choice. If the user opens the preview, sees the ${h.directions.length} directions, rejects all of them, and types their own description, ONLY THEN retry this call with userConfirmedCustom: true. Never set userConfirmedCustom: true without first showing the user the real directions.`,!0)}}catch(h){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${h instanceof Error?h.message:String(h)}`)}let $=r?"Generating plan with your answers (LLM call)":x?"Finalizing design direction":"Thinking through discovery questions",V=e?Ve(e.server,e.progressToken,()=>$):{stop:()=>{}};if(e&&(e.cleanup=()=>V.stop()),!o&&!i&&!x&&!a&&!l&&!c&&!D&&K.trim().length>0&&!G)try{let h=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),f=336*60*60*1e3,w=Date.now()-f,C=(await hn(ci())).filter(M=>!h.has(M.state)).filter(M=>{let ne=Date.parse(M.updated_at);return Number.isFinite(ne)&&ne>=w}).sort((M,ne)=>Date.parse(ne.updated_at)-Date.parse(M.updated_at)).slice(0,5);if(C.length>0)return V.stop(),d(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:C.map(M=>({sessionId:M.id,state:M.state,description:M.description,currentStep:M.current_step,awaitingInput:M.awaiting_input,updatedAt:M.updated_at})),instruction:"This machine has unfinished Mistflow build(s) in flight. Before starting a new project, ask the user whether they want to resume one of these or start fresh. Show the description, state, and updatedAt for each candidate so they can pick.",nextAction:"Step 1: Show the candidates to the user via your host's question UI (AskUserQuestion in Claude Code, request_user_input in Codex Plan mode, quick pick in Cursor). Step 2a (resume): if they pick a candidate, call mist_session({ action: 'resume', sessionId: '<picked>', projectPath }) and follow the next instruction it returns. Step 2b (start fresh): if they want a new build, call mist_plan again with the SAME description and projectPath, plus forceNew: true. The forceNew flag suppresses this check so the new session can be minted."}))}catch(h){console.error("resume-offer check failed (falling through to bootstrap):",h instanceof Error?h.message:h)}let me=o,S;try{ce&&!ee&&!x&&!te&&!l?S=await Hn(ce):S=await Wn(K,{conversationId:ce,answers:ee,autonomous:p,language:u,designConversationId:x,designDirection:Q})}catch(h){V.stop();let f=h instanceof Error?h.message:"Failed to generate plan";return d(f,!0)}let Ce=S.session_id;if(!me&&Ce){me=Ce;try{await mn(Ce,{machine_id:ci(),local_path:n})}catch(h){console.error("workspace bind failed (resume offers will miss this session):",h instanceof Error?h.message:h)}}if(S.status==="clarify_pending"){V.stop();let h=S;return d(JSON.stringify({status:"running",conversationId:h.conversation_id,sessionId:me,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${h.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.${me?` Carry sessionId="${me}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(S.status==="plan_pending"){V.stop();let h=S;return d(JSON.stringify({status:"running",conversationId:h.conversation_id,sessionId:me,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${h.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(S.status==="design_clarify_pending"&&($="Generating creative design directions",S=await Ld(S)),S.status==="design_clarify_pending")return V.stop(),d(JSON.stringify({status:"running",conversationId:i,designConversationId:S.design_conversation_id,sessionId:me,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: "${i??""}" } 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(V.stop(),S.status==="clarify"){let h=S.reflection||"",f=S.suggestedName||"",w=S.suggestedFeatures??[],A=S.questions??[],C=A.some(se=>Array.isArray(se.options)&&typeof se.options[0]=="object"&&se.options[0]?.label),M={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},ne=A.map(se=>{let de=se.decisionKey&&M[se.decisionKey]||Dd(se.question),Ie;return C&&Array.isArray(se.options)?Ie=se.options.map(he=>({label:he.label,description:he.description??""})):Array.isArray(se.options)?Ie=se.options.map((he,T)=>({label:T===0?`${he} (Recommended)`:String(he),description:se.why??""})):Ie=[{label:"Yes (Recommended)",description:se.why??""},{label:"No",description:""}],{question:se.question,header:de,options:Ie,multiSelect:!1}}),ge=S.decisions?.audienceType??null,H=w.length>0?ri(K,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:ge,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:f,suggestedFeatures:w,language:u}):null,F=H?ii(H):"",fe=os(f||"my-app").slice(0,32);try{let se=await Fn(fe);!se.available&&se.suggestion&&(fe=se.suggestion)}catch{}if(F&&(F+=`
|
|
2061
2171
|
|
|
2062
|
-
**Your app URL (you can change this before scaffolding):** https://${
|
|
2063
|
-
`),
|
|
2064
|
-
`)}))}if(
|
|
2172
|
+
**Your app URL (you can change this before scaffolding):** https://${fe}.mistflow.app`),e?.server){let se=[f?`## ${f}`:"## Pick a few details","",`${A.length} quick question${A.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
|
|
2173
|
+
`),de=await vn(e.server,A,se,"clarify");if(de.outcome==="submitted"){V.stop();let Ie={};for(let T of de.answers??[])T.decisionKey?Ie[T.decisionKey]=T.answer:Ie[T.question]=T.answer;let he=de.urlChoice?.trim();he&&(he=he.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let T=await Wn(K,{conversationId:S.conversation_id,answers:Ie,autonomous:p,language:u});if(T.status==="plan_pending"){let Se=T;return d(JSON.stringify({status:"running",conversationId:Se.conversation_id,phase:"generating_plan",...he?{urlChoice:he}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${Se.conversation_id}"${he?`, urlChoice: "${he}"`:""} } 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.`}))}S=T}catch(T){let Se=T instanceof Error?T.message:String(T);return d(`Submitting your answers failed: ${Se}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(de.outcome==="declined")return V.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(de.outcome==="cancelled")return V.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);de.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${de.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:S.conversation_id,questions:A,questionCount:A.length,suggestedFeatures:w,suggestedName:f,suggestedSubdomain:fe,reflection:h,briefText:F,askUserQuestions:ne,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:["\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST ask the user via your host's native structured-question","tool (not a text prompt, not a bash echo, not a chat message).","The user has to actually choose. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","Per host (use whichever applies):"," \u2022 Claude Code \u2192 AskUserQuestion tool"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) \u2192 request_user_input returns"," 'unavailable in <mode> mode'. When you see that error, STOP"," your turn, print the questions as a numbered chat message"," with all options visible, and wait for the user's next"," message. Do NOT resume by picking answers yourself."," \u2022 Any host without a native question tool \u2192 same as above:"," stop your turn, print the questions, wait.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 'Locking in the defaults with X as the only override.'"," (inferring answers from the original spec)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping the question UI because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call the tool (when available): pass each object in the","`askUserQuestions` array below. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${S.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: "${fe}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.',...h||F?["","\u2500\u2500\u2500 BACKGROUND (not for you to summarize and proceed \u2014 it's what the user will see when you show them the questions) \u2500\u2500\u2500",...h?[h]:[],...F?["",F]:[]]:[],...E?["",E]:[]].join(`
|
|
2174
|
+
`)}))}if(S.status==="design_clarify"){let h=S.directions??[],f=S.plan.name??"your app",w=S.design_conversation_id,A=h.map(z=>({id:z.id,name:z.name,summary:z.summary,hero_headline:z.hero_headline,cta_text:z.cta_text,body_sample:z.body_sample,fonts:z.fonts,colors:z.colors,hero_treatment:z.hero_treatment,shape_lang:z.shape_lang,texture:z.texture,decoration_hint:z.decoration_hint})),C={},M=!1;try{if(w){let k=Date.now();for(;Date.now()-k<5e4;){let W=await zn(w),ke=0;for(let Ue of A){let O=W[Ue.id];O&&((O.status==="done"||O.status==="ready")&&typeof O.html=="string"&&O.html.length>0?(C[Ue.id]=O.html,ke+=1):O.status==="failed"&&(ke+=1))}if(ke===A.length){M=!0;break}await new Promise(Ue=>setTimeout(Ue,5e3))}}}catch(z){console.error(`[mist_plan:design_clarify] render poll failed: ${z instanceof Error?z.message:String(z)}`)}if(!M)return d(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:S.conversation_id??i,design_conversation_id:w,renderedSoFar:Object.keys(C).length,totalDirections:A.length,nextAction:`${Object.keys(C).length}/${A.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${S.conversation_id??i??""}" } again IMMEDIATELY \u2014 do NOT bash sleep. Do NOT ask the user about design yet.`}));let ne=A.filter(z=>C[z.id]),oe,ge,H=ye(n,".mistflow"),F=ye(H,"design-directions.html"),fe=ye(H,"picker-state.json"),se=()=>{try{if(rt(fe))return JSON.parse(xn(fe,"utf-8"))}catch{}return{}},de=z=>{try{Nt(H,{recursive:!0}),gt(fe,JSON.stringify(z,null,2),"utf-8")}catch(y){console.error(`[mist_plan:design_clarify] sidecar write failed: ${y instanceof Error?y.message:String(y)}`)}},Ie=se(),he=w&&Ie.opened_for_design_cid===w;try{if(Nt(H,{recursive:!0}),he)oe=F;else{let z=vo(f,ne,C);gt(F,z,"utf-8"),oe=F;let y=wo(`file://${F}`);y.opened||(ge=y.reason),w&&de({opened_for_design_cid:w,elicit_state:"pending",elicit_design_cid:w,opened_at:new Date().toISOString()})}}catch(z){console.error(`[mist_plan:design_clarify] picker write/open failed: ${z instanceof Error?z.message:String(z)}`)}let T=se(),Se=ne.map(z=>({id:z.id,name:z.name})),be=Se.map(z=>z.name).filter(Boolean);if(e?.server&&w&&T.elicit_design_cid===w&&T.elicit_state==="pending"){let z=oe?[`## ${f} \u2014 pick a creative direction`,"",`${ne.length} directions, each with its own fonts, colors, and mood.`,"",`Visual preview (auto-opened in your browser): file://${oe}`,"Each card shows what you'd be picking \u2014 fonts, colors, hero layout."].join(`
|
|
2065
2175
|
`):`## ${f} \u2014 pick a creative direction
|
|
2066
2176
|
|
|
2067
|
-
${
|
|
2177
|
+
${ne.length} directions, each with its own fonts, colors, and mood. Pick one or describe your own.`,y=ne.map(k=>({label:k.name,description:k.summary??""}));y.push({label:"Describe your own direction",description:"Skip the proposed options and type a short description of how the app should feel."});try{let k=await vn(e.server,[{question:`${f} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,decisionKey:"designDirection",options:y,noOtherSentinel:!0,otherFieldTitle:"If 'Describe your own direction' was picked: type how the app should feel (fonts, colors, mood \u2014 your words)."}],z,"design");if(k.outcome==="submitted"&&k.answers?.[0]){let W=k.answers[0].answer.trim(),ke=ne.find(O=>O.name===W),Ue=ke?{direction_id:ke.id}:{custom:W};(S.conversation_id??i)&&(Ue.conversation_id=S.conversation_id??i);try{let O=await Bn(w,Ue);de({...T,elicit_state:"completed",elicit_design_cid:w}),S={status:"ready",plan:O.plan??{},methodology:O.methodology??"",...O.designMd?{designMd:O.designMd}:{}}}catch(O){return console.error(`[mist_plan:design_clarify] submitDesignPick failed: ${O instanceof Error?O.message:String(O)}`),de({...T,elicit_state:"skipped"}),d(`Design submission failed: ${O instanceof Error?O.message:String(O)}. Ask the user to retry by re-running mist_plan with their pick.`,!0)}}else return de({...T,elicit_state:"skipped"}),d(JSON.stringify({status:"design_clarify",previewPath:oe,previewOpenError:ge,directionRefs:Se,directionNames:be,design_conversation_id:w,conversation_id:S.conversation_id??i,nextAction:[`The user closed the elicit picker without picking. The visual picker is still open at file://${oe??"(path missing)"}.`,`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask which direction they pick. List EXACTLY these names: ${be.map(W=>`"${W}"`).join(", ")}.`,`When they pick, call mist_plan with { projectPath, conversationId: "${S.conversation_id??i??""}", designConversationId: "${w??""}", designDirection: { id: "<id from directionRefs>" } }.`].join(`
|
|
2178
|
+
|
|
2179
|
+
`)}))}catch(k){console.error(`[mist_plan:design_clarify] elicit failed: ${k instanceof Error?k.message:String(k)}`),de({...T,elicit_state:"skipped"})}}if(S.status==="design_clarify")return d(JSON.stringify({status:"design_clarify",previewPath:oe,previewOpenError:ge,directionRefs:Se,directionNames:be,design_conversation_id:w,conversation_id:S.conversation_id??i,nextAction:[`The visual picker is open in the user's browser at file://${oe??"(path missing)"} \u2014 every direction is a real, rendered landing page.`,ge?`(auto-open suppressed: ${ge} \u2014 tell the user to open file://${oe} manually)`:"",`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names: ${be.map(z=>`"${z}"`).join(", ")}. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${S.conversation_id??i??""}", 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(`
|
|
2180
|
+
|
|
2181
|
+
`)}))}if(S.status!=="ready")return d(`Unexpected plan status after build: ${S.status}. Please retry by calling mist_plan with the same conversationId.`,!0);let Y=S.plan,ie=Y.name??"Untitled App",we=S.methodology,ue=Y.steps;if(!Array.isArray(ue)||ue.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 xe=Y.suggestedSubdomain??os(ie).slice(0,32)??"my-app";if(!N&&e?.server){try{let f=await Fn(xe);!f.available&&f.suggestion&&(xe=f.suggestion)}catch{}let h=await vn(e.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${xe}.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 ${xe}.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
|
|
2182
|
+
|
|
2183
|
+
The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(h.outcome==="submitted"){let f=h.urlChoice?.trim()||h.answers?.[0]?.answer.trim()||"";f=f.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(f)||!f)&&(f=xe);let w=f.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(w)?N=w:(console.error(`[mist_plan] URL elicitation returned '${f}' \u2014 does not look like a subdomain. Using default '${xe}'.`),N=xe)}else h.outcome==="declined"||h.outcome,N=xe}else N||(N=xe);let Ne=Y.publicPages;if(!Ne||Array.isArray(Ne)&&Ne.length===0){let h=Y.publicLanding;if(h===!1)Ne=[];else{let f=Y.pages,w=ue.some(C=>typeof C.name=="string"&&C.name.toLowerCase().includes("landing")||typeof C.title=="string"&&C.title.toLowerCase().includes("landing")),A=Array.isArray(f)&&f.some(C=>C.path==="/"||C.route==="/");w||A?Ne=["/","/pricing"]:h===!0?Ne=["/"]:Ne=["/"]}}else Y.publicLanding===!1&&Ne.includes("/")&&(Ne=Ne.filter(h=>h!=="/"));let Xe=Y.primaryAction;if(!Xe){let h=Y.features;if(Array.isArray(h)&&h.length>0){let w=h.find(C=>typeof C.priority=="string"&&C.priority.toLowerCase()==="must-have")??h[0];Xe={entity:w.name??w.title??"item",action:"create",fromPage:"/dashboard"}}}let Be=Y.nonNegotiables;(!Be||Array.isArray(Be)&&Be.length===0)&&(Be=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Ze=di(),Tt=ye(ft(),".mistflow","plans");Nt(Tt,{recursive:!0});try{let f=Date.now();for(let w of[Tt,ye(ft(),".mistflow","mockup-state")])if(rt(w))for(let A of gi(w))try{let C=ye(w,A),M=fi(C).mtimeMs;f-M>6048e5&&vd(C)}catch{}}catch{}let _e=Y,U={name:Y.name,summary:Y.summary,dataModel:Y.dataModel,pages:Y.pages,features:Y.features,steps:ue.map(h=>({...h,name:h.name??h.title})),design:Y.design,dbProvider:Y.dbProvider??"neon",authModel:Y.authModel,audienceType:Y.audienceType??"b2c",roles:Y.roles,defaultRole:Y.defaultRole,publicPages:Ne,navStyle:Y.navStyle,multiTenant:Y.multiTenant,primaryAction:Xe,nonNegotiables:Be,requestedSubdomain:N,...u&&u.toLowerCase()!=="english"?{language:u}:{},..._e.pickedDirection?{pickedDirection:_e.pickedDirection}:{},..._e.imageryBrief?{imageryBrief:_e.imageryBrief}:{},..._e.designConversationId?{designConversationId:_e.designConversationId}:{}};gt(ye(Tt,`${Ze}.json`),JSON.stringify({plan:U,methodology:we,...B?{scaffoldTargetPath:B}:{}}));let ae=ue.map(h=>`${h.number}. ${h.name??h.title}`),Ae,$e="";if(!!!_e.pickedDirection){let f=(Y.audienceType??"b2c")==="b2c";Ae={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:f?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:f?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},$e=" 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 ze="",Oe=[];for(let h of ue){let f=h.name??h.title,w=h.integrationId;if(w){let A=qt(w);if(A){let C=Bt(A.id);Oe.push({step:f,presetId:A.id,presetName:A.name,envVars:C?.envVars??[]})}}}if(Oe.length>0){let h=Oe.flatMap(A=>A.envVars),f=[...new Set(h.map(A=>A.key))];ze=` This plan uses integrations (${Oe.map(A=>A.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${f.length>0?` The user will need these API keys: ${f.join(", ")}.`:""}`}return d(JSON.stringify({planId:Ze,name:Y.name,summary:Y.summary,stepCount:ue.length,steps:ae,design:Y.design,...Ae?{heroPhotoQuestion:Ae}:{},...Oe.length>0?{integrations:Oe.map(h=>({step:h.step,preset:h.presetId,name:h.presetName,envVars:h.envVars}))}:{},message:`Plan generated for "${ie}" (${ue.length} steps).${ze}${$e}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,ue.length*3)}\u2013${ue.length*5} minutes total across ${ue.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: '${Ze}' }). If the user says skip or "just build it", call mist_init({ planId: '${Ze}'${B?"":", path: '<absolute path>'"} }) immediately.`,...B?{scaffoldTargetPath:B}:{},...E?{warning:E}:{}}))}var is,Id,jd,vi,ki=I(()=>{"use strict";ve();Pe();si();Wt();oi();Qn();ai();li();is="__mistflow_url_choice__",Id=600*1e3;jd=L.object({description:L.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:L.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:L.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:L.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:L.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}},L.union([L.record(L.string()),L.array(L.object({question:L.string().optional(),decisionKey:L.string().optional(),answer:L.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:L.record(L.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:L.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:L.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:L.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:L.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:L.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:L.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:L.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:L.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:L.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:L.object({id:L.string().optional(),name:L.string().optional(),summary:L.string().optional(),heroHeadline:L.string().optional(),ctaText:L.string().optional(),bodySample:L.string().optional(),fontsHint:L.string().optional(),fonts:L.object({display:L.string(),body:L.string()}).partial().optional(),colorMood:L.string().optional(),colors:L.object({bg:L.string(),fg:L.string(),accent:L.string()}).partial().optional(),heroTreatment:L.string().optional(),shapeLang:L.string().optional(),texture:L.string().optional(),decorationHint:L.string().optional(),custom:L.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:L.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:L.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.")});vi={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(`
|
|
2184
|
+
`),inputSchema:jd,handler:Bd}});var it,xi,ko=I(()=>{"use strict";it={slug:"agent-ui",version:"1.0.0",description:"Mistflow agent UX primitives. Rich tool cards with streaming logs, approval gates for risky actions, cost badges, plan checklists, contextual suggestions.",files:[{src:"src/components/ApprovalGate.tsx",dst:"components/agent/ApprovalGate.tsx",version:"1.0.0",skipIfExists:!1,sourceHash:"sha256:f0622a2873f633683bae7e25f3b62b0b4fc49c7b01601af3009001d36c773273"},{src:"src/components/CostBadge.tsx",dst:"components/agent/CostBadge.tsx",version:"1.0.0",skipIfExists:!1,sourceHash:"sha256:5d2d368e07cfac7025f69b9de87c7402a0d9fdb71d0b2c3fa85138831c918507"},{src:"src/components/PlanSteps.tsx",dst:"components/agent/PlanSteps.tsx",version:"1.0.0",skipIfExists:!1,sourceHash:"sha256:116a8a01c43e27a2c862d8b1218c6b44bc7406aa59c6784612f1d45993f9a3db"},{src:"src/components/SuggestedPrompts.tsx",dst:"components/agent/SuggestedPrompts.tsx",version:"1.0.0",skipIfExists:!1,sourceHash:"sha256:fe6eaea62a2d9c0b74f4cb6f7db3fe6673b647b2d1fc8a640624828cbebe45d7"},{src:"src/components/ToolStream.tsx",dst:"components/agent/ToolStream.tsx",version:"1.0.0",skipIfExists:!1,sourceHash:"sha256:a9c2763830fc13a544a1ef6f6b1f7445362ee9e1915408b85088827e3b1899c5"},{src:"src/lib/cn.ts",dst:"lib/cn.ts",version:"1.0.0",skipIfExists:!0,sourceHash:"sha256:39c7c9fe53788ae5992a1027e1d440e8b8c9d4af61500aa847cb173432c65603"},{src:"src/lib/agent-types.ts",dst:"lib/agent-types.ts",version:"1.0.0",skipIfExists:!1,sourceHash:"sha256:3efa0340d6d3a21524a4693d3bdfc8ee029cf3779616d1c81ea35b2ce76f2744"}],dependencies:{"framer-motion":"^11.18.0",recharts:"^2.15.0",clsx:"^2.1.1","tailwind-merge":"^2.5.0"},postInstallNote:"Components written under components/agent/. See methodologies/agent-ui-components.md for the API and an integration recipe."},xi={"src/components/ApprovalGate.tsx":`/** @mistflow-component approval-gate
|
|
2185
|
+
* @version 1.0.0
|
|
2186
|
+
* @source packages/agent-ui-components/src/components/ApprovalGate.tsx
|
|
2187
|
+
*
|
|
2188
|
+
* Confirmation card for tool calls with side effects (riskLevel >=
|
|
2189
|
+
* "external-write"). Renders BEFORE the tool fires. User sees the action
|
|
2190
|
+
* in human language and chooses Approve / Cancel / Edit. The agent loop
|
|
2191
|
+
* waits on the user signal; on Approve, the tool executes; on Cancel,
|
|
2192
|
+
* the agent gets a "user declined" tool result and adapts.
|
|
2193
|
+
*
|
|
2194
|
+
* Wire-up: in the chat route's \`onToolCall\` middleware, pause execution
|
|
2195
|
+
* when the tool's riskLevel is "external-write" or "destructive", render
|
|
2196
|
+
* this component with the parsed args, and resume on the user's signal.
|
|
2197
|
+
*/
|
|
2198
|
+
|
|
2199
|
+
'use client'
|
|
2200
|
+
|
|
2201
|
+
import { useState, type ReactNode } from 'react'
|
|
2202
|
+
|
|
2203
|
+
export type Risk = 'safe' | 'external-write' | 'destructive'
|
|
2204
|
+
|
|
2205
|
+
export type ApprovalGateProps = {
|
|
2206
|
+
// Human-readable tool label, e.g. "Send email" not "send_email".
|
|
2207
|
+
toolLabel: string
|
|
2208
|
+
|
|
2209
|
+
// One-line summary of what will happen if approved. Should make the
|
|
2210
|
+
// consequence concrete. Bad: "Run send_email tool". Good: "Send the
|
|
2211
|
+
// weekly digest to 1,247 contacts."
|
|
2212
|
+
summary: string
|
|
2213
|
+
|
|
2214
|
+
// The tool's risk level. UI emphasis varies (destructive uses red
|
|
2215
|
+
// accent; external-write uses warning yellow; safe never renders this
|
|
2216
|
+
// component \u2014 agent should bypass it).
|
|
2217
|
+
risk: Risk
|
|
2218
|
+
|
|
2219
|
+
// Optional detail children \u2014 a table of the actual args, an
|
|
2220
|
+
// attachment preview, a contact list, etc. Rendered in the expandable
|
|
2221
|
+
// "Show details" section. Keep editable when possible.
|
|
2222
|
+
details?: ReactNode
|
|
2223
|
+
|
|
2224
|
+
// Cost estimate badge ("~$0.30") \u2014 passed in from the tool registry's
|
|
2225
|
+
// costClass + AI Gateway's per-call estimate. Optional; omit for free
|
|
2226
|
+
// tools.
|
|
2227
|
+
estimatedCost?: string
|
|
2228
|
+
|
|
2229
|
+
// Called on Approve. Receives any edits the user made via the
|
|
2230
|
+
// children's edit affordances (parent owns the editable state).
|
|
2231
|
+
onApprove: () => void
|
|
2232
|
+
|
|
2233
|
+
// Called on Cancel. The agent loop should receive a "user declined"
|
|
2234
|
+
// tool result and adapt rather than crash.
|
|
2235
|
+
onCancel: () => void
|
|
2236
|
+
|
|
2237
|
+
// Optional: called when the user opens the editor. Parent renders
|
|
2238
|
+
// editable fields in \`details\` and re-passes new values.
|
|
2239
|
+
onEdit?: () => void
|
|
2240
|
+
}
|
|
2068
2241
|
|
|
2069
|
-
|
|
2242
|
+
const RISK_TOKENS = {
|
|
2243
|
+
safe: {
|
|
2244
|
+
label: 'Action',
|
|
2245
|
+
barClass: 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-300',
|
|
2246
|
+
buttonClass:
|
|
2247
|
+
'bg-emerald-600 hover:bg-emerald-700 text-white focus-visible:ring-emerald-500',
|
|
2248
|
+
},
|
|
2249
|
+
'external-write': {
|
|
2250
|
+
label: 'Confirm action',
|
|
2251
|
+
barClass: 'bg-amber-500/15 text-amber-700 dark:text-amber-300',
|
|
2252
|
+
buttonClass:
|
|
2253
|
+
'bg-amber-600 hover:bg-amber-700 text-white focus-visible:ring-amber-500',
|
|
2254
|
+
},
|
|
2255
|
+
destructive: {
|
|
2256
|
+
label: 'Destructive action',
|
|
2257
|
+
barClass: 'bg-red-500/15 text-red-700 dark:text-red-300',
|
|
2258
|
+
buttonClass:
|
|
2259
|
+
'bg-red-600 hover:bg-red-700 text-white focus-visible:ring-red-500',
|
|
2260
|
+
},
|
|
2261
|
+
} as const
|
|
2262
|
+
|
|
2263
|
+
export function ApprovalGate({
|
|
2264
|
+
toolLabel,
|
|
2265
|
+
summary,
|
|
2266
|
+
risk,
|
|
2267
|
+
details,
|
|
2268
|
+
estimatedCost,
|
|
2269
|
+
onApprove,
|
|
2270
|
+
onCancel,
|
|
2271
|
+
onEdit,
|
|
2272
|
+
}: ApprovalGateProps) {
|
|
2273
|
+
const [expanded, setExpanded] = useState(false)
|
|
2274
|
+
const tokens = RISK_TOKENS[risk]
|
|
2070
2275
|
|
|
2071
|
-
|
|
2276
|
+
return (
|
|
2277
|
+
<div
|
|
2278
|
+
role="alertdialog"
|
|
2279
|
+
aria-label={\`\${tokens.label}: \${toolLabel}\`}
|
|
2280
|
+
className="my-3 rounded-lg border border-border bg-card text-card-foreground shadow-sm overflow-hidden"
|
|
2281
|
+
>
|
|
2282
|
+
{/* Risk strip */}
|
|
2283
|
+
<div className={\`px-3 py-1.5 text-xs font-medium \${tokens.barClass}\`}>
|
|
2284
|
+
{tokens.label}
|
|
2285
|
+
</div>
|
|
2286
|
+
|
|
2287
|
+
<div className="p-4 space-y-3">
|
|
2288
|
+
<div className="flex items-start justify-between gap-3">
|
|
2289
|
+
<div className="space-y-1 min-w-0">
|
|
2290
|
+
<div className="text-sm font-medium text-foreground">
|
|
2291
|
+
{toolLabel}
|
|
2292
|
+
</div>
|
|
2293
|
+
<div className="text-sm text-muted-foreground leading-snug">
|
|
2294
|
+
{summary}
|
|
2295
|
+
</div>
|
|
2296
|
+
</div>
|
|
2297
|
+
{estimatedCost && (
|
|
2298
|
+
<span className="shrink-0 text-xs text-muted-foreground font-mono">
|
|
2299
|
+
~{estimatedCost}
|
|
2300
|
+
</span>
|
|
2301
|
+
)}
|
|
2302
|
+
</div>
|
|
2303
|
+
|
|
2304
|
+
{details && (
|
|
2305
|
+
<div>
|
|
2306
|
+
<button
|
|
2307
|
+
type="button"
|
|
2308
|
+
onClick={() => setExpanded((v) => !v)}
|
|
2309
|
+
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
|
|
2310
|
+
>
|
|
2311
|
+
{expanded ? '\u25BE Hide details' : '\u25B8 Show details'}
|
|
2312
|
+
</button>
|
|
2313
|
+
{expanded && (
|
|
2314
|
+
<div className="mt-2 rounded-md border border-border bg-muted/30 p-3 text-sm">
|
|
2315
|
+
{details}
|
|
2316
|
+
</div>
|
|
2317
|
+
)}
|
|
2318
|
+
</div>
|
|
2319
|
+
)}
|
|
2320
|
+
|
|
2321
|
+
<div className="flex flex-wrap gap-2 pt-1">
|
|
2322
|
+
<button
|
|
2323
|
+
type="button"
|
|
2324
|
+
onClick={onApprove}
|
|
2325
|
+
className={\`inline-flex items-center justify-center rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 \${tokens.buttonClass}\`}
|
|
2326
|
+
>
|
|
2327
|
+
Approve
|
|
2328
|
+
</button>
|
|
2329
|
+
<button
|
|
2330
|
+
type="button"
|
|
2331
|
+
onClick={onCancel}
|
|
2332
|
+
className="inline-flex items-center justify-center rounded-md border border-border bg-background hover:bg-muted px-3 py-1.5 text-sm font-medium transition-colors"
|
|
2333
|
+
>
|
|
2334
|
+
Cancel
|
|
2335
|
+
</button>
|
|
2336
|
+
{onEdit && (
|
|
2337
|
+
<button
|
|
2338
|
+
type="button"
|
|
2339
|
+
onClick={onEdit}
|
|
2340
|
+
className="inline-flex items-center justify-center rounded-md border border-border bg-background hover:bg-muted px-3 py-1.5 text-sm font-medium transition-colors"
|
|
2341
|
+
>
|
|
2342
|
+
Edit
|
|
2343
|
+
</button>
|
|
2344
|
+
)}
|
|
2345
|
+
</div>
|
|
2346
|
+
</div>
|
|
2347
|
+
</div>
|
|
2348
|
+
)
|
|
2349
|
+
}
|
|
2350
|
+
`,"src/components/CostBadge.tsx":`/** @mistflow-component cost-badge
|
|
2351
|
+
* @version 1.0.0
|
|
2352
|
+
* @source packages/agent-ui-components/src/components/CostBadge.tsx
|
|
2353
|
+
*
|
|
2354
|
+
* Subtle per-tool-call cost indicator. Reads cents from the AI Gateway's
|
|
2355
|
+
* X-Mistflow-Cost-Cents response header. Designed to fade into the
|
|
2356
|
+
* chrome \u2014 builds intuition over time, not anxiety in the moment.
|
|
2357
|
+
*/
|
|
2358
|
+
|
|
2359
|
+
import { cn } from '@/lib/cn'
|
|
2360
|
+
|
|
2361
|
+
export type CostBadgeProps = {
|
|
2362
|
+
cents: number
|
|
2363
|
+
status?: 'estimated' | 'final'
|
|
2364
|
+
className?: string
|
|
2365
|
+
}
|
|
2366
|
+
|
|
2367
|
+
export function CostBadge({
|
|
2368
|
+
cents,
|
|
2369
|
+
status = 'final',
|
|
2370
|
+
className,
|
|
2371
|
+
}: CostBadgeProps) {
|
|
2372
|
+
// Format: cents < 1 \u2192 "<$0.01", cents < 100 \u2192 "$0.XX", cents >= 100 \u2192 "$X.XX".
|
|
2373
|
+
const display =
|
|
2374
|
+
cents < 1
|
|
2375
|
+
? '<$0.01'
|
|
2376
|
+
: cents < 100
|
|
2377
|
+
? \`$\${(cents / 100).toFixed(2)}\`
|
|
2378
|
+
: \`$\${(cents / 100).toFixed(2)}\`
|
|
2379
|
+
|
|
2380
|
+
return (
|
|
2381
|
+
<span
|
|
2382
|
+
className={cn(
|
|
2383
|
+
'inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] font-mono tabular-nums',
|
|
2384
|
+
'bg-muted/50 text-muted-foreground',
|
|
2385
|
+
'transition-colors hover:text-foreground',
|
|
2386
|
+
className,
|
|
2387
|
+
)}
|
|
2388
|
+
title={
|
|
2389
|
+
status === 'estimated'
|
|
2390
|
+
? \`Estimated cost: \${display}\`
|
|
2391
|
+
: \`Cost: \${display}\`
|
|
2392
|
+
}
|
|
2393
|
+
>
|
|
2394
|
+
{status === 'estimated' && (
|
|
2395
|
+
<span aria-hidden className="opacity-60">
|
|
2396
|
+
~
|
|
2397
|
+
</span>
|
|
2398
|
+
)}
|
|
2399
|
+
{display}
|
|
2400
|
+
</span>
|
|
2401
|
+
)
|
|
2402
|
+
}
|
|
2403
|
+
`,"src/components/PlanSteps.tsx":`/** @mistflow-component plan-steps
|
|
2404
|
+
* @version 1.0.0
|
|
2405
|
+
* @source packages/agent-ui-components/src/components/PlanSteps.tsx
|
|
2406
|
+
*
|
|
2407
|
+
* Multi-step plan checklist at the top of an agent response. Status
|
|
2408
|
+
* flow per step: pending (muted square) \u2192 running (spinner) \u2192 complete
|
|
2409
|
+
* (emerald check) | failed (red x) | skipped (muted strikethrough).
|
|
2410
|
+
*/
|
|
2411
|
+
|
|
2412
|
+
'use client'
|
|
2413
|
+
|
|
2414
|
+
import { motion, AnimatePresence } from 'framer-motion'
|
|
2415
|
+
import { cn } from '@/lib/cn'
|
|
2416
|
+
|
|
2417
|
+
export type PlanStepStatus =
|
|
2418
|
+
| 'pending'
|
|
2419
|
+
| 'running'
|
|
2420
|
+
| 'complete'
|
|
2421
|
+
| 'failed'
|
|
2422
|
+
| 'skipped'
|
|
2423
|
+
|
|
2424
|
+
export type PlanStep = {
|
|
2425
|
+
id: string
|
|
2426
|
+
label: string
|
|
2427
|
+
status: PlanStepStatus
|
|
2428
|
+
detail?: string
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
export type PlanStepsProps = {
|
|
2432
|
+
steps: PlanStep[]
|
|
2433
|
+
className?: string
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
export function PlanSteps({ steps, className }: PlanStepsProps) {
|
|
2437
|
+
return (
|
|
2438
|
+
<div
|
|
2439
|
+
className={cn(
|
|
2440
|
+
'rounded-lg border border-border bg-card/50 backdrop-blur-sm p-3 space-y-1.5',
|
|
2441
|
+
className,
|
|
2442
|
+
)}
|
|
2443
|
+
>
|
|
2444
|
+
<div className="text-[11px] uppercase tracking-wider text-muted-foreground font-medium mb-1">
|
|
2445
|
+
Plan
|
|
2446
|
+
</div>
|
|
2447
|
+
<AnimatePresence initial={false}>
|
|
2448
|
+
{steps.map((step, i) => (
|
|
2449
|
+
<motion.div
|
|
2450
|
+
key={step.id}
|
|
2451
|
+
initial={{ opacity: 0, y: -2 }}
|
|
2452
|
+
animate={{ opacity: 1, y: 0 }}
|
|
2453
|
+
exit={{ opacity: 0 }}
|
|
2454
|
+
transition={{ duration: 0.15, delay: i * 0.03 }}
|
|
2455
|
+
className="flex items-start gap-2 text-sm"
|
|
2456
|
+
>
|
|
2457
|
+
<StatusIcon status={step.status} />
|
|
2458
|
+
<div className="flex-1 min-w-0">
|
|
2459
|
+
<div
|
|
2460
|
+
className={cn(
|
|
2461
|
+
'leading-snug',
|
|
2462
|
+
step.status === 'complete' && 'text-muted-foreground',
|
|
2463
|
+
step.status === 'skipped' &&
|
|
2464
|
+
'text-muted-foreground line-through',
|
|
2465
|
+
step.status === 'failed' && 'text-[var(--color-red)]',
|
|
2466
|
+
)}
|
|
2467
|
+
>
|
|
2468
|
+
{step.label}
|
|
2469
|
+
</div>
|
|
2470
|
+
{step.detail && (
|
|
2471
|
+
<div className="text-xs text-muted-foreground mt-0.5">
|
|
2472
|
+
{step.detail}
|
|
2473
|
+
</div>
|
|
2474
|
+
)}
|
|
2475
|
+
</div>
|
|
2476
|
+
</motion.div>
|
|
2477
|
+
))}
|
|
2478
|
+
</AnimatePresence>
|
|
2479
|
+
</div>
|
|
2480
|
+
)
|
|
2481
|
+
}
|
|
2482
|
+
|
|
2483
|
+
function StatusIcon({ status }: { status: PlanStepStatus }) {
|
|
2484
|
+
const baseClass = 'shrink-0 mt-0.5 w-4 h-4 flex items-center justify-center'
|
|
2485
|
+
|
|
2486
|
+
if (status === 'running') {
|
|
2487
|
+
return (
|
|
2488
|
+
<span
|
|
2489
|
+
className={baseClass}
|
|
2490
|
+
style={{ color: 'var(--color-accent)' }}
|
|
2491
|
+
aria-label="running"
|
|
2492
|
+
>
|
|
2493
|
+
<span
|
|
2494
|
+
className="inline-block w-3 h-3 rounded-full border-2 border-current border-t-transparent animate-spin"
|
|
2495
|
+
aria-hidden
|
|
2496
|
+
/>
|
|
2497
|
+
</span>
|
|
2498
|
+
)
|
|
2499
|
+
}
|
|
2500
|
+
|
|
2501
|
+
if (status === 'complete') {
|
|
2502
|
+
return (
|
|
2503
|
+
<span
|
|
2504
|
+
className={cn(baseClass, 'text-[var(--color-emerald)]')}
|
|
2505
|
+
aria-label="complete"
|
|
2506
|
+
>
|
|
2507
|
+
<svg viewBox="0 0 16 16" fill="none" className="w-4 h-4">
|
|
2508
|
+
<path
|
|
2509
|
+
d="M3.5 8.5L7 12L13 5"
|
|
2510
|
+
stroke="currentColor"
|
|
2511
|
+
strokeWidth="1.75"
|
|
2512
|
+
strokeLinecap="round"
|
|
2513
|
+
strokeLinejoin="round"
|
|
2514
|
+
/>
|
|
2515
|
+
</svg>
|
|
2516
|
+
</span>
|
|
2517
|
+
)
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2520
|
+
if (status === 'failed') {
|
|
2521
|
+
return (
|
|
2522
|
+
<span
|
|
2523
|
+
className={cn(baseClass, 'text-[var(--color-red)]')}
|
|
2524
|
+
aria-label="failed"
|
|
2525
|
+
>
|
|
2526
|
+
<svg viewBox="0 0 16 16" fill="none" className="w-4 h-4">
|
|
2527
|
+
<path
|
|
2528
|
+
d="M4 4L12 12M12 4L4 12"
|
|
2529
|
+
stroke="currentColor"
|
|
2530
|
+
strokeWidth="1.75"
|
|
2531
|
+
strokeLinecap="round"
|
|
2532
|
+
/>
|
|
2533
|
+
</svg>
|
|
2534
|
+
</span>
|
|
2535
|
+
)
|
|
2536
|
+
}
|
|
2537
|
+
|
|
2538
|
+
if (status === 'skipped') {
|
|
2539
|
+
return (
|
|
2540
|
+
<span
|
|
2541
|
+
className={cn(baseClass, 'text-muted-foreground/60')}
|
|
2542
|
+
aria-label="skipped"
|
|
2543
|
+
>
|
|
2544
|
+
<span className="block w-2.5 h-px bg-current" />
|
|
2545
|
+
</span>
|
|
2546
|
+
)
|
|
2547
|
+
}
|
|
2548
|
+
|
|
2549
|
+
// pending
|
|
2550
|
+
return (
|
|
2551
|
+
<span
|
|
2552
|
+
className={cn(baseClass, 'text-muted-foreground/40')}
|
|
2553
|
+
aria-label="pending"
|
|
2554
|
+
>
|
|
2555
|
+
<span className="block w-2.5 h-2.5 rounded-sm border border-current" />
|
|
2556
|
+
</span>
|
|
2557
|
+
)
|
|
2558
|
+
}
|
|
2559
|
+
`,"src/components/SuggestedPrompts.tsx":`/** @mistflow-component suggested-prompts
|
|
2560
|
+
* @version 1.0.0
|
|
2561
|
+
* @source packages/agent-ui-components/src/components/SuggestedPrompts.tsx
|
|
2562
|
+
*
|
|
2563
|
+
* Context-aware prompt chips rendered after the assistant's turn. The
|
|
2564
|
+
* chip set is generated by the parent (an engine that knows conversation
|
|
2565
|
+
* context: just-uploaded a file, just-loaded a table, just got an error)
|
|
2566
|
+
* \u2014 this component just renders. Keeps the engine swappable.
|
|
2567
|
+
*/
|
|
2568
|
+
|
|
2569
|
+
'use client'
|
|
2570
|
+
|
|
2571
|
+
import { motion } from 'framer-motion'
|
|
2572
|
+
import { cn } from '@/lib/cn'
|
|
2573
|
+
|
|
2574
|
+
export type SuggestedPrompt = {
|
|
2575
|
+
id: string
|
|
2576
|
+
// 1-3 word leading icon/emoji optional
|
|
2577
|
+
icon?: string
|
|
2578
|
+
// The text shown on the chip and inserted into the input on click
|
|
2579
|
+
text: string
|
|
2580
|
+
// Optional longer-form prompt sent to the model on click (defaults to
|
|
2581
|
+
// text if absent). Lets short chip labels expand to detailed prompts.
|
|
2582
|
+
fullPrompt?: string
|
|
2583
|
+
}
|
|
2584
|
+
|
|
2585
|
+
export type SuggestedPromptsProps = {
|
|
2586
|
+
prompts: SuggestedPrompt[]
|
|
2587
|
+
onSelect: (prompt: SuggestedPrompt) => void
|
|
2588
|
+
className?: string
|
|
2589
|
+
// Show as horizontally scrolling row on mobile, wrap on desktop.
|
|
2590
|
+
scrollOnMobile?: boolean
|
|
2591
|
+
}
|
|
2072
2592
|
|
|
2073
|
-
The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(g.outcome==="submitted"){let f=g.urlChoice?.trim()||g.answers?.[0]?.answer.trim()||"";f=f.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(f)||!f)&&(f=be);let k=f.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(k)?E=k:(console.error(`[mist_plan] URL elicitation returned '${f}' \u2014 does not look like a subdomain. Using default '${be}'.`),E=be)}else g.outcome==="declined"||g.outcome,E=be}else E||(E=be);let Le=U.publicPages;if(!Le||Array.isArray(Le)&&Le.length===0){let g=U.pages,f=se.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),k=Array.isArray(g)&&g.some(T=>T.path==="/"||T.route==="/");f||k?Le=["/","/pricing"]:Le=["/"]}let it=U.primaryAction;if(!it){let g=U.features;if(Array.isArray(g)&&g.length>0){let k=g.find(O=>typeof O.priority=="string"&&O.priority.toLowerCase()==="must-have")??g[0];it={entity:k.name??k.title??"item",action:"create",fromPage:"/dashboard"}}}let Ye=U.nonNegotiables;(!Ye||Array.isArray(Ye)&&Ye.length===0)&&(Ye=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Qe=Qo(),at=ge(gt(),".mistflow","plans");Ct(at,{recursive:!0});try{let f=Date.now();for(let k of[at,ge(gt(),".mistflow","mockup-state")])if(rt(k))for(let T of ni(k))try{let O=ge(k,T),z=ri(O).mtimeMs;f-z>6048e5&&sd(O)}catch{}}catch{}let _e=U,F={name:U.name,summary:U.summary,dataModel:U.dataModel,pages:U.pages,features:U.features,steps:se.map(g=>({...g,name:g.name??g.title})),design:U.design,dbProvider:U.dbProvider??"neon",authModel:U.authModel,audienceType:U.audienceType??"b2c",roles:U.roles,defaultRole:U.defaultRole,publicPages:Le,navStyle:U.navStyle,multiTenant:U.multiTenant,primaryAction:it,nonNegotiables:Ye,requestedSubdomain:E,...u&&u.toLowerCase()!=="english"?{language:u}:{},..._e.pickedDirection?{pickedDirection:_e.pickedDirection}:{},..._e.imageryBrief?{imageryBrief:_e.imageryBrief}:{},..._e.designConversationId?{designConversationId:_e.designConversationId}:{}};ht(ge(at,`${Qe}.json`),JSON.stringify({plan:F,methodology:Re,...W?{scaffoldTargetPath:W}:{}}));let de=se.map(g=>`${g.number}. ${g.name??g.title}`),Se,$e="";if(!!!_e.pickedDirection){let f=(U.audienceType??"b2c")==="b2c";Se={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:f?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:f?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},$e=" 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 qe="",Ee=[];for(let g of se){let f=g.name??g.title,k=g.integrationId;if(k){let T=$t(k);if(T){let O=Ut(T.id);Ee.push({step:f,presetId:T.id,presetName:T.name,envVars:O?.envVars??[]})}}}if(Ee.length>0){let g=Ee.flatMap(T=>T.envVars),f=[...new Set(g.map(T=>T.key))];qe=` This plan uses integrations (${Ee.map(T=>T.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${f.length>0?` The user will need these API keys: ${f.join(", ")}.`:""}`}return d(JSON.stringify({planId:Qe,name:U.name,summary:U.summary,stepCount:se.length,steps:de,design:U.design,...Se?{heroPhotoQuestion:Se}:{},...Ee.length>0?{integrations:Ee.map(g=>({step:g.step,preset:g.presetId,name:g.presetName,envVars:g.envVars}))}:{},message:`Plan generated for "${fe}" (${se.length} steps).${qe}${$e}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,se.length*3)}\u2013${se.length*5} minutes total across ${se.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: '${Qe}' }). If the user says skip or "just build it", call mist_init({ planId: '${Qe}'${W?"":", path: '<absolute path>'"} }) immediately.`,...W?{scaffoldTargetPath:W}:{},...R?{warning:R}:{}}))}var tr,dd,bd,ai,li=_(()=>{"use strict";ve();Pe();Ho();Bt();Wo();Gn();Ko();Jo();tr="__mistflow_url_choice__",dd=600*1e3;bd=L.object({description:L.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:L.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:L.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:L.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:L.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}},L.union([L.record(L.string()),L.array(L.object({question:L.string().optional(),decisionKey:L.string().optional(),answer:L.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:L.record(L.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:L.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:L.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:L.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:L.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:L.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:L.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:L.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:L.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:L.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:L.object({id:L.string().optional(),name:L.string().optional(),summary:L.string().optional(),heroHeadline:L.string().optional(),ctaText:L.string().optional(),bodySample:L.string().optional(),fontsHint:L.string().optional(),fonts:L.object({display:L.string(),body:L.string()}).partial().optional(),colorMood:L.string().optional(),colors:L.object({bg:L.string(),fg:L.string(),accent:L.string()}).partial().optional(),heroTreatment:L.string().optional(),shapeLang:L.string().optional(),texture:L.string().optional(),decorationHint:L.string().optional(),custom:L.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:L.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:L.boolean().optional().describe("Set to true ONLY after the user has explicitly chosen 'start fresh' from a previous mist_plan response with status 'resume_offer'. Suppresses the resume-offer check and lets a new session start even when this machine has unfinished work in flight. Do NOT set this preemptively on the first call \u2014 the resume-offer check needs to run so the user gets the chance to pick up where they left off.")});ai={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist'). Clear new-app requests inside an existing non-Mistflow repo are scaffolded into a remembered child directory; Mistflow does not edit the surrounding codebase.","",`DESIGN REFERENCES (screenshots, Figma, brand names): if the user drags a screenshot, pastes a Figma URL, or names a brand to match ("make it feel like Linear"), use your native vision/knowledge to extract design tokens and submit them via designDirection: { custom: '<your description>', ...extracted_tokens } with userConfirmedCustom: true. The flag is required because the user supplied the reference; without it the server rejects the submission to stop AIs from inventing custom directions. Full flow at docs/design-references.md.`,"","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). For clear new-app requests it automatically creates and remembers a child scaffold directory. For ambiguous requests, it returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token from the response. Do not change projectPath to the suggested child path; Mistflow stores that target for mist_init.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_init with the returned planId. If the response includes scaffoldTargetPath you do not need to pass path; mist_init loads it from the cached plan. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","SESSIONID FLOW (dumb-ai-proof, when the response includes sessionId): keep the sessionId and pass it on every subsequent mist_* call. Calling mist_plan with just { sessionId, projectPath } polls GET /api/sessions/{id}/next and returns the next instruction (wait | ask_user | pick_design | review_mockup | call_mist_init | call_mist_install | call_mist_implement | call_mist_build | call_mist_deploy | call_mist_qa | done). Do exactly what the instruction says \u2014 don't branch on raw state. The backend owns routing; the host relays.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. The aesthetic (fonts, colors, motion) is decided by the design-direction picker step \u2014 the host AI doesn't pick a catalog ID."].join(`
|
|
2074
|
-
|
|
2075
|
-
`)}var nr=_(()=>{"use strict"});var rr,ps=_(()=>{rr="\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 sr,us=_(()=>{sr=`# Landing Page Rules
|
|
2593
|
+
export function SuggestedPrompts({
|
|
2594
|
+
prompts,
|
|
2595
|
+
onSelect,
|
|
2596
|
+
className,
|
|
2597
|
+
scrollOnMobile = true,
|
|
2598
|
+
}: SuggestedPromptsProps) {
|
|
2599
|
+
if (prompts.length === 0) return null
|
|
2600
|
+
|
|
2601
|
+
return (
|
|
2602
|
+
<div
|
|
2603
|
+
className={cn(
|
|
2604
|
+
scrollOnMobile && 'overflow-x-auto -mx-4 px-4 sm:overflow-visible sm:mx-0 sm:px-0',
|
|
2605
|
+
className,
|
|
2606
|
+
)}
|
|
2607
|
+
>
|
|
2608
|
+
<div
|
|
2609
|
+
className={cn(
|
|
2610
|
+
'flex gap-2',
|
|
2611
|
+
scrollOnMobile ? 'sm:flex-wrap' : 'flex-wrap',
|
|
2612
|
+
)}
|
|
2613
|
+
>
|
|
2614
|
+
{prompts.map((p, i) => (
|
|
2615
|
+
<motion.button
|
|
2616
|
+
key={p.id}
|
|
2617
|
+
type="button"
|
|
2618
|
+
initial={{ opacity: 0, y: 4 }}
|
|
2619
|
+
animate={{ opacity: 1, y: 0 }}
|
|
2620
|
+
transition={{ duration: 0.18, delay: i * 0.04 }}
|
|
2621
|
+
onClick={() => onSelect(p)}
|
|
2622
|
+
className={cn(
|
|
2623
|
+
'shrink-0 inline-flex items-center gap-1.5 rounded-full',
|
|
2624
|
+
'border border-border bg-card hover:bg-muted/60',
|
|
2625
|
+
'px-3 py-1.5 text-sm text-foreground',
|
|
2626
|
+
'transition-colors active:scale-[0.98]',
|
|
2627
|
+
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]',
|
|
2628
|
+
)}
|
|
2629
|
+
>
|
|
2630
|
+
{p.icon && (
|
|
2631
|
+
<span aria-hidden className="text-[15px] leading-none">
|
|
2632
|
+
{p.icon}
|
|
2633
|
+
</span>
|
|
2634
|
+
)}
|
|
2635
|
+
<span>{p.text}</span>
|
|
2636
|
+
</motion.button>
|
|
2637
|
+
))}
|
|
2638
|
+
</div>
|
|
2639
|
+
</div>
|
|
2640
|
+
)
|
|
2641
|
+
}
|
|
2642
|
+
`,"src/components/ToolStream.tsx":`/** @mistflow-component tool-stream
|
|
2643
|
+
* @version 1.0.0
|
|
2644
|
+
* @source packages/agent-ui-components/src/components/ToolStream.tsx
|
|
2645
|
+
*
|
|
2646
|
+
* Rich tool-call card: live status, streaming stdout, embedded result,
|
|
2647
|
+
* expandable raw args. Lifecycle:
|
|
2648
|
+
* "pending" \u2192 spinner + "Preparing ..."
|
|
2649
|
+
* "running" \u2192 spinner + streaming logs visible
|
|
2650
|
+
* "complete" \u2192 \u2713 + result embedded (children)
|
|
2651
|
+
* "failed" \u2192 \u26A0 + error; agent's recovery suggestion below
|
|
2652
|
+
*/
|
|
2653
|
+
|
|
2654
|
+
'use client'
|
|
2655
|
+
|
|
2656
|
+
import { useState, type ReactNode } from 'react'
|
|
2657
|
+
import { motion, AnimatePresence } from 'framer-motion'
|
|
2658
|
+
import { cn } from '@/lib/cn'
|
|
2659
|
+
import { CostBadge } from './CostBadge'
|
|
2660
|
+
|
|
2661
|
+
export type ToolStreamStatus = 'pending' | 'running' | 'complete' | 'failed'
|
|
2662
|
+
|
|
2663
|
+
export type ToolStreamProps = {
|
|
2664
|
+
// Human-readable tool name. "Running Python", not "run_python".
|
|
2665
|
+
toolLabel: string
|
|
2666
|
+
// One-line key input summary. "on sales.csv (89 rows)" or
|
|
2667
|
+
// "fetching weather for San Francisco". Concrete, not generic.
|
|
2668
|
+
keyInput?: string
|
|
2669
|
+
status: ToolStreamStatus
|
|
2670
|
+
// Streaming stdout/stderr lines as they arrive. Auto-scrolls inside
|
|
2671
|
+
// the card while running, freezes on completion.
|
|
2672
|
+
streamLines?: string[]
|
|
2673
|
+
// Total elapsed time once complete (or current if running) in ms.
|
|
2674
|
+
// Renders subtly in the card chrome when >= 2000.
|
|
2675
|
+
elapsedMs?: number
|
|
2676
|
+
// Optional cost telemetry \u2014 shown in chrome.
|
|
2677
|
+
costCents?: number
|
|
2678
|
+
// Raw args object \u2014 shown only when user expands "raw args".
|
|
2679
|
+
rawArgs?: Record<string, unknown>
|
|
2680
|
+
// Error message when status === 'failed'.
|
|
2681
|
+
error?: string
|
|
2682
|
+
// The embedded result \u2014 chart, table, image, structured JSON. Renders
|
|
2683
|
+
// below the stream when status === 'complete'.
|
|
2684
|
+
children?: ReactNode
|
|
2685
|
+
}
|
|
2686
|
+
|
|
2687
|
+
export function ToolStream({
|
|
2688
|
+
toolLabel,
|
|
2689
|
+
keyInput,
|
|
2690
|
+
status,
|
|
2691
|
+
streamLines = [],
|
|
2692
|
+
elapsedMs,
|
|
2693
|
+
costCents,
|
|
2694
|
+
rawArgs,
|
|
2695
|
+
error,
|
|
2696
|
+
children,
|
|
2697
|
+
}: ToolStreamProps) {
|
|
2698
|
+
const [rawOpen, setRawOpen] = useState(false)
|
|
2699
|
+
const [streamOpen, setStreamOpen] = useState(status === 'running')
|
|
2700
|
+
const showElapsed = elapsedMs !== undefined && elapsedMs >= 2000
|
|
2701
|
+
const isBusy = status === 'pending' || status === 'running'
|
|
2702
|
+
|
|
2703
|
+
return (
|
|
2704
|
+
<motion.div
|
|
2705
|
+
layout
|
|
2706
|
+
initial={{ opacity: 0, scale: 0.98 }}
|
|
2707
|
+
animate={{ opacity: 1, scale: 1 }}
|
|
2708
|
+
transition={{ duration: 0.2 }}
|
|
2709
|
+
className="my-3 rounded-lg border border-border bg-card overflow-hidden"
|
|
2710
|
+
>
|
|
2711
|
+
{/* Header */}
|
|
2712
|
+
<div className="flex items-center gap-2 px-3 py-2 border-b border-border/60">
|
|
2713
|
+
<StatusGlyph status={status} />
|
|
2714
|
+
<div className="flex-1 min-w-0">
|
|
2715
|
+
<div className="flex items-baseline gap-2 min-w-0">
|
|
2716
|
+
<span className="text-sm font-medium text-foreground shrink-0">
|
|
2717
|
+
{toolLabel}
|
|
2718
|
+
</span>
|
|
2719
|
+
{keyInput && (
|
|
2720
|
+
<span className="text-sm text-muted-foreground truncate">
|
|
2721
|
+
{keyInput}
|
|
2722
|
+
</span>
|
|
2723
|
+
)}
|
|
2724
|
+
</div>
|
|
2725
|
+
</div>
|
|
2726
|
+
<div className="flex items-center gap-2 shrink-0">
|
|
2727
|
+
{showElapsed && (
|
|
2728
|
+
<span className="text-[11px] text-muted-foreground font-mono tabular-nums">
|
|
2729
|
+
{formatElapsed(elapsedMs!)}
|
|
2730
|
+
</span>
|
|
2731
|
+
)}
|
|
2732
|
+
{costCents !== undefined && (
|
|
2733
|
+
<CostBadge
|
|
2734
|
+
cents={costCents}
|
|
2735
|
+
status={status === 'complete' ? 'final' : 'estimated'}
|
|
2736
|
+
/>
|
|
2737
|
+
)}
|
|
2738
|
+
</div>
|
|
2739
|
+
</div>
|
|
2740
|
+
|
|
2741
|
+
{/* Stream area */}
|
|
2742
|
+
{streamLines.length > 0 && (
|
|
2743
|
+
<div>
|
|
2744
|
+
<button
|
|
2745
|
+
type="button"
|
|
2746
|
+
onClick={() => setStreamOpen((v) => !v)}
|
|
2747
|
+
className="w-full flex items-center gap-1.5 px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground hover:bg-muted/30 transition-colors"
|
|
2748
|
+
>
|
|
2749
|
+
<span className="font-mono">
|
|
2750
|
+
{streamOpen ? '\u25BE' : '\u25B8'}
|
|
2751
|
+
</span>
|
|
2752
|
+
<span>
|
|
2753
|
+
{streamOpen ? 'Hide' : 'Show'} output ({streamLines.length} line
|
|
2754
|
+
{streamLines.length === 1 ? '' : 's'})
|
|
2755
|
+
</span>
|
|
2756
|
+
</button>
|
|
2757
|
+
<AnimatePresence>
|
|
2758
|
+
{streamOpen && (
|
|
2759
|
+
<motion.pre
|
|
2760
|
+
initial={{ height: 0, opacity: 0 }}
|
|
2761
|
+
animate={{ height: 'auto', opacity: 1 }}
|
|
2762
|
+
exit={{ height: 0, opacity: 0 }}
|
|
2763
|
+
transition={{ duration: 0.18 }}
|
|
2764
|
+
className={cn(
|
|
2765
|
+
'px-3 pb-3 text-[12px] font-mono leading-relaxed',
|
|
2766
|
+
'text-muted-foreground whitespace-pre-wrap break-words',
|
|
2767
|
+
'max-h-48 overflow-y-auto',
|
|
2768
|
+
isBusy && 'border-l-2 border-[var(--color-accent)]/40 ml-3 pl-2',
|
|
2769
|
+
)}
|
|
2770
|
+
>
|
|
2771
|
+
{streamLines.join('\\n')}
|
|
2772
|
+
</motion.pre>
|
|
2773
|
+
)}
|
|
2774
|
+
</AnimatePresence>
|
|
2775
|
+
</div>
|
|
2776
|
+
)}
|
|
2777
|
+
|
|
2778
|
+
{/* Error */}
|
|
2779
|
+
{status === 'failed' && error && (
|
|
2780
|
+
<div className="px-3 py-2 text-sm text-[var(--color-red)] bg-red-500/5 border-t border-border/60">
|
|
2781
|
+
{error}
|
|
2782
|
+
</div>
|
|
2783
|
+
)}
|
|
2784
|
+
|
|
2785
|
+
{/* Result */}
|
|
2786
|
+
{status === 'complete' && children && (
|
|
2787
|
+
<motion.div
|
|
2788
|
+
initial={{ opacity: 0, y: 4 }}
|
|
2789
|
+
animate={{ opacity: 1, y: 0 }}
|
|
2790
|
+
transition={{ duration: 0.25, delay: 0.05 }}
|
|
2791
|
+
className="border-t border-border/60"
|
|
2792
|
+
>
|
|
2793
|
+
{children}
|
|
2794
|
+
</motion.div>
|
|
2795
|
+
)}
|
|
2796
|
+
|
|
2797
|
+
{/* Raw args footer */}
|
|
2798
|
+
{rawArgs && (
|
|
2799
|
+
<div className="border-t border-border/60">
|
|
2800
|
+
<button
|
|
2801
|
+
type="button"
|
|
2802
|
+
onClick={() => setRawOpen((v) => !v)}
|
|
2803
|
+
className="w-full text-left px-3 py-1.5 text-[11px] text-muted-foreground/80 hover:text-muted-foreground hover:bg-muted/30 transition-colors font-mono"
|
|
2804
|
+
>
|
|
2805
|
+
{rawOpen ? '\u25BE' : '\u25B8'} raw args
|
|
2806
|
+
</button>
|
|
2807
|
+
{rawOpen && (
|
|
2808
|
+
<pre className="px-3 pb-3 text-[11px] font-mono text-muted-foreground/80 overflow-x-auto">
|
|
2809
|
+
{JSON.stringify(rawArgs, null, 2)}
|
|
2810
|
+
</pre>
|
|
2811
|
+
)}
|
|
2812
|
+
</div>
|
|
2813
|
+
)}
|
|
2814
|
+
</motion.div>
|
|
2815
|
+
)
|
|
2816
|
+
}
|
|
2817
|
+
|
|
2818
|
+
function StatusGlyph({ status }: { status: ToolStreamStatus }) {
|
|
2819
|
+
if (status === 'pending' || status === 'running') {
|
|
2820
|
+
return (
|
|
2821
|
+
<span
|
|
2822
|
+
className="inline-block w-3 h-3 rounded-full border-2 border-current border-t-transparent animate-spin shrink-0"
|
|
2823
|
+
style={{ color: 'var(--color-accent)' }}
|
|
2824
|
+
aria-label="running"
|
|
2825
|
+
/>
|
|
2826
|
+
)
|
|
2827
|
+
}
|
|
2828
|
+
if (status === 'complete') {
|
|
2829
|
+
return (
|
|
2830
|
+
<span
|
|
2831
|
+
className="text-[var(--color-emerald)] shrink-0"
|
|
2832
|
+
aria-label="complete"
|
|
2833
|
+
>
|
|
2834
|
+
<svg viewBox="0 0 16 16" className="w-4 h-4" fill="none">
|
|
2835
|
+
<path
|
|
2836
|
+
d="M3.5 8.5L7 12L13 5"
|
|
2837
|
+
stroke="currentColor"
|
|
2838
|
+
strokeWidth="1.75"
|
|
2839
|
+
strokeLinecap="round"
|
|
2840
|
+
strokeLinejoin="round"
|
|
2841
|
+
/>
|
|
2842
|
+
</svg>
|
|
2843
|
+
</span>
|
|
2844
|
+
)
|
|
2845
|
+
}
|
|
2846
|
+
return (
|
|
2847
|
+
<span className="text-[var(--color-red)] shrink-0" aria-label="failed">
|
|
2848
|
+
<svg viewBox="0 0 16 16" className="w-4 h-4" fill="none">
|
|
2849
|
+
<path
|
|
2850
|
+
d="M4 4L12 12M12 4L4 12"
|
|
2851
|
+
stroke="currentColor"
|
|
2852
|
+
strokeWidth="1.75"
|
|
2853
|
+
strokeLinecap="round"
|
|
2854
|
+
/>
|
|
2855
|
+
</svg>
|
|
2856
|
+
</span>
|
|
2857
|
+
)
|
|
2858
|
+
}
|
|
2859
|
+
|
|
2860
|
+
function formatElapsed(ms: number): string {
|
|
2861
|
+
if (ms < 1000) return \`\${ms}ms\`
|
|
2862
|
+
if (ms < 60_000) return \`\${(ms / 1000).toFixed(1)}s\`
|
|
2863
|
+
return \`\${Math.floor(ms / 60_000)}m\${Math.round((ms % 60_000) / 1000)}s\`
|
|
2864
|
+
}
|
|
2865
|
+
`,"src/lib/cn.ts":`/** @mistflow-component cn-helper
|
|
2866
|
+
* @version 1.0.0
|
|
2867
|
+
* @source packages/agent-ui-components/src/lib/cn.ts
|
|
2868
|
+
* @skip-if-exists true
|
|
2869
|
+
*
|
|
2870
|
+
* Standard clsx + tailwind-merge helper. Manifest marks skipIfExists so
|
|
2871
|
+
* projects that already have this file from the base scaffold keep theirs.
|
|
2872
|
+
*/
|
|
2873
|
+
|
|
2874
|
+
import { clsx, type ClassValue } from 'clsx'
|
|
2875
|
+
import { twMerge } from 'tailwind-merge'
|
|
2876
|
+
|
|
2877
|
+
export function cn(...inputs: ClassValue[]) {
|
|
2878
|
+
return twMerge(clsx(inputs))
|
|
2879
|
+
}
|
|
2880
|
+
`,"src/lib/agent-types.ts":`/** @mistflow-component agent-types
|
|
2881
|
+
* @version 1.0.0
|
|
2882
|
+
* @source packages/agent-ui-components/src/lib/agent-types.ts
|
|
2883
|
+
*
|
|
2884
|
+
* Canonical event shape the agent-ui components consume.
|
|
2885
|
+
*
|
|
2886
|
+
* The names track the AI SDK 6 stream-event vocabulary (text-delta,
|
|
2887
|
+
* tool-input-start, tool-input-available, ...) plus a few Mistflow-specific
|
|
2888
|
+
* events for plan/approval/suggestions that AI SDK doesn't model. When the
|
|
2889
|
+
* gateway ships streaming (Phase 2 of agent-ui-rollout.md), these names
|
|
2890
|
+
* align so the reducer doesn't need an adapter.
|
|
2891
|
+
*/
|
|
2892
|
+
|
|
2893
|
+
export type AgentEvent =
|
|
2894
|
+
| { kind: 'text'; text: string }
|
|
2895
|
+
| { kind: 'plan'; steps: { id: string; label: string; detail?: string }[] }
|
|
2896
|
+
| {
|
|
2897
|
+
kind: 'plan-update'
|
|
2898
|
+
stepId: string
|
|
2899
|
+
status: 'pending' | 'running' | 'complete' | 'failed' | 'skipped'
|
|
2900
|
+
}
|
|
2901
|
+
| {
|
|
2902
|
+
kind: 'tool-start'
|
|
2903
|
+
toolCallId: string
|
|
2904
|
+
toolLabel: string
|
|
2905
|
+
keyInput: string
|
|
2906
|
+
rawArgs?: Record<string, unknown>
|
|
2907
|
+
}
|
|
2908
|
+
| { kind: 'tool-log'; toolCallId: string; line: string }
|
|
2909
|
+
| {
|
|
2910
|
+
kind: 'tool-complete'
|
|
2911
|
+
toolCallId: string
|
|
2912
|
+
costCents: number
|
|
2913
|
+
elapsedMs: number
|
|
2914
|
+
result: 'chart' | 'table' | 'text' | 'json'
|
|
2915
|
+
}
|
|
2916
|
+
| {
|
|
2917
|
+
kind: 'approval-request'
|
|
2918
|
+
approvalId: string
|
|
2919
|
+
toolLabel: string
|
|
2920
|
+
summary: string
|
|
2921
|
+
risk: 'safe' | 'external-write' | 'destructive'
|
|
2922
|
+
estimatedCost?: string
|
|
2923
|
+
details?: string
|
|
2924
|
+
}
|
|
2925
|
+
| { kind: 'approval-resolved'; approvalId: string }
|
|
2926
|
+
| { kind: 'suggestions'; prompts: { id: string; icon: string; text: string }[] }
|
|
2927
|
+
| { kind: 'done' }
|
|
2928
|
+
`}});var Ii={};on(Ii,{installAgentUi:()=>cs,planRequiresAgentUiInstall:()=>ls,readComponentsInstalledLedger:()=>To,selfHealAgentUi:()=>Yd});import{existsSync as xo,mkdirSync as Si,readFileSync as Ti,writeFileSync as So}from"fs";import{join as as,dirname as zd}from"path";import{createHash as Hd}from"crypto";function Wd(t){return`sha256:${Hd("sha256").update(t).digest("hex")}`}function Gd(t,e,s){let n=[];for(let o of t.files){let i=e[o.src];if(typeof i!="string")throw new Error(`bundle is corrupt: missing content for ${o.src}. Run 'pnpm --filter @mistflow-ai/agent-ui-components run generate-bundle'.`);let r=as(s,o.dst);o.skipIfExists&&xo(r)||(Si(zd(r),{recursive:!0}),So(r,i),n.push({path:o.dst,sourceVersion:o.version,sourceHash:o.sourceHash,installedHash:Wd(i)}))}return n}function Vd(t,e){let s=[],n=[];if(!xo(t))return{added:s,skipped:n};let o=JSON.parse(Ti(t,"utf8"));o.dependencies??={};for(let[i,r]of Object.entries(e)){if(o.dependencies[i]||o.devDependencies?.[i]){n.push(i);continue}o.dependencies[i]=r,s.push(i)}return So(t,JSON.stringify(o,null,2)+`
|
|
2929
|
+
`),{added:s,skipped:n}}function _i(t){return as(t,".mistflow","components-installed.json")}function To(t){let e=_i(t);if(!xo(e))return{presets:{}};try{let s=Ti(e,"utf8");return{presets:JSON.parse(s)?.presets??{}}}catch{return{presets:{}}}}function Kd(t,e){let s=as(t,".mistflow");Si(s,{recursive:!0}),So(_i(t),JSON.stringify(e,null,2)+`
|
|
2930
|
+
`)}function Jd(t,e){return t?(Array.isArray(t.integrations)?t.integrations:[]).some(n=>{if(typeof n=="string")return n===e;if(n&&typeof n=="object"){let o=n;return o.id===e||o.slug===e||o.name===e}return!1}):!1}function ls(t,e){return Jd(t,"agent-ui")?!To(e).presets["agent-ui"]:!1}function cs(t,e=new Date){let s=Gd(it,xi,t),{added:n,skipped:o}=Vd(as(t,"package.json"),it.dependencies),i=To(t);return i.presets[it.slug]={presetVersion:it.version,installedAt:e.toISOString(),files:s},Kd(t,i),{slug:it.slug,installed:s,depsAdded:n,depsSkipped:o}}function Yd(t,e){if(!ls(t,e))return null;try{let s=cs(e),n=s.depsAdded.length?`, +${s.depsAdded.length} deps`:"";return{message:`installed agent-ui preset (${s.installed.length} files${n})`,isError:!1}}catch(s){return{message:`agent-ui install failed: ${s instanceof Error?s.message:String(s)}`,isError:!0}}}var _o=I(()=>{"use strict";ko()});function Qd(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 Gt(t=process.version){let e=Qd(t);return!e||e.major>=23?!0:e.major===22?e.minor>=12:e.major===20?e.minor>=19:!1}function Xd(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 Ot(t=process.version,e=Xd()){let s={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}.`,s[e],"Then quit and reopen your IDE so the MCP picks up the new Node."].join(`
|
|
2931
|
+
`)}var ds=I(()=>{"use strict"});var ps,Io=I(()=>{ps="\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 us,Po=I(()=>{us=`# Landing Page Rules
|
|
2076
2932
|
|
|
2077
2933
|
These rules apply to every landing page. They are non-negotiable.
|
|
2078
2934
|
|
|
@@ -2185,14 +3041,14 @@ Every element on the page drives toward the primary CTA. If a section doesn't mo
|
|
|
2185
3041
|
### Hero (required)
|
|
2186
3042
|
|
|
2187
3043
|
The most important section. Must have:
|
|
2188
|
-
- A headline that's large and bold (
|
|
3044
|
+
- A headline that's large and bold (canonical ladder: \`text-4xl md:text-5xl lg:text-6xl\`)
|
|
2189
3045
|
- A subheadline (1-2 sentences, \`text-lg\` to \`text-xl\`, muted color)
|
|
2190
3046
|
- One or two CTAs (primary filled button + optional secondary ghost/outline)
|
|
2191
3047
|
- A visual element: product screenshot, photo, abstract shape, or animated element
|
|
2192
3048
|
|
|
2193
3049
|
**Hero sizing (must fit the viewport \u2014 non-negotiable):**
|
|
2194
3050
|
- The primary CTA must be visible on a 1280x800 laptop without scrolling.
|
|
2195
|
-
- **Headline cap is \`lg:text-
|
|
3051
|
+
- **Headline cap is \`lg:text-6xl\` (60px). Period.** Do not use \`lg:text-7xl\`, \`lg:text-8xl\`, \`lg:text-9xl\`, \`lg:text-[Nrem]\`, \`lg:text-[Npx]\`, or \`clamp()\` with an upper bound above 60px to bypass this \u2014 those all blow past the fold on 13" laptops with full browser chrome. If the headline still feels small, shorten the copy, don't enlarge the type.
|
|
2196
3052
|
- Cap the headline at 3 lines on desktop. Tighten \`max-w\` on the text column or shorten copy if it wraps to 4+.
|
|
2197
3053
|
- Vertical padding ceiling: \`py-16 lg:py-24\`. Avoid \`py-32\` and above.
|
|
2198
3054
|
- Do NOT apply \`min-h-screen\` to the hero section.
|
|
@@ -2459,7 +3315,7 @@ Typography: use the fonts configured in \`layout.tsx\` (from \`plan.design.fonts
|
|
|
2459
3315
|
- Always test at: 375px (mobile), 768px (tablet), 1280px (desktop)
|
|
2460
3316
|
- Hero layout: stack vertically on mobile (\`flex-col lg:flex-row\`)
|
|
2461
3317
|
- Feature grids: \`grid-cols-1 md:grid-cols-2 lg:grid-cols-3\`
|
|
2462
|
-
- Reduce headline sizes on mobile
|
|
3318
|
+
- Reduce headline sizes on mobile via the \`clamp()\` floor (the 36px lower bound of \`clamp(2.25rem,6.5vw,5.25rem)\` covers this automatically \u2014 do not stack Tailwind breakpoint utilities on top of clamp).
|
|
2463
3319
|
- Touch targets: all buttons min \`h-12 px-6\` on mobile
|
|
2464
3320
|
- Section padding: \`py-16 md:py-24 lg:py-32\` (scale up with screen size)
|
|
2465
3321
|
- Max content width: \`max-w-6xl mx-auto\` or \`max-w-7xl mx-auto\`
|
|
@@ -2486,36 +3342,36 @@ app/
|
|
|
2486
3342
|
\`\`\`
|
|
2487
3343
|
|
|
2488
3344
|
Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
|
|
2489
|
-
`});import{existsSync as
|
|
3345
|
+
`});import{existsSync as tp,readFileSync as np,writeFileSync as sp}from"fs";import{join as Pi}from"path";function Co(t){return t?op[t]??"\u23ED\uFE0F":"\u23ED\uFE0F"}function Ao(t){return t.name??t.title??`Step ${t.number}`}function Ci(t){return t.entity??t.name??"Unknown"}function rp(t){let e=t.fields??[];return e.length===0?"":typeof e[0]=="string"?e.join(", "):e.map(s=>s.name).filter(Boolean).join(", ")}function ip(t){let e=[],s=t.plan,n=(t.name??s?.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 o=s?.summary??s?.description;if(o){if(e.push("## What this is"),e.push(""),e.push(o),s?.audienceType&&(e.push(""),e.push(`Audience: **${s.audienceType}**.`)),s?.design?.archetype){let c=s.design.tone?` (${s.design.tone} tone)`:"";e.push(`Aesthetic: **${s.design.archetype}**${c} \u2014 see DESIGN.md.`)}e.push("")}let i=s?.steps??[];if(i.length>0){e.push("## Build progress"),e.push("");let c=i.filter(u=>u.status==="completed"||u.status==="done"),m=i.filter(u=>u.status==="in_progress"),p=i.filter(u=>u.status!=="completed"&&u.status!=="done"&&u.status!=="in_progress");if(c.length>0){e.push(`**Done (${c.length}/${i.length}):**`);for(let u of c)e.push(`- ${Co(u.status)} ${Ao(u)}`);e.push("")}if(m.length>0){e.push("**In progress:**");for(let u of m)e.push(`- ${Co(u.status)} ${Ao(u)}`);e.push("")}if(p.length>0){e.push("**Planned next:**");for(let u of p)e.push(`- ${Co(u.status)} ${Ao(u)}`);e.push("")}}let r=s?.dataModel??[];if(r.length>0){e.push("## Data model"),e.push("");for(let c of r){let m=rp(c);m?e.push(`- **${Ci(c)}**(${m})`):e.push(`- **${Ci(c)}**`)}e.push("")}let a=s?.integrations??[];if(a.length>0){e.push("## Active integrations"),e.push("");for(let c of a){let m=c.name??c.id??"integration";e.push(`- **${m}**`)}e.push(""),e.push('Per-integration patterns: load the matching skill via `mist_docs({ topic: "<id>-integration" })` or read `.claude/skills/<id>-integration/SKILL.md`.'),e.push("")}let l=t.deploy;return l?.url&&(e.push("## Deploy"),e.push(""),e.push(`- URL: ${l.url}`),l.completedAt&&e.push(`- Last deploy: ${l.completedAt}`),l.deploymentId&&e.push(`- Last deployment id: \`${l.deploymentId}\``),e.push("")),e.push("## For fresh state"),e.push(""),e.push("This file is a **snapshot** written at scaffold/implement/deploy time \u2014 it can lag the live state of the app by minutes. For authoritative state (current step statuses, env vars actually set, deployment history, runtime errors), call:"),e.push(""),e.push("```"),e.push('mist_project({ action: "get", projectPath })'),e.push("```"),e.push(""),e.join(`
|
|
2490
3346
|
`).trimEnd()+`
|
|
2491
|
-
`}function
|
|
2492
|
-
`)}function
|
|
2493
|
-
`)}function
|
|
3347
|
+
`}function Vt(t){try{let e=Pi(t,"mistflow.json");if(!tp(e))return;let s=np(e,"utf-8"),n=JSON.parse(s),o=ip(n);sp(Pi(t,"PROJECT.md"),o,"utf-8")}catch{}}var op,ms=I(()=>{"use strict";op={completed:"\u2705",done:"\u2705",in_progress:"\u{1F7E1}",pending:"\u23ED\uFE0F",skipped:"\u23ED\uFE0F"}});function Ai(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(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")}function ap(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function lp(t){let e=Ai(t);return e.charAt(0).toLowerCase()+e.slice(1)}function Eo(){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(`
|
|
3348
|
+
`)}function Ri(){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(`
|
|
3349
|
+
`)}function No(t){let e=Ri();if(t.includes(Ro)){let n=t.indexOf(Ro),o=Ei,i=t.indexOf(o,n);if(i===-1)return t.slice(0,n)+e;let r=t.slice(i+o.length);return t.slice(0,n)+e+r.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
|
|
2494
3350
|
|
|
2495
|
-
`+e}function
|
|
2496
|
-
`)}function
|
|
3351
|
+
`+e}function Oo(t,e){let s=Ai(t),n=e??lp(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 ${s}Schema = createSelectSchema(${n});`,`export type ${s} = z.infer<typeof ${s}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${s}Input = createInsertSchema(${n}).omit({`," id: true,"," createdAt: true,","});",`export type Create${s}Input = z.infer<typeof Create${s}Input>;`,""].join(`
|
|
3352
|
+
`)}function jo(t){return`contracts/${ap(t)}.ts`}var Ro,Ei,Do=I(()=>{"use strict";Ro="<!-- mist:contracts:start -->",Ei="<!-- mist:contracts:end -->"});import{z as Kt}from"zod";import{existsSync as Le,mkdirSync as Jt,rmSync as cp,writeFileSync as at,readFileSync as Yt,readdirSync as ji,copyFileSync as dp}from"fs";import{join as pe,resolve as Di,dirname as Sn,isAbsolute as pp}from"path";import{homedir as up}from"os";import{spawn as bf}from"child_process";import{randomBytes as mp}from"crypto";import{simpleGit as gp}from"simple-git";function hp(t){let e=pe(up(),".mistflow","plans",`${t}.json`);if(!Le(e))return null;try{let s=JSON.parse(Yt(e,"utf-8"));return s.plan?{plan:s.plan,...typeof s.scaffoldTargetPath=="string"?{scaffoldTargetPath:s.scaffoldTargetPath}:{}}:null}catch{return null}}function yp(t){let e=Sn(Di(t)),s=10,n=0;for(;n<s&&e!==Sn(e);){if(Le(pe(e,"pnpm-workspace.yaml"))||Le(pe(e,"lerna.json"))||Le(pe(e,"pnpm-lock.yaml"))||Le(pe(e,"package-lock.json"))||Le(pe(e,"yarn.lock"))||Le(pe(e,"bun.lockb"))||Le(pe(e,"bun.lock")))return e;let o=pe(e,"package.json");if(Le(o))try{if(JSON.parse(Yt(o,"utf-8")).workspaces)return e}catch{}e=Sn(e),n++}return null}function j(t,e,s){let n=pe(t,e);Jt(Sn(n),{recursive:!0}),at(n,s)}function xp(t,e){j(t,".cursor/rules/mistflow.mdc",wp),j(t,".github/copilot-instructions.md",vp),j(t,".continue/rules/mistflow.md",hs),j(t,"CONVENTIONS.md",hs),j(t,".aider.conf.yml",kp)}function Sp(t){if(!t.startsWith(`---
|
|
2497
3353
|
`))return{frontmatter:null,body:t};let e=t.indexOf(`
|
|
2498
3354
|
---
|
|
2499
|
-
`,4);if(e<0)return{frontmatter:null,body:t};let
|
|
2500
|
-
`)){let o
|
|
2501
|
-
name: ${
|
|
3355
|
+
`,4);if(e<0)return{frontmatter:null,body:t};let s=t.slice(4,e),n={};for(let o of s.split(`
|
|
3356
|
+
`)){let i=o.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/);if(!i)continue;let[,r,a]=i;(r==="name"||r==="description")&&(n[r]=a.trim())}return{frontmatter:n,body:t.slice(e+5).replace(/^\n+/,"")}}function Tp(t,e){for(let[s,n]of Object.entries(e)){if(!n||n.trim().length===0)continue;let{frontmatter:o,body:i}=Sp(n),r=o?.name??s,a=o?.description??`Mistflow skill: ${s}`,l=`---
|
|
3357
|
+
name: ${r}
|
|
2502
3358
|
description: ${a}
|
|
2503
3359
|
---
|
|
2504
3360
|
|
|
2505
|
-
`;
|
|
3361
|
+
`;j(t,`.claude/skills/${s}/SKILL.md`,l+i);let c=`---
|
|
2506
3362
|
description: ${a}
|
|
2507
3363
|
alwaysApply: false
|
|
2508
3364
|
---
|
|
2509
3365
|
|
|
2510
|
-
`;
|
|
2511
|
-
`),
|
|
2512
|
-
`),
|
|
3366
|
+
`;j(t,`.cursor/rules/${s}.mdc`,c+i)}}function _p(t){if(!Le(t))return!0;let e;try{e=ji(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}function Ip(t,e){let s=(e??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"new-app",n=pe(t,s);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 Ap(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let s=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},o=s.split(`
|
|
3367
|
+
`),i=null,r=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of o){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let u=a(c.slice(6).trim());(u==="dark"||u==="light")&&(n.theme=u);continue}let m=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(m){i=m[1],r=null;continue}if(c.length>0&&!c.startsWith(" ")&&!c.startsWith(" ")&&c.match(/^[a-zA-Z0-9_-]+:(\s|$)/)){i=null,r=null;continue}if(i==="typography"){let u=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(u){r=u[1].replace(/-/g,"_"),n.typography[r]={};continue}let g=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(g&&r){n.typography[r][g[1]]=a(g[2]);continue}}let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(p&&i){let u=p[1].replace(/-/g,"_"),g=a(p[2]);i==="colors"?n.colors[u]=g:i==="rounded"?n.rounded[u]=g:i==="spacing"&&(n.spacing[u]=g)}}return n}function Rp(t,e){let s=t.colors,o=[["--color-background",s.background],["--color-foreground",s.on_background??s.on_surface],["--color-card",s.surface??s.background],["--color-card-foreground",s.on_surface??s.on_background],["--color-popover",s.surface??s.background],["--color-popover-foreground",s.on_surface??s.on_background],["--color-muted",s.surface_variant??s.outline_variant??s.outline],["--color-muted-foreground",s.on_surface_variant??s.outline],["--color-border",s.outline_variant??s.outline],["--color-input",s.outline_variant??s.outline],["--color-primary",s.primary],["--color-primary-foreground",s.on_primary],["--color-ring",s.primary],["--color-secondary",s.secondary],["--color-secondary-foreground",s.on_secondary],["--color-accent",s.secondary],["--color-accent-foreground",s.on_secondary],["--color-destructive",s.error],["--color-destructive-foreground",s.on_error],["--color-success",s.success],["--color-success-foreground",s.on_success],["--color-warning",s.warning],["--color-warning-foreground",s.on_warning],["--color-info",s.info??s.primary],["--color-info-foreground",s.on_info??s.on_primary]].filter(a=>typeof a[1]=="string").map(([a,l])=>` ${a}: ${l};`).join(`
|
|
3368
|
+
`),i=[` --radius-sm: ${t.rounded.sm??"0.25rem"};`,` --radius-md: ${t.rounded.md??e};`,` --radius-lg: ${t.rounded.lg??"0.5rem"};`,` --radius-xl: ${t.rounded.xl??"0.75rem"};`].join(`
|
|
2513
3369
|
`);return`@import "tailwindcss";
|
|
2514
3370
|
@import "tw-animate-css";
|
|
2515
3371
|
|
|
2516
3372
|
@theme {
|
|
2517
|
-
${i}
|
|
2518
3373
|
${o}
|
|
3374
|
+
${i}
|
|
2519
3375
|
}
|
|
2520
3376
|
|
|
2521
3377
|
|
|
@@ -2565,11 +3421,11 @@ ${o}
|
|
|
2565
3421
|
|
|
2566
3422
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2567
3423
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2568
|
-
`}function
|
|
3424
|
+
`}function Ep(t,e){let s=t?.borderRadius??"subtle",n=Pp[s]??"0.375rem";if(e){let i=Ap(e);if(i)return Rp(i,n)}return`@import "tailwindcss";
|
|
2569
3425
|
@import "tw-animate-css";
|
|
2570
3426
|
|
|
2571
3427
|
@theme {
|
|
2572
|
-
${[...
|
|
3428
|
+
${[...Cp.map(([i,r])=>` ${i}: ${r};`)," --radius-sm: 0.25rem;",` --radius-md: ${n};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
|
|
2573
3429
|
`)}
|
|
2574
3430
|
}
|
|
2575
3431
|
|
|
@@ -2619,7 +3475,7 @@ ${[...sp.map(([o,s])=>` ${o}: ${s};`)," --radius-sm: 0.25rem;",` --radius-md:
|
|
|
2619
3475
|
|
|
2620
3476
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2621
3477
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2622
|
-
`}function
|
|
3478
|
+
`}function Oi(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return Ni[e]?Ni[e]:e.replace(/\s+/g,"_")}function Np(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 jp(t,e,s){let n=t.replace(/[\\"`$]/g,""),o=Np(s),r=Op.has(o)?`lang="${o}" dir="rtl"`:`lang="${o}"`,a=e?.fonts?.heading,l=e?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
|
|
2623
3479
|
import { DM_Sans } from "next/font/google";
|
|
2624
3480
|
import { Toaster } from "sonner";
|
|
2625
3481
|
import "./globals.css";
|
|
@@ -2630,12 +3486,12 @@ export const metadata: Metadata = { title: "${n}", description: "Built with Mist
|
|
|
2630
3486
|
|
|
2631
3487
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
2632
3488
|
return (
|
|
2633
|
-
<html ${
|
|
3489
|
+
<html ${r}>
|
|
2634
3490
|
<body className={body.variable}>{children}<Toaster richColors /></body>
|
|
2635
3491
|
</html>
|
|
2636
3492
|
);
|
|
2637
3493
|
}
|
|
2638
|
-
`;let c=
|
|
3494
|
+
`;let c=Oi(a??l),m=Oi(l??a);return c===m?`import type { Metadata } from "next";
|
|
2639
3495
|
import { ${c} } from "next/font/google";
|
|
2640
3496
|
import { Toaster } from "sonner";
|
|
2641
3497
|
import "./globals.css";
|
|
@@ -2646,7 +3502,7 @@ export const metadata: Metadata = { title: "${n}", description: "Built with Mist
|
|
|
2646
3502
|
|
|
2647
3503
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
2648
3504
|
return (
|
|
2649
|
-
<html ${
|
|
3505
|
+
<html ${r}>
|
|
2650
3506
|
<body className={font.variable}>{children}<Toaster richColors /></body>
|
|
2651
3507
|
</html>
|
|
2652
3508
|
);
|
|
@@ -2663,64 +3519,64 @@ export const metadata: Metadata = { title: "${n}", description: "Built with Mist
|
|
|
2663
3519
|
|
|
2664
3520
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
2665
3521
|
return (
|
|
2666
|
-
<html ${
|
|
3522
|
+
<html ${r}>
|
|
2667
3523
|
<body className={\`\${heading.variable} \${body.variable}\`}>{children}<Toaster richColors /></body>
|
|
2668
3524
|
</html>
|
|
2669
3525
|
);
|
|
2670
3526
|
}
|
|
2671
|
-
`}function
|
|
2672
|
-
`)}function
|
|
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";'),
|
|
2674
|
-
`)}}function
|
|
2675
|
-
`)}function
|
|
2676
|
-
`)}let
|
|
2677
|
-
`)}if(
|
|
2678
|
-
`)}let
|
|
2679
|
-
`)}function
|
|
2680
|
-
`)}function
|
|
2681
|
-
`)}function
|
|
2682
|
-
`)}function
|
|
2683
|
-
`)}function
|
|
2684
|
-
`)}function
|
|
2685
|
-
`)}async function
|
|
3527
|
+
`}function Tn(t,...e){let s=JSON.stringify(t).toLowerCase();return e.some(n=>s.includes(n.toLowerCase()))}function Mo(t,...e){return(Array.isArray(t.integrations)?t.integrations:[]).some(n=>{let o=JSON.stringify(n).toLowerCase();return e.some(i=>o.includes(i.toLowerCase()))})}function Dp(t){return t.realMoney===!1?!1:t.realMoney===!0||Mo(t,"stripe")||Tn(t,"stripe","payment","billing","subscription","checkout")}function Mp(t,e){return e==="none"?Mo(t,"resend","email"):e==="email"||e==="invite-only"||Mo(t,"resend","email")||Tn(t,"email notification","email reminder","send email","resend")}function Lo(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[s,n]of Object.entries(Lp))if(e.includes(s))return n;return"Circle"}function _n(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function yt(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\{/g,"{").replace(/\}/g,"}")}function $p(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 i of t.publicPages){if(typeof i!="string"||i.length<1)continue;let r=i.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!r)continue;let a=r.startsWith("/")?r:"/"+r;e.includes(a)||e.push(a)}let s=e.filter(i=>i==="/"),n=e.filter(i=>i!=="/"),o=[];o.push('import { NextRequest, NextResponse } from "next/server";'),o.push(""),o.push("const PUBLIC_PREFIXES = [");for(let i of n)o.push(' "'+i+'",');return o.push("];"),o.push(""),s.length>0&&(o.push('const PUBLIC_EXACT = ["'+s.join('", "')+'"];'),o.push("")),o.push("export function middleware(req: NextRequest) {"),o.push(" const { pathname, search } = req.nextUrl;"),o.push(""),s.length>0&&o.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),o.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),o.push(""),o.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),o.push(" if (!token) {"),o.push(' const loginUrl = new URL("/login", req.url);'),o.push(" const params = new URLSearchParams(search);"),o.push(' for (const key of ["verified", "error"]) {'),o.push(" const v = params.get(key);"),o.push(" if (v) loginUrl.searchParams.set(key, v);"),o.push(" }"),o.push(" return NextResponse.redirect(loginUrl);"),o.push(" }"),o.push(""),o.push(" return NextResponse.next();"),o.push("}"),o.push(""),o.push("export const config = {"),o.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),o.push("};"),o.push(""),o.join(`
|
|
3528
|
+
`)}function Up(t){if(t.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],n=(t.pages??[]).filter(l=>{let c=l.path??l.route??"";return c==="/"||c===""||c.includes("[")||c.replace(/^\//,"").split("/").length>1?!1:!e.some(p=>c.startsWith(p))}).map(l=>{let c=l.path??l.route??"",m=c.startsWith("/")?c:"/"+c,p=l.name??_n(c.replace(/^\//,"")),u=Lo(p);return{label:p,href:m,icon:u}});n.some(l=>l.href==="/dashboard")||n.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let o=t.authModel==="none",i=[...new Set(n.map(l=>l.icon))];o||i.push("LogOut");let r=_n(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";'),o||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+i.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let c of 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">'+r+"</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>"),o?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(`
|
|
3529
|
+
`)}}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";'),o||a.push('import { authClient } from "@/lib/auth-client";'),a.push('import { Button } from "@/components/ui/button";'),a.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),a.push('import { cn } from "@/lib/utils";'),a.push("import { Menu, "+i.join(", ")+' } from "lucide-react";'),a.push(""),a.push("interface SidebarProps {"),a.push(" user: { name: string | null; email: string; role?: string | undefined };"),a.push("}"),a.push(""),a.push("const NAV_ITEMS = [");for(let l of 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">'+r+"</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>"),o||(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">'+r+"</span>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),{path:"components/sidebar.tsx",content:a.join(`
|
|
3530
|
+
`)}}function Fp(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,s=t.defaultRole??e[0],n=[];n.push("export type Role = "+e.map(o=>'"'+o+'"').join(" | ")+";"),n.push(""),n.push("export const ROLES = ["+e.map(o=>'"'+o+'"').join(", ")+"] as const;"),n.push(""),n.push('export const DEFAULT_ROLE: Role = "'+s+'";'),n.push(""),n.push("export const ROLE_LABELS: Record<Role, string> = {");for(let o of e){let i=o.charAt(0).toUpperCase()+o.slice(1);n.push(' "'+o+'": "'+i+'",')}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(`
|
|
3531
|
+
`)}function qp(t){let e=_n(t.name);if(t.authModel==="none"){let i=[];return i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),i.push(' <h1 className="text-4xl font-bold">'+yt(e)+"</h1>"),t.summary&&i.push(' <p className="mt-4 text-lg text-muted-foreground">'+yt(t.summary)+"</p>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
|
|
3532
|
+
`)}let s=t.publicPages?.includes("/"),n=t.design?.landingTone;if(s&&n){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col">'),i.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),i.push(' <h1 className="text-5xl font-bold tracking-tight">'+yt(e)+"</h1>"),t.summary&&i.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+yt(t.summary)+"</p>"),i.push(' <div className="flex gap-4">'),i.push(' <Link href="/register" className="inline-flex h-11 items-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),i.push(" Get Started"),i.push(" </Link>"),i.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </div>"),i.push(" </section>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
|
|
3533
|
+
`)}if(s){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),i.push(' <h1 className="text-4xl font-bold">'+yt(e)+"</h1>"),t.summary&&i.push(' <p className="text-lg text-muted-foreground">'+yt(t.summary)+"</p>"),i.push(' <Link href="/login" className="inline-flex h-10 items-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
|
|
3534
|
+
`)}let o=[];return o.push('import { headers } from "next/headers";'),o.push('import { redirect } from "next/navigation";'),o.push('import { auth } from "@/lib/auth";'),o.push(""),o.push("export default async function HomePage() {"),o.push(" const session = await auth.api.getSession({ headers: await headers() });"),o.push(' if (session) redirect("/dashboard");'),o.push(' redirect("/login");'),o.push("}"),o.push(""),o.join(`
|
|
3535
|
+
`)}function Bp(t,e){let s=t.authModel==="none",n=[];s||(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";'),!s&&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 }) {"),s?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 o=s?"":"<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">'+o+"{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">'+o+"{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">'+o+"{children}</main>"),n.push(" </div>"),n.push(" );")),n.push("}"),n.push(""),n.join(`
|
|
3536
|
+
`)}function zp(t){let e=_n(t.name),s=t.dataModel??[],n=[];if(s.length>0){let o=s.map(r=>Lo(r.entity??r.name??"item")),i=[...new Set(o)];n.push('import { Card, CardContent } from "@/components/ui/card";'),n.push("import { "+i.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">'+yt(e)+"</h1>"),t.summary&&n.push(' <p className="mt-1 text-muted-foreground">'+yt(t.summary)+"</p>"),n.push(" </div>"),s.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 o of s){let i=o.entity??o.name??"Item",r=Lo(i),a=_n(i.replace(/_/g,"-"));n.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),n.push(" <"+r+' 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(`
|
|
3537
|
+
`)}function Hp(t,e=!1){if(!t.multiTenant)return null;let s=[];return e?(s.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),s.push('import { user } from "./auth";'),s.push(""),s.push('export const organization = pgTable("organization", {'),s.push(' id: text("id").primaryKey(),'),s.push(' name: text("name").notNull(),'),s.push(' slug: text("slug").unique().notNull(),'),s.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),s.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),s.push("});"),s.push(""),s.push("export const orgMember = pgTable(")):(s.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),s.push('import { sql } from "drizzle-orm";'),s.push('import { user } from "./auth";'),s.push(""),s.push('export const organization = sqliteTable("organization", {'),s.push(' id: text("id").primaryKey(),'),s.push(' name: text("name").notNull(),'),s.push(' slug: text("slug").unique().notNull(),'),s.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),s.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),s.push("});"),s.push(""),s.push("export const orgMember = sqliteTable(")),s.push(' "org_member",'),s.push(" {"),s.push(' id: text("id").primaryKey(),'),s.push(' orgId: text("org_id").notNull().references(() => organization.id),'),s.push(' userId: text("user_id").notNull().references(() => user.id),'),s.push(' role: text("role").notNull(),'),e?s.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):s.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),s.push(" },"),s.push(" (table) => ({"),s.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),s.push(' userIdx: index("org_member_user_idx").on(table.userId),'),s.push(" }),"),s.push(");"),s.push(""),s.join(`
|
|
3538
|
+
`)}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(`
|
|
3539
|
+
`)}function Gp(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(`
|
|
3540
|
+
`)}function Vp(t,e,s){let n=[],o=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");n.push(`# ${o}`),n.push(""),e?.summary&&(n.push(e.summary),n.push(""));let i=e?.features??[];if(i.length>0){n.push("## Features"),n.push("");for(let l of i){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 |"),s.hasStripe&&n.push("| Payments | Stripe |"),s.hasResend&&n.push("| Email | Resend + React Email |"),s.hasStorage&&n.push("| File Storage | Mistflow Cloud (managed blob storage) |"),s.hasAdmin&&n.push("| Admin | Better Auth admin plugin |"),s.hasAI&&n.push("| AI | Vercel AI SDK + OpenAI |"),n.push("");let r=e?.pages??[];if(r.length>0){n.push("## Pages"),n.push(""),n.push("| Route | Description |"),n.push("|-------|-------------|");for(let l of r){let c=l.path??l.route??l.name??"",m=l.description??"";n.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${m} |`)}n.push("")}let a=e?.dataModel??[];if(a.length>0){n.push("## Data Model"),n.push("");for(let l of a){let c=l.entity??l.name??"Unknown";if(n.push(`### ${c}`),n.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")n.push(`Fields: ${l.fields.join(", ")}`);else{n.push("| Field | Type |"),n.push("|-------|------|");for(let m of l.fields)n.push(`| ${m.name} | ${m.type} |`)}n.push("")}}}return n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),s.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 |"),s.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 |")),s.hasResend&&(n.push("| `RESEND_API_KEY` | Resend API key | Yes |"),n.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),(s.hasAI||s.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` |"),s.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(""),s.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"),s.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 ${s.isNeon?"Postgres":"SQLite"} database connection`),s.hasStripe&&n.push(" stripe.ts Stripe client"),s.hasResend&&(n.push(" resend.ts Resend client"),n.push(" email.ts Email send helpers")),n.push(" server/storage.ts File upload/download helpers (managed R2)"),s.hasAI&&(n.push(" ai.ts Back-compat export for server AI helpers"),n.push(" server/ai.ts Server-only AI Gateway and provider helpers")),s.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(`
|
|
3541
|
+
`)}async function Kp(t,e){if(!Te())return Me("scaffold a new project");if(!Gt())return d(JSON.stringify({status:"node_version_unsupported",code:"node_version_unsupported",message:Ot(),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:s,plan:n,path:o,planId:i,sessionId:r}=t,a,l=[],c,m=null,p=n;if(typeof p=="string")try{let b=JSON.parse(p);b&&typeof b=="object"&&!Array.isArray(b)&&"plan"in b?p=b.plan:p=b}catch{return d("mist_init received `plan` as a string, but it is not valid JSON. Pass the plan object directly or pass planId from mist_plan.",!0)}if(!p&&i){if(m=hp(i),!m)return d(`No plan found for planId '${i}'. Call mist_plan first, or pass the plan object inline.`,!0);p=m.plan}if(!p&&r){let b=await ro(r);b&&(p=b.plan)}if(!p||typeof p!="object"||Array.isArray(p))return d("mist_init requires a plan object or a valid planId from mist_plan. Refusing to scaffold without a structured plan because mist_implement would not know what to build.",!0);let u=o??m?.scaffoldTargetPath;if(!u)return d("mist_init requires an explicit 'path' unless the planId cache includes a scaffoldTargetPath. Call mist_init with the planId returned by mist_plan, pass the absolute scaffold directory, or pass { sessionId, path } in session mode.",!0);if(!pp(u))return d(`mist_init 'path' must be an absolute path \u2014 received '${u}'. Pass the full absolute path to the target directory.`,!0);let g=Di(u),D=s??(typeof p.name=="string"?p.name:void 0);if(!D)return d("mist_init requires a human-readable app name. Pass `name`, or call it with a planId whose cached plan includes a name.",!0);let _=p?.design,x=typeof p.authModel=="string"?p.authModel:void 0,v=x==="none",R=Dp(p),G=Mp(p,x),K=p?Tn(p,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,te=p?Tn(p,"admin panel","admin dashboard","admin management"):!1,ce=p?Tn(p,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,E=p,B=typeof p.dbProvider=="string"?p.dbProvider:"neon",N=Array.isArray(p.dataModel)&&p.dataModel.length>0,ee=B==="none"||v&&!N&&!K,Q=ee?"none":B,J=Q==="neon";if(!_p(g))return d(Ip(g,p?.name),!0);Jt(g,{recursive:!0});try{try{let y=pe(g,".mistflow","rules");Jt(y,{recursive:!0}),at(pe(y,"design-quality.md"),ps),at(pe(y,"landing.md"),us)}catch(y){console.error("Could not write design rule files:",y instanceof Error?y.message:y)}try{let y=pe(Sn(g),".mistflow","mockups");if(Le(y)){let k=ji(y).filter(W=>W.endsWith(".html"));if(k.length>0){let W=pe(g,".mistflow","mockups");Jt(W,{recursive:!0});for(let ke of k)dp(pe(y,ke),pe(W,ke));console.error(`Copied ${k.length} mockup file(s) into project`)}}}catch(y){console.error("Could not copy mockup files:",y instanceof Error?y.message:y)}let b=null;try{b=await Js("nextjs")}catch(y){console.error("Could not fetch scaffold from API, using minimal scaffold:",y instanceof Error?y.message:y)}if(b){let y=D.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let P of b.files){if(P.path==="package.json"||P.path==="middleware.ts"||P.path==="components/sidebar.tsx"||P.path==="components/topnav.tsx"||P.path==="app/(dashboard)/layout.tsx"||P.path==="app/(dashboard)/page.tsx"||P.path==="app/(dashboard)/dashboard/page.tsx"||ee&&(P.path==="lib/db.ts"||P.path==="drizzle.config.ts"||P.path==="db/index.ts"||P.path.startsWith("db/schema/"))||v&&(P.path.includes("(auth)")||P.path.includes("(admin)")||P.path.startsWith("app/admin/")||P.path.includes("components/auth/")||P.path.includes("admin-sidebar")||P.path.includes("app/api/auth/")||P.path.includes("app/api/admin/seed")||P.path==="lib/auth.ts"||P.path==="lib/auth-client.ts"||P.path==="db/schema/auth.ts"||P.path==="db/schema/index.ts"||P.path==="db/index.ts")||!R&&(P.path.includes("stripe")||P.path.includes("webhook/stripe"))||!G&&(P.path.includes("resend")||P.path.includes("emails/"))||!te&&(P.path.includes("(admin)")||P.path.startsWith("app/admin/")||P.path.includes("admin-sidebar"))||J&&(P.path==="lib/db.ts"||P.path==="lib/auth.ts"||P.path==="drizzle.config.ts"||P.path==="db/schema/auth.ts"))continue;let le=P.content.replace(/\{\{APP_NAME\}\}/g,D).replace(/\{\{WORKER_NAME\}\}/g,y);if(J&&P.path==="next.config.ts"&&(le=le.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),P.path==="next.config.ts"){let Ee=yp(g);Ee&&(console.error(`[init] Project is inside monorepo at ${Ee} \u2014 adding outputFileTracingRoot`),le.includes("outputFileTracingRoot")||(le=le.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
2686
3542
|
import { dirname } from "path";
|
|
2687
3543
|
import { fileURLToPath } from "url";
|
|
2688
3544
|
|
|
2689
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));`),
|
|
2690
|
-
images: {`)))}!
|
|
3545
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));`),le=le.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
3546
|
+
images: {`)))}!te&&P.path.includes("sidebar")&&(le=le.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),le=le.replace(/, Shield/g,"")),j(g,P.path,le)}let k={...b.dependencies},W={...b.devDependencies};k["drizzle-zod"]||(k["drizzle-zod"]="^0.5.1"),v&&delete k["better-auth"],ee&&(delete k["drizzle-orm"],delete k["@libsql/client"],delete k["@neondatabase/serverless"],delete W["drizzle-kit"],delete W["@electric-sql/pglite"]),J&&(delete k["@libsql/client"],k["@neondatabase/serverless"]="^0.10.0",W["@electric-sql/pglite"]="^0.2.0"),R&&(k.stripe="^17.0.0"),G&&(k.resend="^4.0.0",k["@react-email/components"]="^0.0.31"),ce&&(k.ai="^4.0.0",k["@ai-sdk/openai"]="^1.0.0",k.openai="^4.0.0",k["server-only"]="^0.0.1",k["zod-to-json-schema"]="3.24.6");let ke={"@noble/ciphers":"^1.3.0"},Ue={react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"},O={dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint",...ee?{}:{"db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"}};if(j(g,"package.json",JSON.stringify({name:D,version:"0.1.0",private:!0,scripts:O,dependencies:k,devDependencies:W,optionalDependencies:ke,overrides:Ue},null,2)),b.methodology){let P=b.methodology;J||(P=P.replace(/import \{ pgTable, text, timestamp(?:, boolean)? \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
|
2691
3547
|
import { sql } from "drizzle-orm";`).replace(/import \{ pgTable, text \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
2692
|
-
import { sql } from "drizzle-orm";`).replace(/pgTable/g,"sqliteTable").replace(/drizzle-orm\/pg-core/g,"drizzle-orm/sqlite-core").replace(/timestamp\("created_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("created_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("updated_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("updated_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("([a-z_]+)"\)/g,'text("$1")').replace(/boolean\("([a-z_]+)"\)\.default\(false\)/g,'integer("$1", { mode: "boolean" }).default(false)')),
|
|
2693
|
-
|
|
2694
|
-
`+
|
|
2695
|
-
`,
|
|
2696
|
-
`)),
|
|
2697
|
-
`)),
|
|
2698
|
-
`)),
|
|
2699
|
-
`)),
|
|
2700
|
-
`));else{
|
|
2701
|
-
`)),
|
|
2702
|
-
`)),
|
|
2703
|
-
`));let
|
|
2704
|
-
`))}}else
|
|
2705
|
-
`)),
|
|
2706
|
-
`)),
|
|
2707
|
-
`)),
|
|
2708
|
-
`))),
|
|
2709
|
-
`)),
|
|
2710
|
-
`)),
|
|
2711
|
-
`))),le&&(D(h,"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
|
-
`)),
|
|
2713
|
-
`)),
|
|
2714
|
-
`)));let
|
|
3548
|
+
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)')),P=No(P),P=P+`
|
|
3549
|
+
|
|
3550
|
+
`+fp+`
|
|
3551
|
+
`,j(g,"AGENTS.md",P),j(g,"CLAUDE.md",P),xp(g,P)}b.skills&&Object.keys(b.skills).length>0&&Tp(g,b.skills);let re=a??p?.designMd;if(re&&j(g,"DESIGN.md",re),c&&j(g,"PLAN.md",c),J)if(j(g,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);",' } else if (process.env.NODE_ENV !== "production") {'," // Local dev \u2014 PGlite (zero-install embedded Postgres). Gating on"," // NODE_ENV !== 'production' lets webpack/esbuild dead-code-eliminate"," // this entire branch in `next build` and the Cloudflare Worker"," // bundle, so pglite + its 30MB WASM never reach prod. In `next dev`"," // the branch is live, the static require resolves ./db-local, and"," // pglite (declared in next.config.ts's serverExternalPackages) is"," // left as an external runtime import. No bundler-evasion tricks."," // eslint-disable-next-line @typescript-eslint/no-require-imports",' const { createLocalDb } = require("./db-local");'," _db = createLocalDb();"," } else {"," throw new Error(",` "DATABASE_URL is not set in production. The Mistflow deploy pipeline injects it automatically \u2014 check the project's env vars in the dashboard."`," );"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
|
|
3552
|
+
`)),j(g,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its 30MB","// WASM binary. db.ts only requires this file when NODE_ENV !==","// 'production', so esbuild dead-code-eliminates the import in prod and","// never reaches this file. In dev, pglite is declared as a server","// external package in next.config.ts so webpack leaves it alone too.","",'import { PGlite } from "@electric-sql/pglite";','import { drizzle } from "drizzle-orm/pglite";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
|
|
3553
|
+
`)),j(g,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
|
|
3554
|
+
`)),v)j(g,"db/schema/index.ts",["// Re-export schema tables here as they are added.",""].join(`
|
|
3555
|
+
`)),j(g,"db/index.ts",["// Re-export schema tables here as they are added.",'export * from "./schema";',""].join(`
|
|
3556
|
+
`));else{j(g,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
|
|
3557
|
+
`)),j(g,"db/schema/index.ts",['export * from "./auth";',""].join(`
|
|
3558
|
+
`)),j(g,"db/index.ts",['export * from "./schema/auth";',""].join(`
|
|
3559
|
+
`));let P=p.defaultRole??"user";j(g,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { genericOAuth } from "better-auth/plugins/generic-oauth";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"","async function sendEmail({ to, subject, html, fallbackUrl }: { to: string; subject: string; html: string; fallbackUrl?: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {"," if (fallbackUrl) {"," console.error(`\\n[auth] No RESEND_API_KEY set. Email to ${to} was not sent.`);"," console.error(`[auth] Dev fallback \u2014 use this link directly:\\n ${fallbackUrl}\\n`);"," } else {"," console.error(`[auth] RESEND_API_KEY not set \u2014 skipping email send to ${to}`);"," }"," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' const body = await res.text().catch(() => "unknown");'," console.error(`[auth] Email send failed (${res.status}): ${body}`);"," throw new Error(`Email send failed: ${res.status}`);"," }","}","","function createAuth() {",' const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',' const isLocal = baseURL.includes("localhost") || baseURL.includes("127.0.0.1");'," const canSendEmail = Boolean(process.env.RESEND_API_KEY);"," const mistflowAppId = process.env.MISTFLOW_APP_ID;"," const mistflowOAuthProxyURL = process.env.MISTFLOW_OAUTH_PROXY_URL;"," // Preview deploys skip email verification so smoke tests and human"," // pre-launch testing can sign up and log in without a real inbox."," // The Mistflow deploy pipeline sets MISTFLOW_RUNTIME_KEY_ENVIRONMENT",' // to "preview" for staging deploys and "production" for prod. Production'," // always requires verification \u2014 there is no way to misconfigure prod into"," // the relaxed mode because the env var is set server-side at deploy."," const runtimeKeyEnvironment = process.env.MISTFLOW_RUNTIME_KEY_ENVIRONMENT;",' const isPreview = runtimeKeyEnvironment === "preview" || runtimeKeyEnvironment === "dev";'," // 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."," // Preview deploys are exempt \u2014 they don't need email since verification is off."," if (!isLocal && !isPreview && !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 && !isPreview && canSendEmail,"," sendResetPassword: async ({ user, token }: { user: { email: string; name: string }; url: string; token: string }) => {"," // Better Auth's default reset URL points at /reset-password/:token (path),"," // which our frontend doesn't route. We build our own pointing at our"," // /reset-password?token=xxx page which reads the token from the query."," const resetUrl = `${baseURL}/reset-password?token=${token}`;"," await sendEmail({"," to: user.email,",' subject: "Reset your password",',' html: `<p>Hi ${user.name},</p><p>Click the link below to reset your password:</p><p><a href="${resetUrl}">${resetUrl}</a></p>`,'," fallbackUrl: isLocal ? resetUrl : undefined,"," });"," },"," },"," emailVerification: {"," sendOnSignUp: canSendEmail,"," autoSignInAfterVerification: true,"," sendVerificationEmail: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Verify your email address",',' html: `<p>Hi ${user.name},</p><p>Click the link below to verify your email:</p><p><a href="${url}">${url}</a></p>`,'," fallbackUrl: isLocal ? url : undefined,"," });"," },"," },"," secret: process.env.AUTH_SECRET,"," plugins: [",` admin({ defaultRole: "${P}" }),`," ...(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(`
|
|
3560
|
+
`))}}else j(g,"package.json",JSON.stringify({name:D,version:"0.1.0",private:!0},null,2));let $=a??p?.designMd;j(g,"app/globals.css",Ep(_,$)),j(g,"app/layout.tsx",jp(D,_,E?.language)),j(g,"README.md",Vp(D,p,{hasStripe:R,hasResend:G,hasStorage:K,hasAdmin:te,hasAI:ce,isNeon:J})),j(g,"contracts/README.md",Eo());let V=p?.dataModel??[],Z=new Set,me=0;for(let y of V){let k=y.entity??y.name;if(!k||typeof k!="string")continue;let W=jo(k);Z.has(W)||(Z.add(W),j(g,W,Oo(k)),me++)}me===0&&j(g,"contracts/.gitkeep","");let S=[],Ce=p?.publicPages;if(Array.isArray(Ce))S=Ce;else if(typeof Ce=="string"){try{S=JSON.parse(Ce)}catch{S=[]}Array.isArray(S)||(S=[])}if(p?.publicLanding===!1)S=S.filter(y=>y!=="/");else if(!S.includes("/")){let y=p?.steps?.some(W=>{let ke=((W.name??"")+" "+(W.description??"")).toLowerCase();return ke.includes("landing")||ke.includes("marketing")||ke.includes("homepage")}),k=p?.pages?.some(W=>W.path==="/");(y||k)&&(S=["/",...S])}let ie={name:D,summary:p?.summary,authModel:x,roles:p?.roles,defaultRole:p?.defaultRole,publicPages:S,navStyle:p?.navStyle,multiTenant:p?.multiTenant,pages:p?.pages,dataModel:p?.dataModel,design:p?.design},we=$p(ie);we&&j(g,"middleware.ts",we);let ue=Up(ie);ue&&j(g,ue.path,ue.content);let xe=Fp(ie);if(xe&&j(g,"lib/roles.ts",xe),j(g,"app/page.tsx",qp(ie)),j(g,"app/(dashboard)/layout.tsx",Bp(ie,te)),j(g,"app/(dashboard)/dashboard/page.tsx",zp(ie)),ie.multiTenant){let y=Hp(ie,J);y&&j(g,"db/schema/organization.ts",y);let k=Wp(ie);k&&j(g,"lib/org.ts",k);let W=Gp(ie);W&&j(g,"components/org-switcher.tsx",W)}j(g,"tsconfig.json",JSON.stringify({compilerOptions:{target:"ES2017",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!1,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,plugins:[{name:"next"}],paths:{"@/*":["./*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],exclude:["node_modules"]},null,2)),R&&j(g,"lib/stripe.ts",['import Stripe from "stripe";',"","let _stripe: Stripe | null = null;","","function getStripe(): Stripe {"," if (!_stripe) {"," if (!process.env.STRIPE_SECRET_KEY) {",' throw new Error("STRIPE_SECRET_KEY is not set");'," }"," _stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {"," typescript: true,"," });"," }"," return _stripe;","}","","// Lazy proxy \u2014 Stripe isn't initialized at import/build time","export const stripe = new Proxy({} as Stripe, {"," get(_target, prop) {"," return (getStripe() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
|
|
3561
|
+
`)),G&&(j(g,"lib/resend.ts",['import { Resend } from "resend";',"","let _resend: Resend | null = null;","","function getResend(): Resend {"," if (!_resend) {"," if (!process.env.RESEND_API_KEY) {",' throw new Error("RESEND_API_KEY is not set");'," }"," _resend = new Resend(process.env.RESEND_API_KEY);"," }"," return _resend;","}","","// Lazy proxy \u2014 Resend isn't initialized at import/build time","export const resend = new Proxy({} as Resend, {"," get(_target, prop) {"," return (getResend() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
|
|
3562
|
+
`)),j(g,"lib/email.ts",['import { resend } from "./resend";',"",'const FROM = process.env.EMAIL_FROM ?? "onboarding@resend.dev";',"","export async function sendEmail({"," to,"," subject,"," react,","}: {"," to: string;"," subject: string;"," react: React.ReactElement;","}) {"," return resend.emails.send({ from: FROM, to, subject, react });","}",""].join(`
|
|
3563
|
+
`)),j(g,"lib/server/email.ts",['import "server-only";','import { render } from "@react-email/render";','import type { ReactElement } from "react";',"",'export class EmailConfigError extends Error { readonly code = "email_config"; }','export class EmailRateLimitError extends Error { readonly code = "email_rate_limit"; }','export class EmailCreditExhaustedError extends Error { readonly code = "email_credits_exhausted"; }','export class EmailUpstreamError extends Error { readonly code = "email_upstream_error"; }','export class EmailValidationError extends Error { readonly code = "email_validation"; }',"","function runtimeKey(): string | undefined {"," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","","export type EmailSendOptions = {"," to: string | string[];"," subject: string;"," html?: string;"," text?: string;"," react?: ReactElement;"," cc?: string[];"," bcc?: string[];"," replyTo?: string;"," idempotencyKey?: string;"," tags?: Record<string, string>;","};","","export const email = {"," /** Send an email. Sandbox decision is server-enforced via the runtime key's"," * environment field \u2014 your app cannot accidentally email real users from"," * dev or preview deploys. Real sends only fire when the key is",' * environment="production".'," *"," * React components are rendered to HTML locally before the gateway call"," * (React doesn't serialize over HTTP). */"," async send(opts: EmailSendOptions): Promise<{ id: string; sandbox?: boolean }> {"," if (!opts.to || (Array.isArray(opts.to) && opts.to.length === 0)) {",' throw new EmailValidationError("Recipient (to) is required");'," }"," if (!opts.subject) {",' throw new EmailValidationError("Subject is required");'," }"," let html = opts.html;"," if (opts.react && !html) {"," html = await render(opts.react);"," }",""," const key = runtimeKey();"," if (key) {"," // Managed mode \u2014 gateway handles sandbox enforcement, idempotency, billing."," const body = {"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, replyTo: opts.replyTo,"," idempotencyKey: opts.idempotencyKey, tags: opts.tags,"," };",' const r = await fetch(apiUrl() + "/api/email/send", {',' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": key },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new EmailConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (r.status === 402) throw new EmailCreditExhaustedError("Email/AI credits exhausted.");',' if (r.status === 429) throw new EmailRateLimitError("Rate limited.");'," if (r.status === 422) throw new EmailValidationError(await r.text());",' if (!r.ok) throw new EmailUpstreamError("Email gateway error " + r.status);'," return (await r.json()) as { id: string; sandbox?: boolean };"," }",""," if (process.env.RESEND_API_KEY) {"," // BYOK direct \u2014 no sandbox enforcement, user is responsible.",' const { Resend } = await import("resend");'," const client = new Resend(process.env.RESEND_API_KEY);",' const fromAddr = process.env.EMAIL_FROM ?? "onboarding@resend.dev";'," const result = await client.emails.send({"," from: fromAddr,"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, reply_to: opts.replyTo,",' ...(opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}),'," });"," if (result.error) throw new EmailUpstreamError(result.error.message);",' return { id: result.data?.id ?? "unknown", sandbox: false };'," }",""," throw new EmailConfigError(",` "Email is not configured. Run 'mist_setup' for managed mode (sandbox-safe in dev) or set RESEND_API_KEY."`," );"," },","};",""].join(`
|
|
3564
|
+
`))),j(g,"lib/server/storage.ts",['import "server-only";',"",'export class StorageConfigError extends Error { readonly code = "storage_config"; }','export class StorageUpstreamError extends Error { readonly code = "storage_upstream_error"; }','export class StorageQuotaError extends Error { readonly code = "storage_quota"; }',"","function runtimeKey(): string {"," const k = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;",` if (!k) throw new StorageConfigError("Storage requires managed mode. Run 'mist_setup' to enable.");`," return k;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","async function callGateway<T>(path: string, body: unknown): Promise<T> {"," const r = await fetch(apiUrl() + path, {",' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new StorageConfigError("Runtime key rejected. Re-run mist_setup.");',' if (r.status === 402) throw new StorageQuotaError("Storage quota exhausted.");',' if (r.status === 413) throw new StorageQuotaError("File exceeds the 100MB upload limit.");',' if (!r.ok) throw new StorageUpstreamError("Storage gateway error " + r.status);'," return (await r.json()) as T;","}","","export const storage = {"," /** Upload a Blob/File. Backend mints a signed URL; client PUTs directly to R2. */"," async put(opts: { key: string; blob: Blob; contentType: string; expiresIn?: number }): Promise<{ finalKey: string }> {"," const signed = await callGateway<{ uploadUrl: string; finalKey: string; expiresAt: string }>(",' "/api/storage/sign-upload",'," {"," key: opts.key,"," contentType: opts.contentType,"," contentLength: opts.blob.size,"," expiresIn: opts.expiresIn,"," },"," );"," const res = await fetch(signed.uploadUrl, {",' method: "PUT",'," body: opts.blob,",' headers: { "Content-Type": opts.contentType },'," });"," if (!res.ok) {",' throw new StorageUpstreamError("Direct R2 upload failed: " + res.status);'," }"," return { finalKey: signed.finalKey };"," },",""," /** Get a short-lived signed download URL for a stored object. */"," async get(opts: { key: string; expiresIn?: number }): Promise<{ url: string; expiresAt: string }> {"," const signed = await callGateway<{ downloadUrl: string; expiresAt: string }>(",' "/api/storage/sign-download",'," { key: opts.key, expiresIn: opts.expiresIn },"," );"," return { url: signed.downloadUrl, expiresAt: signed.expiresAt };"," },",""," /** Delete an object. Server-side delete via R2 SDK. */"," async delete(opts: { key: string }): Promise<void> {",' const r = await fetch(apiUrl() + "/api/storage/object", {',' method: "DELETE",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify({ key: opts.key }),"," });"," if (!r.ok && r.status !== 204) {",' throw new StorageUpstreamError("Delete failed: " + r.status);'," }"," },",""," /** List objects under an optional prefix. Always scoped to your project. */"," async list(opts: { prefix?: string; limit?: number; cursor?: string } = {}): Promise<{ keys: { key: string; size: number }[]; cursor?: string }> {",' return callGateway("/api/storage/list", opts);'," },","};",""].join(`
|
|
3565
|
+
`)),j(g,"app/api/upload/route.ts",["import {"," storage,"," StorageConfigError,"," StorageQuotaError,"," StorageUpstreamError,",'} from "@/lib/server/storage";',"","export async function POST(req: Request) {"," const formData = await req.formData();",' const file = formData.get("file");',' const prefix = (formData.get("prefix") as string | null) ?? "uploads";',""," if (!(file instanceof File)) {",' return Response.json({ error: "Choose a file to upload." }, { status: 400 });'," }","",' const safeName = file.name.replace(/[^a-zA-Z0-9.\\-_]/g, "_");'," const key = `${prefix}/${crypto.randomUUID()}-${safeName}`;",""," try {"," const { finalKey } = await storage.put({"," key,"," blob: file,",' contentType: file.type || "application/octet-stream",'," });"," return Response.json({ key: finalKey });"," } catch (err) {"," if (err instanceof StorageQuotaError) {",' return Response.json({ error: "File too large or storage full." }, { status: 413 });'," }"," if (err instanceof StorageConfigError) {",` return Response.json({ error: "Storage isn't configured for this app yet." }, { status: 503 });`," }"," if (err instanceof StorageUpstreamError) {",' return Response.json({ error: "Storage is temporarily unavailable. Try again." }, { status: 503 });'," }"," throw err;"," }","}",""].join(`
|
|
3566
|
+
`)),j(g,"components/file-upload.tsx",['"use client";','import { useCallback, useState } from "react";',"","interface FileUploadProps {"," /** Called with the persisted storage key after upload succeeds. */"," onUpload: (key: string) => void;"," /** Accept attribute for the file input. Defaults to images. */"," accept?: string;"," /** Client-side size guard, in megabytes. Server still enforces a hard cap. */"," maxSizeMB?: number;",' /** Optional key prefix sent to the upload route. Defaults to "uploads". */'," prefix?: string;","}","",'export function FileUpload({ onUpload, accept = "image/*", maxSizeMB = 10, prefix }: FileUploadProps) {'," const [isDragging, setIsDragging] = useState(false);"," const [uploading, setUploading] = useState(false);"," const [error, setError] = useState<string | null>(null);",""," const handleUpload = useCallback(async (file: File) => {"," setError(null);"," if (file.size > maxSizeMB * 1024 * 1024) {"," setError(`File is over the ${maxSizeMB}MB limit.`);"," return;"," }"," setUploading(true);"," try {"," const formData = new FormData();",' formData.append("file", file);',' if (prefix) formData.append("prefix", prefix);',' const res = await fetch("/api/upload", { method: "POST", body: formData });'," if (!res.ok) {"," const body = await res.json().catch(() => ({}));",' throw new Error(body?.error ?? "Upload failed");'," }"," const { key } = (await res.json()) as { key: string };"," onUpload(key);"," } catch (err) {",' setError(err instanceof Error ? err.message : "Upload failed");'," } finally {"," setUploading(false);"," }"," }, [maxSizeMB, onUpload, prefix]);",""," return (",' <div className="space-y-2">'," <label",' htmlFor="file-upload-input"'," onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}"," onDragLeave={() => setIsDragging(false)}"," onDrop={(e) => {"," e.preventDefault();"," setIsDragging(false);"," const file = e.dataTransfer.files[0];"," if (file) handleUpload(file);"," }}"," className={`flex cursor-pointer flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed p-8 text-center text-sm transition-colors ${",' isDragging ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50"'," }`}"," >"," <input",' id="file-upload-input"',' type="file"'," accept={accept}",' className="hidden"'," onChange={(e) => { const f = e.target.files?.[0]; if (f) handleUpload(f); }}"," />",' <span className="font-medium">',' {uploading ? "Uploading..." : "Drop a file here or click to browse"}'," </span>",' <span className="text-xs text-muted-foreground">Up to {maxSizeMB}MB</span>'," </label>",' {error ? <p className="text-sm text-destructive">{error}</p> : null}'," </div>"," );","}",""].join(`
|
|
3567
|
+
`)),ce&&(j(g,"lib/server/ai.ts",['import "server-only";',"",'import { createOpenAI } from "@ai-sdk/openai";','import { streamText, type CoreMessage } from "ai";','import type { z } from "zod";','import { zodToJsonSchema } from "zod-to-json-schema";',"","export const MISTFLOW_AI_HELPER_VERSION = 2;","","// \u2500\u2500 Typed error hierarchy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Catch the specific class to give the user actionable copy.",'export class AIConfigError extends Error { readonly code = "ai_config"; }','export class AIRateLimitError extends Error { readonly code = "ai_rate_limit"; }','export class AICreditExhaustedError extends Error { readonly code = "ai_credits_exhausted"; }','export class AIModelError extends Error { readonly code = "ai_model_error"; }',"export class AISchemaError extends Error {",' readonly code = "ai_schema_error";'," /** Raw model output that failed validation. Redacted by default; set"," * MISTFLOW_DEBUG=1 in dev to see full output. */"," readonly rawOutput?: string;"," constructor(message: string, rawOutput?: string) {"," super(message);"," this.rawOutput = rawOutput;"," }","}","","function redact(s: string | undefined): string | undefined {"," if (!s) return s;",' if (process.env.MISTFLOW_DEBUG === "1") return s;',' if (s.length <= 80) return "<redacted>";',' return s.slice(0, 40) + " ...<redacted>... " + s.slice(-20);',"}","","// \u2500\u2500 Env + dispatch helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",'const DEFAULT_MISTFLOW_AI_API_URL = "https://api.mistflow.ai";',"","function runtimeKey(): string | undefined {"," // Canonical name first; legacy alias for one release of compat."," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","","function mistflowAiApiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? DEFAULT_MISTFLOW_AI_API_URL).replace(/\\/$/, "");',"}","","function gatewayHeaders(): HeadersInit {"," const key = runtimeKey();"," if (!key) {",` throw new AIConfigError("MISTFLOW_RUNTIME_KEY not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY for BYOK.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": key,'," };","}","","function isManagedAvailable(): boolean { return !!runtimeKey(); }","function isBYOKAvailable(): boolean { return !!process.env.OPENROUTER_API_KEY; }","","function noConfigError(): AIConfigError {"," return new AIConfigError(",` "AI is not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY in .env.local."`," );","}","","async function callManaged(path: string, body: unknown): Promise<Response> {"," const response = await fetch(mistflowAiApiUrl() + path, {",' method: "POST",'," headers: gatewayHeaders(),"," body: JSON.stringify(body),"," });",' if (response.status === 401) throw new AIConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (response.status === 402) throw new AICreditExhaustedError("AI credits exhausted. Top up at https://app.mistflow.ai/ai-gateway");',' if (response.status === 429) throw new AIRateLimitError("Rate limited by gateway. Retry with backoff.");'," if (!response.ok) {",' const text = await response.text().catch(() => "");',' throw new AIModelError("AI gateway error " + response.status + ": " + redact(text));'," }"," return response;","}","","// BYOK direct OpenRouter \u2014 used when MISTFLOW_RUNTIME_KEY is not set.","export const openrouter = createOpenAI({"," apiKey: process.env.OPENROUTER_API_KEY,",' baseURL: "https://openrouter.ai/api/v1",'," headers: {",' "HTTP-Referer": process.env.NEXT_PUBLIC_APP_URL ?? "https://mistflow.app",',' "X-Title": "Mistflow App",'," },","});","","// \u2500\u2500 Public surface: the `ai` object \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Always import this. The wrapper handles all dispatch (managed-first,","// BYOK fallback). Never write process.env.OPENROUTER_API_KEY in feature code.","","// Roles are Mistflow's stable abstraction. The host AI picks one per call","// site at scaffold time; the gateway resolves the role to whichever model","// Mistflow currently maps it to. Customer apps never reference deployment",'// names. Override via `model` (semantic ID like "gpt-5", "claude-sonnet")',"// only when a specific model is genuinely required.",'export type AiRole = "chat" | "reasoning" | "classify" | "image" | "embed" | "tts" | "stt" | "voice_realtime";',"","// OpenAI-style tool definition. Same shape AI SDK 6 and OpenAI use.","// Define a tool with `tool({ inputSchema, execute })` from the `ai`","// package and pass the resulting object verbatim \u2014 or hand-build one.","export type AiTool = {",' type: "function";'," function: { name: string; description?: string; parameters: Record<string, unknown> };","};","",'export type AiToolChoice = "auto" | "required" | "none" | {',' type: "function";'," function: { name: string };","};","","// One element from the response.tool_calls array. Pass back as a",'// "tool" role message on the next turn (see methodologies/model-guide.md).',"export type AiToolCall = {"," id: string;",' type: "function";'," function: { name: string; arguments: string };","};","","export type TextOptions = {"," messages: CoreMessage[];"," role?: AiRole;"," model?: string;"," useCase?: string;"," idempotencyKey?: string;"," tools?: AiTool[];"," toolChoice?: AiToolChoice;","};","","export type TextResult = {"," text: string;"," toolCalls?: AiToolCall[];"," finishReason?: string;","};","","export type ImageOptions = { prompt: string; size?: string; role?: AiRole; model?: string; idempotencyKey?: string };","export type EmbedOptions = { role?: AiRole; model?: string };","export type TTSOptions = { text: string; voice?: string; role?: AiRole; model?: string };","export type STTOptions = { audio: Blob | ArrayBuffer; role?: AiRole; model?: string };","export type RealtimeOptions = { instructions?: string; role?: AiRole; useCase?: string };","","// Convert OpenAI-shaped tool definitions to the AI SDK's tool() shape.","// Used only on the BYOK path; the managed gateway accepts OpenAI shape directly.","function openAiToolsAsSdkTools(tools: AiTool[]): Record<string, { description?: string; inputSchema: Record<string, unknown> }> {"," const out: Record<string, { description?: string; inputSchema: Record<string, unknown> }> = {};"," for (const t of tools) {"," out[t.function.name] = {"," description: t.function.description,"," inputSchema: t.function.parameters,"," };"," }"," return out;","}","","export const ai = {"," // Backwards-compatible text() returns just the string. For tool calls"," // and finish_reason, use textFull() \u2014 it returns the structured result."," async text(opts: TextOptions): Promise<string> {"," const full = await this.textFull(opts);"," return full.text;"," },",""," // Structured text result: text + toolCalls + finishReason. Use this"," // when the model may invoke a tool. The caller is responsible for",' // executing the tool and looping with a "tool" role message.'," async textFull(opts: TextOptions): Promise<TextResult> {"," if (isManagedAvailable()) {",' const r = await callManaged("/api/ai-gateway/runtime/text", {'," role: opts.role, use_case: opts.useCase,"," model: opts.model, idempotency_key: opts.idempotencyKey,"," messages: opts.messages,"," tools: opts.tools, tool_choice: opts.toolChoice,"," });"," const json = (await r.json()) as { text?: string; tool_calls?: AiToolCall[]; finish_reason?: string };"," return {",' text: json.text ?? "",'," toolCalls: json.tool_calls ?? undefined,"," finishReason: json.finish_reason ?? undefined,"," };"," }"," if (isBYOKAvailable()) {"," // BYOK direct: tools land on the OpenRouter call via the AI SDK."," const result = await streamText({",' model: openrouter(opts.model ?? "openai/gpt-5-mini"),'," messages: opts.messages,"," ...(opts.tools ? { tools: openAiToolsAsSdkTools(opts.tools) } : {}),",' ...(opts.toolChoice ? { toolChoice: opts.toolChoice as Parameters<typeof streamText>[0]["toolChoice"] } : {}),'," });"," return {"," text: await result.text,"," toolCalls: (await result.toolCalls)?.map((tc: { toolCallId: string; toolName: string; input: unknown }) => ({"," id: tc.toolCallId,",' type: "function" as const,'," function: { name: tc.toolName, arguments: JSON.stringify(tc.input) },"," })),"," finishReason: await result.finishReason,"," };"," }"," throw noConfigError();"," },",""," async streamText(opts: TextOptions): Promise<Response> {"," if (isManagedAvailable()) {",' return callManaged("/api/ai-gateway/runtime/text", {'," role: opts.role, use_case: opts.useCase,"," model: opts.model, idempotency_key: opts.idempotencyKey,"," messages: opts.messages,"," tools: opts.tools, tool_choice: opts.toolChoice,"," });"," }"," if (isBYOKAvailable()) {"," const result = await streamText({",' model: openrouter(opts.model ?? "openai/gpt-5-mini"),'," messages: opts.messages,"," ...(opts.tools ? { tools: openAiToolsAsSdkTools(opts.tools) } : {}),",' ...(opts.toolChoice ? { toolChoice: opts.toolChoice as Parameters<typeof streamText>[0]["toolChoice"] } : {}),'," });"," 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, role: opts.role, 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", {'," role: opts.role,"," 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", {'," role: opts.role,"," text: opts.text, voice: opts.voice, model: opts.model,"," });"," return await r.blob();"," },",""," async transcribe(opts: STTOptions): Promise<{ text: string }> {"," if (!isManagedAvailable()) throw noConfigError();"," // Backend expects JSON { audio_base64 } per the runtime contract."," const buf = opts.audio instanceof Blob ? await opts.audio.arrayBuffer() : opts.audio;",' let binary = "";'," const bytes = new Uint8Array(buf);"," for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);",' const audio_base64 = (typeof btoa === "function" ? btoa(binary) : Buffer.from(binary, "binary").toString("base64"));',' const r = await callManaged("/api/ai-gateway/runtime/stt", {'," role: opts.role, audio_base64, model: opts.model,"," });"," return (await r.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", {'," role: opts.role, use_case: opts.useCase, 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(`
|
|
3568
|
+
`)),j(g,"lib/ai.ts",['import "server-only";',"",'export * from "./server/ai";',""].join(`
|
|
3569
|
+
`)),j(g,"app/api/chat/route.ts",['import { ai, AIConfigError, AICreditExhaustedError } from "@/lib/server/ai";','import type { CoreMessage } from "ai";',"","export async function POST(req: Request) {"," const { messages } = (await req.json()) as { messages?: CoreMessage[] };"," if (!messages) {",' return Response.json({ error: "messages is required" }, { status: 400 });'," }"," try {"," return await ai.streamText({ messages });"," } catch (e) {"," if (e instanceof AIConfigError) return Response.json({ error: e.message }, { status: 503 });"," if (e instanceof AICreditExhaustedError) return Response.json({ error: e.message }, { status: 402 });",' return Response.json({ error: "AI request failed" }, { status: 500 });'," }","}",""].join(`
|
|
3570
|
+
`)));let Ne=Array.isArray(p?.integrations)?p.integrations.map(y=>({name:y.name,preset:y.preset,envVars:y.envVars??[]})):[],Xe={};for(let y of Ne)for(let k of y.envVars??[])Xe[k.key]||(Xe[k.key]={description:k.description,setupUrl:k.setupUrl,...y.name?{integration:y.name}:{}});let Be=E?.requestedSubdomain||void 0,Ze={name:D,methodologyVersion:b?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},...Be?{requestedSubdomain:Be}:{},plan:Array.isArray(p?.steps)?{...p,steps:p.steps.map(y=>({number:y.number,name:y.name??y.title,description:y.description,entities:y.entities,pages:y.pages,features:y.features,status:"pending"}))}:p,dbProvider:Q,env:{managed:{...!ee&&J?{DATABASE_URL:{description:"Postgres connection URL",scope:"production"}}:ee?{}:{TURSO_URL:{description:"Turso database URL",scope:"production"},TURSO_AUTH_TOKEN:{description:"Turso database auth token",scope:"production"}},...v?{}:{AUTH_SECRET:{description:"Auth encryption secret",scope:"production"}},...R?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...G?{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(Xe).length>0?{required:Xe}:{}},authModel:x??"email",roles:p?.roles??null,navStyle:p?.navStyle??"sidebar",multiTenant:p?.multiTenant??!1,hasAdmin:te,hasResend:G,hasStorage:K,hasAI:ce,deploy:null};j(g,"mistflow.json",JSON.stringify(Ze,null,2)),Vt(g);let Tt=mp(32).toString("hex"),_e=R?`
|
|
2715
3571
|
# Stripe
|
|
2716
3572
|
STRIPE_SECRET_KEY=
|
|
2717
3573
|
STRIPE_WEBHOOK_SECRET=
|
|
2718
3574
|
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
|
2719
|
-
`:"",
|
|
3575
|
+
`:"",U=G?`
|
|
2720
3576
|
# Email (Resend)
|
|
2721
3577
|
RESEND_API_KEY=
|
|
2722
3578
|
EMAIL_FROM=onboarding@resend.dev
|
|
2723
|
-
`:"",
|
|
3579
|
+
`:"",ae="",$e=ce||K?`
|
|
2724
3580
|
# Mistflow Cloud (server-only; never prefix with NEXT_PUBLIC_).
|
|
2725
3581
|
# One runtime key authenticates every managed feature: AI gateway, file storage,
|
|
2726
3582
|
# and future cloud-powered features. Auto-provisioned by \`mist_init\`.
|
|
@@ -2730,26 +3586,26 @@ MISTFLOW_API_URL=https://api.mistflow.ai
|
|
|
2730
3586
|
MISTFLOW_AI_API_URL=https://api.mistflow.ai
|
|
2731
3587
|
# BYOK fallback for AI only (used when MISTFLOW_RUNTIME_KEY is unset).
|
|
2732
3588
|
OPENROUTER_API_KEY=
|
|
2733
|
-
`:""
|
|
2734
|
-
AUTH_SECRET=${
|
|
2735
|
-
AUTH_SECRET=your-secret-here`,
|
|
3589
|
+
`:"",et=v?"":`
|
|
3590
|
+
AUTH_SECRET=${Tt}`,ze=v?"":`
|
|
3591
|
+
AUTH_SECRET=your-secret-here`,Oe=ee?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2736
3592
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2737
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,
|
|
3593
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,h=ee?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2738
3594
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2739
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;
|
|
2740
|
-
${
|
|
3595
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;j(g,".env.local",`${Oe}${et}
|
|
3596
|
+
${v?"":`
|
|
2741
3597
|
# Mistflow-hosted Google sign-in (zero Google Cloud setup)
|
|
2742
3598
|
MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
|
|
2743
|
-
`}${
|
|
2744
|
-
${
|
|
2745
|
-
${
|
|
2746
|
-
${
|
|
3599
|
+
`}${_e}${U}${ae}${$e}`),j(g,".env.example",`${h}${ze}
|
|
3600
|
+
${_e}${U}${ae}${$e}`);let w=[],A=(y,k)=>{w.push({phase:y,message:k})},C=(y,k)=>{let W=w.find(ke=>ke.phase===y&&!ke.durationMs);W&&(W.durationMs=k)};if(e){let y=Ve(e.server,e.progressToken,()=>w[w.length-1]?.message??"Setting up project...");e.cleanup=()=>y.stop()}let M=Be,ne=E?.pickedDirection??E?.designDirection??void 0,oe=E?.imageryBrief??ne?.imagery??void 0,ge=E?.designConversationId??void 0,H=E?{name:E.name,summary:E.summary,audienceType:E.audienceType,authModel:E.authModel,dbProvider:Q,dataModel:E.dataModel,design:E.design,publicLanding:E.publicLanding,...typeof E.designMd=="string"&&E.designMd?{designMd:E.designMd}:{},...E.designConversationId?{designConversationId:E.designConversationId}:{},...Array.isArray(E.features)?{features:E.features}:{},...E.integrations?{integrations:E.integrations}:{},...E.hasAI===!0?{hasAI:!0}:{},...E.hasEmail===!0?{hasEmail:!0}:{},...E.hasStorage===!0?{hasStorage:!0}:{}}:void 0,F,fe;A("register","Registering project on Mistflow...");let se=Date.now();try{let y=await Ct(D,{template:void 0,dbProvider:Q,requestedSubdomain:M,pickedDirection:ne,imageryBrief:oe,planContext:H,designConversationId:ge,sessionId:r});if(F=y.id,y.design_md&&(a=y.design_md),y.plan_md&&(c=y.plan_md),Array.isArray(y.design_warnings)&&y.design_warnings.length>0){l=y.design_warnings;for(let O of y.design_warnings)console.error(`[mist_init] design warning [${O.code}]: ${O.detail}`)}if(y.layout_spec&&p&&typeof p=="object"&&(p.layoutSpec=y.layout_spec),y.picker_render_html&&typeof y.picker_render_html=="string")try{let O=pe(g,".mistflow");Jt(O,{recursive:!0}),at(pe(O,"picker-render.html"),y.picker_render_html),console.error(`[mist_init] picker render written to .mistflow/picker-render.html (${y.picker_render_html.length} chars)`)}catch(O){let re=O instanceof Error?O.message:String(O);console.error(`[mist_init] picker render write failed: ${re}`)}if(oe)try{let O=await Ms(F),re=pe(g,"public","images");Jt(re,{recursive:!0});let P=0,le=0;for(let[Ee,je]of Object.entries(O.slots))if(je.status==="done"&&je.signed_url)try{let De=await Ls(je.signed_url);at(pe(re,`${Ee}.png`),De),P++}catch(De){let jl=De instanceof Error?De.message:String(De);console.error(`[mist_init] imagery: ${Ee} download failed: ${jl}`)}else(je.status==="queued"||je.status==="running")&&le++;(P>0||le>0)&&console.error(`[mist_init] imagery: ${P} ready, ${le} still rendering`)}catch(O){let re=O instanceof Error?O.message:String(O);console.error(`[mist_init] imagery manifest fetch failed: ${re}`)}let k=pe(g,"mistflow.json"),W=JSON.parse(Yt(k,"utf-8"));if(W.projectId=F,y.layout_spec&&W.plan&&typeof W.plan=="object"&&(W.plan.layoutSpec=y.layout_spec),at(k,JSON.stringify(W,null,2)),gn(g,fn(F,D)),y.managed_env&&Object.keys(y.managed_env).length>0){let O=pe(g,".env.local"),re=Le(O)?Yt(O,"utf-8"):"";for(let[P,le]of Object.entries(y.managed_env)){let Ee=new RegExp(`^${P}=.*$`,"m");Ee.test(re)?re=re.replace(Ee,`${P}=${le}`):re+=`
|
|
3601
|
+
${P}=${le}`}at(O,re)}let Ue=y.runtimeKey;if(Ue?.rawKey){let O=pe(g,".env.local"),re=Le(O)?Yt(O,"utf-8"):"",P=(le,Ee)=>{let je=new RegExp(`^${le}=\\s*$`,"m"),De=new RegExp(`^${le}=`,"m");je.test(re)?re=re.replace(je,`${le}=${Ee}`):De.test(re)||(re+=`
|
|
3602
|
+
${le}=${Ee}`)};P("MISTFLOW_RUNTIME_KEY",Ue.rawKey),P("MISTFLOW_AI_RUNTIME_KEY",Ue.rawKey),at(O,re)}if(!v&&y.mistflow_app_id){let O=pe(g,".env.local"),re=Le(O)?Yt(O,"utf-8"):"";/^MISTFLOW_OAUTH_PROXY_URL=/m.test(re)||(re+=`
|
|
2747
3603
|
# Mistflow-hosted Google sign-in (zero Google Cloud setup)
|
|
2748
3604
|
MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
|
|
2749
|
-
`),/^MISTFLOW_APP_ID=/m.test(
|
|
3605
|
+
`),/^MISTFLOW_APP_ID=/m.test(re)||(re+=`
|
|
2750
3606
|
# Mistflow-hosted Google sign-in (zero GCP setup)
|
|
2751
|
-
MISTFLOW_APP_ID=${
|
|
2752
|
-
`),
|
|
3607
|
+
MISTFLOW_APP_ID=${y.mistflow_app_id}
|
|
3608
|
+
`),at(O,re)}try{let{getBaseUrl:O,getAuthHeaders:re}=await Promise.resolve().then(()=>(Pe(),br)),P=re(),le=p?.features,Ee=p?.steps,je={};Array.isArray(le)&&le.length>0&&(je.features=le.map(De=>De.name)),p&&(je.plan=p),Array.isArray(Ee)&&Ee.length>0&&(je.provenance=Ee.map(De=>({feature:De.name??De.title??`Step ${De.number??"?"}`,user_intent:(De.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(je).length>0&&await fetch(`${O()}/api/projects/${encodeURIComponent(F)}/state`,{method:"PUT",headers:{...P,"Content-Type":"application/json"},body:JSON.stringify(je)})}catch{}w[w.length-1].message=`Registered as ${F.slice(0,8)}`}catch(y){let k=y instanceof Error?y.message:String(y);console.error("Could not register project on backend:",k),fe=`Project created locally but NOT registered on Mistflow servers (${k}). Deploy will auto-register it.`,w[w.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}C("register",Date.now()-se);let de=null;if(ls(p,g)){A("agent-ui","Installing agent UI components...");let y=Date.now();try{let k=cs(g);de={presetVersion:it.version,installedAt:new Date().toISOString(),files:k.installed};let W=k.depsAdded.length?`, +${k.depsAdded.length} deps`:k.depsSkipped.length?" (deps already pinned)":"";w[w.length-1].message=`${k.installed.length} agent UI files written${W}`}catch(k){let W=k instanceof Error?k.message:String(k);console.error("agent-ui materialization failed:",W),w[w.length-1].message=`agent-ui skipped: ${W}`,de=null}C("agent-ui",Date.now()-y)}A("git","Initializing git repository...");let Ie=Date.now();try{let y=gp(g);await y.init(),await y.add("."),await y.commit("Initial Mistflow project setup"),w[w.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),w[w.length-1].message="Git init skipped"}C("git",Date.now()-Ie);let he=w.reduce((y,k)=>y+(k.durationMs??0),0),T={projectPath:g,projectId:F,status:"awaiting_install"};de&&(T.agentUi={version:de.presetVersion,filesWritten:de.files.length,postInstallNote:it.postInstallNote}),M&&(T.requestedSubdomain=M,T.productionUrl=`https://${M}.mistflow.app`);let Se=w.map(y=>{let k=y.durationMs?` (${(y.durationMs/1e3).toFixed(1)}s)`:"";return`${y.message}${k}`});T.progress=Se,T.totalSetupTime=`${(he/1e3).toFixed(1)}s`;let be=[];F||be.push("Project was not registered with Mistflow (backend error during create). mist_deploy will retry registration automatically on the first deploy."),fe&&(T.registrationWarning=fe),be.length>0&&(T.warnings=be),l.length>0&&(T.designPipelineWarnings=l,T.designPipelineWarningsHostAction=`Tell the user explicitly: "The design generation pipeline had a partial failure \u2014 your scaffolded landing may not match the picker preview exactly. The build will continue with fallback design tokens. If the deployed landing looks wrong, run mist_plan({ description: '<original description>' }) again to get a fresh picker." Then continue with the install step. Do not silently proceed.`);let z=`${M?`TELL THE USER: "Your app's URL is reserved: https://${M}.mistflow.app \u2014 it goes live when you deploy. While it's being built, you'll get a local preview to watch your app come together in real time." `:""}NEXT: Call mist_install({ projectPath: "${g}" }). This is fire-and-poll \u2014 the first call returns a jobId and status: "running"; re-call with the same jobId every ~15-30s until status is "complete". Typical duration 30-90s. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. After install completes, call mist_implement({ projectPath: "${g}" }) to build the first plan step.`;return T.nextAction=F?z:`${z} NOTE: The project could not be registered with the backend during init (${fe??"see registrationWarning"}). mist_deploy will retry the registration automatically on the first deploy \u2014 no manual recovery needed.`,d(JSON.stringify(T))}catch(b){try{cp(g,{recursive:!0,force:!0})}catch{}throw b}}var fp,bp,hs,wp,vp,kp,Pp,Cp,Ni,Op,Lp,Mi,Li=I(()=>{"use strict";ko();_o();ve();Wt();ds();Io();Po();Pe();At();ms();Do();Do();fp=`## Project plan (PLAN.md)
|
|
2753
3609
|
|
|
2754
3610
|
This project ships with a \`PLAN.md\` at the root \u2014 a PRD-style
|
|
2755
3611
|
projection of the plan with the data model, pages, steps, and per-step
|
|
@@ -2770,17 +3626,17 @@ control plane.
|
|
|
2770
3626
|
To change the plan (new feature, missed requirement, scope shift),
|
|
2771
3627
|
call \`mist_plan\` with \`modify: true\` and a description. The backend
|
|
2772
3628
|
generates a new plan revision and regenerates PLAN.md.
|
|
2773
|
-
`;
|
|
3629
|
+
`;bp=Kt.object({name:Kt.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:Kt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Kt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Kt.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:Kt.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.")});hs="# 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",wp=`---
|
|
2774
3630
|
description: Mistflow project conventions \u2014 read AGENTS.md + PLAN.md first
|
|
2775
3631
|
alwaysApply: false
|
|
2776
3632
|
---
|
|
2777
3633
|
|
|
2778
|
-
${
|
|
3634
|
+
${hs}`,vp=`# VS Code Copilot instructions
|
|
2779
3635
|
|
|
2780
3636
|
This is the project's primary instruction file for VS Code Copilot.
|
|
2781
3637
|
|
|
2782
|
-
${
|
|
2783
|
-
`;
|
|
3638
|
+
${hs}`,kp=`read: ["CONVENTIONS.md", "AGENTS.md", "PLAN.md"]
|
|
3639
|
+
`;Pp={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Cp=[["--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"]];Ni={"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"};Op=new Set(["ar","he","fa","ur"]);Lp={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"};Mi={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:bp,handler:Kp}});var Ui,$i=I(()=>{Ui=`# Consumer Warm Archetype
|
|
2784
3640
|
|
|
2785
3641
|
Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
|
|
2786
3642
|
|
|
@@ -2947,7 +3803,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
|
|
|
2947
3803
|
- Small touch targets. Phone-first means \`h-12\` minimum.
|
|
2948
3804
|
- Empty states that just say "No data." Be encouraging.
|
|
2949
3805
|
- Dark theme as default. Consumer warm apps default to light.
|
|
2950
|
-
`});var
|
|
3806
|
+
`});var qi,Fi=I(()=>{qi=`# Consumer Bold Archetype
|
|
2951
3807
|
|
|
2952
3808
|
Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
|
|
2953
3809
|
|
|
@@ -3118,7 +3974,7 @@ Social/competitive apps need an activity feed:
|
|
|
3118
3974
|
- Card-only layouts with no hierarchy. Use hero cards + supporting cards.
|
|
3119
3975
|
- Missing achievement/progress systems. The gamification IS the product.
|
|
3120
3976
|
- Light-touch buttons. CTAs should be unmissable.
|
|
3121
|
-
`});var
|
|
3977
|
+
`});var zi,Bi=I(()=>{zi=`# Professional Clean Archetype
|
|
3122
3978
|
|
|
3123
3979
|
Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
|
|
3124
3980
|
|
|
@@ -3330,7 +4186,7 @@ h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
|
|
|
3330
4186
|
- Missing status workflows. Every booking/appointment needs a clear state machine.
|
|
3331
4187
|
- Dark theme as default. Clients associate light themes with professionalism.
|
|
3332
4188
|
- Emoji in the UI. Professional context.
|
|
3333
|
-
`});var
|
|
4189
|
+
`});var Wi,Hi=I(()=>{Wi=`# Education Structured Archetype
|
|
3334
4190
|
|
|
3335
4191
|
Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
|
|
3336
4192
|
|
|
@@ -3530,7 +4386,7 @@ border-2 border-destructive bg-destructive/5 rounded-xl p-4
|
|
|
3530
4386
|
- Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
|
|
3531
4387
|
- Long lesson pages with no progress indicator. Users need to know where they are.
|
|
3532
4388
|
- Multiple competing elements per view. One thing at a time. One question at a time.
|
|
3533
|
-
`});var
|
|
4389
|
+
`});var Vi,Gi=I(()=>{Vi=`# Marketplace Browse Archetype
|
|
3534
4390
|
|
|
3535
4391
|
Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
|
|
3536
4392
|
|
|
@@ -3754,7 +4610,7 @@ border-b border-border/30 py-4
|
|
|
3754
4610
|
- Small product images. The image is the primary decision-making element.
|
|
3755
4611
|
- No empty state for zero search results. "No results for 'xyz'. Try broader terms."
|
|
3756
4612
|
- Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
|
|
3757
|
-
`});var
|
|
4613
|
+
`});var Ji,Ki=I(()=>{Ji=`# SaaS Analytical Archetype
|
|
3758
4614
|
|
|
3759
4615
|
Component-level design guidance for B2B SaaS tools, CRMs, analytics dashboards, admin panels, ops tooling, and team productivity apps. This is the biggest category \u2014 most apps that don't fit consumer, marketplace, or booking archetypes land here.
|
|
3760
4616
|
|
|
@@ -3935,7 +4791,7 @@ The most recognizable B2B SaaS landing pattern.
|
|
|
3935
4791
|
- **Inter as the only font.** Pair it with a distinctive heading font or swap it entirely.
|
|
3936
4792
|
- **Centered text + centered image below.** The most overused AI hero. Use split or offset layouts.
|
|
3937
4793
|
- **Animation on every element.** Efficient motion only: hero entrance, card reveals on scroll, number counters. Nothing else.
|
|
3938
|
-
`});var
|
|
4794
|
+
`});var Qi,Yi=I(()=>{Qi=`# Content Editorial Archetype
|
|
3939
4795
|
|
|
3940
4796
|
Component-level design guidance for blogs, newsletters, magazines, publications, documentation sites, knowledge bases, and wiki-style content tools. Substack, The Verge, Medium, Linear's changelog, Stripe's docs are the reference bar.
|
|
3941
4797
|
|
|
@@ -4142,7 +4998,7 @@ Below the hero: 3 featured pieces laid out as a horizontal strip with **oversize
|
|
|
4142
4998
|
- **Dark mode as default for a reading tool.** Offer it as a toggle, not the default.
|
|
4143
4999
|
- **Flashy motion while reading.** Scroll hijacking, parallax on body text, animated backgrounds behind paragraphs \u2014 all break reading flow.
|
|
4144
5000
|
- **More than 2 fonts.** Heading + body is enough. Adding a third font for captions or metadata dilutes the identity.
|
|
4145
|
-
`});var
|
|
5001
|
+
`});var Zi,Xi=I(()=>{Zi=`# Devtool Technical Archetype
|
|
4146
5002
|
|
|
4147
5003
|
Component-level design guidance for developer tools, APIs, CLIs, SDKs, infrastructure platforms, monitoring/observability, AI/ML platforms, deployment targets, and CI/CD tooling. Vercel, Linear, Supabase, Sentry, Warp, Raycast, Cursor, Neon, Anthropic Console are the reference bar.
|
|
4148
5004
|
|
|
@@ -4331,7 +5187,7 @@ Numbers styled as terminal output: \`> 47,293 deploys this week\`, \`> 99.98% up
|
|
|
4331
5187
|
- **Marketing testimonials.** Replace with GitHub star count, StackOverflow mentions, a few short founder-quoted specifics ("Cut our deploy time from 12min to 18sec" from a named engineer at a known company).
|
|
4332
5188
|
- **Feature cards with rocket / lightning / puzzle icons.** Use technical icons (terminal, code, database, network) or skip icons entirely.
|
|
4333
5189
|
- **Motion on code blocks** while the user is trying to read them. Type out ONCE on load, then leave them alone.
|
|
4334
|
-
`});var
|
|
5190
|
+
`});var ta,ea=I(()=>{ta=`# Creative Showcase Archetype
|
|
4335
5191
|
|
|
4336
5192
|
Component-level design guidance for portfolios, design agencies, creative studios, photographers, artists, architects, filmmakers, and any brand whose primary selling point is "look at the work we've made." Apple, Dribbble, Behance, Pentagram, IDEO are the reference bar.
|
|
4337
5193
|
|
|
@@ -4548,7 +5404,7 @@ Premium agency touch: on first load, a full-screen loading component shows the s
|
|
|
4548
5404
|
- **Scroll hijacking through the whole site.** Use sparingly \u2014 one or two scroll-pinned sections maximum.
|
|
4549
5405
|
- **Mystery-meat navigation.** Clever is bad here. "Work / About / Contact" is fine. Don't make visitors guess.
|
|
4550
5406
|
- **No contact info.** The primary purpose of this site is to generate inquiries. Make it stupid-easy to contact you.
|
|
4551
|
-
`});var
|
|
5407
|
+
`});var sa,na=I(()=>{sa=`# Finance Clarity Archetype
|
|
4552
5408
|
|
|
4553
5409
|
Component-level design guidance for fintech apps, invoicing tools, expense trackers, budget apps, payroll, accounting software, banking dashboards, and any product where **money is the primary data type**. Stripe, Wise, Revolut, Mercury, Brex, QuickBooks, Ramp are the reference bar.
|
|
4554
5410
|
|
|
@@ -4767,11 +5623,11 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
|
|
|
4767
5623
|
- **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
|
|
4768
5624
|
- **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
|
|
4769
5625
|
- **Confidence-shaking UX:** progress bars that stall, skeletons that flash between states, tiny fonts for fine print. Users are nervous about their money; give them stability.
|
|
4770
|
-
`});function
|
|
4771
|
-
`),
|
|
4772
|
-
`).slice(-e).map(
|
|
4773
|
-
`).slice(-e).map(
|
|
4774
|
-
`)}function
|
|
5626
|
+
`});function ra(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return oa[e]}var oa,ey,ia=I(()=>{"use strict";$i();Fi();Bi();Hi();Gi();Ki();Yi();Xi();ea();na();oa={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Ui},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:qi},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:zi},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Wi},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Vi},"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:Ji},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Qi},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:Zi},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:ta},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:sa}},ey=Object.keys(oa)});import{spawn as ru,execFileSync as iu}from"child_process";import{existsSync as gs,mkdirSync as ca,openSync as $o,closeSync as Uo,readSync as au,readFileSync as da,writeFileSync as pa,renameSync as ua,unlinkSync as lu,readdirSync as oy,statSync as cu}from"fs";import{homedir as ma}from"os";import{join as qe,dirname as ha}from"path";import{randomBytes as ga,randomUUID as du}from"crypto";function fs(){return qe(ma(),".mistflow","jobs")}function uu(){return qe(ma(),".mistflow","job-wrapper.cjs")}function mu(){let t=uu(),e=ha(t);gs(e)||ca(e,{recursive:!0});let s=`v${fa}`;if(gs(t))try{if(da(t,"utf-8").includes(s))return t}catch{}let n=qe(e,`.job-wrapper.tmp.${ga(6).toString("hex")}`);return pa(n,pu),ua(n,t),t}function Qt(t){return qe(fs(),t)}function ya(t){return qe(Qt(t),"status.json")}function aa(t,e){let s=ya(t),n=qe(ha(s),`.status.tmp.${ga(6).toString("hex")}`);try{pa(n,JSON.stringify(e,null,2)+`
|
|
5627
|
+
`),ua(n,s)}catch(o){try{lu(n)}catch{}throw o}}function hu(t){let e=ya(t);if(!gs(e))return null;try{return JSON.parse(da(e,"utf-8"))}catch{return null}}async function bt(t){let e=`job_${du().replace(/-/g,"").slice(0,12)}`,s=Qt(e);ca(s,{recursive:!0}),Uo($o(qe(s,"stdout.log"),"a")),Uo($o(qe(s,"stderr.log"),"a"));let n=new Date().toISOString(),o={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:n,cmd:t.cmd,args:t.args,cwd:t.cwd};aa(e,o);let i=mu(),r={...process.env,...t.env??{}},a=ru("node",[i,s,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:r});a.unref();let l={...o,wrapperPid:a.pid??0};return aa(e,l),l}function gu(t){let e=t.trim();if(!e)return NaN;let s=Date.parse(e);return Number.isFinite(s)?s:NaN}function fu(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let s=iu("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=gu(s),o=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(o)&&Math.abs(n-o)>2e3)return!1}catch{}return!0}function yu(t,e){let s=Date.parse(t),n=e?Date.parse(e):Date.now();if(!Number.isFinite(s)||!Number.isFinite(n))return"0s";let o=Math.max(0,n-s),i=Math.floor(o/1e3);if(i<60)return`${i}s`;let r=Math.floor(i/60),a=i%60;return r<60?`${r}m ${a}s`:`${Math.floor(r/60)}h ${r%60}m`}function la(t,e){if(!gs(t))return"";let s=cu(t);if(s.size===0)return"";let n=s.size>e?s.size-e:0,o=s.size-n,i=$o(t,"r");try{let r=Buffer.alloc(o);return au(i,r,0,o,n),r.toString("utf-8")}finally{Uo(i)}}function bu(t,e=200){let s=la(qe(Qt(t),"stdout.log"),65536),n=la(qe(Qt(t),"stderr.log"),64*1024),o=[];return s.trim()&&o.push(...s.split(`
|
|
5628
|
+
`).slice(-e).map(i=>`[out] ${i}`)),n.trim()&&o.push(...n.split(`
|
|
5629
|
+
`).slice(-e).map(i=>`[err] ${i}`)),o.filter(i=>i.trim().length>0).join(`
|
|
5630
|
+
`)}function jt(t){return{stdout:qe(Qt(t),"stdout.log"),stderr:qe(Qt(t),"stderr.log")}}async function wt(t){let e=hu(t);if(!e)return null;let s=e;return(e.status==="running"||e.status==="starting")&&!fu(e)&&(s={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...s,elapsed:yu(s.startedAt,s.endedAt),logTail:bu(t)}}async function Xt(t,e){let s=Math.max(100,e.pollIntervalMs??500),n=Date.now()+Math.max(0,e.timeoutMs),o=["complete","failed","unknown_exit"];for(;;){let i=await wt(t);if(!i)return null;try{e.onPoll?.(i)}catch{}if(o.includes(i.status))return i;let r=n-Date.now();if(r<=0)return i;await new Promise(a=>setTimeout(a,Math.min(s,r)))}}var fa,pu,In=I(()=>{"use strict";fa=1,pu=`// Generated by @mistflow-ai/mcp local-jobs (v${fa}). Do not edit.
|
|
4775
5631
|
const { spawn } = require('node:child_process');
|
|
4776
5632
|
const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
|
|
4777
5633
|
const { join, dirname } = require('node:path');
|
|
@@ -4835,9 +5691,9 @@ child.on('error', (err) => {
|
|
|
4835
5691
|
});
|
|
4836
5692
|
process.exit(1);
|
|
4837
5693
|
});
|
|
4838
|
-
`});import{createServer as
|
|
4839
|
-
`)}function
|
|
4840
|
-
`)}async function
|
|
5694
|
+
`});import{createServer as wu}from"net";import{existsSync as ys,readFileSync as ba,writeFileSync as wa,mkdirSync as va}from"fs";import{join as bs}from"path";import{spawn as vu}from"child_process";function ka(){let t=(process.env.MISTFLOW_VISUAL_CONTEXT??"full").toLowerCase();return t==="off"||t==="preview"||t==="full"?t:"full"}function xa(t){return bs(t,".mistflow","visual-context.json")}function Sa(t){let e=xa(t);if(!ys(e))return{screenshotsTaken:0,lastScreenshotStep:0};try{return JSON.parse(ba(e,"utf-8"))}catch{return{screenshotsTaken:0,lastScreenshotStep:0}}}function ku(t,e){let s=bs(t,".mistflow");ys(s)||va(s,{recursive:!0}),wa(xa(t),JSON.stringify(e,null,2)+`
|
|
5695
|
+
`)}function Ta(t,e,s){if(ka()!=="full")return!1;let n=Sa(t);return n.screenshotsTaken>=xu?!1:n.screenshotsTaken===0||s>0&&e>=s||e>0&&e!==n.lastScreenshotStep&&e%3===0}function _a(t,e){let s=Sa(t);ku(t,{screenshotsTaken:s.screenshotsTaken+1,lastScreenshotStep:e})}async function Su(){return new Promise((t,e)=>{let s=wu();s.unref(),s.on("error",e),s.listen(0,"127.0.0.1",()=>{let n=s.address();if(n&&typeof n=="object"){let o=n.port;s.close(()=>t(o))}else s.close(()=>e(new Error("could not read assigned port")))})})}async function Ia(t,e=15e3,s=500){let n=Date.now()+e;for(;Date.now()<n;){try{let o=new AbortController,i=setTimeout(()=>o.abort(),Math.min(s*2,2e3)),r=await fetch(t,{method:"HEAD",signal:o.signal});if(clearTimeout(i),r)return!0}catch{}await new Promise(o=>setTimeout(o,s))}return!1}function Pa(t){return bs(t,".mistflow","preview.json")}function Ca(t){let e=Pa(t);if(!ys(e))return null;try{return JSON.parse(ba(e,"utf-8"))}catch{return null}}function Aa(t){return Ca(t)}function Tu(t,e){let s=bs(t,".mistflow");ys(s)||va(s,{recursive:!0}),wa(Pa(t),JSON.stringify(e,null,2)+`
|
|
5696
|
+
`)}async function Ra(t){if(ka()==="off")return null;let e=Ca(t);if(e){let n=await wt(e.jobId);if(n&&(n.status==="running"||n.status==="starting"))return{state:e,freshlyStarted:!1}}let s;try{s=await Su()}catch{return null}try{let n=await bt({type:"preview",cmd:"sh",args:["-c",`npm run dev -- --port ${s}`],cwd:t});await new Promise(a=>setTimeout(a,600));let o=await wt(n.id);if(o&&(o.status==="failed"||o.status==="unknown_exit"))return null;let i=`http://localhost:${s}`,r={port:s,url:i,jobId:n.id,startedAt:n.startedAt};return Tu(t,r),{state:r,freshlyStarted:!0}}catch{return null}}function Ea(t){try{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",s=process.platform==="win32"?["/c","start","",t]:[t];vu(e,s,{detached:!0,stdio:"ignore"}).unref()}catch{}}var xu,Fo=I(()=>{"use strict";In();xu=5});var Oa,Na=I(()=>{Oa=`# Design Doctrine
|
|
4841
5697
|
|
|
4842
5698
|
This is the standard for every UI you generate. It is not aspirational. It is the floor.
|
|
4843
5699
|
|
|
@@ -4903,7 +5759,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
|
|
|
4903
5759
|
8. Is there ONE memorable moment on the page (signature typography / orchestrated motion / unexpected layout)? **If zero, add one. If three, keep the strongest one.**
|
|
4904
5760
|
|
|
4905
5761
|
If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
|
|
4906
|
-
`});var
|
|
5762
|
+
`});var Da,ja=I(()=>{Da=`# Typography
|
|
4907
5763
|
|
|
4908
5764
|
Typography is the cheapest way to escape AI slop and the most visible place it shows up. Every generic landing uses Inter. Every remarkable landing picks something you'd notice.
|
|
4909
5765
|
|
|
@@ -4976,7 +5832,7 @@ Use the scale declared in DESIGN.md. If not declared, default to:
|
|
|
4976
5832
|
|
|
4977
5833
|
## Hierarchy Rules
|
|
4978
5834
|
|
|
4979
|
-
- Hero typography carries the page. \`text-
|
|
5835
|
+
- Hero typography carries the page. Canonical ladder: \`text-4xl md:text-5xl lg:text-6xl\` (caps at 60px on laptops). If the hero is \`text-3xl\` or below at \`lg\`, it's too timid. Do not exceed \`lg:text-6xl\` \u2014 see \`.mistflow/rules/landing.md\` for the cap (fixes a real viewport-overflow bug on 13" laptops).
|
|
4980
5836
|
- Use weight contrast aggressively. 900 display against 400 body reads as "designed". 700 against 500 reads as "default".
|
|
4981
5837
|
- Tight tracking (\`tracking-tight\` / \`-0.02em\`) on large display. Normal tracking on body. Wide tracking (\`tracking-wider\` / 0.08em) on eyebrow labels, uppercase.
|
|
4982
5838
|
- One typeface does most of the work. Two is a deliberate pairing. Three is a mistake.
|
|
@@ -4991,7 +5847,7 @@ Pick exactly one:
|
|
|
4991
5847
|
- **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
|
|
4992
5848
|
|
|
4993
5849
|
Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
|
|
4994
|
-
`});var
|
|
5850
|
+
`});var La,Ma=I(()=>{La="# 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 Ua,$a=I(()=>{Ua=`# Motion
|
|
4995
5851
|
|
|
4996
5852
|
Motion is the most-ignored dimension of AI-generated UI. Generic landings either have no motion or sprinkle tiny fades on everything. Remarkable landings pick ONE orchestrated moment and execute it precisely.
|
|
4997
5853
|
|
|
@@ -5069,7 +5925,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
|
|
|
5069
5925
|
## One-Line Motion Rule
|
|
5070
5926
|
|
|
5071
5927
|
If the motion you're about to add could be described as "subtle animation on scroll", delete it. Design motion is specific, named, and described in one sentence: "the headline lines drop in from above with a 50ms stagger at page load." If you can't describe it that specifically, you don't have a motion design \u2014 you have motion noise.
|
|
5072
|
-
`});var
|
|
5928
|
+
`});var qa,Fa=I(()=>{qa=`# Spatial Composition
|
|
5073
5929
|
|
|
5074
5930
|
Layout is where AI-slop is most visible. A centered single-column hero with a pill, headline, subhead, and two CTAs is the most-recognizable generic-SaaS pattern on the internet. It is the layout you must not use.
|
|
5075
5931
|
|
|
@@ -5139,7 +5995,7 @@ To signal "designed, not templated":
|
|
|
5139
5995
|
Negative space is a design element. A hero with \`py-32\` and a tight \`max-w-2xl\` text block in a wide viewport reads as confident. A hero that fills every pixel with checkmarks, logos, and counters reads as scared.
|
|
5140
5996
|
|
|
5141
5997
|
Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
|
|
5142
|
-
`});var
|
|
5998
|
+
`});var za,Ba=I(()=>{za=`# Interaction
|
|
5143
5999
|
|
|
5144
6000
|
Every interactive element has a designed state for every phase: rest, hover, focus, active, disabled. The difference between remarkable and adequate lives in these states.
|
|
5145
6001
|
|
|
@@ -5224,7 +6080,7 @@ Small moments that add up to "designed":
|
|
|
5224
6080
|
- **Empty states** offer a specific next action, not "No data yet".
|
|
5225
6081
|
|
|
5226
6082
|
These micro-interactions are the texture of a designed product. Ship them.
|
|
5227
|
-
`});var
|
|
6083
|
+
`});var Wa,Ha=I(()=>{Wa=`# UX Writing
|
|
5228
6084
|
|
|
5229
6085
|
Copy is design. A remarkable page has copy that could only be about this specific product. A generic page has copy that could describe a hundred.
|
|
5230
6086
|
|
|
@@ -5300,18 +6156,18 @@ If there's a pricing page:
|
|
|
5300
6156
|
## The Footer
|
|
5301
6157
|
|
|
5302
6158
|
A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is fine, but the company name / tagline should be specific. "StandupSync \u2014 async updates, human-sized" is better than "\xA9 2026 StandupSync Inc."
|
|
5303
|
-
`});import{existsSync as
|
|
5304
|
-
`),{added:
|
|
5305
|
-
`),Ht(t)}function hr(t){return t.entity??t.name??"Unknown"}function wu(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Ra(t){return t.path??t.route??t.name??""}function vu(t){let e=(t||"text").toLowerCase();return e==="string"||e==="varchar"||e==="char"?"text":e==="integer"||e==="int"||e==="number"||e==="float"||e==="decimal"||e==="double"?"number":e==="boolean"||e==="bool"?"boolean":e==="date"||e==="datetime"||e==="timestamp"?"date":e==="email"?"email":e==="url"||e==="uri"?"url":e==="enum"||e==="select"?"select":e==="text"||e==="longtext"||e==="textarea"?"textarea":"text"}function Ea(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=hr(n).toLowerCase();return r.some(o=>i.includes(o)||o.includes(i))})}function ku(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let i=(n.name??"").toLowerCase(),o=Ra(n).toLowerCase();return r.some(s=>i.includes(s)||s.includes(i)||o.includes(s))})}function Su(t){let e=t.stepType;if(e&&xu.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name??t.title??""} ${t.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function Tu(t){switch(t){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function _u(t){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&e.push(`- **App tone**: ${t.tone}`),t.fonts&&(e.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let r={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${t.borderRadius} (${r[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let r={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${r[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let r={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${t.cardStyle} \u2014 ${r[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&e.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let r=t.visualStrategy,n=t.heroPhoto!==!1,i=n&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),i&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let s=r.heroImages[0];e.push(`- URL: ${s.url}`),e.push(`- Alt text for img tag: "${s.alt||"Hero image"} \u2014 Photo by ${s.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!r.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/home/page.tsx.'"):n||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(r.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let s of r.sectionImages)e.push(`- ${s.url} \u2014 alt: "${s.alt||"section image"} \u2014 Photo by ${s.photographer} on Unsplash"`)}(i||r.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let o=qi(t);o?(e.push(""),e.push(`### Page composition \u2014 ${o.name} archetype`),e.push(`This plan was classified as **${o.id}** \u2014 ${o.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),e.push(""),e.push(o.content)):(e.push(""),e.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),i?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows. Must be DOMAIN-SPECIFIC."),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return e.join(`
|
|
5306
|
-
`)}function
|
|
5307
|
-
`).map(
|
|
5308
|
-
`)}async function
|
|
6159
|
+
`});import{existsSync as Nu,readFileSync as Ou,writeFileSync as ju}from"fs";import{join as Du}from"path";import{z as Pn}from"zod";function vs(t,e){if(e.length===0)return{added:[],skipped:[]};let s=Du(t,"mistflow.json");if(!Nu(s))throw new Error(`mistflow.json not found at ${t}`);let n=Ou(s,"utf-8"),o=JSON.parse(n);o.env=o.env??{},o.env.required=o.env.required??{};let i=o.env.required,r=[],a=[];for(let l of e)if(!(!l?.key||typeof l.key!="string"||!Mu.test(l.key))){if(i[l.key]){a.push(l.key);continue}i[l.key]={description:typeof l.description=="string"?l.description:"",...typeof l.setupUrl=="string"&&l.setupUrl?{setupUrl:l.setupUrl}:{},...typeof l.integration=="string"&&l.integration?{integration:l.integration}:{}},r.push(l.key)}return r.length>0&&ju(s,JSON.stringify(o,null,2)+`
|
|
6160
|
+
`),{added:r,skipped:a}}var ws,Mu,qo=I(()=>{"use strict";ws=Pn.object({key:Pn.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:Pn.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:Pn.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:Pn.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),Mu=/^[A-Z][A-Z0-9_]*$/});import{z as Cn}from"zod";import{existsSync as vt,readFileSync as Bo,writeFileSync as ks,mkdirSync as Ga}from"fs";import{join as Ke,resolve as Lu,dirname as $u}from"path";import{createConnection as Uu}from"net";function Fu(t){return new Promise(e=>{let s=Uu({port:t,host:"127.0.0.1"});s.on("connect",()=>{s.destroy(),e(!0)}),s.on("error",()=>{e(!1)})})}function Bu(t){let e=Ke(t,"mistflow.json");if(!vt(e))return null;try{return JSON.parse(Bo(e,"utf-8"))}catch{return null}}function Va(t,e){let s=Ke(t,"mistflow.json");ks(s,JSON.stringify(e,null,2)+`
|
|
6161
|
+
`),Vt(t)}function xs(t){return t.entity??t.name??"Unknown"}function zu(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Ka(t){return t.path??t.route??t.name??""}function Hu(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 Ja(t,e){if(!t.entities||t.entities.length===0)return e;let s=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let o=xs(n).toLowerCase();return s.some(i=>o.includes(i)||i.includes(o))})}function Wu(t,e){if(!t.pages||t.pages.length===0)return[];let s=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let o=(n.name??"").toLowerCase(),i=Ka(n).toLowerCase();return s.some(r=>o.includes(r)||r.includes(o)||i.includes(r))})}function Vu(t){let e=t.stepType;if(e&&Gu.has(e))return e;if(t.integrationId)return"integration";let s=`${t.name??t.title??""} ${t.description}`.toLowerCase();return s.includes("crud")||s.includes("list")&&s.includes("create")?"crud":s.includes("auth")||s.includes("login")||s.includes("register")?"auth":s.includes("admin")&&(s.includes("panel")||s.includes("dashboard")||s.includes("manage")||s.includes("users"))?"admin":s.includes("dashboard")||s.includes("overview")||s.includes("analytics")?"dashboard":s.includes("schema")||s.includes("database")||s.includes("model")?"schema":s.includes("layout")||s.includes("sidebar")||s.includes("navigation")?"layout":s.includes("deploy")||s.includes("cloudflare")?"deploy":s.includes("organization")||s.includes("team")||s.includes("workspace")||s.includes("multi-tenant")||s.includes("invite member")?"multi-tenant":s.includes("landing")||s.includes("hero")||s.includes("marketing")||s.includes("homepage")?"landing":s.includes("design")||s.includes("theme")||s.includes("styling")||s.includes("ui polish")||s.includes("visual")?"design":"general"}function Ku(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 Ju(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 s={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${t.borderRadius} (${s[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let s={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 ${s[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let s={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 ${s[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&e.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let s=t.visualStrategy,n=t.heroPhoto!==!1,o=n&&!!s.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),o&&s.heroImages&&s.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let r=s.heroImages[0];e.push(`- URL: ${r.url}`),e.push(`- Alt text for img tag: "${r.alt||"Hero image"} \u2014 Photo by ${r.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&&!s.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(s.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let r of s.sectionImages)e.push(`- ${r.url} \u2014 alt: "${r.alt||"section image"} \u2014 Photo by ${r.photographer} on Unsplash"`)}(o||s.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let i=ra(t);i?(e.push(""),e.push(`### Page composition \u2014 ${i.name} archetype`),e.push(`This plan was classified as **${i.id}** \u2014 ${i.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),e.push(""),e.push(i.content)):(e.push(""),e.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),o?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(`
|
|
6162
|
+
`)}function Yu(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((s,n)=>{let o=n+1;e.push(`${o}. \`${s.type}\` (id: \`${s.id}\`, role: \`${s.narrative_role}\`)`),e.push(` - **Intent**: ${s.intent}`),s.answers_section_id&&e.push(` - **Answers**: section \`${s.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 i=JSON.stringify(s.props,null,2).split(`
|
|
6163
|
+
`).map(r=>` ${r}`);e.push(...i),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(`
|
|
6164
|
+
`)}async function Qu(t){try{let e=await Ys("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
|
|
5309
6165
|
- Follow existing patterns in the codebase
|
|
5310
|
-
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Cu(t,e,r,n,i,o){let s=[];s.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),s.push(""),s.push("### What to build:"),s.push(t.description),s.push(""),e.primaryAction&&(s.push("### Primary user action (non-negotiable):"),s.push(`- **Core action**: ${e.primaryAction.action}`),s.push(`- **User flow**: ${e.primaryAction.flow}`),s.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),s.push(""),s.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),s.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l){s.push(_u(e.design)),s.push("");let I=o?Ge(o,".mistflow","rules","design-quality.md"):null;I&&bt(I)?(s.push("### Design quality rules (non-negotiable):"),s.push("**Read `.mistflow/rules/design-quality.md` BEFORE writing any code for this step.** That file contains the full rule set (shadcn usage, routes, typography, color, layout, motion, responsive, UX writing, cognitive load, production hardening, anti-patterns). It's been written to disk to keep this prompt under the per-tool-result token cap \u2014 read it once, then write your code."),s.push("")):(s.push(rr),s.push(""))}else e.design&&!l&&(s.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&s.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),s.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),s.push(""));if(o){let I=qo(o);if(I.length>0){s.push("### Approved wireframe (MUST READ before writing any files):"),s.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let x of I){let y=x.replace(o,"").replace(/^\//,"");s.push(`- \`${y}\``)}s.push(""),s.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),s.push(""),s.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),s.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),s.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),s.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),s.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),s.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),s.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(s.push("### Role system (from plan):"),s.push(`- Roles: ${e.roles.join(", ")}`),s.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),s.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),s.push("")),e.multiTenant&&(s.push("### Multi-tenant (from plan):"),s.push("- Organization tables are in `db/schema/organization.ts`"),s.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),s.push("- All data queries MUST be scoped to the current org (filter by orgId)"),s.push("- Org switcher component is at `components/org-switcher.tsx`"),s.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),s.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),s.push("")),e.language&&(s.push(`### Language: ${e.language}`),s.push(`ALL user-facing text must be written in ${e.language}:`),s.push("- Page titles, headings, labels, button text, placeholder text"),s.push("- Navigation items, menu labels, footer text"),s.push("- Error messages, success messages, empty states"),s.push("- Landing page copy, marketing text, CTAs"),s.push("- Form labels and validation messages"),s.push("Code (variable names, comments, file names) stays in English."),s.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),s.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(i)&&(e.audienceType==="b2c"?(s.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),s.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),s.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),s.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),s.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),s.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),s.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),s.push("")):e.audienceType==="b2b"?(s.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),s.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),s.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),s.push("- Testimonials: from business owners who use the platform"),s.push("- Features: business benefits ('Track dietary preferences across all orders')"),s.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),s.push("")):e.audienceType==="internal"&&(s.push("### Audience: internal staff tool. No marketing copy needed."),s.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),s.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),s.push(""))),r.length>0&&(s.push("### Already completed:"),r.forEach(I=>s.push(`- ${I}`)),s.push(""));let m=e.dataModel?Ea(t,e.dataModel):[];m.length>0&&(s.push("### Data model (from plan):"),m.forEach(I=>{let x=hr(I),y=wu(I.fields);s.push(`- **${x}**: ${y}`),s.push(` Schema file: \`db/schema/${x.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let p=e.pages?ku(t,e.pages):[];if(p.length>0&&(s.push("### Pages to create/update:"),p.forEach(I=>{let x=I.description?` \u2014 ${I.description}`:"";s.push(`- \`${Ra(I)}\`${x}`)}),s.push("")),i==="crud"&&m.length>0&&m.forEach(I=>{let x=hr(I),y=x.toLowerCase().replace(/\s+/g,"-"),C=y.endsWith("s")?y:`${y}s`;s.push(`### Files for ${x} CRUD:`),s.push(`- List page: \`app/(dashboard)/${C}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${C}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${C}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${C}/actions.ts\``),s.push(`- DataTable columns: \`components/${y}-table-columns.tsx\``),s.push(`- Form: \`components/${y}-form.tsx\``),s.push("")}),l){s.push("## Design Doctrine (the standard for every UI step)"),s.push(""),s.push(ga),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(ya),s.push(""),s.push("### Color"),s.push(wa),s.push(""),s.push("### Motion"),s.push(ka),s.push(""),s.push("### Spatial Composition"),s.push(Sa),s.push(""),s.push("### Interaction"),s.push(_a),s.push(""),s.push("### UX Writing"),s.push(Pa),s.push("");let I=o?Ge(o,"DESIGN.md"):void 0,x=I&&bt(I)?(()=>{try{return Ps(I,"utf-8")}catch{return null}})():null;x&&(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(x),s.push(""));let y=o?Ge(o,".mistflow","picker-render.html"):void 0;(i==="landing"||i==="design")&&y&&bt(y)&&(s.push("### Picked landing page render \u2014 ground-truth design contract"),s.push(""),s.push("The user picked their direction from a **fully-rendered HTML preview** of this landing page. That render is at `.mistflow/picker-render.html` (relative to the project root). **Read it** \u2014 it is the design contract the user agreed to."),s.push(""),s.push("Your job for this step is **mechanical translation**: convert that standalone HTML to Next.js Server Components + Client Components in `app/home/page.tsx` (and `components/landing/*.tsx` for any sections you split out). You are NOT redesigning. The user already picked the design \u2014 colors, fonts, composition, copy, and section order are LOCKED."),s.push(""),s.push("How to translate:\n1. **Preserve every voice sample exactly.** The H1 in the rendered HTML is the headline the user picked. The CTA button text is the CTA the user picked. Do NOT paraphrase, shorten, or 'improve' them. The picker is a contract.\n2. **Preserve the section order.** Each `<section data-section-id=\"X\">` in the rendered HTML maps to a TSX section in the SAME order. You may split each section into its own component file (`components/landing/{section-id}.tsx`) for readability \u2014 that's the only structural transformation allowed.\n3. **Migrate inline `<style>` to globals.css**. The render uses one inline `<style>` block; move those rules to `app/globals.css` so the rest of the app shares the design tokens. CSS custom properties (`--color-bg` / `--color-fg` / `--color-accent`) become the canonical design tokens.\n4. **Tailwind utility classes are FORBIDDEN in this step**, the same way they were forbidden in the render. The render already emits raw CSS; keep it that way in the TSX (use `className` to attach classes defined in globals.css, not Tailwind utilities).\n5. **Image slots:** each `<img data-image-slot=\"hero|feature-1|feature-2|feature-3|og|favicon\">` in the render points at picsum placeholder URLs. Replace each `src` with `/images/{slot}.png` \u2014 those files arrive in `public/images/` from the imagery pipeline (see Plan F A.6.1; check `mist_project action='imagery'` for status during the build). For the favicon slot, also wire `app/icon.png` to the same asset.\n6. **Do not add or remove sections.** If the render has 6 sections, the deployed page has 6 sections in the same order. Adding a CTA the user didn't pick is a bug; dropping a feature card the user did pick is also a bug.\n"),s.push("Bar: a designer comparing the picker iframe and the deployed /home page side by side should not be able to tell them apart at first glance. The HTML\u2192TSX translation is mechanical. Anything creative belongs in a separate refinement step the user explicitly asks for."),s.push(""))}if(i==="landing"||i==="design"){s.push("### File location for the landing page (non-negotiable):"),s.push('Write the landing page to **`app/home/page.tsx`** \u2014 NOT `app/page.tsx`. The scaffold\'s `middleware.ts` 308-redirects `/` to `/home` as a workaround for an OpenNext Cloudflare bug. Visitors land at `/` and end up on `/home` transparently. Internal links like `<Link href="/">` still work because the middleware does the redirect on every request.'),s.push("");let I=o?Ge(o,".mistflow","rules","landing.md"):null;I&&bt(I)?(s.push("### Landing page rules:"),s.push("**Read `.mistflow/rules/landing.md` BEFORE writing the landing page.** That file contains the full conversion structure, section catalog, motion menu, and anti-slop audit. Written to disk to keep this prompt under the per-tool-result token cap \u2014 read once, then write your code."),s.push("")):(s.push(sr),s.push(""))}i==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(s.push(Iu(e.layoutSpec)),s.push(""));let u=t.integrationId?$t(t.integrationId):void 0;if(u){let I=Ut(u.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${u.name}** (${u.category})`),I?.docsUrl&&s.push(`Official docs: ${I.docsUrl}`),I?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let x of I.envVars)s.push(`- \`${x.key}\`: ${x.description} \u2014 Get it at ${x.setupUrl}`);s.push(""),s.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}I?.packages?.length&&(s.push(""),s.push(`**Packages to install:** \`npm install ${I.packages.join(" ")}\``)),s.push(""),s.push("---"),s.push(u.prompt),s.push("---"),s.push(""),s.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),s.push("")}let{reminders:h,skill:j}=await Pu(i);return s.push(h),s.push(""),j&&(s.push(`### ${i} reference:`),s.push(j),s.push("")),l&&(s.push("## Self-Audit \u2014 run before submitting this file"),s.push(""),s.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),s.push(""),s.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),s.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),s.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),s.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),s.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),s.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),s.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),s.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),s.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),s.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),s.push(""),s.push(`If every answer is "no, I'm good" \u2014 then submit.`),s.push("")),s.join(`
|
|
5311
|
-
`)}async function
|
|
5312
|
-
`+
|
|
5313
|
-
`)}
|
|
5314
|
-
`)}catch($){console.error("implement-step: failed to write overflow instruction file:",$ instanceof Error?$.message:$),
|
|
6166
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Xu(t,e,s,n,o,i){let r=[];r.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),r.push(""),r.push("### What to build:"),r.push(t.description),r.push(""),e.primaryAction&&(r.push("### Primary user action (non-negotiable):"),r.push(`- **Core action**: ${e.primaryAction.action}`),r.push(`- **User flow**: ${e.primaryAction.flow}`),r.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),r.push(""),r.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."),r.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(o);if(e.design&&l){r.push(Ju(e.design)),r.push("");let _=i?Ke(i,".mistflow","rules","design-quality.md"):null;_&&vt(_)?(r.push("### Design quality rules (non-negotiable):"),r.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."),r.push("")):(r.push(ps),r.push(""))}else e.design&&!l&&(r.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&r.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),r.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),r.push(""));if(i){let _=ei(i);if(_.length>0){r.push("### Approved wireframe (MUST READ before writing any files):"),r.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let x of _){let v=x.replace(i,"").replace(/^\//,"");r.push(`- \`${v}\``)}r.push(""),r.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."),r.push(""),r.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),r.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),r.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),r.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),r.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),r.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"),r.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(r.push("### Role system (from plan):"),r.push(`- Roles: ${e.roles.join(", ")}`),r.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),r.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),r.push("")),e.multiTenant&&(r.push("### Multi-tenant (from plan):"),r.push("- Organization tables are in `db/schema/organization.ts`"),r.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),r.push("- All data queries MUST be scoped to the current org (filter by orgId)"),r.push("- Org switcher component is at `components/org-switcher.tsx`"),r.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."),r.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."),r.push("")),e.language&&(r.push(`### Language: ${e.language}`),r.push(`ALL user-facing text must be written in ${e.language}:`),r.push("- Page titles, headings, labels, button text, placeholder text"),r.push("- Navigation items, menu labels, footer text"),r.push("- Error messages, success messages, empty states"),r.push("- Landing page copy, marketing text, CTAs"),r.push("- Form labels and validation messages"),r.push("Code (variable names, comments, file names) stays in English."),r.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),r.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(o)&&(e.audienceType==="b2c"?(r.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),r.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),r.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),r.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),r.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),r.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),r.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),r.push("")):e.audienceType==="b2b"?(r.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),r.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),r.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),r.push("- Testimonials: from business owners who use the platform"),r.push("- Features: business benefits ('Track dietary preferences across all orders')"),r.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),r.push("")):e.audienceType==="internal"&&(r.push("### Audience: internal staff tool. No marketing copy needed."),r.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),r.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),r.push(""))),s.length>0&&(r.push("### Already completed:"),s.forEach(_=>r.push(`- ${_}`)),r.push(""));let m=e.dataModel?Ja(t,e.dataModel):[];m.length>0&&(r.push("### Data model (from plan):"),m.forEach(_=>{let x=xs(_),v=zu(_.fields);r.push(`- **${x}**: ${v}`),r.push(` Schema file: \`db/schema/${x.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),r.push(""));let p=e.pages?Wu(t,e.pages):[];if(p.length>0&&(r.push("### Pages to create/update:"),p.forEach(_=>{let x=_.description?` \u2014 ${_.description}`:"";r.push(`- \`${Ka(_)}\`${x}`)}),r.push("")),o==="crud"&&m.length>0&&m.forEach(_=>{let x=xs(_),v=x.toLowerCase().replace(/\s+/g,"-"),R=v.endsWith("s")?v:`${v}s`;r.push(`### Files for ${x} CRUD:`),r.push(`- List page: \`app/(dashboard)/${R}/page.tsx\` (Server Component)`),r.push(`- Detail page: \`app/(dashboard)/${R}/[id]/page.tsx\``),r.push(`- Create page: \`app/(dashboard)/${R}/new/page.tsx\``),r.push(`- Server Actions: \`app/(dashboard)/${R}/actions.ts\``),r.push(`- DataTable columns: \`components/${v}-table-columns.tsx\``),r.push(`- Form: \`components/${v}-form.tsx\``),r.push("")}),l){r.push("## Design Doctrine (the standard for every UI step)"),r.push(""),r.push(Oa),r.push(""),r.push("## Design Reference Library"),r.push(""),r.push("### Typography"),r.push(Da),r.push(""),r.push("### Color"),r.push(La),r.push(""),r.push("### Motion"),r.push(Ua),r.push(""),r.push("### Spatial Composition"),r.push(qa),r.push(""),r.push("### Interaction"),r.push(za),r.push(""),r.push("### UX Writing"),r.push(Wa),r.push("");let _=i?Ke(i,"DESIGN.md"):void 0,x=_&&vt(_)?(()=>{try{return Bo(_,"utf-8")}catch{return null}})():null;x&&(r.push("### Design system (source of truth: DESIGN.md):"),r.push(""),r.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."),r.push(""),r.push(x),r.push(""));let v=i?Ke(i,".mistflow","picker-render.html"):void 0;(o==="landing"||o==="design")&&v&&vt(v)&&(r.push("### Picked landing page render \u2014 ground-truth design contract"),r.push(""),r.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."),r.push(""),r.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."),r.push(""),r.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 utilities are allowed**, but the picker's CSS custom properties (`--color-bg`, `--color-fg`, `--color-accent`) MUST remain the source of truth for color \u2014 reference them via `bg-[var(--color-bg)]` or define semantic classes in globals.css, never replace them with `bg-slate-900` or other Tailwind palette swatches. For type sizes and spacing that don't land on Tailwind's ladder, use arbitrary values (`text-[56px]`, `py-[28px]`) \u2014 do not snap to the nearest rung, the picker render is the design contract and the deployed page must match pixel-for-pixel on type, spacing, and color.\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"),r.push("**Two things you MUST add (the picker render is iframe-static and cannot have these \u2014 the deployed page can):**\n7. **Motion.** The picker render has zero JavaScript and at most a decorative CSS `marquee` keyframe. The deployed page must add real entrance choreography using the `motion` package (Framer Motion, already in package.json). Pick ONE consistent style for the whole page: hero entrance reveal on mount (per-word stagger, line-by-line slide, scale-in, or blur-in), scroll-triggered section reveals (`whileInView` with `viewport={{ once: true }}`), and a card hover interaction. See `.mistflow/rules/landing.md` Section 5 (Motion Menu) for the picker \u2014 pick one style and apply it consistently. Without motion, the deployed page reads as dead next to a polished competitor's landing.\n8. **Hero fits the laptop fold.** The picker iframe is sized 1366\xD7768 and the validator caps hero font-size + section padding, but the deployed Next.js app must ALSO ensure the primary CTA is visible at 1280\xD7800 without scrolling. Cap hero vertical padding at `py-16 lg:py-24` (NOT `py-32` or above), never apply `min-h-screen` to the hero section, cap H1 at `lg:text-6xl` (60px \u2014 NEVER `lg:text-7xl`, `lg:text-8xl`, or `lg:text-9xl`, those overflow the fold on 13\" laptops), and limit hero copy to \u22643 lines on desktop. If translating the picker faithfully would push the CTA below the fold (e.g. picker has a tall stacked image block below the headline), tighten the layout to fit instead of preserving the overflow."),r.push("Bar: a designer comparing the picker iframe and the deployed /home page side by side should not be able to tell them apart on type, color, copy, and composition. The deployed page should clearly FEEL more alive (motion) and the hero must fit a laptop fold even if the picker render didn't quite. Everything beyond motion + fold-fit is mechanical translation; redesigning type, color, copy, or section order belongs in a separate refinement step the user explicitly asks for."),r.push(""))}if(o==="landing"||o==="design"){r.push("### File location for the landing page (non-negotiable):"),r.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.'),r.push(""),r.push("### Landing page hard requirements (non-negotiable):"),r.push('**Motion is mandatory.** Import `motion` from the `motion` package (Framer Motion, already in package.json \u2014 `import { motion } from "motion/react"`). Every landing page must have: (1) a hero entrance reveal on mount (per-word stagger, line-by-line slide, scale-in, or blur-in \u2014 pick ONE), (2) scroll-triggered section reveals using `whileInView` with `viewport={{ once: true }}`, (3) one card hover interaction. Pick a single motion style and apply it consistently. A static landing page is a regression \u2014 without motion the deployed page reads as dead next to a polished competitor\'s. See `.mistflow/rules/landing.md` Section 5 (Motion Menu) for the full vocabulary.'),r.push('**Hero must fit the laptop fold.** The primary CTA must be visible at 1280\xD7800 without scrolling. Cap hero section vertical padding at `py-16 lg:py-24` (NOT `py-32` or above). Never apply `min-h-screen` to the hero section. Cap H1 at `lg:text-6xl` (60px \u2014 NEVER `lg:text-7xl`, `lg:text-8xl`, or `lg:text-9xl`, those overflow the fold on 13" laptops). Keep headline copy \u22643 lines on desktop. If the layout would push the CTA below the fold, tighten the composition instead of preserving it.'),r.push("");let _=i?Ke(i,".mistflow","rules","landing.md"):null;_&&vt(_)?(r.push("### Landing page rules:"),r.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."),r.push("")):(r.push(us),r.push(""))}o==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(r.push(Yu(e.layoutSpec)),r.push(""));let u=t.integrationId?qt(t.integrationId):void 0;if(u){let _=Bt(u.id);if(r.push("### Integration blueprint (follow this closely):"),r.push(""),r.push(`Using integration: **${u.name}** (${u.category})`),_?.docsUrl&&r.push(`Official docs: ${_.docsUrl}`),_?.envVars?.length){r.push(""),r.push("**Required environment variables:**");for(let x of _.envVars)r.push(`- \`${x.key}\`: ${x.description} \u2014 Get it at ${x.setupUrl}`);r.push(""),r.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&&(r.push(""),r.push(`**Packages to install:** \`npm install ${_.packages.join(" ")}\``)),r.push(""),r.push("---"),r.push(u.prompt),r.push("---"),r.push(""),r.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."),r.push("")}let{reminders:g,skill:D}=await Qu(o);return r.push(g),r.push(""),D&&(r.push(`### ${o} reference:`),r.push(D),r.push("")),l&&(r.push("## Self-Audit \u2014 run before submitting this file"),r.push(""),r.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.`),r.push(""),r.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.'),r.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."),r.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),r.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),r.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."),r.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),r.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),r.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.'),r.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).'),r.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)."),r.push(""),r.push(`If every answer is "no, I'm good" \u2014 then submit.`),r.push("")),r.join(`
|
|
6167
|
+
`)}async function Zu(t){let{projectPath:e,step:s,envVarsRequired:n}=t,o=Lu(e??process.cwd());if(n&&n.length>0)try{let b=vs(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 i=Bu(o);if(!i)return st(o);if(!vt(Ke(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:b,ensureShadcnComponents:$}=await Promise.resolve().then(()=>(po(),co)),V=await b(o);V&&!i.projectId&&(i.projectId=V);let Z=await $(o);Z.failed?console.error(`[implement] ${Z.failed}`):Z.installed.length>0&&console.error(`[implement] installed ${Z.installed.length} shadcn components`);let{selfHealAgentUi:me}=await Promise.resolve().then(()=>(_o(),Ii)),S=me(i.plan,o);S&&console.error(`[implement] ${S.isError?"warn: ":""}${S.message}`)}catch(b){console.error("[implement] self-heal skipped:",b instanceof Error?b.message:String(b))}let r=i.plan;if(!r||!r.steps||r.steps.length===0)return d("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let a,l=r.steps.find(b=>b.status==="in_progress");if(l){let b=r.steps.findIndex($=>$.number===l.number);b!==-1&&(r.steps[b].status="completed",a=`Auto-completed step ${l.number} (${l.name})`,Va(o,i))}let c;if(s!==void 0){if(c=r.steps.find(b=>b.number===s),!c)return d(`Step ${s} not found. The plan has ${r.steps.length} steps (numbered ${r.steps[0].number} to ${r.steps[r.steps.length-1].number}).`,!0)}else if(c=r.steps.find(b=>b.status!=="completed"),!c)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:r.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 m=r.steps.filter(b=>b.status==="completed").map(b=>`Step ${b.number}: ${b.name}`),{readLocalState:p}=await Promise.resolve().then(()=>(At(),yn)),u=p(o),g=Vu(c),D=[];if((g==="crud"||g==="schema")&&r.dataModel&&c.entities&&c.entities.length>0){let b=Ja(c,r.dataModel);for(let $ of b){let V=xs($);try{let Z=($.fields||[]).map(we=>typeof we=="string"?{name:we,type:"text"}:{name:we.name,type:Hu(we.type),required:we.required!==!1});if(Z.length===0)continue;let me=i.dbProvider==="neon"?"nextjs-neon":"nextjs",S=await Zs(me,V,Z),Ce=0,Y=0;for(let we of S.files){let ue=Ke(o,we.path);if(vt(ue)){Y++;continue}Ga($u(ue),{recursive:!0}),ks(ue,we.content),Ce++}let ie=Ke(o,"db","index.ts");if(vt(ie)){let we=Bo(ie,"utf-8");we.includes(S.dbExport)||ks(ie,we.trimEnd()+`
|
|
6168
|
+
`+S.dbExport+`
|
|
6169
|
+
`)}Ce>0?D.push(`${S.entityPascal} CRUD (${Ce} new files${Y>0?`, ${Y} existing skipped`:""})`):Y>0&&D.push(`${S.entityPascal} CRUD (all ${Y} files already exist \u2014 skipped)`)}catch(Z){console.error(`Module generation failed for ${V} (non-fatal):`,Z instanceof Error?Z.message:Z)}}}let _=await Xu(c,r,m,null,g,o),x=3e4,v=null;if(_.length>x){let b=Ke(o,".mistflow","instructions");try{Ga(b,{recursive:!0});let $=`step-${c.number}.md`,V=Ke(b,$);ks(V,_,"utf-8"),v=`.mistflow/instructions/${$}`,_=[_.slice(0,5e3),"","---",`**Instruction continues in ${v}** (${_.length.toLocaleString()} chars total).`,"",`Read the full file before writing code: \`Read(${v})\`. The truncated portion above contains step framing; the file contains the detailed prescriptive guidance, layout specs, design tokens, and per-section instructions.`].join(`
|
|
6170
|
+
`)}catch($){console.error("implement-step: failed to write overflow instruction file:",$ instanceof Error?$.message:$),_=_.slice(0,x-500)+"\n\n---\n**Instruction was truncated** to fit the tool-result size cap. Detailed guidance for this step (design tokens, layout spec, anti-slop rules) lives in `.mistflow/rules/` and `methodologies/` \u2014 read those for the full context."}}let R=r.steps.findIndex(b=>b.number===c.number);if(R!==-1&&(i.plan.steps[R].status="in_progress",Va(o,i)),u&&i.projectId){let{syncRemoteState:b}=await Promise.resolve().then(()=>(At(),yn));b(i.projectId,u).catch(()=>{})}let G=r.steps.every(b=>b.status==="completed"||b.number===c.number),K;G?K=`THIS IS THE LAST STEP. Rules for speed:
|
|
5315
6171
|
|
|
5316
6172
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
5317
6173
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -5322,56 +6178,56 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
5322
6178
|
- Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
|
|
5323
6179
|
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).
|
|
5324
6180
|
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.
|
|
5325
|
-
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).`:
|
|
6181
|
+
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).`:K=`IMPLEMENT THIS STEP NOW. Rules for speed:
|
|
5326
6182
|
|
|
5327
6183
|
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.
|
|
5328
6184
|
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.
|
|
5329
6185
|
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.
|
|
5330
6186
|
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).
|
|
5331
|
-
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
|
|
5332
|
-
`)}async function
|
|
5333
|
-
`).filter(n=>n.length>0);return
|
|
5334
|
-
`)}var
|
|
5335
|
-
`+
|
|
5336
|
-
`).filter(n=>n.length>0);return
|
|
5337
|
-
`)}function Yu(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let n of t.matchAll(e)){let i=n[1];if(i.startsWith(".")||i.startsWith("@/")||i.startsWith("~/"))continue;let o=i.startsWith("@")?i.split("/").slice(0,2).join("/"):i.split("/")[0];o&&r.add(o)}return[...r]}function Qu(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${At()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var za,Vu,Ha,Wa=_(()=>{"use strict";ve();vn();as();Bt();nr();za=100*1024;Vu=Yt.object({projectPath:Yt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Yt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Yt.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls."),waitSeconds:Yt.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical build fits in 2 round-trips instead of 6-8. Default 20. Set 0 to disable."),sessionId:Yt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});Ha={name:"mist_build",description:"Run a Mistflow project's production build with the fire-and-poll pattern. First call with { projectPath } starts `npm run build` and returns a jobId. Subsequent calls with { jobId } poll status. On failure, the response surfaces structured errors (from parseBuildErrors) and any missingModules[] \u2014 chain into mist_install with those modules, then mist_build again, without asking the user.",inputSchema:Vu,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await yt(r.jobId);if(!c)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let m=r.waitSeconds??20;if(m>0&&(c.status==="running"||c.status==="starting")){let C=c.elapsed,H=e?We(e.server,e.progressToken,()=>`Build running (${C}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let K=await Jt(r.jobId,{timeoutMs:m*1e3,onPoll:ee=>{C=ee.elapsed}});K&&(c=K)}finally{H.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Ju(c.logTail),nextAction:"Build still running after long-poll window. Call mist_build again with the same jobId to continue waiting."}));if(c.status==="complete"){let C=Gu(c.cwd);if(C){let H=Rt(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:H,error:C,nextAction:C+` Full build log: ${H.stdout} and ${H.stderr}.`}),!0)}return d(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let p=Ku(c.id),u=Xn(p),h=Yu(p),j=Qu(p),I=Rt(c.id),x=` Full log: ${I.stdout} and ${I.stderr}.`,y=h.length>0?`Build failed with missing modules: ${h.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${x}`:j?`${j}${x}`:u.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${x}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${x}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:u,missingModules:h,logTail:c.logTail,logPaths:I,nextAction:y}),!0)}let n=Bu(r.projectPath);if(!Je(Ke(n,"package.json")))return d(`No package.json at ${n}. Run mist_init first.`,!0);if(!Je(Ke(n,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let i,o,s,a=Je(Ke(n,"open-next.config.ts"))||Je(Ke(n,"open-next.config.js"));if(r.script)i="npm",o=["run",r.script],s=r.script;else if(a){if(!zt())return d(At(),!0);i="npx",o=["-y","@opennextjs/cloudflare","build"],s="@opennextjs/cloudflare build"}else i="npm",o=["run","build"],s="build";let l=await ft({type:"build",cmd:i,args:o,cwd:n});return d(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:s,nextAction:`Build started. Call mist_build again with { jobId: '${l.id}' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}}});import{existsSync as Xu,readdirSync as Zu}from"fs";import{join as Ga}from"path";import{pathToFileURL as em}from"url";async function tm(t){let e=Ga(t,".mistflow","acceptance"),r=new Map;if(!Xu(e))return r;let n=Zu(e).filter(i=>i.endsWith(".spec.ts")||i.endsWith(".spec.js")||i.endsWith(".spec.mjs"));for(let i of n){let o=i.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!o)continue;let s=Ga(e,i);try{let a=await import(em(s).href),l=a.default??a.run;typeof l=="function"?r.set(o,l):console.error(`Probe ${i} doesn't export a default function (or named 'run'). Skipping.`)}catch(a){console.error(`Failed to load probe ${i}:`,a instanceof Error?a.message:a)}}return r}async function Va(t,e){let{sessionId:r,projectPath:n,deployUrl:i,seedCredentials:o}=e,a=(await on(r)).criteria,l=await tm(n),c=[];for(let m of a){let p=l.get(m.id);if(!p){c.push({criterion_id:m.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${m.id}.spec.ts`}});continue}try{await t.goto(i,{waitUntil:"domcontentloaded"});let u=await p(t,{url:i,criterion:m,seedCredentials:o});c.push({criterion_id:m.id,status:u.pass?"pass":"fail",evidence:{...u.detail?{detail:u.detail}:{},...u.screenshot?{screenshot:u.screenshot}:{}}})}catch(u){c.push({criterion_id:m.id,status:"fail",evidence:{error:u instanceof Error?u.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var Ka=_(()=>{"use strict";Pe()});import{existsSync as nm,readFileSync as rm}from"fs";import{join as sm}from"path";import{z as Qt}from"zod";function Xa(t){let e=sm(t,"mistflow.json");if(!nm(e))return null;try{return JSON.parse(rm(e,"utf-8"))}catch{return null}}async function Ja(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await e.text();return{status:e.status,body:r}}catch(e){return{status:0,body:String(e)}}}async function im(t,e,r){try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),i=await n.text(),o;try{o=JSON.parse(i)}catch{}return{status:n.status,json:o}}catch{return{status:0}}}async function Ya(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function vt(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 Ya(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 Ya(t);return{name:e,status:"fail",detail:`Unexpected error: ${o instanceof Error?o.message:String(o)}`,screenshot:s,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",i)}}async function am(t){if(!t.sessionId)return d("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=Xa(e),n=t.url;if(!n&&t.deploymentId)try{let a=await dt(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 zn(t.deploymentId);l?.adminEmail&&l?.adminPassword&&(i={email:l.adminEmail,password:l.adminPassword})}catch(a){console.error("[acceptance] getSeedInfo failed (continuing without):",a instanceof Error?a.message:String(a))}let o,s;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(Nt(),rn)),l=await a();o=l.context,s=l.page}catch(a){return d(`Playwright not available locally \u2014 install it with \`npx playwright install chromium\`. Detail: ${a instanceof Error?a.message:String(a)}`,!0)}try{let{criteria:a,results:l}=await Va(s,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:i});try{await Qr(t.sessionId,l)}catch(u){console.error("[acceptance] submitAcceptanceResults failed:",u instanceof Error?u.message:String(u))}let c=l.filter(u=>u.status==="pass").length,m=l.filter(u=>u.status==="fail").length,p=l.filter(u=>u.status==="skipped").length;return d(JSON.stringify({status:m===0?"pass":"fail",url:n,totals:{passed:c,failed:m,skipped:p,total:a.length},results:l.map(u=>({criterion_id:u.criterion_id,status:u.status,detail:u.evidence&&typeof u.evidence=="object"&&"detail"in u.evidence?u.evidence.detail:u.evidence&&typeof u.evidence=="object"&&"reason"in u.evidence?u.evidence.reason:void 0})),nextAction:m===0?"All required acceptance criteria passed. The app is shippable.":"Some criteria failed. Read the per-criterion detail, fix the underlying code, then re-run mist_qa action='acceptance'."}),m>0)}finally{if(o)try{await o.close()}catch{}}}async function lm(t){let e=t.projectPath??process.cwd(),r=Xa(e),n=t.url;if(!n&&t.deploymentId)try{let C=await dt(t.deploymentId);C.url&&(n=C.url)}catch(C){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,C instanceof Error?C.message:String(C))}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 Ja(`${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."}),gr(n,o);o.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Ja(`${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."}),gr(n,o);o.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",m="QaTemp1!",p="single",u="user",h=[];async function j(C,H,K,ee){let le=await im(`${n}/api/admin/seed`,{token:ee,email:H,password:m,role:K});if(le.status!==200||!le.json)return console.error(`[qa] Seed (${C}) returned ${le.status}`),null;let R=le.json.sessionToken;if(!R)return null;let W=le.json.seeded===!0;return{role:C,email:H,sessionToken:R,password:W?m:void 0}}if(i){let C=await zn(i);if(C){if(p=C.authMode??"single",u=C.defaultRole??"user",console.error(`[qa] auth_mode=${p}, default_role=${u}`),p!=="none"){let K=await j("actor",l,p==="multi"?"admin":u,C.seedToken);if(K&&h.push(K),p==="multi"){let ee=await j("user",c,u,C.seedToken);ee?h.push(ee):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"&&h.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."}),gr(n,o);let I,x,y;try{let{getIsolatedContext:C}=await Promise.resolve().then(()=>(Nt(),rn)),H=await C();I=H.context,y=H.page}catch(C){let H=C instanceof Error?C.message:String(C);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:H,httpChecks:o.map(({screenshot:K,...ee})=>ee),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(`
|
|
5338
|
-
`)}),!1)}try{let
|
|
5339
|
-
`),
|
|
5340
|
-
\u2026and ${_e.length-8} more.`:"";
|
|
6187
|
+
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 te=Ku(g),ce={stepNumber:c.number,totalSteps:r.steps.length,estimatedMinutes:te,announcement:`Starting step ${c.number} of ${r.steps.length}: ${c.name}. This step usually takes ${te.min}\u2013${te.max} minutes.`},B=JSON.stringify({instruction:_,...v?{instructionFilePath:v}:{},step:{number:c.number,name:c.name,description:c.description,status:"in_progress"},stepTiming:ce,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_implement again immediately after the compaction finishes. The tool finds the in-progress step and returns fresh context \u2014 you don't need to re-read files or re-derive state.",...a?{autoCompleted:a}:{},...D.length>0?{generatedModules:D,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${m.length}/${r.steps.length} steps done`,nextAction:K}),N=Aa(o),ee=N?.url??"http://localhost:3000",Q=N?.port??3e3;return await Fu(Q)&&Ta(o,c.number,r.steps.length)?(_a(o,c.number),ar(ee,B)):d(B)}var qu,Gu,Ya,Qa=I(()=>{"use strict";ve();Pe();Qn();fo();Io();ia();Po();Fo();ms();Na();ja();Ma();$a();Fa();Ba();Ha();qo();qu=Cn.object({projectPath:Cn.string().optional().describe("Path to the project directory (default: cwd)"),step:Cn.number().optional().describe("Specific step number to implement (default: next incomplete step)"),sessionId:Cn.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:Cn.array(ws).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.")});Gu=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);Ya={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:qu,handler:Zu}});import{z as kt}from"zod";import{resolve as em}from"path";async function Xa(t){let{projectPath:e,action:s,key:n,value:o,category:i,description:r,setupUrl:a}=t,l=em(e??process.cwd());if(!Te())return Me("manage env vars");let m=dt(l)?.projectId;if(!m)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(s){case"set":return n?o?(await zs(m,n,o,{category:i,description:r,setupUrl:a}),d(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):d("Value is required. Provide the env var value.",!0):d("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let p=await Bs(m);return p.length===0?d(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):d(JSON.stringify({envVars:p.map(u=>({key:u.key,category:u.category,description:u.description,hasValue:u.has_value})),message:`${p.length} environment variable(s) configured.`}))}case"delete":return n?(await Hs(m,n),d(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):d("Key is required. Provide the env var name to delete.",!0);default:return d(`Unknown action: ${s}. Use set, list, or delete.`,!0)}}catch(p){if(p instanceof X)return d(p.message,!0);let u=p instanceof Error?p.message:"An unexpected error occurred";return d(u,!0)}}var Zy,Za=I(()=>{"use strict";ve();Pe();It();Zy=kt.object({projectPath:kt.string().optional().describe("Path to the project directory (default: cwd)"),action:kt.enum(["set","list","delete"]).describe("Action to perform"),key:kt.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:kt.string().optional().describe("Environment variable value (required for 'set')"),category:kt.string().optional().describe("Category for the env var (default: 'custom')"),description:kt.string().optional().describe("Description of what this env var is for"),setupUrl:kt.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as An}from"zod";import{resolve as tm,join as nm}from"path";import{existsSync as sm,readFileSync as om,writeFileSync as rm}from"fs";function zo(t,e){let s=nm(t,"mistflow.json");if(!sm(s))return;let n;try{n=JSON.parse(om(s,"utf-8"))}catch{return}n.domains=e,rm(s,JSON.stringify(n,null,2)+`
|
|
6188
|
+
`)}async function el(t){let{projectPath:e,action:s,domain:n,domainId:o}=t,i=tm(e??process.cwd());if(!Te())return Me("manage custom domains");let a=dt(i)?.projectId;if(!a)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(s){case"add":{if(!n)return d("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Us(a,n),c=await ut(a);return zo(i,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await ut(a);return l.length===0?d(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):d(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!o){if(n){let p=(await ut(a)).find(u=>u.domain===n);if(p){let u=await Vn(a,p.id);return d(JSON.stringify({domain:u.domain,status:u.status,ssl:u.ssl_status,error:u.error_message,message:u.status==="active"?`Domain '${u.domain}' is active and serving traffic.`:`Domain '${u.domain}' is ${u.status}. Make sure DNS records are configured correctly.`}))}return d(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return d("Provide either domainId or domain name to verify.",!0)}let l=await Vn(a,o),c=await ut(a);return zo(i,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!o&&!n)return d("Provide either domainId or domain name to remove.",!0);let l=o;if(!l&&n){let p=(await ut(a)).find(u=>u.domain===n);if(!p)return d(`Domain '${n}' not found.`,!0);l=p.id}await Fs(a,l);let c=await ut(a);return zo(i,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return d(`Unknown action: ${s}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof X)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var ab,tl=I(()=>{"use strict";ve();Pe();It();ab=An.object({projectPath:An.string().optional().describe("Path to the project directory (default: cwd)"),action:An.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:An.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:An.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as Je}from"zod";var im,nl,sl=I(()=>{"use strict";ve();Za();tl();im=Je.object({resource:Je.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Je.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Je.string().optional().describe("Path to the project directory (default: cwd)"),key:Je.string().optional().describe("(env) Variable name"),value:Je.string().optional().describe("(env set) Variable value"),category:Je.string().optional().describe("(env set) Category"),description:Je.string().optional().describe("(env set) Description"),setupUrl:Je.string().optional().describe("(env set) URL to obtain the value"),domain:Je.string().optional().describe("(domain) Domain name"),domainId:Je.string().optional().describe("(domain) Domain ID")}),nl={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:im,handler:async t=>{let e=t;switch(e.resource){case"env":return Xa({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return el({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return d(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}}});import{z as Rn}from"zod";import{resolve as am}from"path";import{existsSync as lm}from"fs";import{join as cm}from"path";function dm(t,e=15){let s=t.split(`
|
|
6189
|
+
`).filter(n=>n.length>0);return s.length<=e?t:s.slice(-e).join(`
|
|
6190
|
+
`)}var pm,ol,rl=I(()=>{"use strict";ve();In();Wt();Fo();pm=Rn.object({projectPath:Rn.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:Rn.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:Rn.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:Rn.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."}),ol={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:pm,handler:async(t,e)=>{let s=t;if(s.jobId){let l=await wt(s.jobId);if(!l)return d(JSON.stringify({status:"not_found",jobId:s.jobId,message:`No install job found for jobId '${s.jobId}'. Start a new one with { projectPath }.`}),!0);let c=s.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let p=l.elapsed,u=e?Ve(e.server,e.progressToken,()=>`Install running (${p}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let g=await Xt(s.jobId,{timeoutMs:c*1e3,onPoll:D=>{p=D.elapsed}});g&&(l=g)}finally{u.stop()}}if(l.status==="running"||l.status==="starting")return d(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:dm(l.logTail),nextAction:"Install still running after long-poll window. Call mist_install again with the same jobId to continue waiting."}));if(l.status==="complete"){let p=await Ra(l.cwd),u=!1;p&&p.freshlyStarted?(u=await Ia(p.state.url,15e3),u&&Ea(p.state.url)):p&&(u=!0);let g=p?u?` PREVIEW: Live dev server at ${p.state.url} (browser opened). TELL THE USER: "Your app is rendering at ${p.state.url} \u2014 it'll refresh live as it's built."`:` PREVIEW: Dev server starting at ${p.state.url} (still compiling). TELL THE USER: "Open ${p.state.url} in your browser in ~30s \u2014 your app will appear there and refresh live as it's built."`:"";return d(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,...p?{previewUrl:p.state.url,previewReady:u}:{},nextAction:`Dependencies installed.${g} Run mist_implement next to start executing plan steps.`}))}let m=jt(l.id);return d(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:m,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${m.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let n=am(s.projectPath);if(!lm(cm(n,"package.json")))return d(`No package.json at ${n}. Confirm the path and that mist_init has scaffolded the project.`,!0);let r=`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 bt({type:"install",cmd:"sh",args:["-c",r],cwd:n,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return d(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:n,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+a.id+"' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s."}))}}});import{z as Zt}from"zod";import{resolve as um,join as Ye}from"path";import{existsSync as Qe,readFileSync as il,statSync as mm,readdirSync as hm}from"fs";function gm(t){let e=0,s=0,n=[t];for(;n.length>0&&s<1e4;){let o=n.pop();s++;let i;try{i=hm(o)}catch{continue}for(let r of i){let a=Ye(o,r),l;try{l=mm(a)}catch{continue}l.isDirectory()?n.push(a):l.isFile()&&(e+=l.size)}}return e}function fm(t){if(!(Qe(Ye(t,"open-next.config.ts"))||Qe(Ye(t,"open-next.config.js"))))return null;let s=Ye(t,".open-next","worker.js");if(!Qe(s))return`Build exited 0 but .open-next/worker.js is missing at ${s}. 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=Ye(t,".open-next","server-functions","default");if(!Qe(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 o=gm(n);return o<al?`Build exited 0 but the server-functions bundle is only ${o} bytes (expected at least ${al}). 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 bm(t){let e=Ye(fs(),t,"stdout.log"),s=Ye(fs(),t,"stderr.log"),n="";try{Qe(e)&&(n+=il(e,"utf-8"))}catch{}try{Qe(s)&&(n+=`
|
|
6191
|
+
`+il(s,"utf-8"))}catch{}return n}function wm(t,e=15){let s=t.split(`
|
|
6192
|
+
`).filter(n=>n.length>0);return s.length<=e?t:s.slice(-e).join(`
|
|
6193
|
+
`)}function vm(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,s=new Set;for(let n of t.matchAll(e)){let o=n[1];if(o.startsWith(".")||o.startsWith("@/")||o.startsWith("~/"))continue;let i=o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0];i&&s.add(i)}return[...s]}function km(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${Ot()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var al,ym,ll,cl=I(()=>{"use strict";ve();In();yo();Wt();ds();al=100*1024;ym=Zt.object({projectPath:Zt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Zt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Zt.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls."),waitSeconds:Zt.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical build fits in 2 round-trips instead of 6-8. Default 20. Set 0 to disable."),sessionId:Zt.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."});ll={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:ym,handler:async(t,e)=>{let s=t;if(s.jobId){let c=await wt(s.jobId);if(!c)return d(JSON.stringify({status:"not_found",jobId:s.jobId,message:`No build job found for jobId '${s.jobId}'. Start a new one with { projectPath }.`}),!0);let m=s.waitSeconds??20;if(m>0&&(c.status==="running"||c.status==="starting")){let R=c.elapsed,G=e?Ve(e.server,e.progressToken,()=>`Build running (${R}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let K=await Xt(s.jobId,{timeoutMs:m*1e3,onPoll:te=>{R=te.elapsed}});K&&(c=K)}finally{G.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:wm(c.logTail),nextAction:"Build still running after long-poll window. Call mist_build again with the same jobId to continue waiting."}));if(c.status==="complete"){let R=fm(c.cwd);if(R){let G=jt(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:G,error:R,nextAction:R+` Full build log: ${G.stdout} and ${G.stderr}.`}),!0)}return d(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let p=bm(c.id),u=ss(p),g=vm(p),D=km(p),_=jt(c.id),x=` Full log: ${_.stdout} and ${_.stderr}.`,v=g.length>0?`Build failed with missing modules: ${g.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${x}`:D?`${D}${x}`:u.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${x}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${x}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:u,missingModules:g,logTail:c.logTail,logPaths:_,nextAction:v}),!0)}let n=um(s.projectPath);if(!Qe(Ye(n,"package.json")))return d(`No package.json at ${n}. Run mist_init first.`,!0);if(!Qe(Ye(n,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let o,i,r,a=Qe(Ye(n,"open-next.config.ts"))||Qe(Ye(n,"open-next.config.js"));if(s.script)o="npm",i=["run",s.script],r=s.script;else if(a){if(!Gt())return d(Ot(),!0);o="npx",i=["-y","@opennextjs/cloudflare","build"],r="@opennextjs/cloudflare build"}else o="npm",i=["run","build"],r="build";let l=await bt({type:"build",cmd:o,args:i,cwd:n});return d(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:r,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 xm,readdirSync as Sm}from"fs";import{join as dl}from"path";import{pathToFileURL as Tm}from"url";async function _m(t){let e=dl(t,".mistflow","acceptance"),s=new Map;if(!xm(e))return s;let n=Sm(e).filter(o=>o.endsWith(".spec.ts")||o.endsWith(".spec.js")||o.endsWith(".spec.mjs"));for(let o of n){let i=o.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!i)continue;let r=dl(e,o);try{let a=await import(Tm(r).href),l=a.default??a.run;typeof l=="function"?s.set(i,l):console.error(`Probe ${o} doesn't export a default function (or named 'run'). Skipping.`)}catch(a){console.error(`Failed to load probe ${o}:`,a instanceof Error?a.message:a)}}return s}async function pl(t,e){let{sessionId:s,projectPath:n,deployUrl:o,seedCredentials:i}=e,a=(await un(s)).criteria,l=await _m(n),c=[];for(let m of a){let p=l.get(m.id);if(!p){c.push({criterion_id:m.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${m.id}.spec.ts`}});continue}try{await t.goto(o,{waitUntil:"domcontentloaded"});let u=await p(t,{url:o,criterion:m,seedCredentials:i});c.push({criterion_id:m.id,status:u.pass?"pass":"fail",evidence:{...u.detail?{detail:u.detail}:{},...u.screenshot?{screenshot:u.screenshot}:{}}})}catch(u){c.push({criterion_id:m.id,status:"fail",evidence:{error:u instanceof Error?u.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var ul=I(()=>{"use strict";Pe()});import{existsSync as Im,readFileSync as Pm}from"fs";import{join as Cm}from"path";import{z as en}from"zod";function fl(t){let e=Cm(t,"mistflow.json");if(!Im(e))return null;try{return JSON.parse(Pm(e,"utf-8"))}catch{return null}}async function ml(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),s=await e.text();return{status:e.status,body:s}}catch(e){return{status:0,body:String(e)}}}async function Rm(t,e,s){try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...s??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),o=await n.text(),i;try{i=JSON.parse(o)}catch{}return{status:n.status,json:i}}catch{return{status:0}}}async function hl(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function xt(t,e,s){let n=[],o=i=>{i.type()==="error"&&n.push(i.text())};t.on("console",o);try{let i=await s(),r=await hl(t);return{name:e,status:i.pass?"pass":"fail",detail:i.detail,fix:i.fix,screenshot:r,consoleErrors:n.length>0?n:void 0}}catch(i){let r=await hl(t);return{name:e,status:"fail",detail:`Unexpected error: ${i instanceof Error?i.message:String(i)}`,screenshot:r,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",o)}}async function Em(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(),s=fl(e),n=t.url;if(!n&&t.deploymentId)try{let a=await pt(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=s?.deploy?.url),!n)return d("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa action='acceptance'.",!0);let o;if(t.deploymentId)try{let l=await Kn(t.deploymentId);l?.adminEmail&&l?.adminPassword&&(o={email:l.adminEmail,password:l.adminPassword})}catch(a){console.error("[acceptance] getSeedInfo failed (continuing without):",a instanceof Error?a.message:String(a))}let i,r;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(Dt(),dn)),l=await a();i=l.context,r=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 pl(r,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:o});try{await io(t.sessionId,l)}catch(u){console.error("[acceptance] submitAcceptanceResults failed:",u instanceof Error?u.message:String(u))}let c=l.filter(u=>u.status==="pass").length,m=l.filter(u=>u.status==="fail").length,p=l.filter(u=>u.status==="skipped").length;return d(JSON.stringify({status:m===0?"pass":"fail",url:n,totals:{passed:c,failed:m,skipped:p,total:a.length},results:l.map(u=>({criterion_id:u.criterion_id,status:u.status,detail:u.evidence&&typeof u.evidence=="object"&&"detail"in u.evidence?u.evidence.detail:u.evidence&&typeof u.evidence=="object"&&"reason"in u.evidence?u.evidence.reason:void 0})),nextAction:m===0?"All required acceptance criteria passed. The app is shippable.":"Some criteria failed. Read the per-criterion detail, fix the underlying code, then re-run mist_qa action='acceptance'."}),m>0)}finally{if(i)try{await i.close()}catch{}}}async function Nm(t){let e=t.projectPath??process.cwd(),s=fl(e),n=t.url;if(!n&&t.deploymentId)try{let R=await pt(t.deploymentId);R.url&&(n=R.url)}catch(R){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,R instanceof Error?R.message:String(R))}if(n||(n=s?.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 o=s?.projectId,i=[],r=await ml(`${n}/api/health`);if(r.status!==200)return i.push({name:"Health endpoint",status:"fail",detail:`Returns ${r.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),Ss(n,i);i.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await ml(`${n}/api/auth/ok`);if(a.status!==200)return i.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${a.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),Ss(n,i);i.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",m="QaTemp1!",p="single",u="user",g=[];async function D(R,G,K,te){let ce=await Rm(`${n}/api/admin/seed`,{token:te,email:G,password:m,role:K});if(ce.status!==200||!ce.json)return console.error(`[qa] Seed (${R}) returned ${ce.status}`),null;let E=ce.json.sessionToken;if(!E)return null;let B=ce.json.seeded===!0;return{role:R,email:G,sessionToken:E,password:B?m:void 0}}if(o){let R=await Kn(o);if(R){if(p=R.authMode??"single",u=R.defaultRole??"user",console.error(`[qa] auth_mode=${p}, default_role=${u}`),p!=="none"){let K=await D("actor",l,p==="multi"?"admin":u,R.seedToken);if(K&&g.push(K),p==="multi"){let te=await D("user",c,u,R.seedToken);te?g.push(te):i.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${u}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),p="none"}if(p!=="none"&&g.length===0)return i.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy injects ADMIN_SEED_TOKEN and stores it on the backend; the scaffold's /api/admin/seed route accepts { token, email, password, role } and creates synthetic QA users with the requested role."}),Ss(n,i);let _,x,v;try{let{getIsolatedContext:R}=await Promise.resolve().then(()=>(Dt(),dn)),G=await R();_=G.context,v=G.page}catch(R){let G=R instanceof Error?R.message:String(R);return d(JSON.stringify({status:"cannot_verify",url:n,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:G,httpChecks:i.map(({screenshot:K,...te})=>te),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${n}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${n}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_qa again for full verification."].join(`
|
|
6194
|
+
`)}),!1)}try{let R=await xt(v,"Landing page",async()=>{await v.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await v.waitForLoadState("networkidle").catch(()=>{});let E=await v.evaluate(()=>{let N=document.body;if(!N)return"";let ee=document.createTreeWalker(N,NodeFilter.SHOW_TEXT),Q="",J;for(;J=ee.nextNode();){let b=J.parentElement;if(b){let $=window.getComputedStyle(b);$.display!=="none"&&$.visibility!=="hidden"&&parseFloat($.opacity)>0&&(Q+=J.textContent?.trim()+" ")}}return Q.trim()});if(E.length<50)return{pass:!1,detail:`Landing page appears blank (${E.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 B=v.url();return B.includes("/login")||B.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 (${E.length} chars)`}});i.push(R),p==="none"&&i.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let G=g[0],K=(E,B)=>g.length>1&&E?`${B} (${E.role})`:B,te=!1;if(G?.password){let E=await xt(v,K(G,"Login"),async()=>{await v.goto(`${n}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await v.waitForLoadState("networkidle").catch(()=>{});let B=v.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),N=v.locator('input[type="password"], input[name="password"]');try{await B.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 B.first().fill(G.email),await N.first().fill(G.password),await v.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await v.waitForURL(Q=>!Q.pathname.includes("/login"),{timeout:1e4})}catch{let Q=await v.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:Q?`Login failed: ${Q}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified QA accounts."}}return te=!0,{pass:!0,detail:`Logged in, redirected to ${v.url()}`}});i.push(E)}else G&&i.push({name:K(G,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!te&&G){let E=new URL(n).hostname,B=n.startsWith("https");await _.addCookies([{name:B?"__Secure-better-auth.session_token":"better-auth.session_token",value:G.sessionToken,domain:E,path:"/",httpOnly:!0,secure:B,sameSite:"Lax"}]),console.error(`[qa] Injected ${G.role} cookie for primary walk`)}if(G){let E=await xt(v,K(G,"Dashboard"),async()=>{v.url().includes("/dashboard")||(await v.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await v.waitForLoadState("networkidle").catch(()=>{}),new URL(v.url()).pathname==="/"&&(await v.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await v.waitForLoadState("networkidle").catch(()=>{})));let ee=await v.content();return ee.length<1e3?{pass:!1,detail:`Dashboard page is very small (${ee.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await v.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 (${ee.length} bytes)`}});i.push(E);let B=await v.evaluate(()=>{let ee=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(J=>{let b=J.getAttribute("href");b&&b.startsWith("/")&&!b.startsWith("/api")&&!b.includes("[")&&b!=="/dashboard"&&b!=="/"&&!b.includes("/login")&&!b.includes("/sign")&&ee.push(b)}),[...new Set(ee)]});if(B.length>0){let ee=0,Q=[];for(let J of B.slice(0,8)){let b=await xt(v,K(G,`Page: ${J}`),async()=>{await v.goto(`${n}${J}`,{waitUntil:"domcontentloaded",timeout:15e3}),await v.waitForLoadState("networkidle").catch(()=>{});let $=await v.title(),V=await v.content();return $.toLowerCase().includes("500")||$.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."}:$.toLowerCase().includes("404")||$.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${J} not found. Create the page or remove the nav link.`}:await v.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:V.length<500?{pass:!1,detail:`Page is very small (${V.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});b.status==="fail"&&(ee++,Q.push(J)),i.push(b)}}let N=await xt(v,"Design quality",async()=>{let ee=v.url().includes("/dashboard")?v.url():`${n}/dashboard`;v.url().includes("/dashboard")||(await v.goto(ee,{waitUntil:"domcontentloaded",timeout:15e3}),await v.waitForLoadState("networkidle").catch(()=>{}));let Q=await v.evaluate(()=>{let J=[],b=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),$=new Set;b.forEach(U=>{$.add(window.getComputedStyle(U).fontSize)}),b.length>=3&&$.size<2&&J.push("TYPOGRAPHY: All headings appear the same size. Create clear hierarchy with 3+ distinct sizes using a modular scale (1.25-1.5x ratio).");let V=Array.from(b).map(U=>parseInt(U.tagName.charAt(1),10));for(let U=1;U<V.length;U++)if(V[U]-V[U-1]>1){J.push(`TYPOGRAPHY: Heading level skipped (h${V[U-1]} -> h${V[U]}). Use sequential heading levels for accessibility.`);break}let Z=document.querySelectorAll("*"),me=!1,S=!1;Z.forEach(U=>{let ae=window.getComputedStyle(U);ae.backgroundColor==="rgb(0, 0, 0)"&&U.clientHeight>100&&U.clientWidth>200&&(me=!0);let Ae=ae.backgroundColor,$e=ae.color;if(Ae&&!Ae.includes("0, 0, 0")&&!Ae.includes("255, 255, 255")&&Ae!=="rgba(0, 0, 0, 0)"&&Ae!=="transparent"&&$e.match(/rgb\((\d+), (\d+), (\d+)\)/)){let et=$e.match(/rgb\((\d+), (\d+), (\d+)\)/);if(et){let[ze,Oe,h]=[parseInt(et[1]),parseInt(et[2]),parseInt(et[3])],f=Math.abs(ze-Oe)<10&&Math.abs(Oe-h)<10&&ze>80&&ze<180,w=Ae.match(/rgb\((\d+), (\d+), (\d+)\)/);if(f&&w){let[A,C,M]=[parseInt(w[1]),parseInt(w[2]),parseInt(w[3])];!(Math.abs(A-C)<15&&Math.abs(C-M)<15)&&U.textContent&&U.textContent.trim().length>0&&(S=!0)}}}}),me&&J.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)."),S&&J.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 Ce=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),Y=!1;Ce.forEach(U=>{U.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(Y=!0)}),Y&&J.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let ie=document.querySelectorAll("p, li, span, div"),we=0,ue=0;ie.forEach(U=>{U.textContent&&U.textContent.trim().length>20&&U.clientHeight>0&&(ue++,window.getComputedStyle(U).textAlign==="center"&&we++)}),ue>5&&we/ue>.7&&J.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let xe=new Set;Z.forEach(U=>{let ae=window.getComputedStyle(U);ae.gap&&ae.gap!=="normal"&&ae.gap!=="0px"&&xe.add(ae.gap)}),xe.size===1&&Z.length>20&&J.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let Ne=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(U=>{U.querySelectorAll("tbody tr").length===0&&(U.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||J.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 Be=document.querySelectorAll("style"),Ze=!1;Be.forEach(U=>{let ae=U.textContent||"";(ae.includes("bounce")||ae.includes("elastic")||ae.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Ze=!0)}),Ze&&J.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let Tt=document.querySelectorAll("button, a, input, select, [role='button']"),_e=[];if(Tt.forEach(U=>{let ae=U.getBoundingClientRect();if(ae.width>0&&ae.height>0&&(ae.width<32||ae.height<32)){let Ae=U.tagName.toLowerCase(),$e=U.id?`#${U.id}`:"",et=U.className&&typeof U.className=="string"?`.${U.className.split(/\s+/).filter(Boolean).slice(0,2).join(".")}`:"",ze=(U.textContent||"").trim().slice(0,40),Oe=`${Ae}${$e}${et}`,h=`${Math.round(ae.width)}x${Math.round(ae.height)}px`;_e.push(ze?`${Oe} ("${ze}", ${h})`:`${Oe} (${h})`)}}),_e.length>3){let U=_e.slice(0,8).map((Ae,$e)=>` ${$e+1}. ${Ae}`).join(`
|
|
6195
|
+
`),ae=_e.length>8?`
|
|
6196
|
+
\u2026and ${_e.length-8} more.`:"";J.push(`ACCESSIBILITY: ${_e.length} interactive elements are smaller than 32x32px (minimum recommended touch target is 44x44px). Add padding so each element's bounding box reaches 44x44.
|
|
5341
6197
|
Offenders:
|
|
5342
|
-
${
|
|
5343
|
-
${
|
|
5344
|
-
`)}`,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."}});
|
|
5345
|
-
${
|
|
5346
|
-
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});
|
|
5347
|
-
Fix: ${
|
|
6198
|
+
${U}${ae}`)}return J});return Q.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${Q.length} design quality issue(s) found:
|
|
6199
|
+
${Q.map((J,b)=>`${b+1}. ${J}`).join(`
|
|
6200
|
+
`)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});i.push(N)}if(i.find(E=>E.name==="Landing page"&&E.status==="pass")){let E=await xt(v,"Landing design quality",async()=>{await v.goto(n,{waitUntil:"domcontentloaded",timeout:15e3}),await v.waitForLoadState("networkidle").catch(()=>{});let B=await v.evaluate(()=>{let N=[];document.querySelectorAll("*").forEach(b=>{let $=window.getComputedStyle(b);($.getPropertyValue("-webkit-background-clip")||$.getPropertyValue("background-clip"))==="text"&&b.textContent&&b.textContent.trim().length>0&&N.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let Q=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(Q){let b=(Q.textContent||"").toLowerCase(),$=["transform your","unlock the power","revolutionize your","take your .* to the next level","the future of","welcome to","get started today","join thousands","powerful analytics","seamless integration","lightning fast"];for(let V of $)if(b.match(new RegExp(V))){N.push(`COPY: Generic hero text detected ('${V}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(b=>{let V=window.getComputedStyle(b).gridTemplateColumns;if(V){let Z=V.split(" ").filter(S=>S!=="").length,me=b.children;if(Z===3&&me.length===3){let S=Array.from(me).map(ie=>ie.offsetHeight),Ce=S.every(ie=>Math.abs(ie-S[0])<5),Y=Array.from(me).every(ie=>{let we=ie.querySelectorAll("svg"),ue=ie.querySelectorAll("h2, h3, h4"),xe=ie.querySelectorAll("p");return we.length>=1&&ue.length>=1&&xe.length>=1});Ce&&Y&&N.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.")}}}),N});return B.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${B.length} landing design issue(s):
|
|
6201
|
+
${B.map((N,ee)=>`${ee+1}. ${N}`).join(`
|
|
6202
|
+
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(E)}let ce=g[1];if(ce){let{getIsolatedContext:E}=await Promise.resolve().then(()=>(Dt(),dn)),B=await E();x=B.context;let N=B.page,ee=new URL(n).hostname,Q=n.startsWith("https");await x.addCookies([{name:Q?"__Secure-better-auth.session_token":"better-auth.session_token",value:ce.sessionToken,domain:ee,path:"/",httpOnly:!0,secure:Q,sameSite:"Lax"}]),console.error(`[qa] Injected ${ce.role} cookie for secondary walk`);let J=await xt(N,K(ce,"Dashboard"),async()=>{await N.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await N.waitForLoadState("networkidle").catch(()=>{}),new URL(N.url()).pathname==="/"&&(await N.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await N.waitForLoadState("networkidle").catch(()=>{}));let $=await N.content();return $.length<1e3?{pass:!1,detail:`Dashboard is very small (${$.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 N.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 (${$.length} bytes)`}});i.push(J);let b=await N.evaluate(()=>{let $=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(V=>{let Z=V.getAttribute("href");Z&&Z.startsWith("/")&&!Z.startsWith("/api")&&!Z.includes("[")&&Z!=="/dashboard"&&Z!=="/"&&!Z.includes("/login")&&!Z.includes("/sign")&&$.push(Z)}),[...new Set($)]});for(let $ of b.slice(0,8)){let V=await xt(N,K(ce,`Page: ${$}`),async()=>{await N.goto(`${n}${$}`,{waitUntil:"domcontentloaded",timeout:15e3}),await N.waitForLoadState("networkidle").catch(()=>{});let Z=await N.title(),me=await N.content();return Z.toLowerCase().includes("500")||Z.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."}:Z.toLowerCase().includes("404")||Z.toLowerCase().includes("not found")?{pass:!0,detail:"404 (likely admin-only \u2014 acceptable)"}:await N.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."}:me.length<500?{pass:!1,detail:`Page very small (${me.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});i.push(V)}}}finally{_&&await _.close().catch(()=>{}),x&&await x.close().catch(()=>{})}if(t.deploymentId){let R=i.filter(te=>te.status==="fail"),G=i.filter(te=>te.status==="pass"),K=Date.now();await qs(t.deploymentId,{checks:i.map(({screenshot:te,...ce})=>ce),overall:R.length===0?"pass":"fail",passed:G.length,failed:R.length,duration_ms:Date.now()-K}).catch(()=>{})}return Ss(n,i)}function Ss(t,e){let s=e.filter(i=>i.status==="fail"),n=e.filter(i=>i.status==="pass"),o=[];if(s.length===0)o.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${e.length} checks OK. The app is working correctly.`,url:t,checks:e.map(({screenshot:i,...r})=>r)})});else{let i=s.map((r,a)=>`${a+1}. **${r.name}**: ${r.detail}
|
|
6203
|
+
Fix: ${r.fix}`).join(`
|
|
5348
6204
|
|
|
5349
|
-
`);
|
|
6205
|
+
`);o.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${s.length} issue(s) on the live app. Fix them and redeploy.`,url:t,passed:n.length,failed:s.length,checks:e.map(({screenshot:r,...a})=>a),fixInstructions:`The deployed app at ${t} has ${s.length} issue(s):
|
|
5350
6206
|
|
|
5351
|
-
${
|
|
6207
|
+
${i}
|
|
5352
6208
|
|
|
5353
|
-
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
|
|
5354
|
-
${
|
|
6209
|
+
Fix these issues in the source code, then call mist_deploy with action='deploy'${t.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let i of e)i.screenshot&&o.push({type:"image",data:i.screenshot,mimeType:"image/png"});return{content:o}}var Am,gl,yl=I(()=>{"use strict";ve();Pe();ul();Am=en.object({projectPath:en.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:en.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:en.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:en.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:en.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.")}),gl={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:Am,handler:async t=>{let e=t;return e.action==="acceptance"?Em(e):Nm(e)}}});import{existsSync as Ts,readdirSync as Om,statSync as bl,unlinkSync as wl}from"fs";import{join as tn}from"path";import{execFile as jm}from"child_process";function Dm(t,e){let s=0;for(let n of e){let o=tn(t,n);if(Ts(o))try{let i=bl(o);if(i.isFile())s++;else if(i.isDirectory()){let r=[o];for(;r.length;){let a=r.pop(),l=Om(a,{withFileTypes:!0});for(let c of l){let m=tn(a,c.name);c.isDirectory()?r.push(m):s++}}}}catch{}}return s}function Mm(t,e,s){return new Promise(n=>{jm("tar",t,{cwd:e,timeout:s,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(o,i,r)=>{n({success:!o,stderr:r?.toString()??""})})})}async function vl(t){let e=tn(t,".open-next-build.tar.gz"),s=[".open-next"];Ts(tn(t,"db"))&&s.push("db"),Ts(tn(t,"drizzle.config.ts"))&&s.push("drizzle.config.ts"),Ts(tn(t,"package.json"))&&s.push("package.json");let n=Dm(t,s),o=await Mm(["-czf",e,"-C",t,...s],t,12e4);if(!o.success){try{wl(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(o.stderr?`
|
|
6210
|
+
${o.stderr.slice(-500)}`:""))}let i=0;try{i=bl(e).size}catch{}return{path:e,sizeBytes:i,fileCount:n}}function kl(t){if(t)try{wl(t)}catch{}}function xl(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 Tl=I(()=>{"use strict"});import{z as lt}from"zod";import{resolve as Lm,join as En}from"path";import{existsSync as Nn,readFileSync as $m}from"fs";import{homedir as Um}from"os";function _l(t){return Nn(En(t,".open-next"))}function qm(t){return dt(t)?.deploy?.strategy==="staging"?"preview":null}async function Bm(t,e){if(!(Nn(En(t,"open-next.config.ts"))||Nn(En(t,"open-next.config.js"))))return{kind:"failed",result:d(`No .open-next/ build output at ${t}, and no open-next.config.* either. This project is not configured for the Cloudflare adapter \u2014 mist_deploy ships the .open-next/ artifact, not raw source. If this is a Mistflow project, re-run mist_init to restore the OpenNext config.`,!0)};if(!Nn(En(t,"node_modules")))return{kind:"failed",result:d(`node_modules is missing at ${t}. Call mist_install { projectPath } first, then mist_deploy.`,!0)};if(!Gt())return{kind:"failed",result:d(Ot(),!0)};let n=await bt({type:"build",cmd:"npx",args:["-y","@opennextjs/cloudflare","build"],cwd:t}),o=e?Ve(e.server,e.progressToken,()=>`Auto-building before deploy \u2014 OpenNext adapter (${n.id})`):{stop:()=>{}},i;try{i=await Xt(n.id,{timeoutMs:45e3})}finally{o.stop()}if(!i)return{kind:"failed",result:d(`Auto-build job ${n.id} disappeared. Run mist_build { projectPath } manually, then mist_deploy.`,!0)};if(i.status==="running"||i.status==="starting")return{kind:"running",result:d(JSON.stringify({status:"building",buildJobId:n.id,phase:"auto-build",nextAction:`Build is still running after the 45s inline window. Call mist_build { jobId: '${n.id}' } to keep waiting (long-polls server-side), then call mist_deploy { action: 'deploy', projectPath } again. Do NOT ask the user \u2014 the build is in flight, just keep going.`}))};if(i.status==="complete"&&_l(t))return{kind:"ok"};let r=jt(n.id),a=(i.logTail??"").split(`
|
|
5355
6211
|
`).slice(-30).join(`
|
|
5356
|
-
`);return{kind:"failed",result:d(JSON.stringify({status:"build_failed",buildJobId:n.id,exitCode:
|
|
5357
|
-
`)}async function
|
|
5358
|
-
`))}if(
|
|
5359
|
-
${
|
|
6212
|
+
`);return{kind:"failed",result:d(JSON.stringify({status:"build_failed",buildJobId:n.id,exitCode:i.exitCode,logTail:a,logPaths:r,nextAction:`Auto-build before deploy failed (exit ${i.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 zm(t){let e=Lm(t.projectPath);if(!Te())return Me("deploy");let s=dt(e),n=s?.projectId;if(!n){if(!s?.name)return d(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);let a=typeof s.plan=="object"&&s.plan!==null?s.plan:void 0;if(!a&&s.planId)try{let u=En(Um(),".mistflow","plans",`${s.planId}.json`);if(Nn(u)){let g=JSON.parse($m(u,"utf-8"));a=g?.plan??g}}catch{}let l=a?.pickedDirection??void 0,c=a?.imageryBrief??l?.imagery??void 0,m=a?.designConversationId??void 0,p=a?{name:a.name,summary:a.summary,audienceType:a.audienceType,authModel:a.authModel,dbProvider:s.dbProvider,dataModel:a.dataModel,design:a.design,publicLanding:a.publicLanding,...typeof a.designMd=="string"&&a.designMd?{designMd:a.designMd}:{},...m?{designConversationId:m}:{},...a.features?{features:a.features}:{},...a.integrations?{integrations:a.integrations}:{},...a.hasAI===!0?{hasAI:!0}:{},...a.hasEmail===!0?{hasEmail:!0}:{},...a.hasStorage===!0?{hasStorage:!0}:{}}:void 0;try{n=(await Ct(s.name,{dbProvider:s.dbProvider,requestedSubdomain:s.requestedSubdomain,pickedDirection:l,imageryBrief:c,planContext:p,designConversationId:m})).id,js(e,{projectId:n}),console.error(`[deploy] auto-registered project ${n.slice(0,8)} (${s.name})`+(s.requestedSubdomain?` at ${s.requestedSubdomain}.mistflow.app`:"")+(p?" with plan context":" WITHOUT plan context (no plan blob in mistflow.json \u2014 AI/storage may not provision)"))}catch(u){let g=u instanceof X||u instanceof Error?u.message:String(u);return d(`Auto-register before deploy failed: ${g}. 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(!_l(e)){let a=await Bm(e,t.ctx);if(a.kind==="running"||a.kind==="failed")return a.result}let o=t.environment??qm(e)??"production",i=t.adminEmail??pr()?.email,r=null;try{r=await vl(e);let a=await $s(n,r.path,o,i,void 0,void 0,void 0);return d(JSON.stringify({status:"running",jobId:a.deployment_id,deploymentId:a.deployment_id,environment:a.environment??o,buildSize:xl(r.sizeBytes),buildFileCount:r.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${a.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side, so there's no need to sleep between calls. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(a){let l=a instanceof X||a instanceof Error?a.message:String(a);return d(`Deploy upload failed: ${l}`,!0)}finally{kl(r?.path)}}async function Hm(t,e){let s=e.ctx?Ve(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let n=await pt(t,{waitSeconds:e.waitSeconds}),o=Sl(n.status),i=n.id??t;return n.status==="live"?(e.projectPath&&n.url&&(js(e.projectPath,{deploy:{url:n.url,deploymentId:i,completedAt:n.completedAt}}),Vt(e.projectPath)),d(JSON.stringify({status:"complete",jobId:i,deploymentId:i,url:n.url,completedAt:n.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${n.url??""}', deploymentId: '${i}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`}))):n.status==="failed"?d(JSON.stringify({status:"failed",jobId:i,deploymentId:i,error:n.error,phase:o,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):d(JSON.stringify({status:"running",jobId:i,deploymentId:i,phase:o,phaseCode:n.status,nextAction:`Still ${n.status} after the ${e.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${i}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(n){let o=n instanceof X||n instanceof Error?n.message:String(n);return d(`Could not fetch deploy status: ${o}`,!0)}finally{s.stop()}}async function Wm(t,e){if(!Te())return Me("promote a preview deployment");let n=dt(t)?.projectId;if(!n)return d(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let o=e;if(!o)try{let r=(await Lt(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!r)return d("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);o=r.id}catch(i){let r=i instanceof X?i.message:String(i);return d(`Could not list deployments: ${r}`,!0)}try{let i=await Vs(n,o);return d(JSON.stringify({status:"running",jobId:i.deployment_id,deploymentId:i.deployment_id,promotedFrom:o,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${i.deployment_id}' } immediately \u2014 long-polls for up to 20s. Promotion re-uses the preview artifact and typically completes in ~10s, so one poll usually finishes the job.`}))}catch(i){let r=i instanceof X||i instanceof Error?i.message:String(i);return d(`Promote failed: ${r}`,!0)}}async function Gm(t){if(!Te())return Me("roll back a deployment");try{let e=await Ks(t);return d(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let s=e instanceof X||e instanceof Error?e.message:String(e);return d(`Rollback failed: ${s}`,!0)}}var Fm,Il,Pl=I(()=>{"use strict";ve();Pe();It();It();ms();Tl();Wt();qo();In();ds();Fm=lt.object({action:lt.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:lt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:lt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:lt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:lt.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:lt.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:lt.array(ws).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:lt.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.")});Il={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:Fm,handler:async(t,e)=>{let s=t;switch(s.action??"deploy"){case"deploy":{if(!s.projectPath)return d("projectPath is required for action='deploy'.",!0);if(s.envVarsRequired&&s.envVarsRequired.length>0)try{let o=vs(s.projectPath,s.envVarsRequired);o.added.length>0&&console.error(`[deploy] declared env.required: ${o.added.join(", ")}`)}catch(o){console.error("[deploy] env var merge skipped:",o instanceof Error?o.message:String(o))}return zm({projectPath:s.projectPath,environment:s.environment,adminEmail:s.adminEmail,ctx:e})}case"status":return s.deploymentId?Hm(s.deploymentId,{waitSeconds:s.waitSeconds??20,ctx:e,projectPath:s.projectPath,sessionId:s.sessionId}):d("deploymentId is required for action='status'.",!0);case"promote":return s.projectPath?Wm(s.projectPath,s.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return s.deploymentId?Gm(s.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}}});import{z as nn}from"zod";import{hostname as Vm}from"os";function Cl(){return Vm()}function Ho(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(`
|
|
6213
|
+
`)}async function Km(t){let e=Al.safeParse(t);if(!e.success){let r=e.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return d(`Invalid input: ${r}`,!0)}let s=e.data;if((s.action==="status"||s.action==="cancel"||s.action==="resume")&&!s.sessionId)return d(`Invalid input: action="${s.action}" requires sessionId.`,!0);if(s.action==="resume"&&!s.projectPath)return d('Invalid input: action="resume" requires projectPath.',!0);if(s.action==="status"){let r=s.sessionId,[a,l,c]=await Promise.all([Jn(r),Ut(r).catch(()=>null),un(r).catch(()=>null)]),m=[Ho(a),"",l?`Next instruction: ${l.instruction}${l.reason?` (${l.reason})`:""}`:"Next instruction: (unavailable)"];if(c&&c.criteria.length>0){m.push("",`Acceptance criteria (${c.criteria.length}):`);for(let p of c.criteria)m.push(` - [${p.priority}] ${p.id}: ${p.description}`)}return d(m.join(`
|
|
6214
|
+
`))}if(s.action==="cancel"){let r=s.sessionId,a=await so(r,s.reason);return d(`Session cancelled.
|
|
6215
|
+
${Ho(a)}
|
|
5360
6216
|
|
|
5361
|
-
Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(
|
|
6217
|
+
Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(s.action==="resume"){let r=s.sessionId,a=s.projectPath,l=Cl(),c=await mn(r,{machine_id:l,local_path:a}),m=await Jn(r),p=await Ut(r).catch(()=>null);return d(`Resumed session on this machine.
|
|
5362
6218
|
Machine: ${l}
|
|
5363
6219
|
Local path: ${c.local_path}
|
|
5364
6220
|
Last seen: ${c.last_seen_at}
|
|
5365
6221
|
|
|
5366
|
-
`+
|
|
6222
|
+
`+Ho(m)+(p?`
|
|
5367
6223
|
|
|
5368
|
-
Next instruction: ${p.instruction}${p.reason?` (${p.reason})`:""}`:""))}let n=
|
|
5369
|
-
`+(
|
|
5370
|
-
`))}var
|
|
5371
|
-
Reason: ${
|
|
5372
|
-
Status: ${
|
|
6224
|
+
Next instruction: ${p.instruction}${p.reason?` (${p.reason})`:""}`:""))}let n=Cl(),o=await hn(n,{includeIdle:s.includeIdle===!0});if(o.length===0){let r=s.includeIdle?"this machine has no sessions bound at all":"no active sessions touched in the last 24h on this machine";return d(`${r} (${n}).
|
|
6225
|
+
`+(s.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 i=[`Sessions bound on this machine (${n}):`,"",...o.map(r=>` - ${r.id} status=${r.status}${r.paused_after_plan?" (paused)":""} ${r.description?`"${r.description.slice(0,60)}"`:"(no description)"}`)];return d(i.join(`
|
|
6226
|
+
`))}var Al,Rl,El=I(()=>{"use strict";ve();Pe();Al=nn.object({action:nn.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:nn.string().uuid().optional().describe("Required for status / cancel / resume. Omit for list."),reason:nn.string().max(500).optional().describe("Optional cancellation reason (used with action=cancel)."),projectPath:nn.string().min(1).optional().describe("Absolute path to the project directory on this machine. Required for action=resume."),includeIdle:nn.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.")});Rl={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:Al,handler:Km}});var th={};import{Server as Jm}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Ym}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Qm,ListToolsRequestSchema as Xm}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as Zm}from"zod-to-json-schema";async function eh(){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 Ym;await _s.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var _s,Nl,Ol=I(()=>{"use strict";tt();ve();Sr();Lr();Ur();zr();Gr();fo();ni();ki();Li();Qa();sl();rl();cl();yl();Pl();El();Pe();_s=new Jm({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Xo()}),Nl=[xr,Mr,$r,Br,Wr,vi,Mi,Zr,Ya,ti,nl,ol,ll,gl,Il,Rl];_s.setRequestHandler(Xm,async()=>({tools:Nl.map(t=>({name:t.name,description:t.description,inputSchema:Zm(t.inputSchema)}))}));_s.setRequestHandler(Qm,async t=>{let e=Nl.find(s=>s.name===t.params.name);if(!e)return d(`Unknown tool: ${t.params.name}`,!0);try{let s=e.inputSchema.safeParse(t.params.arguments);if(!s.success){let r=s.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return d(`Invalid input: ${r}`,!0)}let n=typeof s.data=="object"&&s.data!==null&&"sessionId"in s.data&&typeof s.data.sessionId=="string"?s.data.sessionId:void 0;if(n&&e.name!=="mist_session")try{let r=await oo(n,e.name);if(!r.allowed)return d(`Tool ${e.name} not allowed for this session.
|
|
6227
|
+
Reason: ${r.reason}
|
|
6228
|
+
Status: ${r.status}
|
|
5373
6229
|
|
|
5374
|
-
Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(
|
|
6230
|
+
Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(r){if(r instanceof X&&r.code==="not_found")console.error(`Guard check 404 for tool ${e.name}: ${r.message}`);else throw r}let o=t.params._meta?.progressToken,i={server:_s,progressToken:o};try{return await e.handler(s.data,i)}finally{i.cleanup?.()}}catch(s){let n=s instanceof Error?s.message:"An unexpected error occurred";return console.error("Tool error:",s),d(n,!0)}});eh().catch(t=>{console.error("Fatal error:",t),process.exit(1)})});import{readFileSync as nh}from"fs";import{dirname as sh,join as oh}from"path";import{fileURLToPath as rh}from"url";var St=process.argv[2];if(St==="--version"||St==="-v"){try{let t=sh(rh(import.meta.url)),e=oh(t,"..","package.json"),s=JSON.parse(nh(e,"utf-8"));console.log(s.version)}catch{console.log("unknown")}process.exit(0)}(St==="--help"||St==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
|
|
5375
6231
|
|
|
5376
6232
|
Usage:
|
|
5377
6233
|
npx @mistflow-ai/mcp Start the MCP server on stdio (default; invoked by editors)
|
|
@@ -5379,8 +6235,8 @@ Usage:
|
|
|
5379
6235
|
|
|
5380
6236
|
To install the server into your editor config, use the installer:
|
|
5381
6237
|
npx -y mistflow-ai install
|
|
5382
|
-
`),process.exit(0));(
|
|
6238
|
+
`),process.exit(0));(St==="install"||St==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${St}' is no longer supported.
|
|
5383
6239
|
Use the installer package instead:
|
|
5384
6240
|
|
|
5385
|
-
npx -y mistflow-ai ${
|
|
5386
|
-
`),process.exit(1));await Promise.resolve().then(()=>(
|
|
6241
|
+
npx -y mistflow-ai ${St}
|
|
6242
|
+
`),process.exit(1));await Promise.resolve().then(()=>(Ol(),th));
|