@mistflow-ai/mcp 1.7.0 → 1.8.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 +238 -532
- package/dist/index.js +258 -552
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}var Wc,Gc,Kc,Jc,Vc,Yc,Qc,Xc,Zc,bs,ws,vs,ks,xs,Ss,_s,lt=v(()=>{"use strict";Wc="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.",Gc='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"`.',Kc="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.",Jc="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.",Vc='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.',Yc="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.",Qc="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.",Xc='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.',Zc="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.",bs="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).",ws="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.",vs="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.",ks="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.",xs="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.",Ss="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).",_s="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 zr,readFileSync as Rs,writeFileSync as ed,mkdirSync as td}from"fs";import{join as Br,dirname as Hr}from"path";import{homedir as nd}from"os";import{fileURLToPath as rd}from"url";function Ve(){if(Xn)return Xn;try{let t=rd(import.meta.url),e=Hr(t);for(let r=0;r<6;r++){let n=Br(e,"package.json");if(zr(n)){let s=JSON.parse(Rs(n,"utf-8"));if(s.name==="@mistflow-ai/mcp"&&typeof s.version=="string")return Xn=s.version,s.version}let o=Hr(e);if(o===e)break;e=o}}catch{}return Xn="0.0.0","0.0.0"}function Zn(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 Ts(t,e){let r=Zn(t),n=Zn(e);if(!r||!n)return 0;for(let o=0;o<3;o++){if(r[o]<n[o])return-1;if(r[o]>n[o])return 1}return 0}function As(t,e,r){if(r&&Ts(t,r)<0)return"unsupported";if(!e||Ts(t,e)>=0)return"none";let o=Zn(t),s=Zn(e);return!o||!s?"none":o[0]<s[0]?"major":o[1]<s[1]?"minor":"patch"}function vn(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||(Je={latest:e,minSupported:r,changelogUrl:n})}function Es(){let t=process.env.MISTFLOW_STATE_DIR||Br(nd(),".mistflow");return Br(t,"upgrade-state.json")}function od(){try{let t=Es();return zr(t)?JSON.parse(Rs(t,"utf-8")):{}}catch{return{}}}function sd(t){try{let e=Es(),r=Hr(e);zr(r)||td(r,{recursive:!0}),ed(e,JSON.stringify(t,null,2)+`
|
|
4
|
-
`,{mode:384})}catch{}}function
|
|
2
|
+
var od=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var vn=(t,e)=>{for(var r in e)od(t,r,{get:e[r],enumerable:!0})};function Es(){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(ud),t.push(""),t.push(sd),t.push(""),t.push(id),t.push(""),t.push(ad),t.push(""),t.push(ld),t.push(""),t.push(md),t.push(""),t.push(dd),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(cd),t.push(""),t.push(pd),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 sd,id,ad,ld,cd,dd,pd,ud,md,_s,Ts,Cs,Is,Ps,Rs,As,ut=x(()=>{"use strict";sd="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.",id='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"`.',ad="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.",ld="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.",cd='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.',dd="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.",pd="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.",ud='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.',md="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.",_s="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).",Ts="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.",Cs="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.",Is="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.",Ps="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.",Rs="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).",As="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 Gr,readFileSync as js,writeFileSync as hd,mkdirSync as gd}from"fs";import{join as zr,dirname as Wr}from"path";import{homedir as fd}from"os";import{fileURLToPath as yd}from"url";function et(){if(Zn)return Zn;try{let t=yd(import.meta.url),e=Wr(t);for(let r=0;r<6;r++){let n=zr(e,"package.json");if(Gr(n)){let s=JSON.parse(js(n,"utf-8"));if(s.name==="@mistflow-ai/mcp"&&typeof s.version=="string")return Zn=s.version,s.version}let o=Wr(e);if(o===e)break;e=o}}catch{}return Zn="0.0.0","0.0.0"}function er(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 Ns(t,e){let r=er(t),n=er(e);if(!r||!n)return 0;for(let o=0;o<3;o++){if(r[o]<n[o])return-1;if(r[o]>n[o])return 1}return 0}function Ds(t,e,r){if(r&&Ns(t,r)<0)return"unsupported";if(!e||Ns(t,e)>=0)return"none";let o=er(t),s=er(e);return!o||!s?"none":o[0]<s[0]?"major":o[1]<s[1]?"minor":"patch"}function kn(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||(Ze={latest:e,minSupported:r,changelogUrl:n})}function Ls(){let t=process.env.MISTFLOW_STATE_DIR||zr(fd(),".mistflow");return zr(t,"upgrade-state.json")}function bd(){try{let t=Ls();return Gr(t)?JSON.parse(js(t,"utf-8")):{}}catch{return{}}}function wd(t){try{let e=Ls(),r=Wr(e);Gr(r)||gd(r,{recursive:!0}),hd(e,JSON.stringify(t,null,2)+`
|
|
4
|
+
`,{mode:384})}catch{}}function vd(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function $s(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!Ze)return null;let t=et();if(t==="0.0.0")return null;let e=Ds(t,Ze.latest,Ze.minSupported);if(e==="none")return null;if(e==="unsupported")return Ms(e,t,Ze);if(Os)return null;let r=bd(),n=Date.now(),o=vd(e);return r.dismissedForVersion===Ze.latest&&e!=="major"||r.lastLatestSeen===Ze.latest&&r.lastShownMs&&n-r.lastShownMs<o?null:(Os=!0,wd({...r,lastShownMs:n,lastLatestSeen:Ze.latest}),Ms(e,t,Ze))}function Ms(t,e,r){let n="npx -y mistflow-ai install",o=r.changelogUrl?`
|
|
5
5
|
What's new: ${r.changelogUrl}`:"";return t==="unsupported"?`
|
|
6
6
|
|
|
7
7
|
---
|
|
@@ -21,7 +21,7 @@ This is a major update. Run \`${n}\` and restart your editor.${o}
|
|
|
21
21
|
--- Mistflow update available: ${e} -> ${r.latest} ---
|
|
22
22
|
Run \`${n}\` to upgrade, then restart your editor.${o}`:`
|
|
23
23
|
|
|
24
|
-
(Mistflow ${r.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function
|
|
24
|
+
(Mistflow ${r.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function Jr(){let t=et(),e=Ze??{latest:"",minSupported:"",changelogUrl:""},r=Ds(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:Ze!==null}}var Zn,Ze,Os,xn=x(()=>{"use strict";Zn=null;Ze=null;Os=!1});var Tn={};vn(Tn,{closeBrowser:()=>Vr,getIsolatedContext:()=>xd,getPage:()=>Kr,getSnapshot:()=>Sn,takeScreenshot:()=>_n});async function Us(){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 kd(){let t=await Us();return(!tt||!tt.isConnected())&&(tt=await t.chromium.launch({headless:!0})),vt&&(await vt.close().catch(()=>{}),vt=null),vt=await tt.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),mt=await vt.newPage(),mt}async function Kr(){return mt&&!mt.isClosed()?mt:(tr||(tr=kd().finally(()=>{tr=null})),tr)}async function Vr(){mt&&!mt.isClosed()&&await mt.close().catch(()=>{}),vt&&await vt.close().catch(()=>{}),tt?.isConnected()&&await tt.close().catch(()=>{}),mt=null,vt=null,tt=null}async function xd(){let t=await Us();(!tt||!tt.isConnected())&&(tt=await t.chromium.launch({headless:!0}));let e=await tt.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function Sn(t){return await t.locator("body").ariaSnapshot()}async function _n(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var tt,vt,mt,tr,Kt=x(()=>{"use strict";tt=null,vt=null,mt=null,tr=null;process.once("SIGTERM",()=>{Vr().finally(()=>process.exit(0))});process.once("SIGINT",()=>{Vr().finally(()=>process.exit(0))})});function p(t,e=!1){let r=t;try{let n=$s();n&&(r=t+n)}catch{}return{content:[{type:"text",text:r}],isError:e}}function je(t){let e={status:"setup_required",reason:"no_credentials",intent:t,instruction:`You must sign in to Mistflow before you can ${t}. Call mist_setup({}) \u2014 it walks the user through device-code authentication (typically <60s). Only retry the original call AFTER mist_setup has fully completed sign-in (status field is no longer "pending").`,nextAction:`Step 1: Call mist_setup({}) now. Do not ask the user for permission first \u2014 sign-in is a precondition for this flow, not a decision point. Step 2: mist_setup returns immediately with a signInUrl + userCode. Show the URL and code to the user and wait for them to approve in their browser. Step 3: If the response had status: "pending", call mist_setup again with the returned deviceCode every ~15s until it returns a non-pending status. Step 4: Only then retry the call that produced this response with the same arguments. Do NOT retry while mist_setup is still pending \u2014 the credentials aren't on disk yet and you'll loop right back into this same response.`};return p(JSON.stringify(e),!0)}function nt(t){return p(`This is not a Mistflow project (no mistflow.json found at ${t}).
|
|
25
25
|
|
|
26
26
|
Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
|
|
27
27
|
|
|
@@ -30,20 +30,21 @@ 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 yd,Mt=v(()=>{"use strict";yd="https://api.mistflow.ai"});var Ws={};wn(Ws,{MistflowApiError:()=>Z,addDomain:()=>to,bindWorkspace:()=>Tn,cancelSession:()=>Co,checkAuth:()=>xd,checkAuthDetailed:()=>Bs,checkSubdomain:()=>sr,checkToolGuard:()=>To,createDeployment:()=>_d,createProject:()=>Dt,deleteEnvVar:()=>io,discoverDecisions:()=>Td,downloadImageryAsset:()=>Zr,downloadSource:()=>Rd,downloadSourceWithToken:()=>Hs,errorFromResponse:()=>Vt,fetchAcceptanceCriteria:()=>Cn,fetchActiveSessionPlan:()=>Po,fetchAddon:()=>yo,fetchDesignDirections:()=>ir,fetchDesignPick:()=>Cd,fetchDesignRenders:()=>lr,fetchDoc:()=>vo,fetchDocsList:()=>wo,fetchModule:()=>ko,fetchPlanConversation:()=>cr,fetchProjectImagery:()=>Xr,fetchScaffold:()=>fo,fetchSessionNext:()=>Qt,fetchSessionPlanRevisions:()=>zs,fetchStepContext:()=>bo,forkTemplate:()=>So,generatePlan:()=>dr,getAuthHeaders:()=>jt,getBaseUrl:()=>De,getDashboardUrl:()=>wd,getDbCredentials:()=>Pd,getDeployLogs:()=>ao,getDeploymentStatus:()=>wt,getProject:()=>Sd,getProjectErrors:()=>lo,getSeedInfo:()=>mr,getSession:()=>hr,getSiteUrl:()=>bd,getTemplate:()=>xo,hasCredentialsOnDisk:()=>Ie,hasLocalCredentials:()=>qs,listCronJobLogs:()=>mo,listCronJobs:()=>co,listDeployments:()=>Yt,listDomains:()=>vt,listEnvVars:()=>oo,listSessionsForMachine:()=>Pn,markLocalSetupDone:()=>Ad,modifyPlan:()=>pr,pingBackend:()=>Qr,promotePreview:()=>ho,redeployProject:()=>Id,removeDomain:()=>no,request:()=>$,rollbackDeployment:()=>go,setCronJobEnabled:()=>po,shareProject:()=>_o,startSession:()=>Ed,submitAcceptanceResults:()=>Io,submitDesignPick:()=>ar,submitSessionAnswers:()=>Nd,triggerCronJobNow:()=>uo,uploadAndDeploy:()=>eo,uploadQAResults:()=>ro,upsertEnvVar:()=>so,verifyDomain:()=>ur});function De(){return rr()}function bd(){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 wd(){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 jt(){let t=Ot();if(!t.ok)throw new Z("auth_missing","No Mistflow credentials found.",401);return vd(t.creds)}function vd(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":Ve()}}function Jt(t){try{vn(t.headers)}catch{}}async function Qr(){try{let t=await fetch(`${De()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Jt(t)}catch{}}async function Fs(t,e,r,n){for(let o=0;o<2;o++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(s){let i=s instanceof Error&&s.name==="TimeoutError",a=s instanceof TypeError;if(n&&o===0&&(i||a)){console.error(`[api] Retrying ${t} after ${i?"timeout":"network error"}`);continue}throw s}throw new Error("fetchWithRetry: exhausted retries")}async function Vt(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 Z(r,n,t.status,e?.details);let o=t.status;return o===401?new Z("auth_invalid",n,o):o===403?new Z("permission_denied",n,o):o===404?new Z("not_found",n,o):o===409?new Z("conflict",n,o):o===422?new Z("validation_error",n,o):o===429?new Z("rate_limited",n,o):o>=500?new Z("server_error",t.statusText||"Internal server error",o):new Z("client_error",n,o)}async function $(t,e={}){let r=jt(),{timeoutMs:n,idempotent:o,...s}=e,i=n??3e4,a=(s.method??"GET").toUpperCase(),l=o??(a==="GET"||a==="HEAD"),c;try{c=await Fs(`${De()}${t}`,{...s,headers:{...r,...s.headers}},i,l)}catch(m){throw m instanceof Error&&m.name==="TimeoutError"?new Z("network_error","Request timed out. Try again in a moment."):new Z("network_error","Cannot reach Mistflow servers. Check your network.")}if(Jt(c),!c.ok)throw await Vt(c);return c.json()}function qs(){return Ot().ok}async function xd(){return(await Bs()).ok}async function Bs(){if(or!==null&&Date.now()<Us)return or?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!qs())return{ok:!1,reason:"no_credentials"};try{return await $("/api/org"),or=!0,Us=Date.now()+kd,{ok:!0}}catch(t){if(or=null,!(t instanceof Z))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 Sd(t){return $(`/api/projects/${encodeURIComponent(t)}`)}async function sr(t){return $(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function Dt(t,e={}){return $("/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,scaffold_features:e.scaffoldFeatures})})}async function Xr(t){return $(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function Zr(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 _d(t,e){return $("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function eo(t,e,r="production",n,o,s,i){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=Ot();if(!c.ok)throw new Z("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),o&&h.append("schema_pushed","true"),s){let{existsSync:S}=await import("fs");if(S(s)){let w=a(s),E=new Blob([w],{type:"application/gzip"});h.append("source",E,"source.tar.gz")}}i&&h.append("git_commit_sha",i);let F;try{F=await fetch(`${De()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":Ve()},body:h,signal:AbortSignal.timeout(3e5)})}catch{throw new Z("network_error","Cannot reach Mistflow servers. Check your network.")}if(Jt(F),!F.ok)throw await Vt(F);let T=await F.json();return{...T,id:T.deployment_id}}async function wt(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",o=Math.min(6e4,(r+5)*1e3);return $(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:o}:void 0)}async function ir(t){return $(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Cd(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",o=Math.min(6e4,(r+5)*1e3);return $(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:o})}async function ar(t,e){return $(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),timeoutMs:6e4})}async function lr(t){try{return await $(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function cr(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",o=Math.min(6e4,(r+5)*1e3);return $(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:o})}async function dr(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 o=e.designDirection,s=256,i=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<=s?a:void 0,m=(()=>{if(l&&l.length>0)return l.length<=i?l:l.slice(0,i)+" (truncated)";if(!c){let h=JSON.stringify(o);return h.length<=i?h:h.slice(0,i)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${s}; falling back to custom`);let p=c?{direction_id:c}:{custom:m};e.conversationId&&(p.conversation_id=e.conversationId);let u=await ar(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 $("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function pr(t,e,r={}){return $("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function Td(t){return $("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function to(t,e){return $(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function vt(t){return $(`/api/projects/${encodeURIComponent(t)}/domains`)}async function ur(t,e){return $(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function no(t,e){return $(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Pd(t){return $(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function mr(t){try{return await $(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof Z&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function ro(t,e){try{return await $(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(r){return console.error("[api] Failed to upload QA results:",r instanceof Error?r.message:r),null}}async function oo(t){return $(`/api/projects/${encodeURIComponent(t)}/env`)}async function so(t,e,r,n){return $(`/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 io(t,e){return $(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function ao(t){return $(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function lo(t,e="7d"){return $(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Yt(t){return $(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function co(t){return $(`/api/projects/${encodeURIComponent(t)}/cron-jobs`)}async function po(t,e,r){return $(`/api/projects/${encodeURIComponent(t)}/cron-jobs/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({enabled:r}),headers:{"Content-Type":"application/json"}})}async function uo(t,e){return $(`/api/projects/${encodeURIComponent(t)}/cron-jobs/${encodeURIComponent(e)}/trigger`,{method:"POST"})}async function mo(t,e,r=50){return $(`/api/projects/${encodeURIComponent(t)}/cron-jobs/${encodeURIComponent(e)}/logs?limit=${r}`)}async function Id(t){return $(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function ho(t,e){let r=new URLSearchParams({preview_deployment_id:e});return $(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function go(t){return $(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function Rd(t,e){let r=Ot();if(!r.ok)throw new Z("auth_missing","Not authenticated.",401);let n=r.creds,o=await fetch(`${De()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":Ve()},signal:AbortSignal.timeout(12e4)});if(Jt(o),!o.ok)throw await Vt(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(e,i)}async function Lt(t,e){let{timeoutMs:r,idempotent:n,...o}=e??{},s=r??3e4,i=(o.method??"GET").toUpperCase(),a=n??(i==="GET"||i==="HEAD"),l;try{l=await Fs(`${De()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":Ve()},...o},s,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new Z("network_error","Request timed out. Try again in a moment."):new Z("network_error","Cannot reach Mistflow servers. Check your network.")}if(Jt(l),!l.ok)throw await Vt(l);return l.json()}async function fo(t="nextjs"){return Lt(`/api/scaffold/${encodeURIComponent(t)}`)}async function yo(t){return Lt(`/api/scaffold/addon/${encodeURIComponent(t)}`)}async function bo(t,e){return Lt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function wo(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return Lt(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function vo(t,e){return Lt(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function ko(t,e,r,n){return Lt(`/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 xo(t){return Lt(`/api/templates/${encodeURIComponent(t)}`)}async function So(t){return $(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Hs(t,e,r){let n;try{n=await fetch(`${De()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":Ve()},signal:AbortSignal.timeout(12e4)})}catch{throw new Z("network_error","Cannot reach Mistflow servers. Check your network.")}if(Jt(n),!n.ok)throw n.status===401?new Z("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await Vt(n);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await n.arrayBuffer());o(r,s)}async function Ad(t){await $(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function _o(t,e){return $(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function Ed(t){return $("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function hr(t){return $(`/api/sessions/${t}`)}async function Co(t,e){return $(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Qt(t){return $(`/api/sessions/${t}/next`)}async function Nd(t,e){return $(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function To(t,e){return $(`/api/sessions/${t}/can/${e}`)}async function Cn(t){return $(`/api/sessions/${t}/acceptance`)}async function zs(t){return $(`/api/sessions/${t}/revisions`)}async function Po(t){let e=await zs(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 Tn(t,e){return $(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function Pn(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return $(`/api/sessions/me/workspaces?${n}`)}async function Io(t,e,r){return $(`/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 Z,or,Us,kd,Re=v(()=>{"use strict";Mt();kn();Z=class extends Error{constructor(r,n,o,s){super(n);this.code=r;this.statusCode=o;this.details=s;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"}};or=null,Us=0,kd=300*1e3});import{z as Ro}from"zod";import{platform as Od}from"os";import{execFile as Gs}from"child_process";function jd(t){return"error"in t}function Js(t){return new Promise(e=>setTimeout(e,t))}function Dd(t){return new Promise(e=>{let r=Od();r==="win32"?Gs("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):Gs(r==="darwin"?"open":"xdg-open",[t],o=>{o&&console.error("Could not open browser:",o.message),e(!o)}),setTimeout(()=>e(!1),5e3)})}async function Ks(t,e,r,n){let o=r,s=n.sleep??Js;for(let i=0;i<e;i++){await s(o);let a;try{let c=await n.fetch(`${De()}/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(jd(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 Vr({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 $d(t,e=Ld){let r=t;if(r?.apiKey)try{let i=await e.fetch(`${De()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!i.ok)return d("Invalid API key. Check the key and try again.",!0);let a=await i.json();return Vr({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 i=await Ks(r.deviceCode,6,5e3,e);return i||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 i=await e.fetch(`${De()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!i.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await i.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let o=`${n.verification_uri}?code=${n.user_code}`;console.error(`
|
|
33
|
+
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Fs(t,e){try{let{getPage:r,takeScreenshot:n}=await Promise.resolve().then(()=>(Kt(),Tn)),o=await r();await o.setViewportSize(Sd);try{await o.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{});let s=await n(o,!1);return{content:[{type:"text",text:e},{type:"image",data:s.toString("base64"),mimeType:"image/png"}]}}finally{await o.setViewportSize(_d).catch(()=>{})}}catch{return p(e)}}var Sd,_d,ye=x(()=>{"use strict";xn();Sd={width:1024,height:576},_d={width:1280,height:720}});import{readFileSync as Yr,existsSync as nr,writeFileSync as qs,mkdirSync as Td,renameSync as Bs,unlinkSync as Hs}from"fs";import{join as Cn,dirname as zs}from"path";import{homedir as Cd}from"os";import{randomBytes as Ws}from"crypto";function Gs(){return Cn(Cd(),".mistflow","credentials.json")}function rr(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function Js(){let t=Gs();if(!nr(t))return null;try{let e=JSON.parse(Yr(t,"utf-8"));return typeof e.apiKey=="string"?{[Id]:e}:e}catch{return null}}function Mt(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=Js();if(!e)return{ok:!1,reason:"missing"};let r=rr(),n=e[r];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function Qr(t){let e=Gs(),r=zs(e);nr(r)||Td(r,{recursive:!0});let n=Js()??{},o=rr();n[o]=t;let s=Cn(r,`.credentials.tmp.${Ws(8).toString("hex")}`);try{qs(s,JSON.stringify(n,null,2)+`
|
|
34
|
+
`,{mode:384}),Bs(s,e)}catch(i){try{Hs(s)}catch{}throw i}}function Ks(){let t=Mt();return t.ok?t.creds:null}function Ie(){return Mt().ok}function ht(t){let e=Cn(t,"mistflow.json");if(!nr(e))return null;try{return JSON.parse(Yr(e,"utf-8"))}catch{return null}}function or(t,e){let r=Cn(t,"mistflow.json");if(nr(r))try{let o={...JSON.parse(Yr(r,"utf-8")),...e},s=Cn(zs(r),`.mistflow.json.tmp.${Ws(8).toString("hex")}`);try{qs(s,JSON.stringify(o,null,2)+`
|
|
35
|
+
`,"utf-8"),Bs(s,r)}catch(i){try{Hs(s)}catch{}throw i}}catch{}}var Id,jt=x(()=>{"use strict";Id="https://api.mistflow.ai"});var ti={};vn(ti,{MistflowApiError:()=>ee,addDomain:()=>ro,bindWorkspace:()=>Pn,cancelSession:()=>Io,checkAuth:()=>Nd,checkAuthDetailed:()=>Xs,checkSubdomain:()=>ir,checkToolGuard:()=>Po,createDeployment:()=>Od,createProject:()=>Lt,deleteEnvVar:()=>lo,discoverDecisions:()=>jd,downloadImageryAsset:()=>to,downloadSource:()=>$d,downloadSourceWithToken:()=>Zs,errorFromResponse:()=>Yt,fetchAcceptanceCriteria:()=>In,fetchActiveSessionPlan:()=>Ro,fetchAddon:()=>wo,fetchDesignDirections:()=>ar,fetchDesignPick:()=>Md,fetchDesignRenders:()=>cr,fetchDoc:()=>xo,fetchDocsList:()=>ko,fetchModule:()=>So,fetchPlanConversation:()=>dr,fetchProjectImagery:()=>eo,fetchScaffold:()=>bo,fetchSessionNext:()=>Xt,fetchSessionPlanRevisions:()=>ei,fetchStepContext:()=>vo,forkTemplate:()=>To,generatePlan:()=>pr,getAuthHeaders:()=>Dt,getBaseUrl:()=>De,getDashboardUrl:()=>Rd,getDbCredentials:()=>Dd,getDeployLogs:()=>co,getDeploymentStatus:()=>kt,getProject:()=>Zr,getProjectErrors:()=>po,getSeedInfo:()=>hr,getSession:()=>gr,getSiteUrl:()=>Pd,getTemplate:()=>_o,hasCredentialsOnDisk:()=>Ie,hasLocalCredentials:()=>Qs,listCronJobLogs:()=>go,listCronJobs:()=>uo,listDeployments:()=>Qt,listDomains:()=>xt,listEnvVars:()=>io,listSessionsForMachine:()=>Rn,markLocalSetupDone:()=>Ud,modifyPlan:()=>ur,pingBackend:()=>Xr,promotePreview:()=>fo,redeployProject:()=>Ld,removeDomain:()=>oo,request:()=>D,rollbackDeployment:()=>yo,setCronJobEnabled:()=>mo,shareProject:()=>Co,startSession:()=>Fd,submitAcceptanceResults:()=>Ao,submitDesignPick:()=>lr,submitSessionAnswers:()=>qd,triggerCronJobNow:()=>ho,uploadAndDeploy:()=>no,uploadQAResults:()=>so,upsertEnvVar:()=>ao,verifyDomain:()=>mr});function De(){return rr()}function Pd(){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 Rd(){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 Dt(){let t=Mt();if(!t.ok)throw new ee("auth_missing","No Mistflow credentials found.",401);return Ad(t.creds)}function Ad(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":et()}}function Vt(t){try{kn(t.headers)}catch{}}async function Xr(){try{let t=await fetch(`${De()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Vt(t)}catch{}}async function Ys(t,e,r,n){for(let o=0;o<2;o++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(s){let i=s instanceof Error&&s.name==="TimeoutError",a=s instanceof TypeError;if(n&&o===0&&(i||a)){console.error(`[api] Retrying ${t} after ${i?"timeout":"network error"}`);continue}throw s}throw new Error("fetchWithRetry: exhausted retries")}async function Yt(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 ee(r,n,t.status,e?.details);let o=t.status;return o===401?new ee("auth_invalid",n,o):o===403?new ee("permission_denied",n,o):o===404?new ee("not_found",n,o):o===409?new ee("conflict",n,o):o===422?new ee("validation_error",n,o):o===429?new ee("rate_limited",n,o):o>=500?new ee("server_error",t.statusText||"Internal server error",o):new ee("client_error",n,o)}async function D(t,e={}){let r=Dt(),{timeoutMs:n,idempotent:o,...s}=e,i=n??3e4,a=(s.method??"GET").toUpperCase(),l=o??(a==="GET"||a==="HEAD"),c;try{c=await Ys(`${De()}${t}`,{...s,headers:{...r,...s.headers}},i,l)}catch(u){throw u instanceof Error&&u.name==="TimeoutError"?new ee("network_error","Request timed out. Try again in a moment."):new ee("network_error","Cannot reach Mistflow servers. Check your network.")}if(Vt(c),!c.ok)throw await Yt(c);return c.json()}function Qs(){return Mt().ok}async function Nd(){return(await Xs()).ok}async function Xs(){if(sr!==null&&Date.now()<Vs)return sr?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Qs())return{ok:!1,reason:"no_credentials"};try{return await D("/api/org"),sr=!0,Vs=Date.now()+Ed,{ok:!0}}catch(t){if(sr=null,!(t instanceof ee))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 Zr(t){return D(`/api/projects/${encodeURIComponent(t)}`)}async function ir(t){return D(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function Lt(t,e={}){return D("/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,scaffold_features:e.scaffoldFeatures})})}async function eo(t){return D(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function to(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 Od(t,e){return D("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function no(t,e,r="production",n,o,s,i){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=Mt();if(!c.ok)throw new ee("auth_missing","No Mistflow credentials found.",401);let u=c.creds,d=a(e),m=new Blob([d],{type:"application/gzip"}),h=new FormData;if(h.append("project_id",t),h.append("build",m,l(e)),r!=="production"&&h.append("environment",r),n&&h.append("admin_email",n),o&&h.append("schema_pushed","true"),s){let{existsSync:y}=await import("fs");if(y(s)){let v=a(s),N=new Blob([v],{type:"application/gzip"});h.append("source",N,"source.tar.gz")}}i&&h.append("git_commit_sha",i);let _;try{_=await fetch(`${De()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${u.apiKey}`,"X-Mistflow-MCP-Version":et()},body:h,signal:AbortSignal.timeout(3e5)})}catch{throw new ee("network_error","Cannot reach Mistflow servers. Check your network.")}if(Vt(_),!_.ok)throw await Yt(_);let P=await _.json();return{...P,id:P.deployment_id}}async function kt(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",o=Math.min(6e4,(r+5)*1e3);return D(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:o}:void 0)}async function ar(t){return D(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Md(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",o=Math.min(6e4,(r+5)*1e3);return D(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:o})}async function lr(t,e){return D(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),timeoutMs:6e4})}async function cr(t){try{return await D(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function dr(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",o=Math.min(6e4,(r+5)*1e3);return D(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:o})}async function pr(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 o=e.designDirection,s=256,i=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<=s?a:void 0,u=(()=>{if(l&&l.length>0)return l.length<=i?l:l.slice(0,i)+" (truncated)";if(!c){let h=JSON.stringify(o);return h.length<=i?h:h.slice(0,i)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${s}; falling back to custom`);let d=c?{direction_id:c}:{custom:u};e.conversationId&&(d.conversation_id=e.conversationId);let m=await lr(e.designConversationId,d);return{status:"ready",plan:m.plan??{},methodology:m.methodology??"",...m.designMd?{designMd:m.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return D("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function ur(t,e,r={}){return D("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function jd(t){return D("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function ro(t,e){return D(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function xt(t){return D(`/api/projects/${encodeURIComponent(t)}/domains`)}async function mr(t,e){return D(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function oo(t,e){return D(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Dd(t){return D(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function hr(t){try{return await D(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof ee&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function so(t,e){try{return await D(`/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 io(t){return D(`/api/projects/${encodeURIComponent(t)}/env`)}async function ao(t,e,r,n){return D(`/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 lo(t,e){return D(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function co(t){return D(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function po(t,e="7d"){return D(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Qt(t){return D(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function uo(t){return D(`/api/projects/${encodeURIComponent(t)}/cron-jobs`)}async function mo(t,e,r){return D(`/api/projects/${encodeURIComponent(t)}/cron-jobs/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({enabled:r}),headers:{"Content-Type":"application/json"}})}async function ho(t,e){return D(`/api/projects/${encodeURIComponent(t)}/cron-jobs/${encodeURIComponent(e)}/trigger`,{method:"POST"})}async function go(t,e,r=50){return D(`/api/projects/${encodeURIComponent(t)}/cron-jobs/${encodeURIComponent(e)}/logs?limit=${r}`)}async function Ld(t){return D(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function fo(t,e){let r=new URLSearchParams({preview_deployment_id:e});return D(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function yo(t){return D(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function $d(t,e){let r=Mt();if(!r.ok)throw new ee("auth_missing","Not authenticated.",401);let n=r.creds,o=await fetch(`${De()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":et()},signal:AbortSignal.timeout(12e4)});if(Vt(o),!o.ok)throw await Yt(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(e,i)}async function $t(t,e){let{timeoutMs:r,idempotent:n,...o}=e??{},s=r??3e4,i=(o.method??"GET").toUpperCase(),a=n??(i==="GET"||i==="HEAD"),l;try{l=await Ys(`${De()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":et()},...o},s,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new ee("network_error","Request timed out. Try again in a moment."):new ee("network_error","Cannot reach Mistflow servers. Check your network.")}if(Vt(l),!l.ok)throw await Yt(l);return l.json()}async function bo(t="nextjs"){return $t(`/api/scaffold/${encodeURIComponent(t)}`)}async function wo(t){return $t(`/api/scaffold/addon/${encodeURIComponent(t)}`)}async function vo(t,e){return $t(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function ko(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return $t(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function xo(t,e){return $t(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function So(t,e,r,n){return $t(`/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 _o(t){return $t(`/api/templates/${encodeURIComponent(t)}`)}async function To(t){return D(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Zs(t,e,r){let n;try{n=await fetch(`${De()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":et()},signal:AbortSignal.timeout(12e4)})}catch{throw new ee("network_error","Cannot reach Mistflow servers. Check your network.")}if(Vt(n),!n.ok)throw n.status===401?new ee("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await Yt(n);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await n.arrayBuffer());o(r,s)}async function Ud(t){await D(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Co(t,e){return D(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function Fd(t){return D("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function gr(t){return D(`/api/sessions/${t}`)}async function Io(t,e){return D(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Xt(t){return D(`/api/sessions/${t}/next`)}async function qd(t,e){return D(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Po(t,e){return D(`/api/sessions/${t}/can/${e}`)}async function In(t){return D(`/api/sessions/${t}/acceptance`)}async function ei(t){return D(`/api/sessions/${t}/revisions`)}async function Ro(t){let e=await ei(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 Pn(t,e){return D(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function Rn(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return D(`/api/sessions/me/workspaces?${n}`)}async function Ao(t,e,r){return D(`/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 ee,sr,Vs,Ed,Se=x(()=>{"use strict";jt();xn();ee=class extends Error{constructor(r,n,o,s){super(n);this.code=r;this.statusCode=o;this.details=s;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"}};sr=null,Vs=0,Ed=300*1e3});import{z as Eo}from"zod";import{platform as Bd}from"os";import{execFile as ni}from"child_process";function zd(t){return"error"in t}function oi(t){return new Promise(e=>setTimeout(e,t))}function Wd(t){return new Promise(e=>{let r=Bd();r==="win32"?ni("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):ni(r==="darwin"?"open":"xdg-open",[t],o=>{o&&console.error("Could not open browser:",o.message),e(!o)}),setTimeout(()=>e(!1),5e3)})}async function ri(t,e,r,n){let o=r,s=n.sleep??oi;for(let i=0;i<e;i++){await s(o);let a;try{let c=await n.fetch(`${De()}/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(zd(a))switch(a.error){case"authorization_pending":continue;case"slow_down":o+=5e3;continue;case"expired_token":return p("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return p("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return p("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=a.email||a.org_name||a.org_slug;return Qr({apiKey:a.api_key,apiKeyId:a.api_key_id,apiKeyName:a.api_key_name,orgId:a.org_id,orgSlug:a.org_slug,email:a.email}),p(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function Jd(t,e=Gd){let r=t;if(r?.apiKey)try{let i=await e.fetch(`${De()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!i.ok)return p("Invalid API key. Check the key and try again.",!0);let a=await i.json();return Qr({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),p(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let i=await ri(r.deviceCode,6,5e3,e);return i||p(JSON.stringify({status:"pending",deviceCode:r.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let i=await e.fetch(`${De()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!i.ok)return p("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await i.json()}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}let o=`${n.verification_uri}?code=${n.user_code}`;console.error(`
|
|
36
36
|
Sign in at: ${o}
|
|
37
37
|
Your code: ${n.user_code}
|
|
38
|
-
`);try{await e.openBrowser(o)}catch{}let s=await
|
|
39
|
-
`)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s>0){let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();a&&a!=='""'&&a!=="''"&&e.add(i)}}return e}var
|
|
40
|
-
`)}function
|
|
41
|
-
`),
|
|
42
|
-
`),
|
|
38
|
+
`);try{await e.openBrowser(o)}catch{}let s=await ri(n.device_code,6,5e3,e);return s||p(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 Hd,Gd,si,ii=x(()=>{"use strict";ut();ye();Se();jt();Hd=Eo.object({apiKey:Eo.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:Eo.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.")});Gd={fetch:globalThis.fetch,openBrowser:Wd,sleep:oi};si={name:"mist_setup",description:_s,inputSchema:Hd,handler:t=>Jd(t)}});import{existsSync as Kd,readFileSync as Vd}from"fs";function ai(t){let e=new Set;if(!Kd(t))return e;let r=Vd(t,"utf-8");for(let n of r.split(`
|
|
39
|
+
`)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s>0){let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();a&&a!=='""'&&a!=="''"&&e.add(i)}}return e}var li=x(()=>{"use strict"});var Nn={};vn(Nn,{emptyState:()=>En,fetchRemoteState:()=>tp,fuzzyMatch:()=>rp,getLocalStatePath:()=>No,readLocalState:()=>ep,syncRemoteState:()=>np,writeLocalState:()=>An});import{existsSync as ci,readFileSync as Yd,writeFileSync as Qd,mkdirSync as Xd,renameSync as Zd}from"fs";import{join as di}from"path";function No(t){return di(t,".mistflow","state.json")}function ep(t){let e=No(t);if(!ci(e))return null;try{return JSON.parse(Yd(e,"utf-8"))}catch{return null}}function An(t,e){let r=di(t,".mistflow");ci(r)||Xd(r,{recursive:!0});let n=No(t),o=`${n}.${process.pid}.tmp`;Qd(o,JSON.stringify(e,null,2)+`
|
|
40
|
+
`),Zd(o,n)}function En(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function tp(t){let e;try{e=Dt()}catch{return null}try{let r=await fetch(`${De()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":et()}});try{kn(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function np(t,e){let r;try{r=Dt()}catch{return!1}try{let n=await fetch(`${De()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":et()},body:JSON.stringify(e)});try{kn(n.headers)}catch{}return n.ok}catch{return!1}}function rp(t,e){let r=t.toLowerCase(),n=e.toLowerCase();return n.includes(r)||r.includes(n)?!0:r.split(/\s+/).some(s=>s.length>=3&&n.includes(s))}var Ut=x(()=>{"use strict";Se();xn()});var Oo={};vn(Oo,{ensureBackendRegistered:()=>dp,ensureShadcnComponents:()=>pp});import{existsSync as ui,readFileSync as op,writeFileSync as sp}from"fs";import{join as fr}from"path";import{spawn as ip}from"child_process";function ap(t,e,r,n,o){return new Promise(s=>{let i=ip(t,e,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:n,...o?{env:{...process.env,...o}}:{}}),a="",l="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{l+=c.toString()}),i.on("close",c=>s({success:c===0,stdout:a,stderr:l})),i.on("error",c=>s({success:!1,stdout:a,stderr:l+c.message}))})}function lp(t){let e=fr(t,"mistflow.json");if(!ui(e))return null;try{return JSON.parse(op(e,"utf-8"))}catch{return null}}function cp(t,e){sp(fr(t,"mistflow.json"),JSON.stringify(e,null,2))}async function pi(t,e){try{let r=e.features,n=e.steps,o={plan:e};Array.isArray(r)&&r.length>0&&(o.features=r.map(s=>s.name)),Array.isArray(n)&&n.length>0&&(o.provenance=n.map(s=>({feature:s.name??s.title??`Step ${s.number??"?"}`,user_intent:(s.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${De()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...Dt(),"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function dp(t,e={}){let r=lp(t);if(r){if(!Ie())return r.projectId;if(!r.projectId)try{let o=r.plan?.requestedSubdomain,s=await Lt(r.name,{dbProvider:r.dbProvider??"neon",requestedSubdomain:o});return r.projectId=s.id,cp(t,r),An(t,En(s.id,r.name)),r.plan&&await pi(s.id,r.plan),console.error(`[self-heal] registered project ${s.id.slice(0,8)} with backend`),s.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&r.plan&&r.projectId&&await pi(r.projectId,r.plan),r.projectId}}async function pp(t,e){let r=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],n=e&&e.length>0?e:r,o=fr(t,"components","ui"),s=[],i=[];for(let c of n)ui(fr(o,`${c}.tsx`))?s.push(c):i.push(c);if(i.length===0)return{installed:[],alreadyPresent:s};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await ap("npx",["--yes","shadcn@latest","add","-y","-o",...i],t,18e4,a);return l.success?{installed:i,alreadyPresent:s}:{installed:[],alreadyPresent:s,failed:`shadcn add failed for: ${i.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Mo=x(()=>{"use strict";Se();Ut()});import{z as St}from"zod";import{resolve as up,join as mi}from"path";import{existsSync as mp,readFileSync as hi,writeFileSync as gi}from"fs";var hp,fi,yi=x(()=>{"use strict";ye();li();Se();hp=St.object({action:St.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:St.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:St.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:St.object({key:St.string(),description:St.string().optional(),setupUrl:St.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),fi={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:hp,handler:async t=>{let e=t,r=up(e.projectPath??process.cwd()),n=mi(r,"mistflow.json");if(!mp(n))return nt(r);let o;try{o=JSON.parse(hi(n,"utf-8"))}catch{return p("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!o.projectId)try{let{ensureBackendRegistered:y}=await Promise.resolve().then(()=>(Mo(),Oo));await y(r)&&(o=JSON.parse(hi(n,"utf-8")))}catch{}let a=o.plan,l=a?.steps?.filter(y=>y.status==="completed").length??0,c=a?.steps?.length??0,u=ai(mi(r,".env.local")),d=o.env?.required?Object.entries(o.env.required).map(([y,v])=>({name:y,description:v?.description,configured:u.has(y)})):[];if(o.projectId){try{let y=await Zr(o.projectId);!o.deploy?.url&&y.deployUrl&&(o.deploy={...o.deploy??{},url:y.deployUrl,lastDeployedAt:new Date().toISOString()},gi(n,JSON.stringify(o,null,2)+`
|
|
41
|
+
`))}catch{}Promise.resolve().then(()=>(Ut(),Nn)).then(({fetchRemoteState:y})=>y(o.projectId)).catch(()=>{})}let m=[`Project: ${o.name}`];if(a){m.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let y of a.steps){let v=y.status==="completed"?"\u2713":y.status==="in_progress"?"\u2192":" ";m.push(` [${v}] ${y.number}. ${y.name}`)}}let h=d.filter(y=>!y.configured);h.length>0&&m.push(`Missing env vars: ${h.map(y=>y.name).join(", ")}`),o.deploy?.url?m.push(`Deployed: ${o.deploy.url} (${o.deploy.count??0} deploys)`):m.push("Not deployed yet");let _=[],P=a?.steps?.find(y=>y.status!=="completed");return P?_.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${P.number} (${P.name}).`):a&&l===c&&(o.deploy?.url||_.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),h.length>0&&_.push(`Missing env vars in .env.local: ${h.map(y=>y.name).join(", ")}`),p(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:d,deploy:o.deploy??null,contextMessage:m.join(`
|
|
42
|
+
`),nextSteps:_}))}let s=[];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 p(`Step ${e.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",s.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},s.push(`Added required env var: ${e.addEnvVar.key}`)),gi(n,JSON.stringify(o,null,2)+`
|
|
43
|
+
`),o.projectId&&Promise.resolve().then(()=>(Ut(),Nn)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(r);c&&await l(o.projectId,c)}).catch(()=>{});let i=[];if(e.completedStep!==void 0){let l=o.plan?.steps?.find(c=>c.status!=="completed");l?i.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):i.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&&(i.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&i.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),p(JSON.stringify({updated:!0,changes:s,message:s.length>0?`Project state saved. ${s.join(". ")}.`:"No changes made.",nextSteps:i.length>0?i:void 0}))}}});function gp(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function en(t){let e=Zt.find(n=>n.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Zt.find(n=>{let o=n.name.toLowerCase().replace(/[^a-z0-9]/g,"");return o===r||o.includes(r)||r.includes(o)})}function tn(t){return jo[t]}function Do(t){return t?Zt.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Zt}function bi(t){let e=t??Zt,r={};for(let o of e){r[o.category]||(r[o.category]=[]);let s=jo[o.id],i=s?` \u2014 ${s.description}`:"",a=s?.packages.length?` (${s.packages.join(", ")})`:"";r[o.category].push(`${o.id} \u2014 "${o.name}"${i}${a}`)}let n=[];for(let[o,s]of Object.entries(r))n.push(`**${o}**:
|
|
43
44
|
${s.map(i=>` - ${i}`).join(`
|
|
44
45
|
`)}`);return n.join(`
|
|
45
46
|
|
|
46
|
-
`)}function
|
|
47
|
+
`)}function wi(t){return(t?Do(t):Zt).map(r=>{let n=jo[r.id];return{id:r.id,slug:gp(r.name),name:r.name,category:r.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var jo,Zt,yr=x(()=>{"use strict";jo={"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"},"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:[],docsUrl:"https://neon.com/docs/extensions/pgvector",packages:[],difficulty:"medium"},"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"}},Zt=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
|
|
47
48
|
|
|
48
49
|
### File Structure
|
|
49
50
|
\`\`\`
|
|
@@ -134,306 +135,7 @@ export async function POST(req: NextRequest) {
|
|
|
134
135
|
3. **From address must match a verified domain** or use onboarding@resend.dev for testing.
|
|
135
136
|
4. **Webhooks need a public URL.** Use ngrok or similar for local webhook testing.
|
|
136
137
|
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
|
-
### File Structure
|
|
140
|
-
\`\`\`
|
|
141
|
-
lib/openai.ts \u2014 OpenAI client singleton
|
|
142
|
-
app/api/chat/route.ts \u2014 Streaming chat API route
|
|
143
|
-
components/chat.tsx \u2014 Chat UI component with streaming
|
|
144
|
-
\`\`\`
|
|
145
|
-
|
|
146
|
-
### Client Setup (lib/openai.ts)
|
|
147
|
-
\`\`\`typescript
|
|
148
|
-
import OpenAI from "openai";
|
|
149
|
-
|
|
150
|
-
export const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
|
|
151
|
-
\`\`\`
|
|
152
|
-
|
|
153
|
-
### Streaming Chat Route (app/api/chat/route.ts)
|
|
154
|
-
\`\`\`typescript
|
|
155
|
-
import { openai } from "@/lib/openai";
|
|
156
|
-
import { NextRequest } from "next/server";
|
|
157
|
-
|
|
158
|
-
export async function POST(req: NextRequest) {
|
|
159
|
-
const { messages, systemPrompt } = await req.json();
|
|
160
|
-
|
|
161
|
-
const stream = await openai.chat.completions.create({
|
|
162
|
-
model: "gpt-4o-mini",
|
|
163
|
-
messages: [
|
|
164
|
-
{ role: "system", content: systemPrompt || "You are a helpful assistant." },
|
|
165
|
-
...messages,
|
|
166
|
-
],
|
|
167
|
-
stream: true,
|
|
168
|
-
});
|
|
169
|
-
|
|
170
|
-
// Stream the response using ReadableStream
|
|
171
|
-
const encoder = new TextEncoder();
|
|
172
|
-
const readable = new ReadableStream({
|
|
173
|
-
async start(controller) {
|
|
174
|
-
for await (const chunk of stream) {
|
|
175
|
-
const text = chunk.choices[0]?.delta?.content || "";
|
|
176
|
-
if (text) controller.enqueue(encoder.encode(text));
|
|
177
|
-
}
|
|
178
|
-
controller.close();
|
|
179
|
-
},
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
return new Response(readable, {
|
|
183
|
-
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
184
|
-
});
|
|
185
|
-
}
|
|
186
|
-
\`\`\`
|
|
187
|
-
|
|
188
|
-
### Chat UI Component (components/chat.tsx)
|
|
189
|
-
\`\`\`tsx
|
|
190
|
-
"use client";
|
|
191
|
-
import { useState, useRef, useEffect } from "react";
|
|
192
|
-
|
|
193
|
-
interface Message { role: "user" | "assistant"; content: string }
|
|
194
|
-
|
|
195
|
-
export function Chat() {
|
|
196
|
-
const [messages, setMessages] = useState<Message[]>([]);
|
|
197
|
-
const [input, setInput] = useState("");
|
|
198
|
-
const [streaming, setStreaming] = useState(false);
|
|
199
|
-
const scrollRef = useRef<HTMLDivElement>(null);
|
|
200
|
-
|
|
201
|
-
useEffect(() => {
|
|
202
|
-
scrollRef.current?.scrollIntoView({ behavior: "smooth" });
|
|
203
|
-
}, [messages]);
|
|
204
|
-
|
|
205
|
-
async function handleSend() {
|
|
206
|
-
if (!input.trim() || streaming) return;
|
|
207
|
-
const userMsg: Message = { role: "user", content: input };
|
|
208
|
-
setMessages((prev) => [...prev, userMsg]);
|
|
209
|
-
setInput("");
|
|
210
|
-
setStreaming(true);
|
|
211
|
-
|
|
212
|
-
const res = await fetch("/api/chat", {
|
|
213
|
-
method: "POST",
|
|
214
|
-
headers: { "Content-Type": "application/json" },
|
|
215
|
-
body: JSON.stringify({ messages: [...messages, userMsg] }),
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
const reader = res.body?.getReader();
|
|
219
|
-
const decoder = new TextDecoder();
|
|
220
|
-
let assistantContent = "";
|
|
221
|
-
|
|
222
|
-
setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
|
|
223
|
-
|
|
224
|
-
while (reader) {
|
|
225
|
-
const { done, value } = await reader.read();
|
|
226
|
-
if (done) break;
|
|
227
|
-
assistantContent += decoder.decode(value);
|
|
228
|
-
setMessages((prev) => [
|
|
229
|
-
...prev.slice(0, -1),
|
|
230
|
-
{ role: "assistant", content: assistantContent },
|
|
231
|
-
]);
|
|
232
|
-
}
|
|
233
|
-
setStreaming(false);
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
return (
|
|
237
|
-
<div className="flex flex-col h-full">
|
|
238
|
-
<div className="flex-1 overflow-y-auto p-4 space-y-4">
|
|
239
|
-
{messages.map((m, i) => (
|
|
240
|
-
<div key={i} className={\`flex \${m.role === "user" ? "justify-end" : "justify-start"}\`}>
|
|
241
|
-
<div className={\`max-w-[80%] rounded-lg px-4 py-2 \${
|
|
242
|
-
m.role === "user" ? "bg-primary text-primary-foreground" : "bg-muted"
|
|
243
|
-
}\`}>
|
|
244
|
-
{m.content}
|
|
245
|
-
</div>
|
|
246
|
-
</div>
|
|
247
|
-
))}
|
|
248
|
-
<div ref={scrollRef} />
|
|
249
|
-
</div>
|
|
250
|
-
<div className="border-t p-4 flex gap-2">
|
|
251
|
-
<input value={input} onChange={(e) => setInput(e.target.value)}
|
|
252
|
-
onKeyDown={(e) => e.key === "Enter" && handleSend()}
|
|
253
|
-
placeholder="Type a message..." className="flex-1 rounded-md border px-3 py-2" />
|
|
254
|
-
<button onClick={handleSend} disabled={streaming}
|
|
255
|
-
className="rounded-md bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50">
|
|
256
|
-
Send
|
|
257
|
-
</button>
|
|
258
|
-
</div>
|
|
259
|
-
</div>
|
|
260
|
-
);
|
|
261
|
-
}
|
|
262
|
-
\`\`\`
|
|
263
|
-
|
|
264
|
-
### Common Pitfalls
|
|
265
|
-
1. **Never expose OPENAI_API_KEY to the client.** Always call OpenAI from server-side API routes.
|
|
266
|
-
2. **Use gpt-4o-mini for most features** unless the user specifically asks for gpt-4o. Cost difference is 10x.
|
|
267
|
-
3. **Set max_tokens to prevent runaway costs.** Default to 1000 for chat, 2000 for content generation.
|
|
268
|
-
4. **Handle rate limits gracefully.** Return a user-friendly error, not a raw 429 response.
|
|
269
|
-
5. **Streaming is the default UX pattern.** Non-streaming feels broken for chat interfaces.
|
|
270
|
-
6. **Long streaming responses are fine on Mistflow Cloud.** Network I/O (waiting for OpenAI to generate tokens) does NOT count toward CPU time. A 2-minute streaming chat response uses only milliseconds of CPU.
|
|
271
|
-
7. **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:"anthropic-ai",name:"Anthropic / Claude",category:"ai",prompt:`## Anthropic / Claude Integration
|
|
272
|
-
|
|
273
|
-
### File Structure
|
|
274
|
-
\`\`\`
|
|
275
|
-
lib/anthropic.ts \u2014 Anthropic client singleton
|
|
276
|
-
app/api/chat/route.ts \u2014 Streaming chat API route
|
|
277
|
-
components/chat.tsx \u2014 Chat UI component with streaming
|
|
278
|
-
\`\`\`
|
|
279
|
-
|
|
280
|
-
### Client Setup (lib/anthropic.ts)
|
|
281
|
-
\`\`\`typescript
|
|
282
|
-
import Anthropic from "@anthropic-ai/sdk";
|
|
283
|
-
|
|
284
|
-
export const anthropic = new Anthropic({
|
|
285
|
-
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
286
|
-
});
|
|
287
|
-
\`\`\`
|
|
288
|
-
|
|
289
|
-
### Streaming Chat Route (app/api/chat/route.ts)
|
|
290
|
-
\`\`\`typescript
|
|
291
|
-
import { anthropic } from "@/lib/anthropic";
|
|
292
|
-
import { NextRequest } from "next/server";
|
|
293
|
-
|
|
294
|
-
export async function POST(req: NextRequest) {
|
|
295
|
-
const { messages, systemPrompt } = await req.json();
|
|
296
|
-
|
|
297
|
-
const stream = anthropic.messages.stream({
|
|
298
|
-
model: "claude-sonnet-4-6",
|
|
299
|
-
max_tokens: 1024,
|
|
300
|
-
system: systemPrompt || "You are a helpful assistant.",
|
|
301
|
-
messages,
|
|
302
|
-
});
|
|
303
|
-
|
|
304
|
-
const encoder = new TextEncoder();
|
|
305
|
-
const readable = new ReadableStream({
|
|
306
|
-
async start(controller) {
|
|
307
|
-
for await (const event of stream) {
|
|
308
|
-
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
|
|
309
|
-
controller.enqueue(encoder.encode(event.delta.text));
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
controller.close();
|
|
313
|
-
},
|
|
314
|
-
});
|
|
315
|
-
|
|
316
|
-
return new Response(readable, {
|
|
317
|
-
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
318
|
-
});
|
|
319
|
-
}
|
|
320
|
-
\`\`\`
|
|
321
|
-
|
|
322
|
-
### Chat UI Component (components/chat.tsx)
|
|
323
|
-
Use the same chat component pattern as the OpenAI integration. The client-side code is identical since both stream plain text. Only the API route differs.
|
|
324
|
-
|
|
325
|
-
### Common Pitfalls
|
|
326
|
-
1. **Never expose ANTHROPIC_API_KEY to the client.** Always call Anthropic from server-side API routes.
|
|
327
|
-
2. **Use claude-sonnet-4-6 for most features.** Use claude-haiku-4-5 for high-volume, cost-sensitive tasks. Claude opus is for complex reasoning.
|
|
328
|
-
3. **Anthropic uses a different message format than OpenAI.** Role is "user" or "assistant" (no "system" role in messages). System prompt is a separate top-level field.
|
|
329
|
-
4. **Set max_tokens explicitly.** Unlike OpenAI, Anthropic requires max_tokens on every request.
|
|
330
|
-
5. **Streaming is the default UX pattern.** Use \`anthropic.messages.stream()\` not \`anthropic.messages.create()\` for chat.
|
|
331
|
-
6. **Long streaming responses are fine on Mistflow Cloud.** Network I/O does NOT count toward CPU time.
|
|
332
|
-
7. **Never ask the user to paste ANTHROPIC_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"openrouter-ai",name:"OpenRouter",category:"ai",prompt:`## OpenRouter Integration
|
|
333
|
-
|
|
334
|
-
OpenRouter provides a single API for 200+ AI models (GPT-4o, Claude, Llama, Mistral, Gemini, etc.). It uses an OpenAI-compatible API, so you use the standard OpenAI SDK with a different base URL and API key.
|
|
335
|
-
|
|
336
|
-
### File Structure
|
|
337
|
-
\`\`\`
|
|
338
|
-
lib/openrouter.ts \u2014 OpenRouter client
|
|
339
|
-
app/api/chat/route.ts \u2014 Streaming chat API route
|
|
340
|
-
components/chat.tsx \u2014 Chat UI component with streaming
|
|
341
|
-
components/model-selector.tsx \u2014 Model picker dropdown
|
|
342
|
-
\`\`\`
|
|
343
|
-
|
|
344
|
-
### Client Setup (lib/openrouter.ts)
|
|
345
|
-
\`\`\`typescript
|
|
346
|
-
import { OpenRouter } from "@openrouter/sdk";
|
|
347
|
-
|
|
348
|
-
export const openrouter = new OpenRouter({
|
|
349
|
-
apiKey: process.env.OPENROUTER_API_KEY,
|
|
350
|
-
});
|
|
351
|
-
|
|
352
|
-
// Popular models \u2014 use these as defaults or in a model selector
|
|
353
|
-
export const MODELS = {
|
|
354
|
-
fast: "meta-llama/llama-3.1-8b-instruct",
|
|
355
|
-
balanced: "anthropic/claude-sonnet-4-6",
|
|
356
|
-
powerful: "openai/gpt-4o",
|
|
357
|
-
cheap: "meta-llama/llama-3.1-8b-instruct",
|
|
358
|
-
} as const;
|
|
359
|
-
\`\`\`
|
|
360
|
-
|
|
361
|
-
### Streaming Chat Route (app/api/chat/route.ts)
|
|
362
|
-
\`\`\`typescript
|
|
363
|
-
import { openrouter, MODELS } from "@/lib/openrouter";
|
|
364
|
-
import { NextRequest } from "next/server";
|
|
365
|
-
|
|
366
|
-
export async function POST(req: NextRequest) {
|
|
367
|
-
const { messages, systemPrompt, model } = await req.json();
|
|
368
|
-
|
|
369
|
-
const completion = await openrouter.chat.send({
|
|
370
|
-
model: model || MODELS.balanced,
|
|
371
|
-
messages: [
|
|
372
|
-
{ role: "system", content: systemPrompt || "You are a helpful assistant." },
|
|
373
|
-
...messages,
|
|
374
|
-
],
|
|
375
|
-
stream: true,
|
|
376
|
-
});
|
|
377
|
-
|
|
378
|
-
const encoder = new TextEncoder();
|
|
379
|
-
const readable = new ReadableStream({
|
|
380
|
-
async start(controller) {
|
|
381
|
-
for await (const chunk of completion) {
|
|
382
|
-
const text = chunk.choices?.[0]?.delta?.content || "";
|
|
383
|
-
if (text) controller.enqueue(encoder.encode(text));
|
|
384
|
-
}
|
|
385
|
-
controller.close();
|
|
386
|
-
},
|
|
387
|
-
});
|
|
388
|
-
|
|
389
|
-
return new Response(readable, {
|
|
390
|
-
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
\`\`\`
|
|
394
|
-
|
|
395
|
-
### Model Selector Component (components/model-selector.tsx)
|
|
396
|
-
\`\`\`tsx
|
|
397
|
-
"use client";
|
|
398
|
-
|
|
399
|
-
const MODELS = [
|
|
400
|
-
{ id: "anthropic/claude-sonnet-4-6", label: "Claude Sonnet", tier: "Balanced" },
|
|
401
|
-
{ id: "openai/gpt-4o", label: "GPT-4o", tier: "Powerful" },
|
|
402
|
-
{ id: "openai/gpt-4o-mini", label: "GPT-4o Mini", tier: "Fast" },
|
|
403
|
-
{ id: "meta-llama/llama-3.1-70b-instruct", label: "Llama 3.1 70B", tier: "Open Source" },
|
|
404
|
-
{ id: "google/gemini-2.0-flash-001", label: "Gemini 2.0 Flash", tier: "Fast" },
|
|
405
|
-
];
|
|
406
|
-
|
|
407
|
-
interface ModelSelectorProps {
|
|
408
|
-
value: string;
|
|
409
|
-
onChange: (model: string) => void;
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
export function ModelSelector({ value, onChange }: ModelSelectorProps) {
|
|
413
|
-
return (
|
|
414
|
-
<select
|
|
415
|
-
value={value}
|
|
416
|
-
onChange={(e) => onChange(e.target.value)}
|
|
417
|
-
className="rounded-md border px-2 py-1 text-sm"
|
|
418
|
-
>
|
|
419
|
-
{MODELS.map((m) => (
|
|
420
|
-
<option key={m.id} value={m.id}>
|
|
421
|
-
{m.label} ({m.tier})
|
|
422
|
-
</option>
|
|
423
|
-
))}
|
|
424
|
-
</select>
|
|
425
|
-
);
|
|
426
|
-
}
|
|
427
|
-
\`\`\`
|
|
428
|
-
|
|
429
|
-
### Common Pitfalls
|
|
430
|
-
1. **Never expose OPENROUTER_API_KEY to the client.** Always call OpenRouter from server-side API routes.
|
|
431
|
-
2. **Model IDs use provider/model format.** E.g. "anthropic/claude-sonnet-4-6", not just "claude-sonnet".
|
|
432
|
-
3. **Use the \`@openrouter/sdk\` package.** It wraps the OpenRouter API with proper types and streaming support.
|
|
433
|
-
4. **Set max_tokens explicitly** for Anthropic models routed through OpenRouter. OpenAI models have defaults, Anthropic models don't.
|
|
434
|
-
5. **Check model pricing at openrouter.ai/models.** Costs vary 100x between models. Show users which model they're using.
|
|
435
|
-
6. **Long streaming responses are fine on Mistflow Cloud.** Network I/O does NOT count toward CPU time.
|
|
436
|
-
7. **Never ask the user to paste OPENROUTER_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"stripe-payments",name:"Stripe Payments",category:"payments",prompt:`## Stripe Payments Integration
|
|
138
|
+
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:"stripe-payments",name:"Stripe Payments",category:"payments",prompt:`## Stripe Payments Integration
|
|
437
139
|
|
|
438
140
|
### File Structure
|
|
439
141
|
\`\`\`
|
|
@@ -1680,12 +1382,12 @@ the tool fires.
|
|
|
1680
1382
|
stuck; a hard cap is the cheapest safety net.
|
|
1681
1383
|
3. **Don't echo user prompts back to the model as tool output.** The model
|
|
1682
1384
|
will get confused about whose turn it is. Tool output is OUTPUT from
|
|
1683
|
-
the tool, not from the user.`}]});import{z as
|
|
1385
|
+
the tool, not from the user.`}]});import{z as Fe}from"zod";import{resolve as On}from"path";import{existsSync as Mn,readFileSync as jn}from"fs";import{join as Dn}from"path";var fp,vi,ki=x(()=>{"use strict";ye();ut();yi();Se();xn();yr();fp=Fe.object({action:Fe.enum(["get","update","share","integrations","errors","logs","deployments","cron","cron-logs","cron-toggle","cron-trigger","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. 'cron' lists the project's cron jobs and their current status. 'cron-logs' returns recent execution history for one cron job (pass cronJobId). 'cron-toggle' enables or disables a cron job (pass cronJobId + cronEnabled). 'cron-trigger' fires a cron job once now via a QStash one-off publish (pass cronJobId). '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."),cronJobId:Fe.string().optional().describe("(cron-logs / cron-toggle / cron-trigger) UUID of the cron job"),cronEnabled:Fe.boolean().optional().describe("(cron-toggle) true to enable, false to pause")}),vi={name:"mist_project",description:Ts,inputSchema:fp,handler:async t=>{let e=t;if(["share","errors","logs","deployments","cron","cron-logs","cron-toggle","cron-trigger"].includes(e.action)&&!Ie())return je(`${e.action} project state`);let n=()=>{let o=On(e.projectPath??process.cwd()),s=Dn(o,"mistflow.json");if(!Mn(s))return{error:`Not a Mistflow project (no mistflow.json found at ${o}). Run mist_init to create one.`};let i;try{i=JSON.parse(jn(s,"utf-8"))}catch{return{error:"Could not read mistflow.json."}}let a=i.projectId;return a?{id:a}:{error:"This project hasn't been registered with Mistflow yet. Run mist_init first."}};switch(e.action){case"get":case"update":return fi.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let o=On(e.projectPath??process.cwd()),s=Dn(o,"mistflow.json");if(!Mn(s))return nt(o);let i;try{i=JSON.parse(jn(s,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let a=i.projectId;if(!a)return p("No project ID found. Deploy the project first to register it.",!0);try{let l=await Co(a,{isTemplate:!0,description:e.templateDescription});return p(JSON.stringify({shareUrl:l.share_url,shareToken:l.share_token,message:`Your project is now a shareable template!
|
|
1684
1386
|
|
|
1685
1387
|
Anyone can fork it: ${l.share_url}
|
|
1686
1388
|
|
|
1687
1389
|
Others can use it in their AI editor:
|
|
1688
|
-
"build me something like ${l.share_url}"`}))}catch(l){let c=l instanceof Error?l.message:"Failed to share project";return d(c,!0)}}case"integrations":{if(e.integrationId){let a=Zt(e.integrationId);if(!a)return d(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let l=en(a.id);return d(JSON.stringify({integration:{id:a.id,name:a.name,category:a.category,description:l?.description??"",packages:l?.packages??[],envVars:l?.envVars??[],docsUrl:l?.docsUrl??"",difficulty:l?.difficulty??"medium"},message:`Integration "${a.name}" (${a.category}) \u2014 ${l?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${l?.envVars?.map(c=>c.key).join(", ")||"none"}. Docs: ${l?.docsUrl??"n/a"}.`}))}let o=li(e.category??void 0),s=Mo(e.category??void 0),i=ai(s);return d(JSON.stringify({count:o.length,integrations:o.map(a=>({id:a.id,name:a.name,category:a.category,description:a.description,packages:a.packages,difficulty:a.difficulty,envVars:a.envVars.map(l=>l.key)})),formatted:i,message:`${o.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let o=En(e.projectPath??process.cwd()),s=Mn(o,"mistflow.json");if(!Nn(s))return Qe(o);let i;try{i=JSON.parse(On(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let a=i.projectId;if(!a)return d("No project ID found. Deploy the project first.",!0);try{let l=await lo(a,e.period??"7d");return l.total===0?d(JSON.stringify({total:0,period:l.period,message:`No runtime errors in the last ${l.period}. The app is running clean.`})):d(JSON.stringify({total:l.total,period:l.period,errors:l.errors,message:`${l.total} runtime error(s) in the last ${l.period}. Review the errors above and use mist_debug to investigate.`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch errors";return d(c,!0)}}case"logs":{let o=En(e.projectPath??process.cwd()),s=Mn(o,"mistflow.json");if(!Nn(s))return Qe(o);let i;try{i=JSON.parse(On(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let a=i.projectId;if(!a)return d("No project ID found. Deploy the project first.",!0);let l=e.deploymentId;if(!l)try{let c=await Yt(a);if(c.length===0)return d("No deployments found for this project.",!0);l=c[0].id}catch(c){let m=c instanceof Error?c.message:"Failed to fetch deployments";return d(m,!0)}try{let[c,m]=await Promise.all([ao(l),wt(l)]),p=c.filter(h=>h.level==="error"),u=c.filter(h=>h.level==="warn");return d(JSON.stringify({deploymentId:l,status:m.status,errorMessage:m.error??null,totalLogs:c.length,errorCount:p.length,warnCount:u.length,logs:c.map(h=>({time:h.timestamp,level:h.level,phase:h.phase,message:h.message})),message:m.status==="failed"?`Deployment failed. ${p.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${m.status}. ${c.length} log entries (${p.length} errors, ${u.length} warnings).`}))}catch(c){let m=c instanceof Error?c.message:"Failed to fetch deploy logs";return d(m,!0)}}case"deployments":{let o=En(e.projectPath??process.cwd()),s=Mn(o,"mistflow.json");if(!Nn(s))return Qe(o);let i;try{i=JSON.parse(On(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let a=i.projectId;if(!a)return d("No project ID found. Deploy the project first.",!0);try{let l=await Yt(a);return d(JSON.stringify({total:l.length,deployments:l.map(c=>({id:c.id,status:c.status,errorMessage:c.error_message,durationSeconds:c.duration_seconds,isRollback:!!c.rollback_from_id,createdAt:c.created_at})),message:`${l.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return d(c,!0)}}case"cron":{let o=n();if(o.error)return d(o.error,!0);try{let s=await co(o.id);return d(JSON.stringify({count:s.length,cronJobs:s.map(i=>({id:i.id,name:i.name,schedule:i.schedule,timezone:i.timezone,description:i.description,enabled:i.enabled,disabledReason:i.disabled_reason,consecutiveFailures:i.consecutive_failures,lastRunAt:i.last_run_at,lastStatus:i.last_status})),message:s.length===0?"No cron jobs configured. Add a `cron` array to mistflow.json and redeploy.":`${s.length} cron job(s). Use cron-logs / cron-toggle / cron-trigger with cronJobId to drill in.`}))}catch(s){return d(s instanceof Error?s.message:"Failed to list cron jobs",!0)}}case"cron-logs":{let o=n();if(o.error)return d(o.error,!0);if(!e.cronJobId)return d("cron-logs requires `cronJobId`.",!0);try{let s=await mo(o.id,e.cronJobId);return d(JSON.stringify({total:s.length,logs:s.map(i=>({triggerId:i.trigger_id,scheduledAt:i.scheduled_at,deliveredAt:i.delivered_at,status:i.status,statusCode:i.status_code,durationMs:i.duration_ms,error:i.error}))}))}catch(s){return d(s instanceof Error?s.message:"Failed to fetch cron logs",!0)}}case"cron-toggle":{let o=n();if(o.error)return d(o.error,!0);if(!e.cronJobId||typeof e.cronEnabled!="boolean")return d("cron-toggle requires `cronJobId` and `cronEnabled` (true/false).",!0);try{let s=await po(o.id,e.cronJobId,e.cronEnabled);return d(JSON.stringify({id:s.id,name:s.name,enabled:s.enabled,message:s.enabled?`Cron "${s.name}" enabled. It will resume firing on schedule within ~60s.`:`Cron "${s.name}" paused. It will stop firing within ~60s.`}))}catch(s){return d(s instanceof Error?s.message:"Failed to toggle cron job",!0)}}case"cron-trigger":{let o=n();if(o.error)return d(o.error,!0);if(!e.cronJobId)return d("cron-trigger requires `cronJobId`.",!0);try{let s=await uo(o.id,e.cronJobId);return d(JSON.stringify({...s,message:"Queued for immediate execution. Logs will appear in cron-logs within a few seconds."}))}catch(s){return d(s instanceof Error?s.message:"Failed to trigger cron job",!0)}}case"version":{Wr().backendSignalReceived||await Qr();let o=Wr(),s=o.severity==="none",i={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return d(JSON.stringify({current:o.current,latest:o.latest||"unknown",minSupported:o.minSupported||"unknown",severity:o.severity,upToDate:s,upgradeCmd:o.upgradeCmd,changelogUrl:o.changelogUrl,backendSignalReceived:o.backendSignalReceived,message:o.backendSignalReceived?`Mistflow MCP ${o.current} (${i[o.severity]??o.severity}). Latest: ${o.latest}.${s?"":` Run \`${o.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${o.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return d(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, cron, cron-logs, cron-toggle, cron-trigger, or version.`,!0)}}}});import{z as Ut}from"zod";var lp,pi,ui=v(()=>{"use strict";lt();xe();Kt();lp=Ut.object({action:Ut.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:Ut.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Ut.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:Ut.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:Ut.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Ut.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),pi={name:"mist_browser",description:vs,inputSchema:lp,handler:async t=>{let e=t,r=await Gr();if(e.action==="navigate"){if(!e.url)return d("URL is required for 'navigate'.",!0);let s=[],i=c=>{c.type()==="error"&&s.push(c.text())};r.on("console",i),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=c=>a.push(c.message);if(r.on("pageerror",l),await r.waitForTimeout(500),r.removeListener("console",i),r.removeListener("pageerror",l),s.length>0||a.length>0){let c=await xn(r),m=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:s,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let p=await Sn(r);m.push({type:"image",data:p.toString("base64"),mimeType:"image/png"})}return{content:m}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return d("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return d("Selector is required for 'type'.",!0);if(!e.value)return d("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return d("Selector is required for 'fill'.",!0);if(!e.value)return d("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return d("Selector is required for 'select_option'.",!0);if(!e.value)return d("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return d("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let s;if(e.selector){let i=await r.$(e.selector);if(!i)return d(`Element not found: ${e.selector}`,!0);s=await i.screenshot({type:"png"})}else s=await Sn(r,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:s.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let s=await xn(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:s})}]}}let n=await xn(r),o=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:n})}];if(e.includeScreenshot){let s=await Sn(r);o.push({type:"image",data:s.toString("base64"),mimeType:"image/png"})}return{content:o}}}});import{z as mi}from"zod";var hi,gi,fi=v(()=>{"use strict";lt();xe();hi=`# Mistflow MCP tool reference
|
|
1390
|
+
"build me something like ${l.share_url}"`}))}catch(l){let c=l instanceof Error?l.message:"Failed to share project";return p(c,!0)}}case"integrations":{if(e.integrationId){let a=en(e.integrationId);if(!a)return p(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let l=tn(a.id);return p(JSON.stringify({integration:{id:a.id,name:a.name,category:a.category,description:l?.description??"",packages:l?.packages??[],envVars:l?.envVars??[],docsUrl:l?.docsUrl??"",difficulty:l?.difficulty??"medium"},message:`Integration "${a.name}" (${a.category}) \u2014 ${l?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${l?.envVars?.map(c=>c.key).join(", ")||"none"}. Docs: ${l?.docsUrl??"n/a"}.`}))}let o=wi(e.category??void 0),s=Do(e.category??void 0),i=bi(s);return p(JSON.stringify({count:o.length,integrations:o.map(a=>({id:a.id,name:a.name,category:a.category,description:a.description,packages:a.packages,difficulty:a.difficulty,envVars:a.envVars.map(l=>l.key)})),formatted:i,message:`${o.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let o=On(e.projectPath??process.cwd()),s=Dn(o,"mistflow.json");if(!Mn(s))return nt(o);let i;try{i=JSON.parse(jn(s,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let a=i.projectId;if(!a)return p("No project ID found. Deploy the project first.",!0);try{let l=await po(a,e.period??"7d");return l.total===0?p(JSON.stringify({total:0,period:l.period,message:`No runtime errors in the last ${l.period}. The app is running clean.`})):p(JSON.stringify({total:l.total,period:l.period,errors:l.errors,message:`${l.total} runtime error(s) in the last ${l.period}. Review the errors above and check mist_project action='logs' for surrounding context. mist_debug is for build errors; for runtime errors, fix the code directly.`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch errors";return p(c,!0)}}case"logs":{let o=On(e.projectPath??process.cwd()),s=Dn(o,"mistflow.json");if(!Mn(s))return nt(o);let i;try{i=JSON.parse(jn(s,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let a=i.projectId;if(!a)return p("No project ID found. Deploy the project first.",!0);let l=e.deploymentId;if(!l)try{let c=await Qt(a);if(c.length===0)return p("No deployments found for this project.",!0);l=c[0].id}catch(c){let u=c instanceof Error?c.message:"Failed to fetch deployments";return p(u,!0)}try{let[c,u]=await Promise.all([co(l),kt(l)]),d=c.filter(h=>h.level==="error"),m=c.filter(h=>h.level==="warn");return p(JSON.stringify({deploymentId:l,status:u.status,errorMessage:u.error??null,totalLogs:c.length,errorCount:d.length,warnCount:m.length,logs:c.map(h=>({time:h.timestamp,level:h.level,phase:h.phase,message:h.message})),message:u.status==="failed"?`Deployment failed. ${d.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${u.status}. ${c.length} log entries (${d.length} errors, ${m.length} warnings).`}))}catch(c){let u=c instanceof Error?c.message:"Failed to fetch deploy logs";return p(u,!0)}}case"deployments":{let o=On(e.projectPath??process.cwd()),s=Dn(o,"mistflow.json");if(!Mn(s))return nt(o);let i;try{i=JSON.parse(jn(s,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let a=i.projectId;if(!a)return p("No project ID found. Deploy the project first.",!0);try{let l=await Qt(a);return p(JSON.stringify({total:l.length,deployments:l.map(c=>({id:c.id,status:c.status,errorMessage:c.error_message,durationSeconds:c.duration_seconds,isRollback:!!c.rollback_from_id,createdAt:c.created_at})),message:`${l.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return p(c,!0)}}case"cron":{let o=n();if(o.error)return p(o.error,!0);try{let s=await uo(o.id);return p(JSON.stringify({count:s.length,cronJobs:s.map(i=>({id:i.id,name:i.name,schedule:i.schedule,timezone:i.timezone,description:i.description,enabled:i.enabled,disabledReason:i.disabled_reason,consecutiveFailures:i.consecutive_failures,lastRunAt:i.last_run_at,lastStatus:i.last_status})),message:s.length===0?"No cron jobs configured. Add a `cron` array to mistflow.json and redeploy.":`${s.length} cron job(s). Use cron-logs / cron-toggle / cron-trigger with cronJobId to drill in.`}))}catch(s){return p(s instanceof Error?s.message:"Failed to list cron jobs",!0)}}case"cron-logs":{let o=n();if(o.error)return p(o.error,!0);if(!e.cronJobId)return p("cron-logs requires `cronJobId`.",!0);try{let s=await go(o.id,e.cronJobId);return p(JSON.stringify({total:s.length,logs:s.map(i=>({triggerId:i.trigger_id,scheduledAt:i.scheduled_at,deliveredAt:i.delivered_at,status:i.status,statusCode:i.status_code,durationMs:i.duration_ms,error:i.error}))}))}catch(s){return p(s instanceof Error?s.message:"Failed to fetch cron logs",!0)}}case"cron-toggle":{let o=n();if(o.error)return p(o.error,!0);if(!e.cronJobId||typeof e.cronEnabled!="boolean")return p("cron-toggle requires `cronJobId` and `cronEnabled` (true/false).",!0);try{let s=await mo(o.id,e.cronJobId,e.cronEnabled);return p(JSON.stringify({id:s.id,name:s.name,enabled:s.enabled,message:s.enabled?`Cron "${s.name}" enabled. It will resume firing on schedule within ~60s.`:`Cron "${s.name}" paused. It will stop firing within ~60s.`}))}catch(s){return p(s instanceof Error?s.message:"Failed to toggle cron job",!0)}}case"cron-trigger":{let o=n();if(o.error)return p(o.error,!0);if(!e.cronJobId)return p("cron-trigger requires `cronJobId`.",!0);try{let s=await ho(o.id,e.cronJobId);return p(JSON.stringify({...s,message:"Queued for immediate execution. Logs will appear in cron-logs within a few seconds."}))}catch(s){return p(s instanceof Error?s.message:"Failed to trigger cron job",!0)}}case"version":{Jr().backendSignalReceived||await Xr();let o=Jr(),s=o.severity==="none",i={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return p(JSON.stringify({current:o.current,latest:o.latest||"unknown",minSupported:o.minSupported||"unknown",severity:o.severity,upToDate:s,upgradeCmd:o.upgradeCmd,changelogUrl:o.changelogUrl,backendSignalReceived:o.backendSignalReceived,message:o.backendSignalReceived?`Mistflow MCP ${o.current} (${i[o.severity]??o.severity}). Latest: ${o.latest}.${s?"":` Run \`${o.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${o.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return p(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, cron, cron-logs, cron-toggle, cron-trigger, or version.`,!0)}}}});import{z as Ft}from"zod";var yp,xi,Si=x(()=>{"use strict";ut();ye();Kt();yp=Ft.object({action:Ft.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:Ft.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Ft.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:Ft.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:Ft.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Ft.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),xi={name:"mist_browser",description:Cs,inputSchema:yp,handler:async t=>{let e=t,r=await Kr();if(e.action==="navigate"){if(!e.url)return p("URL is required for 'navigate'.",!0);let s=[],i=c=>{c.type()==="error"&&s.push(c.text())};r.on("console",i),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=c=>a.push(c.message);if(r.on("pageerror",l),await r.waitForTimeout(500),r.removeListener("console",i),r.removeListener("pageerror",l),s.length>0||a.length>0){let c=await Sn(r),u=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:s,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let d=await _n(r);u.push({type:"image",data:d.toString("base64"),mimeType:"image/png"})}return{content:u}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return p("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return p("Selector is required for 'type'.",!0);if(!e.value)return p("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return p("Selector is required for 'fill'.",!0);if(!e.value)return p("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return p("Selector is required for 'select_option'.",!0);if(!e.value)return p("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return p("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return p("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let s;if(e.selector){let i=await r.$(e.selector);if(!i)return p(`Element not found: ${e.selector}`,!0);s=await i.screenshot({type:"png"})}else s=await _n(r,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:s.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let s=await Sn(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:s})}]}}let n=await Sn(r),o=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:n})}];if(e.includeScreenshot){let s=await _n(r);o.push({type:"image",data:s.toString("base64"),mimeType:"image/png"})}return{content:o}}}});import{z as _i}from"zod";var Ti,Ci,Ii=x(()=>{"use strict";ut();ye();Ti=`# Mistflow MCP tool reference
|
|
1689
1391
|
|
|
1690
1392
|
Every capability is an MCP tool. There is no companion CLI. Long-running tools
|
|
1691
1393
|
(install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
|
|
@@ -2022,27 +1724,27 @@ is cheaper than building the wrong thing and iterating.
|
|
|
2022
1724
|
|
|
2023
1725
|
mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
|
|
2024
1726
|
mist_deploy({ action: "status", deploymentId }) # poll
|
|
2025
|
-
`,
|
|
2026
|
-
`),o=new RegExp(`^### \`${r}`),s=-1,i=n.length;for(let a=0;a<n.length;a++)if(o.test(n[a]))s=a;else if(s>=0&&n[a].startsWith("### ")){i=a;break}else if(s>=0&&n[a].startsWith("## ")&&a>s){i=a;break}return s<0?
|
|
2027
|
-
`).trim())}}});import{z as
|
|
1727
|
+
`,Ci={name:"mist_help",description:Is,inputSchema:_i.object({command:_i.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return p(Ti);let r=e.startsWith("mist_")?e:`mist_${e}`,n=Ti.split(`
|
|
1728
|
+
`),o=new RegExp(`^### \`${r}`),s=-1,i=n.length;for(let a=0;a<n.length;a++)if(o.test(n[a]))s=a;else if(s>=0&&n[a].startsWith("### ")){i=a;break}else if(s>=0&&n[a].startsWith("## ")&&a>s){i=a;break}return s<0?p(`No tool named '${r}' found. Call mist_help with no args to see the full catalog.`,!0):p(n.slice(s,i).join(`
|
|
1729
|
+
`).trim())}}});import{z as Ln}from"zod";var Pi,Ri,Ai=x(()=>{"use strict";ut();Se();ye();Pi=Ln.object({action:Ln.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:Ln.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:Ln.enum(["stack","skill","integration"]).optional().describe("Optional filter for action='list'. 'stack' = framework methodology, 'skill' = design + structural patterns, 'integration' = third-party services."),stack:Ln.string().optional().default("nextjs").describe("Stack slug. Defaults to 'nextjs' (currently the only supported stack).")}),Ri={name:"mist_docs",description:Ps,inputSchema:Pi,handler:async t=>{let{action:e,topic:r,kind:n,stack:o}=Pi.parse(t);try{if(e==="list"){let a=await ko(o,n),l=[];l.push(`# Mistflow docs catalog (${a.stack})
|
|
2028
1730
|
${a.topics.length} topics. Call \`mist_docs({ action: "get", topic: "<id>" })\` to fetch one.
|
|
2029
|
-
`);let c={};for(let
|
|
2030
|
-
`).trim())}if(!r)return
|
|
1731
|
+
`);let c={};for(let d of a.topics)(c[d.kind]??=[]).push(d);let u=["stack","skill","integration"];for(let d of u){let m=c[d];if(!(!m||m.length===0)){l.push(`## ${d}`);for(let h of m)l.push(`- **${h.id}** \u2014 ${h.title}: ${h.description}`);l.push("")}}return p(l.join(`
|
|
1732
|
+
`).trim())}if(!r)return p("Missing `topic`. Pass action='get' with a topic id, or action='list' to see available topics.",!0);let s=await xo(o,r),i=`<!-- mist_docs: topic=${s.topic} kind=${s.kind} stack=${s.stack} -->
|
|
2031
1733
|
# ${s.title}
|
|
2032
1734
|
|
|
2033
1735
|
${s.description}
|
|
2034
1736
|
|
|
2035
1737
|
---
|
|
2036
1738
|
|
|
2037
|
-
`;return
|
|
1739
|
+
`;return p(i+s.content)}catch(s){if(s instanceof ee&&s.statusCode===404)return p(s.message,!0);let i=s instanceof Error?s.message:String(s);return p(`mist_docs failed: ${i}
|
|
2038
1740
|
|
|
2039
|
-
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
|
|
1741
|
+
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 br,mkdirSync as Oi,readFileSync as Mi,readdirSync as ji,writeFileSync as bp}from"fs";import{join as _t,resolve as wp}from"path";import{homedir as $o}from"os";import{z as $n}from"zod";function nn(t){return t.entity??t.name??"Unknown"}function rn(t){return typeof t=="string"?t:t.name}function Lo(t){return typeof t=="string"?"text":t.type}function Ei(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(o=>{let s={};for(let[i,a]of Object.entries(o))s[i]=a==null?"":String(a);return s});let r=t.fields||[],n=[];for(let o=0;o<3;o++){let s={};for(let i of r)s[rn(i)]=vp(rn(i),Lo(i),nn(t),o);n.push(s)}return n}function vp(t,e,r,n){let o=t.toLowerCase(),s=(e||"text").toLowerCase();return o==="name"||o==="title"?[`${r} Alpha`,`${r} Beta`,`${r} 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")||s==="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")||s==="number"||s==="integer"?["12","34","56"][n]:s==="boolean"||s==="bool"?["Yes","No","Yes"][n]:o.includes("description")||s==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function kp(t){let e=t.dataModel??[],r=t.pages??[],n=t.design??{},o=r.map(d=>({label:d.name??d.path??"Page",route:d.path??d.route??"/"})),s=[],i=e.slice(0,3).map(d=>({name:nn(d),fields:(d.fields||[]).map(m=>({name:rn(m),type:Lo(m)})),sampleData:Ei(d)})),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(d=>nn(d)).join(", ")}`),a.push("RECENT: Latest activity or items"),s.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(d=>nn(d)).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:i});let l=e[0];if(l){let d=nn(l),m=d.toLowerCase().endsWith("s")?d:`${d}s`;s.push({name:`${d} List`,type:"detail",route:`/${m.toLowerCase()}`,purpose:`Browse, search, and manage ${m.toLowerCase()}. Create new ${d.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${m}" title + "Add ${d}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(h=>rn(h)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${m.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${m.toLowerCase()} matching..." with clear filter`],entities:[{name:d,fields:(l.fields||[]).map(h=>({name:rn(h),type:Lo(h)})),sampleData:Ei(l)}]})}t.steps.some(d=>{let m=`${d.name??d.title??""} ${d.description??""}`.toLowerCase();return m.includes("landing")||m.includes("hero")||m.includes("marketing")||m.includes("homepage")})&&s.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let u=[];for(let d of e.slice(0,3)){let m=nn(d);(d.fields||[]).find(_=>{let P=rn(_).toLowerCase();return P==="name"||P==="title"})&&u.push(`What if a ${m.toLowerCase()}'s name is 47 characters? Does the layout break?`),u.push(`What if there are 0 ${m.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&u.push("What does a brand-new user see? (no data, no setup)"),u.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:s,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:u}}function xp(t,e,r){let n=[];n.push(`# Wireframe sketch for ${t.appName}`),n.push(""),n.push(`**${t.appName}** \u2014 ${t.summary}`),n.push(""),e&&(n.push("## Feedback to apply"),n.push(e),n.push("")),n.push("## Design principles"),n.push(""),n.push("Apply these when deciding layout and hierarchy:"),n.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),n.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),n.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),n.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),n.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),n.push(""),n.push("## Wireframe rules (strict)"),n.push(""),n.push(`Write a **single self-contained HTML file** saved to \`${r}\`.`),n.push(""),n.push("The wireframe must:"),n.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),n.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),n.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),n.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),n.push("- Include **HTML comments** explaining design decisions"),n.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),n.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),n.push("- Include a small header bar showing: screen name tabs + the design direction summary"),n.push(""),n.push("The wireframe must NOT:"),n.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),n.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),n.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),n.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),n.push(""),n.push("## Screens to wireframe"),n.push("");for(let 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 s of o.informationHierarchy)n.push(`- ${s}`);n.push(""),n.push("**Interaction states** (add HTML comments for non-visible states):");for(let s of o.interactionStates)n.push(`- ${s}`);if(n.push(""),o.entities.length>0){n.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let s of o.entities)n.push(`
|
|
2040
1742
|
**${s.name}** \u2014 fields: ${s.fields.map(i=>`${i.name} (${i.type})`).join(", ")}`),n.push("```json"),n.push(JSON.stringify(s.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 \`${r}\``),n.push(`2. Open it for the user: \`open "${r}"\``),n.push(`3. Tell the user: "Here's a rough wireframe of your app. Does the layout feel right? Let me know what to change, or I can start building if it's close."`),n.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),n.join(`
|
|
2041
|
-
`)}function
|
|
2042
|
-
${o.message}`})}),r.on("close",o=>{e({exitCode:o??1,combined:n})})})}var
|
|
2043
|
-
Recommended: ${i.recommended}`:""}`:i.recommended?`Recommended: ${i.recommended}`:void 0,enum:
|
|
2044
|
-
`)}function
|
|
2045
|
-
`),s=e.map((i,a)=>{let l=
|
|
1743
|
+
`)}function Di(t){return _t($o(),".mistflow","mockup-state",`${t}.json`)}function Sp(t){let e=Di(t);if(!br(e))return null;try{return JSON.parse(Mi(e,"utf-8"))}catch{return null}}function Ni(t,e){let r=_t($o(),".mistflow","mockup-state");Oi(r,{recursive:!0}),bp(Di(t),JSON.stringify(e,null,2))}function $i(t){let e=_t(t,".mistflow","mockups");return br(e)?ji(e).filter(r=>r.endsWith(".html")).map(r=>_t(e,r)):[]}var _p,Li,Uo=x(()=>{"use strict";ut();ye();_p=$n.object({planId:$n.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:$n.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:$n.string().optional().describe("User feedback to apply to the next iteration."),approved:$n.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."}),Li={name:"mist_mockup",description:As,inputSchema:_p,handler:async t=>{let e=t,{planId:r,feedback:n,approved:o}=e,s=wp(e.projectPath??process.cwd()),i=_t($o(),".mistflow","plans",`${r}.json`);if(!br(i))return p(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(Mi(i,"utf-8"))}catch{return p("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return p("Plan data is empty. Call mist_plan again.",!0);let c=Sp(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let u=_t(s,".mistflow","mockups");Oi(u,{recursive:!0});let d=`mockup-${r}.html`,m=_t(u,d);if(o){c.approved=!0,Ni(r,c);let v=br(u)?ji(u).filter(N=>N.endsWith(".html")).map(N=>_t(".mistflow","mockups",N)):[];return p(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:v,nextAction:`Call mist_init with planId='${r}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}c.iterationCount++,n&&c.feedback.push(n);let h=kp(l);c.screens=h.screens.map(v=>v.name),Ni(r,c);let _=xp(h,n??void 0,m),P=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,y=n?`Apply the user's feedback to ${m}. 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 ${m}, then open it in the browser. Ask the user if the layout feels right.`;return p(JSON.stringify({status:"wireframe",requires_user_input:!0,iterationCount:c.iterationCount,screens:h.screens.map(v=>({name:v.name,type:v.type,route:v.route})),wireframePrompt:_,designDirection:h.designDirection,...P?{nudge:P}:{},mockupFile:d,mockupPath:m,nextAction:y}))}}});function wr(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,c,u,d,m]=a;e.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:`${d}: ${m}`,humanMessage:`There is a type error in ${l} on line ${c}: ${m}`,suggestion:`Check line ${c} in ${l}. ${d==="TS2345"?"The types of the arguments do not match.":`Fix the ${d} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(n)){let[,l,c,u,d]=a;e.some(m=>m.file===l&&m.line===parseInt(c,10))||e.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:d,humanMessage:`There is an error in ${l} on line ${c}: ${d.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 s=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(s)){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 i=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of t.matchAll(i)){let[,l,c,u,d]=a;e.some(m=>m.file===l&&m.line===parseInt(u,10))||e.push({file:l,line:parseInt(u,10),column:parseInt(d,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${u}.`,suggestion:`Check line ${u} in ${l} for a missing closing bracket or unexpected token.`})}return e}var Fo=x(()=>{"use strict"});import{z as qo}from"zod";import{resolve as Tp}from"path";import{spawn as Cp}from"child_process";function Pp(t){return new Promise(e=>{let r=Cp("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.stderr?.on("data",o=>{n+=o.toString()}),r.on("error",o=>{e({exitCode:127,combined:`${n}
|
|
1744
|
+
${o.message}`})}),r.on("close",o=>{e({exitCode:o??1,combined:n})})})}var Ip,Ui,Fi=x(()=>{"use strict";ut();ye();Fo();Ip=qo.object({projectPath:qo.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:qo.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});Ui={name:"mist_debug",description:Rs,inputSchema:Ip,handler:async t=>{let e=t,r=Tp(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let i=await Pp(r);if(i.exitCode===0)return p(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=i.combined}let o=wr(n),s=n.slice(0,2e3);return o.length===0?p(JSON.stringify({errors:o,rawOutput:s,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):p(JSON.stringify({errors:o,rawOutput:s,message:`Found ${o.length} error${o.length===1?"":"s"} in the build output.`}))}}});import{spawn as Rp}from"child_process";function Bo(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(Ap())return{opened:!1,reason:"headless environment detected"};let r=process.platform,n,o;r==="darwin"?(n="open",o=[e.href]):r==="win32"?(n="cmd",o=["/c","start","",e.href]):(n="xdg-open",o=[e.href]);try{let s=Rp(n,o,{shell:!1,stdio:"ignore",detached:!0});return s.on("error",()=>{}),s.unref(),{opened:!0}}catch(s){return{opened:!1,reason:s instanceof Error?s.message:"spawn failed"}}}function Ap(){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 qi=x(()=>{"use strict"});function rt(t,e,r,n=3e3){if(e===void 0)return{stop:()=>{}};let o=0,s=!1,a=setInterval(()=>{s||(o++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:o,message:r()}}).catch(()=>{}))},n);return{stop:()=>{s||(s=!0,clearInterval(a))}}}var on=x(()=>{"use strict"});function Ep(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function Np(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function Op(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function Mp(t){let e={},r=[],n=[],o=new Set;for(let s=0;s<t.length;s++){let i=t[s],a=i.decisionKey?Op(i.decisionKey):`q_${s+1}`,l=a,c=2;for(;o.has(l);)l=`${a}_${c}`,c++;o.add(l);let u=i.freetext?"":`${l}_other`;if(u&&o.add(u),n.push({primary:l,other:u,question:i}),i.freetext){e[l]={type:"string",title:i.question,description:i.why,...i.recommended?{default:i.recommended}:{}},r.push(l);continue}let d=(i.options??[]).map(h=>typeof h=="string"?h:h.label),m=i.noOtherSentinel?[...d]:[...d,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:i.question,description:i.why?`${i.why}${i.recommended?`
|
|
1745
|
+
Recommended: ${i.recommended}`:""}`:i.recommended?`Recommended: ${i.recommended}`:void 0,enum:m,enumNames:m,...i.recommended&&d.includes(i.recommended)?{default:i.recommended}:{}},r.push(l),e[u]={type:"string",title:i.otherFieldTitle??"If 'Other' selected above: type your answer",description:"Leave blank if you picked an option from the list."}}return{schema:{type:"object",properties:e,required:r},fieldKeys:n}}function jp(t,e){let r=[],n;for(let{primary:o,other:s,question:i}of e){let a=String(t[o]??"").trim(),l;if(i.freetext)l=a||i.recommended||"";else{let u=s?String(t[s]??"").trim():"",d=a.toLowerCase(),m=d.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(d);u?l=u:m?l=i.recommended??(i.options?.[0]&&typeof i.options[0]=="object"?i.options[0].label:"")??a:l=a}let c=i.decisionKey??"";if(c==="urlChoice"){n=l;continue}r.push({question:i.question,decisionKey:c,answer:l})}return{answers:r,urlChoice:n}}function gt(t,e,r){let n;switch(r.outcome){case"submitted":n=`submitted (${r.answers?.length??0} answers${r.urlChoice?`, urlChoice="${r.urlChoice}"`:""})`;break;case"error":n=`error (${r.errorMessage??"unknown"})`;break;case"unsupported":n=`unsupported (${e})`;break;default:n=r.outcome}console.error(`[mist_plan] elicitation/${t}: ${n}`)}async function Un(t,e,r,n="discovery"){if(Np()){let u={outcome:"unsupported"};return gt(n,"MISTFLOW_ELICITATION kill switch on",u),u}if(!Ep(t)){let u={outcome:"unsupported"};return gt(n,"client did not declare elicitation capability",u),u}if(e.length===0){let u={outcome:"submitted",answers:[]};return gt(n,"no questions to ask",u),u}let{schema:o,fieldKeys:s}=Mp(e),i;try{i=await t.elicitInput({message:r,requestedSchema:o,mode:"form"},{timeout:300*1e3})}catch(u){let d=u instanceof Error?u.message:String(u);if(d.toLowerCase().includes("not support")){let h={outcome:"unsupported"};return gt(n,`SDK rejected form mode: ${d}`,h),h}let m={outcome:"error",errorMessage:d};return gt(n,"",m),m}if(i.action==="decline"){let u={outcome:"declined"};return gt(n,"",u),u}if(i.action==="cancel"){let u={outcome:"cancelled"};return gt(n,"",u),u}if(i.action!=="accept"||!i.content){let u={outcome:"error",errorMessage:`Unexpected elicitation result: ${i.action}`};return gt(n,"",u),u}let{answers:a,urlChoice:l}=jp(i.content,s),c={outcome:"submitted",answers:a,urlChoice:l};return gt(n,"",c),c}var Bi=x(()=>{"use strict"});function Hi(t,e,r){let n=r?.suggestedName||Lp(t),o=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",s=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),i=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":e.surfaceType==="agent"?"Chat agent":"App",a;if(r?.suggestedFeatures&&r.suggestedFeatures.length>0)a=r.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;a=[];for(let c of Dp){let u=c.keywords.test(l),d=c.condition(e);(u||d)&&a.push({name:c.name,description:c.description,checked:u,source:u?"explicit":"suggested"})}}return{name:n,audience:o,audienceType:s,surfaceType:i,primaryAction:e.primaryAction||"manage items",features:a,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:r?.language||"English"}}function zi(t){let e=t.features.filter(a=>a.checked),r=t.features.filter(a=>!a.checked),n={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},o={neon:"Postgres",turso:"SQLite (legacy)"},s={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},i=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${s[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){i.push("**Included:**");for(let a of e)i.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(i.push(""),i.push(`**Integrations:** ${t.integrations.join(", ")}`)),r.length>0){i.push(""),i.push("**Available to add:**");for(let a of r)i.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return i.join(`
|
|
1746
|
+
`)}function Lp(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return vr(e[1]);let r=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),o=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(s=>s.length>2&&!r.has(s)).slice(0,3);return o.length===0?"my-app":o.join("-")}function vr(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Dp,Wi=x(()=>{"use strict";Dp=[{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 Ho(t,e,r){let n=Fn(t||"your app"),o=e.map((i,a)=>{let l=kr(i.id||`direction-${a}`),c=Fn(i.name||`Direction ${a+1}`),u=Fn(i.summary||"");return`<button class="tab${a===0?" active":""}" data-target="${l}" type="button"><span class="tab-name">${c}</span>${u?`<span class="tab-sub">${u}</span>`:""}</button>`}).join(`
|
|
1747
|
+
`),s=e.map((i,a)=>{let l=kr(i.id||`direction-${a}`),c=r[i.id??""]??"";return`<iframe class="render-frame${a===0?" active":""}" data-id="${l}" srcdoc="${kr(c)}" sandbox="allow-same-origin allow-scripts" title="${kr(i.name||`Direction ${a+1}`)}"></iframe>`}).join(`
|
|
2046
1748
|
`);return`<!doctype html>
|
|
2047
1749
|
<html lang="en">
|
|
2048
1750
|
<head>
|
|
@@ -2131,7 +1833,7 @@ Recommended: ${i.recommended}`:""}`:i.recommended?`Recommended: ${i.recommended}
|
|
|
2131
1833
|
${s}
|
|
2132
1834
|
</div>
|
|
2133
1835
|
<footer class="picker-foot">
|
|
2134
|
-
<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
|
|
1836
|
+
<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?Fn(e[0].name):"Morning Paper"}</em>”). Images only for representation, will be replaced with actual designs.</div>
|
|
2135
1837
|
<div><strong>None fit?</strong> Tell your assistant <code>describe your own</code> and give a short description.</div>
|
|
2136
1838
|
</footer>
|
|
2137
1839
|
<script>
|
|
@@ -2149,44 +1851,44 @@ ${s}
|
|
|
2149
1851
|
</script>
|
|
2150
1852
|
</body>
|
|
2151
1853
|
</html>
|
|
2152
|
-
`}function
|
|
2153
|
-
`)})}function
|
|
2154
|
-
Reason: ${t.reason}`:"";switch(t.state){case"COMPLETE":return`Session complete.${e?` Live URL: ${e}`:""}${r}`;case"CANCELLED":return`Session was cancelled.${r}`;case"FAILED":return`Session ended in FAILED.${e?` Last known URL: ${e}`:""}${r}`;case"ABANDONED":return`Session was abandoned.${r}`;case"EXPIRED":return`Session expired.${r}`;default:return`Session finished with state ${t.state}.${e?` URL: ${e}`:""}${r}`}}async function
|
|
2155
|
-
`));case"resume_conversation":{let
|
|
2156
|
-
`))}case"continue":return
|
|
2157
|
-
`));case"call_mist_init":return
|
|
2158
|
-
`));case"call_mist_deploy":return
|
|
2159
|
-
`));case"ask_user":return
|
|
2160
|
-
`));case"pick_design":return
|
|
2161
|
-
`));case"review_mockup":return
|
|
2162
|
-
`));case"call_mist_install":return
|
|
2163
|
-
`));case"call_mist_implement":return
|
|
2164
|
-
`));case"call_mist_build":return
|
|
2165
|
-
`));case"call_mist_qa":return
|
|
2166
|
-
`));case"review_plan":return
|
|
2167
|
-
`));case"done":return
|
|
2168
|
-
`))}}catch(g){let
|
|
2169
|
-
|
|
2170
|
-
`)}))}return
|
|
2171
|
-
`)}),!0);if(g==="foreign"){let
|
|
1854
|
+
`}function Fn(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function kr(t){return Fn(t)}var Gi=x(()=>{"use strict"});import{z as q}from"zod";import{existsSync as ft,mkdirSync as Bt,readFileSync as qn,readdirSync as Zi,statSync as ea,unlinkSync as $p,writeFileSync as Tt}from"fs";import{dirname as Up,isAbsolute as Fp,join as be}from"path";import{homedir as Ct,hostname as Ji}from"os";import{createHash as qp,createHmac as ta,randomBytes as Bp,randomUUID as Ki,timingSafeEqual as Hp}from"crypto";function na(){let t=be(Ct(),".mistflow","confirm-secret");if(ft(t))try{return Buffer.from(qn(t,"utf-8").trim(),"hex")}catch{}let e=Bp(32);return Bt(be(Ct(),".mistflow"),{recursive:!0}),Tt(t,e.toString("hex"),{mode:384}),e}function ra(t){return qp("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function Wp(t,e){let r={cwd:t,d:ra(e),exp:Date.now()+zp},n=Buffer.from(JSON.stringify(r)).toString("base64url"),o=ta("sha256",na()).update(n).digest("base64url");return`${n}.${o}`}function Gp(t,e,r){let n=t.split(".");if(n.length!==2)return!1;let[o,s]=n,i=ta("sha256",na()).update(o).digest("base64url"),a=Buffer.from(s),l=Buffer.from(i);if(a.length!==l.length||!Hp(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!==ra(r))}catch{return!1}}function Jp(t){let e=t,r=Ct(),n=!1;for(let o=0;o<64;o++){if(ft(be(e,"mistflow.json")))return"mistflow";if(!n&&ft(be(e,"package.json"))&&(n=!0),e===r)break;let s=Up(e);if(s===e)break;e=s}return n?"foreign":"none"}function Kp(t){let e=Ct(),r=t.replace(/\/+$/,"");if(r===e||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let o of n)if(r===be(e,o))return!0;return!1}function Vp(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 Vi(t){if(!ft(t))return!0;try{return ea(t).isDirectory()?Zi(t).filter(n=>n!==".mistflow").length===0:!1}catch{return!1}}function Yp(t,e){let r=Vp(e),n=be(t,r);if(Vi(n))return n;for(let o=2;o<=50;o++){let s=be(t,`${r}-${o}`);if(Vi(s))return s}return be(t,`${r}-${Date.now()}`)}function Qp(t,e){if(e)return!0;let r=t.toLowerCase(),n=/\b(build|create|make|scaffold|start|generate)\b/.test(r),o=/\b(app|application|website|site|web\s+app|landing\s+page|dashboard|tool|marketplace|game|blog|portfolio|crm)\b/.test(r),s=/\b(add|change|fix|update|edit|refactor|debug|review)\b/.test(r)&&!n;return n&&o&&!s}function Yi(t){try{Bt(t,{recursive:!0});return}catch(e){return e instanceof Error?e.message:String(e)}}function Qi(t){let{projectPath:e,description:r,confirmToken:n,suggestedPath:o,previousTokenInvalid:s}=t;return JSON.stringify({status:"confirm_new_project",requires_user_input:!0,projectPath:e,description:r,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.",s?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
1855
|
+
`)})}function Zp(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 eu(t){let e=be(Ct(),".mistflow","plans",`${t}.json`);if(!ft(e))return null;try{return JSON.parse(qn(e,"utf-8")).plan??null}catch{return null}}async function tu(t){let e=Date.now(),r=5e4,n=2e3;for(;Date.now()-e<r;){try{let o=await ar(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 s=o instanceof Error?o.message:String(o);if(s.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll failed: ${s}`)}await new Promise(o=>setTimeout(o,n))}return console.error("[plan] directions poll exhausted (50s) \u2014 preserving pending so host re-polls"),t}function nu(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function ru(t,e){for(let r of e){let n=nu(t[r]);if(n)return n}}function ou(t){return ru(t,["mockup_url","mockupUrl","preview_url","previewUrl","live_url","liveUrl","deploy_url","deployUrl","url"])}function qt(t,e){return`Next action: call ${t} with ${JSON.stringify(e)}. Do not omit sessionId.`}function Xi(t){return t?.length?t.map((e,r)=>{let n=typeof e.text=="string"?e.text:typeof e.question=="string"?e.question:`Question ${r+1}`,o=Array.isArray(e.options)?e.options.map(s=>{if(s&&typeof s=="object"&&"label"in s){let i=s.label;return typeof i=="string"?i:null}return typeof s=="string"?s:null}).filter(s=>!!s):[];return o.length?`${r+1}. ${n} Options: ${o.join(", ")}`:`${r+1}. ${n}`}):["No questions were returned by the backend."]}function su(t){let e=ou(t),r=t.reason?`
|
|
1856
|
+
Reason: ${t.reason}`:"";switch(t.state){case"COMPLETE":return`Session complete.${e?` Live URL: ${e}`:""}${r}`;case"CANCELLED":return`Session was cancelled.${r}`;case"FAILED":return`Session ended in FAILED.${e?` Last known URL: ${e}`:""}${r}`;case"ABANDONED":return`Session was abandoned.${r}`;case"EXPIRED":return`Session expired.${r}`;default:return`Session finished with state ${t.state}.${e?` URL: ${e}`:""}${r}`}}async function iu(t,e){let{description:r,projectPath:n,sessionId:o,conversationId:s,answers:i,existingPlan:a,existingPlanId:l,templateToken:c,remixDescription:u,autonomous:d,language:m,brandMentioned:h,confirmToken:_,urlChoice:P,designConversationId:y,designDirection:v,userConfirmedCustom:N,forceNew:K}=t;if(o&&!s&&!y)try{let g=await Xt(o),b=[`Session ID: ${g.session_id}`,`Status: ${g.status??"active"}`,`Instruction: ${g.instruction}`];switch(g.reason&&b.push(`Reason: ${g.reason}`),g.instruction){case"wait":return p([...b,`Next action: ${g.reason??"The backend is still preparing the next step."} Tell the user briefly what's happening, then call mist_plan with { projectPath, sessionId: "${g.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(`
|
|
1857
|
+
`));case"resume_conversation":{let C=g.conversation_id;return p([...b,`In-flight conversation: ${C??"(missing \u2014 backend bug)"}`,`Next action: call mist_plan with { projectPath, conversationId: "${C??""}" } 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(`
|
|
1858
|
+
`))}case"continue":return p([...b,`Next action: ${g.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(`
|
|
1859
|
+
`));case"call_mist_init":return p([...b,qt("mist_init",{sessionId:g.session_id,path:n})].join(`
|
|
1860
|
+
`));case"call_mist_deploy":return p([...b,qt("mist_deploy",{sessionId:g.session_id,projectPath:n})].join(`
|
|
1861
|
+
`));case"ask_user":return p([...b,"Next action: ask the user these questions, then submit the answers through the session flow.",...Xi(g.questions)].join(`
|
|
1862
|
+
`));case"pick_design":return p([...b,"Next action: ask the user to pick one of these design directions, then submit the choice through the session flow.",...Xi(g.directions??g.questions)].join(`
|
|
1863
|
+
`));case"review_mockup":return p([...b,qt("mist_mockup",{sessionId:g.session_id,projectPath:n})].join(`
|
|
1864
|
+
`));case"call_mist_install":return p([...b,qt("mist_install",{sessionId:g.session_id,projectPath:n})].join(`
|
|
1865
|
+
`));case"call_mist_implement":return p([...b,qt("mist_implement",{sessionId:g.session_id,projectPath:n})].join(`
|
|
1866
|
+
`));case"call_mist_build":return p([...b,qt("mist_build",{sessionId:g.session_id,projectPath:n})].join(`
|
|
1867
|
+
`));case"call_mist_qa":return p([...b,qt("mist_qa",{sessionId:g.session_id,projectPath:n})].join(`
|
|
1868
|
+
`));case"review_plan":return p([...b,`Next action: ${g.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(`
|
|
1869
|
+
`));case"done":return p([...b,su(g)].join(`
|
|
1870
|
+
`))}}catch(g){let b=g instanceof Error?g.message:String(g);return p(`Could not poll session '${o}': ${b}`,!0)}if(s&&!r&&!i&&!y&&!v&&!a&&!l&&!c)try{let g=await dr(s);if(g.status==="clarify_pending"||g.status==="plan_pending"){let A=typeof g.phase_hint=="string"?g.phase_hint:null,O=typeof g.elapsed_seconds=="number"?g.elapsed_seconds:null,Y=typeof g.progress=="number"?g.progress:null,Q=g.status==="plan_pending",se=Q?"generating_plan":"generating_questions",we=A?`${A}${O!==null?` (${O}s elapsed)`:""}`:Q?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return p(JSON.stringify({status:"running",conversationId:s,phase:se,...A?{phaseHint:A}:{},...O!==null?{elapsedSeconds:O}:{},...Y!==null?{progress:Y}:{},nextAction:`${we}. Tell the user briefly what's happening (e.g. "${A??(Q?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${s}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}if(g.status==="design_clarify"&&Array.isArray(g.directions)){let O=g.directions.map((j,Xe)=>({id:j.id??String(Xe),name:j.name??`Direction ${Xe+1}`,summary:j.summary,hero_headline:j.hero_headline,cta_text:j.cta_text,body_sample:j.body_sample,fonts:j.fonts,colors:j.colors,hero_treatment:j.hero_treatment,shape_lang:j.shape_lang,texture:j.texture,decoration_hint:j.decoration_hint})),Y=g.plan?.name??"your app",Q=g.design_conversation_id,se={},we=!1;try{if(Q){let U=Date.now();for(;Date.now()-U<5e4;){let Ee=await cr(Q),Ae=0;for(let Ne of O){let xe=Ee[Ne.id];xe&&((xe.status==="done"||xe.status==="ready")&&typeof xe.html=="string"&&xe.html.length>0?(se[Ne.id]=xe.html,Ae+=1):xe.status==="failed"&&(Ae+=1))}if(Ae===O.length){we=!0;break}await new Promise(Ne=>setTimeout(Ne,5e3))}}}catch(j){console.error(`[mist_plan:design_clarify] render poll failed: ${j instanceof Error?j.message:String(j)}`)}if(!we)return p(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:s,design_conversation_id:Q,renderedSoFar:Object.keys(se).length,totalDirections:O.length,nextAction:`${Object.keys(se).length}/${O.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${s}" } 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 X=O.filter(j=>se[j.id]),Z,Ce,L=be(n,".mistflow"),me=be(L,"design-directions.html"),ve=be(L,"picker-state.json"),pe=!1;if(Q)try{ft(ve)&&JSON.parse(qn(ve,"utf-8")).opened_for_design_cid===Q&&(pe=!0)}catch{}try{if(Bt(L,{recursive:!0}),pe)Z=me;else{let j=Ho(Y,X,se);Tt(me,j,"utf-8"),Z=me;let Xe=Bo(`file://${me}`);Xe.opened||(Ce=Xe.reason),Q&&Tt(ve,JSON.stringify({opened_for_design_cid:Q,opened_at:new Date().toISOString()},null,2),"utf-8")}}catch(j){console.error(`[mist_plan:design_clarify] picker write/open failed: ${j instanceof Error?j.message:String(j)}`)}let ce=X.map(j=>({id:j.id,name:j.name})),Ue=ce.map(j=>j.name).filter(Boolean);return p(JSON.stringify({status:"design_clarify",previewPath:Z,previewOpenError:Ce,directionRefs:ce,directionNames:Ue,design_conversation_id:Q,conversation_id:s,nextAction:[`The visual picker has been opened in the user's browser at file://${Z??"(path missing)"} \u2014 every direction is a real, rendered landing page. The user is looking at it now.`,Ce?`(auto-open suppressed: ${Ce} \u2014 tell the user to open file://${Z} manually)`:"",`Now use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names as options: ${Ue.map(j=>`"${j}"`).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: "${s}", designConversationId: "${Q}", 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(`
|
|
1871
|
+
|
|
1872
|
+
`)}))}let b=new Set(["clarify","ready","design_clarify_pending","design_clarify"]),C=typeof g.status=="string"?g.status:"";return b.has(C)?p(JSON.stringify(g)):p(JSON.stringify(g),!0)}catch(g){let b=g instanceof Error?g.message:String(g);return p(`Could not poll plan conversation '${s}': ${b}`,!0)}let z=r??"";if(!z.trim()&&!s&&!y&&!a&&!l&&!c)return p("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(y&&!v&&!z.trim()&&!i)return p(`You passed designConversationId='${y}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${y}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let re=a;if(!re&&l&&(re=eu(l)??void 0,!re))return p("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let de=s;if(!Ie())return je("plan a new app");let te,B;if(!de&&!re&&!c&&!y){if(!Fp(n))return p(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let g=Jp(n);if(g!=="mistflow"&&Kp(n))return p(JSON.stringify({status:"unsafe_cwd",projectPath:n,instruction:[`The projectPath you passed (${n}) is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Create the subfolder at ${n}/<subfolder-name>.`," 3. Call mist_plan again with the SAME description and projectPath set to the new subfolder.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description."].join(`
|
|
1873
|
+
`)}),!0);if(g==="foreign"){let b=_?Gp(_,n,z):!1,C=Yp(n,z),A=Qp(z,h);if(A||b){B=C;let O=Yi(B);if(O)return p(`Mistflow could not create the scaffold directory at ${B}: ${O}`,!0);te=`Note: Mistflow will scaffold the new app at \`${B}\`. The existing project at \`${n}\` is not modified.`}if(!b&&!A){let O=Wp(n,z);if(e?.server){let Y=await Un(e.server,[{question:"You're inside an existing project. Where should Mistflow scaffold the new app?",decisionKey:"scopeChoice",recommended:`Create at: ${C}`,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: ${C}`,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
|
|
2172
1874
|
|
|
2173
1875
|
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.
|
|
2174
1876
|
|
|
2175
|
-
Default path: \`${x}\``,"scope");if(J.outcome==="submitted"){let oe=J.answers?.[0]?.answer??"",le=oe.toLowerCase(),we=oe.startsWith("/")?oe:null;if(we||le.startsWith("create at:")||le.startsWith("choose a different path")){let I=we||(le.startsWith("choose a different path")?null:x);if(!I)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);q=I;let Q=Ui(q);if(Q)return d(`Mistflow could not create the scaffold directory at ${q}: ${Q}`,!0);X=`Note: Mistflow will scaffold the new app at \`${q}\`. The existing project at \`${n}\` is not modified.`}else return le.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 J.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(Fi({projectPath:n,description:Y,confirmToken:N,suggestedPath:x,previousTokenInvalid:!!F}))}else return d(Fi({projectPath:n,description:Y,confirmToken:N,suggestedPath:x,previousTokenInvalid:!!F}))}}}if(c)try{if(!(await xo(c)).plan)return d("This template has no plan to fork. Try a different template.",!0);let y=await So(c),x=y.plan,O="";if(m&&y.has_source)try{let Q=await pr(y.plan,m),fe=Q.plan??Q,te=Q.diff,ve=fe?.steps??[],Oe=new Set([...(te?.added??[]).map(ke=>ke.number),...(te?.modified??[]).map(ke=>ke.number)]),ye=ve.map(ke=>{let Gt=ke.number;return Oe.has(Gt)?{...ke,status:"pending"}:{...ke,status:"completed",source:"forked"}});fe.steps=ye,x=fe;let R=ye.filter(ke=>ke.status==="pending").length;O=` Remixed: ${ye.filter(ke=>ke.status==="completed").length} steps unchanged, ${R} steps need re-implementation.`}catch(Q){console.error("[plan] Remix failed, using original plan:",Q),O=" (Remix failed \u2014 using original plan. You can modify it later.)"}let N=Li(),J=Se(_t(),".mistflow","plans");qt(J,{recursive:!0}),St(Se(J,`${N}.json`),JSON.stringify({plan:x,projectId:y.id,sourceDeploymentId:y.source_deployment_id,forkToken:y.fork_token,requiredEnvVars:y.required_env_vars,dbProvider:y.db_provider}));let oe=x?.name??"forked-app",le=y.has_source,we=le?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",I=y.deploy_url?` Instant deploy started \u2014 your app will be live at ${y.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:N,forkedFrom:y.forked_from,projectId:y.id,hasSource:le,deployUrl:y.deploy_url,message:`Forked "${y.forked_from}" into your workspace.${O}${I} ${we} NEXT: Call mist_init, name='${oe}', and planId='${N}' to create the project now.`}))}catch(g){let y=g instanceof Error?g.message:"Failed to fork template";return d(y,!0)}if(ne){let g;if(n){let I=Se(n,"PLAN.md");if(pt(I))try{g=Un(I,"utf-8")}catch(Q){console.error(`[mist_plan:modify] PLAN.md read failed (${I}): ${Q instanceof Error?Q.message:String(Q)}`)}}let y;try{y=await pr(ne,Y,{planMd:g})}catch(I){let Q=I instanceof Error?I.message:"Failed to modify plan";return d(Q,!0)}let x=y.plan,O=y.diff,N=typeof y.plan_md=="string"?y.plan_md:null,J,oe;if(N&&n)try{let I=Se(n,"PLAN.md");St(I,N,"utf-8"),J=I}catch(I){oe=I instanceof Error?I.message:String(I)}let le=[];if(O?.added?.length){let I=O.added.map(Q=>Q.title);le.push(`Added ${I.length} step(s): ${I.join(", ")}`)}if(O?.removed?.length){let I=O.removed.map(Q=>Q.title);le.push(`Removed ${I.length} step(s): ${I.join(", ")}`)}if(O?.modified?.length){let I=O.modified.map(Q=>Q.title);le.push(`Modified ${I.length} step(s): ${I.join(", ")}`)}let we=le.length>0?le.join(". "):"No changes detected.";return d(JSON.stringify({plan:x,diff:O,planMdPath:J,planMdError:oe,message:`Plan modified. ${we}. Update mistflow.json with the new plan${J?"; PLAN.md has been regenerated at "+J:""}, then continue with mist_implement.`}))}let M=T?.trim()||void 0,L=i;if(Array.isArray(i)){let g=i.findIndex(y=>y&&typeof y=="object"&&y.decisionKey==="urlChoice");if(g>=0){let y=i[g];!M&&y.answer&&(M=y.answer);let x=i.slice(0,g).concat(i.slice(g+1));L=x.length>0?x:void 0}}else if(i!=null){let g=i;if(!M&&kr in g&&(M=g[kr]),!M&&"urlChoice"in g&&(M=g.urlChoice),kr in g||"urlChoice"in g){let{[kr]:y,urlChoice:x,...O}=g;L=Object.keys(O).length>0?O:void 0}}if(M&&(M=M.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),M){let g=M.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(g)?M=g:(console.error(`[mist_plan] Discarding urlChoice '${M}' \u2014 does not look like a subdomain. Backend will auto-generate.`),M=void 0)}let ee;if(w){ee={...w},delete ee.userConfirmedCustom,delete ee.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[y,x]of Object.entries(g))w[y]!==void 0&&ee[x]===void 0&&(ee[x]=w[y])}let re=ee!==void 0&&typeof ee.custom=="string"&&!ee.id&&!ee.name,k=E===!0||w!==void 0&&(w.userConfirmedCustom===!0||w.user_confirmed_custom===!0);if(re&&S)try{let g=await ir(S);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: '${S}' } to keep polling. When directions are ready (status: 'design_clarify'), surface them to the user via AskUserQuestion. Custom is only legitimate AFTER the user has seen the real options and explicitly rejected them \u2014 never as a workaround for a slow generation run.`,!0);if(g.status==="ready"&&Array.isArray(g.directions)&&g.directions.length>0&&!k){let y=g.directions.map(x=>x.name).join(", ");return d(`Refusing to submit a custom design direction: the backend has ${g.directions.length} real directions ready (${y}). The picker is mandatory \u2014 you must surface those exact directions to the user via AskUserQuestion before submitting any pick. Re-call mist_plan with { conversationId, designConversationId: '${S}' } to get the picker payload (status: 'design_clarify'), render the directions HTML preview at .mistflow/design-directions.html for the user, then submit the user's choice. If the user opens the preview, sees the ${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 B=i?"Generating plan with your answers (LLM call)":S?"Finalizing design direction":"Thinking through discovery questions",D=e?Xe(e.server,e.progressToken,()=>B):{stop:()=>{}};if(e&&(e.cleanup=()=>D.stop()),!o&&!s&&!S&&!a&&!l&&!c&&!F&&Y.trim().length>0&&!V)try{let g=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),y=336*60*60*1e3,x=Date.now()-y,N=(await Pn(Di())).filter(J=>!g.has(J.state)).filter(J=>{let oe=Date.parse(J.updated_at);return Number.isFinite(oe)&&oe>=x}).sort((J,oe)=>Date.parse(oe.updated_at)-Date.parse(J.updated_at)).slice(0,5);if(N.length>0)return D.stop(),d(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:N.map(J=>({sessionId:J.id,state:J.state,description:J.description,currentStep:J.current_step,awaitingInput:J.awaiting_input,updatedAt:J.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 ge=o,P;try{ce&&!L&&!S&&!ne&&!l?P=await cr(ce):P=await dr(Y,{conversationId:ce,answers:L,autonomous:p,language:u,designConversationId:S,designDirection:ee})}catch(g){D.stop();let y=g instanceof Error?g.message:"Failed to generate plan";return d(y,!0)}let Fe=P.session_id;if(!ge&&Fe){ge=Fe;try{await Tn(Fe,{machine_id:Di(),local_path:n})}catch(g){console.error("workspace bind failed (resume offers will miss this session):",g instanceof Error?g.message:g)}}if(P.status==="clarify_pending"){D.stop();let g=P;return d(JSON.stringify({status:"running",conversationId:g.conversation_id,sessionId:ge,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.${ge?` Carry sessionId="${ge}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(P.status==="plan_pending"){D.stop();let g=P;return d(JSON.stringify({status:"running",conversationId:g.conversation_id,sessionId:ge,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(P.status==="design_clarify_pending"&&(B="Generating creative design directions",P=await Gp(P)),P.status==="design_clarify_pending")return D.stop(),d(JSON.stringify({status:"running",conversationId:s,designConversationId:P.design_conversation_id,sessionId:ge,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: "${s??""}" } 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(D.stop(),P.status==="clarify"){let g=P.reflection||"",y=P.suggestedName||"",x=P.suggestedFeatures??[],O=P.questions??[],N=O.some(te=>Array.isArray(te.options)&&typeof te.options[0]=="object"&&te.options[0]?.label),J={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",surfaceMcp:"AI access",surfaceBackgroundJobs:"Scheduled tasks",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},oe=O.map(te=>{let ve=te.decisionKey&&J[te.decisionKey]||zp(te.question),Oe;return N&&Array.isArray(te.options)?Oe=te.options.map(ye=>({label:ye.label,description:ye.description??""})):Array.isArray(te.options)?Oe=te.options.map((ye,R)=>({label:R===0?`${ye} (Recommended)`:String(ye),description:te.why??""})):Oe=[{label:"Yes (Recommended)",description:te.why??""},{label:"No",description:""}],{question:te.question,header:ve,options:Oe,multiSelect:!1}}),we=P.decisions?.audienceType??null,I=x.length>0?Ni(Y,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:we,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null,surfaceMcp:null,surfaceBackgroundJobs:null},{suggestedName:y,suggestedFeatures:x,language:u}):null,Q=I?Oi(I):"",fe=wr(y||"my-app").slice(0,32);try{let te=await sr(fe);!te.available&&te.suggestion&&(fe=te.suggestion)}catch{}if(Q&&(Q+=`
|
|
1877
|
+
Default path: \`${C}\``,"scope");if(Y.outcome==="submitted"){let Q=Y.answers?.[0]?.answer??"",se=Q.toLowerCase(),we=Q.startsWith("/")?Q:null;if(we||se.startsWith("create at:")||se.startsWith("choose a different path")){let X=we||(se.startsWith("choose a different path")?null:C);if(!X)return p("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);B=X;let Z=Yi(B);if(Z)return p(`Mistflow could not create the scaffold directory at ${B}: ${Z}`,!0);te=`Note: Mistflow will scaffold the new app at \`${B}\`. The existing project at \`${n}\` is not modified.`}else return se.startsWith("cancel")?p("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(`User submitted an unrecognized scope choice: ${Q}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return Y.outcome==="declined"?p("User declined the scope confirmation. They wanted to edit the existing project, not create a new Mistflow app. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(Qi({projectPath:n,description:z,confirmToken:O,suggestedPath:C,previousTokenInvalid:!!_}))}else return p(Qi({projectPath:n,description:z,confirmToken:O,suggestedPath:C,previousTokenInvalid:!!_}))}}}if(c)try{if(!(await _o(c)).plan)return p("This template has no plan to fork. Try a different template.",!0);let b=await To(c),C=b.plan,A="";if(u&&b.has_source)try{let Z=await ur(b.plan,u),Ce=Z.plan??Z,L=Z.diff,me=Ce?.steps??[],ve=new Set([...(L?.added??[]).map(j=>j.number),...(L?.modified??[]).map(j=>j.number)]),pe=me.map(j=>{let Xe=j.number;return ve.has(Xe)?{...j,status:"pending"}:{...j,status:"completed",source:"forked"}});Ce.steps=pe,C=Ce;let ce=pe.filter(j=>j.status==="pending").length;A=` Remixed: ${pe.filter(j=>j.status==="completed").length} steps unchanged, ${ce} steps need re-implementation.`}catch(Z){console.error("[plan] Remix failed, using original plan:",Z),A=" (Remix failed \u2014 using original plan. You can modify it later.)"}let O=Ki(),Y=be(Ct(),".mistflow","plans");Bt(Y,{recursive:!0}),Tt(be(Y,`${O}.json`),JSON.stringify({plan:C,projectId:b.id,sourceDeploymentId:b.source_deployment_id,forkToken:b.fork_token,requiredEnvVars:b.required_env_vars,dbProvider:b.db_provider}));let Q=C?.name??"forked-app",se=b.has_source,we=se?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",X=b.deploy_url?` Instant deploy started \u2014 your app will be live at ${b.deploy_url} in under a minute.`:"";return p(JSON.stringify({planId:O,forkedFrom:b.forked_from,projectId:b.id,hasSource:se,deployUrl:b.deploy_url,message:`Forked "${b.forked_from}" into your workspace.${A}${X} ${we} NEXT: Call mist_init, name='${Q}', and planId='${O}' to create the project now.`}))}catch(g){let b=g instanceof Error?g.message:"Failed to fork template";return p(b,!0)}if(re){let g;if(n){let X=be(n,"PLAN.md");if(ft(X))try{g=qn(X,"utf-8")}catch(Z){console.error(`[mist_plan:modify] PLAN.md read failed (${X}): ${Z instanceof Error?Z.message:String(Z)}`)}}let b;try{b=await ur(re,z,{planMd:g})}catch(X){let Z=X instanceof Error?X.message:"Failed to modify plan";return p(Z,!0)}let C=b.plan,A=b.diff,O=typeof b.plan_md=="string"?b.plan_md:null,Y,Q;if(O&&n)try{let X=be(n,"PLAN.md");Tt(X,O,"utf-8"),Y=X}catch(X){Q=X instanceof Error?X.message:String(X)}let se=[];if(A?.added?.length){let X=A.added.map(Z=>Z.title);se.push(`Added ${X.length} step(s): ${X.join(", ")}`)}if(A?.removed?.length){let X=A.removed.map(Z=>Z.title);se.push(`Removed ${X.length} step(s): ${X.join(", ")}`)}if(A?.modified?.length){let X=A.modified.map(Z=>Z.title);se.push(`Modified ${X.length} step(s): ${X.join(", ")}`)}let we=se.length>0?se.join(". "):"No changes detected.";return p(JSON.stringify({plan:C,diff:A,planMdPath:Y,planMdError:Q,message:`Plan modified. ${we}. Update mistflow.json with the new plan${Y?"; PLAN.md has been regenerated at "+Y:""}, then continue with mist_implement.`}))}let R=P?.trim()||void 0,oe=i;if(Array.isArray(i)){let g=i.findIndex(b=>b&&typeof b=="object"&&b.decisionKey==="urlChoice");if(g>=0){let b=i[g];!R&&b.answer&&(R=b.answer);let C=i.slice(0,g).concat(i.slice(g+1));oe=C.length>0?C:void 0}}else if(i!=null){let g=i;if(!R&&xr in g&&(R=g[xr]),!R&&"urlChoice"in g&&(R=g.urlChoice),xr in g||"urlChoice"in g){let{[xr]:b,urlChoice:C,...A}=g;oe=Object.keys(A).length>0?A:void 0}}if(R&&(R=R.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),R){let g=R.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(g)?R=g:(console.error(`[mist_plan] Discarding urlChoice '${R}' \u2014 does not look like a subdomain. Backend will auto-generate.`),R=void 0)}let W;if(v){W={...v},delete W.userConfirmedCustom,delete W.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[b,C]of Object.entries(g))v[b]!==void 0&&W[C]===void 0&&(W[C]=v[b])}let ae=W!==void 0&&typeof W.custom=="string"&&!W.id&&!W.name,T=N===!0||v!==void 0&&(v.userConfirmedCustom===!0||v.user_confirmed_custom===!0);if(ae&&y)try{let g=await ar(y);if(g.status==="pending")return p(`Refusing to submit a custom design direction: the backend's direction-generation BG task is still running (status: pending). The user has not yet had the chance to see the real directions. Stop asking the user about aesthetic / fonts / colors / mood right now \u2014 the backend will produce 3-4 concrete options shortly. Re-call mist_plan with { projectPath, conversationId, designConversationId: '${y}' } 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&&!T){let b=g.directions.map(C=>C.name).join(", ");return p(`Refusing to submit a custom design direction: the backend has ${g.directions.length} real directions ready (${b}). 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: '${y}' } 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 H=i?"Generating plan with your answers (LLM call)":y?"Finalizing design direction":"Thinking through discovery questions",$=e?rt(e.server,e.progressToken,()=>H):{stop:()=>{}};if(e&&(e.cleanup=()=>$.stop()),!o&&!s&&!y&&!a&&!l&&!c&&!_&&z.trim().length>0&&!K)try{let g=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),b=336*60*60*1e3,C=Date.now()-b,O=(await Rn(Ji())).filter(Y=>!g.has(Y.state)).filter(Y=>{let Q=Date.parse(Y.updated_at);return Number.isFinite(Q)&&Q>=C}).sort((Y,Q)=>Date.parse(Q.updated_at)-Date.parse(Y.updated_at)).slice(0,5);if(O.length>0)return $.stop(),p(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:O.map(Y=>({sessionId:Y.id,state:Y.state,description:Y.description,currentStep:Y.current_step,awaitingInput:Y.awaiting_input,updatedAt:Y.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=o,S;try{de&&!oe&&!y&&!re&&!l?S=await dr(de):S=await pr(z,{conversationId:de,answers:oe,autonomous:d,language:m,designConversationId:y,designDirection:W})}catch(g){$.stop();let b=g instanceof Error?g.message:"Failed to generate plan";return p(b,!0)}let qe=S.session_id;if(!ne&&qe){ne=qe;try{await Pn(qe,{machine_id:Ji(),local_path:n})}catch(g){console.error("workspace bind failed (resume offers will miss this session):",g instanceof Error?g.message:g)}}if(S.status==="clarify_pending"){$.stop();let g=S;return p(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(S.status==="plan_pending"){$.stop();let g=S;return p(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(S.status==="design_clarify_pending"&&(H="Generating creative design directions",S=await tu(S)),S.status==="design_clarify_pending")return $.stop(),p(JSON.stringify({status:"running",conversationId:s,designConversationId:S.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: "${s??""}" } 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(),S.status==="clarify"){let g=S.reflection||"",b=S.suggestedName||"",C=S.suggestedFeatures??[],A=S.questions??[],O=A.some(L=>Array.isArray(L.options)&&typeof L.options[0]=="object"&&L.options[0]?.label),Y={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",surfaceMcp:"AI access",surfaceBackgroundJobs:"Scheduled tasks",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},Q=A.map(L=>{let me=L.decisionKey&&Y[L.decisionKey]||Zp(L.question),ve;return O&&Array.isArray(L.options)?ve=L.options.map(pe=>({label:pe.label,description:pe.description??""})):Array.isArray(L.options)?ve=L.options.map((pe,ce)=>({label:ce===0?`${pe} (Recommended)`:String(pe),description:L.why??""})):ve=[{label:"Yes (Recommended)",description:L.why??""},{label:"No",description:""}],{question:L.question,header:me,options:ve,multiSelect:!1}}),we=S.decisions?.audienceType??null,X=C.length>0?Hi(z,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:we,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null,surfaceMcp:null,surfaceBackgroundJobs:null},{suggestedName:b,suggestedFeatures:C,language:m}):null,Z=X?zi(X):"",Ce=vr(b||"my-app").slice(0,32);try{let L=await ir(Ce);!L.available&&L.suggestion&&(Ce=L.suggestion)}catch{}if(Z&&(Z+=`
|
|
2176
1878
|
|
|
2177
|
-
**Your app URL (you can change this before scaffolding):** https://${
|
|
2178
|
-
`),
|
|
2179
|
-
`)}))}if(
|
|
2180
|
-
`):`## ${
|
|
1879
|
+
**Your app URL (you can change this before scaffolding):** https://${Ce}.mistflow.app`),e?.server){let L=[b?`## ${b}`:"## 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(`
|
|
1880
|
+
`),me=await Un(e.server,A,L,"clarify");if(me.outcome==="submitted"){$.stop();let ve={};for(let ce of me.answers??[])ce.decisionKey?ve[ce.decisionKey]=ce.answer:ve[ce.question]=ce.answer;let pe=me.urlChoice?.trim();pe&&(pe=pe.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let ce=await pr(z,{conversationId:S.conversation_id,answers:ve,autonomous:d,language:m});if(ce.status==="plan_pending"){let Ue=ce;return p(JSON.stringify({status:"running",conversationId:Ue.conversation_id,phase:"generating_plan",...pe?{urlChoice:pe}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${Ue.conversation_id}"${pe?`, urlChoice: "${pe}"`:""} } 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=ce}catch(ce){let Ue=ce instanceof Error?ce.message:String(ce);return p(`Submitting your answers failed: ${Ue}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(me.outcome==="declined")return $.stop(),p("User declined the planning flow via the form. They likely want a different approach \u2014 ask them what they'd prefer instead of re-running mist_plan.",!0);if(me.outcome==="cancelled")return $.stop(),p("User cancelled the planning form without picking. The conversation is still alive \u2014 re-run mist_plan with the same conversationId if they want to retry, or start a fresh plan if they want to change the description.",!0);me.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${me.errorMessage}) \u2014 falling back to prose flow.`)}}return p(JSON.stringify({status:"clarify",requires_user_input:!0,nextAction:"STOP \u2014 DO NOT submit answers yourself. Render every entry in `askUserQuestions` via your host's native question tool (AskUserQuestion in Claude Code, request_user_input in OpenAI Codex Plan mode, quick pick in Cursor) and WAIT for the user to actually answer. If your host has no native question tool, stop your turn, print the questions verbatim as a numbered list with all options visible, and wait for the user's next message. Calling mist_plan with answers in the same turn you received the questions is ALWAYS wrong, regardless of how obvious `recommended` looks.",conversation_id:S.conversation_id,questions:A,questionCount:A.length,suggestedFeatures:C,suggestedName:b,suggestedSubdomain:Ce,reflection:g,briefText:Z,askUserQuestions:Q,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:["\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST ask the user via your host's native structured-question","tool (not a text prompt, not a bash echo, not a chat message).","The user has to actually choose. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","Per host (use whichever applies):"," \u2022 Claude Code \u2192 AskUserQuestion tool"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) \u2192 request_user_input returns"," 'unavailable in <mode> mode'. When you see that error, STOP"," your turn, print the questions as a numbered chat message"," with all options visible, and wait for the user's next"," message. Do NOT resume by picking answers yourself."," \u2022 Any host without a native question tool \u2192 same as above:"," stop your turn, print the questions, wait.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 'Locking in the defaults with X as the only override.'"," (inferring answers from the original spec)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping the question UI because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call the tool (when available): pass each object in the","`askUserQuestions` array below. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${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: "${Ce}".`,'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.',...g||Z?["","\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",...g?[g]:[],...Z?["",Z]:[]]:[],...te?["",te]:[]].join(`
|
|
1881
|
+
`)}))}if(S.status==="design_clarify"){let g=S.directions??[],b=S.plan.name??"your app",C=S.design_conversation_id,A=g.map(U=>({id:U.id,name:U.name,summary:U.summary,hero_headline:U.hero_headline,cta_text:U.cta_text,body_sample:U.body_sample,fonts:U.fonts,colors:U.colors,hero_treatment:U.hero_treatment,shape_lang:U.shape_lang,texture:U.texture,decoration_hint:U.decoration_hint})),O={},Y=!1;try{if(C){let Ae=Date.now();for(;Date.now()-Ae<5e4;){let Ne=await cr(C),xe=0;for(let pt of A){let ge=Ne[pt.id];ge&&((ge.status==="done"||ge.status==="ready")&&typeof ge.html=="string"&&ge.html.length>0?(O[pt.id]=ge.html,xe+=1):ge.status==="failed"&&(xe+=1))}if(xe===A.length){Y=!0;break}await new Promise(pt=>setTimeout(pt,5e3))}}}catch(U){console.error(`[mist_plan:design_clarify] render poll failed: ${U instanceof Error?U.message:String(U)}`)}if(!Y)return p(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:S.conversation_id??s,design_conversation_id:C,renderedSoFar:Object.keys(O).length,totalDirections:A.length,nextAction:`${Object.keys(O).length}/${A.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${S.conversation_id??s??""}" } again IMMEDIATELY \u2014 do NOT bash sleep. Do NOT ask the user about design yet.`}));let Q=A.filter(U=>O[U.id]),se,we,X=be(n,".mistflow"),Z=be(X,"design-directions.html"),Ce=be(X,"picker-state.json"),L=()=>{try{if(ft(Ce))return JSON.parse(qn(Ce,"utf-8"))}catch{}return{}},me=U=>{try{Bt(X,{recursive:!0}),Tt(Ce,JSON.stringify(U,null,2),"utf-8")}catch(Ee){console.error(`[mist_plan:design_clarify] sidecar write failed: ${Ee instanceof Error?Ee.message:String(Ee)}`)}},ve=L(),pe=C&&ve.opened_for_design_cid===C;try{if(Bt(X,{recursive:!0}),pe)se=Z;else{let U=Ho(b,Q,O);Tt(Z,U,"utf-8"),se=Z;let Ee=Bo(`file://${Z}`);Ee.opened||(we=Ee.reason),C&&me({opened_for_design_cid:C,elicit_state:"pending",elicit_design_cid:C,opened_at:new Date().toISOString()})}}catch(U){console.error(`[mist_plan:design_clarify] picker write/open failed: ${U instanceof Error?U.message:String(U)}`)}let ce=L(),Ue=Q.map(U=>({id:U.id,name:U.name})),j=Ue.map(U=>U.name).filter(Boolean);if(e?.server&&C&&ce.elicit_design_cid===C&&ce.elicit_state==="pending"){let U=se?[`## ${b} \u2014 pick a creative direction`,"",`${Q.length} directions, each with its own fonts, colors, and mood.`,"",`Visual preview (auto-opened in your browser): file://${se}`,"Each card shows what you'd be picking \u2014 fonts, colors, hero layout."].join(`
|
|
1882
|
+
`):`## ${b} \u2014 pick a creative direction
|
|
2181
1883
|
|
|
2182
|
-
${
|
|
1884
|
+
${Q.length} directions, each with its own fonts, colors, and mood. Pick one or describe your own.`,Ee=Q.map(Ae=>({label:Ae.name,description:Ae.summary??""}));Ee.push({label:"Describe your own direction",description:"Skip the proposed options and type a short description of how the app should feel."});try{let Ae=await Un(e.server,[{question:`${b} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,decisionKey:"designDirection",options:Ee,noOtherSentinel:!0,otherFieldTitle:"If 'Describe your own direction' was picked: type how the app should feel (fonts, colors, mood \u2014 your words)."}],U,"design");if(Ae.outcome==="submitted"&&Ae.answers?.[0]){let Ne=Ae.answers[0].answer.trim(),xe=Q.find(ge=>ge.name===Ne),pt=xe?{direction_id:xe.id}:{custom:Ne};(S.conversation_id??s)&&(pt.conversation_id=S.conversation_id??s);try{let ge=await lr(C,pt);me({...ce,elicit_state:"completed",elicit_design_cid:C}),S={status:"ready",plan:ge.plan??{},methodology:ge.methodology??"",...ge.designMd?{designMd:ge.designMd}:{}}}catch(ge){return console.error(`[mist_plan:design_clarify] submitDesignPick failed: ${ge instanceof Error?ge.message:String(ge)}`),me({...ce,elicit_state:"skipped"}),p(`Design submission failed: ${ge instanceof Error?ge.message:String(ge)}. Ask the user to retry by re-running mist_plan with their pick.`,!0)}}else return me({...ce,elicit_state:"skipped"}),p(JSON.stringify({status:"design_clarify",previewPath:se,previewOpenError:we,directionRefs:Ue,directionNames:j,design_conversation_id:C,conversation_id:S.conversation_id??s,nextAction:[`The user closed the elicit picker without picking. The visual picker is still open at file://${se??"(path missing)"}.`,`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask which direction they pick. List EXACTLY these names: ${j.map(Ne=>`"${Ne}"`).join(", ")}.`,`When they pick, call mist_plan with { projectPath, conversationId: "${S.conversation_id??s??""}", designConversationId: "${C??""}", designDirection: { id: "<id from directionRefs>" } }.`].join(`
|
|
2183
1885
|
|
|
2184
|
-
`)}))}catch(
|
|
1886
|
+
`)}))}catch(Ae){console.error(`[mist_plan:design_clarify] elicit failed: ${Ae instanceof Error?Ae.message:String(Ae)}`),me({...ce,elicit_state:"skipped"})}}if(S.status==="design_clarify")return p(JSON.stringify({status:"design_clarify",previewPath:se,previewOpenError:we,directionRefs:Ue,directionNames:j,design_conversation_id:C,conversation_id:S.conversation_id??s,nextAction:[`The visual picker is open in the user's browser at file://${se??"(path missing)"} \u2014 every direction is a real, rendered landing page.`,we?`(auto-open suppressed: ${we} \u2014 tell the user to open file://${se} manually)`:"",`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names: ${j.map(U=>`"${U}"`).join(", ")}. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${S.conversation_id??s??""}", designConversationId: "${C??""}", 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(`
|
|
2185
1887
|
|
|
2186
|
-
`)}))}if(
|
|
1888
|
+
`)}))}if(S.status!=="ready")return p(`Unexpected plan status after build: ${S.status}. Please retry by calling mist_plan with the same conversationId.`,!0);let J=S.plan,_e=J.name??"Untitled App",ke=S.methodology,ie=J.steps;if(!Array.isArray(ie)||ie.length===0)return p("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let Te=J.suggestedSubdomain??vr(_e).slice(0,32)??"my-app";if(!R&&e?.server){try{let b=await ir(Te);!b.available&&b.suggestion&&(Te=b.suggestion)}catch{}let g=await Un(e.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${Te}.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 ${Te}.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"}],`## ${_e} \u2014 pick the URL
|
|
2187
1889
|
|
|
2188
|
-
The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(g.outcome==="submitted"){let y=g.urlChoice?.trim()||g.answers?.[0]?.answer.trim()||"";y=y.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(y)||!y)&&(y=pe);let x=y.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(x)?M=x:(console.error(`[mist_plan] URL elicitation returned '${y}' \u2014 does not look like a subdomain. Using default '${pe}'.`),M=pe)}else g.outcome==="declined"||g.outcome,M=pe}else M||(M=pe);let Le=K.publicPages;if(!Le||Array.isArray(Le)&&Le.length===0){let g=K.publicLanding;if(g===!1)Le=[];else{let y=K.pages,x=_e.some(N=>typeof N.name=="string"&&N.name.toLowerCase().includes("landing")||typeof N.title=="string"&&N.title.toLowerCase().includes("landing")),O=Array.isArray(y)&&y.some(N=>N.path==="/"||N.route==="/");x||O?Le=["/","/pricing"]:g===!0?Le=["/"]:Le=["/"]}}else K.publicLanding===!1&&Le.includes("/")&&(Le=Le.filter(g=>g!=="/"));let gt=K.primaryAction;if(!gt){let g=K.features;if(Array.isArray(g)&&g.length>0){let x=g.find(N=>typeof N.priority=="string"&&N.priority.toLowerCase()==="must-have")??g[0];gt={entity:x.name??x.title??"item",action:"create",fromPage:"/dashboard"}}}let tt=K.nonNegotiables;(!tt||Array.isArray(tt)&&tt.length===0)&&(tt=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let it=Li(),Ge=Se(_t(),".mistflow","plans");qt(Ge,{recursive:!0});try{let y=Date.now();for(let x of[Ge,Se(_t(),".mistflow","mockup-state")])if(pt(x))for(let O of Bi(x))try{let N=Se(x,O),J=Hi(N).mtimeMs;y-J>6048e5&&Rp(N)}catch{}}catch{}let Ee=K,G={name:K.name,summary:K.summary,dataModel:K.dataModel,pages:K.pages,features:K.features,steps:_e.map(g=>({...g,name:g.name??g.title})),design:K.design,dbProvider:K.dbProvider??"neon",authModel:K.authModel,audienceType:K.audienceType??"b2c",roles:K.roles,defaultRole:K.defaultRole,publicPages:Le,navStyle:K.navStyle,multiTenant:K.multiTenant,surfaceType:K.surfaceType,integrations:K.integrations,primaryAction:gt,nonNegotiables:tt,requestedSubdomain:M,...u&&u.toLowerCase()!=="english"?{language:u}:{},...Ee.pickedDirection?{pickedDirection:Ee.pickedDirection}:{},...Ee.imageryBrief?{imageryBrief:Ee.imageryBrief}:{},...Ee.designConversationId?{designConversationId:Ee.designConversationId}:{}};St(Se(Ge,`${it}.json`),JSON.stringify({plan:G,methodology:be,...q?{scaffoldTargetPath:q}:{}}));let de=_e.map(g=>`${g.number}. ${g.name??g.title}`),Ne,We="";if(!!!Ee.pickedDirection){let y=(K.audienceType??"b2c")==="b2c";Ne={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:y?"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:y?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},We=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call."}let rt="",$e=[];for(let g of _e){let y=g.name??g.title,x=g.integrationId;if(x){let O=Zt(x);if(O){let N=en(O.id);$e.push({step:y,presetId:O.id,presetName:O.name,envVars:N?.envVars??[]})}}}if($e.length>0){let g=$e.flatMap(O=>O.envVars),y=[...new Set(g.map(O=>O.key))];rt=` This plan uses integrations (${$e.map(O=>O.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${y.length>0?` The user will need these API keys: ${y.join(", ")}.`:""}`}return d(JSON.stringify({planId:it,name:K.name,summary:K.summary,stepCount:_e.length,steps:de,design:K.design,...Ne?{heroPhotoQuestion:Ne}:{},...$e.length>0?{integrations:$e.map(g=>({step:g.step,preset:g.presetId,name:g.presetName,envVars:g.envVars}))}:{},message:`Plan generated for "${ae}" (${_e.length} steps).${rt}${We}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,_e.length*3)}\u2013${_e.length*5} minutes total across ${_e.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: '${it}' }). If the user says skip or "just build it", call mist_init({ planId: '${it}'${q?"":", path: '<absolute path>'"} }) immediately.`,...q?{scaffoldTargetPath:q}:{},...X?{warning:X}:{}}))}var kr,jp,Hp,Ki,Ji=v(()=>{"use strict";xe();Re();Ai();rn();Ei();fr();Mi();ji();kr="__mistflow_url_choice__",jp=600*1e3;Hp=H.object({description:H.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:H.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:H.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:H.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:H.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}},H.union([H.record(H.string()),H.array(H.object({question:H.string().optional(),decisionKey:H.string().optional(),answer:H.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:H.record(H.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:H.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:H.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:H.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:H.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:H.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:H.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:H.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:H.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:H.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:H.object({id:H.string().optional(),name:H.string().optional(),summary:H.string().optional(),heroHeadline:H.string().optional(),ctaText:H.string().optional(),bodySample:H.string().optional(),fontsHint:H.string().optional(),fonts:H.object({display:H.string(),body:H.string()}).partial().optional(),colorMood:H.string().optional(),colors:H.object({bg:H.string(),fg:H.string(),accent:H.string()}).partial().optional(),heroTreatment:H.string().optional(),shapeLang:H.string().optional(),texture:H.string().optional(),decorationHint:H.string().optional(),custom:H.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:H.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:H.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.")});Ki={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(`
|
|
2189
|
-
`),inputSchema:
|
|
1890
|
+
The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(g.outcome==="submitted"){let b=g.urlChoice?.trim()||g.answers?.[0]?.answer.trim()||"";b=b.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(b)||!b)&&(b=Te);let C=b.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(C)?R=C:(console.error(`[mist_plan] URL elicitation returned '${b}' \u2014 does not look like a subdomain. Using default '${Te}'.`),R=Te)}else g.outcome==="declined"||g.outcome,R=Te}else R||(R=Te);let We=J.publicPages;if(!We||Array.isArray(We)&&We.length===0){let g=J.publicLanding;if(g===!1)We=[];else{let b=J.pages,C=ie.some(O=>typeof O.name=="string"&&O.name.toLowerCase().includes("landing")||typeof O.title=="string"&&O.title.toLowerCase().includes("landing")),A=Array.isArray(b)&&b.some(O=>O.path==="/"||O.route==="/");C||A?We=["/","/pricing"]:g===!0?We=["/"]:We=["/"]}}else J.publicLanding===!1&&We.includes("/")&&(We=We.filter(g=>g!=="/"));let Le=J.primaryAction;if(!Le){let g=J.features;if(Array.isArray(g)&&g.length>0){let C=g.find(O=>typeof O.priority=="string"&&O.priority.toLowerCase()==="must-have")??g[0];Le={entity:C.name??C.title??"item",action:"create",fromPage:"/dashboard"}}}let it=J.nonNegotiables;(!it||Array.isArray(it)&&it.length===0)&&(it=["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=Ki(),wt=be(Ct(),".mistflow","plans");Bt(wt,{recursive:!0});try{let b=Date.now();for(let C of[wt,be(Ct(),".mistflow","mockup-state")])if(ft(C))for(let A of Zi(C))try{let O=be(C,A),Y=ea(O).mtimeMs;b-Y>6048e5&&$p(O)}catch{}}catch{}let Me=J,M={name:J.name,summary:J.summary,dataModel:J.dataModel,pages:J.pages,features:J.features,steps:ie.map(g=>({...g,name:g.name??g.title})),design:J.design,dbProvider:J.dbProvider??"neon",authModel:J.authModel,audienceType:J.audienceType??"b2c",roles:J.roles,defaultRole:J.defaultRole,publicPages:We,navStyle:J.navStyle,multiTenant:J.multiTenant,surfaceType:J.surfaceType,integrations:J.integrations,primaryAction:Le,nonNegotiables:it,requestedSubdomain:R,...m&&m.toLowerCase()!=="english"?{language:m}:{},...Me.pickedDirection?{pickedDirection:Me.pickedDirection}:{},...Me.imageryBrief?{imageryBrief:Me.imageryBrief}:{},...Me.designConversationId?{designConversationId:Me.designConversationId}:{}};Tt(be(wt,`${Qe}.json`),JSON.stringify({plan:M,methodology:ke,...B?{scaffoldTargetPath:B}:{}}));let ue=ie.map(g=>`${g.number}. ${g.name??g.title}`),Pe,Ge="";if(!!!Me.pickedDirection){let b=(J.audienceType??"b2c")==="b2c";Pe={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:b?"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:b?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},Ge=" 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 Je="",$e=[];for(let g of ie){let b=g.name??g.title,C=g.integrationId;if(C){let A=en(C);if(A){let O=tn(A.id);$e.push({step:b,presetId:A.id,presetName:A.name,envVars:O?.envVars??[]})}}}if($e.length>0){let g=$e.flatMap(A=>A.envVars),b=[...new Set(g.map(A=>A.key))];Je=` This plan uses integrations (${$e.map(A=>A.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${b.length>0?` The user will need these API keys: ${b.join(", ")}.`:""}`}return p(JSON.stringify({planId:Qe,name:J.name,summary:J.summary,stepCount:ie.length,steps:ue,design:J.design,...Pe?{heroPhotoQuestion:Pe}:{},...$e.length>0?{integrations:$e.map(g=>({step:g.step,preset:g.presetId,name:g.presetName,envVars:g.envVars}))}:{},message:`Plan generated for "${_e}" (${ie.length} steps).${Je}${Ge}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,ie.length*3)}\u2013${ie.length*5} minutes total across ${ie.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}'${B?"":", path: '<absolute path>'"} }) immediately.`,...B?{scaffoldTargetPath:B}:{},...te?{warning:te}:{}}))}var xr,zp,Xp,oa,sa=x(()=>{"use strict";ye();Se();qi();on();Bi();yr();Wi();Gi();xr="__mistflow_url_choice__",zp=600*1e3;Xp=q.object({description:q.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:q.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:q.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:q.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:q.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}},q.union([q.record(q.string()),q.array(q.object({question:q.string().optional(),decisionKey:q.string().optional(),answer:q.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:q.record(q.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:q.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:q.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:q.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:q.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:q.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:q.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:q.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:q.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:q.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:q.object({id:q.string().optional(),name:q.string().optional(),summary:q.string().optional(),heroHeadline:q.string().optional(),ctaText:q.string().optional(),bodySample:q.string().optional(),fontsHint:q.string().optional(),fonts:q.object({display:q.string(),body:q.string()}).partial().optional(),colorMood:q.string().optional(),colors:q.object({bg:q.string(),fg:q.string(),accent:q.string()}).partial().optional(),heroTreatment:q.string().optional(),shapeLang:q.string().optional(),texture:q.string().optional(),decorationHint:q.string().optional(),custom:q.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:q.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:q.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.")});oa={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(`
|
|
1891
|
+
`),inputSchema:Xp,handler:iu}});var yt,ia,zo=x(()=>{"use strict";yt={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/ErrorBoundary.tsx",dst:"components/agent/ErrorBoundary.tsx",version:"1.0.0",skipIfExists:!1,sourceHash:"sha256:b638e1163a807780fe937be5e267a8379e8fe1afb661f44cb4582089b1808392"},{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."},ia={"src/components/ApprovalGate.tsx":`/** @mistflow-component approval-gate
|
|
2190
1892
|
* @version 1.0.0
|
|
2191
1893
|
* @source packages/agent-ui-components/src/components/ApprovalGate.tsx
|
|
2192
1894
|
*
|
|
@@ -3006,26 +2708,26 @@ export type AgentEvent =
|
|
|
3006
2708
|
| { kind: 'approval-resolved'; approvalId: string }
|
|
3007
2709
|
| { kind: 'suggestions'; prompts: { id: string; icon: string; text: string }[] }
|
|
3008
2710
|
| { kind: 'done' }
|
|
3009
|
-
`}});import{existsSync as
|
|
3010
|
-
`,"utf8"),a}function
|
|
3011
|
-
`,"utf8"),l}function
|
|
3012
|
-
`),"utf8");return}let r=
|
|
2711
|
+
`}});import{existsSync as Ht,mkdirSync as aa,readFileSync as sn,writeFileSync as at}from"fs";import{dirname as la,join as It}from"path";async function ca(t,e){let r=await wo("ai-chat"),n=[],o=new Set(["lib/ai/tools/manifest.ts","components/chat/ChatBox.tsx","components/chat/ChatMessage.tsx","components/chat/ChatHistory.tsx","components/chat/AttachmentChip.tsx","app/chat/[chatId]/page.tsx","app/chat/layout.tsx","app/chat/page.tsx"]);for(let c of r.files){if(c.path.endsWith(".fragment.json")||c.path==="README.md")continue;let u=It(t,c.path);o.has(c.path)&&Ht(u)||(aa(la(u),{recursive:!0}),at(u,c.content,"utf8"),n.push(c.path))}let s=r.files.find(c=>c.path==="README.md");if(s){let c=It(t,"docs","ai-chat-addon.md");aa(la(c),{recursive:!0}),at(c,s.content,"utf8"),n.push("docs/ai-chat-addon.md")}let i=au(t,r.files,e.integrations),a=lu(t,r.files);cu(t);let l=e.integrations.includes("run-python");return l&&du(t),pu(t,e.mcpEnabled===!0),uu(t,e.mcpEnabled===!0),{installed:n,depsAdded:i,cronAdded:a,runPythonWired:l}}function au(t,e,r){let n=e.find(l=>l.path==="package.json.fragment.json");if(!n)return[];let o=JSON.parse(n.content),s=It(t,"package.json");if(!Ht(s))return[];let i=JSON.parse(sn(s,"utf8"));i.dependencies=i.dependencies??{};let a=[];for(let[l,c]of Object.entries(o.dependencies??{}))i.dependencies[l]!==c&&(i.dependencies[l]=c,a.push(`${l}@${c}`));for(let l of r){let c=o._conditionalDeps?.[l];if(c)for(let[u,d]of Object.entries(c))i.dependencies[u]!==d&&(i.dependencies[u]=d,a.push(`${u}@${d}`))}return at(s,JSON.stringify(i,null,2)+`
|
|
2712
|
+
`,"utf8"),a}function lu(t,e){let r=e.find(c=>c.path==="mistflow.json.fragment.json");if(!r)return[];let n=JSON.parse(r.content);if(!n.cron||n.cron.length===0)return[];let o=It(t,"mistflow.json"),s=Ht(o)?JSON.parse(sn(o,"utf8")):{},i=Array.isArray(s.cron)?s.cron:[],a=new Set(i.map(c=>c.name)),l=[];for(let c of n.cron)a.has(c.name)||(i.push(c),l.push(c.name));return s.cron=i,at(o,JSON.stringify(s,null,2)+`
|
|
2713
|
+
`,"utf8"),l}function cu(t){let e=It(t,"db","schema","index.ts");if(!Ht(e)){at(e,["export * from './auth';","export * from './ai-chat';",""].join(`
|
|
2714
|
+
`),"utf8");return}let r=sn(e,"utf8");if(r.includes("./ai-chat"))return;let n=r.replace(/\n+$/,"");at(e,n+`
|
|
3013
2715
|
export * from './ai-chat';
|
|
3014
|
-
`,"utf8")}function
|
|
2716
|
+
`,"utf8")}function du(t){let e=It(t,"lib","ai","tools","manifest.ts");if(!Ht(e))return;let r=sn(e,"utf8");if(r.includes("runPythonTool"))return;let n=r,o=n.match(/^import[\s\S]*?;\s*$/m);o?n=n.replace(o[0],o[0]+`
|
|
3015
2717
|
import { runPythonTool } from "./run-python";
|
|
3016
2718
|
`):n=`import { runPythonTool } from "./run-python";
|
|
3017
2719
|
|
|
3018
|
-
`+n,n.includes("// __SCAFFOLD_TOOLS_PLACEHOLDER__")?n=n.replace(/\/\/ __SCAFFOLD_TOOLS_PLACEHOLDER__/,"runPythonTool,"):/TOOLS:\s*ToolManifest\[\]\s*=\s*\[\s*\]/.test(n)&&(n=n.replace(/TOOLS:\s*ToolManifest\[\]\s*=\s*\[\s*\]/,"TOOLS: ToolManifest[] = [runPythonTool]")),
|
|
2720
|
+
`+n,n.includes("// __SCAFFOLD_TOOLS_PLACEHOLDER__")?n=n.replace(/\/\/ __SCAFFOLD_TOOLS_PLACEHOLDER__/,"runPythonTool,"):/TOOLS:\s*ToolManifest\[\]\s*=\s*\[\s*\]/.test(n)&&(n=n.replace(/TOOLS:\s*ToolManifest\[\]\s*=\s*\[\s*\]/,"TOOLS: ToolManifest[] = [runPythonTool]")),at(e,n,"utf8")}function pu(t,e){let r=It(t,"db","schema","ai-chat.ts");if(!Ht(r))return;let n=sn(r,"utf8");if(!n.includes("SCAFFOLD_MCP_CALLER_IMPORT_PLACEHOLDER"))return;let o=e?`// installer-rewrote MCP_CALLER_IMPORT (mcp enabled)
|
|
3019
2721
|
import { mcpCaller } from "./mcp";`:`// installer-rewrote MCP_CALLER_IMPORT (mcp disabled \u2014 schema still compiles, CHECK enforces null)
|
|
3020
|
-
const mcpCaller: { id: ReturnType<typeof text> } | undefined = undefined;`,s=n.replace(/\/\/ SCAFFOLD_MCP_CALLER_IMPORT_PLACEHOLDER[\s\S]*?const mcpCaller:[^;]+;/,o);
|
|
2722
|
+
const mcpCaller: { id: ReturnType<typeof text> } | undefined = undefined;`,s=n.replace(/\/\/ SCAFFOLD_MCP_CALLER_IMPORT_PLACEHOLDER[\s\S]*?const mcpCaller:[^;]+;/,o);at(r,s,"utf8")}function uu(t,e){let r=It(t,"lib","chat","sandbox.ts");if(!Ht(r))return;let n=sn(r,"utf8");if(!n.includes("SCAFFOLD_SANDBOX_CAP_SQL_PLACEHOLDER"))return;if(e){let i=n.replace(/\s*\/\/ SCAFFOLD_SANDBOX_CAP_SQL_PLACEHOLDER[^\n]*\n[^\n]*\n[^\n]*\n[^\n]*\n/,`
|
|
3021
2723
|
// installer-kept MCP-on cap SQL (mcp_caller table exists)
|
|
3022
|
-
`);
|
|
2724
|
+
`);at(r,i,"utf8");return}let s=n.replace(/const activeCountResult = await db\.execute\(sql`[\s\S]*?`\);/,["const activeCountResult = await db.execute(sql`"," SELECT COUNT(*)::int AS count FROM agent_sandboxes s"," JOIN ai_chats c ON c.id = s.chat_id"," WHERE c.user_id = ${userId}"," AND s.e2b_sandbox_id IS NOT NULL"," AND s.expires_at > NOW()"," `);"].join(`
|
|
3023
2725
|
`)).replace(/\s*\/\/ SCAFFOLD_SANDBOX_CAP_SQL_PLACEHOLDER[^\n]*\n[^\n]*\n[^\n]*\n[^\n]*\n/,`
|
|
3024
2726
|
// installer-rewrote sandbox cap SQL (mcp disabled \u2014 JOIN only ai_chats)
|
|
3025
|
-
`);
|
|
3026
|
-
`),{added:r,skipped:n}}function
|
|
3027
|
-
`)}function
|
|
3028
|
-
`)}var Cr=v(()=>{"use strict"});var Tr,Ko=v(()=>{Tr="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n"});var Pr,Jo=v(()=>{Pr=`# Landing Page Rules
|
|
2727
|
+
`);at(r,s,"utf8")}function an(t){return t?(Array.isArray(t.integrations)?t.integrations:[]).some(r=>typeof r=="string"&&r==="ai-chat")?!0:t.surfaceType==="agent":!1}var da=x(()=>{"use strict";Se()});var ha={};vn(ha,{installAgentUi:()=>Tr,planRequiresAgentUiInstall:()=>_r,readComponentsInstalledLedger:()=>Jo,selfHealAgentUi:()=>vu});import{existsSync as Wo,mkdirSync as pa,readFileSync as ua,writeFileSync as Go}from"fs";import{join as Sr,dirname as mu}from"path";import{createHash as hu}from"crypto";function gu(t){return`sha256:${hu("sha256").update(t).digest("hex")}`}function fu(t,e,r){let n=[];for(let o of t.files){let s=e[o.src];if(typeof s!="string")throw new Error(`bundle is corrupt: missing content for ${o.src}. Run 'pnpm --filter @mistflow-ai/agent-ui-components run generate-bundle'.`);let i=Sr(r,o.dst);o.skipIfExists&&Wo(i)||(pa(mu(i),{recursive:!0}),Go(i,s),n.push({path:o.dst,sourceVersion:o.version,sourceHash:o.sourceHash,installedHash:gu(s)}))}return n}function yu(t,e){let r=[],n=[];if(!Wo(t))return{added:r,skipped:n};let o=JSON.parse(ua(t,"utf8"));o.dependencies??={};for(let[s,i]of Object.entries(e)){if(o.dependencies[s]||o.devDependencies?.[s]){n.push(s);continue}o.dependencies[s]=i,r.push(s)}return Go(t,JSON.stringify(o,null,2)+`
|
|
2728
|
+
`),{added:r,skipped:n}}function ma(t){return Sr(t,".mistflow","components-installed.json")}function Jo(t){let e=ma(t);if(!Wo(e))return{presets:{}};try{let r=ua(e,"utf8");return{presets:JSON.parse(r)?.presets??{}}}catch{return{presets:{}}}}function bu(t,e){let r=Sr(t,".mistflow");pa(r,{recursive:!0}),Go(ma(t),JSON.stringify(e,null,2)+`
|
|
2729
|
+
`)}function wu(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 _r(t,e){return wu(t,"agent-ui")?!Jo(e).presets["agent-ui"]:!1}function Tr(t,e=new Date){let r=fu(yt,ia,t),{added:n,skipped:o}=yu(Sr(t,"package.json"),yt.dependencies),s=Jo(t);return s.presets[yt.slug]={presetVersion:yt.version,installedAt:e.toISOString(),files:r},bu(t,s),{slug:yt.slug,installed:r,depsAdded:n,depsSkipped:o}}function vu(t,e){if(!_r(t,e))return null;try{let r=Tr(e),n=r.depsAdded.length?`, +${r.depsAdded.length} deps`:"";return{message:`installed agent-ui preset (${r.installed.length} files${n})`,isError:!1}}catch(r){return{message:`agent-ui install failed: ${r instanceof Error?r.message:String(r)}`,isError:!0}}}var Ko=x(()=>{"use strict";zo()});function ku(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 ln(t=process.version){let e=ku(t);return!e||e.major>=23?!0:e.major===22?e.minor>=12:e.major===20?e.minor>=19:!1}function xu(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 zt(t=process.version,e=xu()){let r={pnpm:"Run: pnpm env use --global 22.12.0",fnm:"Run: fnm install 22.12 && fnm use 22.12",nvm:"Run: nvm install 22.12 && nvm use 22.12",volta:"Run: volta install node@22.12",brew:"Run: brew install node@22 && brew link node@22 --force --overwrite",system:"Install Node 22.12+ from https://nodejs.org/download",unknown:"Install Node 22.12+ from https://nodejs.org/download"};return[`OpenNext/Cloudflare builds require Node 20.19+, 22.12+, or 23+. The current MCP process is running ${t}.`,r[e],"Then quit and reopen your IDE so the MCP picks up the new Node."].join(`
|
|
2730
|
+
`)}var Cr=x(()=>{"use strict"});var Ir,Vo=x(()=>{Ir="\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 Pr,Yo=x(()=>{Pr=`# Landing Page Rules
|
|
3029
2731
|
|
|
3030
2732
|
These rules apply to every landing page. They are non-negotiable.
|
|
3031
2733
|
|
|
@@ -3439,9 +3141,9 @@ app/
|
|
|
3439
3141
|
\`\`\`
|
|
3440
3142
|
|
|
3441
3143
|
Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
|
|
3442
|
-
`});import{existsSync as
|
|
3144
|
+
`});import{existsSync as Tu,readFileSync as Cu,writeFileSync as Iu}from"fs";import{join as ga}from"path";function Qo(t){return t?Pu[t]??"\u23ED\uFE0F":"\u23ED\uFE0F"}function Xo(t){return t.name??t.title??`Step ${t.number}`}function fa(t){return t.entity??t.name??"Unknown"}function Ru(t){let e=t.fields??[];return e.length===0?"":typeof e[0]=="string"?e.join(", "):e.map(r=>r.name).filter(Boolean).join(", ")}function Au(t){let e=[],r=t.plan,n=(t.name??r?.name??"App").split("-").map(d=>d.charAt(0).toUpperCase()+d.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=r?.summary??r?.description;o&&(e.push("## What this is"),e.push(""),e.push(o),r?.audienceType&&(e.push(""),e.push(`Audience: **${r.audienceType}**.`)),e.push(""));let s=r?.pickedDirection&&typeof r.pickedDirection=="object"?r.pickedDirection:void 0,i=typeof s?.name=="string"?s.name:r?.design?.archetype;if(i){let d=!s&&r?.design?.tone?` (${r.design.tone} tone)`:"";e.push("## Design brief"),e.push(""),e.push(`Aesthetic: **${i}**${d} \u2014 see DESIGN.md.`),e.push("")}let a=r?.steps??[];if(a.length>0){e.push("## Build progress"),e.push("");let d=a.filter(_=>_.status==="completed"||_.status==="done"),m=a.filter(_=>_.status==="in_progress"),h=a.filter(_=>_.status!=="completed"&&_.status!=="done"&&_.status!=="in_progress");if(d.length>0){e.push(`**Done (${d.length}/${a.length}):**`);for(let _ of d)e.push(`- ${Qo(_.status)} ${Xo(_)}`);e.push("")}if(m.length>0){e.push("**In progress:**");for(let _ of m)e.push(`- ${Qo(_.status)} ${Xo(_)}`);e.push("")}if(h.length>0){e.push("**Planned next:**");for(let _ of h)e.push(`- ${Qo(_.status)} ${Xo(_)}`);e.push("")}}let l=r?.dataModel??[];if(l.length>0){e.push("## Data model"),e.push("");for(let d of l){let m=Ru(d);m?e.push(`- **${fa(d)}**(${m})`):e.push(`- **${fa(d)}**`)}e.push("")}let c=r?.integrations??[];if(c.length>0){e.push("## Active integrations"),e.push("");for(let d of c){let m=d.name??d.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 u=t.deploy;return u?.url&&(e.push("## Deploy"),e.push(""),e.push(`- URL: ${u.url}`),u.completedAt&&e.push(`- Last deploy: ${u.completedAt}`),u.deploymentId&&e.push(`- Last deployment id: \`${u.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(`
|
|
3443
3145
|
`).trimEnd()+`
|
|
3444
|
-
`}function
|
|
3146
|
+
`}function cn(t){try{let e=ga(t,"mistflow.json");if(!Tu(e))return;let r=Cu(e,"utf-8"),n=JSON.parse(r),o=Au(n);Iu(ga(t,"PROJECT.md"),o,"utf-8")}catch{}}var Pu,Rr=x(()=>{"use strict";Pu={completed:"\u2705",done:"\u2705",in_progress:"\u{1F7E1}",pending:"\u23ED\uFE0F",skipped:"\u23ED\uFE0F"}});function ya(){return`import { mcpCallLog } from "@/db";
|
|
3445
3147
|
import type { McpAuthStatus, McpCallStatus } from "./types";
|
|
3446
3148
|
|
|
3447
3149
|
export interface McpAuditRow {
|
|
@@ -3487,7 +3189,7 @@ export async function writeMcpAuditRow(
|
|
|
3487
3189
|
costCents: row.costCents.toString(),
|
|
3488
3190
|
});
|
|
3489
3191
|
}
|
|
3490
|
-
`}var
|
|
3192
|
+
`}var ba=x(()=>{"use strict"});function wa(){return`import { drizzle } from "drizzle-orm/neon-http";
|
|
3491
3193
|
import { neon } from "@neondatabase/serverless";
|
|
3492
3194
|
import { and, eq, gte, inArray, lt, sql } from "drizzle-orm";
|
|
3493
3195
|
import { mcpCaller, mcpCallLog } from "@/db";
|
|
@@ -3715,7 +3417,7 @@ export async function getRateLimitCount(
|
|
|
3715
3417
|
));
|
|
3716
3418
|
return Number(rows[0]?.total ?? 0);
|
|
3717
3419
|
}
|
|
3718
|
-
`}var
|
|
3420
|
+
`}var va=x(()=>{"use strict"});function Nu(t){if(!Eu.test(t))throw new Error(`Invalid MCP tool name "${t}". Use snake_case matching /^[a-z][a-z0-9_]{0,63}$/.`)}function Ou(t){let e=new Map;for(let r of t){Nu(r.toolName);let n=e.get(r.toolName);if(n)throw new Error(`Duplicate MCP tool name "${r.toolName}" from ${r.exportedName}; already provided by ${n}.`);e.set(r.toolName,r.exportedName)}}function ka(t=[]){Ou(t);let e=[...t].sort((s,i)=>s.toolName.localeCompare(i.toolName)),r=e.map(s=>`import { ${s.exportedName} } from "${s.importPath}";`).join(`
|
|
3719
3421
|
`),n=r?`${r}
|
|
3720
3422
|
`:"",o=e.length>0?`
|
|
3721
3423
|
${e.map(s=>s.exportedName).join(`,
|
|
@@ -3723,7 +3425,7 @@ export async function getRateLimitCount(
|
|
|
3723
3425
|
`:"";return`import type { McpToolHandler } from "./types";
|
|
3724
3426
|
${n}
|
|
3725
3427
|
export const MCP_TOOLS: McpToolHandler[] = [${o}];
|
|
3726
|
-
`}function
|
|
3428
|
+
`}function xa(){return`import { z } from "zod";
|
|
3727
3429
|
import type { McpEnv } from "./caller-auth";
|
|
3728
3430
|
|
|
3729
3431
|
export interface AuthenticatedMcpCaller {
|
|
@@ -3796,7 +3498,7 @@ export interface McpToolHandler<TShape extends z.ZodRawShape = z.ZodRawShape> {
|
|
|
3796
3498
|
context: McpToolContext,
|
|
3797
3499
|
) => Promise<McpToolResult>;
|
|
3798
3500
|
}
|
|
3799
|
-
`}var
|
|
3501
|
+
`}var Eu,Sa=x(()=>{"use strict";Eu=/^[a-z][a-z0-9_]{0,63}$/});function _a(t,e,r={}){let n=t.replace(/["\\\n\r]/g,""),o=e.replace(/["\\\n\r]/g,"");return`import { NextRequest, NextResponse } from "next/server";
|
|
3800
3502
|
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
3801
3503
|
import { authenticateCaller, getMcpDb } from "@/lib/mcp/caller-auth";
|
|
3802
3504
|
import { redactConsoleError, writeMcpAuditRow } from "@/lib/mcp/audit";
|
|
@@ -3961,7 +3663,7 @@ export function GET(): Response {
|
|
|
3961
3663
|
{ status: 405, headers: { "Allow": "POST", "content-type": "application/json" } },
|
|
3962
3664
|
);
|
|
3963
3665
|
}
|
|
3964
|
-
`}var
|
|
3666
|
+
`}var Ta=x(()=>{"use strict"});function Ca(){return`import { index, integer, jsonb, numeric, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
|
3965
3667
|
|
|
3966
3668
|
export const mcpCaller = pgTable(
|
|
3967
3669
|
"mcp_caller",
|
|
@@ -4010,7 +3712,7 @@ export const mcpCallLog = pgTable(
|
|
|
4010
3712
|
authStatusIdx: index("mcp_call_log_auth_status_idx").on(table.authStatus),
|
|
4011
3713
|
}),
|
|
4012
3714
|
);
|
|
4013
|
-
`}var
|
|
3715
|
+
`}var Ia=x(()=>{"use strict"});function Pa(){return`import type { z } from "zod";
|
|
4014
3716
|
import { getMcpDb, getMonthlySpendCents, getRateLimitCount, isToolAllowed } from "./caller-auth";
|
|
4015
3717
|
import { redactConsoleError, writeMcpAuditRow } from "./audit";
|
|
4016
3718
|
import type { AuthenticatedMcpCaller, McpToolHandler, McpToolResult } from "./types";
|
|
@@ -4199,7 +3901,7 @@ export async function runMcpTool<TShape extends z.ZodRawShape>(
|
|
|
4199
3901
|
return toolError("handler_error");
|
|
4200
3902
|
}
|
|
4201
3903
|
}
|
|
4202
|
-
`}var
|
|
3904
|
+
`}var Ra=x(()=>{"use strict"});function Zo(t){let e=t.appVersion??"0.0.1",r=t.useAiChatManifest===!0;return{id:"mcp",files:[{path:"app/mcp/route.ts",content:_a(t.appName,e,{useAiChatManifest:r})},{path:"lib/mcp/tool-runner.ts",content:Pa()},...r?[]:[{path:"lib/mcp/registry.ts",content:ka()}],{path:"lib/mcp/caller-auth.ts",content:wa()},{path:"lib/mcp/audit.ts",content:ya()},{path:"lib/mcp/types.ts",content:xa()}],packageJsonDeps:{...Mu},envVars:{MCP_AUTH_MODE:"dev",ENVIRONMENT:"development"},productionEnvVars:{MCP_AUTH_MODE:"",ENVIRONMENT:"production"},schemaFragment:Ca(),nextConfigRules:{forbidIgnoreBuildErrors:!0}}}var Mu,Aa=x(()=>{"use strict";ba();va();Sa();Ta();Ia();Ra();Mu={"@modelcontextprotocol/sdk":"1.0.0","zod-to-json-schema":"^3.24.0",zod:"^3.24.0"}});var Ea=x(()=>{"use strict"});import{z as f}from"zod";var Na,ju,Du,Lu,$u,Uu,Fu,qu,Bu,Hu,zu,Wu,Gu,Ju,Yb,Oa=x(()=>{"use strict";Na=f.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).transform(t=>t),ju=f.array(f.enum(["read","write"])).min(1).max(2).superRefine((t,e)=>{new Set(t).size!==t.length&&e.addIssue({code:f.ZodIssueCode.custom,message:"capabilities must contain unique values"});let r=JSON.stringify(t);new Set([JSON.stringify(["read"]),JSON.stringify(["write"]),JSON.stringify(["read","write"])]).has(r)||e.addIssue({code:f.ZodIssueCode.custom,message:"capabilities must be exactly ['read'], ['write'], or ['read', 'write']"})}).transform(t=>t),Du=f.object({type:f.literal("nango"),authMode:f.literal("oauth"),providerConfigKey:f.string().min(1),syncSupported:f.boolean(),mcpSupported:f.boolean(),connectionConfigId:f.string().min(1).optional()}),Lu=f.object({idFormat:f.literal("mf_${appProjectId}_${appOrgId}_${appUserId}_${providerSlug}"),segmentEncoding:f.literal("base64url-or-validated-slug"),mappingTable:f.object({targetFile:f.literal("db/schema.ts"),tableName:f.literal("connected_service_connections"),requiredColumns:f.tuple([f.literal("connection_id"),f.literal("app_project_id"),f.literal("app_org_id"),f.literal("app_user_id"),f.literal("provider_slug"),f.literal("provider_account_id"),f.literal("provider_workspace_id"),f.literal("created_at"),f.literal("updated_at"),f.literal("disconnected_at")])}),uniqueness:f.tuple([f.literal("connection_id"),f.literal("app_project_id,app_org_id,app_user_id,provider_slug")])}),$u=f.object({kind:f.enum(["schema","migration","workers-nango-client","sync-runner","list-records","webhook-route","server-action","connect-component","disconnect-route","mcp-tool","mcp-registry","manifest"]),targetFile:f.string().min(1),source:f.string(),mergeStrategy:f.enum(["append-generated-block","create-file","replace-generated-block","json-merge","ast-array-merge"]),generatedBlockSlug:Na.optional()}),Uu=f.object({packageName:f.string().min(1),versionRange:f.string().min(1),dependencyType:f.enum(["dependency","devDependency"]),runtime:f.enum(["client","worker-server","nango-runner","test"]),importAllowedFrom:f.array(f.string().min(1)).readonly()}),Fu=f.object({key:f.string().regex(/^[A-Z0-9_]+$/),description:f.string().min(1),exposure:f.enum(["server-secret","client-public"]),requiredAt:f.enum(["build","runtime"]),setupUrl:f.string().url().optional(),example:f.string().optional()}),qu=f.object({title:f.string().min(1),body:f.string().min(1),link:f.string().url().optional(),requiresUserAction:f.boolean()}),Bu=f.discriminatedUnion("type",[f.object({type:f.literal("public")}),f.object({type:f.literal("owner")}),f.object({type:f.literal("principal-table"),principalTable:f.string().min(1),requiredBeforeExpose:f.literal(!0),staleDataBehavior:f.literal("fail-closed")})]),Hu=f.object({webhook:f.object({route:f.literal("app/api/webhooks/nango/route.ts"),signature:f.literal("nango-hmac-sha256"),rawBodyRequired:f.literal(!0),timestampToleranceSeconds:f.literal(300),replayPrevention:f.object({table:f.literal("connected_service_webhook_events"),key:f.literal("event_id")}),payloadValidation:f.literal("zod"),publicButSigned:f.literal(!0)}),acl:Bu,logging:f.object({redactHeaders:f.literal(!0),redactTokens:f.literal(!0),redactSecrets:f.literal(!0),redactProviderPayloadText:f.literal(!0)}),audit:f.object({enabled:f.literal(!0),redactRequestBody:f.literal(!0),redactResponseBody:f.literal(!0)})}),zu=f.object({targetFile:f.literal("db/schema.ts"),exportedTables:f.array(f.string().min(1)),source:f.string().min(1),mergeStrategy:f.literal("append-generated-block")}),Wu=f.object({nangoSyncName:f.string().min(1),nangoModelName:f.string().min(1),targetFile:f.custom(t=>typeof t=="string"&&/^nango-integrations\/.+\.ts$/.test(t)),listRecordsFile:f.custom(t=>typeof t=="string"&&/^lib\/sync\/.+\.ts$/.test(t)),webhookEventTypes:f.array(f.string().min(1)).readonly(),source:f.string().min(1)}),Gu=f.object({name:f.string().min(1),inputSchemaExport:f.string().min(1),responseSchemaExport:f.string().min(1),method:f.enum(["GET","POST","PUT","PATCH","DELETE"]),pathTemplate:f.string().startsWith("/"),allowCallerControlledUrl:f.literal(!1).optional(),rateLimitBehavior:f.string().min(1),idempotencyBehavior:f.string().min(1),redactedAuditEventShape:f.string().min(1)}),Ju=f.object({targetFile:f.custom(t=>typeof t=="string"&&/^lib\/actions\/.+\.ts$/.test(t)),operations:f.array(Gu).min(1),source:f.string().min(1)}),Yb=f.object({slug:Na,version:f.string().min(1),name:f.string().min(1),category:f.literal("connected-service"),capabilities:ju,provider:Du,connection:Lu,files:f.array($u),dependencies:f.array(Uu),envVars:f.array(Fu),setupSteps:f.array(qu),security:Hu,schema:zu.optional(),sync:Wu.optional(),actions:Ju.optional()}).superRefine((t,e)=>{let r=t.capabilities.includes("read"),n=t.capabilities.includes("write");r&&!t.sync&&e.addIssue({code:f.ZodIssueCode.custom,path:["sync"],message:"read-capable presets must define sync"}),!r&&t.sync&&e.addIssue({code:f.ZodIssueCode.custom,path:["sync"],message:"write-only presets must not define sync"}),n&&!t.actions&&e.addIssue({code:f.ZodIssueCode.custom,path:["actions"],message:"write-capable presets must define actions"}),!n&&t.actions&&e.addIssue({code:f.ZodIssueCode.custom,path:["actions"],message:"read-only presets must not define actions"})})});var Bn=x(()=>{"use strict"});var es=x(()=>{"use strict"});var ts=x(()=>{"use strict"});var ns=x(()=>{"use strict";Bn()});var rs=x(()=>{"use strict"});var os=x(()=>{"use strict";Bn()});var ja=x(()=>{"use strict";es();Bn();os();rs();ns();ts()});var Da,La,Vu,Yu,Qu,Xu,Zu,Ar,$a=x(()=>{"use strict";Da="nango-base-connect",La=`import { pgTable, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'
|
|
4203
3905
|
|
|
4204
3906
|
// Per-(project, org, user, provider) Nango connection registry. The Nango
|
|
4205
3907
|
// connection ID is assigned by Nango itself (NOT pre-generated by us) and
|
|
@@ -4250,7 +3952,7 @@ export const connectedServiceSyncCursors = pgTable('connected_service_sync_curso
|
|
|
4250
3952
|
table.nango_model_name,
|
|
4251
3953
|
),
|
|
4252
3954
|
}))
|
|
4253
|
-
`,
|
|
3955
|
+
`,Vu=`import { redactForConnectedServiceLog } from '@mistflow-ai/runtime/nango'
|
|
4254
3956
|
|
|
4255
3957
|
const NANGO_BASE_URL = process.env.NANGO_API_URL ?? 'https://api.nango.dev'
|
|
4256
3958
|
|
|
@@ -4415,7 +4117,7 @@ export async function deleteConnection(args: { connectionId: string; providerCon
|
|
|
4415
4117
|
throw new NangoApiError('Failed to delete Nango connection', response.status, errBody)
|
|
4416
4118
|
}
|
|
4417
4119
|
}
|
|
4418
|
-
`,
|
|
4120
|
+
`,Yu=`// Public route \u2014 the auth boundary is the signed Nango HMAC.
|
|
4419
4121
|
// Verification runs through @mistflow-ai/runtime/nango/verifyNangoWebhook
|
|
4420
4122
|
// which checks \`X-Nango-Hmac-Sha256\` over the raw body and uses the
|
|
4421
4123
|
// store's atomic insertEvent for replay prevention.
|
|
@@ -4580,7 +4282,7 @@ export async function POST(request: Request): Promise<Response> {
|
|
|
4580
4282
|
})
|
|
4581
4283
|
}
|
|
4582
4284
|
}
|
|
4583
|
-
`,
|
|
4285
|
+
`,Qu=`import { NextRequest, NextResponse } from 'next/server'
|
|
4584
4286
|
import { createConnectSession } from '@/lib/nango-client'
|
|
4585
4287
|
import { auth } from '@/lib/auth'
|
|
4586
4288
|
|
|
@@ -4639,7 +4341,7 @@ export async function POST(request: NextRequest): Promise<Response> {
|
|
|
4639
4341
|
)
|
|
4640
4342
|
}
|
|
4641
4343
|
}
|
|
4642
|
-
`,
|
|
4344
|
+
`,Xu=`"use client"
|
|
4643
4345
|
|
|
4644
4346
|
// Generic Nango Connect button. Pass \`providers\` to restrict which
|
|
4645
4347
|
// integrations the user can pick from, or omit to show every provider
|
|
@@ -4742,7 +4444,7 @@ export function ConnectButton({
|
|
|
4742
4444
|
</button>
|
|
4743
4445
|
)
|
|
4744
4446
|
}
|
|
4745
|
-
`,
|
|
4447
|
+
`,Zu=`import { NextRequest, NextResponse } from 'next/server'
|
|
4746
4448
|
import { eq, and, isNull } from 'drizzle-orm'
|
|
4747
4449
|
import { db } from '@/lib/db'
|
|
4748
4450
|
import { connectedServiceConnections } from '@/db/schema/connected-services'
|
|
@@ -4824,36 +4526,31 @@ export async function POST(request: NextRequest): Promise<Response> {
|
|
|
4824
4526
|
|
|
4825
4527
|
return new Response(null, { status: 204 })
|
|
4826
4528
|
}
|
|
4827
|
-
`,
|
|
4828
|
-
`)}function
|
|
4829
|
-
`)}function
|
|
4529
|
+
`,Ar={slug:Da,version:"1.0.0",name:"Nango Connected Services (generic)",category:"connected-service",capabilities:["read","write"],provider:{type:"nango",authMode:"oauth",providerConfigKey:"*",syncSupported:!0,mcpSupported:!1},connection:{idFormat:"mf_${appProjectId}_${appOrgId}_${appUserId}_${providerSlug}",segmentEncoding:"base64url-or-validated-slug",mappingTable:{targetFile:"db/schema.ts",tableName:"connected_service_connections",requiredColumns:["connection_id","app_project_id","app_org_id","app_user_id","provider_slug","provider_account_id","provider_workspace_id","created_at","updated_at","disconnected_at"]},uniqueness:["connection_id","app_project_id,app_org_id,app_user_id,provider_slug"]},schema:{targetFile:"db/schema.ts",exportedTables:["connected_service_connections","connected_service_webhook_events","connected_service_sync_cursors"],source:La,mergeStrategy:"append-generated-block"},files:[{kind:"schema",targetFile:"db/schema.ts",source:La,mergeStrategy:"append-generated-block",generatedBlockSlug:Da},{kind:"migration",targetFile:"drizzle",source:"connected_service_base",mergeStrategy:"create-file"},{kind:"workers-nango-client",targetFile:"lib/nango-client.ts",source:Vu,mergeStrategy:"create-file"},{kind:"webhook-route",targetFile:"app/api/webhooks/nango/route.ts",source:Yu,mergeStrategy:"create-file"},{kind:"server-action",targetFile:"app/api/connect-sessions/route.ts",source:Qu,mergeStrategy:"create-file"},{kind:"connect-component",targetFile:"components/connect-button.tsx",source:Xu,mergeStrategy:"create-file"},{kind:"disconnect-route",targetFile:"app/api/connected-services/disconnect/route.ts",source:Zu,mergeStrategy:"create-file"},{kind:"manifest",targetFile:".mistflow/state.json",source:"",mergeStrategy:"json-merge"}],dependencies:[{packageName:"@nangohq/frontend",versionRange:"^0.52.0",dependencyType:"dependency",runtime:"client",importAllowedFrom:["components/connect-button.tsx"]},{packageName:"@mistflow-ai/runtime",versionRange:"^0.1.0",dependencyType:"dependency",runtime:"worker-server",importAllowedFrom:["app/api/webhooks/","lib/nango-client","lib/sync/"]}],envVars:[{key:"NANGO_SECRET_KEY",description:"Nango secret key (server-side). Get from app.nango.dev.",exposure:"server-secret",requiredAt:"runtime",setupUrl:"https://app.nango.dev"},{key:"NANGO_WEBHOOK_SECRET",description:"Webhook signing secret. Get from Nango dashboard \u2192 webhooks.",exposure:"server-secret",requiredAt:"runtime",setupUrl:"https://app.nango.dev"}],setupSteps:[{title:"Sign up for Nango Cloud",body:"Free tier covers small projects. You'll get your secret key + webhook secret.",link:"https://app.nango.dev",requiresUserAction:!0},{title:"Enable providers in Nango",body:"In the Nango dashboard, enable the providers your app needs (Slack, Gmail, etc.). Each provider needs its OAuth credentials configured in Nango.",link:"https://docs.nango.dev/guides/getting-started",requiresUserAction:!0},{title:"Set Mistflow project env vars",body:"Paste NANGO_SECRET_KEY and NANGO_WEBHOOK_SECRET into Mistflow dashboard \u2192 project \u2192 env vars.",requiresUserAction:!0},{title:"Configure Nango webhook URL after deploy",body:"After your first deploy, copy the app URL and paste into Nango dashboard \u2192 webhooks. Webhook path is /api/webhooks/nango.",requiresUserAction:!0}],security:{webhook:{route:"app/api/webhooks/nango/route.ts",signature:"nango-hmac-sha256",rawBodyRequired:!0,timestampToleranceSeconds:300,replayPrevention:{table:"connected_service_webhook_events",key:"event_id"},payloadValidation:"zod",publicButSigned:!0},acl:{type:"owner"},logging:{redactHeaders:!0,redactTokens:!0,redactSecrets:!0,redactProviderPayloadText:!0},audit:{enabled:!0,redactRequestBody:!0,redactResponseBody:!0}}}});var Ua=x(()=>{"use strict"});var Fa=x(()=>{"use strict";Ea();Oa();Bn();es();ts();ns();rs();os();ja();$a();Ua()});function qa(t){if(!t)return"Item";let e=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return e.length===0?"Item":e.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}function em(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function tm(t){let e=qa(t);return e.charAt(0).toLowerCase()+e.slice(1)}function is(){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(`
|
|
4530
|
+
`)}function Ba(){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(`
|
|
4531
|
+
`)}function as(t){let e=Ba();if(t.includes(ss)){let n=t.indexOf(ss),o=Ha,s=t.indexOf(o,n);if(s===-1)return t.slice(0,n)+e;let i=t.slice(s+o.length);return t.slice(0,n)+e+i.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
|
|
4830
4532
|
|
|
4831
|
-
`+e}function
|
|
4832
|
-
`)}function
|
|
4533
|
+
`+e}function ls(t,e){let r=qa(t),n=e??tm(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${n} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${r}Schema = createSelectSchema(${n});`,`export type ${r} = z.infer<typeof ${r}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${r}Input = createInsertSchema(${n}).omit({`," id: true,"," createdAt: true,","});",`export type Create${r}Input = z.infer<typeof Create${r}Input>;`,""].join(`
|
|
4534
|
+
`)}function cs(t){return`contracts/${em(t)}.ts`}var ss,Ha,ds=x(()=>{"use strict";ss="<!-- mist:contracts:start -->",Ha="<!-- mist:contracts:end -->"});import{z as dn}from"zod";import{existsSync as ze,mkdirSync as pn,rmSync as nm,writeFileSync as bt,readFileSync as un,readdirSync as Ja,copyFileSync as rm}from"fs";import{join as he,resolve as Ka,dirname as Hn,isAbsolute as om}from"path";import{homedir as sm}from"os";import{spawn as Hw}from"child_process";import{randomBytes as im}from"crypto";import{simpleGit as lm}from"simple-git";function am(t){let e=he(sm(),".mistflow","plans",`${t}.json`);if(!ze(e))return null;try{let r=JSON.parse(un(e,"utf-8"));return r.plan?{plan:r.plan,...typeof r.scaffoldTargetPath=="string"?{scaffoldTargetPath:r.scaffoldTargetPath}:{}}:null}catch{return null}}function dm(t){let e=Hn(Ka(t)),r=10,n=0;for(;n<r&&e!==Hn(e);){if(ze(he(e,"pnpm-workspace.yaml"))||ze(he(e,"lerna.json"))||ze(he(e,"pnpm-lock.yaml"))||ze(he(e,"package-lock.json"))||ze(he(e,"yarn.lock"))||ze(he(e,"bun.lockb"))||ze(he(e,"bun.lock")))return e;let o=he(e,"package.json");if(ze(o))try{if(JSON.parse(un(o,"utf-8")).workspaces)return e}catch{}e=Hn(e),n++}return null}function E(t,e,r){let n=he(t,e);pn(Hn(n),{recursive:!0}),bt(n,r)}function gm(t,e){E(t,".cursor/rules/mistflow.mdc",um),E(t,".github/copilot-instructions.md",mm),E(t,".continue/rules/mistflow.md",Er),E(t,"CONVENTIONS.md",Er),E(t,".aider.conf.yml",hm)}function fm(t){if(!t.startsWith(`---
|
|
4833
4535
|
`))return{frontmatter:null,body:t};let e=t.indexOf(`
|
|
4834
4536
|
---
|
|
4835
4537
|
`,4);if(e<0)return{frontmatter:null,body:t};let r=t.slice(4,e),n={};for(let o of r.split(`
|
|
4836
|
-
`)){let s=o.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/);if(!s)continue;let[,i,a]=s;(i==="name"||i==="description")&&(n[i]=a.trim())}return{frontmatter:n,body:t.slice(e+5).replace(/^\n+/,"")}}function
|
|
4538
|
+
`)){let s=o.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/);if(!s)continue;let[,i,a]=s;(i==="name"||i==="description")&&(n[i]=a.trim())}return{frontmatter:n,body:t.slice(e+5).replace(/^\n+/,"")}}function ym(t,e){for(let[r,n]of Object.entries(e)){if(!n||n.trim().length===0)continue;let{frontmatter:o,body:s}=fm(n),i=o?.name??r,a=o?.description??`Mistflow skill: ${r}`,l=`---
|
|
4837
4539
|
name: ${i}
|
|
4838
4540
|
description: ${a}
|
|
4839
4541
|
---
|
|
4840
4542
|
|
|
4841
|
-
`;
|
|
4543
|
+
`;E(t,`.claude/skills/${r}/SKILL.md`,l+s);let c=`---
|
|
4842
4544
|
description: ${a}
|
|
4843
4545
|
alwaysApply: false
|
|
4844
4546
|
---
|
|
4845
4547
|
|
|
4846
|
-
`;
|
|
4847
|
-
`)
|
|
4848
|
-
`),s=[
|
|
4849
|
-
`)
|
|
4850
|
-
|
|
4851
|
-
|
|
4852
|
-
@theme {
|
|
4853
|
-
${o}
|
|
4854
|
-
${s}
|
|
4855
|
-
}
|
|
4856
|
-
|
|
4548
|
+
`;E(t,`.cursor/rules/${r}.mdc`,c+s)}}function bm(t){if(!ze(t))return!0;let e;try{e=Ja(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}function wm(t,e){let r=(e??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"new-app",n=he(t,r);return`${t} isn't empty, so we can't scaffold the project here without clobbering existing files. Retry mist_init with path: "${n}" (a subdirectory) \u2014 the user almost certainly meant "create a new app inside this folder," not "overwrite this folder." Confirm with the user once if you're not sure, but the suggested sub-path is usually right. (A leftover .mistflow/ from planning is fine \u2014 init preserves it.)`}function ps(t){if(!t)return!1;let e=t.trim().replace(/^#/,"");if(!/^[0-9a-fA-F]{6}$/.test(e))return!1;let r=parseInt(e.slice(0,2),16)/255,n=parseInt(e.slice(2,4),16)/255,o=parseInt(e.slice(4,6),16)/255,s=a=>a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return .2126*s(r)+.7152*s(n)+.0722*s(o)<.35}function xm(t,e){if(!e)return;let r=e.colors&&typeof e.colors=="object"?e.colors:{},n=e.fonts&&typeof e.fonts=="object"?e.fonts:{},o=typeof r.bg=="string"?r.bg:"#ffffff",s=typeof r.fg=="string"?r.fg:ps(o)?"#fafafa":"#111111",i=typeof r.accent=="string"?r.accent:"#0a0a0a",a=typeof n.display=="string"?n.display:"Fraunces",l=typeof n.body=="string"?n.body:"DM Sans",c=typeof e.name=="string"?e.name:`${t} Direction`,u=typeof e.summary=="string"?e.summary:"",d=typeof e.color_mood=="string"?e.color_mood:typeof e.colorMood=="string"?e.colorMood:"",m=typeof e.decoration_hint=="string"?e.decoration_hint:typeof e.decorationHint=="string"?e.decorationHint:"Use the picked direction's typography, colors, and composition exactly.",h=e.shape_lang==="sharp"||e.shapeLang==="sharp"?{sm:"0px",md:"0px",lg:"0px",xl:"0px"}:e.shape_lang==="pill"||e.shapeLang==="pill"?{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px"}:{sm:"4px",md:"8px",lg:"12px",xl:"16px"},_=ps(o)?"dark":"light",P=_==="dark"?"#142936":"#ffffff",y=_==="dark"?"#1A3544":"#f4f4f5",v=_==="dark"?"rgba(237,243,245,0.18)":"#d4d4d8",N=_==="dark"?"rgba(237,243,245,0.10)":"#e4e4e7",K=ps(i)?"#ffffff":"#0a0a0a";return["---",`name: ${JSON.stringify(c)}`,`theme: ${_}`,"colors:",` primary: ${JSON.stringify(i)}`,` on-primary: ${JSON.stringify(K)}`,` secondary: ${JSON.stringify(y)}`,` on-secondary: ${JSON.stringify(s)}`,` background: ${JSON.stringify(o)}`,` on-background: ${JSON.stringify(s)}`,` surface: ${JSON.stringify(P)}`,` on-surface: ${JSON.stringify(s)}`,` surface-variant: ${JSON.stringify(y)}`,` on-surface-variant: ${JSON.stringify(s)}`,` outline: ${JSON.stringify(v)}`,` outline-variant: ${JSON.stringify(N)}`,' error: "#dc2626"',' on-error: "#ffffff"',' success: "#16a34a"',' on-success: "#ffffff"',' warning: "#ca8a04"',' on-warning: "#0a0a0a"',' info: "#2563eb"',' on-info: "#ffffff"',"typography:"," display-lg:",` fontFamily: ${JSON.stringify(a)}`,' fontSize: "clamp(48px, 7vw, 96px)"',' fontWeight: "700"',' lineHeight: "1.05"'," headline-lg:",` fontFamily: ${JSON.stringify(a)}`,' fontSize: "clamp(32px, 4vw, 56px)"',' fontWeight: "700"',' lineHeight: "1.1"'," headline-md:",` fontFamily: ${JSON.stringify(a)}`,' fontSize: "clamp(24px, 3vw, 36px)"',' fontWeight: "600"',' lineHeight: "1.2"'," body-lg:",` fontFamily: ${JSON.stringify(l)}`,' fontSize: "18px"',' fontWeight: "400"',' lineHeight: "1.6"'," body-md:",` fontFamily: ${JSON.stringify(l)}`,' fontSize: "16px"',' fontWeight: "400"',' lineHeight: "1.55"'," label-sm:",` fontFamily: ${JSON.stringify(l)}`,' fontSize: "13px"',' fontWeight: "500"',' lineHeight: "1.4"',"rounded:",` sm: ${JSON.stringify(h.sm)}`,` md: ${JSON.stringify(h.md)}`,` lg: ${JSON.stringify(h.lg)}`,` xl: ${JSON.stringify(h.xl)}`,"spacing:",' unit: "4px"',' container-padding: "24px"',' card-gap: "16px"',' section-margin: "96px"',"---","",`# ${c}`,"",u||`${c} is the selected creative direction for ${t}.`,"",`Color mood: ${d||`background ${o}, foreground ${s}, accent ${i}`}.`,"","Authenticated app surfaces default to a light workspace adaptation unless the user explicitly chooses a dark app interface. Use the picked direction for landing identity; keep dashboards, lists, tables, forms, and settings light, dense, and work-focused.","",`Signature: ${m}`,""].join(`
|
|
4549
|
+
`)}function Sm(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let r=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},o=r.split(`
|
|
4550
|
+
`),s=null,i=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 m=a(c.slice(6).trim());(m==="dark"||m==="light")&&(n.theme=m);continue}let u=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(u){s=u[1],i=null;continue}if(c.length>0&&!c.startsWith(" ")&&!c.startsWith(" ")&&c.match(/^[a-zA-Z0-9_-]+:(\s|$)/)){s=null,i=null;continue}if(s==="typography"){let m=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(m){i=m[1].replace(/-/g,"_"),n.typography[i]={};continue}let h=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(h&&i){n.typography[i][h[1]]=a(h[2]);continue}}let d=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(d&&s){let m=d[1].replace(/-/g,"_"),h=a(d[2]);s==="colors"?n.colors[m]=h:s==="rounded"?n.rounded[m]=h:s==="spacing"&&(n.spacing[m]=h)}}return n}function _m(t,e){let r=t.colors,n=t.theme==="dark"?{...r,background:"#fafafa",on_background:"#111827",surface:"#ffffff",on_surface:"#111827",surface_variant:"#f4f4f5",on_surface_variant:"#52525b",outline:"#d4d4d8",outline_variant:"#e4e4e7",secondary:"#f4f4f5",on_secondary:"#18181b",tertiary:r.tertiary??"#eef2f2",on_tertiary:r.on_tertiary??"#111827"}:r,s=[["--color-background",n.background],["--color-foreground",n.on_background??n.on_surface],["--color-card",n.surface??n.background],["--color-card-foreground",n.on_surface??n.on_background],["--color-popover",n.surface??n.background],["--color-popover-foreground",n.on_surface??n.on_background],["--color-muted",n.surface_variant??n.outline_variant??n.outline],["--color-muted-foreground",n.on_surface_variant??n.outline],["--color-border",n.outline_variant??n.outline],["--color-input",n.outline_variant??n.outline],["--color-primary",n.primary],["--color-primary-foreground",n.on_primary],["--color-ring",n.primary],["--color-secondary",n.secondary],["--color-secondary-foreground",n.on_secondary],["--color-accent",n.secondary],["--color-accent-foreground",n.on_secondary],["--color-destructive",n.error],["--color-destructive-foreground",n.on_error],["--color-success",n.success],["--color-success-foreground",n.on_success],["--color-warning",n.warning],["--color-warning-foreground",n.on_warning],["--color-info",n.info??n.primary],["--color-info-foreground",n.on_info??n.on_primary]].filter(c=>typeof c[1]=="string").map(([c,u])=>` ${c}: ${u};`).join(`
|
|
4551
|
+
`),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(`
|
|
4552
|
+
`),a=[["--landing-background",r.background],["--landing-foreground",r.on_background??r.on_surface],["--landing-surface",r.surface??r.background],["--landing-surface-variant",r.surface_variant],["--landing-accent",r.primary],["--landing-accent-foreground",r.on_primary],["--landing-outline",r.outline]].filter(c=>typeof c[1]=="string").map(([c,u])=>` ${c}: ${u};`).join(`
|
|
4553
|
+
`),l=`
|
|
4857
4554
|
|
|
4858
4555
|
@layer base {
|
|
4859
4556
|
* { border-color: var(--color-border); }
|
|
@@ -4861,6 +4558,8 @@ ${s}
|
|
|
4861
4558
|
}
|
|
4862
4559
|
|
|
4863
4560
|
:root {
|
|
4561
|
+
${a?`${a}
|
|
4562
|
+
`:""} --app-surface-mode: light-workspace;
|
|
4864
4563
|
--ease-quart-out: cubic-bezier(0.25, 1, 0.5, 1);
|
|
4865
4564
|
--ease-expo-out: cubic-bezier(0.16, 1, 0.3, 1);
|
|
4866
4565
|
--ease-back-out: cubic-bezier(0.34, 1.56, 0.64, 1);
|
|
@@ -4901,11 +4600,18 @@ ${s}
|
|
|
4901
4600
|
|
|
4902
4601
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
4903
4602
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
4904
|
-
|
|
4603
|
+
`;return`@import "tailwindcss";
|
|
4604
|
+
@import "tw-animate-css";
|
|
4605
|
+
|
|
4606
|
+
@theme {
|
|
4607
|
+
${s}
|
|
4608
|
+
${i}
|
|
4609
|
+
}
|
|
4610
|
+
${l}`}function za(t,e){let r=t?.borderRadius??"subtle",n=vm[r]??"0.375rem";if(e){let s=Sm(e);if(s)return _m(s,n)}return`@import "tailwindcss";
|
|
4905
4611
|
@import "tw-animate-css";
|
|
4906
4612
|
|
|
4907
4613
|
@theme {
|
|
4908
|
-
${[...
|
|
4614
|
+
${[...km.map(([s,i])=>` ${s}: ${i};`)," --radius-sm: 0.25rem;",` --radius-md: ${n};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
|
|
4909
4615
|
`)}
|
|
4910
4616
|
}
|
|
4911
4617
|
|
|
@@ -4955,7 +4661,7 @@ ${[...um.map(([s,i])=>` ${s}: ${i};`)," --radius-sm: 0.25rem;",` --radius-md:
|
|
|
4955
4661
|
|
|
4956
4662
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
4957
4663
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
4958
|
-
`}function
|
|
4664
|
+
`}function Ga(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return Wa[e]?Wa[e]:e.replace(/\s+/g,"_")}function Tm(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 Im(t,e,r){let n=t.replace(/[\\"`$]/g,""),o=Tm(r),i=Cm.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";
|
|
4959
4665
|
import { DM_Sans } from "next/font/google";
|
|
4960
4666
|
import { Toaster } from "sonner";
|
|
4961
4667
|
import "./globals.css";
|
|
@@ -4971,7 +4677,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
4971
4677
|
</html>
|
|
4972
4678
|
);
|
|
4973
4679
|
}
|
|
4974
|
-
`;let c=
|
|
4680
|
+
`;let c=Ga(a??l),u=Ga(l??a);return c===u?`import type { Metadata } from "next";
|
|
4975
4681
|
import { ${c} } from "next/font/google";
|
|
4976
4682
|
import { Toaster } from "sonner";
|
|
4977
4683
|
import "./globals.css";
|
|
@@ -4988,12 +4694,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
4988
4694
|
);
|
|
4989
4695
|
}
|
|
4990
4696
|
`:`import type { Metadata } from "next";
|
|
4991
|
-
import { ${c}, ${
|
|
4697
|
+
import { ${c}, ${u} } from "next/font/google";
|
|
4992
4698
|
import { Toaster } from "sonner";
|
|
4993
4699
|
import "./globals.css";
|
|
4994
4700
|
|
|
4995
4701
|
const heading = ${c}({ subsets: ["latin"], variable: "--font-heading" });
|
|
4996
|
-
const body = ${
|
|
4702
|
+
const body = ${u}({ subsets: ["latin"], variable: "--font-body" });
|
|
4997
4703
|
|
|
4998
4704
|
export const metadata: Metadata = { title: "${n}", description: "Built with Mistflow" };
|
|
4999
4705
|
|
|
@@ -5004,59 +4710,59 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
5004
4710
|
</html>
|
|
5005
4711
|
);
|
|
5006
4712
|
}
|
|
5007
|
-
`}function
|
|
5008
|
-
`)}function
|
|
4713
|
+
`}function Wt(t,...e){let r=JSON.stringify(t).toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function Gt(t,...e){return(Array.isArray(t.integrations)?t.integrations:[]).some(n=>{let o=JSON.stringify(n).toLowerCase();return e.some(s=>o.includes(s.toLowerCase()))})}function Pm(t){return t.realMoney!==!0?!1:Gt(t,"stripe")||Wt(t,"stripe","payment","billing","subscription","checkout")}function Rm(t){return t.hasAI===!0?!0:Gt(t,"openai","anthropic","openrouter","ai")||Wt(t,"ai integration","openai","anthropic","openrouter","llm","ai chat","chatbot","gpt","ai-powered","ai powered","ai-generated","ai generated","ai-assisted","ai assisted","ai scorecard","ai scorecards","ai interviewer","ai interview","generate interview","generate questions","draft interview","scorecard generation","evaluate transcript","transcript evaluation","recommendation label")}function Am(t){return t.useConnectedServices===!0?!0:t.useConnectedServices===!1?!1:t.slackIngest===!0?!0:t.slackIngest===!1?!1:Gt(t,"slack","slack-messages","gmail","google-mail","notion","hubspot","salesforce","github","linear","jira","asana","trello","intercom","zendesk","stripe-customers","shopify","airtable","confluence")?!0:Wt(t,"connected service","connected services","ingest from","pull from","sync with","sync data from","connect slack","their slack","from slack","sync slack","search slack","connect gmail","their gmail","from gmail","sync gmail","search gmail","connect notion","their notion","from notion","sync notion","search notion","connect hubspot","their hubspot","from hubspot","sync hubspot","hubspot contacts","connect linear","their linear","from linear","sync linear","mirror linear","connect jira","from jira","sync jira","connect github","from github","sync github","connect salesforce","from salesforce","sync salesforce","import contacts","import messages","import emails","external service","third-party service")}function Em(t){return t.surfaceMcp===!0||t.exposeMcp===!0?!0:t.surfaceMcp===!1||t.exposeMcp===!1?!1:Gt(t,"mcp","mcp endpoint","mcp-endpoint")?!0:Wt(t,"mcp endpoint","expose tools to ai","expose tools to agents","callable by ai agents","callable from claude","claude can call","agent integration")}function Nm(t,e){return e==="none"?Gt(t,"resend","email"):e==="email"||e==="invite-only"||Gt(t,"resend","email")||Wt(t,"email notification","email reminder","send email","resend")}function us(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[r,n]of Object.entries(Om))if(e.includes(r))return n;return"Circle"}function zn(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Pt(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\{/g,"{").replace(/\}/g,"}")}function Mm(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 s of t.publicPages){if(typeof s!="string"||s.length<1)continue;let i=s.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!i)continue;let a=i.startsWith("/")?i:"/"+i;e.includes(a)||e.push(a)}let r=e.filter(s=>s==="/"),n=e.filter(s=>s!=="/"),o=[];o.push('import { NextRequest, NextResponse } from "next/server";'),o.push(""),o.push("const PUBLIC_PREFIXES = [");for(let s of n)o.push(' "'+s+'",');return o.push("];"),o.push(""),r.length>0&&(o.push('const PUBLIC_EXACT = ["'+r.join('", "')+'"];'),o.push("")),o.push("export function middleware(req: NextRequest) {"),o.push(" const { pathname, search } = req.nextUrl;"),o.push(""),r.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(`
|
|
4714
|
+
`)}function jm(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(d=>c.startsWith(d))}).map(l=>{let c=l.path??l.route??"",u=c.startsWith("/")?c:"/"+c,d=l.name??zn(c.replace(/^\//,"")),m=us(d);return{label:d,href:u,icon:m}});n.some(l=>l.href==="/dashboard")||n.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let o=t.authModel==="none",s=[...new Set(n.map(l=>l.icon))];o||s.push("LogOut");let i=zn(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 { "+s.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">'+i+"</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(`
|
|
5009
4715
|
`)}}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, "+s.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">'+i+"</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">'+i+"</span>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),{path:"components/sidebar.tsx",content:a.join(`
|
|
5010
|
-
`)}}function
|
|
5011
|
-
`)}function
|
|
5012
|
-
`)}let r=t.publicPages?.includes("/"),n=t.design?.landingTone;if(r&&n){let s=[];return s.push('import Link from "next/link";'),s.push(""),s.push("export default function HomePage() {"),s.push(" return ("),s.push(' <main className="flex min-h-screen flex-col">'),s.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),s.push(' <h1 className="text-5xl font-bold tracking-tight">'+
|
|
5013
|
-
`)}if(r){let s=[];return s.push('import Link from "next/link";'),s.push(""),s.push("export default function HomePage() {"),s.push(" return ("),s.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),s.push(' <h1 className="text-4xl font-bold">'+
|
|
4716
|
+
`)}}function Dm(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,r=t.defaultRole??e[0],n=[];n.push("export type Role = "+e.map(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 = "'+r+'";'),n.push(""),n.push("export const ROLE_LABELS: Record<Role, string> = {");for(let o of e){let s=o.charAt(0).toUpperCase()+o.slice(1);n.push(' "'+o+'": "'+s+'",')}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(`
|
|
4717
|
+
`)}function Lm(t){let e=zn(t.name);if(t.authModel==="none"){let s=[];return s.push("export default function HomePage() {"),s.push(" return ("),s.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),s.push(' <h1 className="text-4xl font-bold">'+Pt(e)+"</h1>"),t.summary&&s.push(' <p className="mt-4 text-lg text-muted-foreground">'+Pt(t.summary)+"</p>"),s.push(" </main>"),s.push(" );"),s.push("}"),s.push(""),s.join(`
|
|
4718
|
+
`)}let r=t.publicPages?.includes("/"),n=t.design?.landingTone;if(r&&n){let s=[];return s.push('import Link from "next/link";'),s.push(""),s.push("export default function HomePage() {"),s.push(" return ("),s.push(' <main className="flex min-h-screen flex-col">'),s.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),s.push(' <h1 className="text-5xl font-bold tracking-tight">'+Pt(e)+"</h1>"),t.summary&&s.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+Pt(t.summary)+"</p>"),s.push(' <div className="flex gap-4">'),s.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">'),s.push(" Get Started"),s.push(" </Link>"),s.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),s.push(" Sign In"),s.push(" </Link>"),s.push(" </div>"),s.push(" </section>"),s.push(" </main>"),s.push(" );"),s.push("}"),s.push(""),s.join(`
|
|
4719
|
+
`)}if(r){let s=[];return s.push('import Link from "next/link";'),s.push(""),s.push("export default function HomePage() {"),s.push(" return ("),s.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),s.push(' <h1 className="text-4xl font-bold">'+Pt(e)+"</h1>"),t.summary&&s.push(' <p className="text-lg text-muted-foreground">'+Pt(t.summary)+"</p>"),s.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">'),s.push(" Sign In"),s.push(" </Link>"),s.push(" </main>"),s.push(" );"),s.push("}"),s.push(""),s.join(`
|
|
5014
4720
|
`)}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(`
|
|
5015
|
-
`)}function
|
|
5016
|
-
`)}function
|
|
5017
|
-
`)}function
|
|
5018
|
-
`)}function
|
|
5019
|
-
`)}function
|
|
5020
|
-
`)}function
|
|
5021
|
-
`)}async function
|
|
4721
|
+
`)}function $m(t,e){let r=t.authModel==="none",n=[];r||(n.push('import { Suspense } from "react";'),n.push('import { headers } from "next/headers";'),n.push('import { redirect } from "next/navigation";'),n.push('import { auth } from "@/lib/auth";'),n.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?n.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&n.push('import Sidebar from "@/components/sidebar";'),!r&&t.roles&&t.roles.length>0&&n.push('import { getUserRole } from "@/lib/roles";'),n.push(""),n.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),r?n.push(' const user = { name: "Guest", email: "" };'):(n.push(" const session = await auth.api.getSession({ headers: await headers() });"),n.push(' if (!session) redirect("/login");'),n.push(""),t.roles&&t.roles.length>0?(n.push(" const role = getUserRole(session.user as Record<string, unknown>);"),n.push(" const user = { name: session.user.name, email: session.user.email, role };")):(n.push(" const user = {"),n.push(" name: session.user.name,"),n.push(" email: session.user.email,"),n.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),n.push(" };"))),n.push("");let o=r?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(" <TopNav user={user} />"),n.push(' <main className="mx-auto max-w-7xl p-6">'+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(`
|
|
4722
|
+
`)}function Um(t){let e=zn(t.name),r=t.dataModel??[],n=[];if(r.length>0){let o=r.map(i=>us(i.entity??i.name??"item")),s=[...new Set(o)];n.push('import { Card, CardContent } from "@/components/ui/card";'),n.push("import { "+s.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">'+Pt(e)+"</h1>"),t.summary&&n.push(' <p className="mt-1 text-muted-foreground">'+Pt(t.summary)+"</p>"),n.push(" </div>"),r.length>0){n.push(' <div className="rounded-lg border p-8 text-center">'),n.push(' <h2 className="text-lg font-semibold">Get started</h2>'),n.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),n.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let o of r){let s=o.entity??o.name??"Item",i=us(s),a=zn(s.replace(/_/g,"-"));n.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),n.push(" <"+i+' 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(`
|
|
4723
|
+
`)}function Fm(t,e=!1){if(!t.multiTenant)return null;let r=[];return e?(r.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = pgTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),r.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = pgTable(")):(r.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),r.push('import { sql } from "drizzle-orm";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = sqliteTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = sqliteTable(")),r.push(' "org_member",'),r.push(" {"),r.push(' id: text("id").primaryKey(),'),r.push(' orgId: text("org_id").notNull().references(() => organization.id),'),r.push(' userId: text("user_id").notNull().references(() => user.id),'),r.push(' role: text("role").notNull(),'),e?r.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):r.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(" },"),r.push(" (table) => ({"),r.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),r.push(' userIdx: index("org_member_user_idx").on(table.userId),'),r.push(" }),"),r.push(");"),r.push(""),r.join(`
|
|
4724
|
+
`)}function qm(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(`
|
|
4725
|
+
`)}function Bm(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(`
|
|
4726
|
+
`)}function Hm(t,e,r){let n=[],o=t.split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ");n.push(`# ${o}`),n.push(""),e?.summary&&(n.push(e.summary),n.push(""));let s=e?.features??[];if(s.length>0){n.push("## Features"),n.push("");for(let c of s){let u=c.description?` \u2014 ${c.description}`:"";n.push(`- **${c.name}**${u}`)}n.push("")}n.push("## Tech Stack"),n.push(""),n.push("| Layer | Technology |"),n.push("|-------|------------|"),n.push("| Framework | Next.js 15 (App Router) |"),n.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),n.push("| Auth | Better Auth (email/password, social login) |"),n.push("| Styling | Tailwind CSS + shadcn/ui |"),n.push("| Deployment | Mistflow Cloud |"),r.hasStripe&&n.push("| Payments | Stripe |"),r.hasResend&&n.push("| Email | Resend + React Email |"),r.hasStorage&&n.push("| File Storage | Mistflow Cloud (managed blob storage) |"),r.hasAdmin&&n.push("| Admin | Better Auth admin plugin |"),r.hasAI&&n.push("| AI | Vercel AI SDK + OpenAI |"),n.push("");let i=e?.pages??[];if(i.length>0){n.push("## Pages"),n.push(""),n.push("| Route | Description |"),n.push("|-------|-------------|");for(let c of i){let u=c.path??c.route??c.name??"",d=c.description??"";n.push(`| \`${u.startsWith("/")?u:"/"+u}\` | ${d} |`)}n.push("")}let a=e?.dataModel??[];if(a.length>0){n.push("## Data Model"),n.push("");for(let c of a){let u=c.entity??c.name??"Unknown";if(n.push(`### ${u}`),n.push(""),c.fields.length>0){if(typeof c.fields[0]=="string")n.push(`Fields: ${c.fields.join(", ")}`);else{n.push("| Field | Type |"),n.push("|-------|------|");for(let d of c.fields)n.push(`| ${d.name} | ${d.type} |`)}n.push("")}}}n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),r.isNeon?n.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(n.push("| `TURSO_URL` | Database connection URL | Yes |"),n.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),n.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),r.hasStripe&&(n.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),n.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),n.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),r.hasResend&&(n.push("| `RESEND_API_KEY` | Email sending key | Managed by Mistflow in production; optional local override |"),n.push("| `EMAIL_FROM` | Sender email address | Managed by Mistflow in production; optional local override |")),(r.hasAI||r.hasStorage)&&n.push("| `MISTFLOW_RUNTIME_KEY` | Mistflow Cloud runtime key \u2014 authenticates AI gateway, file storage, and other managed features | Auto-provisioned at `mist_init` |"),r.hasAI&&n.push("| `OPENROUTER_API_KEY` | OpenRouter key for your-key fallback (only used when `MISTFLOW_RUNTIME_KEY` is unset) | Optional |"),n.push(""),n.push("### Local database"),n.push(""),r.isNeon?(n.push("For local development, start a local Postgres server:"),n.push(""),n.push("```bash"),n.push("# Using Docker:"),n.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),n.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),n.push("```")):(n.push("For local development, start a local Turso server:"),n.push(""),n.push("```bash"),n.push("npx turso dev"),n.push("```")),n.push(""),n.push("Then set up the database:"),n.push(""),n.push("```bash"),n.push("npm run db:push"),n.push("```"),n.push(""),n.push("### Run"),n.push(""),n.push("```bash"),n.push("npm run dev"),n.push("```"),n.push(""),n.push("Open [http://localhost:3000](http://localhost:3000)."),n.push(""),n.push("## Project Structure"),n.push(""),n.push("```"),n.push("app/"),n.push(" (auth)/ Login and registration pages"),n.push(" (dashboard)/ Authenticated app pages"),r.hasAdmin&&n.push(" admin/ Admin panel pages (at /admin/...)"),n.push(" home/ Public landing page (served via / \u2192 /home redirect)"),n.push(" api/ API routes (auth, health, webhooks)"),n.push(" layout.tsx Root layout with fonts and providers"),n.push(" globals.css Design tokens and Tailwind config"),n.push("components/ Reusable UI components"),n.push("db/"),n.push(" schema/ Database table definitions"),n.push(" index.ts Schema exports"),n.push("lib/"),n.push(" auth.ts Better Auth server config"),n.push(" auth-client.ts Better Auth client config"),n.push(` db.ts ${r.isNeon?"Postgres":"SQLite"} database connection`),r.hasStripe&&n.push(" stripe.ts Stripe client"),r.hasResend&&(n.push(" resend.ts Resend client"),n.push(" email.ts Email send helpers")),n.push(" server/storage.ts File upload/download helpers (managed R2)"),r.hasAI&&(n.push(" ai.ts Back-compat export for server AI helpers"),n.push(" server/ai.ts Server-only AI Gateway and provider helpers")),r.hasResend&&n.push("emails/ React Email templates"),n.push("```"),n.push(""),n.push("## Deploy"),n.push(""),n.push("Deploy to production with Mistflow:"),n.push(""),n.push("```"),n.push("# In your AI editor (Claude Code, Cursor, etc.):"),n.push("mist_deploy action='deploy'"),n.push("```"),n.push(""),n.push("Your app will be live at `https://<app-name>.mistflow.app`."),n.push("");let l=e?.pickedDirection;if(l||e?.design){n.push("## Design"),n.push(""),typeof l?.name=="string"&&n.push(`- **Picked direction**: ${l.name}`);let c=l?.fonts&&typeof l.fonts=="object"?l.fonts:void 0;c?(typeof c.display=="string"&&n.push(`- **Display font**: ${c.display}`),typeof c.body=="string"&&n.push(`- **Body font**: ${c.body}`)):e?.design?.fonts&&(n.push(`- **Heading font**: ${e.design.fonts.heading}`),n.push(`- **Body font**: ${e.design.fonts.body}`));let u=l?.colors&&typeof l.colors=="object"?l.colors:void 0;typeof u?.accent=="string"?n.push(`- **Accent color**: ${u.accent}`):e?.design?.accentColor&&n.push(`- **Accent color**: ${e.design.accentColor}`),e?.design?.borderRadius&&n.push(`- **Border radius**: ${e.design.borderRadius}`),!l&&e?.design?.tone&&n.push(`- **Tone**: ${e.design.tone}`),n.push("")}return n.push("---"),n.push(""),n.push("Built with [Mistflow](https://mistflow.ai)"),n.push(""),n.join(`
|
|
4727
|
+
`)}async function zm(t,e){if(!Ie())return je("scaffold a new project");if(!ln())return p(JSON.stringify({status:"node_version_unsupported",code:"node_version_unsupported",message:zt(),nextAction:"Tell the user their Node version is too old, paste the upgrade command from `message`, and stop. Do NOT proceed with mist_init \u2014 the scaffolded app would build-fail at deploy time."}),!0);let{name:r,plan:n,path:o,planId:s,sessionId:i}=t,a,l=[],c,u=null,d=n;if(typeof d=="string")try{let S=JSON.parse(d);S&&typeof S=="object"&&!Array.isArray(S)&&"plan"in S?d=S.plan:d=S}catch{return p("mist_init received `plan` as a string, but it is not valid JSON. Pass the plan object directly or pass planId from mist_plan.",!0)}if(!d&&s){if(u=am(s),!u)return p(`No plan found for planId '${s}'. Call mist_plan first, or pass the plan object inline.`,!0);d=u.plan}if(!d&&i){let S=await Ro(i);S&&(d=S.plan)}if(!d||typeof d!="object"||Array.isArray(d))return p("mist_init requires a plan object or a valid planId from mist_plan. Refusing to scaffold without a structured plan because mist_implement would not know what to build.",!0);let m=o??u?.scaffoldTargetPath;if(!m)return p("mist_init requires an explicit 'path' unless the planId cache includes a scaffoldTargetPath. Call mist_init with the planId returned by mist_plan, pass the absolute scaffold directory, or pass { sessionId, path } in session mode.",!0);if(!om(m))return p(`mist_init 'path' must be an absolute path \u2014 received '${m}'. Pass the full absolute path to the target directory.`,!0);let h=Ka(m),_=r??(typeof d.name=="string"?d.name:void 0);if(!_)return p("mist_init requires a human-readable app name. Pass `name`, or call it with a planId whose cached plan includes a name.",!0);let P=d?.design,y=d,v=y?.pickedDirection??y?.designDirection??void 0,N=xm(_,v),K=typeof d.authModel=="string"?d.authModel:void 0,z=K==="none",re=Pm(d),de=Nm(d,K),te=d?Wt(d,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,B=d?Wt(d,"admin panel","admin dashboard","admin management"):!1,R=d?Rm(d):!1,oe=d?Em(d):!1,W=d?Am(d):!1,ae=W,T=typeof d.dbProvider=="string"?d.dbProvider:"neon",H=Array.isArray(d.dataModel)&&d.dataModel.length>0,$=T==="none"||z&&!H&&!te,V=$?"none":T,ne=V==="neon";if(!bm(h))return p(wm(h,d?.name),!0);pn(h,{recursive:!0});try{try{let w=he(h,".mistflow","rules");pn(w,{recursive:!0}),bt(he(w,"design-quality.md"),Ir),bt(he(w,"landing.md"),Pr)}catch(w){console.error("Could not write design rule files:",w instanceof Error?w.message:w)}try{let w=he(Hn(h),".mistflow","mockups");if(ze(w)){let I=Ja(w).filter(F=>F.endsWith(".html"));if(I.length>0){let F=he(h,".mistflow","mockups");pn(F,{recursive:!0});for(let Re of I)rm(he(w,Re),he(F,Re));console.error(`Copied ${I.length} mockup file(s) into project`)}}}catch(w){console.error("Could not copy mockup files:",w instanceof Error?w.message:w)}let S=null;try{S=await bo("nextjs")}catch(w){console.error("Could not fetch scaffold from API, using minimal scaffold:",w instanceof Error?w.message:w)}if(S){let w=_.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let k of S.files){if(k.path==="package.json"||k.path==="middleware.ts"||k.path==="components/sidebar.tsx"||k.path==="components/topnav.tsx"||k.path==="app/(dashboard)/layout.tsx"||k.path==="app/(dashboard)/page.tsx"||k.path==="app/(dashboard)/dashboard/page.tsx"||$&&(k.path==="lib/db.ts"||k.path==="drizzle.config.ts"||k.path==="db/index.ts"||k.path.startsWith("db/schema/"))||z&&(k.path.includes("(auth)")||k.path.includes("(admin)")||k.path.startsWith("app/admin/")||k.path.includes("components/auth/")||k.path.includes("admin-sidebar")||k.path.includes("app/api/auth/")||k.path.includes("app/api/admin/seed")||k.path==="lib/auth.ts"||k.path==="lib/auth-client.ts"||k.path==="db/schema/auth.ts"||k.path==="db/schema/index.ts"||k.path==="db/index.ts")||!re&&(k.path.includes("stripe")||k.path.includes("webhook/stripe"))||!de&&(k.path.includes("resend")||k.path.includes("emails/"))||!B&&(k.path.includes("(admin)")||k.path.startsWith("app/admin/")||k.path.includes("admin-sidebar"))||ne&&(k.path==="lib/db.ts"||k.path==="lib/auth.ts"||k.path==="drizzle.config.ts"||k.path==="db/schema/auth.ts"))continue;let G=k.content.replace(/\{\{APP_NAME\}\}/g,_).replace(/\{\{WORKER_NAME\}\}/g,w);if(ne&&k.path==="next.config.ts"&&(G=G.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),k.path==="next.config.ts"){let fe=dm(h);fe&&(console.error(`[init] Project is inside monorepo at ${fe} \u2014 adding outputFileTracingRoot`),G.includes("outputFileTracingRoot")||(G=G.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
5022
4728
|
import { dirname } from "path";
|
|
5023
4729
|
import { fileURLToPath } from "url";
|
|
5024
4730
|
|
|
5025
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));`),
|
|
5026
|
-
images: {`)))}!
|
|
4731
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));`),G=G.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
4732
|
+
images: {`)))}!B&&k.path.includes("sidebar")&&(G=G.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),G=G.replace(/, Shield/g,"")),E(h,k.path,G)}let I={...S.dependencies},F={...S.devDependencies};if(I["drizzle-zod"]||(I["drizzle-zod"]="^0.5.1"),z&&delete I["better-auth"],$&&(delete I["drizzle-orm"],delete I["@libsql/client"],delete I["@neondatabase/serverless"],delete F["drizzle-kit"],delete F["@electric-sql/pglite"]),ne&&(delete I["@libsql/client"],I["@neondatabase/serverless"]="^0.10.0",F["@electric-sql/pglite"]="^0.2.0"),re&&(I.stripe="^17.0.0"),de&&(I.resend="^4.0.0",I["@react-email/components"]="^0.0.31"),R&&(I.ai="^4.0.0",I["@ai-sdk/openai"]="^1.0.0",I.openai="^4.0.0",I["server-only"]="^0.0.1",I["zod-to-json-schema"]="3.24.6"),oe&&ne){let k=Zo({appName:_,appVersion:"0.0.1",useAiChatManifest:an(d)});for(let[G,fe]of Object.entries(k.packageJsonDeps))G==="zod-to-json-schema"&&I[G]||(I[G]=fe)}if(W&&ne)for(let k of Ar.dependencies)k.dependencyType==="devDependency"?F[k.packageName]||(F[k.packageName]=k.versionRange):I[k.packageName]||(I[k.packageName]=k.versionRange);let Re={"@noble/ciphers":"^1.3.0"},Ss={react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"},wn={dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint",...$?{}:{"db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"}};if(E(h,"package.json",JSON.stringify({name:_,version:"0.1.0",private:!0,scripts:wn,dependencies:I,devDependencies:F,optionalDependencies:Re,overrides:Ss},null,2)),S.methodology){let k=S.methodology;ne||(k=k.replace(/import \{ pgTable, text, timestamp(?:, boolean)? \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
|
5027
4733
|
import { sql } from "drizzle-orm";`).replace(/import \{ pgTable, text \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
5028
|
-
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)')),
|
|
5029
|
-
|
|
5030
|
-
`+
|
|
5031
|
-
`,
|
|
5032
|
-
`)),
|
|
5033
|
-
`)),
|
|
5034
|
-
`)),
|
|
5035
|
-
`)),
|
|
5036
|
-
`));else{if(
|
|
5037
|
-
`)),
|
|
5038
|
-
`)),
|
|
5039
|
-
`)),
|
|
5040
|
-
`))}}else
|
|
5041
|
-
`)),
|
|
5042
|
-
`)),
|
|
5043
|
-
`)),
|
|
5044
|
-
`))),
|
|
5045
|
-
`)),
|
|
5046
|
-
`)),
|
|
5047
|
-
`)),ce&&(j(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.","","// 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(`
|
|
5048
|
-
`)),
|
|
5049
|
-
`)),!0&&(
|
|
5050
|
-
`)));let
|
|
4734
|
+
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)')),k=as(k),k=k+`
|
|
4735
|
+
|
|
4736
|
+
`+cm+`
|
|
4737
|
+
`,E(h,"AGENTS.md",k),E(h,"CLAUDE.md",k),gm(h,k)}S.skills&&Object.keys(S.skills).length>0&&ym(h,S.skills);let le=a??d?.designMd??N;if(le&&E(h,"DESIGN.md",le),c&&E(h,"PLAN.md",c),ne)if(E(h,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";','import * as schema from "@/db/schema";',"","// 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. Pass `schema` so `db.query.<table>`"," // (Drizzle's relational query builder) is populated \u2014 without it,"," // `db.query.<anything>` is undefined and crashes at runtime."," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql, { schema });",' } 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(`
|
|
4738
|
+
`)),E(h,"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";','import * as schema from "@/db/schema";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client, { schema });","}",""].join(`
|
|
4739
|
+
`)),E(h,"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(`
|
|
4740
|
+
`)),z)E(h,"db/schema/index.ts",["// Re-export schema tables here as they are added.",oe?'export * from "./mcp";':null,W?'export * from "./connected-services";':null,""].filter(k=>k!==null).join(`
|
|
4741
|
+
`)),E(h,"db/index.ts",["// Re-export schema tables here as they are added.",'export * from "./schema";',""].join(`
|
|
4742
|
+
`));else{if(E(h,"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(`
|
|
4743
|
+
`)),E(h,"db/schema/index.ts",['export * from "./auth";',oe?'export * from "./mcp";':null,W?'export * from "./connected-services";':null,""].filter(G=>G!==null).join(`
|
|
4744
|
+
`)),E(h,"db/index.ts",['export * from "./schema/auth";',oe?'export * from "./schema/mcp";':null,W?'export * from "./schema/connected-services";':null,""].filter(G=>G!==null).join(`
|
|
4745
|
+
`)),oe&&ne){let G=Zo({appName:_,appVersion:"0.0.1",useAiChatManifest:an(d)});for(let fe of G.files)E(h,fe.path,fe.content);E(h,"db/schema/mcp.ts",G.schemaFragment)}if(W&&ne)for(let G of Ar.files){if(G.kind==="schema"){E(h,"db/schema/connected-services.ts",G.source);continue}G.kind==="migration"||G.kind==="manifest"||G.source&&E(h,G.targetFile,G.source)}let k=d.defaultRole??"user";E(h,"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;"," const googleClientId = process.env.GOOGLE_CLIENT_ID;"," const googleClientSecret = process.env.GOOGLE_CLIENT_SECRET;"," // 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";',' const isProduction = runtimeKeyEnvironment === "production";'," // Google sign-in routing:"," // - Production with both GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET set:"," // use the customer's Google client (consent screen branded as their app)."," // - Otherwise (preview, dev, or missing BYO keys): use Mistflow's hosted"," // OAuth proxy. Customers never need to register preview URLs in Google"," // Console \u2014 the proxy fans them out from a single canonical redirect URI."," const useByoGoogle = isProduction && Boolean(googleClientId && googleClientSecret);"," const useProxyGoogle = !useByoGoogle && Boolean(mistflowAppId && mistflowOAuthProxyURL);"," const googleProviderConfig = useByoGoogle"," ? {",' providerId: "google",'," clientId: googleClientId!,"," clientSecret: googleClientSecret!,",' discoveryUrl: "https://accounts.google.com/.well-known/openid-configuration",',' scopes: ["openid", "email", "profile"],'," pkce: true,"," redirectURI: `${baseURL}/api/auth/oauth2/callback/google`,"," }"," : useProxyGoogle"," ? {",' 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`,"," }"," : null;"," if (googleProviderConfig) {",' console.error(`[auth] Google sign-in: ${useByoGoogle ? "BYO (your Google client)" : "proxy (Mistflow-hosted)"}`);'," }"," // 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: "${k}" }),`," ...(googleProviderConfig ? [genericOAuth({ config: [googleProviderConfig] })] : []),"," nextCookies(),"," ],"," databaseHooks: {"," user: {"," create: {"," // Auto-promote the app admin on first signup when the plan has"," // a global admin role. ADMIN_EMAIL is injected by the Mistflow"," // deploy pipeline (the email of the account that ran"," // mist_deploy). Tenant roles such as workspace owner are stored"," // separately in app tables. 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(`
|
|
4746
|
+
`))}}else E(h,"package.json",JSON.stringify({name:_,version:"0.1.0",private:!0},null,2));let qe=a??d?.designMd??N;E(h,"app/globals.css",za(P,qe)),E(h,"app/layout.tsx",Im(_,P,y?.language)),E(h,"README.md",Hm(_,d,{hasStripe:re,hasResend:de,hasStorage:te,hasAdmin:B,hasAI:R,isNeon:ne})),E(h,"contracts/README.md",is());let J=d?.dataModel??[],_e=new Set,ke=0;for(let w of J){let I=w.entity??w.name;if(!I||typeof I!="string")continue;let F=cs(I);_e.has(F)||(_e.add(F),E(h,F,ls(I)),ke++)}ke===0&&E(h,"contracts/.gitkeep","");let ie=[],Te=d?.publicPages;if(Array.isArray(Te))ie=Te;else if(typeof Te=="string"){try{ie=JSON.parse(Te)}catch{ie=[]}Array.isArray(ie)||(ie=[])}if(d?.publicLanding===!1)ie=ie.filter(w=>w!=="/");else if(!ie.includes("/")){let w=d?.steps?.some(F=>{let Re=((F.name??"")+" "+(F.description??"")).toLowerCase();return Re.includes("landing")||Re.includes("marketing")||Re.includes("homepage")}),I=d?.pages?.some(F=>F.path==="/");(w||I)&&(ie=["/",...ie])}let Le={name:_,summary:d?.summary,authModel:K,roles:d?.roles,defaultRole:d?.defaultRole,publicPages:ie,navStyle:d?.navStyle,multiTenant:d?.multiTenant,pages:d?.pages,dataModel:d?.dataModel,design:d?.design},it=Mm(Le);it&&E(h,"middleware.ts",it);let Qe=jm(Le);Qe&&E(h,Qe.path,Qe.content);let wt=Dm(Le);if(wt&&E(h,"lib/roles.ts",wt),E(h,"app/page.tsx",Lm(Le)),E(h,"app/(dashboard)/layout.tsx",$m(Le,B)),E(h,"app/(dashboard)/dashboard/page.tsx",Um(Le)),Le.multiTenant){let w=Fm(Le,ne);w&&E(h,"db/schema/organization.ts",w);let I=qm(Le);I&&E(h,"lib/org.ts",I);let F=Bm(Le);F&&E(h,"components/org-switcher.tsx",F)}E(h,"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)),re&&E(h,"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(`
|
|
4747
|
+
`)),de&&(E(h,"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(`
|
|
4748
|
+
`)),E(h,"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(`
|
|
4749
|
+
`)),E(h,"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(`
|
|
4750
|
+
`))),E(h,"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(`
|
|
4751
|
+
`)),E(h,"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(`
|
|
4752
|
+
`)),E(h,"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(`
|
|
4753
|
+
`)),R&&(E(h,"lib/server/ai.ts",['import "server-only";',"",'import { createOpenAI } from "@ai-sdk/openai";','import { generateText, streamText, type CoreMessage } from "ai";','import type { z } from "zod";','import { zodToJsonSchema } from "zod-to-json-schema";',"","// Bumped from 2 -> 3 when the wrapper unified on @ai-sdk/openai + the","// Mistflow /v1/* OpenAI-compat surface. Earlier versions called the","// Mistflow-native /api/ai-gateway/runtime/* endpoints directly.","export const MISTFLOW_AI_HELPER_VERSION = 4;","","// Embedding dimension is SCHEMA for any app that stores vectors in a","// DB column (pgvector etc.). The scaffold declared the column with","// this exact value; if you swap the embed model or switch BYOK modes","// and the new model returns a different dim, ai.embed() will throw","// an actionable error BEFORE the bad vectors hit your DB.","// Managed mode default (text-embedding-3-small) = 1536. If you switch","// to a different model with a different dim, you must also migrate","// every vector column and re-embed every existing row.","export const EMBEDDING_DIMENSIONS = 1536;","","// \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 Mode detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Two modes:","// 1. Managed (default): MISTFLOW_RUNTIME_KEY set \u2192 calls Mistflow /v1/*","// surface, billed in Mistflow credits.","// 2. Direct BYOK: OPENROUTER_API_KEY set \u2192 calls openrouter.ai/api/v1/*","// directly with the customer's key. Mistflow never sees these","// requests. Customer pays OpenRouter directly.","// Voice realtime is NOT part of either mode \u2014 it's a separate xAI","// direct integration. See methodologies/voice-realtime.md.",'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(/\\/$/, "");',"}","","// Direct BYOK mode: the customer set OPENROUTER_API_KEY. We route all","// supported modalities (chat/embed/image/TTS/STT) directly to OpenRouter","// with their key. Voice realtime is NOT part of either mode \u2014 see","// methodologies/voice-realtime.md for the bring-your-own-xAI pattern.","const useDirect = !!process.env.OPENROUTER_API_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."`," );","}","","// \u2500\u2500 Role \u2192 OpenRouter model mapping (Direct BYOK mode only) \u2500\u2500\u2500\u2500\u2500\u2500\u2500",'// In managed mode, role names ("chat", "reasoning", etc) are sent',"// straight to /v1/* and the gateway resolves them against the curated","// catalog. In direct mode, we translate roles to concrete OpenRouter",`// model IDs because OpenRouter doesn't know what "chat" means.`,"//",'// Override per call site: pass an explicit model (any "provider/model"',"// string passes through verbatim).","// Override globally per role via env var, e.g. MISTFLOW_ROLE_CHAT=openai/gpt-5.","// These are the OpenRouter model IDs as of May 2026. Update via dashboard","// (Phase 3) or hand-edit when OpenRouter renames models. Mistflow won't","// push retroactive changes \u2014 your app stays on these defaults until you","// redeploy with new ones.","const ROLE_TO_OPENROUTER: Record<string, string> = {",' chat: "anthropic/claude-sonnet-4.6",',' reasoning: "openai/gpt-5.5",',' classify: "openai/gpt-5.4-mini",'," // vision is image-IN, text-OUT \u2014 describe / classify / extract from a"," // photo. Distinct from `image` (text -> image generation). gpt-4o is"," // the cheapest strongly-multimodal OpenRouter route; bump to gpt-5 for"," // harder visual reasoning.",' vision: "openai/gpt-4o",'," // 1536-dim, matches the scaffold's EMBEDDING_DIMENSIONS so vector"," // DB columns keep working after a Direct BYOK switch with no override.",' embed: "openai/text-embedding-3-small",',' image: "openai/gpt-5.4-image-2",',' tts: "openai/gpt-4o-mini-tts-2025-12-15",',' stt: "openai/whisper-large-v3",',"};","","function resolveModel(modelOrRole: string | undefined, role: string | undefined, defaultRole: string): string {"," // Explicit model on the call wins (host AI may pick a specific model"," // when context demands it, e.g. claude-opus-4 for hard reasoning)."," const id = modelOrRole ?? role ?? defaultRole;"," // Explicit provider-prefixed ID (foo/bar) passes through in both modes.",' if (id.includes("/")) return id;'," // Env var override (dashboard-set or hand-set per project)."," const envOverride = process.env[`MISTFLOW_ROLE_${id.toUpperCase()}`];"," if (envOverride) return envOverride;"," // Direct mode: translate role \u2192 OpenRouter ID."," if (useDirect) return ROLE_TO_OPENROUTER[id] ?? id;"," // Managed mode: pass role/semantic-id straight to /v1/* and let the",' // backend resolve. "chat" is a valid model field in our /v1/* surface.'," return id;","}","","// \u2500\u2500 Unified client (managed \u2192 Mistflow /v1, direct \u2192 OpenRouter /v1) \u2500\u2500","// Both modes are OpenAI-compatible at the wire level. The only thing","// that changes between modes is baseURL + apiKey. This is the whole","// point of standardizing on /v1/* for our managed surface.","const baseURL = useDirect",' ? "https://openrouter.ai/api/v1"',' : mistflowAiApiUrl() + "/v1";',"const apiKey = useDirect",' ? (process.env.OPENROUTER_API_KEY ?? "")',' : (runtimeKey() ?? "");',"","const client = createOpenAI({"," apiKey,"," baseURL,"," ...(useDirect ? {"," headers: {",' "HTTP-Referer": process.env.NEXT_PUBLIC_APP_URL ?? "https://mistflow.app",',' "X-Title": "Mistflow App",'," },"," } : {}),","});","","// Kept as a named export for back-compat with code that imported","// `openrouter` directly. Equivalent to `client` when in direct mode.","export const openrouter = useDirect ? client : createOpenAI({",' apiKey: process.env.OPENROUTER_API_KEY ?? "",',' baseURL: "https://openrouter.ai/api/v1",',"});","","// \u2500\u2500 Raw fetch helper for /v1/* endpoints (non-chat modalities) \u2500\u2500\u2500\u2500","// We use AI SDK for chat (its primitives handle streaming, tool calls,","// finish_reason semantics, etc). For embed/image/TTS/STT we hit /v1/*","// directly \u2014 both modes accept the same OpenAI shape, with adapters","// where OpenRouter diverges (image gen and STT).","async function v1Post(path: string, body: unknown, init?: { isFormData?: boolean; body?: BodyInit }): Promise<Response> {"," if (!apiKey) throw noConfigError();"," const isForm = init?.isFormData === true;"," const headers: Record<string, string> = {",' "Authorization": "Bearer " + apiKey,'," };",' if (!isForm) headers["Content-Type"] = "application/json";'," const response = await fetch(baseURL + path, {",' method: "POST",'," headers,"," body: isForm ? (init?.body as BodyInit) : JSON.stringify(body),"," });"," if (response.status === 401) {"," throw new AIConfigError(useDirect",' ? "OpenRouter rejected your key. Check OPENROUTER_API_KEY."',' : "Runtime key rejected by gateway. Re-run mist_setup.");'," }"," if (response.status === 402) {"," throw new AICreditExhaustedError(useDirect",' ? "OpenRouter credits exhausted. Top up at https://openrouter.ai/credits"',' : "Mistflow credits exhausted. Top up at https://app.mistflow.ai/ai-gateway");'," }",' if (response.status === 429) throw new AIRateLimitError("Rate limited. Retry with backoff.");'," if (!response.ok) {",' const text = await response.text().catch(() => "");',' throw new AIModelError("AI gateway error " + response.status + ": " + redact(text));'," }"," return response;","}","","// \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 or","// direct BYOK). Never write process.env.OPENROUTER_API_KEY or","// MISTFLOW_RUNTIME_KEY in feature code.","","// Roles are Mistflow's stable abstraction. The host AI picks one per","// call site at scaffold time. In managed mode the gateway resolves;","// in direct mode the wrapper translates to a concrete OpenRouter ID","// (see ROLE_TO_OPENROUTER). Override via `model` only when a specific","// model is genuinely required.",'// "voice_realtime" is intentionally NOT in this type. Voice realtime',"// doesn't go through this wrapper \u2014 see methodologies/voice-realtime.md","// for the bring-your-own-xAI direct integration pattern.",'export type AiRole = "chat" | "reasoning" | "classify" | "vision" | "image" | "embed" | "tts" | "stt";',"","// 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 };","","// Convert OpenAI-shaped tool definitions to the AI SDK's tool() shape.","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;","}","","// Translate AI-SDK-style errors (or fetch errors) into the typed hierarchy.","function mapAiSdkError(err: unknown): Error {"," const e = err as { status?: number; statusCode?: number; message?: string; name?: string };"," const status = e?.status ?? e?.statusCode;",' if (status === 401) return new AIConfigError(useDirect ? "OpenRouter rejected your key." : "Runtime key rejected by gateway.");',' if (status === 402) return new AICreditExhaustedError("AI credits exhausted.");',' if (status === 429) return new AIRateLimitError("Rate limited by gateway. Retry with backoff.");',' return new AIModelError("AI text generation failed: " + (e?.message ?? String(err)));',"}","","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. Used when"," // the model may invoke a tool. Routes through AI SDK's generateText"," // either against Mistflow /v1/chat/completions or OpenRouter /v1/chat/completions."," async textFull(opts: TextOptions): Promise<TextResult> {"," if (!isManagedAvailable() && !isBYOKAvailable()) throw noConfigError();",' const modelId = resolveModel(opts.model, opts.role, "chat");'," try {"," const result = await generateText({"," model: client.chat(modelId),"," messages: opts.messages,",' ...(opts.tools ? { tools: openAiToolsAsSdkTools(opts.tools) as Parameters<typeof generateText>[0]["tools"] } : {}),',' ...(opts.toolChoice ? { toolChoice: opts.toolChoice as Parameters<typeof generateText>[0]["toolChoice"] } : {}),'," });"," return {"," text: result.text,"," toolCalls: 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: result.finishReason,"," };"," } catch (err) {"," throw mapAiSdkError(err);"," }"," },",""," // Streaming text. Returns an AI-SDK DataStreamResponse \u2014 wire into"," // an HTTP route by returning it from the handler directly."," async streamText(opts: TextOptions): Promise<Response> {"," if (!isManagedAvailable() && !isBYOKAvailable()) throw noConfigError();",' const modelId = resolveModel(opts.model, opts.role, "chat");'," try {"," const result = streamText({"," model: client.chat(modelId),"," messages: opts.messages,",' ...(opts.tools ? { tools: openAiToolsAsSdkTools(opts.tools) as Parameters<typeof streamText>[0]["tools"] } : {}),',' ...(opts.toolChoice ? { toolChoice: opts.toolChoice as Parameters<typeof streamText>[0]["toolChoice"] } : {}),'," });"," return result.toTextStreamResponse();"," } catch (err) {"," throw mapAiSdkError(err);"," }"," },",""," // Vision: describe / classify / extract from an image. Pass a URL or"," // an in-memory buffer; the wrapper builds the multimodal CoreMessage[]"," // so callers don't need to know the SDK shape. When `schema` is set,"," // returns the parsed JSON; otherwise returns the model's text."," async vision<T = string>(opts: {"," image: string | URL | Uint8Array | ArrayBuffer | Blob;"," prompt: string;"," schema?: z.ZodType<T>;"," role?: AiRole;"," model?: string;"," useCase?: string;"," }): Promise<T> {"," const imagePart ="," opts.image instanceof URL"," ? opts.image",' : typeof opts.image === "string"'," ? new URL(opts.image)"," : opts.image;"," const messages: CoreMessage[] = [];"," if (opts.schema) {",' const jsonSchema = zodToJsonSchema(opts.schema, { target: "openApi3" });'," messages.push({",' role: "system",'," content:",' "Respond ONLY with valid JSON matching this schema: " +'," JSON.stringify(jsonSchema) +",' ". No prose, no markdown, no surrounding text.",'," });"," }"," messages.push({",' role: "user",'," content: [",' { type: "text", text: opts.prompt },',' { type: "image", image: imagePart },'," ],"," });"," const text = await this.text({"," messages,",' role: opts.role ?? "vision",'," model: opts.model,",' useCase: opts.useCase ?? "vision",'," });"," if (!opts.schema) return text as unknown as T;"," let parsed: unknown;"," try {"," parsed = JSON.parse(text);"," } catch {",' throw new AISchemaError("Vision model returned non-JSON output", redact(text));'," }"," const result = opts.schema.safeParse(parsed);"," if (!result.success) {"," throw new AISchemaError(",' "Vision output failed schema validation: " + result.error.message,'," redact(text),"," );"," }"," return result.data;"," },",""," async extractJSON<T>(opts: { prompt: string; schema: z.ZodType<T>; model?: string; useCase?: string }): Promise<T> {"," // JSON-schema-prompt + local Zod validation. Works in both modes.",' 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() && !isBYOKAvailable()) throw noConfigError();",' const modelId = resolveModel(opts.model, opts.role, "embed");',' const response = await v1Post("/embeddings", { model: modelId, input });'," const json = (await response.json()) as { data: Array<{ embedding: number[]; index: number }> };"," const vectors = json.data.map((d) => d.embedding);"," // Embedding dimension is SCHEMA, not config. If your app stores"," // these in a vector DB (pgvector, etc.), the column was declared"," // with EMBEDDING_DIMENSIONS = 1536 by the scaffold. A model switch"," // (e.g. managed \u2192 Direct BYOK) can silently change the returned"," // dimension, which would explode at INSERT time deep inside your"," // code. Catch it here at the boundary with an actionable error."," if (vectors.length > 0 && vectors[0].length !== EMBEDDING_DIMENSIONS) {"," throw new AIConfigError(",' "Embedding dimension mismatch: configured EMBEDDING_DIMENSIONS=" +',' EMBEDDING_DIMENSIONS + " but model " + modelId + " returned " +',` vectors[0].length + ". Your vector DB schema won't accept these. " +`,' "Either pick a model whose dimension matches your schema, or run " +',' "a migration to re-declare the vector column with the new dim and " +',' "re-embed all rows. NEVER mix dimensions in one column."'," );"," }"," return vectors;"," },",""," async generateImage(opts: ImageOptions): Promise<Array<{ url?: string; b64_json?: string }>> {"," if (!isManagedAvailable() && !isBYOKAvailable()) throw noConfigError();",' const modelId = resolveModel(opts.model, opts.role, "image");'," if (useDirect) {"," // OpenRouter quirk: image gen routes through /chat/completions",' // with modalities: ["image"]. The image data lands in the response'," // message.images array as a data URL.",' const response = await v1Post("/chat/completions", {'," model: modelId,",' messages: [{ role: "user", content: opts.prompt }],',' modalities: ["image", "text"],'," });"," const json = (await response.json()) as {"," choices?: Array<{ message?: { images?: Array<{ image_url?: { url?: string } }> } }>;"," };"," const images = json.choices?.[0]?.message?.images ?? [];"," return images.map((img) => {",' const url = img.image_url?.url ?? "";',' if (url.startsWith("data:image")) {',' return { b64_json: url.split(",")[1] ?? "" };'," }"," return { url };"," });"," }"," // Managed: classic OpenAI shape /v1/images/generations.",' const response = await v1Post("/images/generations", {'," model: modelId,"," prompt: opts.prompt,",' size: opts.size ?? "1024x1024",',' response_format: "b64_json",'," });"," const json = (await response.json()) as { data: Array<{ url?: string; b64_json?: string }> };"," return json.data;"," },",""," async speak(opts: TTSOptions): Promise<Blob> {"," if (!isManagedAvailable() && !isBYOKAvailable()) throw noConfigError();",' const modelId = resolveModel(opts.model, opts.role, "tts");'," // Both modes: OpenAI-shape /v1/audio/speech. We always request mp3"," // because (a) it's universally playable, (b) Mistral TTS providers"," // only support mp3, and (c) it's smaller on the wire than pcm."," // OpenAI's classic default is pcm; OpenRouter's default is also pcm,"," // so explicit mp3 is required.",' const response = await v1Post("/audio/speech", {'," model: modelId,"," input: opts.text,",' voice: opts.voice ?? "alloy",',' response_format: "mp3",'," });"," return await response.blob();"," },",""," async transcribe(opts: STTOptions): Promise<{ text: string }> {"," if (!isManagedAvailable() && !isBYOKAvailable()) throw noConfigError();",' const modelId = resolveModel(opts.model, opts.role, "stt");'," const buf = opts.audio instanceof Blob ? await opts.audio.arrayBuffer() : opts.audio;"," if (useDirect) {"," // OpenRouter STT shape: { model, input_audio: { data: base64, format } }",` // \u2014 not OpenAI's multipart file upload. Default the format to "wav"`," // when we can't infer from the Blob's MIME type."," const bytes = new Uint8Array(buf);",' let binary = "";'," for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);",' const b64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(binary, "binary").toString("base64");',' const mime = opts.audio instanceof Blob ? opts.audio.type : "";',' const format = mime.includes("wav") ? "wav"',' : mime.includes("mpeg") || mime.includes("mp3") ? "mp3"',' : mime.includes("webm") ? "webm"',' : mime.includes("m4a") || mime.includes("mp4") ? "m4a"',' : mime.includes("ogg") ? "ogg"',' : "wav";',' const response = await v1Post("/audio/transcriptions", {'," model: modelId,"," input_audio: { data: b64, format },"," });"," return (await response.json()) as { text: string };"," }"," // Managed: classic OpenAI multipart upload to /v1/audio/transcriptions."," const formData = new FormData();",' formData.append("file", new Blob([buf]), "audio.webm");',' formData.append("model", modelId);',' const response = await v1Post("/audio/transcriptions", null, { isFormData: true, body: formData });'," return (await response.json()) as { text: string };"," },",""," // Voice realtime is not part of `ai`. To build voice features, follow"," // the xAI direct pattern: bring an XAI_API_KEY, mint an ephemeral session"," // server-side, connect via WebRTC client-side. See"," // methodologies/voice-realtime.md for a full scaffold.","};","","// \u2500\u2500 Legacy named exports (back-compat) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// These wrap the new `ai` object so existing call sites keep working.",'export type AiCapability = "llm" | "tts" | "stt" | "image";',"",'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 });","}","","// Retained for old call sites that hand-build a Mistflow-shape payload.","// New code should call `ai.text()` / `ai.streamText()` / `ai.textFull()`.","export async function mistflowManagedText(messages: CoreMessage[], options: { useCase?: string; model?: string; stream?: boolean } = {}) {"," if (options.stream) {"," return ai.streamText({ messages, model: options.model, useCase: options.useCase });"," }"," const result = await ai.textFull({ messages, model: options.model, useCase: options.useCase });"," return new Response(JSON.stringify({"," text: result.text,"," tool_calls: result.toolCalls,"," finish_reason: result.finishReason,",' }), { headers: { "Content-Type": "application/json" } });',"}","","export async function mistflowManagedImage(prompt: string, options: { model?: string; size?: string; idempotencyKey?: string } = {}) {"," const out = await ai.generateImage({ prompt, model: options.model, size: options.size, idempotencyKey: options.idempotencyKey });"," // Legacy callers expect { data: [...] } shape from the old /runtime/image endpoint."," return { data: out };","}","","// mistflowManagedRealtimeSession was removed in v3 \u2014 voice realtime is","// no longer part of this wrapper. Use the xAI direct pattern instead.","","// No-op in v3 \u2014 direct usage reporting is handled by the provider directly","// in direct BYOK mode (OpenRouter knows what the customer spent) and by","// the /v1/* surface's automatic usage events in managed mode. Kept for","// back-compat with code that still calls it.","export async function reportDirectAIUsage(_report: Record<string, unknown>): Promise<void> {"," return;","}",""].join(`
|
|
4754
|
+
`)),E(h,"lib/ai.ts",['import "server-only";',"",'export * from "./server/ai";',""].join(`
|
|
4755
|
+
`)),!0&&(d&&Gt(d,"ai-chat"))||E(h,"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(`
|
|
4756
|
+
`)));let Me=Array.isArray(d?.integrations)?d.integrations.map(w=>({name:w.name,preset:w.preset,envVars:w.envVars??[]})):[],M={},ue=new Set([...de?["RESEND_API_KEY","EMAIL_FROM"]:[],...R||te||an(d)?["MISTFLOW_RUNTIME_KEY","MISTFLOW_AI_RUNTIME_KEY"]:[]]);for(let w of Me)for(let I of w.envVars??[])ue.has(I.key)||M[I.key]||(M[I.key]={description:I.description,setupUrl:I.setupUrl,...w.name?{integration:w.name}:{}});if(W&&ne)for(let w of Ar.envVars)M[w.key]||(M[w.key]={description:w.description,setupUrl:w.setupUrl??"https://app.nango.dev",integration:"connected-services"});let Pe=y?.requestedSubdomain||void 0,Ge={name:_,methodologyVersion:S?.version??"1.0",createdAt:new Date().toISOString(),...s?{planId:s}:{},...Pe?{requestedSubdomain:Pe}:{},plan:Array.isArray(d?.steps)?{...d,steps:d.steps.map(w=>({number:w.number,name:w.name??w.title,description:w.description,entities:w.entities,pages:w.pages,features:w.features,status:"pending"}))}:d,dbProvider:V,env:{managed:{...!$&&ne?{DATABASE_URL:{description:"Postgres connection URL",scope:"production"}}:$?{}:{TURSO_URL:{description:"Turso database URL",scope:"production"},TURSO_AUTH_TOKEN:{description:"Turso database auth token",scope:"production"}},...z?{}:{AUTH_SECRET:{description:"Auth encryption secret",scope:"production"}},...re?{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"}}:{},...de?{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"}}:{},...R||te||an(d)?{MISTFLOW_RUNTIME_KEY:{description:"Mistflow runtime key \u2014 authenticates AI gateway, file storage, and other managed features",scope:"production"}}:{}},...Object.keys(M).length>0?{required:M}:{}},authModel:K??"email",roles:d?.roles??null,navStyle:d?.navStyle??"sidebar",multiTenant:d?.multiTenant??!1,hasAdmin:B,hasResend:de,hasStorage:te,hasAI:R,deploy:null};E(h,"mistflow.json",JSON.stringify(Ge,null,2)),cn(h);let dt=im(32).toString("hex"),Je=re?`
|
|
5051
4757
|
# Stripe
|
|
5052
4758
|
STRIPE_SECRET_KEY=
|
|
5053
4759
|
STRIPE_WEBHOOK_SECRET=
|
|
5054
4760
|
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
|
5055
|
-
`:""
|
|
4761
|
+
`:"",$e=de?`
|
|
5056
4762
|
# Email (Resend)
|
|
5057
4763
|
RESEND_API_KEY=
|
|
5058
4764
|
EMAIL_FROM=onboarding@resend.dev
|
|
5059
|
-
`:"",
|
|
4765
|
+
`:"",g="",C=R||te?`
|
|
5060
4766
|
# Mistflow Cloud (server-only; never prefix with NEXT_PUBLIC_).
|
|
5061
4767
|
# One runtime key authenticates every managed feature: AI gateway, file storage,
|
|
5062
4768
|
# and future cloud-powered features. Auto-provisioned by \`mist_init\`.
|
|
@@ -5066,44 +4772,44 @@ MISTFLOW_API_URL=https://api.mistflow.ai
|
|
|
5066
4772
|
MISTFLOW_AI_API_URL=https://api.mistflow.ai
|
|
5067
4773
|
# BYOK fallback for AI only (used when MISTFLOW_RUNTIME_KEY is unset).
|
|
5068
4774
|
OPENROUTER_API_KEY=
|
|
5069
|
-
`:"",
|
|
5070
|
-
AUTH_SECRET=${
|
|
5071
|
-
AUTH_SECRET=your-secret-here`,
|
|
4775
|
+
`:"",A=z?"":`
|
|
4776
|
+
AUTH_SECRET=${dt}`,O=z?"":`
|
|
4777
|
+
AUTH_SECRET=your-secret-here`,Y=$?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
5072
4778
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
5073
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,
|
|
4779
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Q=$?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
5074
4780
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
5075
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,
|
|
4781
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,se=z?"":`
|
|
5076
4782
|
# Mistflow-hosted Google sign-in (zero Google Cloud setup)
|
|
5077
4783
|
MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
|
|
5078
|
-
`,
|
|
4784
|
+
`,we=oe?`
|
|
5079
4785
|
# MCP endpoint (lets external AIs call this app's tools)
|
|
5080
4786
|
MCP_AUTH_MODE=dev
|
|
5081
4787
|
ENVIRONMENT=development
|
|
5082
|
-
`:"",oe
|
|
4788
|
+
`:"",X=oe?`
|
|
5083
4789
|
# MCP endpoint (lets external AIs call this app's tools).
|
|
5084
4790
|
# Leave MCP_AUTH_MODE empty in production. Set ENVIRONMENT=production on deploy.
|
|
5085
4791
|
MCP_AUTH_MODE=
|
|
5086
4792
|
ENVIRONMENT=production
|
|
5087
|
-
`:"",
|
|
4793
|
+
`:"",Z=W?`
|
|
5088
4794
|
# Connected services via Nango (BYO key)
|
|
5089
4795
|
# Sign up at https://app.nango.dev, enable your providers, paste these.
|
|
5090
4796
|
NANGO_SECRET_KEY=
|
|
5091
4797
|
NANGO_WEBHOOK_SECRET=
|
|
5092
|
-
`:"",
|
|
4798
|
+
`:"",Ce=W?`
|
|
5093
4799
|
# Connected services via Nango (BYO key) \u2014 sign up at https://app.nango.dev
|
|
5094
4800
|
NANGO_SECRET_KEY=
|
|
5095
4801
|
NANGO_WEBHOOK_SECRET=
|
|
5096
|
-
`:"";
|
|
5097
|
-
${
|
|
5098
|
-
${
|
|
5099
|
-
${
|
|
5100
|
-
${
|
|
4802
|
+
`:"";E(h,".env.local",`${Y}${A}
|
|
4803
|
+
${se}${Je}${$e}${g}${C}${we}${Z}`),E(h,".env.example",`${Q}${O}
|
|
4804
|
+
${Je}${$e}${g}${C}${X}${Ce}`);let L=[],me=(w,I)=>{L.push({phase:w,message:I})},ve=(w,I)=>{let F=L.find(Re=>Re.phase===w&&!Re.durationMs);F&&(F.durationMs=I)};if(e){let w=rt(e.server,e.progressToken,()=>L[L.length-1]?.message??"Setting up project...");e.cleanup=()=>w.stop()}let pe=Pe,ce=v,Ue=y?.imageryBrief??ce?.imagery??void 0,j=y?.designConversationId??void 0,Xe=y?{name:y.name,summary:y.summary,audienceType:y.audienceType,authModel:y.authModel,dbProvider:V,dataModel:y.dataModel,design:y.design,publicLanding:y.publicLanding,...Object.keys(M).length>0?{env:{required:M}}:{},...typeof y.designMd=="string"&&y.designMd?{designMd:y.designMd}:{},...y.designConversationId?{designConversationId:y.designConversationId}:{},...Array.isArray(y.features)?{features:y.features}:{},...y.integrations?{integrations:y.integrations}:{},...y.hasAI===!0?{hasAI:!0}:{},...y.hasEmail===!0?{hasEmail:!0}:{},...y.hasStorage===!0?{hasStorage:!0}:{}}:void 0,U,Ee;me("register","Registering project on Mistflow...");let Ae=Date.now();try{let w=await Lt(_,{template:void 0,dbProvider:V,requestedSubdomain:pe,pickedDirection:ce,imageryBrief:Ue,planContext:Xe,designConversationId:j,sessionId:i,scaffoldFeatures:["google_byo"]});U=w.id,w.design_md&&(a=w.design_md),w.plan_md&&(c=w.plan_md);let I=a??d?.designMd??N;if(I?(E(h,"DESIGN.md",I),E(h,"app/globals.css",za(P,I))):ce&&l.push({code:"design_md_missing_after_pick",detail:"The user picked a design direction, but neither backend DESIGN.md nor the deterministic fallback was available. Landing implementation should stop instead of improvising."}),Array.isArray(w.design_warnings)&&w.design_warnings.length>0){l=w.design_warnings;for(let le of w.design_warnings)console.error(`[mist_init] design warning [${le.code}]: ${le.detail}`)}if(w.layout_spec&&d&&typeof d=="object"&&(d.layoutSpec=w.layout_spec),w.picker_render_html&&typeof w.picker_render_html=="string")try{let le=he(h,".mistflow");pn(le,{recursive:!0}),bt(he(le,"picker-render.html"),w.picker_render_html),console.error(`[mist_init] picker render written to .mistflow/picker-render.html (${w.picker_render_html.length} chars)`)}catch(le){let k=le instanceof Error?le.message:String(le);console.error(`[mist_init] picker render write failed: ${k}`)}if(Ue)try{let le=await eo(U),k=he(h,"public","images");pn(k,{recursive:!0});let G=0,fe=0;for(let[Ve,Be]of Object.entries(le.slots))if(Be.status==="done"&&Be.signed_url)try{let He=await to(Be.signed_url);bt(he(k,`${Ve}.png`),He),G++}catch(He){let rd=He instanceof Error?He.message:String(He);console.error(`[mist_init] imagery: ${Ve} download failed: ${rd}`)}else(Be.status==="queued"||Be.status==="running")&&fe++;(G>0||fe>0)&&console.error(`[mist_init] imagery: ${G} ready, ${fe} still rendering`)}catch(le){let k=le instanceof Error?le.message:String(le);console.error(`[mist_init] imagery manifest fetch failed: ${k}`)}let F=he(h,"mistflow.json"),Re=JSON.parse(un(F,"utf-8"));if(Re.projectId=U,w.layout_spec&&Re.plan&&typeof Re.plan=="object"&&(Re.plan.layoutSpec=w.layout_spec),bt(F,JSON.stringify(Re,null,2)),An(h,En(U,_)),w.managed_env&&Object.keys(w.managed_env).length>0){let le=he(h,".env.local"),k=ze(le)?un(le,"utf-8"):"";for(let[G,fe]of Object.entries(w.managed_env)){let Ve=new RegExp(`^${G}=.*$`,"m");Ve.test(k)?k=k.replace(Ve,`${G}=${fe}`):k+=`
|
|
4805
|
+
${G}=${fe}`}bt(le,k)}let wn=w.runtimeKey;if(wn?.rawKey){let le=he(h,".env.local"),k=ze(le)?un(le,"utf-8"):"",G=(fe,Ve)=>{let Be=new RegExp(`^${fe}=\\s*$`,"m"),He=new RegExp(`^${fe}=`,"m");Be.test(k)?k=k.replace(Be,`${fe}=${Ve}`):He.test(k)||(k+=`
|
|
4806
|
+
${fe}=${Ve}`)};G("MISTFLOW_RUNTIME_KEY",wn.rawKey),G("MISTFLOW_AI_RUNTIME_KEY",wn.rawKey),bt(le,k)}if(!z&&w.mistflow_app_id){let le=he(h,".env.local"),k=ze(le)?un(le,"utf-8"):"";/^MISTFLOW_OAUTH_PROXY_URL=/m.test(k)||(k+=`
|
|
5101
4807
|
# Mistflow-hosted Google sign-in (zero Google Cloud setup)
|
|
5102
4808
|
MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
|
|
5103
|
-
`),/^MISTFLOW_APP_ID=/m.test(
|
|
4809
|
+
`),/^MISTFLOW_APP_ID=/m.test(k)||(k+=`
|
|
5104
4810
|
# Mistflow-hosted Google sign-in (zero GCP setup)
|
|
5105
|
-
MISTFLOW_APP_ID=${
|
|
5106
|
-
`),
|
|
4811
|
+
MISTFLOW_APP_ID=${w.mistflow_app_id}
|
|
4812
|
+
`),bt(le,k)}try{let{getBaseUrl:le,getAuthHeaders:k}=await Promise.resolve().then(()=>(Se(),ti)),G=k(),fe=d?.features,Ve=d?.steps,Be={};Array.isArray(fe)&&fe.length>0&&(Be.features=fe.map(He=>He.name)),d&&(Be.plan=d),Array.isArray(Ve)&&Ve.length>0&&(Be.provenance=Ve.map(He=>({feature:He.name??He.title??`Step ${He.number??"?"}`,user_intent:(He.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(Be).length>0&&await fetch(`${le()}/api/projects/${encodeURIComponent(U)}/state`,{method:"PUT",headers:{...G,"Content-Type":"application/json"},body:JSON.stringify(Be)})}catch{}L[L.length-1].message=`Registered as ${U.slice(0,8)}`}catch(w){let I=w instanceof Error?w.message:String(w);console.error("Could not register project on backend:",I),Ee=`Project created locally but NOT registered on Mistflow servers (${I}). Deploy will auto-register it.`,L[L.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}ve("register",Date.now()-Ae);let Ne=null;if(_r(d,h)){me("agent-ui","Installing agent UI components...");let w=Date.now();try{let I=Tr(h);Ne={presetVersion:yt.version,installedAt:new Date().toISOString(),files:I.installed};let F=I.depsAdded.length?`, +${I.depsAdded.length} deps`:I.depsSkipped.length?" (deps already pinned)":"";L[L.length-1].message=`${I.installed.length} agent UI files written${F}`}catch(I){let F=I instanceof Error?I.message:String(I);console.error("agent-ui materialization failed:",F),L[L.length-1].message=`agent-ui skipped: ${F}`,Ne=null}ve("agent-ui",Date.now()-w)}let xe=null;if(an(d)){me("ai-chat","Installing ai-chat addon (chat surface)...");let w=Date.now();try{let I=Array.isArray(d?.integrations)?d.integrations:[],F=await ca(h,{integrations:I,mcpEnabled:oe&&ne});xe={files:F.installed.length,deps:F.depsAdded.length,crons:F.cronAdded.length,runPython:F.runPythonWired};let Re=[`${F.installed.length} files`,F.depsAdded.length?`+${F.depsAdded.length} deps`:null,F.cronAdded.length?`+${F.cronAdded.length} cron${F.cronAdded.length>1?"s":""}`:null,F.runPythonWired?"run-python wired":null].filter(Boolean).join(", ");L[L.length-1].message=`ai-chat: ${Re}`}catch(I){ve("ai-chat",Date.now()-w);let F=I instanceof Error?I.message:String(I);throw new Error(`ai-chat addon install failed for agent app: ${F}. Without the addon, the scaffold has no chat route. Retry init, or remove "ai-chat" from plan.integrations to scaffold a basic Next.js app instead.`)}ve("ai-chat",Date.now()-w)}me("git","Initializing git repository...");let pt=Date.now();try{let w=lm(h);await w.init(),await w.add("."),await w.commit("Initial Mistflow project setup"),L[L.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),L[L.length-1].message="Git init skipped"}ve("git",Date.now()-pt);let ge=L.reduce((w,I)=>w+(I.durationMs??0),0),Ke={projectPath:h,projectId:U,status:"awaiting_install"};Ne&&(Ke.agentUi={version:Ne.presetVersion,filesWritten:Ne.files.length,postInstallNote:yt.postInstallNote}),xe&&(Ke.aiChat={filesWritten:xe.files,depsAdded:xe.deps,cronsRegistered:xe.crons,runPythonEnabled:xe.runPython,postInstallNote:"Chat agent ready at /chat. Add tools by appending ToolManifest entries to lib/ai/tools/manifest.ts."}),pe&&(Ke.requestedSubdomain=pe,Ke.productionUrl=`https://${pe}.mistflow.app`);let nd=L.map(w=>{let I=w.durationMs?` (${(w.durationMs/1e3).toFixed(1)}s)`:"";return`${w.message}${I}`});Ke.progress=nd,Ke.totalSetupTime=`${(ge/1e3).toFixed(1)}s`;let Hr=[];U||Hr.push("Project was not registered with Mistflow (backend error during create). mist_deploy will retry registration automatically on the first deploy."),Ee&&(Ke.registrationWarning=Ee),Hr.length>0&&(Ke.warnings=Hr),l.length>0&&(Ke.designPipelineWarnings=l,Ke.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 xs=`${pe?`TELL THE USER: "Your app's URL is reserved: https://${pe}.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: "${h}" }). 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: "${h}" }) to build the first plan step.`;return Ke.nextAction=U?xs:`${xs} NOTE: The project could not be registered with the backend during init (${Ee??"see registrationWarning"}). mist_deploy will retry the registration automatically on the first deploy \u2014 no manual recovery needed.`,p(JSON.stringify(Ke))}catch(S){try{nm(h,{recursive:!0,force:!0})}catch{}throw S}}var cm,pm,Er,um,mm,hm,vm,km,Wa,Cm,Om,Va,Ya=x(()=>{"use strict";zo();da();Ko();ye();on();Cr();Vo();Yo();Se();Ut();Rr();Aa();Fa();ds();ds();cm=`## Project plan (PLAN.md)
|
|
5107
4813
|
|
|
5108
4814
|
This project ships with a \`PLAN.md\` at the root \u2014 a PRD-style
|
|
5109
4815
|
projection of the plan with the data model, pages, steps, and per-step
|
|
@@ -5124,17 +4830,17 @@ control plane.
|
|
|
5124
4830
|
To change the plan (new feature, missed requirement, scope shift),
|
|
5125
4831
|
call \`mist_plan\` with \`modify: true\` and a description. The backend
|
|
5126
4832
|
generates a new plan revision and regenerates PLAN.md.
|
|
5127
|
-
`;
|
|
4833
|
+
`;pm=dn.object({name:dn.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:dn.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:dn.string().optional().describe("Absolute path where the project should be scaffolded."),planId:dn.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:dn.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.")});Er="# 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",um=`---
|
|
5128
4834
|
description: Mistflow project conventions \u2014 read AGENTS.md + PLAN.md first
|
|
5129
4835
|
alwaysApply: false
|
|
5130
4836
|
---
|
|
5131
4837
|
|
|
5132
|
-
${
|
|
4838
|
+
${Er}`,mm=`# VS Code Copilot instructions
|
|
5133
4839
|
|
|
5134
4840
|
This is the project's primary instruction file for VS Code Copilot.
|
|
5135
4841
|
|
|
5136
|
-
${
|
|
5137
|
-
`;
|
|
4842
|
+
${Er}`,hm=`read: ["CONVENTIONS.md", "AGENTS.md", "PLAN.md"]
|
|
4843
|
+
`;vm={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},km=[["--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"]];Wa={"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"};Cm=new Set(["ar","he","fa","ur"]);Om={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"};Va={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:pm,handler:zm}});var Xa,Qa=x(()=>{Xa=`# Consumer Warm Archetype
|
|
5138
4844
|
|
|
5139
4845
|
Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
|
|
5140
4846
|
|
|
@@ -5301,7 +5007,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
|
|
|
5301
5007
|
- Small touch targets. Phone-first means \`h-12\` minimum.
|
|
5302
5008
|
- Empty states that just say "No data." Be encouraging.
|
|
5303
5009
|
- Dark theme as default. Consumer warm apps default to light.
|
|
5304
|
-
`});var
|
|
5010
|
+
`});var el,Za=x(()=>{el=`# Consumer Bold Archetype
|
|
5305
5011
|
|
|
5306
5012
|
Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
|
|
5307
5013
|
|
|
@@ -5472,7 +5178,7 @@ Social/competitive apps need an activity feed:
|
|
|
5472
5178
|
- Card-only layouts with no hierarchy. Use hero cards + supporting cards.
|
|
5473
5179
|
- Missing achievement/progress systems. The gamification IS the product.
|
|
5474
5180
|
- Light-touch buttons. CTAs should be unmissable.
|
|
5475
|
-
`});var
|
|
5181
|
+
`});var nl,tl=x(()=>{nl=`# Professional Clean Archetype
|
|
5476
5182
|
|
|
5477
5183
|
Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
|
|
5478
5184
|
|
|
@@ -5684,7 +5390,7 @@ h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
|
|
|
5684
5390
|
- Missing status workflows. Every booking/appointment needs a clear state machine.
|
|
5685
5391
|
- Dark theme as default. Clients associate light themes with professionalism.
|
|
5686
5392
|
- Emoji in the UI. Professional context.
|
|
5687
|
-
`});var
|
|
5393
|
+
`});var ol,rl=x(()=>{ol=`# Education Structured Archetype
|
|
5688
5394
|
|
|
5689
5395
|
Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
|
|
5690
5396
|
|
|
@@ -5884,7 +5590,7 @@ border-2 border-destructive bg-destructive/5 rounded-xl p-4
|
|
|
5884
5590
|
- Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
|
|
5885
5591
|
- Long lesson pages with no progress indicator. Users need to know where they are.
|
|
5886
5592
|
- Multiple competing elements per view. One thing at a time. One question at a time.
|
|
5887
|
-
`});var
|
|
5593
|
+
`});var il,sl=x(()=>{il=`# Marketplace Browse Archetype
|
|
5888
5594
|
|
|
5889
5595
|
Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
|
|
5890
5596
|
|
|
@@ -6108,7 +5814,7 @@ border-b border-border/30 py-4
|
|
|
6108
5814
|
- Small product images. The image is the primary decision-making element.
|
|
6109
5815
|
- No empty state for zero search results. "No results for 'xyz'. Try broader terms."
|
|
6110
5816
|
- Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
|
|
6111
|
-
`});var
|
|
5817
|
+
`});var ll,al=x(()=>{ll=`# SaaS Analytical Archetype
|
|
6112
5818
|
|
|
6113
5819
|
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.
|
|
6114
5820
|
|
|
@@ -6289,7 +5995,7 @@ The most recognizable B2B SaaS landing pattern.
|
|
|
6289
5995
|
- **Inter as the only font.** Pair it with a distinctive heading font or swap it entirely.
|
|
6290
5996
|
- **Centered text + centered image below.** The most overused AI hero. Use split or offset layouts.
|
|
6291
5997
|
- **Animation on every element.** Efficient motion only: hero entrance, card reveals on scroll, number counters. Nothing else.
|
|
6292
|
-
`});var
|
|
5998
|
+
`});var dl,cl=x(()=>{dl=`# Content Editorial Archetype
|
|
6293
5999
|
|
|
6294
6000
|
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.
|
|
6295
6001
|
|
|
@@ -6496,7 +6202,7 @@ Below the hero: 3 featured pieces laid out as a horizontal strip with **oversize
|
|
|
6496
6202
|
- **Dark mode as default for a reading tool.** Offer it as a toggle, not the default.
|
|
6497
6203
|
- **Flashy motion while reading.** Scroll hijacking, parallax on body text, animated backgrounds behind paragraphs \u2014 all break reading flow.
|
|
6498
6204
|
- **More than 2 fonts.** Heading + body is enough. Adding a third font for captions or metadata dilutes the identity.
|
|
6499
|
-
`});var
|
|
6205
|
+
`});var ul,pl=x(()=>{ul=`# Devtool Technical Archetype
|
|
6500
6206
|
|
|
6501
6207
|
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.
|
|
6502
6208
|
|
|
@@ -6685,7 +6391,7 @@ Numbers styled as terminal output: \`> 47,293 deploys this week\`, \`> 99.98% up
|
|
|
6685
6391
|
- **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).
|
|
6686
6392
|
- **Feature cards with rocket / lightning / puzzle icons.** Use technical icons (terminal, code, database, network) or skip icons entirely.
|
|
6687
6393
|
- **Motion on code blocks** while the user is trying to read them. Type out ONCE on load, then leave them alone.
|
|
6688
|
-
`});var
|
|
6394
|
+
`});var hl,ml=x(()=>{hl=`# Creative Showcase Archetype
|
|
6689
6395
|
|
|
6690
6396
|
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.
|
|
6691
6397
|
|
|
@@ -6902,7 +6608,7 @@ Premium agency touch: on first load, a full-screen loading component shows the s
|
|
|
6902
6608
|
- **Scroll hijacking through the whole site.** Use sparingly \u2014 one or two scroll-pinned sections maximum.
|
|
6903
6609
|
- **Mystery-meat navigation.** Clever is bad here. "Work / About / Contact" is fine. Don't make visitors guess.
|
|
6904
6610
|
- **No contact info.** The primary purpose of this site is to generate inquiries. Make it stupid-easy to contact you.
|
|
6905
|
-
`});var
|
|
6611
|
+
`});var fl,gl=x(()=>{fl=`# Finance Clarity Archetype
|
|
6906
6612
|
|
|
6907
6613
|
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.
|
|
6908
6614
|
|
|
@@ -7121,11 +6827,11 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
|
|
|
7121
6827
|
- **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
|
|
7122
6828
|
- **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
|
|
7123
6829
|
- **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.
|
|
7124
|
-
`});function
|
|
7125
|
-
`),
|
|
6830
|
+
`});function bl(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return yl[e]}var yl,Pv,wl=x(()=>{"use strict";Qa();Za();tl();rl();sl();al();cl();pl();ml();gl();yl={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Xa},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:el},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:nl},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:ol},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:il},"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:ll},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:dl},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:ul},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:hl},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:fl}},Pv=Object.keys(yl)});import{spawn as th,execFileSync as nh}from"child_process";import{existsSync as Nr,mkdirSync as xl,openSync as ms,closeSync as hs,readSync as rh,readFileSync as Sl,writeFileSync as _l,renameSync as Tl,unlinkSync as oh,readdirSync as Nv,statSync as sh}from"fs";import{homedir as Cl}from"os";import{join as Ye,dirname as Il}from"path";import{randomBytes as Pl,randomUUID as ih}from"crypto";function Or(){return Ye(Cl(),".mistflow","jobs")}function lh(){return Ye(Cl(),".mistflow","job-wrapper.cjs")}function ch(){let t=lh(),e=Il(t);Nr(e)||xl(e,{recursive:!0});let r=`v${Rl}`;if(Nr(t))try{if(Sl(t,"utf-8").includes(r))return t}catch{}let n=Ye(e,`.job-wrapper.tmp.${Pl(6).toString("hex")}`);return _l(n,ah),Tl(n,t),t}function mn(t){return Ye(Or(),t)}function Al(t){return Ye(mn(t),"status.json")}function vl(t,e){let r=Al(t),n=Ye(Il(r),`.status.tmp.${Pl(6).toString("hex")}`);try{_l(n,JSON.stringify(e,null,2)+`
|
|
6831
|
+
`),Tl(n,r)}catch(o){try{oh(n)}catch{}throw o}}function dh(t){let e=Al(t);if(!Nr(e))return null;try{return JSON.parse(Sl(e,"utf-8"))}catch{return null}}async function Rt(t){let e=`job_${ih().replace(/-/g,"").slice(0,12)}`,r=mn(e);xl(r,{recursive:!0}),hs(ms(Ye(r,"stdout.log"),"a")),hs(ms(Ye(r,"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};vl(e,o);let s=ch(),i={...process.env,...t.env??{}},a=th("node",[s,r,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:i});a.unref();let l={...o,wrapperPid:a.pid??0};return vl(e,l),l}function ph(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function uh(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=nh("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=ph(r),o=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(o)&&Math.abs(n-o)>2e3)return!1}catch{}return!0}function mh(t,e){let r=Date.parse(t),n=e?Date.parse(e):Date.now();if(!Number.isFinite(r)||!Number.isFinite(n))return"0s";let o=Math.max(0,n-r),s=Math.floor(o/1e3);if(s<60)return`${s}s`;let i=Math.floor(s/60),a=s%60;return i<60?`${i}m ${a}s`:`${Math.floor(i/60)}h ${i%60}m`}function kl(t,e){if(!Nr(t))return"";let r=sh(t);if(r.size===0)return"";let n=r.size>e?r.size-e:0,o=r.size-n,s=ms(t,"r");try{let i=Buffer.alloc(o);return rh(s,i,0,o,n),i.toString("utf-8")}finally{hs(s)}}function hh(t,e=200){let r=kl(Ye(mn(t),"stdout.log"),65536),n=kl(Ye(mn(t),"stderr.log"),64*1024),o=[];return r.trim()&&o.push(...r.split(`
|
|
7126
6832
|
`).slice(-e).map(s=>`[out] ${s}`)),n.trim()&&o.push(...n.split(`
|
|
7127
6833
|
`).slice(-e).map(s=>`[err] ${s}`)),o.filter(s=>s.trim().length>0).join(`
|
|
7128
|
-
`)}function
|
|
6834
|
+
`)}function Jt(t){return{stdout:Ye(mn(t),"stdout.log"),stderr:Ye(mn(t),"stderr.log")}}async function At(t){let e=dh(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!uh(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:mh(r.startedAt,r.endedAt),logTail:hh(t)}}async function hn(t,e){let r=Math.max(100,e.pollIntervalMs??500),n=Date.now()+Math.max(0,e.timeoutMs),o=["complete","failed","unknown_exit"];for(;;){let s=await At(t);if(!s)return null;try{e.onPoll?.(s)}catch{}if(o.includes(s.status))return s;let i=n-Date.now();if(i<=0)return s;await new Promise(a=>setTimeout(a,Math.min(r,i)))}}var Rl,ah,Wn=x(()=>{"use strict";Rl=1,ah=`// Generated by @mistflow-ai/mcp local-jobs (v${Rl}). Do not edit.
|
|
7129
6835
|
const { spawn } = require('node:child_process');
|
|
7130
6836
|
const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
|
|
7131
6837
|
const { join, dirname } = require('node:path');
|
|
@@ -7189,9 +6895,9 @@ child.on('error', (err) => {
|
|
|
7189
6895
|
});
|
|
7190
6896
|
process.exit(1);
|
|
7191
6897
|
});
|
|
7192
|
-
`});import{createServer as
|
|
7193
|
-
`)}function
|
|
7194
|
-
`)}async function
|
|
6898
|
+
`});import{createServer as gh}from"net";import{existsSync as Mr,readFileSync as El,writeFileSync as Nl,mkdirSync as Ol}from"fs";import{join as jr}from"path";import{spawn as fh}from"child_process";function Ml(){let t=(process.env.MISTFLOW_VISUAL_CONTEXT??"full").toLowerCase();return t==="off"||t==="preview"||t==="full"?t:"full"}function jl(t){return jr(t,".mistflow","visual-context.json")}function Dl(t){let e=jl(t);if(!Mr(e))return{screenshotsTaken:0,lastScreenshotStep:0};try{return JSON.parse(El(e,"utf-8"))}catch{return{screenshotsTaken:0,lastScreenshotStep:0}}}function yh(t,e){let r=jr(t,".mistflow");Mr(r)||Ol(r,{recursive:!0}),Nl(jl(t),JSON.stringify(e,null,2)+`
|
|
6899
|
+
`)}function Ll(t,e,r){if(Ml()!=="full")return!1;let n=Dl(t);return n.screenshotsTaken>=bh?!1:n.screenshotsTaken===0||r>0&&e>=r||e>0&&e!==n.lastScreenshotStep&&e%3===0}function $l(t,e){let r=Dl(t);yh(t,{screenshotsTaken:r.screenshotsTaken+1,lastScreenshotStep:e})}async function wh(){return new Promise((t,e)=>{let r=gh();r.unref(),r.on("error",e),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(n&&typeof n=="object"){let o=n.port;r.close(()=>t(o))}else r.close(()=>e(new Error("could not read assigned port")))})})}async function Ul(t,e=15e3,r=500){let n=Date.now()+e;for(;Date.now()<n;){try{let o=new AbortController,s=setTimeout(()=>o.abort(),Math.min(r*2,2e3)),i=await fetch(t,{method:"HEAD",signal:o.signal});if(clearTimeout(s),i)return!0}catch{}await new Promise(o=>setTimeout(o,r))}return!1}function Fl(t){return jr(t,".mistflow","preview.json")}function ql(t){let e=Fl(t);if(!Mr(e))return null;try{return JSON.parse(El(e,"utf-8"))}catch{return null}}function Bl(t){return ql(t)}function vh(t,e){let r=jr(t,".mistflow");Mr(r)||Ol(r,{recursive:!0}),Nl(Fl(t),JSON.stringify(e,null,2)+`
|
|
6900
|
+
`)}async function Hl(t){if(Ml()==="off")return null;let e=ql(t);if(e){let n=await At(e.jobId);if(n&&(n.status==="running"||n.status==="starting"))return{state:e,freshlyStarted:!1}}let r;try{r=await wh()}catch{return null}try{let n=await Rt({type:"preview",cmd:"sh",args:["-c",`npm run dev -- --port ${r}`],cwd:t});await new Promise(a=>setTimeout(a,600));let o=await At(n.id);if(o&&(o.status==="failed"||o.status==="unknown_exit"))return null;let s=`http://localhost:${r}`,i={port:r,url:s,jobId:n.id,startedAt:n.startedAt};return vh(t,i),{state:i,freshlyStarted:!0}}catch{return null}}function zl(t){try{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];fh(e,r,{detached:!0,stdio:"ignore"}).unref()}catch{}}var bh,gs=x(()=>{"use strict";Wn();bh=5});var Gl,Wl=x(()=>{Gl=`# Design Doctrine
|
|
7195
6901
|
|
|
7196
6902
|
This is the standard for every UI you generate. It is not aspirational. It is the floor.
|
|
7197
6903
|
|
|
@@ -7257,7 +6963,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
|
|
|
7257
6963
|
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.**
|
|
7258
6964
|
|
|
7259
6965
|
If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
|
|
7260
|
-
`});var
|
|
6966
|
+
`});var Kl,Jl=x(()=>{Kl=`# Typography
|
|
7261
6967
|
|
|
7262
6968
|
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.
|
|
7263
6969
|
|
|
@@ -7345,7 +7051,7 @@ Pick exactly one:
|
|
|
7345
7051
|
- **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
|
|
7346
7052
|
|
|
7347
7053
|
Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
|
|
7348
|
-
`});var
|
|
7054
|
+
`});var Yl,Vl=x(()=>{Yl="# 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 Xl,Ql=x(()=>{Xl=`# Motion
|
|
7349
7055
|
|
|
7350
7056
|
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.
|
|
7351
7057
|
|
|
@@ -7423,7 +7129,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
|
|
|
7423
7129
|
## One-Line Motion Rule
|
|
7424
7130
|
|
|
7425
7131
|
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.
|
|
7426
|
-
`});var
|
|
7132
|
+
`});var ec,Zl=x(()=>{ec=`# Spatial Composition
|
|
7427
7133
|
|
|
7428
7134
|
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.
|
|
7429
7135
|
|
|
@@ -7493,7 +7199,7 @@ To signal "designed, not templated":
|
|
|
7493
7199
|
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.
|
|
7494
7200
|
|
|
7495
7201
|
Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
|
|
7496
|
-
`});var
|
|
7202
|
+
`});var nc,tc=x(()=>{nc=`# Interaction
|
|
7497
7203
|
|
|
7498
7204
|
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.
|
|
7499
7205
|
|
|
@@ -7578,7 +7284,7 @@ Small moments that add up to "designed":
|
|
|
7578
7284
|
- **Empty states** offer a specific next action, not "No data yet".
|
|
7579
7285
|
|
|
7580
7286
|
These micro-interactions are the texture of a designed product. Ship them.
|
|
7581
|
-
`});var
|
|
7287
|
+
`});var oc,rc=x(()=>{oc=`# UX Writing
|
|
7582
7288
|
|
|
7583
7289
|
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.
|
|
7584
7290
|
|
|
@@ -7654,18 +7360,18 @@ If there's a pricing page:
|
|
|
7654
7360
|
## The Footer
|
|
7655
7361
|
|
|
7656
7362
|
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."
|
|
7657
|
-
`});import{existsSync as
|
|
7658
|
-
`),{added:i,skipped:a}}var
|
|
7659
|
-
`),an(t)}function $r(t){return t.entity??t.name??"Unknown"}function Rh(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Vl(t){return t.path??t.route??t.name??""}function Ah(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 Yl(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let o=$r(n).toLowerCase();return r.some(s=>o.includes(s)||s.includes(o))})}function Eh(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let o=(n.name??"").toLowerCase(),s=Vl(n).toLowerCase();return r.some(i=>o.includes(i)||i.includes(o)||s.includes(i))})}function Oh(t){let e=t.stepType;if(e&&Nh.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 Mh(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 jh(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,o=n&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),o&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let i=r.heroImages[0];e.push(`- URL: ${i.url}`),e.push(`- Alt text for img tag: "${i.alt||"Hero image"} \u2014 Photo by ${i.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 i of r.sectionImages)e.push(`- ${i.url} \u2014 alt: "${i.alt||"section image"} \u2014 Photo by ${i.photographer} on Unsplash"`)}(o||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 s=il(t);s?(e.push(""),e.push(`### Page composition \u2014 ${s.name} archetype`),e.push(`This plan was classified as **${s.id}** \u2014 ${s.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(s.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(`
|
|
7660
|
-
`)}function
|
|
7363
|
+
`});import{existsSync as Ph,readFileSync as Rh,writeFileSync as Ah}from"fs";import{join as Eh}from"path";import{z as Gn}from"zod";function Lr(t,e){if(e.length===0)return{added:[],skipped:[]};let r=Eh(t,"mistflow.json");if(!Ph(r))throw new Error(`mistflow.json not found at ${t}`);let n=Rh(r,"utf-8"),o=JSON.parse(n);o.env=o.env??{},o.env.required=o.env.required??{};let s=o.env.required,i=[],a=[];for(let l of e)if(!(!l?.key||typeof l.key!="string"||!Nh.test(l.key))){if(s[l.key]){a.push(l.key);continue}s[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}:{}},i.push(l.key)}return i.length>0&&Ah(r,JSON.stringify(o,null,2)+`
|
|
7364
|
+
`),{added:i,skipped:a}}var Dr,Nh,fs=x(()=>{"use strict";Dr=Gn.object({key:Gn.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:Gn.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:Gn.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:Gn.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),Nh=/^[A-Z][A-Z0-9_]*$/});import{z as Jn}from"zod";import{existsSync as Et,readFileSync as ys,writeFileSync as $r,mkdirSync as sc,renameSync as Oh}from"fs";import{join as ot,resolve as Mh,dirname as jh}from"path";import{createConnection as Dh}from"net";function Lh(t){return new Promise(e=>{let r=Dh({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}function Uh(t){let e=ot(t,"mistflow.json");if(!Et(e))return null;try{return JSON.parse(ys(e,"utf-8"))}catch{return null}}function ic(t,e){let r=ot(t,"mistflow.json"),n=`${r}.${process.pid}.tmp`;$r(n,JSON.stringify(e,null,2)+`
|
|
7365
|
+
`),Oh(n,r),cn(t)}function Ur(t){return t.entity??t.name??"Unknown"}function Fh(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function ac(t){return t.path??t.route??t.name??""}function qh(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 lc(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let o=Ur(n).toLowerCase();return r.some(s=>o.includes(s)||s.includes(o))})}function Bh(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let o=(n.name??"").toLowerCase(),s=ac(n).toLowerCase();return r.some(i=>o.includes(i)||i.includes(o)||s.includes(i))})}function zh(t){let e=t.stepType;if(e&&Hh.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 Wh(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 Gh(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,o=n&&!!r.heroImages?.length,s=!!r.sectionImages?.length;if(e.push(""),e.push("### Visual strategy:"),o&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image fallback** \u2014 use this Unsplash photo as the landing page hero BACKGROUND when `/public/images/hero.png` is missing, pending, or visibly worse than the photo:");let a=r.heroImages[0];e.push(`- URL: ${a.url}`),e.push(`- Alt text for img tag: "${a.alt||"Hero image"} \u2014 Photo by ${a.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 gives the page real atmosphere and context; pair it with a domain-specific product/mockup card when this is a SaaS/tool/customer app.")}else n&&!r.heroImages?.length?e.push("**Hero background** \u2014 no Unsplash hero image was fetched. Do NOT shrink the page into a text/card-only dashboard hero. Keep a generous media/scene region in the hero, use the picker `/images/hero.png` asset if it exists, otherwise use a large CSS scene placeholder and tell the user imagery is pending."):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&&r.sectionImages){e.push("**Section image fallbacks available** \u2014 use these for feature sections, about sections, or testimonial backgrounds when `/public/images/feature-*.png` is missing or pending:");for(let a of r.sectionImages)e.push(`- ${a.url} \u2014 alt: "${a.alt||"section image"} \u2014 Photo by ${a.photographer} on Unsplash"`)}(o||s)&&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."),e.push("**Marketing visual floor**: every public landing page needs a real visual anchor. Acceptable anchors are: `/images/{slot}.png` from the picker imagery pipeline, the Unsplash fallbacks above, a video/canvas/Three.js scene, or a large domain-specific product UI mockup. A cramped hero made only of text, icons, and small cards is a failed implementation."),e.push("**Minimal hero rule**: the first viewport should have one clear headline, one short supporting sentence, one primary CTA plus at most one secondary action, and one generous visual/scene anchor. Do NOT add a stats row, feature-card cluster, benefit checklist, or extra explanatory paragraphs unless they appear in the picked render or layout spec."),e.push("**Glassmorphism is allowed when selected**: if the picked direction, DESIGN.md, or cardStyle/texture says `glass`, `glassmorphic`, or liquid glass, use restrained frosted panels for the hero visual, nav, or one focal card. Do not spray glass on every card, and do not use glass as the unselected default.");let i=bl(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 + frosted SaaS mockup pattern by default \u2014 that template was retired because it produces the same cold hero regardless of the app's intent. If the selected direction explicitly calls for glassmorphism, keep it as a restrained texture on one focal surface while preserving the archetype's composition.`),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 (last-resort fallback):**"),e.push("The hero uses a spacious split layout with text on the left and a product preview on the right. Keep it minimal: no stats row or benefit checklist unless the plan includes real proof points."),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 (Optional proof row only when the plan has real proof) \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%)**: bold headline (use accent color on ONE key word or phrase) \u2192 one short description sentence \u2192 primary CTA plus optional secondary text/link. Omit badge pills, stats rows, and feature bullets unless they are in the picked render or plan 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("**Proof row**: optional only when the plan contains real proof points. Do not invent decorative `500+ / 25K+ / 99%` stats to fill space."))}return e.join(`
|
|
7366
|
+
`)}function Jh(t){let e=[];return e.push("### Landing layout (Plan G IR \u2014 STRUCTURAL AUTHORITY for this page):"),e.push(""),e.push("Build the landing page with EXACTLY these sections, in this order. Each section's `type` names a primitive \u2014 render it using the picked direction's fonts + colors + shape language. The `intent` explains WHY the section exists; the `props` are the content."),e.push(""),e.push(`- **Page intent**: ${t.page_intent}`),e.push(`- **Narrative arc**: ${t.narrative_arc}`),e.push(`- **Audience**: ${t.audience_persona}`),t.primary_cta&&e.push(`- **Primary CTA**: \`${t.primary_cta.label}\` \u2014 ${t.primary_cta.intent}`),e.push(""),e.push("**Sections (build in order):**"),e.push(""),t.sections.forEach((r,n)=>{let o=n+1;e.push(`${o}. \`${r.type}\` (id: \`${r.id}\`, role: \`${r.narrative_role}\`)`),e.push(` - **Intent**: ${r.intent}`),r.answers_section_id&&e.push(` - **Answers**: section \`${r.answers_section_id}\` (use visual cues \u2014 paired typography, matching accent, sequential numbering \u2014 to make the relationship readable)`),e.push(" - **Props** (JSON):"),e.push(" ```json");let s=JSON.stringify(r.props,null,2).split(`
|
|
7661
7367
|
`).map(i=>` ${i}`);e.push(...s),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(`
|
|
7662
|
-
`)}async function
|
|
7368
|
+
`)}async function Kh(t){try{let e=await vo("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
|
|
7663
7369
|
- Follow existing patterns in the codebase
|
|
7664
|
-
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function $h(t,e,r,n,o,s){let i=[];i.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),i.push(""),i.push("### What to build:"),i.push(t.description),i.push(""),e.primaryAction&&(i.push("### Primary user action (non-negotiable):"),i.push(`- **Core action**: ${e.primaryAction.action}`),i.push(`- **User flow**: ${e.primaryAction.flow}`),i.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),i.push(""),i.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."),i.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(o);if(e.design&&l){i.push(jh(e.design)),i.push("");let T=s?Ze(s,".mistflow","rules","design-quality.md"):null;T&&Rt(T)?(i.push("### Design quality rules (non-negotiable):"),i.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."),i.push("")):(i.push(Tr),i.push(""))}else e.design&&!l&&(i.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&i.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),i.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),i.push(""));if(s){let T=Pi(s);if(T.length>0){i.push("### Approved wireframe (MUST READ before writing any files):"),i.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let S of T){let w=S.replace(s,"").replace(/^\//,"");i.push(`- \`${w}\``)}i.push(""),i.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."),i.push(""),i.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),i.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),i.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),i.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),i.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),i.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"),i.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(i.push("### Role system (from plan):"),i.push(`- Roles: ${e.roles.join(", ")}`),i.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),i.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),i.push("")),e.multiTenant&&(i.push("### Multi-tenant (from plan):"),i.push("- Organization tables are in `db/schema/organization.ts`"),i.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),i.push("- All data queries MUST be scoped to the current org (filter by orgId)"),i.push("- Org switcher component is at `components/org-switcher.tsx`"),i.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."),i.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."),i.push("")),e.language&&(i.push(`### Language: ${e.language}`),i.push(`ALL user-facing text must be written in ${e.language}:`),i.push("- Page titles, headings, labels, button text, placeholder text"),i.push("- Navigation items, menu labels, footer text"),i.push("- Error messages, success messages, empty states"),i.push("- Landing page copy, marketing text, CTAs"),i.push("- Form labels and validation messages"),i.push("Code (variable names, comments, file names) stays in English."),i.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),i.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(o)&&(e.audienceType==="b2c"?(i.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),i.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),i.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),i.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),i.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),i.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),i.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),i.push("")):e.audienceType==="b2b"?(i.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),i.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),i.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),i.push("- Testimonials: from business owners who use the platform"),i.push("- Features: business benefits ('Track dietary preferences across all orders')"),i.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),i.push("")):e.audienceType==="internal"&&(i.push("### Audience: internal staff tool. No marketing copy needed."),i.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),i.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),i.push(""))),r.length>0&&(i.push("### Already completed:"),r.forEach(T=>i.push(`- ${T}`)),i.push(""));let m=e.dataModel?Yl(t,e.dataModel):[];m.length>0&&(i.push("### Data model (from plan):"),m.forEach(T=>{let S=$r(T),w=Rh(T.fields);i.push(`- **${S}**: ${w}`),i.push(` Schema file: \`db/schema/${S.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),i.push(""));let p=e.pages?Eh(t,e.pages):[];if(p.length>0&&(i.push("### Pages to create/update:"),p.forEach(T=>{let S=T.description?` \u2014 ${T.description}`:"";i.push(`- \`${Vl(T)}\`${S}`)}),i.push("")),o==="crud"&&m.length>0&&m.forEach(T=>{let S=$r(T),w=S.toLowerCase().replace(/\s+/g,"-"),E=w.endsWith("s")?w:`${w}s`;i.push(`### Files for ${S} CRUD:`),i.push(`- List page: \`app/(dashboard)/${E}/page.tsx\` (Server Component)`),i.push(`- Detail page: \`app/(dashboard)/${E}/[id]/page.tsx\``),i.push(`- Create page: \`app/(dashboard)/${E}/new/page.tsx\``),i.push(`- Server Actions: \`app/(dashboard)/${E}/actions.ts\``),i.push(`- DataTable columns: \`components/${w}-table-columns.tsx\``),i.push(`- Form: \`components/${w}-form.tsx\``),i.push("")}),l){i.push("## Design Doctrine (the standard for every UI step)"),i.push(""),i.push(Ml),i.push(""),i.push("## Design Reference Library"),i.push(""),i.push("### Typography"),i.push(Dl),i.push(""),i.push("### Color"),i.push($l),i.push(""),i.push("### Motion"),i.push(Fl),i.push(""),i.push("### Spatial Composition"),i.push(Bl),i.push(""),i.push("### Interaction"),i.push(zl),i.push(""),i.push("### UX Writing"),i.push(Gl),i.push("");let T=s?Ze(s,"DESIGN.md"):void 0,S=T&&Rt(T)?(()=>{try{return hs(T,"utf-8")}catch{return null}})():null;S&&(i.push("### Design system (source of truth: DESIGN.md):"),i.push(""),i.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."),i.push(""),i.push(S),i.push(""));let w=s?Ze(s,".mistflow","picker-render.html"):void 0;(o==="landing"||o==="design")&&w&&Rt(w)&&(i.push("### Picked landing page render \u2014 ground-truth design contract"),i.push(""),i.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."),i.push(""),i.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."),i.push(""),i.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"),i.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."),i.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."),i.push(""))}if(o==="landing"||o==="design"){i.push("### File location for the landing page (non-negotiable):"),i.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.'),i.push(""),i.push("### Landing page hard requirements (non-negotiable):"),i.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.'),i.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.'),i.push("");let T=s?Ze(s,".mistflow","rules","landing.md"):null;T&&Rt(T)?(i.push("### Landing page rules:"),i.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."),i.push("")):(i.push(Pr),i.push(""))}o==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(i.push(Dh(e.layoutSpec)),i.push(""));let u=t.integrationId?Zt(t.integrationId):void 0;if(u){let T=en(u.id);if(i.push("### Integration blueprint (follow this closely):"),i.push(""),i.push(`Using integration: **${u.name}** (${u.category})`),T?.docsUrl&&i.push(`Official docs: ${T.docsUrl}`),T?.envVars?.length){i.push(""),i.push("**Required environment variables:**");for(let S of T.envVars)i.push(`- \`${S.key}\`: ${S.description} \u2014 Get it at ${S.setupUrl}`);i.push(""),i.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.")}T?.packages?.length&&(i.push(""),i.push(`**Packages to install:** \`npm install ${T.packages.join(" ")}\``)),i.push(""),i.push("---"),i.push(u.prompt),i.push("---"),i.push(""),i.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."),i.push("")}let{reminders:h,skill:F}=await Lh(o);return i.push(h),i.push(""),F&&(i.push(`### ${o} reference:`),i.push(F),i.push("")),l&&(i.push("## Self-Audit \u2014 run before submitting this file"),i.push(""),i.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.`),i.push(""),i.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.'),i.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."),i.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),i.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),i.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."),i.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),i.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),i.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.'),i.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).'),i.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)."),i.push(""),i.push(`If every answer is "no, I'm good" \u2014 then submit.`),i.push("")),i.join(`
|
|
7665
|
-
`)}async function
|
|
7666
|
-
`+
|
|
7667
|
-
`)}
|
|
7668
|
-
`)}catch(
|
|
7370
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Vh(t,e,r,n,o,s){let i=[];i.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),i.push(""),i.push("### What to build:"),i.push(t.description),i.push(""),e.primaryAction&&(i.push("### Primary user action (non-negotiable):"),i.push(`- **Core action**: ${e.primaryAction.action}`),i.push(`- **User flow**: ${e.primaryAction.flow}`),i.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),i.push(""),i.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."),i.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(o);if(e.design&&l){i.push(Gh(e.design)),i.push("");let P=s?ot(s,".mistflow","rules","design-quality.md"):null;P&&Et(P)?(i.push("### Design quality rules (non-negotiable):"),i.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."),i.push("")):(i.push(Ir),i.push(""))}else e.design&&!l&&(i.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&i.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),i.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),i.push(""));if(s){let P=$i(s);if(P.length>0){i.push("### Approved wireframe (MUST READ before writing any files):"),i.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let y of P){let v=y.replace(s,"").replace(/^\//,"");i.push(`- \`${v}\``)}i.push(""),i.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."),i.push(""),i.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),i.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),i.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),i.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),i.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),i.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"),i.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(i.push("### Role system (from plan):"),i.push(`- Roles: ${e.roles.join(", ")}`),i.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),i.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),i.push("")),e.multiTenant&&(i.push("### Multi-tenant (from plan):"),i.push("- Organization tables are in `db/schema/organization.ts`"),i.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),i.push("- All data queries MUST be scoped to the current org (filter by orgId)"),i.push("- Org switcher component is at `components/org-switcher.tsx`"),i.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."),i.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."),i.push("")),e.language&&(i.push(`### Language: ${e.language}`),i.push(`ALL user-facing text must be written in ${e.language}:`),i.push("- Page titles, headings, labels, button text, placeholder text"),i.push("- Navigation items, menu labels, footer text"),i.push("- Error messages, success messages, empty states"),i.push("- Landing page copy, marketing text, CTAs"),i.push("- Form labels and validation messages"),i.push("Code (variable names, comments, file names) stays in English."),i.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),i.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(o)&&(e.audienceType==="b2c"?(i.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),i.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),i.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),i.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),i.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),i.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),i.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),i.push("")):e.audienceType==="b2b"?(i.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),i.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),i.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),i.push("- Testimonials: from business owners who use the platform"),i.push("- Features: business benefits ('Track dietary preferences across all orders')"),i.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),i.push("")):e.audienceType==="internal"&&(i.push("### Audience: internal staff tool. No marketing copy needed."),i.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),i.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),i.push(""))),r.length>0&&(i.push("### Already completed:"),r.forEach(P=>i.push(`- ${P}`)),i.push(""));let u=e.dataModel?lc(t,e.dataModel):[];u.length>0&&(i.push("### Data model (from plan):"),u.forEach(P=>{let y=Ur(P),v=Fh(P.fields);i.push(`- **${y}**: ${v}`),i.push(` Schema file: \`db/schema/${y.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),i.push(""));let d=e.pages?Bh(t,e.pages):[];if(d.length>0&&(i.push("### Pages to create/update:"),d.forEach(P=>{let y=P.description?` \u2014 ${P.description}`:"";i.push(`- \`${ac(P)}\`${y}`)}),i.push("")),o==="crud"&&u.length>0&&u.forEach(P=>{let y=Ur(P),v=y.toLowerCase().replace(/\s+/g,"-"),N=v.endsWith("s")?v:`${v}s`;i.push(`### Files for ${y} CRUD:`),i.push(`- List page: \`app/(dashboard)/${N}/page.tsx\` (Server Component)`),i.push(`- Detail page: \`app/(dashboard)/${N}/[id]/page.tsx\``),i.push(`- Create page: \`app/(dashboard)/${N}/new/page.tsx\``),i.push(`- Server Actions: \`app/(dashboard)/${N}/actions.ts\``),i.push(`- DataTable columns: \`components/${v}-table-columns.tsx\``),i.push(`- Form: \`components/${v}-form.tsx\``),i.push("")}),l){i.push("## Design Doctrine (the standard for every UI step)"),i.push(""),i.push(Gl),i.push(""),i.push("## Design Reference Library"),i.push(""),i.push("### Typography"),i.push(Kl),i.push(""),i.push("### Color"),i.push(Yl),i.push(""),i.push("### Motion"),i.push(Xl),i.push(""),i.push("### Spatial Composition"),i.push(ec),i.push(""),i.push("### Interaction"),i.push(nc),i.push(""),i.push("### UX Writing"),i.push(oc),i.push("");let P=s?ot(s,"DESIGN.md"):void 0,y=P&&Et(P)?(()=>{try{return ys(P,"utf-8")}catch{return null}})():null;y&&(i.push("### Design system (source of truth: DESIGN.md):"),i.push(""),i.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."),i.push(""),i.push(y),i.push(""));let v=s?ot(s,".mistflow","picker-render.html"):void 0;(o==="landing"||o==="design")&&v&&Et(v)&&(i.push("### Picked landing page render \u2014 ground-truth design contract"),i.push(""),i.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."),i.push(""),i.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."),i.push(""),i.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` ONLY when the corresponding file exists in `public/images/`. If the slot file is missing, pending, or failed, use the Unsplash URLs in the Visual strategy block above as the public landing fallback. If neither exists, preserve the image/media area as a large domain-specific scene placeholder and tell the user imagery is pending \u2014 never delete the image section, never replace it with a tiny card-only mockup, and never ship picsum URLs. For the favicon slot, also wire `app/icon.png` when the asset exists.\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.\n7. **Keep the hero minimal.** Preserve the picked hero's structure, but do not add a stats row, benefit checklist, extra paragraph, or feature-card cluster to the first viewport. Hero copy is one H1 plus one short supporting sentence; CTAs are one primary plus at most one secondary action unless the picker render already contains more.\n"),i.push("**Two things you MUST add (the picker render is iframe-static and cannot have these \u2014 the deployed page can):**\n8. **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), section reveals, and a card hover interaction. Content must be visible by default before JavaScript runs: do not set critical sections to `initial={{ opacity: 0 }}` unless a hydrated state or CSS fallback makes them visible on Cloudflare. 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.\n9. **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 one short paragraph (\u226422 words, \u22643 lines on desktop). `py-16 lg:py-24` is the normal marketing hero target; `py-10`, `py-12`, `lg:py-10`, and `lg:py-12` are dashboard-density spacing and should not appear in the hero. Use `gap-6`/`gap-8` and `p-5`+ for hero visuals instead of `gap-3`/`p-3` clusters, stats rows, and checklist stacks in the hero. If translating the picker faithfully would push the CTA below the fold, rebalance the composition while keeping the visual area large and intentional."),i.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."),i.push(""))}if(o==="landing"||o==="design"){i.push("### File location for the landing page (non-negotiable):"),i.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.'),i.push(""),i.push("### Landing page hard requirements (non-negotiable):"),i.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) section reveals that enhance already-visible content, (3) one card hover interaction. Never make critical content depend on JavaScript for visibility; Cloudflare deploys must show all sections even if animation hydration is delayed. 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.'),i.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 and supporting copy to one short paragraph (\u226422 words). Do not interpret fold-fit as cramped dashboard spacing: avoid `py-10`/`lg:py-12` heroes, `gap-3` hero grids, `p-3` product mockups, stats rows, feature-card clusters, and benefit checklists in the hero. Marketing heroes should feel minimal, spacious, and image-led or scene-led while still fitting the first fold.'),i.push("");let P=s?ot(s,".mistflow","rules","landing.md"):null;P&&Et(P)?(i.push("### Landing page rules:"),i.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."),i.push("")):(i.push(Pr),i.push(""))}o==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(i.push(Jh(e.layoutSpec)),i.push(""));let m=t.integrationId?en(t.integrationId):void 0;if(m){let P=tn(m.id);if(i.push("### Integration blueprint (follow this closely):"),i.push(""),i.push(`Using integration: **${m.name}** (${m.category})`),P?.docsUrl&&i.push(`Official docs: ${P.docsUrl}`),P?.envVars?.length){i.push(""),i.push("**Required environment variables:**");for(let y of P.envVars)i.push(`- \`${y.key}\`: ${y.description} \u2014 Get it at ${y.setupUrl}`);i.push(""),i.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.")}P?.packages?.length&&(i.push(""),i.push(`**Packages to install:** \`npm install ${P.packages.join(" ")}\``)),i.push(""),i.push("---"),i.push(m.prompt),i.push("---"),i.push(""),i.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."),i.push("")}let{reminders:h,skill:_}=await Kh(o);return i.push(h),i.push(""),_&&(i.push(`### ${o} reference:`),i.push(_),i.push("")),l&&(i.push("## Self-Audit \u2014 run before submitting this file"),i.push(""),i.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.`),i.push(""),i.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.'),i.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."),i.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),i.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),i.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."),i.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),i.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),i.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.'),i.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).'),i.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)."),i.push("11. **Text-heavy or crowded landing hero?** More than one support paragraph, a stats row, checklist, or feature-card cluster in the first viewport? \u2192 cut it back to one headline, one short sentence, one primary CTA, and one visual anchor."),i.push(""),i.push(`If every answer is "no, I'm good" \u2014 then submit.`),i.push("")),i.join(`
|
|
7371
|
+
`)}async function Yh(t){let{projectPath:e,step:r,envVarsRequired:n}=t,o=Mh(e??process.cwd());if(n&&n.length>0)try{let T=Lr(o,n);T.added.length>0&&console.error(`[implement] declared env.required: ${T.added.join(", ")}`)}catch(T){console.error("[implement] env var merge skipped:",T instanceof Error?T.message:String(T))}let s=Uh(o);if(!s)return nt(o);if(!Et(ot(o,"node_modules")))return p(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:T,ensureShadcnComponents:H}=await Promise.resolve().then(()=>(Mo(),Oo)),$=await T(o);$&&!s.projectId&&(s.projectId=$);let V=await H(o);V.failed?console.error(`[implement] ${V.failed}`):V.installed.length>0&&console.error(`[implement] installed ${V.installed.length} shadcn components`);let{selfHealAgentUi:ne}=await Promise.resolve().then(()=>(Ko(),ha)),S=ne(s.plan,o);S&&console.error(`[implement] ${S.isError?"warn: ":""}${S.message}`)}catch(T){console.error("[implement] self-heal skipped:",T instanceof Error?T.message:String(T))}let i=s.plan;if(!i||!i.steps||i.steps.length===0)return p("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let a,l=i.steps.find(T=>T.status==="in_progress");if(l){let T=i.steps.findIndex(H=>H.number===l.number);T!==-1&&(i.steps[T].status="completed",a=`Auto-completed step ${l.number} (${l.name})`,ic(o,s))}let c;if(r!==void 0){if(c=i.steps.find(T=>T.number===r),!c)return p(`Step ${r} not found. The plan has ${i.steps.length} steps (numbered ${i.steps[0].number} to ${i.steps[i.steps.length-1].number}).`,!0)}else if(c=i.steps.find(T=>T.status!=="completed"),!c)return p(JSON.stringify({message:"All plan steps are completed!",completedSteps:i.steps.map(T=>T.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let u=i.steps.filter(T=>T.status==="completed").map(T=>`Step ${T.number}: ${T.name}`),{readLocalState:d}=await Promise.resolve().then(()=>(Ut(),Nn)),m=d(o),h=zh(c),_=[];if((h==="crud"||h==="schema")&&i.dataModel&&c.entities&&c.entities.length>0){let T=lc(c,i.dataModel);for(let H of T){let $=Ur(H);try{let V=(H.fields||[]).map(ke=>typeof ke=="string"?{name:ke,type:"text"}:{name:ke.name,type:qh(ke.type),required:ke.required!==!1});if(V.length===0)continue;let ne=s.dbProvider==="neon"?"nextjs-neon":"nextjs",S=await So(ne,$,V),qe=0,J=0;for(let ke of S.files){let ie=ot(o,ke.path);if(Et(ie)){J++;continue}sc(jh(ie),{recursive:!0}),$r(ie,ke.content),qe++}let _e=ot(o,"db","index.ts");if(Et(_e)){let ke=ys(_e,"utf-8");ke.includes(S.dbExport)||$r(_e,ke.trimEnd()+`
|
|
7372
|
+
`+S.dbExport+`
|
|
7373
|
+
`)}qe>0?_.push(`${S.entityPascal} CRUD (${qe} new files${J>0?`, ${J} existing skipped`:""})`):J>0&&_.push(`${S.entityPascal} CRUD (all ${J} files already exist \u2014 skipped)`)}catch(V){console.error(`Module generation failed for ${$} (non-fatal):`,V instanceof Error?V.message:V)}}}let P=await Vh(c,i,u,null,h,o),y=3e4,v=null;if(P.length>y){let T=ot(o,".mistflow","instructions");try{sc(T,{recursive:!0});let H=`step-${c.number}.md`,$=ot(T,H);$r($,P,"utf-8"),v=`.mistflow/instructions/${H}`,P=[P.slice(0,5e3),"","---",`**Instruction continues in ${v}** (${P.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(`
|
|
7374
|
+
`)}catch(H){console.error("implement-step: failed to write overflow instruction file:",H instanceof Error?H.message:H),P=P.slice(0,y-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 N=i.steps.findIndex(T=>T.number===c.number);if(N!==-1&&(s.plan.steps[N].status="in_progress",ic(o,s)),m&&s.projectId){let{syncRemoteState:T}=await Promise.resolve().then(()=>(Ut(),Nn));T(s.projectId,m).catch(()=>{})}let K=i.steps.every(T=>T.status==="completed"||T.number===c.number),z;K?z=`THIS IS THE LAST STEP. Rules for speed:
|
|
7669
7375
|
|
|
7670
7376
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
7671
7377
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -7676,60 +7382,60 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
7676
7382
|
- Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
|
|
7677
7383
|
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).
|
|
7678
7384
|
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.
|
|
7679
|
-
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).`:
|
|
7385
|
+
7. If mist_build reports type errors in files you did NOT modify in this build (e.g. lib/auth.ts, app/api/admin/seed/route.ts, scaffold-origin code), DO NOT stop \u2014 Mistflow apps do not typecheck before deploy and these errors don't block production. Proceed to mist_deploy. Only halt if mist_build reports an actual compile/runtime failure (a missing import, a syntax error, a runtime error you introduced).`:z=`IMPLEMENT THIS STEP NOW. Rules for speed:
|
|
7680
7386
|
|
|
7681
7387
|
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.
|
|
7682
7388
|
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.
|
|
7683
7389
|
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.
|
|
7684
7390
|
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).
|
|
7685
|
-
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
|
|
7686
|
-
`)}async function
|
|
7687
|
-
`)}function
|
|
7688
|
-
`)}function
|
|
7689
|
-
`)}var
|
|
7391
|
+
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 re=Wh(h),de={stepNumber:c.number,totalSteps:i.steps.length,estimatedMinutes:re,announcement:`Starting step ${c.number} of ${i.steps.length}: ${c.name}. This step usually takes ${re.min}\u2013${re.max} minutes.`},B=JSON.stringify({instruction:P,...v?{instructionFilePath:v}:{},step:{number:c.number,name:c.name,description:c.description,status:"in_progress"},stepTiming:de,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}:{},..._.length>0?{generatedModules:_,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${u.length}/${i.steps.length} steps done`,nextAction:z}),R=Bl(o),oe=R?.url??"http://localhost:3000",W=R?.port??3e3;return await Lh(W)&&Ll(o,c.number,i.steps.length)?($l(o,c.number),Fs(oe,B)):p(B)}var $h,Hh,cc,dc=x(()=>{"use strict";ye();Se();yr();Uo();Vo();wl();Yo();gs();Rr();Wl();Jl();Vl();Ql();Zl();tc();rc();fs();$h=Jn.object({projectPath:Jn.string().optional().describe("Path to the project directory (default: cwd)"),step:Jn.number().optional().describe("Specific step number to implement (default: next incomplete step)"),sessionId:Jn.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:Jn.array(Dr).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.")});Hh=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);cc={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:$h,handler:Yh}});import{resolve as Qh}from"path";async function pc(t){let{projectPath:e,action:r,key:n,value:o,category:s,description:i,setupUrl:a}=t,l=Qh(e??process.cwd());if(!Ie())return je("manage env vars");let u=ht(l)?.projectId;if(!u)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"set":return n?o?(await ao(u,n,o,{category:s,description:i,setupUrl:a}),p(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):p("Value is required. Provide the env var value.",!0):p("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let d=await io(u);return d.length===0?p(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):p(JSON.stringify({envVars:d.map(m=>({key:m.key,category:m.category,description:m.description,hasValue:m.has_value})),message:`${d.length} environment variable(s) configured.`}))}case"delete":return n?(await lo(u,n),p(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):p("Key is required. Provide the env var name to delete.",!0);default:return p(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(d){if(d instanceof ee)return p(d.message,!0);let m=d instanceof Error?d.message:"An unexpected error occurred";return p(m,!0)}}var uc=x(()=>{"use strict";ye();Se();jt()});import{resolve as Xh,join as Zh}from"path";import{existsSync as eg,readFileSync as tg,writeFileSync as ng}from"fs";function bs(t,e){let r=Zh(t,"mistflow.json");if(!eg(r))return;let n;try{n=JSON.parse(tg(r,"utf-8"))}catch{return}n.domains=e,ng(r,JSON.stringify(n,null,2)+`
|
|
7392
|
+
`)}async function mc(t){let{projectPath:e,action:r,domain:n,domainId:o}=t,s=Xh(e??process.cwd());if(!Ie())return je("manage custom domains");let a=ht(s)?.projectId;if(!a)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!n)return p("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await ro(a,n),c=await xt(a);return bs(s,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await xt(a);return l.length===0?p(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):p(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!o){if(n){let d=(await xt(a)).find(m=>m.domain===n);if(d){let m=await mr(a,d.id);return p(JSON.stringify({domain:m.domain,status:m.status,ssl:m.ssl_status,error:m.error_message,message:m.status==="active"?`Domain '${m.domain}' is active and serving traffic.`:`Domain '${m.domain}' is ${m.status}. Make sure DNS records are configured correctly.`}))}return p(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return p("Provide either domainId or domain name to verify.",!0)}let l=await mr(a,o),c=await xt(a);return bs(s,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!o&&!n)return p("Provide either domainId or domain name to remove.",!0);let l=o;if(!l&&n){let d=(await xt(a)).find(m=>m.domain===n);if(!d)return p(`Domain '${n}' not found.`,!0);l=d.id}await oo(a,l);let c=await xt(a);return bs(s,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return p(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof ee)return p(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return p(c,!0)}}var hc=x(()=>{"use strict";ye();Se();jt()});function rg(t){return typeof t=="string"&&gc.includes(t)}function og(t){let e=typeof t.name=="string"&&t.name.trim().length>0?t.name.trim():"<caller-name>",r=typeof t.monthlyBudgetCents=="string"?t.monthlyBudgetCents:"0",n=Array.isArray(t.toolAllowlist)?JSON.stringify(t.toolAllowlist):"null",o=typeof t.rateLimitPerMin=="number"&&Number.isFinite(t.rateLimitPerMin)&&t.rateLimitPerMin>=0?String(t.rateLimitPerMin):"null";return["# Create an MCP caller in the user's deployed app","","The MCP extension generated `createMcpCaller()` in `lib/mcp/caller-auth.ts` of the user's app.","Callers live in the app's own database (the `mcp_caller` table), NOT in the Mistflow backend.","","## Recommended approach","","Run this as a one-off script in the user's app (e.g. in `scripts/mcp-create-caller.ts`):","","```ts","import { createMcpCaller } from '@/lib/mcp/caller-auth'","import { getMcpDb } from '@/lib/mcp/caller-auth'","","const result = await createMcpCaller(getMcpDb(process.env as never), {",` name: ${JSON.stringify(e)},`,` monthlyBudgetCents: ${JSON.stringify(r)},`,` toolAllowlist: ${n},`,` rateLimitPerMin: ${o},`,"})","","// The plaintext token is shown ONCE. Capture it now; only the hash is stored.","console.error('caller created', result.callerId, result.tokenHashPrefix)","console.log(result.token)","```","","## Security","- Run on a trusted machine; the script prints the raw bearer token.","- Store the token in a password manager. The DB only retains the hash.","- If you lose the token, revoke the caller and create a new one."].join(`
|
|
7393
|
+
`)}function sg(){return["# List MCP callers in the user's deployed app","","```ts","import { listMcpCallers, getMcpDb } from '@/lib/mcp/caller-auth'","","const callers = await listMcpCallers(getMcpDb(process.env as never))","console.table(callers.map(({ id, name, tokenHashPrefix, monthlyBudgetCents, revokedAt }) => ({"," id, name, tokenHashPrefix, monthlyBudgetCents, revokedAt,","})))","```","","Listing never returns the raw bearer token (only the hash prefix). To rotate a token, revoke and re-create."].join(`
|
|
7394
|
+
`)}function ig(t){let e=typeof t.callerId=="string"&&t.callerId.trim().length>0?t.callerId.trim():"<caller-id>";return["# Revoke an MCP caller in the user's deployed app","","```ts","import { revokeMcpCaller, getMcpDb } from '@/lib/mcp/caller-auth'","",`await revokeMcpCaller(getMcpDb(process.env as never), ${JSON.stringify(e)})`,"```","","After revocation the caller's bearer token will be rejected by `authenticateCaller()` with code `invalid_or_revoked`."].join(`
|
|
7395
|
+
`)}var gc,fc,yc=x(()=>{"use strict";ye();gc=["create","list","revoke"];fc=async t=>{let e=t??{};if(!rg(e.action))return p(`Unknown action: ${String(e.action)}. Use one of: ${gc.join(", ")}.`,!0);switch(e.action){case"create":return p(og(e),!1);case"list":return p(sg(),!1);case"revoke":return p(ig(e),!1)}}});import{z as Oe}from"zod";var ag,bc,wc=x(()=>{"use strict";ye();uc();hc();yc();ag=Oe.object({resource:Oe.enum(["env","domain","mcp-caller"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains. 'mcp-caller' manages bearer tokens for the app's MCP endpoint (create/list/revoke)."),action:Oe.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'. mcp-caller: 'create', 'list', 'revoke'."),projectPath:Oe.string().optional().describe("Path to the project directory (default: cwd)"),key:Oe.string().optional().describe("(env) Variable name"),value:Oe.string().optional().describe("(env set) Variable value"),category:Oe.string().optional().describe("(env set) Category"),description:Oe.string().optional().describe("(env set) Description"),setupUrl:Oe.string().optional().describe("(env set) URL to obtain the value"),domain:Oe.string().optional().describe("(domain) Domain name"),domainId:Oe.string().optional().describe("(domain) Domain ID"),name:Oe.string().optional().describe("(mcp-caller create) Human-readable name"),callerId:Oe.string().optional().describe("(mcp-caller revoke) The caller id to revoke"),monthlyBudgetCents:Oe.string().optional().describe("(mcp-caller create) Budget cap in cents as a string. '0' means unlimited."),toolAllowlist:Oe.array(Oe.string()).optional().describe("(mcp-caller create) Restrict the caller to these MCP tool names. Omit for unrestricted."),rateLimitPerMin:Oe.number().optional().describe("(mcp-caller create) Per-minute rate limit on this caller's tool calls.")}),bc={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:ag,handler:async t=>{let e=t;switch(e.resource){case"env":return pc({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return mc({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});case"mcp-caller":return fc({action:e.action,name:e.name,callerId:e.callerId,monthlyBudgetCents:e.monthlyBudgetCents,toolAllowlist:e.toolAllowlist,rateLimitPerMin:e.rateLimitPerMin});default:return p(`Unknown resource: ${e.resource}. Use env, domain, or mcp-caller.`,!0)}}}});import{z as Kn}from"zod";import{resolve as lg}from"path";import{existsSync as cg}from"fs";import{join as dg}from"path";function pg(t,e=15){let r=t.split(`
|
|
7690
7396
|
`).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
|
|
7691
|
-
`)}var
|
|
7692
|
-
`+
|
|
7397
|
+
`)}var ug,vc,kc=x(()=>{"use strict";ye();Wn();on();gs();ug=Kn.object({projectPath:Kn.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:Kn.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:Kn.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:Kn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),vc={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:ug,handler:async(t,e)=>{let r=t;if(r.jobId){let l=await At(r.jobId);if(!l)return p(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No install job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let c=r.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let d=l.elapsed,m=e?rt(e.server,e.progressToken,()=>`Install running (${d}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let h=await hn(r.jobId,{timeoutMs:c*1e3,onPoll:_=>{d=_.elapsed}});h&&(l=h)}finally{m.stop()}}if(l.status==="running"||l.status==="starting")return p(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:pg(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 d=await Hl(l.cwd),m=!1;d&&d.freshlyStarted?(m=await Ul(d.state.url,15e3),m&&zl(d.state.url)):d&&(m=!0);let h=d?m?` PREVIEW: Live dev server at ${d.state.url} (browser opened). TELL THE USER: "Your app is rendering at ${d.state.url} \u2014 it'll refresh live as it's built."`:` PREVIEW: Dev server starting at ${d.state.url} (still compiling). TELL THE USER: "Open ${d.state.url} in your browser in ~30s \u2014 your app will appear there and refresh live as it's built."`:"";return p(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,...d?{previewUrl:d.state.url,previewReady:m}:{},nextAction:`Dependencies installed.${h} Run mist_implement next to start executing plan steps.`}))}let u=Jt(l.id);return p(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:u,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${u.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let n=lg(r.projectPath);if(!cg(dg(n,"package.json")))return p(`No package.json at ${n}. Confirm the path and that mist_init has scaffolded the project.`,!0);let i=`npm install && (${`npx --yes shadcn@latest add -y -o ${["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"].join(" ")}`} || echo 'shadcn add failed \u2014 implement will retry lazily')`,a=await Rt({type:"install",cmd:"sh",args:["-c",i],cwd:n,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return p(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:n,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+a.id+"' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s."}))}}});import{z as gn}from"zod";import{resolve as mg,join as st}from"path";import{existsSync as lt,readFileSync as xc,statSync as hg,readdirSync as gg}from"fs";function fg(t){let e=0,r=0,n=[t];for(;n.length>0&&r<1e4;){let o=n.pop();r++;let s;try{s=gg(o)}catch{continue}for(let i of s){let a=st(o,i),l;try{l=hg(a)}catch{continue}l.isDirectory()?n.push(a):l.isFile()&&(e+=l.size)}}return e}function yg(t){if(!(lt(st(t,"open-next.config.ts"))||lt(st(t,"open-next.config.js"))))return null;let r=st(t,".open-next","worker.js");if(!lt(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker entrypoint. Common causes: (1) open-next.config.ts is misconfigured, (2) a client component imports a Node-only API (fs, path, crypto node:* imports in 'use client' files), (3) the adapter crashed silently mid-build. Check the logTail above for "error"/"failed" messages, fix the offending file, and re-run mist_build.`;let n=st(t,".open-next","server-functions","default");if(!lt(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=fg(n);return o<Sc?`Build exited 0 but the server-functions bundle is only ${o} bytes (expected at least ${Sc}). 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 wg(t){let e=st(Or(),t,"stdout.log"),r=st(Or(),t,"stderr.log"),n="";try{lt(e)&&(n+=xc(e,"utf-8"))}catch{}try{lt(r)&&(n+=`
|
|
7398
|
+
`+xc(r,"utf-8"))}catch{}return n}function vg(t,e=15){let r=t.split(`
|
|
7693
7399
|
`).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
|
|
7694
|
-
`)}function dg(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let n of t.matchAll(e)){let o=n[1];if(o.startsWith(".")||o.startsWith("@/")||o.startsWith("~/"))continue;let s=o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0];s&&r.add(s)}return[...r]}function pg(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${Ht()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var pc,ag,uc,mc=v(()=>{"use strict";xe();zn();$o();rn();Cr();pc=100*1024;ag=hn.object({projectPath:hn.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:hn.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:hn.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:hn.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:hn.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."});uc={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:ag,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await It(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 E=c.elapsed,V=e?Xe(e.server,e.progressToken,()=>`Build running (${E}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let Y=await mn(r.jobId,{timeoutMs:m*1e3,onPoll:ne=>{E=ne.elapsed}});Y&&(c=Y)}finally{V.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:cg(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 E=ig(c.cwd);if(E){let V=Wt(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:V,error:E,nextAction:E+` Full build log: ${V.stdout} and ${V.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=lg(c.id),u=br(p),h=dg(p),F=pg(p),T=Wt(c.id),S=` Full log: ${T.stdout} and ${T.stderr}.`,w=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.${S}`:F?`${F}${S}`:u.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${S}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${S}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:u,missingModules:h,logTail:c.logTail,logPaths:T,nextAction:w}),!0)}let n=ng(r.projectPath);if(!st(et(n,"package.json")))return d(`No package.json at ${n}. Run mist_init first.`,!0);if(!st(et(n,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let o,s,i,a=st(et(n,"open-next.config.ts"))||st(et(n,"open-next.config.js"));if(r.script)o="npm",s=["run",r.script],i=r.script;else if(a){if(!sn())return d(Ht(),!0);o="npx",s=["-y","@opennextjs/cloudflare","build"],i="@opennextjs/cloudflare build"}else o="npm",s=["run","build"],i="build";let l=await Pt({type:"build",cmd:o,args:s,cwd:n});return d(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:i,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 ug,readdirSync as mg}from"fs";import{join as hc}from"path";import{pathToFileURL as hg}from"url";async function gg(t){let e=hc(t,".mistflow","acceptance"),r=new Map;if(!ug(e))return r;let n=mg(e).filter(o=>o.endsWith(".spec.ts")||o.endsWith(".spec.js")||o.endsWith(".spec.mjs"));for(let o of n){let s=o.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!s)continue;let i=hc(e,o);try{let a=await import(hg(i).href),l=a.default??a.run;typeof l=="function"?r.set(s,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 r}async function gc(t,e){let{sessionId:r,projectPath:n,deployUrl:o,seedCredentials:s}=e,a=(await Cn(r)).criteria,l=await gg(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:s});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 fc=v(()=>{"use strict";Re()});import{existsSync as fg,readFileSync as yg}from"fs";import{join as bg}from"path";import{z as gn}from"zod";function vc(t){let e=bg(t,"mistflow.json");if(!fg(e))return null;try{return JSON.parse(yg(e,"utf-8"))}catch{return null}}async function yc(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 vg(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)}),o=await n.text(),s;try{s=JSON.parse(o)}catch{}return{status:n.status,json:s}}catch{return{status:0}}}async function bc(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function Et(t,e,r){let n=[],o=s=>{s.type()==="error"&&n.push(s.text())};t.on("console",o);try{let s=await r(),i=await bc(t);return{name:e,status:s.pass?"pass":"fail",detail:s.detail,fix:s.fix,screenshot:i,consoleErrors:n.length>0?n:void 0}}catch(s){let i=await bc(t);return{name:e,status:"fail",detail:`Unexpected error: ${s instanceof Error?s.message:String(s)}`,screenshot:i,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",o)}}async function kg(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=vc(e),n=t.url;if(!n&&t.deploymentId)try{let a=await wt(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 o;if(t.deploymentId)try{let l=await mr(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 s,i;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(Kt(),_n)),l=await a();s=l.context,i=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 gc(i,{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(s)try{await s.close()}catch{}}}async function xg(t){let e=t.projectPath??process.cwd(),r=vc(e),n=t.url;if(!n&&t.deploymentId)try{let E=await wt(t.deploymentId);E.url&&(n=E.url)}catch(E){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,E instanceof Error?E.message:String(E))}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 o=r?.projectId,s=[],i=await yc(`${n}/api/health`);if(i.status!==200)return s.push({name:"Health endpoint",status:"fail",detail:`Returns ${i.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),Ur(n,s);s.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await yc(`${n}/api/auth/ok`);if(a.status!==200)return s.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${a.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),Ur(n,s);s.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 F(E,V,Y,ne){let ce=await vg(`${n}/api/admin/seed`,{token:ne,email:V,password:m,role:Y});if(ce.status!==200||!ce.json)return console.error(`[qa] Seed (${E}) returned ${ce.status}`),null;let X=ce.json.sessionToken;if(!X)return null;let q=ce.json.seeded===!0;return{role:E,email:V,sessionToken:X,password:q?m:void 0}}if(o){let E=await mr(o);if(E){if(p=E.authMode??"single",u=E.defaultRole??"user",console.error(`[qa] auth_mode=${p}, default_role=${u}`),p!=="none"){let Y=await F("actor",l,p==="multi"?"admin":u,E.seedToken);if(Y&&h.push(Y),p==="multi"){let ne=await F("user",c,u,E.seedToken);ne?h.push(ne):s.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 s.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy injects ADMIN_SEED_TOKEN and stores it on the backend; the scaffold's /api/admin/seed route accepts { token, email, password, role } and creates synthetic QA users with the requested role."}),Ur(n,s);let T,S,w;try{let{getIsolatedContext:E}=await Promise.resolve().then(()=>(Kt(),_n)),V=await E();T=V.context,w=V.page}catch(E){let V=E instanceof Error?E.message:String(E);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:V,httpChecks:s.map(({screenshot:Y,...ne})=>ne),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${n}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${n}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_qa again for full verification."].join(`
|
|
7695
|
-
`)}),!1)}try{let
|
|
7696
|
-
`),
|
|
7697
|
-
\u2026and ${
|
|
7400
|
+
`)}function kg(t){let e=[/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,/Module not found:\s*(?:Error:\s*)?Can't find ['"]([^'"]+)['"]/g,/Cannot find module ['"]([^'"]+)['"]/g],r=new Set;for(let n of e)for(let o of t.matchAll(n)){let s=o[1];if(s.startsWith(".")||s.startsWith("@/")||s.startsWith("~/"))continue;let i=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];i&&r.add(i)}return[...r]}function xg(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${zt()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var Sc,bg,_c,Tc=x(()=>{"use strict";ye();Wn();Fo();on();Cr();Sc=100*1024;bg=gn.object({projectPath:gn.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:gn.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:gn.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:gn.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:gn.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."});_c={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:bg,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await At(r.jobId);if(!c)return p(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let u=r.waitSeconds??20;if(u>0&&(c.status==="running"||c.status==="starting")){let N=c.elapsed,K=e?rt(e.server,e.progressToken,()=>`Build running (${N}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let z=await hn(r.jobId,{timeoutMs:u*1e3,onPoll:re=>{N=re.elapsed}});z&&(c=z)}finally{K.stop()}}if(c.status==="running"||c.status==="starting")return p(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:vg(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 N=yg(c.cwd);if(N){let K=Jt(c.id);return p(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:K,error:N,nextAction:N+` Full build log: ${K.stdout} and ${K.stderr}.`}),!0)}return p(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let d=wg(c.id),m=wr(d),h=kg(d),_=xg(d),P=Jt(c.id),y=` Full log: ${P.stdout} and ${P.stderr}.`,v=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.${y}`:_?`${_}${y}`:m.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${y}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${y}`;return p(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:m,missingModules:h,logTail:c.logTail,logPaths:P,nextAction:v}),!0)}let n=mg(r.projectPath);if(!lt(st(n,"package.json")))return p(`No package.json at ${n}. Run mist_init first.`,!0);if(!lt(st(n,"node_modules")))return p(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let o,s,i,a=lt(st(n,"open-next.config.ts"))||lt(st(n,"open-next.config.js"));if(r.script)o="npm",s=["run",r.script],i=r.script;else if(a){if(!ln())return p(zt(),!0);o="npx",s=["-y","@opennextjs/cloudflare","build"],i="@opennextjs/cloudflare build"}else o="npm",s=["run","build"],i="build";let l=await Rt({type:"build",cmd:o,args:s,cwd:n});return p(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:i,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 Sg,readdirSync as _g}from"fs";import{join as Cc}from"path";import{pathToFileURL as Tg}from"url";async function Cg(t){let e=Cc(t,".mistflow","acceptance"),r=new Map;if(!Sg(e))return r;let n=_g(e).filter(o=>o.endsWith(".spec.ts")||o.endsWith(".spec.js")||o.endsWith(".spec.mjs"));for(let o of n){let s=o.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!s)continue;let i=Cc(e,o);try{let a=await import(Tg(i).href),l=a.default??a.run;typeof l=="function"?r.set(s,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 r}async function Ic(t,e){let{sessionId:r,projectPath:n,deployUrl:o,seedCredentials:s}=e,a=(await In(r)).criteria,l=await Cg(n),c=[];for(let u of a){let d=l.get(u.id);if(!d){c.push({criterion_id:u.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${u.id}.spec.ts`}});continue}try{await t.goto(o,{waitUntil:"domcontentloaded"});let m=await d(t,{url:o,criterion:u,seedCredentials:s});c.push({criterion_id:u.id,status:m.pass?"pass":"fail",evidence:{...m.detail?{detail:m.detail}:{},...m.screenshot?{screenshot:m.screenshot}:{}}})}catch(m){c.push({criterion_id:u.id,status:"fail",evidence:{error:m instanceof Error?m.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var Pc=x(()=>{"use strict";Se()});import{existsSync as Ig,readFileSync as Pg}from"fs";import{join as Rg}from"path";import{z as fn}from"zod";function Nc(t){let e=Rg(t,"mistflow.json");if(!Ig(e))return null;try{return JSON.parse(Pg(e,"utf-8"))}catch{return null}}async function Rc(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 Eg(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)}),o=await n.text(),s;try{s=JSON.parse(o)}catch{}return{status:n.status,json:s}}catch{return{status:0}}}async function Ac(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function Nt(t,e,r){let n=[],o=s=>{s.type()==="error"&&n.push(s.text())};t.on("console",o);try{let s=await r(),i=await Ac(t);return{name:e,status:s.pass?"pass":"fail",detail:s.detail,fix:s.fix,screenshot:i,consoleErrors:n.length>0?n:void 0}}catch(s){let i=await Ac(t);return{name:e,status:"fail",detail:`Unexpected error: ${s instanceof Error?s.message:String(s)}`,screenshot:i,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",o)}}async function Ng(t){if(!t.sessionId)return p("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=Nc(e),n=t.url;if(!n&&t.deploymentId)try{let a=await kt(t.deploymentId);a.url&&(n=a.url)}catch(a){console.error(`[acceptance] Could not resolve URL from deploymentId ${t.deploymentId}:`,a instanceof Error?a.message:String(a))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa action='acceptance'.",!0);let o;if(t.deploymentId)try{let l=await hr(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 s,i;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(Kt(),Tn)),l=await a();s=l.context,i=l.page}catch(a){return p(`Playwright not available locally \u2014 install it with \`npx playwright install chromium\`. Detail: ${a instanceof Error?a.message:String(a)}`,!0)}try{let{criteria:a,results:l}=await Ic(i,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:o});try{await Ao(t.sessionId,l)}catch(m){console.error("[acceptance] submitAcceptanceResults failed:",m instanceof Error?m.message:String(m))}let c=l.filter(m=>m.status==="pass").length,u=l.filter(m=>m.status==="fail").length,d=l.filter(m=>m.status==="skipped").length;return p(JSON.stringify({status:u===0?"pass":"fail",url:n,totals:{passed:c,failed:u,skipped:d,total:a.length},results:l.map(m=>({criterion_id:m.criterion_id,status:m.status,detail:m.evidence&&typeof m.evidence=="object"&&"detail"in m.evidence?m.evidence.detail:m.evidence&&typeof m.evidence=="object"&&"reason"in m.evidence?m.evidence.reason:void 0})),nextAction:u===0?"All required acceptance criteria passed. The app is shippable.":"Some criteria failed. Read the per-criterion detail, fix the underlying code, then re-run mist_qa action='acceptance'."}),u>0)}finally{if(s)try{await s.close()}catch{}}}async function Og(t){let e=t.projectPath??process.cwd(),r=Nc(e),n=t.url;if(!n&&t.deploymentId)try{let N=await kt(t.deploymentId);N.url&&(n=N.url)}catch(N){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,N instanceof Error?N.message:String(N))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);n.startsWith("http")||(n=`https://${n}`);let o=r?.projectId,s=[],i=await Rc(`${n}/api/health`);if(i.status!==200)return s.push({name:"Health endpoint",status:"fail",detail:`Returns ${i.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),Fr(n,s);s.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Rc(`${n}/api/auth/ok`);if(a.status!==200)return s.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."}),Fr(n,s);s.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",u="QaTemp1!",d="single",m="user",h=[];async function _(N,K,z,re){let de=await Eg(`${n}/api/admin/seed`,{token:re,email:K,password:u,role:z});if(de.status!==200||!de.json)return console.error(`[qa] Seed (${N}) returned ${de.status}`),null;let te=de.json.sessionToken;if(!te)return null;let B=de.json.seeded===!0;return{role:N,email:K,sessionToken:te,password:B?u:void 0}}if(o){let N=await hr(o);if(N){if(d=N.authMode??"single",m=N.defaultRole??"user",console.error(`[qa] auth_mode=${d}, default_role=${m}`),d!=="none"){let z=await _("actor",l,d==="multi"?"admin":m,N.seedToken);if(z&&h.push(z),d==="multi"){let re=await _("user",c,m,N.seedToken);re?h.push(re):s.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${m}). 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"),d="none"}if(d!=="none"&&h.length===0)return s.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."}),Fr(n,s);let P,y,v;try{let{getIsolatedContext:N}=await Promise.resolve().then(()=>(Kt(),Tn)),K=await N();P=K.context,v=K.page}catch(N){let K=N instanceof Error?N.message:String(N);return p(JSON.stringify({status:"cannot_verify",url:n,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:K,httpChecks:s.map(({screenshot:z,...re})=>re),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(`
|
|
7401
|
+
`)}),!1)}try{let N=await Nt(v,"Landing page",async()=>{await v.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await v.waitForLoadState("networkidle").catch(()=>{});let te=await v.evaluate(()=>{let R=document.body;if(!R)return"";let oe=document.createTreeWalker(R,NodeFilter.SHOW_TEXT),W="",ae;for(;ae=oe.nextNode();){let T=ae.parentElement;if(T){let H=window.getComputedStyle(T);H.display!=="none"&&H.visibility!=="hidden"&&parseFloat(H.opacity)>0&&(W+=ae.textContent?.trim()+" ")}}return W.trim()});if(te.length<50)return{pass:!1,detail:`Landing page appears blank (${te.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 (${te.length} chars)`}});s.push(N),d==="none"&&s.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let K=h[0],z=(te,B)=>h.length>1&&te?`${B} (${te.role})`:B,re=!1;if(K?.password){let te=await Nt(v,z(K,"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]'),R=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(K.email),await R.first().fill(K.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(W=>!W.pathname.includes("/login"),{timeout:1e4})}catch{let W=await v.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:W?`Login failed: ${W}`:"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 re=!0,{pass:!0,detail:`Logged in, redirected to ${v.url()}`}});s.push(te)}else K&&s.push({name:z(K,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!re&&K){let te=new URL(n).hostname,B=n.startsWith("https");await P.addCookies([{name:B?"__Secure-better-auth.session_token":"better-auth.session_token",value:K.sessionToken,domain:te,path:"/",httpOnly:!0,secure:B,sameSite:"Lax"}]),console.error(`[qa] Injected ${K.role} cookie for primary walk`)}if(K){let te=await Nt(v,z(K,"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 oe=await v.content();return oe.length<1e3?{pass:!1,detail:`Dashboard page is very small (${oe.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 (${oe.length} bytes)`}});s.push(te);let B=await v.evaluate(()=>{let oe=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(ae=>{let T=ae.getAttribute("href");T&&T.startsWith("/")&&!T.startsWith("/api")&&!T.includes("[")&&T!=="/dashboard"&&T!=="/"&&!T.includes("/login")&&!T.includes("/sign")&&oe.push(T)}),[...new Set(oe)]});if(B.length>0){let oe=0,W=[];for(let ae of B.slice(0,8)){let T=await Nt(v,z(K,`Page: ${ae}`),async()=>{await v.goto(`${n}${ae}`,{waitUntil:"domcontentloaded",timeout:15e3}),await v.waitForLoadState("networkidle").catch(()=>{});let H=await v.title(),$=await v.content();return H.toLowerCase().includes("500")||H.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."}:H.toLowerCase().includes("404")||H.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${ae} 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."}:$.length<500?{pass:!1,detail:`Page is very small (${$.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});T.status==="fail"&&(oe++,W.push(ae)),s.push(T)}}let R=await Nt(v,"Design quality",async()=>{let oe=v.url().includes("/dashboard")?v.url():`${n}/dashboard`;v.url().includes("/dashboard")||(await v.goto(oe,{waitUntil:"domcontentloaded",timeout:15e3}),await v.waitForLoadState("networkidle").catch(()=>{}));let W=await v.evaluate(()=>{let ae=[],T=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),H=new Set;T.forEach(M=>{H.add(window.getComputedStyle(M).fontSize)}),T.length>=3&&H.size<2&&ae.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 $=Array.from(T).map(M=>parseInt(M.tagName.charAt(1),10));for(let M=1;M<$.length;M++)if($[M]-$[M-1]>1){ae.push(`TYPOGRAPHY: Heading level skipped (h${$[M-1]} -> h${$[M]}). Use sequential heading levels for accessibility.`);break}let V=document.querySelectorAll("*"),ne=!1,S=!1;V.forEach(M=>{let ue=window.getComputedStyle(M);ue.backgroundColor==="rgb(0, 0, 0)"&&M.clientHeight>100&&M.clientWidth>200&&(ne=!0);let Pe=ue.backgroundColor,Ge=ue.color;if(Pe&&!Pe.includes("0, 0, 0")&&!Pe.includes("255, 255, 255")&&Pe!=="rgba(0, 0, 0, 0)"&&Pe!=="transparent"&&Ge.match(/rgb\((\d+), (\d+), (\d+)\)/)){let dt=Ge.match(/rgb\((\d+), (\d+), (\d+)\)/);if(dt){let[Je,$e,g]=[parseInt(dt[1]),parseInt(dt[2]),parseInt(dt[3])],b=Math.abs(Je-$e)<10&&Math.abs($e-g)<10&&Je>80&&Je<180,C=Pe.match(/rgb\((\d+), (\d+), (\d+)\)/);if(b&&C){let[A,O,Y]=[parseInt(C[1]),parseInt(C[2]),parseInt(C[3])];!(Math.abs(A-O)<15&&Math.abs(O-Y)<15)&&M.textContent&&M.textContent.trim().length>0&&(S=!0)}}}}),ne&&ae.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&&ae.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 qe=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),J=!1;qe.forEach(M=>{M.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(J=!0)}),J&&ae.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let _e=document.querySelectorAll("p, li, span, div"),ke=0,ie=0;_e.forEach(M=>{M.textContent&&M.textContent.trim().length>20&&M.clientHeight>0&&(ie++,window.getComputedStyle(M).textAlign==="center"&&ke++)}),ie>5&&ke/ie>.7&&ae.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let Te=new Set;V.forEach(M=>{let ue=window.getComputedStyle(M);ue.gap&&ue.gap!=="normal"&&ue.gap!=="0px"&&Te.add(ue.gap)}),Te.size===1&&V.length>20&&ae.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let We=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(M=>{M.querySelectorAll("tbody tr").length===0&&(M.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||ae.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 it=document.querySelectorAll("style"),Qe=!1;it.forEach(M=>{let ue=M.textContent||"";(ue.includes("bounce")||ue.includes("elastic")||ue.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Qe=!0)}),Qe&&ae.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let wt=document.querySelectorAll("button, a, input, select, [role='button']"),Me=[];if(wt.forEach(M=>{let ue=M.getBoundingClientRect();if(ue.width>0&&ue.height>0&&(ue.width<32||ue.height<32)){let Pe=M.tagName.toLowerCase(),Ge=M.id?`#${M.id}`:"",dt=M.className&&typeof M.className=="string"?`.${M.className.split(/\s+/).filter(Boolean).slice(0,2).join(".")}`:"",Je=(M.textContent||"").trim().slice(0,40),$e=`${Pe}${Ge}${dt}`,g=`${Math.round(ue.width)}x${Math.round(ue.height)}px`;Me.push(Je?`${$e} ("${Je}", ${g})`:`${$e} (${g})`)}}),Me.length>3){let M=Me.slice(0,8).map((Pe,Ge)=>` ${Ge+1}. ${Pe}`).join(`
|
|
7402
|
+
`),ue=Me.length>8?`
|
|
7403
|
+
\u2026and ${Me.length-8} more.`:"";ae.push(`ACCESSIBILITY: ${Me.length} interactive elements are smaller than 32x32px (minimum recommended touch target is 44x44px). Add padding so each element's bounding box reaches 44x44.
|
|
7698
7404
|
Offenders:
|
|
7699
|
-
${
|
|
7700
|
-
${
|
|
7701
|
-
`)}`,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."}});s.push(
|
|
7702
|
-
${
|
|
7703
|
-
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});s.push(
|
|
7405
|
+
${M}${ue}`)}return ae});return W.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${W.length} design quality issue(s) found:
|
|
7406
|
+
${W.map((ae,T)=>`${T+1}. ${ae}`).join(`
|
|
7407
|
+
`)}`,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."}});s.push(R)}if(s.find(te=>te.name==="Landing page"&&te.status==="pass")){let te=await Nt(v,"Landing design quality",async()=>{await v.goto(n,{waitUntil:"domcontentloaded",timeout:15e3}),await v.waitForLoadState("networkidle").catch(()=>{});let B=await v.evaluate(()=>{let R=[];document.querySelectorAll("*").forEach(T=>{let H=window.getComputedStyle(T);(H.getPropertyValue("-webkit-background-clip")||H.getPropertyValue("background-clip"))==="text"&&T.textContent&&T.textContent.trim().length>0&&R.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let W=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(W){let T=(W.textContent||"").toLowerCase(),H=["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 $ of H)if(T.match(new RegExp($))){R.push(`COPY: Generic hero text detected ('${$}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(T=>{let $=window.getComputedStyle(T).gridTemplateColumns;if($){let V=$.split(" ").filter(S=>S!=="").length,ne=T.children;if(V===3&&ne.length===3){let S=Array.from(ne).map(_e=>_e.offsetHeight),qe=S.every(_e=>Math.abs(_e-S[0])<5),J=Array.from(ne).every(_e=>{let ke=_e.querySelectorAll("svg"),ie=_e.querySelectorAll("h2, h3, h4"),Te=_e.querySelectorAll("p");return ke.length>=1&&ie.length>=1&&Te.length>=1});qe&&J&&R.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.")}}}),R});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):
|
|
7408
|
+
${B.map((R,oe)=>`${oe+1}. ${R}`).join(`
|
|
7409
|
+
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});s.push(te)}let de=h[1];if(de){let{getIsolatedContext:te}=await Promise.resolve().then(()=>(Kt(),Tn)),B=await te();y=B.context;let R=B.page,oe=new URL(n).hostname,W=n.startsWith("https");await y.addCookies([{name:W?"__Secure-better-auth.session_token":"better-auth.session_token",value:de.sessionToken,domain:oe,path:"/",httpOnly:!0,secure:W,sameSite:"Lax"}]),console.error(`[qa] Injected ${de.role} cookie for secondary walk`);let ae=await Nt(R,z(de,"Dashboard"),async()=>{await R.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await R.waitForLoadState("networkidle").catch(()=>{}),new URL(R.url()).pathname==="/"&&(await R.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await R.waitForLoadState("networkidle").catch(()=>{}));let H=await R.content();return H.length<1e3?{pass:!1,detail:`Dashboard is very small (${H.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 R.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 (${H.length} bytes)`}});s.push(ae);let T=await R.evaluate(()=>{let H=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach($=>{let V=$.getAttribute("href");V&&V.startsWith("/")&&!V.startsWith("/api")&&!V.includes("[")&&V!=="/dashboard"&&V!=="/"&&!V.includes("/login")&&!V.includes("/sign")&&H.push(V)}),[...new Set(H)]});for(let H of T.slice(0,8)){let $=await Nt(R,z(de,`Page: ${H}`),async()=>{await R.goto(`${n}${H}`,{waitUntil:"domcontentloaded",timeout:15e3}),await R.waitForLoadState("networkidle").catch(()=>{});let V=await R.title(),ne=await R.content();return V.toLowerCase().includes("500")||V.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."}:V.toLowerCase().includes("404")||V.toLowerCase().includes("not found")?{pass:!0,detail:"404 (likely admin-only \u2014 acceptable)"}:await R.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."}:ne.length<500?{pass:!1,detail:`Page very small (${ne.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});s.push($)}}}finally{P&&await P.close().catch(()=>{}),y&&await y.close().catch(()=>{})}if(t.deploymentId){let N=s.filter(re=>re.status==="fail"),K=s.filter(re=>re.status==="pass"),z=Date.now();await so(t.deploymentId,{checks:s.map(({screenshot:re,...de})=>de),overall:N.length===0?"pass":"fail",passed:K.length,failed:N.length,duration_ms:Date.now()-z}).catch(()=>{})}return Fr(n,s)}function Fr(t,e){let r=e.filter(s=>s.status==="fail"),n=e.filter(s=>s.status==="pass"),o=[];if(r.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:s,...i})=>i)})});else{let s=r.map((i,a)=>`${a+1}. **${i.name}**: ${i.detail}
|
|
7704
7410
|
Fix: ${i.fix}`).join(`
|
|
7705
7411
|
|
|
7706
7412
|
`);o.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${r.length} issue(s) on the live app. Fix them and redeploy.`,url:t,passed:n.length,failed:r.length,checks:e.map(({screenshot:i,...a})=>a),fixInstructions:`The deployed app at ${t} has ${r.length} issue(s):
|
|
7707
7413
|
|
|
7708
7414
|
${s}
|
|
7709
7415
|
|
|
7710
|
-
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 s of e)s.screenshot&&o.push({type:"image",data:s.screenshot,mimeType:"image/png"});return{content:o}}var
|
|
7711
|
-
${o.stderr.slice(-500)}`:""))}let s=0;try{s=
|
|
7416
|
+
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 s of e)s.screenshot&&o.push({type:"image",data:s.screenshot,mimeType:"image/png"});return{content:o}}var Ag,Ec,Oc=x(()=>{"use strict";ye();Se();Pc();Ag=fn.object({projectPath:fn.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:fn.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:fn.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:fn.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:fn.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.")}),Ec={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:Ag,handler:async t=>{let e=t;return e.action==="acceptance"?Ng(e):Og(e)}}});import{existsSync as qr,readdirSync as Mg,statSync as Mc,unlinkSync as jc}from"fs";import{join as yn}from"path";import{execFile as jg}from"child_process";function Dg(t,e){let r=0;for(let n of e){let o=yn(t,n);if(qr(o))try{let s=Mc(o);if(s.isFile())r++;else if(s.isDirectory()){let i=[o];for(;i.length;){let a=i.pop(),l=Mg(a,{withFileTypes:!0});for(let c of l){let u=yn(a,c.name);c.isDirectory()?i.push(u):r++}}}}catch{}}return r}function Lg(t,e,r){return new Promise(n=>{jg("tar",t,{cwd:e,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(o,s,i)=>{n({success:!o,stderr:i?.toString()??""})})})}async function Dc(t){let e=yn(t,".open-next-build.tar.gz"),r=[".open-next"];qr(yn(t,"db"))&&r.push("db"),qr(yn(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),qr(yn(t,"package.json"))&&r.push("package.json");let n=Dg(t,r),o=await Lg(["-czf",e,"-C",t,...r],t,12e4);if(!o.success){try{jc(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(o.stderr?`
|
|
7417
|
+
${o.stderr.slice(-500)}`:""))}let s=0;try{s=Mc(e).size}catch{}return{path:e,sizeBytes:s,fileCount:n}}function Lc(t){if(t)try{jc(t)}catch{}}function $c(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function Uc(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 Fc=x(()=>{"use strict"});import{existsSync as $g,readdirSync as Ug,statSync as Fg}from"fs";import{join as Vn,relative as qg}from"path";function ws(t){try{return Fg(t).mtimeMs}catch{return null}}function Wg(t,e){let r=Vn(t,e);if(!$g(r))return null;let n=null;try{let o=Ug(r,{recursive:!0,withFileTypes:!0});for(let s of o){if(!s.isFile())continue;let i=s.parentPath??s.path??r,a=Vn(i,s.name),l=ws(a);l!==null&&(!n||l>n.mtime)&&(n={mtime:l,path:qg(t,a)})}}catch{}return n}function Gg(t){let e=null,r=n=>{n&&(!e||n.mtime>e.mtime)&&(e=n)};for(let n of Hg){let o=ws(Vn(t,n));o!==null&&r({mtime:o,path:n})}for(let n of Bg)r(Wg(t,n));return e}function qc(t){let e=ws(Vn(t,zg));if(e===null)return{stale:!0,reason:"no .open-next/worker.js build artifact"};let r=Gg(t);return r?r.mtime>e?{stale:!0,reason:`${r.path} modified after last build`,buildMtime:e,newestSource:r}:{stale:!1,buildMtime:e}:{stale:!0,reason:"no source files visible to verify build against",buildMtime:e}}function vs(t){return new Date(t).toISOString()}var Bg,Hg,zg,Bc=x(()=>{"use strict";Bg=["app","components","lib","db","contracts","hooks","styles","public"],Hg=["middleware.ts","middleware.js","next.config.ts","next.config.js","next.config.mjs","open-next.config.ts","open-next.config.js","open-next.config.mjs","tailwind.config.ts","tailwind.config.js","postcss.config.js","postcss.config.mjs","drizzle.config.ts","package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","tsconfig.json",".env",".env.local",".env.production",".env.development"],zg=Vn(".open-next","worker.js")});import{z as ct}from"zod";import{resolve as Jg,join as Yn}from"path";import{existsSync as Qn,readFileSync as Kg}from"fs";import{homedir as Vg}from"os";function Qg(t){return Qn(Yn(t,".open-next"))}function Xg(t){return ht(t)?.deploy?.strategy==="staging"?"preview":null}function Zg(t){let e=ht(t),r=e?.plan?.steps;if(!Array.isArray(r))return;let n=!1;for(let o of r)o.status==="in_progress"&&(o.status="completed",n=!0);n&&or(t,{plan:e.plan})}async function ef(t,e){if(!(Qn(Yn(t,"open-next.config.ts"))||Qn(Yn(t,"open-next.config.js"))))return{kind:"failed",result:p(`No .open-next/ build output at ${t}, and no open-next.config.* either. This project is not configured for the Cloudflare adapter \u2014 mist_deploy ships the .open-next/ artifact, not raw source. If this is a Mistflow project, re-run mist_init to restore the OpenNext config.`,!0)};if(!Qn(Yn(t,"node_modules")))return{kind:"failed",result:p(`node_modules is missing at ${t}. Call mist_install { projectPath } first, then mist_deploy.`,!0)};if(!ln())return{kind:"failed",result:p(zt(),!0)};let n=await Rt({type:"build",cmd:"npx",args:["-y","@opennextjs/cloudflare","build"],cwd:t}),o=e?rt(e.server,e.progressToken,()=>`Auto-building before deploy \u2014 OpenNext adapter (${n.id})`):{stop:()=>{}},s;try{s=await hn(n.id,{timeoutMs:45e3})}finally{o.stop()}if(!s)return{kind:"failed",result:p(`Auto-build job ${n.id} disappeared. Run mist_build { projectPath } manually, then mist_deploy.`,!0)};if(s.status==="running"||s.status==="starting")return{kind:"running",result:p(JSON.stringify({status:"building",buildJobId:n.id,phase:"auto-build",nextAction:`Build is still running after the 45s inline window. Call mist_build { jobId: '${n.id}' } to keep waiting (long-polls server-side), then call mist_deploy { action: 'deploy', projectPath } again. Do NOT ask the user \u2014 the build is in flight, just keep going.`}))};if(s.status==="complete"&&Qg(t))return{kind:"ok"};let i=Jt(n.id),a=(s.logTail??"").split(`
|
|
7712
7418
|
`).slice(-30).join(`
|
|
7713
|
-
`);return{kind:"failed",result:d(JSON.stringify({status:"build_failed",buildJobId:n.id,exitCode:s.exitCode,logTail:a,logPaths:i,nextAction:`Auto-build before deploy failed (exit ${s.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 Og(t){let e=Pg(t.projectPath);if(!Ie())return je("deploy");let r=bt(e),n=r?.projectId;if(!n){if(!r?.name)return d(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);let a=typeof r.plan=="object"&&r.plan!==null?r.plan:void 0;if(!a&&r.planId)try{let u=Vn(Rg(),".mistflow","plans",`${r.planId}.json`);if(Yn(u)){let h=JSON.parse(Ig(u,"utf-8"));a=h?.plan??h}}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:r.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 Dt(r.name,{dbProvider:r.dbProvider,requestedSubdomain:r.requestedSubdomain,pickedDirection:l,imageryBrief:c,planContext:p,designConversationId:m})).id,Yr(e,{projectId:n}),console.error(`[deploy] auto-registered project ${n.slice(0,8)} (${r.name})`+(r.requestedSubdomain?` at ${r.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 h=u instanceof Z||u instanceof Error?u.message:String(u);return d(`Auto-register before deploy failed: ${h}. 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(!Rc(e)){let a=await Ng(e,t.ctx);if(a.kind==="running"||a.kind==="failed")return a.result}let o=t.environment??Eg(e)??"production",s=t.adminEmail??$s()?.email,i=null;try{i=await _c(e);let a=await eo(n,i.path,o,s,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:Tc(i.sizeBytes),buildFileCount:i.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${a.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side, so there's no need to sleep between calls. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(a){let l=a instanceof Z||a instanceof Error?a.message:String(a);return d(`Deploy upload failed: ${l}`,!0)}finally{Cc(i?.path)}}async function Mg(t,e){let r=e.ctx?Xe(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let n=await wt(t,{waitSeconds:e.waitSeconds}),o=Pc(n.status),s=n.id??t;return n.status==="live"?(e.projectPath&&n.url&&(Yr(e.projectPath,{deploy:{url:n.url,deploymentId:s,completedAt:n.completedAt}}),an(e.projectPath)),d(JSON.stringify({status:"complete",jobId:s,deploymentId:s,url:n.url,completedAt:n.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${n.url??""}', deploymentId: '${s}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`}))):n.status==="failed"?d(JSON.stringify({status:"failed",jobId:s,deploymentId:s,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:s,deploymentId:s,phase:o,phaseCode:n.status,nextAction:`Still ${n.status} after the ${e.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${s}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(n){let o=n instanceof Z||n instanceof Error?n.message:String(n);return d(`Could not fetch deploy status: ${o}`,!0)}finally{r.stop()}}async function jg(t,e){if(!Ie())return je("promote a preview deployment");let n=bt(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 i=(await Yt(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!i)return d("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);o=i.id}catch(s){let i=s instanceof Z?s.message:String(s);return d(`Could not list deployments: ${i}`,!0)}try{let s=await ho(n,o);return d(JSON.stringify({status:"running",jobId:s.deployment_id,deploymentId:s.deployment_id,promotedFrom:o,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${s.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(s){let i=s instanceof Z||s instanceof Error?s.message:String(s);return d(`Promote failed: ${i}`,!0)}}async function Dg(t){if(!Ie())return je("roll back a deployment");try{let e=await go(t);return d(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let r=e instanceof Z||e instanceof Error?e.message:String(e);return d(`Rollback failed: ${r}`,!0)}}var Ag,Ac,Ec=v(()=>{"use strict";xe();Re();Mt();Mt();Ir();Ic();rn();ms();zn();Cr();Ag=ht.object({action:ht.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:ht.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:ht.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:ht.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:ht.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:ht.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:ht.array(jr).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:ht.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")});Ac={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:Ag,handler:async(t,e)=>{let r=t;switch(r.action??"deploy"){case"deploy":{if(!r.projectPath)return d("projectPath is required for action='deploy'.",!0);if(r.envVarsRequired&&r.envVarsRequired.length>0)try{let o=Dr(r.projectPath,r.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 Og({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail,ctx:e})}case"status":return r.deploymentId?Mg(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e,projectPath:r.projectPath,sessionId:r.sessionId}):d("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?jg(r.projectPath,r.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?Dg(r.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}}});import{z as yn}from"zod";import{hostname as Lg}from"os";function Nc(){return Lg()}function fs(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(`
|
|
7714
|
-
`)}async function
|
|
7715
|
-
`))}if(r.action==="cancel"){let i=r.sessionId,a=await
|
|
7716
|
-
${
|
|
7419
|
+
`);return{kind:"failed",result:p(JSON.stringify({status:"build_failed",buildJobId:n.id,exitCode:s.exitCode,logTail:a,logPaths:i,nextAction:`Auto-build before deploy failed (exit ${s.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 tf(t){let e=Jg(t.projectPath);if(!Ie())return je("deploy");let r=ht(e),n=r?.projectId;if(!n){if(!r?.name)return p(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);let d=typeof r.plan=="object"&&r.plan!==null?r.plan:void 0;if(!d&&r.planId)try{let y=Yn(Vg(),".mistflow","plans",`${r.planId}.json`);if(Qn(y)){let v=JSON.parse(Kg(y,"utf-8"));d=v?.plan??v}}catch{}let m=d?.pickedDirection??void 0,h=d?.imageryBrief??m?.imagery??void 0,_=d?.designConversationId??void 0,P=d?{name:d.name,summary:d.summary,audienceType:d.audienceType,authModel:d.authModel,dbProvider:r.dbProvider,dataModel:d.dataModel,design:d.design,publicLanding:d.publicLanding,...typeof d.designMd=="string"&&d.designMd?{designMd:d.designMd}:{},..._?{designConversationId:_}:{},...d.features?{features:d.features}:{},...d.integrations?{integrations:d.integrations}:{},...d.hasAI===!0?{hasAI:!0}:{},...d.hasEmail===!0?{hasEmail:!0}:{},...d.hasStorage===!0?{hasStorage:!0}:{}}:void 0;try{n=(await Lt(r.name,{dbProvider:r.dbProvider,requestedSubdomain:r.requestedSubdomain,pickedDirection:m,imageryBrief:h,planContext:P,designConversationId:_})).id,or(e,{projectId:n}),console.error(`[deploy] auto-registered project ${n.slice(0,8)} (${r.name})`+(r.requestedSubdomain?` at ${r.requestedSubdomain}.mistflow.app`:"")+(P?" with plan context":" WITHOUT plan context (no plan blob in mistflow.json \u2014 AI/storage may not provision)"))}catch(y){let v=y instanceof ee||y instanceof Error?y.message:String(y);return p(`Auto-register before deploy failed: ${v}. 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)}}let o=qc(e),s=t.forceRebuild===!0||o.stale,i,a;if(s){t.forceRebuild?a="forceRebuild=true requested":!("buildMtime"in o)||o.buildMtime===void 0?a=o.reason:a=`${o.reason} (last build: ${vs(o.buildMtime)})`,console.error(`[deploy] running fresh build \u2014 ${a}`);let d=await ef(e,t.ctx);if(d.kind==="running"||d.kind==="failed")return d.result;i="fresh"}else a=`up to date with source (built ${vs(o.buildMtime)})`,console.error(`[deploy] reusing existing .open-next/ build \u2014 ${a}`),i="reused";let l=t.environment??Xg(e)??"production",c=t.adminEmail??Ks()?.email,u=null;try{u=await Dc(e);let d=await no(n,u.path,l,c,void 0,void 0,void 0);return p(JSON.stringify({status:"running",jobId:d.deployment_id,deploymentId:d.deployment_id,environment:d.environment??l,buildSize:$c(u.sizeBytes),buildFileCount:u.fileCount,buildSource:i,buildSourceDetail:a,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${d.deployment_id}', projectPath: '${e}' } 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(d){let m=d instanceof ee||d instanceof Error?d.message:String(d);return p(`Deploy upload failed: ${m}`,!0)}finally{Lc(u?.path)}}async function nf(t,e){let r=e.ctx?rt(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let n=await kt(t,{waitSeconds:e.waitSeconds}),o=Uc(n.status),s=n.id??t;return n.status==="live"?(e.projectPath&&n.url&&(Zg(e.projectPath),or(e.projectPath,{deploy:{url:n.url,deploymentId:s,completedAt:n.completedAt}}),cn(e.projectPath)),p(JSON.stringify({status:"complete",jobId:s,deploymentId:s,url:n.url,completedAt:n.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${n.url??""}', deploymentId: '${s}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`}))):n.status==="failed"?p(JSON.stringify({status:"failed",jobId:s,deploymentId:s,error:n.error,phase:o,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):p(JSON.stringify({status:"running",jobId:s,deploymentId:s,phase:o,phaseCode:n.status,nextAction:`Still ${n.status} after the ${e.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${s}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(n){let o=n instanceof ee||n instanceof Error?n.message:String(n);return p(`Could not fetch deploy status: ${o}`,!0)}finally{r.stop()}}async function rf(t,e){if(!Ie())return je("promote a preview deployment");let n=ht(t)?.projectId;if(!n)return p(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let o=e;if(!o)try{let i=(await Qt(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!i)return p("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);o=i.id}catch(s){let i=s instanceof ee?s.message:String(s);return p(`Could not list deployments: ${i}`,!0)}try{let s=await fo(n,o);return p(JSON.stringify({status:"running",jobId:s.deployment_id,deploymentId:s.deployment_id,promotedFrom:o,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${s.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(s){let i=s instanceof ee||s instanceof Error?s.message:String(s);return p(`Promote failed: ${i}`,!0)}}async function of(t){if(!Ie())return je("roll back a deployment");try{let e=await yo(t);return p(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let r=e instanceof ee||e instanceof Error?e.message:String(e);return p(`Rollback failed: ${r}`,!0)}}var Yg,Hc,zc=x(()=>{"use strict";ye();Se();jt();jt();Rr();Fc();Bc();on();fs();Wn();Cr();Yg=ct.object({action:ct.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:ct.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:ct.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:ct.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:ct.string().optional().describe("Optional override for the owner email. Defaults to the email of whoever ran mist_setup (read from ~/.mistflow/credentials.json). Apps with a global admin role auto-promote this email to admin on first signup. Pass explicitly only when the deploying user is not the intended owner contact."),waitSeconds:ct.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:ct.array(Dr).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:ct.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."),forceRebuild:ct.boolean().optional().describe("Force a fresh OpenNext build even when the existing .open-next/ artifact appears up to date. Use when the staleness heuristic might miss a change (e.g. node_modules swapped out-of-band, generated files updated outside the watched source dirs, or a previous deploy looked wrong and you want to rule out caching). Default false. Ignored for non-deploy actions.")});Hc={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:Yg,handler:async(t,e)=>{let r=t;switch(r.action??"deploy"){case"deploy":{if(!r.projectPath)return p("projectPath is required for action='deploy'.",!0);if(r.envVarsRequired&&r.envVarsRequired.length>0)try{let o=Lr(r.projectPath,r.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 tf({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail,forceRebuild:r.forceRebuild,ctx:e})}case"status":return r.deploymentId?nf(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e,projectPath:r.projectPath,sessionId:r.sessionId}):p("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?rf(r.projectPath,r.deploymentId):p("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?of(r.deploymentId):p("deploymentId is required for action='rollback'.",!0)}}}});import{z as bn}from"zod";import{hostname as sf}from"os";function Wc(){return sf()}function ks(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(`
|
|
7420
|
+
`)}async function af(t){let e=Gc.safeParse(t);if(!e.success){let i=e.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return p(`Invalid input: ${i}`,!0)}let r=e.data;if((r.action==="status"||r.action==="cancel"||r.action==="resume")&&!r.sessionId)return p(`Invalid input: action="${r.action}" requires sessionId.`,!0);if(r.action==="resume"&&!r.projectPath)return p('Invalid input: action="resume" requires projectPath.',!0);if(r.action==="status"){let i=r.sessionId,[a,l,c]=await Promise.all([gr(i),Xt(i).catch(()=>null),In(i).catch(()=>null)]),u=[ks(a),"",l?`Next instruction: ${l.instruction}${l.reason?` (${l.reason})`:""}`:"Next instruction: (unavailable)"];if(c&&c.criteria.length>0){u.push("",`Acceptance criteria (${c.criteria.length}):`);for(let d of c.criteria)u.push(` - [${d.priority}] ${d.id}: ${d.description}`)}return p(u.join(`
|
|
7421
|
+
`))}if(r.action==="cancel"){let i=r.sessionId,a=await Io(i,r.reason);return p(`Session cancelled.
|
|
7422
|
+
${ks(a)}
|
|
7717
7423
|
|
|
7718
|
-
Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(r.action==="resume"){let i=r.sessionId,a=r.projectPath,l=
|
|
7424
|
+
Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(r.action==="resume"){let i=r.sessionId,a=r.projectPath,l=Wc(),c=await Pn(i,{machine_id:l,local_path:a}),u=await gr(i),d=await Xt(i).catch(()=>null);return p(`Resumed session on this machine.
|
|
7719
7425
|
Machine: ${l}
|
|
7720
7426
|
Local path: ${c.local_path}
|
|
7721
7427
|
Last seen: ${c.last_seen_at}
|
|
7722
7428
|
|
|
7723
|
-
`+
|
|
7429
|
+
`+ks(u)+(d?`
|
|
7724
7430
|
|
|
7725
|
-
Next instruction: ${
|
|
7726
|
-
`+(r.includeIdle?"Run mist_plan to start a new one.":'Run mist_plan to start a new one, mist_session action="resume" with a sessionId, or mist_session action="list" includeIdle=true to see older sessions.'))}let s=[`Sessions bound on this machine (${n}):`,"",...o.map(i=>` - ${i.id} status=${i.status}${i.paused_after_plan?" (paused)":""} ${i.description?`"${i.description.slice(0,60)}"`:"(no description)"}`)];return
|
|
7727
|
-
`))}var
|
|
7728
|
-
`)}var
|
|
7431
|
+
Next instruction: ${d.instruction}${d.reason?` (${d.reason})`:""}`:""))}let n=Wc(),o=await Rn(n,{includeIdle:r.includeIdle===!0});if(o.length===0){let i=r.includeIdle?"this machine has no sessions bound at all":"no active sessions touched in the last 24h on this machine";return p(`${i} (${n}).
|
|
7432
|
+
`+(r.includeIdle?"Run mist_plan to start a new one.":'Run mist_plan to start a new one, mist_session action="resume" with a sessionId, or mist_session action="list" includeIdle=true to see older sessions.'))}let s=[`Sessions bound on this machine (${n}):`,"",...o.map(i=>` - ${i.id} status=${i.status}${i.paused_after_plan?" (paused)":""} ${i.description?`"${i.description.slice(0,60)}"`:"(no description)"}`)];return p(s.join(`
|
|
7433
|
+
`))}var Gc,Jc,Kc=x(()=>{"use strict";ye();Se();Gc=bn.object({action:bn.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:bn.string().uuid().optional().describe("Required for status / cancel / resume. Omit for list."),reason:bn.string().max(500).optional().describe("Optional cancellation reason (used with action=cancel)."),projectPath:bn.string().min(1).optional().describe("Absolute path to the project directory on this machine. Required for action=resume."),includeIdle:bn.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.")});Jc={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:Gc,handler:af}});async function Vc(t){let e=JSON.stringify({project_id:t.projectId,sql:t.sql,confirm_production:t.confirmProduction});return D("/api/runtime/query",{method:"POST",body:e,timeoutMs:lf,idempotent:!1})}var lf,Yc=x(()=>{"use strict";Se();lf=3e4});import{existsSync as cf,readFileSync as df}from"fs";import{join as pf,resolve as uf}from"path";import{z as Xn}from"zod";function mf(t){let e=[];if(e.push(`Query executed in ${t.execution_time_ms}ms. Returned ${t.row_count} row${t.row_count===1?"":"s"}${t.truncated?" (truncated)":""}.`),t.redacted_field_count>0&&e.push(`Redacted ${t.redacted_field_count} field${t.redacted_field_count===1?"":"s"} that looked like secrets (passwords, API keys, tokens).`),e.push(`Query fingerprint: ${t.query_fingerprint}`),t.columns.length>0&&(e.push(""),e.push(`Columns: ${t.columns.map(r=>r.name).join(", ")}`)),t.rows.length>0){e.push("");let r=t.rows.slice(0,10);e.push(`First ${r.length} row${r.length===1?"":"s"}:`);for(let n of r)e.push(" "+JSON.stringify(n));t.rows.length>10&&e.push(` \u2026 ${t.rows.length-10} more in JSON below`)}return e.push(""),e.push("```json"),e.push(JSON.stringify(t,null,2)),e.push("```"),e.join(`
|
|
7434
|
+
`)}var Qc,Xc,Zc=x(()=>{"use strict";ye();Se();Yc();Qc=Xn.object({action:Xn.literal("query").describe("Always 'query' in v1.0. Other actions reserved for future versions."),projectPath:Xn.string().optional().describe("Path to the Mistflow project (containing mistflow.json). Defaults to cwd."),sql:Xn.string().min(1).max(1e5).describe("Read-only SQL to execute. Must be a single SELECT / WITH / UNION query. INSERT/UPDATE/DELETE/DDL all rejected at the backend with a clear error."),confirmProduction:Xn.literal(!0).describe("Must be exactly `true`. Explicit acknowledgment that the query runs against the project's production database. Every call is audited and visible in the dashboard.")}),Xc={name:"mist_runtime",description:"Run a read-only SQL query against a Mistflow project's PRODUCTION database. Use this for: inspecting data, debugging production behavior, counting rows, auditing user state. DO NOT use this for: implementing features, schema changes, or recurring workflows \u2014 those go through mist_plan / mist_implement. Writes (INSERT/UPDATE/DELETE/DDL) are rejected at the backend with a clear error. Set confirmProduction=true to acknowledge production access; every call is audited.",inputSchema:Qc,handler:async t=>{let e=Qc.safeParse(t);if(!e.success){let l=e.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");return p(`Invalid mist_runtime input: ${l}. Required shape: { action: "query", sql: string, confirmProduction: true }.`,!0)}let r=e.data;if(!Ie())return je("run a runtime query");let n=uf(r.projectPath??process.cwd()),o=pf(n,"mistflow.json");if(!cf(o))return nt(n);let s;try{s=JSON.parse(df(o,"utf-8")).projectId}catch{return p("Could not read mistflow.json.",!0)}if(!s)return p("This project hasn't been registered with Mistflow yet. Run mist_init first.",!0);let i=r.sql.replace(/^\s*(?:\/\*[\s\S]*?\*\/|--[^\n]*\n?)*\s*/,"").trim();if(!/^(select|with|explain|values)\b/i.test(i))return p("mist_runtime accepts read-only SQL only (SELECT / WITH / EXPLAIN / VALUES). INSERT/UPDATE/DELETE/DDL/TRUNCATE are rejected. For schema or data changes, use mist_plan + mist_implement.",!0);let a;try{a=await Vc({projectId:s,sql:r.sql,confirmProduction:r.confirmProduction})}catch(l){let c=l instanceof Error?l.message:String(l);return p(`mist_runtime query failed: ${c}`,!0)}return p(mf(a))}}});var vf={};import{Server as hf}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as gf}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as ff,ListToolsRequestSchema as yf}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as bf}from"zod-to-json-schema";async function wf(){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 gf;await Br.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var Br,ed,td=x(()=>{"use strict";ut();ye();ii();ki();Si();Ii();Ai();Uo();Fi();sa();Ya();dc();wc();kc();Tc();Oc();zc();Kc();Zc();Se();Br=new hf({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Es()}),ed=[si,vi,xi,Ci,Ri,oa,Va,Li,cc,Ui,bc,vc,_c,Ec,Hc,Jc,Xc];Br.setRequestHandler(yf,async()=>({tools:ed.map(t=>({name:t.name,description:t.description,inputSchema:bf(t.inputSchema)}))}));Br.setRequestHandler(ff,async t=>{let e=ed.find(r=>r.name===t.params.name);if(!e)return p(`Unknown tool: ${t.params.name}`,!0);try{let r=e.inputSchema.safeParse(t.params.arguments);if(!r.success){let i=r.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return p(`Invalid input: ${i}`,!0)}let n=typeof r.data=="object"&&r.data!==null&&"sessionId"in r.data&&typeof r.data.sessionId=="string"?r.data.sessionId:void 0;if(n&&e.name!=="mist_session")try{let i=await Po(n,e.name);if(!i.allowed)return p(`Tool ${e.name} not allowed for this session.
|
|
7729
7435
|
Reason: ${i.reason}
|
|
7730
7436
|
Status: ${i.status}
|
|
7731
7437
|
|
|
7732
|
-
Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(i){if(i instanceof
|
|
7438
|
+
Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(i){if(i instanceof ee&&i.code==="not_found")console.error(`Guard check 404 for tool ${e.name}: ${i.message}`);else throw i}let o=t.params._meta?.progressToken,s={server:Br,progressToken:o};try{return await e.handler(r.data,s)}finally{s.cleanup?.()}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),p(n,!0)}});wf().catch(t=>{console.error("Fatal error:",t),process.exit(1)})});import{readFileSync as kf}from"fs";import{dirname as xf,join as Sf}from"path";import{fileURLToPath as _f}from"url";var Ot=process.argv[2];if(Ot==="--version"||Ot==="-v"){try{let t=xf(_f(import.meta.url)),e=Sf(t,"..","package.json"),r=JSON.parse(kf(e,"utf-8"));console.log(r.version)}catch{console.log("unknown")}process.exit(0)}(Ot==="--help"||Ot==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
|
|
7733
7439
|
|
|
7734
7440
|
Usage:
|
|
7735
7441
|
npx @mistflow-ai/mcp Start the MCP server on stdio (default; invoked by editors)
|
|
@@ -7737,8 +7443,8 @@ Usage:
|
|
|
7737
7443
|
|
|
7738
7444
|
To install the server into your editor config, use the installer:
|
|
7739
7445
|
npx -y mistflow-ai install
|
|
7740
|
-
`),process.exit(0));(
|
|
7446
|
+
`),process.exit(0));(Ot==="install"||Ot==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${Ot}' is no longer supported.
|
|
7741
7447
|
Use the installer package instead:
|
|
7742
7448
|
|
|
7743
|
-
npx -y mistflow-ai ${
|
|
7744
|
-
`),process.exit(1));await Promise.resolve().then(()=>(
|
|
7449
|
+
npx -y mistflow-ai ${Ot}
|
|
7450
|
+
`),process.exit(1));await Promise.resolve().then(()=>(td(),vf));
|