@mistflow-ai/mcp 1.0.1 → 1.0.3
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 +14 -14
- package/dist/index.js +105 -105
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -2204,9 +2204,9 @@ ${n}
|
|
|
2204
2204
|
</div>
|
|
2205
2205
|
</body>
|
|
2206
2206
|
</html>
|
|
2207
|
-
`}var Va,Ja,Ka,Js=x(()=>{"use strict";Va=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],Ja=["sharp","soft","pill","organic"],Ka=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"]});import{z as _}from"zod";import{existsSync as _t,mkdirSync as nn,readFileSync as Ys,readdirSync as el,statSync as tl,unlinkSync as nl,writeFileSync as on}from"fs";import{dirname as ol,isAbsolute as sl,join as oe}from"path";import{homedir as je}from"os";import{createHash as rl,createHmac as Qs,randomBytes as il,randomUUID as Ks,timingSafeEqual as al}from"crypto";function Xs(){let t=oe(je(),".mistflow","confirm-secret");if(_t(t))try{return Buffer.from(Ys(t,"utf-8").trim(),"hex")}catch{}let e=il(32);return nn(oe(je(),".mistflow"),{recursive:!0}),on(t,e.toString("hex"),{mode:384}),e}function Zs(t){return rl("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function cl(t,e){let o={cwd:t,d:Zs(e),exp:Date.now()+ll},n=Buffer.from(JSON.stringify(o)).toString("base64url"),s=Qs("sha256",Xs()).update(n).digest("base64url");return`${n}.${s}`}function pl(t,e,o){let n=t.split(".");if(n.length!==2)return!1;let[s,a]=n,r=Qs("sha256",Xs()).update(s).digest("base64url"),i=Buffer.from(a),l=Buffer.from(r);if(i.length!==l.length||!al(i,l))return!1;try{let p=JSON.parse(Buffer.from(s,"base64url").toString("utf-8"));return!(typeof p.exp!="number"||Date.now()>p.exp||p.cwd!==e||p.d!==Zs(o))}catch{return!1}}function dl(t){let e=t,o=je(),n=!1;for(let s=0;s<64;s++){if(_t(oe(e,"mistflow.json")))return"mistflow";if(!n&&_t(oe(e,"package.json"))&&(n=!0),e===o)break;let a=ol(e);if(a===e)break;e=a}return n?"foreign":"none"}function ul(t){let e=je(),o=t.replace(/\/+$/,"");if(o===e||o==="/"||o===""||o==="/tmp"||o==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let s of n)if(o===oe(e,s))return!0;return!1}function hl(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,s]of e)if(n.test(t))return s;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 gl(t){let e=oe(je(),".mistflow","plans",`${t}.json`);if(!_t(e))return null;try{return JSON.parse(Ys(e,"utf-8")).plan??null}catch{return null}}async function fl(t){for(let n=0;n<60;n++){try{let s=await En(t.design_conversation_id);if(s.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:s.directions,plan:s.plan,methodology:s.methodology};if(s.status==="failed")return{status:"ready",plan:s.plan,methodology:s.methodology}}catch(s){let a=s instanceof Error?s.message:String(s);if(a.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll attempt ${n+1} failed: ${a}`)}await new Promise(s=>setTimeout(s,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:t.plan,methodology:t.methodology}}async function yl(t,e){let{description:o,projectPath:n,conversationId:s,answers:a,existingPlan:r,existingPlanId:i,templateToken:l,remixDescription:p,autonomous:m,language:u,landingDesign:d,appStyle:b,brandMentioned:R,confirmToken:w,urlChoice:y,designConversationId:k,designDirection:U}=t;if(s&&!o&&!a&&!k&&!U&&!r&&!i&&!l)try{let h=await qt(s);return h.status==="clarify_pending"?c(JSON.stringify({status:"running",conversationId:s,phase:"generating_questions",nextAction:`Still generating. Call mist_plan with { projectPath, conversationId: "${s}" } again in ~10-15s.`})):c(JSON.stringify(h))}catch(h){let g=h instanceof Error?h.message:String(h);return c(`Could not poll plan conversation '${s}': ${g}`,!0)}let Y=o??"";if(!Y.trim()&&!s&&!r&&!i&&!l)return c("mist_plan requires a `description` for the first call (the user's app idea). Pass { conversationId } alone to poll an in-flight call, or along with { answers } to submit responses.",!0);let G=r;if(!G&&i&&(G=gl(i)??void 0,!G))return c("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let ie=s;if(!J())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let B;if(!ie&&!G&&!l){if(!sl(n))return c(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let h=dl(n);if(h!=="mistflow"&&ul(n))return c(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(`
|
|
2207
|
+
`}var Va,Ja,Ka,Js=x(()=>{"use strict";Va=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],Ja=["sharp","soft","pill","organic"],Ka=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"]});import{z as _}from"zod";import{existsSync as _t,mkdirSync as nn,readFileSync as Ys,readdirSync as el,statSync as tl,unlinkSync as nl,writeFileSync as on}from"fs";import{dirname as ol,isAbsolute as sl,join as oe}from"path";import{homedir as je}from"os";import{createHash as rl,createHmac as Qs,randomBytes as il,randomUUID as Ks,timingSafeEqual as al}from"crypto";function Xs(){let t=oe(je(),".mistflow","confirm-secret");if(_t(t))try{return Buffer.from(Ys(t,"utf-8").trim(),"hex")}catch{}let e=il(32);return nn(oe(je(),".mistflow"),{recursive:!0}),on(t,e.toString("hex"),{mode:384}),e}function Zs(t){return rl("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function cl(t,e){let o={cwd:t,d:Zs(e),exp:Date.now()+ll},n=Buffer.from(JSON.stringify(o)).toString("base64url"),s=Qs("sha256",Xs()).update(n).digest("base64url");return`${n}.${s}`}function pl(t,e,o){let n=t.split(".");if(n.length!==2)return!1;let[s,a]=n,r=Qs("sha256",Xs()).update(s).digest("base64url"),i=Buffer.from(a),l=Buffer.from(r);if(i.length!==l.length||!al(i,l))return!1;try{let p=JSON.parse(Buffer.from(s,"base64url").toString("utf-8"));return!(typeof p.exp!="number"||Date.now()>p.exp||p.cwd!==e||p.d!==Zs(o))}catch{return!1}}function dl(t){let e=t,o=je(),n=!1;for(let s=0;s<64;s++){if(_t(oe(e,"mistflow.json")))return"mistflow";if(!n&&_t(oe(e,"package.json"))&&(n=!0),e===o)break;let a=ol(e);if(a===e)break;e=a}return n?"foreign":"none"}function ul(t){let e=je(),o=t.replace(/\/+$/,"");if(o===e||o==="/"||o===""||o==="/tmp"||o==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let s of n)if(o===oe(e,s))return!0;return!1}function hl(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,s]of e)if(n.test(t))return s;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 gl(t){let e=oe(je(),".mistflow","plans",`${t}.json`);if(!_t(e))return null;try{return JSON.parse(Ys(e,"utf-8")).plan??null}catch{return null}}async function fl(t){for(let n=0;n<60;n++){try{let s=await En(t.design_conversation_id);if(s.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:s.directions,plan:s.plan,methodology:s.methodology};if(s.status==="failed")return{status:"ready",plan:s.plan,methodology:s.methodology}}catch(s){let a=s instanceof Error?s.message:String(s);if(a.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll attempt ${n+1} failed: ${a}`)}await new Promise(s=>setTimeout(s,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:t.plan,methodology:t.methodology}}async function yl(t,e){let{description:o,projectPath:n,conversationId:s,answers:a,existingPlan:r,existingPlanId:i,templateToken:l,remixDescription:p,autonomous:m,language:u,landingDesign:d,appStyle:b,brandMentioned:R,confirmToken:w,urlChoice:y,designConversationId:k,designDirection:U}=t;if(s&&!o&&!a&&!k&&!U&&!r&&!i&&!l)try{let h=await qt(s);return h.status==="clarify_pending"?c(JSON.stringify({status:"running",conversationId:s,phase:"generating_questions",nextAction:`Still generating. Call mist_plan with { projectPath, conversationId: "${s}" } again in ~10-15s.`})):h.status==="plan_pending"?c(JSON.stringify({status:"running",conversationId:s,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${s}" } again in ~15-20s.`})):c(JSON.stringify(h))}catch(h){let g=h instanceof Error?h.message:String(h);return c(`Could not poll plan conversation '${s}': ${g}`,!0)}let Y=o??"";if(!Y.trim()&&!s&&!r&&!i&&!l)return c("mist_plan requires a `description` for the first call (the user's app idea). Pass { conversationId } alone to poll an in-flight call, or along with { answers } to submit responses.",!0);let G=r;if(!G&&i&&(G=gl(i)??void 0,!G))return c("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let ie=s;if(!J())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let B;if(!ie&&!G&&!l){if(!sl(n))return c(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let h=dl(n);if(h!=="mistflow"&&ul(n))return c(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(`
|
|
2208
2208
|
`)}),!0);if(h==="foreign"&&!R){if(!(w?pl(w,n,Y):!1)){let P=cl(n,Y);return c(JSON.stringify({status:"confirm_new_project",projectPath:n,description:Y,confirmToken:P,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:"Creates a fresh project in this folder without touching the existing code."},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",w?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
2209
|
-
`)}))}B="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else h==="foreign"&&R&&(B="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await Wn(l)).plan)return c("This template has no plan to fork. Try a different template.",!0);let g=await Gn(l),P=g.plan,I="";if(p&&g.has_source)try{let ee=await Bt(g.plan,p),$=ee.plan??ee,Dt=ee.diff,q=$?.steps??[],yn=new Set([...(Dt?.added??[]).map(pe=>pe.number),...(Dt?.modified??[]).map(pe=>pe.number)]),_e=q.map(pe=>{let fi=pe.number;return yn.has(fi)?{...pe,status:"pending"}:{...pe,status:"completed",source:"forked"}});$.steps=_e,P=$;let Fe=_e.filter(pe=>pe.status==="pending").length;I=` Remixed: ${_e.filter(pe=>pe.status==="completed").length} steps unchanged, ${Fe} steps need re-implementation.`}catch(ee){console.error("[plan] Remix failed, using original plan:",ee),I=" (Remix failed \u2014 using original plan. You can modify it later.)"}let V=Ks(),F=oe(je(),".mistflow","plans");nn(F,{recursive:!0}),on(oe(F,`${V}.json`),JSON.stringify({plan:P,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let X=P?.name??"forked-app",Z=g.has_source,ht=Z?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Le=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return c(JSON.stringify({planId:V,forkedFrom:g.forked_from,projectId:g.id,hasSource:Z,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${I}${Le} ${ht} NEXT: Call mist_init, name='${X}', and planId='${V}' to create the project now.`}))}catch(h){let g=h instanceof Error?h.message:"Failed to fork template";return c(g,!0)}if(G){let h;try{h=await Bt(G,Y)}catch(F){let X=F instanceof Error?F.message:"Failed to modify plan";return c(X,!0)}let g=h.plan,P=h.diff,I=[];if(P?.added?.length){let F=P.added.map(X=>X.title);I.push(`Added ${F.length} step(s): ${F.join(", ")}`)}if(P?.removed?.length){let F=P.removed.map(X=>X.title);I.push(`Removed ${F.length} step(s): ${F.join(", ")}`)}if(P?.modified?.length){let F=P.modified.map(X=>X.title);I.push(`Modified ${F.length} step(s): ${F.join(", ")}`)}let V=I.length>0?I.join(". "):"No changes detected.";return c(JSON.stringify({plan:g,diff:P,message:`Plan modified. ${V}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let v=y?.trim()||void 0,L=a;if(!v&&a&&tn in a&&(v=a[tn]),a&&tn in a){let{[tn]:h,...g}=a;L=Object.keys(g).length>0?g:void 0}if(v&&(v=v.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),v){let h=v.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(h)?v=h:(console.error(`[mist_plan] Discarding urlChoice '${v}' \u2014 does not look like a subdomain. Backend will auto-generate.`),v=void 0)}let Q;if(U){Q={...U};let h={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[g,P]of Object.entries(h))U[g]!==void 0&&Q[P]===void 0&&(Q[P]=U[g])}let se=a?"Generating plan with your answers (LLM call)":k?"Finalizing design direction":"Thinking through discovery questions",
|
|
2209
|
+
`)}))}B="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else h==="foreign"&&R&&(B="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await Wn(l)).plan)return c("This template has no plan to fork. Try a different template.",!0);let g=await Gn(l),P=g.plan,I="";if(p&&g.has_source)try{let ee=await Bt(g.plan,p),$=ee.plan??ee,Dt=ee.diff,q=$?.steps??[],yn=new Set([...(Dt?.added??[]).map(pe=>pe.number),...(Dt?.modified??[]).map(pe=>pe.number)]),_e=q.map(pe=>{let fi=pe.number;return yn.has(fi)?{...pe,status:"pending"}:{...pe,status:"completed",source:"forked"}});$.steps=_e,P=$;let Fe=_e.filter(pe=>pe.status==="pending").length;I=` Remixed: ${_e.filter(pe=>pe.status==="completed").length} steps unchanged, ${Fe} steps need re-implementation.`}catch(ee){console.error("[plan] Remix failed, using original plan:",ee),I=" (Remix failed \u2014 using original plan. You can modify it later.)"}let V=Ks(),F=oe(je(),".mistflow","plans");nn(F,{recursive:!0}),on(oe(F,`${V}.json`),JSON.stringify({plan:P,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let X=P?.name??"forked-app",Z=g.has_source,ht=Z?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Le=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return c(JSON.stringify({planId:V,forkedFrom:g.forked_from,projectId:g.id,hasSource:Z,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${I}${Le} ${ht} NEXT: Call mist_init, name='${X}', and planId='${V}' to create the project now.`}))}catch(h){let g=h instanceof Error?h.message:"Failed to fork template";return c(g,!0)}if(G){let h;try{h=await Bt(G,Y)}catch(F){let X=F instanceof Error?F.message:"Failed to modify plan";return c(X,!0)}let g=h.plan,P=h.diff,I=[];if(P?.added?.length){let F=P.added.map(X=>X.title);I.push(`Added ${F.length} step(s): ${F.join(", ")}`)}if(P?.removed?.length){let F=P.removed.map(X=>X.title);I.push(`Removed ${F.length} step(s): ${F.join(", ")}`)}if(P?.modified?.length){let F=P.modified.map(X=>X.title);I.push(`Modified ${F.length} step(s): ${F.join(", ")}`)}let V=I.length>0?I.join(". "):"No changes detected.";return c(JSON.stringify({plan:g,diff:P,message:`Plan modified. ${V}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let v=y?.trim()||void 0,L=a;if(!v&&a&&tn in a&&(v=a[tn]),a&&tn in a){let{[tn]:h,...g}=a;L=Object.keys(g).length>0?g:void 0}if(v&&(v=v.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),v){let h=v.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(h)?v=h:(console.error(`[mist_plan] Discarding urlChoice '${v}' \u2014 does not look like a subdomain. Backend will auto-generate.`),v=void 0)}let Q;if(U){Q={...U};let h={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[g,P]of Object.entries(h))U[g]!==void 0&&Q[P]===void 0&&(Q[P]=U[g])}let se=a?"Generating plan with your answers (LLM call)":k?"Finalizing design direction":"Thinking through discovery questions",fe=e?en(e.server,e.progressToken,()=>se):{stop:()=>{}};e&&(e.cleanup=()=>fe.stop());let E;try{ie&&!L&&!k&&!G&&!i?E=await qt(ie):E=await Nn(Y,{conversationId:ie,answers:L,autonomous:m,language:u,designConversationId:k,designDirection:Q})}catch(h){fe.stop();let g=h instanceof Error?h.message:"Failed to generate plan";return c(g,!0)}if(E.status==="clarify_pending"){fe.stop();let h=E;return c(JSON.stringify({status:"running",conversationId:h.conversation_id,phase:"generating_questions",nextAction:`Discovery questions are generating (backend Sonnet call). Call mist_plan with { projectPath, conversationId: "${h.conversation_id}" } in ~10-15s to poll. Do NOT re-send description or answers \u2014 just the conversationId.`}))}if(E.status==="plan_pending"){fe.stop();let h=E;return c(JSON.stringify({status:"running",conversationId:h.conversation_id,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${h.conversation_id}" } in ~15-20s to poll. Do NOT re-send answers \u2014 the server already has them.`}))}if(E.status==="design_clarify_pending"&&(se="Generating creative design directions",E=await fl(E)),fe.stop(),E.status==="clarify"){let h=E.reflection||"",g=E.suggestedName||"",P=E.suggestedFeatures??[],I=E.questions??[],V=I.some(q=>Array.isArray(q.options)&&typeof q.options[0]=="object"&&q.options[0]?.label),F={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},X=I.map(q=>{let yn=q.decisionKey&&F[q.decisionKey]||hl(q.question),_e;return V&&Array.isArray(q.options)?_e=q.options.map(Fe=>({label:Fe.label,description:Fe.description??""})):Array.isArray(q.options)?_e=q.options.map((Fe,Eo)=>({label:Eo===0?`${Fe} (Recommended)`:String(Fe),description:q.why??""})):_e=[{label:"Yes (Recommended)",description:q.why??""},{label:"No",description:""}],{question:q.question,header:yn,options:_e,multiSelect:!1}}),ht=E.decisions?.audienceType??null,Le=P.length>0?zs(Y,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:ht,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:P,language:u}):null,ee=Le?Hs(Le):"",$=co(g||"my-app").slice(0,32);try{let q=await An($);!q.available&&q.suggestion&&($=q.suggestion)}catch{}ee&&(ee+=`
|
|
2210
2210
|
|
|
2211
2211
|
**Your app URL:** https://${$}.mistflow.app`);let Dt={question:`Your app will be at ${$}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${$}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};return X.push(Dt),c(JSON.stringify({status:"clarify",conversation_id:E.conversation_id,questions:I,questionCount:I.length,suggestedFeatures:P,suggestedName:g,suggestedSubdomain:$,reflection:h,briefText:ee,askUserQuestions:X,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:[...B?[B,""]:[],h?`${h}
|
|
2212
2212
|
`:"",ee?`Here's what I'd build:
|
|
@@ -2214,7 +2214,7 @@ ${n}
|
|
|
2214
2214
|
${ee}
|
|
2215
2215
|
`:"",`I have ${I.length} quick question${I.length===1?"":"s"} to pin down the details.`,"","MANDATORY: Use the AskUserQuestion tool to present these questions. Do NOT present them as text.","","IF you have access to the AskUserQuestion tool (Claude Code):"," Use it to present questions with selectable options. Pass the 'askUserQuestions' array directly.","","OTHERWISE (Cursor, Codex, or other hosts):"," Present each question conversationally with the options listed.","","BEFORE calling mist_plan for the final plan generation, tell the user:"," 'Generating your plan now. This usually takes about 60\u201390 seconds \u2014 I'm designing the data model, laying out pages, and writing build steps.'","This primes the user for the silent wait. Do NOT call mist_plan without saying this first.","","Once you have all answers, call mist_plan again with:",` conversationId: "${E.conversation_id}"`,' answers: { "<question text>": "<user answer>", ... }'," description: (same description as before)",' urlChoice: "<the URL subdomain the user picked>" \u2190 pass as a top-level param, NOT inside answers',"","NOTE: You may receive another 'clarify' response with follow-up questions if the user's answers","revealed new ambiguity. This is normal \u2014 relay those questions too. Keep going until you get 'ready'.","","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: "${$}".`,'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.'].join(`
|
|
2216
2216
|
`)}))}if(E.status==="design_clarify"){let h=E.directions??[],g=E.plan.name??"your app",P;try{let Z=h.map($=>({id:$.id,name:$.name,summary:$.summary,hero_headline:$.hero_headline,cta_text:$.cta_text,body_sample:$.body_sample,fonts:$.fonts,colors:$.colors,hero_treatment:$.hero_treatment,shape_lang:$.shape_lang,texture:$.texture,decoration_hint:$.decoration_hint})),ht=Vs(g,Z),Le=oe(n,".mistflow");nn(Le,{recursive:!0});let ee=oe(Le,"design-directions.html");on(ee,ht,"utf-8"),P=ee}catch(Z){console.error(`[mist_plan] design-directions preview render failed: ${Z instanceof Error?Z.message:String(Z)}`)}let I=h.map(Z=>({label:Z.name,description:`${Z.summary} \u2014 ${Z.fonts?.display??""} + ${Z.fonts?.body??""}`}));I.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let V={question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:I,multiSelect:!1},F=P?`A visual preview of all ${h.length} directions has been written to ${P}. Open it in the browser \u2014 each card is rendered in its direction's own fonts + palette so the user can see what they're picking.`:"No visual preview rendered (see server logs). The AskUserQuestion options below carry fonts + mood so the user can still pick.",X=P?`open "${P}"`:"";return c(JSON.stringify({status:"design_clarify",designConversationId:E.design_conversation_id,directions:h,previewPath:P,askUserQuestion:V,instruction:[`The plan for "${g}" is ready. I've proposed ${h.length} creative directions \u2014 each commits to a specific aesthetic (fonts, colors, voice).`,"",F,X?`Run this command for the user: ${X}`:"","","MANDATORY: After opening the preview, use the AskUserQuestion tool to present the directionQuestion above. Do NOT present it as text.","","Once the user picks a direction, call mist_plan again with:"," description: (same description as before)",` designConversationId: "${E.design_conversation_id}"`," designDirection: <the full direction object from the 'directions' array that the user picked>","","IF the user picks 'Describe your own direction':"," Ask them a short open question ('How should the app feel? Any fonts or colors in mind?')."," Then call mist_plan with designDirection: { custom: '<their description>' } and the same designConversationId.","","The next mist_plan call takes ~10-20s \u2014 that's the LLM generating the final DESIGN.md with the picked direction. Tell the user 'Locking in the direction now \u2014 this takes about 15 seconds.' before calling."].filter(Boolean).join(`
|
|
2217
|
-
`)}))}let N=E.plan,fe=N.name??"Untitled App",Ie=E.methodology,D=N.steps;if(!Array.isArray(D)||D.length===0)return c("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let re=N.publicPages;if(!re||Array.isArray(re)&&re.length===0){let h=N.pages,g=D.some(I=>typeof I.name=="string"&&I.name.toLowerCase().includes("landing")||typeof I.title=="string"&&I.title.toLowerCase().includes("landing")),P=Array.isArray(h)&&h.some(I=>I.path==="/"||I.route==="/");g||P?re=["/","/pricing"]:re=["/"]}let dt=N.primaryAction;if(!dt){let h=N.features;if(Array.isArray(h)&&h.length>0){let P=h.find(V=>typeof V.priority=="string"&&V.priority.toLowerCase()==="must-have")??h[0];dt={entity:P.name??P.title??"item",action:"create",fromPage:"/dashboard"}}}let Me=N.nonNegotiables;(!Me||Array.isArray(Me)&&Me.length===0)&&(Me=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let z=Ks(),Ge=oe(je(),".mistflow","plans");nn(Ge,{recursive:!0});try{let g=Date.now();for(let P of[Ge,oe(je(),".mistflow","mockup-state")])if(_t(P))for(let I of el(P))try{let V=oe(P,I),F=tl(V).mtimeMs;g-F>6048e5&&nl(V)}catch{}}catch{}let ae;if(d){let h=Gt(d);h?ae=h.id:console.error(`Landing design '${d}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let Ue=b||void 0,ce=!!ae,ut=D.some(h=>{let g=`${h.name??h.title} ${h.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),ye=!ce&&ut?ks(Y,{maxResults:2}):[];ye.length>0&&(ae=ye[0].id,console.error(`Auto-assigned landing layout preset (default): ${ye[0].title} (${ae})`));let gn={name:N.name,summary:N.summary,dataModel:N.dataModel,pages:N.pages,features:N.features,steps:D.map(h=>({...h,name:h.name??h.title})),design:N.design,landingDesign:ae,appStyle:Ue,dbProvider:N.dbProvider??"neon",authModel:N.authModel,audienceType:N.audienceType??"b2c",roles:N.roles,defaultRole:N.defaultRole,publicPages:re,navStyle:N.navStyle,multiTenant:N.multiTenant,primaryAction:dt,nonNegotiables:Me,requestedSubdomain:v,...u&&u.toLowerCase()!=="english"?{language:u}:{}};on(oe(Ge,`${z}.json`),JSON.stringify({plan:gn,methodology:Ie}));let fn=D.map(h=>`${h.number}. ${h.name??h.title}`),ke="",mt=[],$e;!ce&&ye.length>0&&(mt=ye.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${Ke()}/designs?tab=landing-designs`})),$e={question:"What landing page style fits this app?",header:"Landing Design",options:[...ye.map((g,P)=>({label:P===0?`${g.title} (Recommended)`:g.title,description:g.description})),{label:"Design from scratch (Creative)",description:"No template \u2014 the AI designs a bespoke hero from your app's concept using 3D, scroll-driven animation, or particle effects. Higher creative ceiling, takes ~10 min longer, occasionally needs a second pass."},{label:"Browse all landing designs",description:`Not sure? See all landing designs at ${Ke()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},ke=` REQUIRED: ask the user which landing design they want using the AskUserQuestion tool with the 'landingDesignQuestion' object before calling mist_init. Do NOT assume the recommended option \u2014 the user may want a different style than we inferred. Recommended: ${ye.map(g=>g.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_init. If they pick a specific preset title, look up its ID via mist_project action='landing-designs' and pass that. If they pick the recommended option, pass landingDesign='${ye[0].id}' explicitly.`);let jt="",f=[],S=void 0,H=(N.audienceType??"b2c")==="b2c",be={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:H?"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:H?"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.",T="",M=[];for(let h of D){let g=h.name??h.title,P=h.integrationId;if(P){let I=et(P);if(I){let V=tt(I.id);M.push({step:g,presetId:I.id,presetName:I.name,envVars:V?.envVars??[]})}}}if(M.length>0){let h=M.flatMap(I=>I.envVars),g=[...new Set(h.map(I=>I.key))];T=` This plan uses integrations (${M.map(I=>I.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return c(JSON.stringify({planId:z,name:N.name,summary:N.summary,stepCount:D.length,steps:fn,design:N.design,...ae?{landingDesign:ae}:{},...Ue?{appStyle:Ue}:{},...f.length>0?{recommendedAppStyles:f}:{},...S?{appStyleQuestion:S}:{},...mt.length>0?{recommendedLandingDesigns:mt}:{},...$e?{landingDesignQuestion:$e}:{},heroPhotoQuestion:be,...M.length>0?{integrations:M.map(h=>({step:h.step,preset:h.presetId,name:h.presetName,envVars:h.envVars}))}:{},message:`Plan generated for "${fe}" (${D.length} steps).${ae?` Landing layout "${ae}" set as default.`:""}${Ue?` App style "${Ue}" will be applied across all pages.`:""}${T}${jt}${ke}${we}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,D.length*3)}\u2013${D.length*5} minutes total across ${D.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: '${z}' }). If the user says skip or "just build it", call mist_init({ planId: '${z}', path: '<absolute path>' }) immediately.`,...B?{warning:B}:{}}))}var tn,ll,ml,er,tr=x(()=>{"use strict";W();le();lo();eo();Vt();Ws();Js();tn="__mistflow_url_choice__",ll=600*1e3;ml=_.object({description:_.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:_.string().min(1).describe("REQUIRED. Absolute path to the user's current working directory \u2014 where the Mistflow app will be scaffolded. Pass the directory the user is actually working in (e.g. /Users/alice/projects). Do NOT pass '/', '~', $HOME, Desktop, Documents, Downloads, or /tmp \u2014 the tool will refuse to scaffold at those locations. If you are unsure of the user's working directory, ask them before calling this tool."),conversationId:_.string().optional().describe("Returned by a previous mist_plan call with status 'clarify' or 'running'. Pass it back alone (no description) to poll an in-flight discovery call; pass with answers to submit responses."),answers:_.record(_.string()).optional().describe("User's answers to the clarifying questions from the previous round. Keys are the questions, values are the answers."),existingPlan:_.record(_.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:_.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:_.string().optional().describe("Fork from a shared template. Pass the share token (from a mistflow.ai/t/... URL) to clone that project's plan into your workspace."),remixDescription:_.string().optional().describe("Optional remix request when forking a template. Describes how you want the template to be different. E.g. 'Make it for tracking books instead of habits, add a search feature.' Only used with templateToken."),autonomous:_.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:_.string().optional().describe("ID of a curated landing page design for the hero section. When set, the design's detailed blueprint (colors, fonts, layout, animations) is injected during the landing page implementation step. Use mist_project with action='landing-designs' to browse available landing designs."),appStyle:_.string().optional().describe("ID of a full-app style (e.g. 'stripe', 'linear', 'vercel', 'notion'). When set, the style's color palette, typography, component specs, shadows, and layout rules are injected during ALL implementation steps for consistent brand-quality design across every page. Use mist_project with action='app-styles' to browse available app styles."),language:_.string().optional().describe("UI language for the app. All user-facing text, labels, buttons, and content will be generated in this language. Use the language name in English (e.g. 'Spanish', 'French', 'Arabic', 'Japanese'). Defaults to English if not specified."),brandMentioned:_.boolean().optional().describe("Set to true ONLY when the user's original request explicitly invoked Mistflow by name (e.g. 'build me a CRM using mist', 'make a todo app with mistflow'). Skips the existing-project confirmation gate because the user clearly wants Mistflow. Do NOT set this for generic 'build me X' requests. Do NOT infer this \u2014 only set it when the user literally typed 'mist' or 'mistflow'."),confirmToken:_.string().optional().describe("The token returned in a previous mist_plan response with status 'confirm_new_project'. Only pass this AFTER asking the user via AskUserQuestion and they chose to scaffold a new Mistflow app in an existing-project directory. The token is bound to the projectPath and description \u2014 you must pass the SAME description AND projectPath on the retry."),urlChoice:_.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers. The answers-dict magic key is deprecated and unreliable."),designConversationId:_.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass it back on the follow-up call together with designDirection to finalize the plan's DESIGN.md."),designDirection:_.object({id:_.string().optional(),name:_.string().optional(),summary:_.string().optional(),heroHeadline:_.string().optional(),ctaText:_.string().optional(),bodySample:_.string().optional(),fontsHint:_.string().optional(),fonts:_.object({display:_.string(),body:_.string()}).partial().optional(),colorMood:_.string().optional(),colors:_.object({bg:_.string(),fg:_.string(),accent:_.string()}).partial().optional(),heroTreatment:_.string().optional(),shapeLang:_.string().optional(),texture:_.string().optional(),decorationHint:_.string().optional(),custom:_.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass the FULL direction object the user chose (all fields from the 'directions' array). If the user wrote their own description instead of picking one, pass { custom: '<their description>' } and omit the other fields.")});er={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist').","","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). When that happens AND brandMentioned is not set, the handler returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token from the response.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_init with the returned planId. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. Pass appStyle (53 full-app design systems like 'stripe', 'linear') to apply a design system. Browse via mist_project action='app-styles'. Landing layout presets are auto-assigned based on app description."].join(`
|
|
2217
|
+
`)}))}let N=E.plan,ye=N.name??"Untitled App",Ie=E.methodology,D=N.steps;if(!Array.isArray(D)||D.length===0)return c("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let re=N.publicPages;if(!re||Array.isArray(re)&&re.length===0){let h=N.pages,g=D.some(I=>typeof I.name=="string"&&I.name.toLowerCase().includes("landing")||typeof I.title=="string"&&I.title.toLowerCase().includes("landing")),P=Array.isArray(h)&&h.some(I=>I.path==="/"||I.route==="/");g||P?re=["/","/pricing"]:re=["/"]}let dt=N.primaryAction;if(!dt){let h=N.features;if(Array.isArray(h)&&h.length>0){let P=h.find(V=>typeof V.priority=="string"&&V.priority.toLowerCase()==="must-have")??h[0];dt={entity:P.name??P.title??"item",action:"create",fromPage:"/dashboard"}}}let Me=N.nonNegotiables;(!Me||Array.isArray(Me)&&Me.length===0)&&(Me=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let z=Ks(),Ge=oe(je(),".mistflow","plans");nn(Ge,{recursive:!0});try{let g=Date.now();for(let P of[Ge,oe(je(),".mistflow","mockup-state")])if(_t(P))for(let I of el(P))try{let V=oe(P,I),F=tl(V).mtimeMs;g-F>6048e5&&nl(V)}catch{}}catch{}let ae;if(d){let h=Gt(d);h?ae=h.id:console.error(`Landing design '${d}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let Ue=b||void 0,ce=!!ae,ut=D.some(h=>{let g=`${h.name??h.title} ${h.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),be=!ce&&ut?ks(Y,{maxResults:2}):[];be.length>0&&(ae=be[0].id,console.error(`Auto-assigned landing layout preset (default): ${be[0].title} (${ae})`));let gn={name:N.name,summary:N.summary,dataModel:N.dataModel,pages:N.pages,features:N.features,steps:D.map(h=>({...h,name:h.name??h.title})),design:N.design,landingDesign:ae,appStyle:Ue,dbProvider:N.dbProvider??"neon",authModel:N.authModel,audienceType:N.audienceType??"b2c",roles:N.roles,defaultRole:N.defaultRole,publicPages:re,navStyle:N.navStyle,multiTenant:N.multiTenant,primaryAction:dt,nonNegotiables:Me,requestedSubdomain:v,...u&&u.toLowerCase()!=="english"?{language:u}:{}};on(oe(Ge,`${z}.json`),JSON.stringify({plan:gn,methodology:Ie}));let fn=D.map(h=>`${h.number}. ${h.name??h.title}`),ke="",mt=[],$e;!ce&&be.length>0&&(mt=be.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${Ke()}/designs?tab=landing-designs`})),$e={question:"What landing page style fits this app?",header:"Landing Design",options:[...be.map((g,P)=>({label:P===0?`${g.title} (Recommended)`:g.title,description:g.description})),{label:"Design from scratch (Creative)",description:"No template \u2014 the AI designs a bespoke hero from your app's concept using 3D, scroll-driven animation, or particle effects. Higher creative ceiling, takes ~10 min longer, occasionally needs a second pass."},{label:"Browse all landing designs",description:`Not sure? See all landing designs at ${Ke()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},ke=` REQUIRED: ask the user which landing design they want using the AskUserQuestion tool with the 'landingDesignQuestion' object before calling mist_init. Do NOT assume the recommended option \u2014 the user may want a different style than we inferred. Recommended: ${be.map(g=>g.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_init. If they pick a specific preset title, look up its ID via mist_project action='landing-designs' and pass that. If they pick the recommended option, pass landingDesign='${be[0].id}' explicitly.`);let jt="",f=[],S=void 0,H=(N.audienceType??"b2c")==="b2c",we={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:H?"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:H?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},ve=" 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.",T="",M=[];for(let h of D){let g=h.name??h.title,P=h.integrationId;if(P){let I=et(P);if(I){let V=tt(I.id);M.push({step:g,presetId:I.id,presetName:I.name,envVars:V?.envVars??[]})}}}if(M.length>0){let h=M.flatMap(I=>I.envVars),g=[...new Set(h.map(I=>I.key))];T=` This plan uses integrations (${M.map(I=>I.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return c(JSON.stringify({planId:z,name:N.name,summary:N.summary,stepCount:D.length,steps:fn,design:N.design,...ae?{landingDesign:ae}:{},...Ue?{appStyle:Ue}:{},...f.length>0?{recommendedAppStyles:f}:{},...S?{appStyleQuestion:S}:{},...mt.length>0?{recommendedLandingDesigns:mt}:{},...$e?{landingDesignQuestion:$e}:{},heroPhotoQuestion:we,...M.length>0?{integrations:M.map(h=>({step:h.step,preset:h.presetId,name:h.presetName,envVars:h.envVars}))}:{},message:`Plan generated for "${ye}" (${D.length} steps).${ae?` Landing layout "${ae}" set as default.`:""}${Ue?` App style "${Ue}" will be applied across all pages.`:""}${T}${jt}${ke}${ve}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,D.length*3)}\u2013${D.length*5} minutes total across ${D.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: '${z}' }). If the user says skip or "just build it", call mist_init({ planId: '${z}', path: '<absolute path>' }) immediately.`,...B?{warning:B}:{}}))}var tn,ll,ml,er,tr=x(()=>{"use strict";W();le();lo();eo();Vt();Ws();Js();tn="__mistflow_url_choice__",ll=600*1e3;ml=_.object({description:_.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:_.string().min(1).describe("REQUIRED. Absolute path to the user's current working directory \u2014 where the Mistflow app will be scaffolded. Pass the directory the user is actually working in (e.g. /Users/alice/projects). Do NOT pass '/', '~', $HOME, Desktop, Documents, Downloads, or /tmp \u2014 the tool will refuse to scaffold at those locations. If you are unsure of the user's working directory, ask them before calling this tool."),conversationId:_.string().optional().describe("Returned by a previous mist_plan call with status 'clarify' or 'running'. Pass it back alone (no description) to poll an in-flight discovery call; pass with answers to submit responses."),answers:_.record(_.string()).optional().describe("User's answers to the clarifying questions from the previous round. Keys are the questions, values are the answers."),existingPlan:_.record(_.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:_.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:_.string().optional().describe("Fork from a shared template. Pass the share token (from a mistflow.ai/t/... URL) to clone that project's plan into your workspace."),remixDescription:_.string().optional().describe("Optional remix request when forking a template. Describes how you want the template to be different. E.g. 'Make it for tracking books instead of habits, add a search feature.' Only used with templateToken."),autonomous:_.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:_.string().optional().describe("ID of a curated landing page design for the hero section. When set, the design's detailed blueprint (colors, fonts, layout, animations) is injected during the landing page implementation step. Use mist_project with action='landing-designs' to browse available landing designs."),appStyle:_.string().optional().describe("ID of a full-app style (e.g. 'stripe', 'linear', 'vercel', 'notion'). When set, the style's color palette, typography, component specs, shadows, and layout rules are injected during ALL implementation steps for consistent brand-quality design across every page. Use mist_project with action='app-styles' to browse available app styles."),language:_.string().optional().describe("UI language for the app. All user-facing text, labels, buttons, and content will be generated in this language. Use the language name in English (e.g. 'Spanish', 'French', 'Arabic', 'Japanese'). Defaults to English if not specified."),brandMentioned:_.boolean().optional().describe("Set to true ONLY when the user's original request explicitly invoked Mistflow by name (e.g. 'build me a CRM using mist', 'make a todo app with mistflow'). Skips the existing-project confirmation gate because the user clearly wants Mistflow. Do NOT set this for generic 'build me X' requests. Do NOT infer this \u2014 only set it when the user literally typed 'mist' or 'mistflow'."),confirmToken:_.string().optional().describe("The token returned in a previous mist_plan response with status 'confirm_new_project'. Only pass this AFTER asking the user via AskUserQuestion and they chose to scaffold a new Mistflow app in an existing-project directory. The token is bound to the projectPath and description \u2014 you must pass the SAME description AND projectPath on the retry."),urlChoice:_.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers. The answers-dict magic key is deprecated and unreliable."),designConversationId:_.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass it back on the follow-up call together with designDirection to finalize the plan's DESIGN.md."),designDirection:_.object({id:_.string().optional(),name:_.string().optional(),summary:_.string().optional(),heroHeadline:_.string().optional(),ctaText:_.string().optional(),bodySample:_.string().optional(),fontsHint:_.string().optional(),fonts:_.object({display:_.string(),body:_.string()}).partial().optional(),colorMood:_.string().optional(),colors:_.object({bg:_.string(),fg:_.string(),accent:_.string()}).partial().optional(),heroTreatment:_.string().optional(),shapeLang:_.string().optional(),texture:_.string().optional(),decorationHint:_.string().optional(),custom:_.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass the FULL direction object the user chose (all fields from the 'directions' array). If the user wrote their own description instead of picking one, pass { custom: '<their description>' } and omit the other fields.")});er={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist').","","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). When that happens AND brandMentioned is not set, the handler returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token from the response.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_init with the returned planId. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. Pass appStyle (53 full-app design systems like 'stripe', 'linear') to apply a design system. Browse via mist_project action='app-styles'. Landing layout presets are auto-assigned based on app description."].join(`
|
|
2218
2218
|
`),inputSchema:ml,handler:yl}});function nr(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(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join("")}function bl(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function wl(t){let e=nr(t);return e.charAt(0).toLowerCase()+e.slice(1)}function mo(){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(`
|
|
2219
2219
|
`)}function or(){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(`
|
|
2220
2220
|
`)}function ho(t){let e=or();if(t.includes(uo)){let n=t.indexOf(uo),s=sr,a=t.indexOf(s,n);if(a===-1)return t.slice(0,n)+e;let r=t.slice(a+s.length);return t.slice(0,n)+e+r.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
|
|
@@ -2400,19 +2400,19 @@ import { dirname } from "path";
|
|
|
2400
2400
|
import { fileURLToPath } from "url";
|
|
2401
2401
|
|
|
2402
2402
|
const __dirname = dirname(fileURLToPath(import.meta.url));`),M=M.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
2403
|
-
images: {`)))}!b&&T.path.includes("sidebar")&&(M=M.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),M=M.replace(/, Shield/g,"")),A(r,T.path,M)}let S={...k.dependencies},O={...k.devDependencies};if(S["drizzle-zod"]||(S["drizzle-zod"]="^0.5.1"),y&&(delete S["@libsql/client"],S["@neondatabase/serverless"]="^0.10.0",O["@electric-sql/pglite"]="^0.2.0"),m&&(S.stripe="^17.0.0"),u&&(S.resend="^4.0.0",S["@react-email/components"]="^0.0.31"),R&&(S.ai="^4.0.0",S["@ai-sdk/openai"]="^1.0.0",S.openai="^4.0.0"),A(r,"package.json",JSON.stringify({name:o,version:"0.1.0",private:!0,scripts:{dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"},dependencies:S,devDependencies:O,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1"}},null,2)),k.methodology){let T=k.methodology;y&&(T=T.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres")),T=ho(T),A(r,"AGENTS.md",T),A(r,"CLAUDE.md",T)}let
|
|
2403
|
+
images: {`)))}!b&&T.path.includes("sidebar")&&(M=M.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),M=M.replace(/, Shield/g,"")),A(r,T.path,M)}let S={...k.dependencies},O={...k.devDependencies};if(S["drizzle-zod"]||(S["drizzle-zod"]="^0.5.1"),y&&(delete S["@libsql/client"],S["@neondatabase/serverless"]="^0.10.0",O["@electric-sql/pglite"]="^0.2.0"),m&&(S.stripe="^17.0.0"),u&&(S.resend="^4.0.0",S["@react-email/components"]="^0.0.31"),R&&(S.ai="^4.0.0",S["@ai-sdk/openai"]="^1.0.0",S.openai="^4.0.0"),A(r,"package.json",JSON.stringify({name:o,version:"0.1.0",private:!0,scripts:{dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"},dependencies:S,devDependencies:O,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1"}},null,2)),k.methodology){let T=k.methodology;y&&(T=T.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres")),T=ho(T),A(r,"AGENTS.md",T),A(r,"CLAUDE.md",T)}let ve=i?.designMd;ve&&A(r,"DESIGN.md",ve),y&&(A(r,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);"," } else {"," // Local dev \u2014 PGlite (zero-install embedded Postgres). Lives in"," // lib/db-local.ts and is loaded through a runtime-only require"," // whose path is built from a variable, so esbuild's static"," // analysis can't follow it. Keeps pglite + its 30MB WASM out of"," // the Worker bundle.",' const localPath: string = "./" + "db-local";'," // eslint-disable-next-line @typescript-eslint/no-require-imports"," const { createLocalDb } = require(localPath);"," _db = createLocalDb();"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
|
|
2404
2404
|
`)),A(r,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its","// transitive 30MB WASM binary. Loaded via runtime-only require() from","// db.ts, where the path is built from a variable to defeat static analysis.","",'const pglitePkg: string = ["@electric-sql", "pglite"].join("/");',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { PGlite } = require(pglitePkg);","",'const drizzlePath: string = "drizzle-orm/" + "pglite";',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { drizzle } = require(drizzlePath);","","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
|
|
2405
2405
|
`)),A(r,"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(`
|
|
2406
2406
|
`)),A(r,"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(`
|
|
2407
2407
|
`)),A(r,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"","async function sendEmail({ to, subject, html, fallbackUrl }: { to: string; subject: string; html: string; fallbackUrl?: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {"," if (fallbackUrl) {"," console.error(`\\n[auth] No RESEND_API_KEY set. Email to ${to} was not sent.`);"," console.error(`[auth] Dev fallback \u2014 use this link directly:\\n ${fallbackUrl}\\n`);"," } else {"," console.error(`[auth] RESEND_API_KEY not set \u2014 skipping email send to ${to}`);"," }"," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' const body = await res.text().catch(() => "unknown");'," console.error(`[auth] Email send failed (${res.status}): ${body}`);"," throw new Error(`Email send failed: ${res.status}`);"," }","}","","function createAuth() {",' const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',' const isLocal = baseURL.includes("localhost") || baseURL.includes("127.0.0.1");'," const canSendEmail = Boolean(process.env.RESEND_API_KEY);"," // Refuse to boot a production app with email auth but no mail sender. Mistflow's"," // deploy pipeline injects a managed Resend key automatically; if it's missing,"," // that's a real misconfig and silent fallbacks let unverified users sign up."," if (!isLocal && !canSendEmail) {",` throw new Error("[auth] RESEND_API_KEY is required in production. The Mistflow deploy pipeline injects one automatically \u2014 if you're seeing this, check the project's env vars in the dashboard, or set your own RESEND_API_KEY.");`," }"," return betterAuth({"," baseURL,"," trustedOrigins: [baseURL],",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,"," requireEmailVerification: !isLocal && canSendEmail,"," sendResetPassword: async ({ user, token }: { user: { email: string; name: string }; url: string; token: string }) => {"," // Better Auth's default reset URL points at /reset-password/:token (path),"," // which our frontend doesn't route. We build our own pointing at our"," // /reset-password?token=xxx page which reads the token from the query."," const resetUrl = `${baseURL}/reset-password?token=${token}`;"," await sendEmail({"," to: user.email,",' subject: "Reset your password",',' html: `<p>Hi ${user.name},</p><p>Click the link below to reset your password:</p><p><a href="${resetUrl}">${resetUrl}</a></p>`,'," fallbackUrl: isLocal ? resetUrl : undefined,"," });"," },"," },"," emailVerification: {"," sendOnSignUp: canSendEmail,"," autoSignInAfterVerification: true,"," sendVerificationEmail: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Verify your email address",',' html: `<p>Hi ${user.name},</p><p>Click the link below to verify your email:</p><p><a href="${url}">${url}</a></p>`,'," fallbackUrl: isLocal ? url : undefined,"," });"," },"," },"," secret: process.env.AUTH_SECRET,",' plugins: [admin({ defaultRole: "user" }), nextCookies()],'," databaseHooks: {"," user: {"," create: {"," // Auto-promote the app owner to admin on first signup. ADMIN_EMAIL"," // is injected by the Mistflow deploy pipeline (the email of the"," // account that ran mist_deploy). Email verification still gates"," // login when Resend is configured, so a collision attempt can't"," // actually sign in without clicking a link delivered to the"," // owner's inbox."," before: async (user: { email?: string; [k: string]: unknown }) => {"," const adminEmail = process.env.ADMIN_EMAIL;"," if (adminEmail && user.email?.toLowerCase() === adminEmail.toLowerCase()) {",' return { data: { ...user, role: "admin" } };'," }"," return { data: user };"," },"," },"," },"," },"," socialProviders: {"," ...(process.env.GOOGLE_CLIENT_ID ? {"," google: {"," clientId: process.env.GOOGLE_CLIENT_ID,"," clientSecret: process.env.GOOGLE_CLIENT_SECRET!,"," },"," } : {}),"," ...(process.env.GITHUB_CLIENT_ID ? {"," github: {"," clientId: process.env.GITHUB_CLIENT_ID,"," clientSecret: process.env.GITHUB_CLIENT_SECRET!,"," },"," } : {}),"," },"," });","}","","// Lazy init \u2014 process.env isn't populated at module scope on Cloudflare Workers.","// The `has` trap is required: better-auth's toNextJsHandler does",'// `"handler" in auth ? auth.handler(request) : auth(request)` \u2014 without a `has`',"// trap the default forwards to the empty target object, returns false, and the","// handler tries to call the Proxy as a function, which throws TypeError and","// returns 500 on every /api/auth/* request.","let _auth: ReturnType<typeof createAuth> | null = null;","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_target, prop, receiver) {"," if (!_auth) _auth = createAuth();"," const value = Reflect.get(_auth, prop, receiver);",' if (typeof value === "function") return value.bind(_auth);'," return value;"," },"," has(_target, prop) {"," if (!_auth) _auth = createAuth();"," return prop in _auth;"," },","});",""].join(`
|
|
2408
|
-
`)))}else A(r,"package.json",JSON.stringify({name:o,version:"0.1.0",private:!0},null,2));let U=i?.designMd;A(r,"app/globals.css",jl(l,p,U)),A(r,"app/layout.tsx",Ml(o,l,w?.language)),A(r,"README.md",Vl(o,i,{hasStripe:m,hasResend:u,hasStorage:d,hasAdmin:b,hasAI:R,isNeon:y})),A(r,"contracts/README.md",mo());let Y=i?.dataModel??[],G=new Set,ie=0;for(let f of Y){let S=f.entity??f.name;if(!S||typeof S!="string")continue;let O=fo(S);G.has(O)||(G.add(O),A(r,O,go(S)),ie++)}ie===0&&A(r,"contracts/.gitkeep","");let B=[],v=i?.publicPages;if(Array.isArray(v))B=v;else if(typeof v=="string"){try{B=JSON.parse(v)}catch{B=[]}Array.isArray(B)||(B=[])}if(!B.includes("/")){let f=i?.steps?.some(O=>{let H=((O.name??"")+" "+(O.description??"")).toLowerCase();return H.includes("landing")||H.includes("marketing")||H.includes("homepage")}),S=i?.pages?.some(O=>O.path==="/");(f||S)&&(B=["/",...B])}let L={name:o,summary:i?.summary,authModel:i?.authModel,roles:i?.roles,defaultRole:i?.defaultRole,publicPages:B,navStyle:i?.navStyle,multiTenant:i?.multiTenant,pages:i?.pages,dataModel:i?.dataModel,design:i?.design},Q=$l(L);Q&&A(r,"middleware.ts",Q);let se=Ll(L);se&&A(r,se.path,se.content);let
|
|
2408
|
+
`)))}else A(r,"package.json",JSON.stringify({name:o,version:"0.1.0",private:!0},null,2));let U=i?.designMd;A(r,"app/globals.css",jl(l,p,U)),A(r,"app/layout.tsx",Ml(o,l,w?.language)),A(r,"README.md",Vl(o,i,{hasStripe:m,hasResend:u,hasStorage:d,hasAdmin:b,hasAI:R,isNeon:y})),A(r,"contracts/README.md",mo());let Y=i?.dataModel??[],G=new Set,ie=0;for(let f of Y){let S=f.entity??f.name;if(!S||typeof S!="string")continue;let O=fo(S);G.has(O)||(G.add(O),A(r,O,go(S)),ie++)}ie===0&&A(r,"contracts/.gitkeep","");let B=[],v=i?.publicPages;if(Array.isArray(v))B=v;else if(typeof v=="string"){try{B=JSON.parse(v)}catch{B=[]}Array.isArray(B)||(B=[])}if(!B.includes("/")){let f=i?.steps?.some(O=>{let H=((O.name??"")+" "+(O.description??"")).toLowerCase();return H.includes("landing")||H.includes("marketing")||H.includes("homepage")}),S=i?.pages?.some(O=>O.path==="/");(f||S)&&(B=["/",...B])}let L={name:o,summary:i?.summary,authModel:i?.authModel,roles:i?.roles,defaultRole:i?.defaultRole,publicPages:B,navStyle:i?.navStyle,multiTenant:i?.multiTenant,pages:i?.pages,dataModel:i?.dataModel,design:i?.design},Q=$l(L);Q&&A(r,"middleware.ts",Q);let se=Ll(L);se&&A(r,se.path,se.content);let fe=Fl(L);if(fe&&A(r,"lib/roles.ts",fe),A(r,"app/page.tsx",ql(L)),A(r,"app/(dashboard)/layout.tsx",Bl(L,b)),A(r,"app/(dashboard)/dashboard/page.tsx",zl(L)),L.multiTenant){let f=Hl(L,y);f&&A(r,"db/schema/organization.ts",f);let S=Wl(L);S&&A(r,"lib/org.ts",S);let O=Gl(L);O&&A(r,"components/org-switcher.tsx",O)}A(r,"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)),m&&A(r,"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(`
|
|
2409
2409
|
`)),u&&(A(r,"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(`
|
|
2410
2410
|
`)),A(r,"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(`
|
|
2411
2411
|
`))),d&&(A(r,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? "https://api.mistflow.ai";',"const MISTFLOW_API_KEY = process.env.MISTFLOW_API_KEY;","const PROJECT_ID = process.env.MISTFLOW_PROJECT_ID;","","interface UploadResult {"," upload_url: string;"," download_url: string;"," key: string;","}","","function authHeaders(): Record<string, string> {"," return {",' "Content-Type": "application/json",',' "Authorization": `ApiKey ${MISTFLOW_API_KEY}`,'," };","}","",'export async function getUploadUrl(filename: string, contentType: string = "application/octet-stream"): Promise<UploadResult> {'," const res = await fetch(`${MISTFLOW_API}/api/storage/upload-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename, content_type: contentType }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," return res.json();","}","","export async function getDownloadUrl(filename: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/download-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.download_url;","}","","export async function deleteFile(filename: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/delete`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });","}","","export async function uploadFile(file: File): Promise<string> {"," const { upload_url, download_url } = await getUploadUrl(file.name, file.type);",' await fetch(upload_url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });'," return download_url;","}",""].join(`
|
|
2412
2412
|
`)),A(r,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadUrl } from "@/lib/storage";',"","export async function POST(req: NextRequest) {"," const { filename, contentType } = await req.json();"," if (!filename) {",' return NextResponse.json({ error: "filename is required" }, { status: 400 });'," }"," try {",' const result = await getUploadUrl(filename, contentType ?? "application/octet-stream");'," return NextResponse.json(result);"," } catch {",' return NextResponse.json({ error: "Failed to get upload URL" }, { status: 500 });'," }","}",""].join(`
|
|
2413
2413
|
`))),R&&(A(r,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
|
|
2414
2414
|
`)),A(r,"app/api/chat/route.ts",['import { openai } from "@/lib/ai";','import { streamText } from "ai";',"","export async function POST(req: Request) {"," const { messages } = await req.json();",""," const result = streamText({",' model: openai("gpt-4o"),'," messages,"," });",""," return result.toDataStreamResponse();","}",""].join(`
|
|
2415
|
-
`)));let E={name:o,methodologyVersion:k?.version??"1.0",createdAt:new Date().toISOString(),...a?{planId:a}:{},plan:Array.isArray(i?.steps)?{...i,steps:i.steps.map(f=>({number:f.number,name:f.name??f.title,description:f.description,entities:f.entities,pages:f.pages,features:f.features,status:"pending"}))}:i,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...m?{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"}}:{},...u?{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"}}:{},...d?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...R?{required:{OPENAI_API_KEY:{description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"}}}:{}},authModel:i?.authModel??"email",roles:i?.roles??null,navStyle:i?.navStyle??"sidebar",multiTenant:i?.multiTenant??!1,hasAdmin:b,hasResend:u,hasStorage:d,hasAI:R,deploy:null};A(r,"mistflow.json",JSON.stringify(E,null,2));let N=Sl(32).toString("hex"),
|
|
2415
|
+
`)));let E={name:o,methodologyVersion:k?.version??"1.0",createdAt:new Date().toISOString(),...a?{planId:a}:{},plan:Array.isArray(i?.steps)?{...i,steps:i.steps.map(f=>({number:f.number,name:f.name??f.title,description:f.description,entities:f.entities,pages:f.pages,features:f.features,status:"pending"}))}:i,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...m?{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"}}:{},...u?{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"}}:{},...d?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...R?{required:{OPENAI_API_KEY:{description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"}}}:{}},authModel:i?.authModel??"email",roles:i?.roles??null,navStyle:i?.navStyle??"sidebar",multiTenant:i?.multiTenant??!1,hasAdmin:b,hasResend:u,hasStorage:d,hasAI:R,deploy:null};A(r,"mistflow.json",JSON.stringify(E,null,2));let N=Sl(32).toString("hex"),ye=m?`
|
|
2416
2416
|
# Stripe
|
|
2417
2417
|
STRIPE_SECRET_KEY=
|
|
2418
2418
|
STRIPE_WEBHOOK_SECRET=
|
|
@@ -2434,10 +2434,10 @@ OPENAI_API_KEY=
|
|
|
2434
2434
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2435
2435
|
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;A(r,".env.local",`${dt}
|
|
2436
2436
|
AUTH_SECRET=${N}
|
|
2437
|
-
${
|
|
2437
|
+
${ye}${Ie}${D}${re}`),A(r,".env.example",`${Me}
|
|
2438
2438
|
AUTH_SECRET=your-secret-here
|
|
2439
|
-
${
|
|
2440
|
-
${we}=${T}`}wo(H,be)}try{let{getBaseUrl:H,getAuthHeaders:be}=await Promise.resolve().then(()=>(le(),os)),we=be(),T=i?.features,M=i?.steps,h={};Array.isArray(T)&&T.length>0&&(h.features=T.map(g=>g.name)),i&&(h.plan=i),Array.isArray(M)&&M.length>0&&(h.provenance=M.map(g=>({feature:g.name??g.title??`Step ${g.number??"?"}`,user_intent:(g.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(h).length>0&&await fetch(`${H()}/api/projects/${encodeURIComponent(ce)}/state`,{method:"PUT",headers:{...we,"Content-Type":"application/json"},body:JSON.stringify(h)})}catch{}z[z.length-1].message=`Registered as ${ce.slice(0,8)}`}catch(f){let S=f instanceof Error?f.message:String(f);console.error("Could not register project on backend:",S),ut=`Project created locally but NOT registered on Mistflow servers (${S}). Deploy will auto-register it.`,z[z.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}ae("register",Date.now()-ye),Ge("git","Initializing git repository...");let gn=Date.now();try{let f=Il(r);await f.init(),await f.add("."),await f.commit("Initial Mistflow project setup"),z[z.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),z[z.length-1].message="Git init skipped"}ae("git",Date.now()-gn);let fn=z.reduce((f,S)=>f+(S.durationMs??0),0),ke={projectPath:r,projectId:ce,status:"awaiting_install"},mt=z.map(f=>{let S=f.durationMs?` (${(f.durationMs/1e3).toFixed(1)}s)`:"";return`${f.message}${S}`});ke.progress=mt,ke.totalSetupTime=`${(fn/1e3).toFixed(1)}s`;let $e=[];ce||$e.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),ut&&(ke.registrationWarning=ut),$e.length>0&&(ke.warnings=$e);let jt=`NEXT: Call mist_install({ projectPath: "${r}" }). 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: "${r}" }) to build the first plan step.`;return ke.nextAction=ce?jt:`${jt} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,c(JSON.stringify(ke))}var Tl,Al,Cl,rr,Ol,Ul,cr,pr=x(()=>{"use strict";W();lo();le();Be();yo();yo();Tl=Tt.object({name:Tt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:Tt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Tt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Tt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});Al={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Cl=[["--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"]];rr={"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"};Ol=new Set(["ar","he","fa","ur"]);Ul={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"};cr={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:Tl,handler:Jl}});var ur,dr=x(()=>{ur="\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 hr,mr=x(()=>{hr=`# Landing Page Rules
|
|
2439
|
+
${ye}${Ie}${D}${re}`);let z=[],Ge=(f,S)=>{z.push({phase:f,message:S})},ae=(f,S)=>{let O=z.find(H=>H.phase===f&&!H.durationMs);O&&(O.durationMs=S)};if(e){let f=en(e.server,e.progressToken,()=>z[z.length-1]?.message??"Setting up project...");e.cleanup=()=>f.stop()}let Ue=w?.requestedSubdomain||void 0,ce,ut;Ge("register","Registering project on Mistflow...");let be=Date.now();try{let f=await vt(o,void 0,"neon",Ue);ce=f.id;let S=he(r,"mistflow.json"),O=JSON.parse(rn(S,"utf-8"));if(O.projectId=ce,wo(S,JSON.stringify(O,null,2)),kt(r,St(ce,o)),f.managed_env&&Object.keys(f.managed_env).length>0){let H=he(r,".env.local"),we=He(H)?rn(H,"utf-8"):"";for(let[ve,T]of Object.entries(f.managed_env)){let M=new RegExp(`^${ve}=.*$`,"m");M.test(we)?we=we.replace(M,`${ve}=${T}`):we+=`
|
|
2440
|
+
${ve}=${T}`}wo(H,we)}try{let{getBaseUrl:H,getAuthHeaders:we}=await Promise.resolve().then(()=>(le(),os)),ve=we(),T=i?.features,M=i?.steps,h={};Array.isArray(T)&&T.length>0&&(h.features=T.map(g=>g.name)),i&&(h.plan=i),Array.isArray(M)&&M.length>0&&(h.provenance=M.map(g=>({feature:g.name??g.title??`Step ${g.number??"?"}`,user_intent:(g.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(h).length>0&&await fetch(`${H()}/api/projects/${encodeURIComponent(ce)}/state`,{method:"PUT",headers:{...ve,"Content-Type":"application/json"},body:JSON.stringify(h)})}catch{}z[z.length-1].message=`Registered as ${ce.slice(0,8)}`}catch(f){let S=f instanceof Error?f.message:String(f);console.error("Could not register project on backend:",S),ut=`Project created locally but NOT registered on Mistflow servers (${S}). Deploy will auto-register it.`,z[z.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}ae("register",Date.now()-be),Ge("git","Initializing git repository...");let gn=Date.now();try{let f=Il(r);await f.init(),await f.add("."),await f.commit("Initial Mistflow project setup"),z[z.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),z[z.length-1].message="Git init skipped"}ae("git",Date.now()-gn);let fn=z.reduce((f,S)=>f+(S.durationMs??0),0),ke={projectPath:r,projectId:ce,status:"awaiting_install"},mt=z.map(f=>{let S=f.durationMs?` (${(f.durationMs/1e3).toFixed(1)}s)`:"";return`${f.message}${S}`});ke.progress=mt,ke.totalSetupTime=`${(fn/1e3).toFixed(1)}s`;let $e=[];ce||$e.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),ut&&(ke.registrationWarning=ut),$e.length>0&&(ke.warnings=$e);let jt=`NEXT: Call mist_install({ projectPath: "${r}" }). 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: "${r}" }) to build the first plan step.`;return ke.nextAction=ce?jt:`${jt} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,c(JSON.stringify(ke))}var Tl,Al,Cl,rr,Ol,Ul,cr,pr=x(()=>{"use strict";W();lo();le();Be();yo();yo();Tl=Tt.object({name:Tt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:Tt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Tt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Tt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});Al={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Cl=[["--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"]];rr={"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"};Ol=new Set(["ar","he","fa","ur"]);Ul={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"};cr={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:Tl,handler:Jl}});var ur,dr=x(()=>{ur="\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 hr,mr=x(()=>{hr=`# Landing Page Rules
|
|
2441
2441
|
|
|
2442
2442
|
These rules apply to every landing page. They are non-negotiable.
|
|
2443
2443
|
|
|
@@ -3302,9 +3302,9 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
3302
3302
|
`)}async function bc(t){try{let e=await zn("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
|
|
3303
3303
|
- Follow existing patterns in the codebase
|
|
3304
3304
|
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function wc(t,e,o,n,s,a){let r=[];r.push(`## Step ${t.number}: ${t.name}`),r.push(""),r.push("### What to build:"),r.push(t.description),r.push(""),e.primaryAction&&(r.push("### Primary user action (non-negotiable):"),r.push(`- **Core action**: ${e.primaryAction.action}`),r.push(`- **User flow**: ${e.primaryAction.flow}`),r.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),r.push(""),r.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),r.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(s);if(e.design&&l?(r.push(yc(e.design,{hasDesignPreset:!!e.landingDesign&&(s==="landing"||s==="design")})),r.push("")):e.design&&!l&&(r.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&r.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),r.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),r.push("")),a){let w=Fs(a);if(w.length>0){r.push("### Approved wireframe (MUST READ before writing any files):"),r.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let y of w){let k=y.replace(a,"").replace(/^\//,"");r.push(`- \`${k}\``)}r.push(""),r.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),r.push(""),r.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),r.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),r.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),r.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),r.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),r.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),r.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(r.push("### Role system (from plan):"),r.push(`- Roles: ${e.roles.join(", ")}`),r.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),r.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),r.push("")),e.multiTenant&&(r.push("### Multi-tenant (from plan):"),r.push("- Organization tables are in `db/schema/organization.ts`"),r.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),r.push("- All data queries MUST be scoped to the current org (filter by orgId)"),r.push("- Org switcher component is at `components/org-switcher.tsx`"),r.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),r.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),r.push("")),e.language&&(r.push(`### Language: ${e.language}`),r.push(`ALL user-facing text must be written in ${e.language}:`),r.push("- Page titles, headings, labels, button text, placeholder text"),r.push("- Navigation items, menu labels, footer text"),r.push("- Error messages, success messages, empty states"),r.push("- Landing page copy, marketing text, CTAs"),r.push("- Form labels and validation messages"),r.push("Code (variable names, comments, file names) stays in English."),r.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),r.push(""));let p=["landing","design","auth","general","crud","dashboard"];e.audienceType&&p.includes(s)&&(e.audienceType==="b2c"?(r.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),r.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),r.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),r.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),r.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),r.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),r.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),r.push("")):e.audienceType==="b2b"?(r.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),r.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),r.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),r.push("- Testimonials: from business owners who use the platform"),r.push("- Features: business benefits ('Track dietary preferences across all orders')"),r.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),r.push("")):e.audienceType==="internal"&&(r.push("### Audience: internal staff tool. No marketing copy needed."),r.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),r.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),r.push(""))),o.length>0&&(r.push("### Already completed:"),o.forEach(w=>r.push(`- ${w}`)),r.push(""));let m=e.dataModel?Er(t,e.dataModel):[];m.length>0&&(r.push("### Data model (from plan):"),m.forEach(w=>{let y=an(w),k=dc(w.fields);r.push(`- **${y}**: ${k}`),r.push(` Schema file: \`db/schema/${y.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),r.push(""));let u=e.pages?mc(t,e.pages):[];if(u.length>0&&(r.push("### Pages to create/update:"),u.forEach(w=>{let y=w.description?` \u2014 ${w.description}`:"";r.push(`- \`${Cr(w)}\`${y}`)}),r.push("")),s==="crud"&&m.length>0&&m.forEach(w=>{let y=an(w),k=y.toLowerCase().replace(/\s+/g,"-"),U=k.endsWith("s")?k:`${k}s`;r.push(`### Files for ${y} CRUD:`),r.push(`- List page: \`app/(dashboard)/${U}/page.tsx\` (Server Component)`),r.push(`- Detail page: \`app/(dashboard)/${U}/[id]/page.tsx\``),r.push(`- Create page: \`app/(dashboard)/${U}/new/page.tsx\``),r.push(`- Server Actions: \`app/(dashboard)/${U}/actions.ts\``),r.push(`- DataTable columns: \`components/${k}-table-columns.tsx\``),r.push(`- Form: \`components/${k}-form.tsx\``),r.push("")}),l){r.push("## Design Doctrine (the standard for every UI step)"),r.push(""),r.push(fr),r.push(""),r.push("## Design Reference Library"),r.push(""),r.push("### Typography"),r.push(br),r.push(""),r.push("### Color"),r.push(vr),r.push(""),r.push("### Motion"),r.push(kr),r.push(""),r.push("### Spatial Composition"),r.push(Pr),r.push(""),r.push("### Interaction"),r.push(_r),r.push(""),r.push("### UX Writing"),r.push(Rr),r.push("");let w=a?rt(a,"DESIGN.md"):void 0,y=w&&Ct(w)?(()=>{try{return So(w,"utf-8")}catch{return null}})():null;y&&(r.push("### Design system (source of truth: DESIGN.md):"),r.push(""),r.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),r.push(""),r.push(y),r.push(""))}(s==="landing"||s==="design")&&(r.push(hr),r.push(""));let d=t.integrationId?et(t.integrationId):void 0;if(d){let w=tt(d.id);if(r.push("### Integration blueprint (follow this closely):"),r.push(""),r.push(`Using integration: **${d.name}** (${d.category})`),w?.docsUrl&&r.push(`Official docs: ${w.docsUrl}`),w?.envVars?.length){r.push(""),r.push("**Required environment variables:**");for(let y of w.envVars)r.push(`- \`${y.key}\`: ${y.description} \u2014 Get it at ${y.setupUrl}`);r.push(""),r.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}w?.packages?.length&&(r.push(""),r.push(`**Packages to install:** \`npm install ${w.packages.join(" ")}\``)),r.push(""),r.push("---"),r.push(d.prompt),r.push("---"),r.push(""),r.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),r.push("")}let{reminders:b,skill:R}=await bc(s);return r.push(b),r.push(""),R&&!(s==="landing"&&e.landingDesign==="freeform")&&(r.push(`### ${s} reference:`),r.push(R),r.push("")),l&&(r.push("## Self-Audit \u2014 run before submitting this file"),r.push(""),r.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),r.push(""),r.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),r.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),r.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),r.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),r.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),r.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),r.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),r.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),r.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),r.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),r.push(""),r.push(`If every answer is "no, I'm good" \u2014 then submit.`),r.push("")),r.join(`
|
|
3305
|
-
`)}async function vc(t){let{projectPath:e,step:o}=t,n=rc(e??process.cwd()),s=pc(n);if(!s)return Pe(n);if(!Ct(rt(n,"node_modules")))return c(`Dependencies are not installed at ${n}. Call mist_install and projectPath='${n}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:v,ensureShadcnComponents:L}=await Promise.resolve().then(()=>(Qn(),Yn));await v(n);let Q=await L(n);Q.failed?console.error(`[implement] ${Q.failed}`):Q.installed.length>0&&console.error(`[implement] installed ${Q.installed.length} shadcn components`)}catch(v){console.error("[implement] self-heal skipped:",v instanceof Error?v.message:String(v))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return c("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let r,i=a.steps.find(v=>v.status==="in_progress");if(i){let v=a.steps.findIndex(L=>L.number===i.number);v!==-1&&(a.steps[v].status="completed",r=`Auto-completed step ${i.number} (${i.name})`,Ar(n,s))}let l;if(o!==void 0){if(l=a.steps.find(v=>v.number===o),!l)return c(`Step ${o} not found. The plan has ${a.steps.length} steps (numbered ${a.steps[0].number} to ${a.steps[a.steps.length-1].number}).`,!0)}else if(l=a.steps.find(v=>v.status!=="completed"),!l)return c(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(v=>v.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let p=a.steps.filter(v=>v.status==="completed").map(v=>`Step ${v.number}: ${v.name}`),{readLocalState:m}=await Promise.resolve().then(()=>(Be(),Pt)),u=m(n),d=gc(l),b=[];if((d==="crud"||d==="schema")&&a.dataModel&&l.entities&&l.entities.length>0){let v=Er(l,a.dataModel);for(let L of v){let Q=an(L);try{let se=(L.fields||[]).map(D=>typeof D=="string"?{name:D,type:"text"}:{name:D.name,type:uc(D.type),required:D.required!==!1});if(se.length===0)continue;let
|
|
3305
|
+
`)}async function vc(t){let{projectPath:e,step:o}=t,n=rc(e??process.cwd()),s=pc(n);if(!s)return Pe(n);if(!Ct(rt(n,"node_modules")))return c(`Dependencies are not installed at ${n}. Call mist_install and projectPath='${n}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:v,ensureShadcnComponents:L}=await Promise.resolve().then(()=>(Qn(),Yn));await v(n);let Q=await L(n);Q.failed?console.error(`[implement] ${Q.failed}`):Q.installed.length>0&&console.error(`[implement] installed ${Q.installed.length} shadcn components`)}catch(v){console.error("[implement] self-heal skipped:",v instanceof Error?v.message:String(v))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return c("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let r,i=a.steps.find(v=>v.status==="in_progress");if(i){let v=a.steps.findIndex(L=>L.number===i.number);v!==-1&&(a.steps[v].status="completed",r=`Auto-completed step ${i.number} (${i.name})`,Ar(n,s))}let l;if(o!==void 0){if(l=a.steps.find(v=>v.number===o),!l)return c(`Step ${o} not found. The plan has ${a.steps.length} steps (numbered ${a.steps[0].number} to ${a.steps[a.steps.length-1].number}).`,!0)}else if(l=a.steps.find(v=>v.status!=="completed"),!l)return c(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(v=>v.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let p=a.steps.filter(v=>v.status==="completed").map(v=>`Step ${v.number}: ${v.name}`),{readLocalState:m}=await Promise.resolve().then(()=>(Be(),Pt)),u=m(n),d=gc(l),b=[];if((d==="crud"||d==="schema")&&a.dataModel&&l.entities&&l.entities.length>0){let v=Er(l,a.dataModel);for(let L of v){let Q=an(L);try{let se=(L.fields||[]).map(D=>typeof D=="string"?{name:D,type:"text"}:{name:D.name,type:uc(D.type),required:D.required!==!1});if(se.length===0)continue;let fe=s.dbProvider==="neon"?"nextjs-neon":"nextjs",E=await Hn(fe,Q,se),N=0,ye=0;for(let D of E.files){let re=rt(n,D.path);if(Ct(re)){ye++;continue}sc(ic(re),{recursive:!0}),ko(re,D.content),N++}let Ie=rt(n,"db","index.ts");if(Ct(Ie)){let D=So(Ie,"utf-8");D.includes(E.dbExport)||ko(Ie,D.trimEnd()+`
|
|
3306
3306
|
`+E.dbExport+`
|
|
3307
|
-
`)}N>0?b.push(`${E.entityPascal} CRUD (${N} new files${
|
|
3307
|
+
`)}N>0?b.push(`${E.entityPascal} CRUD (${N} new files${ye>0?`, ${ye} existing skipped`:""})`):ye>0&&b.push(`${E.entityPascal} CRUD (all ${ye} files already exist \u2014 skipped)`)}catch(se){console.error(`Module generation failed for ${Q} (non-fatal):`,se instanceof Error?se.message:se)}}}let R=await wc(l,a,p,null,d,n),w=a.steps.findIndex(v=>v.number===l.number);if(w!==-1&&(s.plan.steps[w].status="in_progress",Ar(n,s)),u&&s.projectId){let{syncRemoteState:v}=await Promise.resolve().then(()=>(Be(),Pt));v(s.projectId,u).catch(()=>{})}let y=a.steps.every(v=>v.status==="completed"||v.number===l.number),k;y?k=`THIS IS THE LAST STEP. Rules for speed:
|
|
3308
3308
|
|
|
3309
3309
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
3310
3310
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -3320,8 +3320,8 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
3320
3320
|
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.
|
|
3321
3321
|
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).
|
|
3322
3322
|
5. After writing ALL files, call mist_implement to move to the next step. Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let U=fc(d),Y={stepNumber:l.number,totalSteps:a.steps.length,estimatedMinutes:U,announcement:`Starting step ${l.number} of ${a.steps.length}: ${l.name}. This step usually takes ${U.min}\u2013${U.max} minutes.`},ie=JSON.stringify({instruction:R,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:Y,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.",...r?{autoCompleted:r}:{},...b.length>0?{generatedModules:b,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:`${p.length}/${a.steps.length} steps done`,nextAction:k});return await lc(3e3)?Jo("http://localhost:3000",ie):c(ie)}var cc,hc,Nr,jr=x(()=>{"use strict";W();le();Vt();ro();dr();mr();gr();yr();wr();xr();Sr();Ir();Tr();cc=xo.object({projectPath:xo.string().optional().describe("Path to the project directory (default: cwd)"),step:xo.number().optional().describe("Specific step number to implement (default: next incomplete step)")});hc=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);Nr={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:cc,handler:vc}});import{z as De}from"zod";import{resolve as xc}from"path";async function Dr(t){let{projectPath:e,action:o,key:n,value:s,category:a,description:r,setupUrl:i}=t,l=xc(e??process.cwd());if(!J())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let m=Ae(l)?.projectId;if(!m)return c("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(o){case"set":return n?s?(await Mn(m,n,s,{category:a,description:r,setupUrl:i}),c(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):c("Value is required. Provide the env var value.",!0):c("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let u=await On(m);return u.length===0?c(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):c(JSON.stringify({envVars:u.map(d=>({key:d.key,category:d.category,description:d.description,hasValue:d.has_value})),message:`${u.length} environment variable(s) configured.`}))}case"delete":return n?(await Un(m,n),c(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):c("Key is required. Provide the env var name to delete.",!0);default:return c(`Unknown action: ${o}. Use set, list, or delete.`,!0)}}catch(u){if(u instanceof C)return c(u.message,!0);let d=u instanceof Error?u.message:"An unexpected error occurred";return c(d,!0)}}var om,Or=x(()=>{"use strict";W();le();Je();om=De.object({projectPath:De.string().optional().describe("Path to the project directory (default: cwd)"),action:De.enum(["set","list","delete"]).describe("Action to perform"),key:De.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:De.string().optional().describe("Environment variable value (required for 'set')"),category:De.string().optional().describe("Category for the env var (default: 'custom')"),description:De.string().optional().describe("Description of what this env var is for"),setupUrl:De.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as Et}from"zod";import{resolve as kc,join as Sc}from"path";import{existsSync as Pc,readFileSync as Ic,writeFileSync as _c}from"fs";function Po(t,e){let o=Sc(t,"mistflow.json");if(!Pc(o))return;let n;try{n=JSON.parse(Ic(o,"utf-8"))}catch{return}n.domains=e,_c(o,JSON.stringify(n,null,2)+`
|
|
3323
|
-
`)}async function Mr(t){let{projectPath:e,action:o,domain:n,domainId:s}=t,a=kc(e??process.cwd());if(!J())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let i=Ae(a)?.projectId;if(!i)return c("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(o){case"add":{if(!n)return c("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await jn(i,n),p=await Ce(i);return Po(a,p.map(m=>({domain:m.domain,status:m.status}))),c(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await Ce(i);return l.length===0?c(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):c(JSON.stringify({domains:l.map(p=>({id:p.id,domain:p.domain,status:p.status,ssl:p.ssl_status,error:p.error_message}))}))}case"verify":{if(!s){if(n){let u=(await Ce(i)).find(d=>d.domain===n);if(u){let d=await zt(i,u.id);return c(JSON.stringify({domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message,message:d.status==="active"?`Domain '${d.domain}' is active and serving traffic.`:`Domain '${d.domain}' is ${d.status}. Make sure DNS records are configured correctly.`}))}return c(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return c("Provide either domainId or domain name to verify.",!0)}let l=await zt(i,s),p=await Ce(i);return Po(a,p.map(m=>({domain:m.domain,status:m.status}))),c(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!s&&!n)return c("Provide either domainId or domain name to remove.",!0);let l=s;if(!l&&n){let u=(await Ce(i)).find(d=>d.domain===n);if(!u)return c(`Domain '${n}' not found.`,!0);l=u.id}await Dn(i,l);let p=await Ce(i);return Po(a,p.map(m=>({domain:m.domain,status:m.status}))),c(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return c(`Unknown action: ${o}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof C)return c(l.message,!0);let p=l instanceof Error?l.message:"An unexpected error occurred";return c(p,!0)}}var dm,Ur=x(()=>{"use strict";W();le();Je();dm=Et.object({projectPath:Et.string().optional().describe("Path to the project directory (default: cwd)"),action:Et.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:Et.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:Et.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as ge}from"zod";var Tc,$r,Lr=x(()=>{"use strict";W();Or();Ur();Tc=ge.object({resource:ge.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:ge.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:ge.string().optional().describe("Path to the project directory (default: cwd)"),key:ge.string().optional().describe("(env) Variable name"),value:ge.string().optional().describe("(env set) Variable value"),category:ge.string().optional().describe("(env set) Category"),description:ge.string().optional().describe("(env set) Description"),setupUrl:ge.string().optional().describe("(env set) URL to obtain the value"),domain:ge.string().optional().describe("(domain) Domain name"),domainId:ge.string().optional().describe("(domain) Domain ID")}),$r={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:Tc,handler:async t=>{let e=t;switch(e.resource){case"env":return Dr({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return Mr({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return c(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}}});import{spawn as Rc,execFileSync as Ac}from"child_process";import{existsSync as ln,mkdirSync as Br,openSync as Io,closeSync as _o,readSync as Cc,readFileSync as zr,writeFileSync as Hr,renameSync as Wr,unlinkSync as Ec,readdirSync as vm,statSync as Nc}from"fs";import{homedir as Gr}from"os";import{join as
|
|
3324
|
-
`),Wr(n,o)}catch(s){try{Ec(n)}catch{}throw s}}function Uc(t){let e=Yr(t);if(!ln(e))return null;try{return JSON.parse(zr(e,"utf-8"))}catch{return null}}async function it(t){let e=`job_${jc().replace(/-/g,"").slice(0,12)}`,o=cn(e);Br(o,{recursive:!0}),_o(Io(
|
|
3323
|
+
`)}async function Mr(t){let{projectPath:e,action:o,domain:n,domainId:s}=t,a=kc(e??process.cwd());if(!J())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let i=Ae(a)?.projectId;if(!i)return c("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(o){case"add":{if(!n)return c("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await jn(i,n),p=await Ce(i);return Po(a,p.map(m=>({domain:m.domain,status:m.status}))),c(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await Ce(i);return l.length===0?c(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):c(JSON.stringify({domains:l.map(p=>({id:p.id,domain:p.domain,status:p.status,ssl:p.ssl_status,error:p.error_message}))}))}case"verify":{if(!s){if(n){let u=(await Ce(i)).find(d=>d.domain===n);if(u){let d=await zt(i,u.id);return c(JSON.stringify({domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message,message:d.status==="active"?`Domain '${d.domain}' is active and serving traffic.`:`Domain '${d.domain}' is ${d.status}. Make sure DNS records are configured correctly.`}))}return c(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return c("Provide either domainId or domain name to verify.",!0)}let l=await zt(i,s),p=await Ce(i);return Po(a,p.map(m=>({domain:m.domain,status:m.status}))),c(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!s&&!n)return c("Provide either domainId or domain name to remove.",!0);let l=s;if(!l&&n){let u=(await Ce(i)).find(d=>d.domain===n);if(!u)return c(`Domain '${n}' not found.`,!0);l=u.id}await Dn(i,l);let p=await Ce(i);return Po(a,p.map(m=>({domain:m.domain,status:m.status}))),c(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return c(`Unknown action: ${o}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof C)return c(l.message,!0);let p=l instanceof Error?l.message:"An unexpected error occurred";return c(p,!0)}}var dm,Ur=x(()=>{"use strict";W();le();Je();dm=Et.object({projectPath:Et.string().optional().describe("Path to the project directory (default: cwd)"),action:Et.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:Et.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:Et.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as ge}from"zod";var Tc,$r,Lr=x(()=>{"use strict";W();Or();Ur();Tc=ge.object({resource:ge.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:ge.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:ge.string().optional().describe("Path to the project directory (default: cwd)"),key:ge.string().optional().describe("(env) Variable name"),value:ge.string().optional().describe("(env set) Variable value"),category:ge.string().optional().describe("(env set) Category"),description:ge.string().optional().describe("(env set) Description"),setupUrl:ge.string().optional().describe("(env set) URL to obtain the value"),domain:ge.string().optional().describe("(domain) Domain name"),domainId:ge.string().optional().describe("(domain) Domain ID")}),$r={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:Tc,handler:async t=>{let e=t;switch(e.resource){case"env":return Dr({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return Mr({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return c(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}}});import{spawn as Rc,execFileSync as Ac}from"child_process";import{existsSync as ln,mkdirSync as Br,openSync as Io,closeSync as _o,readSync as Cc,readFileSync as zr,writeFileSync as Hr,renameSync as Wr,unlinkSync as Ec,readdirSync as vm,statSync as Nc}from"fs";import{homedir as Gr}from"os";import{join as xe,dirname as Vr}from"path";import{randomBytes as Jr,randomUUID as jc}from"crypto";function pn(){return xe(Gr(),".mistflow","jobs")}function Oc(){return xe(Gr(),".mistflow","job-wrapper.cjs")}function Mc(){let t=Oc(),e=Vr(t);ln(e)||Br(e,{recursive:!0});let o=`v${Kr}`;if(ln(t))try{if(zr(t,"utf-8").includes(o))return t}catch{}let n=xe(e,`.job-wrapper.tmp.${Jr(6).toString("hex")}`);return Hr(n,Dc),Wr(n,t),t}function cn(t){return xe(pn(),t)}function Yr(t){return xe(cn(t),"status.json")}function Fr(t,e){let o=Yr(t),n=xe(Vr(o),`.status.tmp.${Jr(6).toString("hex")}`);try{Hr(n,JSON.stringify(e,null,2)+`
|
|
3324
|
+
`),Wr(n,o)}catch(s){try{Ec(n)}catch{}throw s}}function Uc(t){let e=Yr(t);if(!ln(e))return null;try{return JSON.parse(zr(e,"utf-8"))}catch{return null}}async function it(t){let e=`job_${jc().replace(/-/g,"").slice(0,12)}`,o=cn(e);Br(o,{recursive:!0}),_o(Io(xe(o,"stdout.log"),"a")),_o(Io(xe(o,"stderr.log"),"a"));let n=new Date().toISOString(),s={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:n,cmd:t.cmd,args:t.args,cwd:t.cwd};Fr(e,s);let a=Mc(),r={...process.env,...t.env??{}},i=Rc("node",[a,o,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:r});i.unref();let l={...s,wrapperPid:i.pid??0};return Fr(e,l),l}function $c(t){let e=t.trim();if(!e)return NaN;let o=Date.parse(e);return Number.isFinite(o)?o:NaN}function Lc(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let o=Ac("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=$c(o),s=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(s)&&Math.abs(n-s)>2e3)return!1}catch{}return!0}function Fc(t,e){let o=Date.parse(t),n=e?Date.parse(e):Date.now();if(!Number.isFinite(o)||!Number.isFinite(n))return"0s";let s=Math.max(0,n-o),a=Math.floor(s/1e3);if(a<60)return`${a}s`;let r=Math.floor(a/60),i=a%60;return r<60?`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m`}function qr(t,e){if(!ln(t))return"";let o=Nc(t);if(o.size===0)return"";let n=o.size>e?o.size-e:0,s=o.size-n,a=Io(t,"r");try{let r=Buffer.alloc(s);return Cc(a,r,0,s,n),r.toString("utf-8")}finally{_o(a)}}function qc(t,e=20){let o=qr(xe(cn(t),"stdout.log"),16384),n=qr(xe(cn(t),"stderr.log"),16*1024),s=[];return o.trim()&&s.push(...o.split(`
|
|
3325
3325
|
`).slice(-e).map(a=>`[out] ${a}`)),n.trim()&&s.push(...n.split(`
|
|
3326
3326
|
`).slice(-e).map(a=>`[err] ${a}`)),s.filter(a=>a.trim().length>0).join(`
|
|
3327
3327
|
`)}async function at(t){let e=Uc(t);if(!e)return null;let o=e;return(e.status==="running"||e.status==="starting")&&!Lc(e)&&(o={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...o,elapsed:Fc(o.startedAt,o.endedAt),logTail:qc(t)}}var Kr,Dc,dn=x(()=>{"use strict";Kr=1,Dc=`// Generated by @mistflow-ai/mcp local-jobs (v${Kr}). Do not edit.
|
|
@@ -3389,7 +3389,7 @@ child.on('error', (err) => {
|
|
|
3389
3389
|
process.exit(1);
|
|
3390
3390
|
});
|
|
3391
3391
|
`});import{z as To}from"zod";import{resolve as Bc}from"path";import{existsSync as zc}from"fs";import{join as Hc}from"path";var Wc,Qr,Xr=x(()=>{"use strict";W();dn();Wc=To.object({projectPath:To.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:To.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),Qr={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:Wc,handler:async t=>{let e=t;if(e.jobId){let i=await at(e.jobId);return i?i.status==="running"||i.status==="starting"?c(JSON.stringify({status:"running",jobId:i.id,elapsed:i.elapsed,logTail:i.logTail,nextAction:"Still running. Call mist_install with the same jobId in ~15-30s to check progress."})):i.status==="complete"?c(JSON.stringify({status:"complete",jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,nextAction:"Dependencies installed. Run mist_implement next to start executing plan steps."})):c(JSON.stringify({status:i.status,jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,logTail:i.logTail,nextAction:"npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. After fixing, start a new install with { projectPath }."}),!0):c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No install job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0)}let o=Bc(e.projectPath);if(!zc(Hc(o,"package.json")))return c(`No package.json at ${o}. Confirm the path and that mist_init has scaffolded the project.`,!0);let a=`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')`,r=await it({type:"install",cmd:"sh",args:["-c",a],cwd:o,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return c(JSON.stringify({status:"running",jobId:r.id,startedAt:r.startedAt,cwd:o,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+r.id+"' } in ~15-30s to check progress. Typical duration: 30-90s."}))}}});import{z as un}from"zod";import{resolve as Gc,join as lt}from"path";import{existsSync as ct,readFileSync as Zr}from"fs";function Jc(t){let e=lt(pn(),t,"stdout.log"),o=lt(pn(),t,"stderr.log"),n="";try{ct(e)&&(n+=Zr(e,"utf-8"))}catch{}try{ct(o)&&(n+=`
|
|
3392
|
-
`+Zr(o,"utf-8"))}catch{}return n}function Kc(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,o=new Set;for(let n of t.matchAll(e)){let s=n[1];if(s.startsWith(".")||s.startsWith("@/")||s.startsWith("~/"))continue;let a=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];a&&o.add(a)}return[...o]}var Vc,ei,ti=x(()=>{"use strict";W();dn();io();Vc=un.object({projectPath:un.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:un.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:un.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});ei={name:"mist_build",description:"Run a Mistflow project's production build with the fire-and-poll pattern. First call with { projectPath } starts `npm run build` and returns a jobId. Subsequent calls with { jobId } poll status. On failure, the response surfaces structured errors (from parseBuildErrors) and any missingModules[] \u2014 chain into mist_install with those modules, then mist_build again, without asking the user.",inputSchema:Vc,handler:async t=>{let e=t;if(e.jobId){let l=await at(e.jobId);if(!l)return c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No build job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0);if(l.status==="running"||l.status==="starting")return c(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:l.logTail,nextAction:"Build still running. Call mist_build again with the same jobId in ~20-40s."}));if(l.status==="complete")return c(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}));let p=Jc(l.id),m=Zt(p),u=Kc(p),d=u.length>0?`Build failed with missing modules: ${u.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.`:m.length>0?"Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.":"Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.";return c(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,errors:m,missingModules:u,logTail:l.logTail,nextAction:d}),!0)}let o=Gc(e.projectPath);if(!ct(lt(o,"package.json")))return c(`No package.json at ${o}. Run mist_init first.`,!0);if(!ct(lt(o,"node_modules")))return c(`node_modules not installed. Run mist_install { projectPath: '${o}' } first.`,!0);let n,s,a,r=ct(lt(o,"open-next.config.ts"))||ct(lt(o,"open-next.config.js"));e.script?(n="npm",s=["run",e.script],a=e.script):r?(n="npx",s=["-y","@opennextjs/cloudflare","build"],a="@opennextjs/cloudflare build"):(n="npm",s=["run","build"],a="build");let i=await it({type:"build",cmd:n,args:s,cwd:o});return c(JSON.stringify({status:"running",jobId:i.id,startedAt:i.startedAt,cwd:o,script:a,nextAction:`Build started. Call mist_build again with { jobId: '${i.id}' } in ~30s to check progress. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}}});import{z as Nt}from"zod";import{resolve as Yc,join as Ro}from"path";import{existsSync as Ao}from"fs";var Qc,ni,oi=x(()=>{"use strict";W();dn();Qc=Nt.object({projectPath:Nt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Nt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),baseUrl:Nt.string().optional().describe("Override the URL Playwright tests hit \u2014 defaults to the project's configured base URL."),grep:Nt.string().optional().describe("Pass-through to `playwright test -g`. Useful for running a single scenario.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a QA run, or jobId to poll an existing one."}),ni={name:"mist_qa",description:"Run a Mistflow project's Playwright QA suite with the fire-and-poll pattern. First call with { projectPath, baseUrl? } starts the run and returns a jobId. Subsequent calls with { jobId } poll status. Call AFTER mist_deploy \u2014 the QA suite targets the deployed URL. Do NOT show the deploy URL to the user until mist_qa reports status: 'complete' with exitCode 0.",inputSchema:Qc,handler:async t=>{let e=t;if(e.jobId){let i=await at(e.jobId);return i?i.status==="running"||i.status==="starting"?c(JSON.stringify({status:"running",jobId:i.id,elapsed:i.elapsed,logTail:i.logTail,nextAction:"QA still running. Call mist_qa again with the same jobId in ~15-30s."})):i.status==="complete"?c(JSON.stringify({status:"complete",jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,nextAction:"QA passed. Surface the deploy URL to the user now \u2014 the app is verified."})):c(JSON.stringify({status:i.status,jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,logTail:i.logTail,nextAction:"QA failed. Read the logTail for which scenarios broke. Do NOT show the deploy URL to the user. Fix the code, redeploy (mist_deploy), then re-run mist_qa."}),!0):c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No QA job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0)}let o=Yc(e.projectPath);if(!Ao(Ro(o,"package.json")))return c(`No package.json at ${o}. Run mist_init first.`,!0);if(!(Ao(Ro(o,"playwright.config.ts"))||Ao(Ro(o,"playwright.config.js"))))return c(`No playwright.config.ts at ${o}. Mistflow projects scaffold with Playwright; if missing, run mist_implement to regenerate or add one manually.`,!0);let s=["playwright","test"];e.grep&&s.push("-g",e.grep);let a={};e.baseUrl&&(a.BASE_URL=e.baseUrl);let r=await it({type:"qa",cmd:"npx",args:s,cwd:o,env:a});return c(JSON.stringify({status:"running",jobId:r.id,startedAt:r.startedAt,cwd:o,baseUrl:e.baseUrl??"(from project config)",nextAction:`QA started. Call mist_qa again with { jobId: '${r.id}' } in ~20s. Typical duration: 30-120s depending on scenario count.`}))}}});import{existsSync as mn,readdirSync as Xc,statSync as si,unlinkSync as ri}from"fs";import{join as We}from"path";import{execFile as Zc}from"child_process";function ep(t,e){let o=0;for(let n of e){let s=We(t,n);if(mn(s))try{let a=si(s);if(a.isFile())o++;else if(a.isDirectory()){let r=[s];for(;r.length;){let i=r.pop(),l=Xc(i,{withFileTypes:!0});for(let p of l){let m=We(i,p.name);p.isDirectory()?r.push(m):o++}}}}catch{}}return o}function ii(t,e,o){return new Promise(n=>{Zc("tar",t,{cwd:e,timeout:o,maxBuffer:10*1024*1024},(s,a,r)=>{n({success:!s,stderr:r?.toString()??""})})})}async function ai(t){let e=We(t,".open-next-build.tar.gz"),o=[".open-next"];mn(We(t,"db"))&&o.push("db"),mn(We(t,"drizzle.config.ts"))&&o.push("drizzle.config.ts"),mn(We(t,"package.json"))&&o.push("package.json");let n=ep(t,o),s=await ii(["-czf",e,"-C",t,...o],t,12e4);if(!s.success){try{ri(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(s.stderr?`
|
|
3392
|
+
`+Zr(o,"utf-8"))}catch{}return n}function Kc(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,o=new Set;for(let n of t.matchAll(e)){let s=n[1];if(s.startsWith(".")||s.startsWith("@/")||s.startsWith("~/"))continue;let a=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];a&&o.add(a)}return[...o]}var Vc,ei,ti=x(()=>{"use strict";W();dn();io();Vc=un.object({projectPath:un.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:un.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:un.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});ei={name:"mist_build",description:"Run a Mistflow project's production build with the fire-and-poll pattern. First call with { projectPath } starts `npm run build` and returns a jobId. Subsequent calls with { jobId } poll status. On failure, the response surfaces structured errors (from parseBuildErrors) and any missingModules[] \u2014 chain into mist_install with those modules, then mist_build again, without asking the user.",inputSchema:Vc,handler:async t=>{let e=t;if(e.jobId){let l=await at(e.jobId);if(!l)return c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No build job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0);if(l.status==="running"||l.status==="starting")return c(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:l.logTail,nextAction:"Build still running. Call mist_build again with the same jobId in ~20-40s."}));if(l.status==="complete")return c(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}));let p=Jc(l.id),m=Zt(p),u=Kc(p),d=u.length>0?`Build failed with missing modules: ${u.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.`:m.length>0?"Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.":"Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.";return c(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,errors:m,missingModules:u,logTail:l.logTail,nextAction:d}),!0)}let o=Gc(e.projectPath);if(!ct(lt(o,"package.json")))return c(`No package.json at ${o}. Run mist_init first.`,!0);if(!ct(lt(o,"node_modules")))return c(`node_modules not installed. Run mist_install { projectPath: '${o}' } first.`,!0);let n,s,a,r=ct(lt(o,"open-next.config.ts"))||ct(lt(o,"open-next.config.js"));e.script?(n="npm",s=["run",e.script],a=e.script):r?(n="npx",s=["-y","@opennextjs/cloudflare","build"],a="@opennextjs/cloudflare build"):(n="npm",s=["run","build"],a="build");let i=await it({type:"build",cmd:n,args:s,cwd:o});return c(JSON.stringify({status:"running",jobId:i.id,startedAt:i.startedAt,cwd:o,script:a,nextAction:`Build started. Call mist_build again with { jobId: '${i.id}' } in ~30s to check progress. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}}});import{z as Nt}from"zod";import{resolve as Yc,join as Ro}from"path";import{existsSync as Ao}from"fs";var Qc,ni,oi=x(()=>{"use strict";W();dn();Qc=Nt.object({projectPath:Nt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Nt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),baseUrl:Nt.string().optional().describe("Override the URL Playwright tests hit \u2014 defaults to the project's configured base URL."),grep:Nt.string().optional().describe("Pass-through to `playwright test -g`. Useful for running a single scenario.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a QA run, or jobId to poll an existing one."}),ni={name:"mist_qa",description:"Run a Mistflow project's Playwright QA suite with the fire-and-poll pattern. First call with { projectPath, baseUrl? } starts the run and returns a jobId. Subsequent calls with { jobId } poll status. Call AFTER mist_deploy \u2014 the QA suite targets the deployed URL. Do NOT show the deploy URL to the user until mist_qa reports status: 'complete' with exitCode 0.",inputSchema:Qc,handler:async t=>{let e=t;if(e.jobId){let i=await at(e.jobId);return i?i.status==="running"||i.status==="starting"?c(JSON.stringify({status:"running",jobId:i.id,elapsed:i.elapsed,logTail:i.logTail,nextAction:"QA still running. Call mist_qa again with the same jobId in ~15-30s."})):i.status==="complete"?c(JSON.stringify({status:"complete",jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,nextAction:"QA passed. Surface the deploy URL to the user now \u2014 the app is verified."})):c(JSON.stringify({status:i.status,jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,logTail:i.logTail,nextAction:"QA failed. Read the logTail for which scenarios broke. Do NOT show the deploy URL to the user. Fix the code, redeploy (mist_deploy), then re-run mist_qa."}),!0):c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No QA job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0)}let o=Yc(e.projectPath);if(!Ao(Ro(o,"package.json")))return c(`No package.json at ${o}. Run mist_init first.`,!0);if(!(Ao(Ro(o,"playwright.config.ts"))||Ao(Ro(o,"playwright.config.js"))))return c(`No playwright.config.ts at ${o}. Mistflow projects scaffold with Playwright; if missing, run mist_implement to regenerate or add one manually.`,!0);let s=["playwright","test"];e.grep&&s.push("-g",e.grep);let a={};e.baseUrl&&(a.BASE_URL=e.baseUrl);let r=await it({type:"qa",cmd:"npx",args:s,cwd:o,env:a});return c(JSON.stringify({status:"running",jobId:r.id,startedAt:r.startedAt,cwd:o,baseUrl:e.baseUrl??"(from project config)",nextAction:`QA started. Call mist_qa again with { jobId: '${r.id}' } in ~20s. Typical duration: 30-120s depending on scenario count.`}))}}});import{existsSync as mn,readdirSync as Xc,statSync as si,unlinkSync as ri}from"fs";import{join as We}from"path";import{execFile as Zc}from"child_process";function ep(t,e){let o=0;for(let n of e){let s=We(t,n);if(mn(s))try{let a=si(s);if(a.isFile())o++;else if(a.isDirectory()){let r=[s];for(;r.length;){let i=r.pop(),l=Xc(i,{withFileTypes:!0});for(let p of l){let m=We(i,p.name);p.isDirectory()?r.push(m):o++}}}}catch{}}return o}function ii(t,e,o){return new Promise(n=>{Zc("tar",t,{cwd:e,timeout:o,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(s,a,r)=>{n({success:!s,stderr:r?.toString()??""})})})}async function ai(t){let e=We(t,".open-next-build.tar.gz"),o=[".open-next"];mn(We(t,"db"))&&o.push("db"),mn(We(t,"drizzle.config.ts"))&&o.push("drizzle.config.ts"),mn(We(t,"package.json"))&&o.push("package.json");let n=ep(t,o),s=await ii(["-czf",e,"-C",t,...o],t,12e4);if(!s.success){try{ri(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(s.stderr?`
|
|
3393
3393
|
${s.stderr.slice(-500)}`:""))}let a=0;try{a=si(e).size}catch{}return{path:e,sizeBytes:a,fileCount:n}}async function li(t){let e=We(t,".mistflow-source.tar.gz");return(await ii(["-czf",e,"-C",t,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],t,12e4)).success?e:null}function Co(t){if(t)try{ri(t)}catch{}}function ci(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function pi(t){switch(t){case"pending":return"Provisioning...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";case"live":return"Live!";case"failed":return"Failed";default:return`Status: ${t}`}}var di=x(()=>{"use strict"});import{z as pt}from"zod";import{resolve as tp,join as np}from"path";import{existsSync as op}from"fs";function rp(t){return op(np(t,".open-next"))}function ip(t){return Ae(t)?.deploy?.strategy==="staging"?"preview":null}async function ap(t){let e=tp(t.projectPath);if(!J())return c("Not signed in. Call mist_setup first.",!0);let n=Ae(e)?.projectId;if(!n)return c(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);if(!rp(e))return c(`No .open-next build output at ${e}. Run mist_build first \u2014 the deploy tool ships the build artifact, not the raw source.`,!0);let s=t.environment??ip(e)??"production",a=null,r=null;try{a=await ai(e),r=await li(e);let i=await Cn(n,a.path,s,t.adminEmail,void 0,r??void 0,void 0);return c(JSON.stringify({status:"running",jobId:i.deployment_id,deploymentId:i.deployment_id,environment:i.environment??s,buildSize:ci(a.sizeBytes),buildFileCount:a.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${i.deployment_id}' } in ~5-10s to poll deployment progress. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(i){let l=i instanceof C||i instanceof Error?i.message:String(i);return c(`Deploy upload failed: ${l}`,!0)}finally{Co(a?.path),Co(r)}}async function lp(t){try{let e=await xt(t),o=pi(e.status);return e.status==="live"?c(JSON.stringify({status:"complete",jobId:e.id,deploymentId:e.id,url:e.url,completedAt:e.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, baseUrl: '${e.url??""}' } next. Do NOT show the URL to the user until mist_qa returns status: 'complete'.`})):e.status==="failed"?c(JSON.stringify({status:"failed",jobId:e.id,deploymentId:e.id,error:e.error,phase:o,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):c(JSON.stringify({status:"running",jobId:e.id,deploymentId:e.id,phase:o,phaseCode:e.status,nextAction:`Still ${e.status}. Call mist_deploy { action: 'status', deploymentId: '${e.id}' } again in ~5-10s.`}))}catch(e){let o=e instanceof C||e instanceof Error?e.message:String(e);return c(`Could not fetch deploy status: ${o}`,!0)}}async function cp(t,e){if(!J())return c("Not signed in. Call mist_setup first.",!0);let n=Ae(t)?.projectId;if(!n)return c(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let s=e;if(!s)try{let r=(await Qe(n)).find(i=>i.environment==="preview"&&i.status==="live");if(!r)return c("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);s=r.id}catch(a){let r=a instanceof C?a.message:String(a);return c(`Could not list deployments: ${r}`,!0)}try{let a=await Fn(n,s);return c(JSON.stringify({status:"running",jobId:a.deployment_id,deploymentId:a.deployment_id,promotedFrom:s,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${a.deployment_id}' } to poll. Promotion re-uses the preview artifact so it typically completes in ~10s.`}))}catch(a){let r=a instanceof C||a instanceof Error?a.message:String(a);return c(`Promote failed: ${r}`,!0)}}async function pp(t){if(!J())return c("Not signed in. Call mist_setup first.",!0);try{let e=await qn(t);return c(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } to poll.`}))}catch(e){let o=e instanceof C||e instanceof Error?e.message:String(e);return c(`Rollback failed: ${o}`,!0)}}var sp,ui,mi=x(()=>{"use strict";W();le();Je();di();sp=pt.object({action:pt.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:pt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:pt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:pt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:pt.string().optional().describe("Admin email injected as BETTER_AUTH_ADMIN_EMAIL on first deploy of an auth-enabled project.")});ui={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:sp,handler:async t=>{let e=t;switch(e.action??"deploy"){case"deploy":return e.projectPath?ap({projectPath:e.projectPath,environment:e.environment,adminEmail:e.adminEmail}):c("projectPath is required for action='deploy'.",!0);case"status":return e.deploymentId?lp(e.deploymentId):c("deploymentId is required for action='status'.",!0);case"promote":return e.projectPath?cp(e.projectPath,e.deploymentId):c("projectPath is required for action='promote'.",!0);case"rollback":return e.deploymentId?pp(e.deploymentId):c("deploymentId is required for action='rollback'.",!0)}}}});var yp={};import{Server as dp}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as up}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as mp,ListToolsRequestSchema as hp}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as gp}from"zod-to-json-schema";async function fp(){let 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 up;await hn.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var hn,hi,gi=x(()=>{"use strict";Te();W();ls();_s();Rs();Ns();ro();Bs();tr();pr();jr();Lr();Xr();ti();oi();mi();hn=new dp({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:$o()}),hi=[as,Is,Ts,Es,er,cr,Ls,Nr,qs,$r,Qr,ei,ni,ui];hn.setRequestHandler(hp,async()=>({tools:hi.map(t=>({name:t.name,description:t.description,inputSchema:gp(t.inputSchema)}))}));hn.setRequestHandler(mp,async t=>{let e=hi.find(o=>o.name===t.params.name);if(!e)return c(`Unknown tool: ${t.params.name}`,!0);try{let o=e.inputSchema.safeParse(t.params.arguments);if(!o.success){let a=o.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join(", ");return c(`Invalid input: ${a}`,!0)}let n=t.params._meta?.progressToken,s={server:hn,progressToken:n};try{return await e.handler(o.data,s)}finally{s.cleanup?.()}}catch(o){let n=o instanceof Error?o.message:"An unexpected error occurred";return console.error("Tool error:",o),c(n,!0)}});fp().catch(t=>{console.error("Fatal error:",t),process.exit(1)})});import{readFileSync as bp}from"fs";import{dirname as wp,join as vp}from"path";import{fileURLToPath as xp}from"url";var Oe=process.argv[2];if(Oe==="--version"||Oe==="-v"){try{let t=wp(xp(import.meta.url)),e=vp(t,"..","package.json"),o=JSON.parse(bp(e,"utf-8"));console.log(o.version)}catch{console.log("unknown")}process.exit(0)}(Oe==="--help"||Oe==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
|
|
3394
3394
|
|
|
3395
3395
|
Usage:
|