@mistflow-ai/mcp 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +194 -179
  2. package/dist/index.js +193 -178
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,28 +1,28 @@
1
- var Er=Object.defineProperty;var ze=(t,e)=>()=>(t&&(e=t(t=0)),e);var Nt=(t,e)=>{for(var o in e)Er(t,o,{get:e[o],enumerable:!0})};import{existsSync as gn,readFileSync as No,writeFileSync as qr,mkdirSync as Br}from"fs";import{join as mn,dirname as hn}from"path";import{homedir as zr}from"os";import{fileURLToPath as Hr}from"url";function pe(){if(jt)return jt;try{let t=Hr(import.meta.url),e=hn(t);for(let o=0;o<6;o++){let n=mn(e,"package.json");if(gn(n)){let a=JSON.parse(No(n,"utf-8"));if(a.name==="@mistflow-ai/mcp"&&typeof a.version=="string")return jt=a.version,a.version}let s=hn(e);if(s===e)break;e=s}}catch{}return jt="0.0.0","0.0.0"}function Dt(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function Ao(t,e){let o=Dt(t),n=Dt(e);if(!o||!n)return 0;for(let s=0;s<3;s++){if(o[s]<n[s])return-1;if(o[s]>n[s])return 1}return 0}function jo(t,e,o){if(o&&Ao(t,o)<0)return"unsupported";if(!e||Ao(t,e)>=0)return"none";let s=Dt(t),a=Dt(e);return!s||!a?"none":s[0]<a[0]?"major":s[1]<a[1]?"minor":"patch"}function ut(t){let e=t.get("x-mistflow-mcp-latest")??"",o=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!o||(ce={latest:e,minSupported:o,changelogUrl:n})}function Do(){let t=process.env.MISTFLOW_STATE_DIR||mn(zr(),".mistflow");return mn(t,"upgrade-state.json")}function Wr(){try{let t=Do();return gn(t)?JSON.parse(No(t,"utf-8")):{}}catch{return{}}}function Gr(t){try{let e=Do(),o=hn(e);gn(o)||Br(o,{recursive:!0}),qr(e,JSON.stringify(t,null,2)+`
2
- `,{mode:384})}catch{}}function Vr(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Oo(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!ce)return null;let t=pe();if(t==="0.0.0")return null;let e=jo(t,ce.latest,ce.minSupported);if(e==="none")return null;if(e==="unsupported")return Eo(e,t,ce);if(Co)return null;let o=Wr(),n=Date.now(),s=Vr(e);return o.dismissedForVersion===ce.latest&&e!=="major"||o.lastLatestSeen===ce.latest&&o.lastShownMs&&n-o.lastShownMs<s?null:(Co=!0,Gr({...o,lastShownMs:n,lastLatestSeen:ce.latest}),Eo(e,t,ce))}function Eo(t,e,o){let n="npx -y mistflow-ai install",s=o.changelogUrl?`
3
- What's new: ${o.changelogUrl}`:"";return t==="unsupported"?`
1
+ var $r=Object.defineProperty;var Qe=(t,e)=>()=>(t&&(e=t(t=0)),e);var Dt=(t,e)=>{for(var s in e)$r(t,s,{get:e[s],enumerable:!0})};import{existsSync as wn,readFileSync as Os,writeFileSync as Vr,mkdirSync as Jr}from"fs";import{join as yn,dirname as bn}from"path";import{homedir as Yr}from"os";import{fileURLToPath as Kr}from"url";function be(){if(Ot)return Ot;try{let t=Kr(import.meta.url),e=bn(t);for(let s=0;s<6;s++){let n=yn(e,"package.json");if(wn(n)){let i=JSON.parse(Os(n,"utf-8"));if(i.name==="@mistflow-ai/mcp"&&typeof i.version=="string")return Ot=i.version,i.version}let o=bn(e);if(o===e)break;e=o}}catch{}return Ot="0.0.0","0.0.0"}function Mt(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function Ns(t,e){let s=Mt(t),n=Mt(e);if(!s||!n)return 0;for(let o=0;o<3;o++){if(s[o]<n[o])return-1;if(s[o]>n[o])return 1}return 0}function Ms(t,e,s){if(s&&Ns(t,s)<0)return"unsupported";if(!e||Ns(t,e)>=0)return"none";let o=Mt(t),i=Mt(e);return!o||!i?"none":o[0]<i[0]?"major":o[1]<i[1]?"minor":"patch"}function gt(t){let e=t.get("x-mistflow-mcp-latest")??"",s=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!s||(ye={latest:e,minSupported:s,changelogUrl:n})}function $s(){let t=process.env.MISTFLOW_STATE_DIR||yn(Yr(),".mistflow");return yn(t,"upgrade-state.json")}function Qr(){try{let t=$s();return wn(t)?JSON.parse(Os(t,"utf-8")):{}}catch{return{}}}function Xr(t){try{let e=$s(),s=bn(e);wn(s)||Jr(s,{recursive:!0}),Vr(e,JSON.stringify(t,null,2)+`
2
+ `,{mode:384})}catch{}}function Zr(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Us(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!ye)return null;let t=be();if(t==="0.0.0")return null;let e=Ms(t,ye.latest,ye.minSupported);if(e==="none")return null;if(e==="unsupported")return Ds(e,t,ye);if(js)return null;let s=Qr(),n=Date.now(),o=Zr(e);return s.dismissedForVersion===ye.latest&&e!=="major"||s.lastLatestSeen===ye.latest&&s.lastShownMs&&n-s.lastShownMs<o?null:(js=!0,Xr({...s,lastShownMs:n,lastLatestSeen:ye.latest}),Ds(e,t,ye))}function Ds(t,e,s){let n="npx -y mistflow-ai install",o=s.changelogUrl?`
3
+ What's new: ${s.changelogUrl}`:"";return t==="unsupported"?`
4
4
 
5
5
  ---
6
6
  Mistflow ${e} is no longer supported.
7
- You must upgrade to ${o.latest} or newer to continue:
7
+ You must upgrade to ${s.latest} or newer to continue:
8
8
 
9
9
  ${n}
10
10
 
11
- After upgrading, restart your AI editor.${s}
11
+ After upgrading, restart your AI editor.${o}
12
12
  ---`:t==="major"?`
13
13
 
14
14
  ---
15
- Mistflow ${o.latest} is available (you have ${e}).
16
- This is a major update. Run \`${n}\` and restart your editor.${s}
15
+ Mistflow ${s.latest} is available (you have ${e}).
16
+ This is a major update. Run \`${n}\` and restart your editor.${o}
17
17
  ---`:t==="minor"?`
18
18
 
19
- --- Mistflow update available: ${e} -> ${o.latest} ---
20
- Run \`${n}\` to upgrade, then restart your editor.${s}`:`
19
+ --- Mistflow update available: ${e} -> ${s.latest} ---
20
+ Run \`${n}\` to upgrade, then restart your editor.${o}`:`
21
21
 
22
- (Mistflow ${o.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function fn(){let t=pe(),e=ce??{latest:"",minSupported:"",changelogUrl:""},o=jo(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:o,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:ce!==null}}var jt,ce,Co,mt=ze(()=>{"use strict";jt=null;ce=null;Co=!1});var Uo={};Nt(Uo,{closeBrowser:()=>bn,getIsolatedContext:()=>Kr,getPage:()=>yn,getSnapshot:()=>ht,takeScreenshot:()=>gt});async function Mo(){try{return await import("playwright")}catch{throw new Error("Playwright is not installed. Run: cd packages/mcp-server && pnpm add playwright && npx playwright install chromium")}}async function Jr(){let t=await Mo();return(!de||!de.isConnected())&&(de=await t.chromium.launch({headless:!0})),Ie&&(await Ie.close().catch(()=>{}),Ie=null),Ie=await de.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),xe=await Ie.newPage(),xe}async function yn(){return xe&&!xe.isClosed()?xe:(Ot||(Ot=Jr().finally(()=>{Ot=null})),Ot)}async function bn(){xe&&!xe.isClosed()&&await xe.close().catch(()=>{}),Ie&&await Ie.close().catch(()=>{}),de?.isConnected()&&await de.close().catch(()=>{}),xe=null,Ie=null,de=null}async function Kr(){let t=await Mo();(!de||!de.isConnected())&&(de=await t.chromium.launch({headless:!0}));let e=await de.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),o=await e.newPage();return{context:e,page:o}}async function ht(t){return await t.locator("body").ariaSnapshot()}async function gt(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var de,Ie,xe,Ot,wn=ze(()=>{"use strict";de=null,Ie=null,xe=null,Ot=null;process.once("SIGTERM",()=>{bn().finally(()=>process.exit(0))});process.once("SIGINT",()=>{bn().finally(()=>process.exit(0))})});import{readFileSync as Lo,existsSync as vn,writeFileSync as Yr,mkdirSync as Qr,renameSync as Xr,unlinkSync as Zr}from"fs";import{join as xn,dirname as ei}from"path";import{homedir as ti}from"os";import{randomBytes as ni}from"crypto";function Fo(){return xn(ti(),".mistflow","credentials.json")}function Mt(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function qo(){let t=Fo();if(!vn(t))return null;try{let e=JSON.parse(Lo(t,"utf-8"));return typeof e.apiKey=="string"?{[oi]:e}:e}catch{return null}}function He(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=qo();if(!e)return{ok:!1,reason:"missing"};let o=Mt(),n=e[o];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function kn(t){let e=Fo(),o=ei(e);vn(o)||Qr(o,{recursive:!0});let n=qo()??{},s=Mt();n[s]=t;let a=xn(o,`.credentials.tmp.${ni(8).toString("hex")}`);try{Yr(a,JSON.stringify(n,null,2)+`
23
- `,{mode:384}),Xr(a,e)}catch(r){try{Zr(a)}catch{}throw r}}function G(){return He().ok}function _e(t){let e=xn(t,"mistflow.json");if(!vn(e))return null;try{return JSON.parse(Lo(e,"utf-8"))}catch{return null}}var oi,We=ze(()=>{"use strict";oi="https://api.mistflow.ai"});var Vo={};Nt(Vo,{MistflowApiError:()=>A,addDomain:()=>Rn,checkAuth:()=>ai,checkAuthDetailed:()=>Wo,checkSubdomain:()=>Pn,createDeployment:()=>ci,createProject:()=>yt,deleteEnvVar:()=>Nn,discoverDecisions:()=>pi,downloadSource:()=>gi,downloadSourceWithToken:()=>Go,fetchDesignDirections:()=>_n,fetchModule:()=>Ln,fetchPlanConversation:()=>$t,fetchScaffold:()=>Un,fetchStepContext:()=>$n,forkTemplate:()=>qn,generatePlan:()=>Tn,getAuthHeaders:()=>Ue,getBaseUrl:()=>V,getDashboardUrl:()=>si,getDbCredentials:()=>di,getDeployLogs:()=>jn,getDeploymentStatus:()=>bt,getProject:()=>li,getProjectErrors:()=>Dn,getSeedInfo:()=>ui,getSiteUrl:()=>Ge,getTemplate:()=>Fn,hasCredentialsOnDisk:()=>G,hasLocalCredentials:()=>Ho,listDeployments:()=>Je,listDomains:()=>Te,listEnvVars:()=>Cn,markLocalSetupDone:()=>fi,modifyPlan:()=>Lt,pingBackend:()=>Sn,promotePreview:()=>On,redeployProject:()=>hi,removeDomain:()=>An,rollbackDeployment:()=>Mn,shareProject:()=>Bn,uploadAndDeploy:()=>In,uploadQAResults:()=>mi,upsertEnvVar:()=>En,verifyDomain:()=>Ft});function V(){return Mt()}function Ge(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9102")}return"https://mistflow.ai"}function si(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function Ue(){let t=He();if(!t.ok)throw new A("auth_missing","No Mistflow credentials found.",401);return ri(t.creds)}function ri(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":pe()}}function Ve(t){try{ut(t.headers)}catch{}}async function Sn(){try{let t=await fetch(`${V()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Ve(t)}catch{}}async function zo(t,e,o,n){for(let s=0;s<2;s++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(o)})}catch(a){let r=a instanceof Error&&a.name==="TimeoutError",i=a instanceof TypeError;if(n&&s===0&&(r||i)){console.error(`[api] Retrying ${t} after ${r?"timeout":"network error"}`);continue}throw a}throw new Error("fetchWithRetry: exhausted retries")}async function ft(t){let e=null;try{e=await t.json()}catch{e=null}let o=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(o)return new A(o,n,t.status,e?.details);let s=t.status;return s===401?new A("auth_invalid",n,s):s===403?new A("permission_denied",n,s):s===404?new A("not_found",n,s):s===409?new A("conflict",n,s):s===422?new A("validation_error",n,s):s===429?new A("rate_limited",n,s):s>=500?new A("server_error",t.statusText||"Internal server error",s):new A("client_error",n,s)}async function N(t,e={}){let o=Ue(),{timeoutMs:n,idempotent:s,...a}=e,r=n??3e4,i=(a.method??"GET").toUpperCase(),l=s??(i==="GET"||i==="HEAD"),p;try{p=await zo(`${V()}${t}`,{...a,headers:{...o,...a.headers}},r,l)}catch(m){throw m instanceof Error&&m.name==="TimeoutError"?new A("network_error","Request timed out. Try again in a moment."):new A("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ve(p),!p.ok)throw await ft(p);return p.json()}function Ho(){return He().ok}async function ai(){return(await Wo()).ok}async function Wo(){if(Ut!==null&&Date.now()<Bo)return Ut?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Ho())return{ok:!1,reason:"no_credentials"};try{return await N("/api/org"),Ut=!0,Bo=Date.now()+ii,{ok:!0}}catch(t){if(Ut=null,!(t instanceof A))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function li(t){return N(`/api/projects/${encodeURIComponent(t)}`)}async function Pn(t){return N(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function yt(t,e,o="neon",n){return N("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e,db_provider:o,requested_subdomain:n})})}async function ci(t,e){return N("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function In(t,e,o="production",n,s,a,r){let{readFileSync:i}=await import("fs"),{basename:l}=await import("path"),p=He();if(!p.ok)throw new A("auth_missing","No Mistflow credentials found.",401);let m=p.creds,u=i(e),d=new Blob([u],{type:"application/gzip"}),b=new FormData;if(b.append("project_id",t),b.append("build",d,l(e)),o!=="production"&&b.append("environment",o),n&&b.append("admin_email",n),s&&b.append("schema_pushed","true"),a){let{existsSync:y}=await import("fs");if(y(a)){let x=i(a),M=new Blob([x],{type:"application/gzip"});b.append("source",M,"source.tar.gz")}}r&&b.append("git_commit_sha",r);let T;try{T=await fetch(`${V()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":pe()},body:b,signal:AbortSignal.timeout(3e5)})}catch{throw new A("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ve(T),!T.ok)throw await ft(T);let w=await T.json();return{...w,id:w.deployment_id}}async function bt(t){return N(`/api/deploy/${encodeURIComponent(t)}/status`)}async function _n(t){return N(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function $t(t,e){let o=e?.waitSeconds??10,n=o>0?`?wait=${o}`:"",s=Math.min(6e4,(o+5)*1e3);return N(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:s})}async function Tn(t,e){let o={description:t,conversation_id:e?.conversationId,answers:e?.answers};e?.autonomous&&(o.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(o.language=e.language),e?.designConversationId&&(o.design_conversation_id=e.designConversationId),e?.designDirection&&(o.design_direction=e.designDirection);let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return N("/api/plan",{method:"POST",body:JSON.stringify(o),timeoutMs:n,idempotent:!1})}async function Lt(t,e){return N("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function pi(t){return N("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Rn(t,e){return N(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function Te(t){return N(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Ft(t,e){return N(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function An(t,e){return N(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function di(t){return N(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function ui(t){try{return await N(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof A&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function mi(t,e){try{return await N(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(o){return console.error("[api] Failed to upload QA results:",o instanceof Error?o.message:o),null}}async function Cn(t){return N(`/api/projects/${encodeURIComponent(t)}/env`)}async function En(t,e,o,n){return N(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:o,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function Nn(t,e){return N(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function jn(t){return N(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Dn(t,e="7d"){return N(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Je(t){return N(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function hi(t){return N(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function On(t,e){let o=new URLSearchParams({preview_deployment_id:e});return N(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:o.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Mn(t){return N(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function gi(t,e){let o=He();if(!o.ok)throw new A("auth_missing","Not authenticated.",401);let n=o.creds,s=await fetch(`${V()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":pe()},signal:AbortSignal.timeout(12e4)});if(Ve(s),!s.ok)throw await ft(s);let{writeFileSync:a}=await import("fs"),r=Buffer.from(await s.arrayBuffer());a(e,r)}async function qt(t,e){let{timeoutMs:o,idempotent:n,...s}=e??{},a=o??3e4,r=(s.method??"GET").toUpperCase(),i=n??(r==="GET"||r==="HEAD"),l;try{l=await zo(`${V()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":pe()},...s},a,i)}catch(p){throw p instanceof Error&&p.name==="TimeoutError"?new A("network_error","Request timed out. Try again in a moment."):new A("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ve(l),!l.ok)throw await ft(l);return l.json()}async function Un(t="nextjs"){return qt(`/api/scaffold/${encodeURIComponent(t)}`)}async function $n(t,e){return qt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Ln(t,e,o,n){return qt(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:o,entity_plural:n})})}async function Fn(t){return qt(`/api/templates/${encodeURIComponent(t)}`)}async function qn(t){return N(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Go(t,e,o){let n;try{n=await fetch(`${V()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":pe()},signal:AbortSignal.timeout(12e4)})}catch{throw new A("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ve(n),!n.ok)throw n.status===401?new A("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await ft(n);let{writeFileSync:s}=await import("fs"),a=Buffer.from(await n.arrayBuffer());s(o,a)}async function fi(t){await N(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Bn(t,e){return N(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}var A,Ut,Bo,ii,ie=ze(()=>{"use strict";We();mt();A=class extends Error{constructor(o,n,s,a){super(n);this.code=o;this.statusCode=s;this.details=a;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};Ut=null,Bo=0,ii=300*1e3});var xt={};Nt(xt,{emptyState:()=>vt,fetchRemoteState:()=>Ai,fuzzyMatch:()=>Ei,getLocalStatePath:()=>Hn,readLocalState:()=>Ri,syncRemoteState:()=>Ci,writeLocalState:()=>wt});import{existsSync as Zo,readFileSync as Ii,writeFileSync as _i,mkdirSync as Ti}from"fs";import{join as es}from"path";function Hn(t){return es(t,".mistflow","state.json")}function Ri(t){let e=Hn(t);if(!Zo(e))return null;try{return JSON.parse(Ii(e,"utf-8"))}catch{return null}}function wt(t,e){let o=es(t,".mistflow");Zo(o)||Ti(o,{recursive:!0}),_i(Hn(t),JSON.stringify(e,null,2)+`
24
- `)}function vt(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Ai(t){let e;try{e=Ue()}catch{return null}try{let o=await fetch(`${V()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":pe()}});try{ut(o.headers)}catch{}return o.ok?await o.json():null}catch{return null}}async function Ci(t,e){let o;try{o=Ue()}catch{return!1}try{let n=await fetch(`${V()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...o,"Content-Type":"application/json","X-Mistflow-MCP-Version":pe()},body:JSON.stringify(e)});try{ut(n.headers)}catch{}return n.ok}catch{return!1}}function Ei(t,e){let o=t.toLowerCase(),n=e.toLowerCase();return n.includes(o)||o.includes(n)?!0:o.split(/\s+/).some(a=>a.length>=3&&n.includes(a))}var $e=ze(()=>{"use strict";ie();mt()});var Wn={};Nt(Wn,{ensureBackendRegistered:()=>$i,ensureShadcnComponents:()=>Li});import{existsSync as ns,readFileSync as Ni,writeFileSync as ji}from"fs";import{join as Bt}from"path";import{spawn as Di}from"child_process";function Oi(t,e,o,n,s){return new Promise(a=>{let r=Di(t,e,{cwd:o,stdio:["pipe","pipe","pipe"],timeout:n,...s?{env:{...process.env,...s}}:{}}),i="",l="";r.stdout?.on("data",p=>{i+=p.toString()}),r.stderr?.on("data",p=>{l+=p.toString()}),r.on("close",p=>a({success:p===0,stdout:i,stderr:l})),r.on("error",p=>a({success:!1,stdout:i,stderr:l+p.message}))})}function Mi(t){let e=Bt(t,"mistflow.json");if(!ns(e))return null;try{return JSON.parse(Ni(e,"utf-8"))}catch{return null}}function Ui(t,e){ji(Bt(t,"mistflow.json"),JSON.stringify(e,null,2))}async function ts(t,e){try{let o=e.features,n=e.steps,s={plan:e};Array.isArray(o)&&o.length>0&&(s.features=o.map(a=>a.name)),Array.isArray(n)&&n.length>0&&(s.provenance=n.map(a=>({feature:a.name??a.title??`Step ${a.number??"?"}`,user_intent:(a.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${V()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...Ue(),"Content-Type":"application/json"},body:JSON.stringify(s)})}catch(o){console.error("[self-heal] state sync failed:",o instanceof Error?o.message:String(o))}}async function $i(t,e={}){let o=Mi(t);if(o){if(!G())return o.projectId;if(!o.projectId)try{let s=o.plan?.requestedSubdomain,a=await yt(o.name,void 0,o.dbProvider??"neon",s);return o.projectId=a.id,Ui(t,o),wt(t,vt(a.id,o.name)),o.plan&&await ts(a.id,o.plan),console.error(`[self-heal] registered project ${a.id.slice(0,8)} with backend`),a.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&o.plan&&o.projectId&&await ts(o.projectId,o.plan),o.projectId}}async function Li(t,e){let o=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],n=e&&e.length>0?e:o,s=Bt(t,"components","ui"),a=[],r=[];for(let p of n)ns(Bt(s,`${p}.tsx`))?a.push(p):r.push(p);if(r.length===0)return{installed:[],alreadyPresent:a};let i={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Oi("npx",["--yes","shadcn@latest","add","-y","-o",...r],t,18e4,i);return l.success?{installed:r,alreadyPresent:a}:{installed:[],alreadyPresent:a,failed:`shadcn add failed for: ${r.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Gn=ze(()=>{"use strict";ie();$e()});import{Server as Ic}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as _c}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Tc,ListToolsRequestSchema as Rc}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as Ac}from"zod-to-json-schema";var Nr="mist_plan uses the fire-and-poll shape: the first call returns quickly with status 'running' and a conversationId while the backend Sonnet ask_questions call runs in the background (that call alone can take 30-150s). Poll by calling mist_plan with just { conversationId } every ~10-15s until status is 'clarify' (questions arrived) or 'ready' (plan generated). Do NOT re-send description or answers while polling \u2014 the conversation is already tracked server-side.",jr='Treat the tool\'s returned JSON as authoritative. If `mist_plan` returns `status: "clarify"`, the planning call completed and is waiting on user answers. Do NOT rerun the same call or describe it as "still generating". Only poll again when `status: "design_clarify_pending"`.',Dr="When submitting discovery answers back to `mist_plan` (conversationId + answers), prefer an array payload: `answers: [{question, decisionKey, answer}, ...]`. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",Or="Before scaffolding a NEW app, resolve the destination path explicitly. If the user asked to create/build a new app and the current directory is not already that Mistflow project, ask whether to scaffold in the current folder or a new subfolder here (unless the user already gave a path). Do NOT inspect sibling directories and silently adopt one as the base just because it looks similar. Reuse an existing Mistflow project only when the user explicitly asks to continue/edit that project.",Mr='Once the user approves the plan, the mist_init \u2192 mist_install \u2192 mist_implement (repeat) \u2192 mist_build \u2192 mist_deploy \u2192 mist_qa chain is expected. Do NOT pause between these calls to ask the user "should I continue?" or offer options like "full build vs step-by-step." A tool returns a status that requires user input when it genuinely needs one (e.g. confirm_new_project, awaiting promotion). Otherwise chain calls continuously. Brief one-line status updates are fine; permission requests are not.',Ur="mist_init is all-or-nothing for normal users: it registers the cloud project first, scaffolds in a temp directory, then moves the finished app into place only after both steps succeed. If auth, quota, or network registration fails, stop before any app appears locally. Do NOT suggest reusing another app unless the user explicitly asks.",$r="If mist_init fails, stop before any cloud command and explain why. Do NOT default to reusing some other existing app as recovery unless the user explicitly asked to continue that app.",Lr='Long-running tools (mist_plan, mist_install, mist_build, mist_qa, mist_deploy) use the fire-and-poll pattern. The first call returns `status: "running"` with a `jobId` or `conversationId`. Every subsequent call with that same id returns the current state \u2014 re-call IMMEDIATELY whenever you see `status: "running"`. DO NOT run `bash sleep`, `setTimeout`, or any wall-clock wait between polls \u2014 Claude Code\'s harness blocks standalone sleeps, and every MCP server poll endpoint holds the connection up to ~10-15s on its side already, returning as soon as state changes. Just call the tool again. Each response is well inside the 60s MCP ceiling. When `status: "complete"` or `"failed"` arrives, the tool is done. Never assume a job stalled because a single call took 10s \u2014 calls return fast, but the work keeps running in the background. Do not ask the user whether to keep polling; polling is how these tools work.',Fr="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST render every question via your native structured-question UI \u2014 `AskUserQuestion` in Claude Code, quick pick in Cursor, equivalent in other hosts \u2014 and wait for the user to actually answer. Do NOT pick the `recommended` option on their behalf. Do NOT print the questions as a markdown list with a 'say the word if you want to change any' fallback. Do NOT proceed without real answers even if you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode \u2014 if the user isn't available, stop and wait; the flow resumes when they respond. Every question is a product decision the user is paying to make, and `recommended` is a hint for them, not a permission slip for you. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to do that step.",ko="Connect the user's Mistflow account. Call this ONLY when: (a) the user has literally never signed in, or (b) a previous tool call returned error code 'auth_missing' or 'auth_revoked'. DO NOT call this tool in response to 500 errors, 404 errors, network errors, or any generic failure \u2014 those are backend issues, not auth issues. Running mist_setup when not needed wastes the user's time and creates login fatigue. Once signed in, the MCP persists a long-lived API key and never asks again. Two-phase device code flow: (1) Call without deviceCode \u2014 opens browser, returns status 'pending' with deviceCode and userCode. Tell the user the verification code and that they need to approve in the browser. (2) Call again with deviceCode after ~15 seconds \u2014 polls for approval. Also accepts an apiKey for headless auth (skips device code entirely).",So="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'landing-designs' / 'integrations' browse curated catalogs (pass presetId / integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",Po="Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",Io="Returns the full Mistflow MCP tool reference. Call ONCE at session start (or whenever unsure which tool to pick) to learn the 14-tool surface, the fire-and-poll pattern, and how to chain end-to-end from mist_plan through mist_qa. Static \u2014 no backend round-trip, safe to call frequently.",_o="Analyze build errors from a Next.js / TypeScript project. Extracts structured errors with file, line, a human-readable message for the user, and an actionable suggestion. Call with { projectPath } to run `npm run build` and parse the failure; call with { buildOutput } to parse output captured elsewhere (e.g. from a failed mist_build job).",To="Generate a grayscale wireframe sketch of the planned app so the user can review layout + information hierarchy before any code is written. The server returns a structured spec + a wireframePrompt \u2014 the host AI writes the HTML file to .mistflow/mockups/mockup-<planId>.html and opens it. Pass { planId } for the first iteration, { planId, feedback: '...' } to iterate, { planId, approved: true } to lock the design before mist_init. Iterative by design \u2014 expect 1-3 rounds of feedback.";function Ro(){let t=[];return t.push("Mistflow is a full-stack app builder that creates and deploys web apps from natural language descriptions. When a user asks to build, create, or make a web app, website, landing page, dashboard, internal tool, marketplace, content site, or browser game, use Mistflow tools. Mistflow creates NEW apps from scratch. It does NOT modify existing non-Mistflow codebases."),t.push(""),t.push('Every capability is an MCP tool. There is no companion CLI. Long-running work (install, build, qa, deploy) uses the fire-and-poll pattern: the first call returns a jobId and `status: "running"`; subsequent calls with that jobId return fresh state. Each call responds in under a second \u2014 no 60s timeout risk.'),t.push(""),t.push(Lr),t.push(""),t.push(Nr),t.push(""),t.push(jr),t.push(""),t.push(Dr),t.push(""),t.push(Or),t.push(""),t.push(Fr),t.push(""),t.push(Ur),t.push(""),t.push("New app workflow:"),t.push("1. Choose destination: if the user didn't already give a path, ask whether to scaffold in the current folder or a new subfolder here. Resolve the absolute path before mist_init."),t.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via AskUserQuestion, collect the answers, and submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick.'),t.push("3. Mockup (optional, recommended): call mist_mockup with the planId \u2014 returns a wireframe prompt. Write the HTML to the returned path, open it for the user, wait for approval. Iterate with { feedback }, lock with { approved: true }."),t.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),t.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),t.push("6. Implement: mist_implement runs one plan step at a time and auto-marks the prior step complete. Call repeatedly until all steps are done."),t.push("7. Build: mist_build { projectPath } starts; poll with { jobId }. On failure, the response has `missingModules[]` \u2014 chain mist_install with those modules then mist_build again without asking."),t.push("8. Deploy: mist_deploy { projectPath } starts tar + upload; poll with { action: 'status', deploymentId }. On complete, response has `qaRequired: true` and a `url` \u2014 do NOT surface the URL to the user until mist_qa passes. Subsequent actions: 'promote' (staging \u2192 prod), 'rollback' (revert to a specific deploymentId)."),t.push("9. QA: mist_qa { projectPath } starts Playwright; poll with { jobId }. Only surface the deploy URL to the user after QA exits 0."),t.push(""),t.push(Mr),t.push(""),t.push($r),t.push(""),t.push("Updating an existing Mistflow app:"),t.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),t.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),t.push("- Feature needing new data model: ask product questions, call mist_project action='get' for context, call mist_plan with existingPlanId, then mist_implement, then mist_build \u2192 mist_deploy."),t.push("- Integration addition: ask product questions, mist_project action='get', mist_plan with existingPlanId, mist_implement, mist_config resource='env' for keys, mist_build \u2192 mist_deploy \u2192 mist_qa."),t.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),t.push(""),t.push("Tool summary:"),t.push("- mist_setup: authentication. Only call when the user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth."),t.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),t.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),t.push("- mist_help: returns the full tool reference. Call once per session."),t.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),t.push("- mist_install / mist_build / mist_qa / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),t.join(`
25
- `)}mt();function c(t,e=!1){let o=t;try{let n=Oo();n&&(o=t+n)}catch{}return{content:[{type:"text",text:o}],isError:e}}function ke(t){return c(`This is not a Mistflow project (no mistflow.json found at ${t}).
22
+ (Mistflow ${s.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function vn(){let t=be(),e=ye??{latest:"",minSupported:"",changelogUrl:""},s=Ms(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:s,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:ye!==null}}var Ot,ye,js,ft=Qe(()=>{"use strict";Ot=null;ye=null;js=!1});var Sn={};Dt(Sn,{closeBrowser:()=>kn,getIsolatedContext:()=>ti,getPage:()=>xn,getSnapshot:()=>yt,takeScreenshot:()=>bt});async function Ls(){try{return await import("playwright")}catch{throw new Error("Playwright is not installed. Run: cd packages/mcp-server && pnpm add playwright && npx playwright install chromium")}}async function ei(){let t=await Ls();return(!we||!we.isConnected())&&(we=await t.chromium.launch({headless:!0})),je&&(await je.close().catch(()=>{}),je=null),je=await we.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Ie=await je.newPage(),Ie}async function xn(){return Ie&&!Ie.isClosed()?Ie:($t||($t=ei().finally(()=>{$t=null})),$t)}async function kn(){Ie&&!Ie.isClosed()&&await Ie.close().catch(()=>{}),je&&await je.close().catch(()=>{}),we?.isConnected()&&await we.close().catch(()=>{}),Ie=null,je=null,we=null}async function ti(){let t=await Ls();(!we||!we.isConnected())&&(we=await t.chromium.launch({headless:!0}));let e=await we.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),s=await e.newPage();return{context:e,page:s}}async function yt(t){return await t.locator("body").ariaSnapshot()}async function bt(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var we,je,Ie,$t,Ut=Qe(()=>{"use strict";we=null,je=null,Ie=null,$t=null;process.once("SIGTERM",()=>{kn().finally(()=>process.exit(0))});process.once("SIGINT",()=>{kn().finally(()=>process.exit(0))})});import{readFileSync as qs,existsSync as Pn,writeFileSync as ni,mkdirSync as si,renameSync as oi,unlinkSync as ri}from"fs";import{join as In,dirname as ii}from"path";import{homedir as ai}from"os";import{randomBytes as li}from"crypto";function Bs(){return In(ai(),".mistflow","credentials.json")}function Lt(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function zs(){let t=Bs();if(!Pn(t))return null;try{let e=JSON.parse(qs(t,"utf-8"));return typeof e.apiKey=="string"?{[ci]:e}:e}catch{return null}}function Xe(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=zs();if(!e)return{ok:!1,reason:"missing"};let s=Lt(),n=e[s];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function Tn(t){let e=Bs(),s=ii(e);Pn(s)||si(s,{recursive:!0});let n=zs()??{},o=Lt();n[o]=t;let i=In(s,`.credentials.tmp.${li(8).toString("hex")}`);try{ni(i,JSON.stringify(n,null,2)+`
23
+ `,{mode:384}),oi(i,e)}catch(r){try{ri(i)}catch{}throw r}}function X(){return Xe().ok}function De(t){let e=In(t,"mistflow.json");if(!Pn(e))return null;try{return JSON.parse(qs(e,"utf-8"))}catch{return null}}var ci,Ze=Qe(()=>{"use strict";ci="https://api.mistflow.ai"});var Ys={};Dt(Ys,{MistflowApiError:()=>U,addDomain:()=>Nn,checkAuth:()=>mi,checkAuthDetailed:()=>Vs,checkSubdomain:()=>Rn,createDeployment:()=>gi,createProject:()=>vt,deleteEnvVar:()=>Un,discoverDecisions:()=>fi,downloadSource:()=>wi,downloadSourceWithToken:()=>Js,fetchDesignDirections:()=>An,fetchModule:()=>Wn,fetchPlanConversation:()=>qt,fetchScaffold:()=>zn,fetchStepContext:()=>Hn,forkTemplate:()=>Vn,generatePlan:()=>En,getAuthHeaders:()=>Ge,getBaseUrl:()=>Z,getDashboardUrl:()=>di,getDbCredentials:()=>yi,getDeployLogs:()=>Ln,getDeploymentStatus:()=>xt,getProject:()=>hi,getProjectErrors:()=>Fn,getSeedInfo:()=>Dn,getSiteUrl:()=>et,getTemplate:()=>Gn,hasCredentialsOnDisk:()=>X,hasLocalCredentials:()=>Gs,listDeployments:()=>nt,listDomains:()=>Oe,listEnvVars:()=>Mn,markLocalSetupDone:()=>vi,modifyPlan:()=>Bt,pingBackend:()=>_n,promotePreview:()=>qn,redeployProject:()=>bi,removeDomain:()=>jn,rollbackDeployment:()=>Bn,shareProject:()=>Jn,uploadAndDeploy:()=>Cn,uploadQAResults:()=>On,upsertEnvVar:()=>$n,verifyDomain:()=>zt});function Z(){return Lt()}function et(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9102")}return"https://mistflow.ai"}function di(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function Ge(){let t=Xe();if(!t.ok)throw new U("auth_missing","No Mistflow credentials found.",401);return pi(t.creds)}function pi(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":be()}}function tt(t){try{gt(t.headers)}catch{}}async function _n(){try{let t=await fetch(`${Z()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});tt(t)}catch{}}async function Ws(t,e,s,n){for(let o=0;o<2;o++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(s)})}catch(i){let r=i instanceof Error&&i.name==="TimeoutError",a=i instanceof TypeError;if(n&&o===0&&(r||a)){console.error(`[api] Retrying ${t} after ${r?"timeout":"network error"}`);continue}throw i}throw new Error("fetchWithRetry: exhausted retries")}async function wt(t){let e=null;try{e=await t.json()}catch{e=null}let s=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(s)return new U(s,n,t.status,e?.details);let o=t.status;return o===401?new U("auth_invalid",n,o):o===403?new U("permission_denied",n,o):o===404?new U("not_found",n,o):o===409?new U("conflict",n,o):o===422?new U("validation_error",n,o):o===429?new U("rate_limited",n,o):o>=500?new U("server_error",t.statusText||"Internal server error",o):new U("client_error",n,o)}async function L(t,e={}){let s=Ge(),{timeoutMs:n,idempotent:o,...i}=e,r=n??3e4,a=(i.method??"GET").toUpperCase(),l=o??(a==="GET"||a==="HEAD"),d;try{d=await Ws(`${Z()}${t}`,{...i,headers:{...s,...i.headers}},r,l)}catch(h){throw h instanceof Error&&h.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(tt(d),!d.ok)throw await wt(d);return d.json()}function Gs(){return Xe().ok}async function mi(){return(await Vs()).ok}async function Vs(){if(Ft!==null&&Date.now()<Hs)return Ft?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Gs())return{ok:!1,reason:"no_credentials"};try{return await L("/api/org"),Ft=!0,Hs=Date.now()+ui,{ok:!0}}catch(t){if(Ft=null,!(t instanceof U))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function hi(t){return L(`/api/projects/${encodeURIComponent(t)}`)}async function Rn(t){return L(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function vt(t,e,s="neon",n){return L("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e,db_provider:s,requested_subdomain:n})})}async function gi(t,e){return L("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function Cn(t,e,s="production",n,o,i,r){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),d=Xe();if(!d.ok)throw new U("auth_missing","No Mistflow credentials found.",401);let h=d.creds,m=a(e),p=new Blob([m],{type:"application/gzip"}),y=new FormData;if(y.append("project_id",t),y.append("build",p,l(e)),s!=="production"&&y.append("environment",s),n&&y.append("admin_email",n),o&&y.append("schema_pushed","true"),i){let{existsSync:f}=await import("fs");if(f(i)){let k=a(i),_=new Blob([k],{type:"application/gzip"});y.append("source",_,"source.tar.gz")}}r&&y.append("git_commit_sha",r);let v;try{v=await fetch(`${Z()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":be()},body:y,signal:AbortSignal.timeout(3e5)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(tt(v),!v.ok)throw await wt(v);let b=await v.json();return{...b,id:b.deployment_id}}async function xt(t){return L(`/api/deploy/${encodeURIComponent(t)}/status`)}async function An(t){return L(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function qt(t,e){let s=e?.waitSeconds??20,n=s>0?`?wait=${s}`:"",o=Math.min(6e4,(s+5)*1e3);return L(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:o})}async function En(t,e){let s={description:t,conversation_id:e?.conversationId,answers:e?.answers};e?.autonomous&&(s.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(s.language=e.language),e?.designConversationId&&(s.design_conversation_id=e.designConversationId),e?.designDirection&&(s.design_direction=e.designDirection);let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return L("/api/plan",{method:"POST",body:JSON.stringify(s),timeoutMs:n,idempotent:!1})}async function Bt(t,e){return L("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function fi(t){return L("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Nn(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function Oe(t){return L(`/api/projects/${encodeURIComponent(t)}/domains`)}async function zt(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function jn(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function yi(t){return L(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Dn(t){try{return await L(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof U&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function On(t,e){try{return await L(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(s){return console.error("[api] Failed to upload QA results:",s instanceof Error?s.message:s),null}}async function Mn(t){return L(`/api/projects/${encodeURIComponent(t)}/env`)}async function $n(t,e,s,n){return L(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:s,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function Un(t,e){return L(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ln(t){return L(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Fn(t,e="7d"){return L(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function nt(t){return L(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function bi(t){return L(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function qn(t,e){let s=new URLSearchParams({preview_deployment_id:e});return L(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:s.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Bn(t){return L(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function wi(t,e){let s=Xe();if(!s.ok)throw new U("auth_missing","Not authenticated.",401);let n=s.creds,o=await fetch(`${Z()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":be()},signal:AbortSignal.timeout(12e4)});if(tt(o),!o.ok)throw await wt(o);let{writeFileSync:i}=await import("fs"),r=Buffer.from(await o.arrayBuffer());i(e,r)}async function Ht(t,e){let{timeoutMs:s,idempotent:n,...o}=e??{},i=s??3e4,r=(o.method??"GET").toUpperCase(),a=n??(r==="GET"||r==="HEAD"),l;try{l=await Ws(`${Z()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":be()},...o},i,a)}catch(d){throw d instanceof Error&&d.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(tt(l),!l.ok)throw await wt(l);return l.json()}async function zn(t="nextjs"){return Ht(`/api/scaffold/${encodeURIComponent(t)}`)}async function Hn(t,e){return Ht(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Wn(t,e,s,n){return Ht(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:s,entity_plural:n})})}async function Gn(t){return Ht(`/api/templates/${encodeURIComponent(t)}`)}async function Vn(t){return L(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Js(t,e,s){let n;try{n=await fetch(`${Z()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":be()},signal:AbortSignal.timeout(12e4)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(tt(n),!n.ok)throw n.status===401?new U("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await wt(n);let{writeFileSync:o}=await import("fs"),i=Buffer.from(await n.arrayBuffer());o(s,i)}async function vi(t){await L(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Jn(t,e){return L(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}var U,Ft,Hs,ui,de=Qe(()=>{"use strict";Ze();ft();U=class extends Error{constructor(s,n,o,i){super(n);this.code=s;this.statusCode=o;this.details=i;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};Ft=null,Hs=0,ui=300*1e3});var Pt={};Dt(Pt,{emptyState:()=>St,fetchRemoteState:()=>ji,fuzzyMatch:()=>Oi,getLocalStatePath:()=>Kn,readLocalState:()=>Ni,syncRemoteState:()=>Di,writeLocalState:()=>kt});import{existsSync as to,readFileSync as Ci,writeFileSync as Ai,mkdirSync as Ei}from"fs";import{join as no}from"path";function Kn(t){return no(t,".mistflow","state.json")}function Ni(t){let e=Kn(t);if(!to(e))return null;try{return JSON.parse(Ci(e,"utf-8"))}catch{return null}}function kt(t,e){let s=no(t,".mistflow");to(s)||Ei(s,{recursive:!0}),Ai(Kn(t),JSON.stringify(e,null,2)+`
24
+ `)}function St(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function ji(t){let e;try{e=Ge()}catch{return null}try{let s=await fetch(`${Z()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":be()}});try{gt(s.headers)}catch{}return s.ok?await s.json():null}catch{return null}}async function Di(t,e){let s;try{s=Ge()}catch{return!1}try{let n=await fetch(`${Z()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...s,"Content-Type":"application/json","X-Mistflow-MCP-Version":be()},body:JSON.stringify(e)});try{gt(n.headers)}catch{}return n.ok}catch{return!1}}function Oi(t,e){let s=t.toLowerCase(),n=e.toLowerCase();return n.includes(s)||s.includes(n)?!0:s.split(/\s+/).some(i=>i.length>=3&&n.includes(i))}var Ve=Qe(()=>{"use strict";de();ft()});var Qn={};Dt(Qn,{ensureBackendRegistered:()=>Bi,ensureShadcnComponents:()=>zi});import{existsSync as oo,readFileSync as Mi,writeFileSync as $i}from"fs";import{join as Wt}from"path";import{spawn as Ui}from"child_process";function Li(t,e,s,n,o){return new Promise(i=>{let r=Ui(t,e,{cwd:s,stdio:["pipe","pipe","pipe"],timeout:n,...o?{env:{...process.env,...o}}:{}}),a="",l="";r.stdout?.on("data",d=>{a+=d.toString()}),r.stderr?.on("data",d=>{l+=d.toString()}),r.on("close",d=>i({success:d===0,stdout:a,stderr:l})),r.on("error",d=>i({success:!1,stdout:a,stderr:l+d.message}))})}function Fi(t){let e=Wt(t,"mistflow.json");if(!oo(e))return null;try{return JSON.parse(Mi(e,"utf-8"))}catch{return null}}function qi(t,e){$i(Wt(t,"mistflow.json"),JSON.stringify(e,null,2))}async function so(t,e){try{let s=e.features,n=e.steps,o={plan:e};Array.isArray(s)&&s.length>0&&(o.features=s.map(i=>i.name)),Array.isArray(n)&&n.length>0&&(o.provenance=n.map(i=>({feature:i.name??i.title??`Step ${i.number??"?"}`,user_intent:(i.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${Z()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...Ge(),"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(s){console.error("[self-heal] state sync failed:",s instanceof Error?s.message:String(s))}}async function Bi(t,e={}){let s=Fi(t);if(s){if(!X())return s.projectId;if(!s.projectId)try{let o=s.plan?.requestedSubdomain,i=await vt(s.name,void 0,s.dbProvider??"neon",o);return s.projectId=i.id,qi(t,s),kt(t,St(i.id,s.name)),s.plan&&await so(i.id,s.plan),console.error(`[self-heal] registered project ${i.id.slice(0,8)} with backend`),i.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&s.plan&&s.projectId&&await so(s.projectId,s.plan),s.projectId}}async function zi(t,e){let s=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],n=e&&e.length>0?e:s,o=Wt(t,"components","ui"),i=[],r=[];for(let d of n)oo(Wt(o,`${d}.tsx`))?i.push(d):r.push(d);if(r.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Li("npx",["--yes","shadcn@latest","add","-y","-o",...r],t,18e4,a);return l.success?{installed:r,alreadyPresent:i}:{installed:[],alreadyPresent:i,failed:`shadcn add failed for: ${r.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Xn=Qe(()=>{"use strict";de();Ve()});import{Server as Mc}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as $c}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Uc,ListToolsRequestSchema as Lc}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as Fc}from"zod-to-json-schema";var Ur="mist_plan uses the fire-and-poll shape: the first call returns quickly with status 'running' and a conversationId while the backend Sonnet ask_questions call runs in the background (that call alone can take 30-150s). Poll by calling mist_plan with just { conversationId } every ~10-15s until status is 'clarify' (questions arrived) or 'ready' (plan generated). Do NOT re-send description or answers while polling \u2014 the conversation is already tracked server-side.",Lr='Treat the tool\'s returned JSON as authoritative. If `mist_plan` returns `status: "clarify"`, the planning call completed and is waiting on user answers. Do NOT rerun the same call or describe it as "still generating". Only poll again when `status: "design_clarify_pending"`.',Fr="When submitting discovery answers back to `mist_plan` (conversationId + answers), prefer an array payload: `answers: [{question, decisionKey, answer}, ...]`. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",qr="Before scaffolding a NEW app, resolve the destination path explicitly. If the user asked to create/build a new app and the current directory is not already that Mistflow project, ask whether to scaffold in the current folder or a new subfolder here (unless the user already gave a path). Do NOT inspect sibling directories and silently adopt one as the base just because it looks similar. Reuse an existing Mistflow project only when the user explicitly asks to continue/edit that project.",Br='Once the user approves the plan, the mist_init \u2192 mist_install \u2192 mist_implement (repeat) \u2192 mist_build \u2192 mist_deploy \u2192 mist_qa chain is expected. Do NOT pause between these calls to ask the user "should I continue?" or offer options like "full build vs step-by-step." A tool returns a status that requires user input when it genuinely needs one (e.g. confirm_new_project, awaiting promotion). Otherwise chain calls continuously. Brief one-line status updates are fine; permission requests are not.',zr="mist_init is all-or-nothing for normal users: it registers the cloud project first, scaffolds in a temp directory, then moves the finished app into place only after both steps succeed. If auth, quota, or network registration fails, stop before any app appears locally. Do NOT suggest reusing another app unless the user explicitly asks.",Hr="If mist_init fails, stop before any cloud command and explain why. Do NOT default to reusing some other existing app as recovery unless the user explicitly asked to continue that app.",Wr='Long-running tools (mist_plan, mist_install, mist_build, mist_qa, mist_deploy) use the fire-and-poll pattern. The first call returns `status: "running"` with a `jobId` or `conversationId`. Every subsequent call with that same id returns the current state \u2014 re-call IMMEDIATELY whenever you see `status: "running"`. DO NOT run `bash sleep`, `setTimeout`, or any wall-clock wait between polls \u2014 Claude Code\'s harness blocks standalone sleeps, and every MCP server poll endpoint holds the connection up to ~10-15s on its side already, returning as soon as state changes. Just call the tool again. Each response is well inside the 60s MCP ceiling. When `status: "complete"` or `"failed"` arrives, the tool is done. Never assume a job stalled because a single call took 10s \u2014 calls return fast, but the work keeps running in the background. Do not ask the user whether to keep polling; polling is how these tools work.',Gr="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST render every question via your native structured-question UI \u2014 `AskUserQuestion` in Claude Code, quick pick in Cursor, equivalent in other hosts \u2014 and wait for the user to actually answer. Do NOT pick the `recommended` option on their behalf. Do NOT print the questions as a markdown list with a 'say the word if you want to change any' fallback. Do NOT proceed without real answers even if you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode \u2014 if the user isn't available, stop and wait; the flow resumes when they respond. Every question is a product decision the user is paying to make, and `recommended` is a hint for them, not a permission slip for you. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to do that step.",Is="Connect the user's Mistflow account. Call this ONLY when: (a) the user has literally never signed in, or (b) a previous tool call returned error code 'auth_missing' or 'auth_revoked'. DO NOT call this tool in response to 500 errors, 404 errors, network errors, or any generic failure \u2014 those are backend issues, not auth issues. Running mist_setup when not needed wastes the user's time and creates login fatigue. Once signed in, the MCP persists a long-lived API key and never asks again. Two-phase device code flow: (1) Call without deviceCode \u2014 opens browser, returns status 'pending' with deviceCode and userCode. Tell the user the verification code and that they need to approve in the browser. (2) Call again with deviceCode after ~15 seconds \u2014 polls for approval. Also accepts an apiKey for headless auth (skips device code entirely).",Ts="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'landing-designs' / 'integrations' browse curated catalogs (pass presetId / integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",_s="Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",Rs="Returns the full Mistflow MCP tool reference. Call ONCE at session start (or whenever unsure which tool to pick) to learn the 14-tool surface, the fire-and-poll pattern, and how to chain end-to-end from mist_plan through mist_qa. Static \u2014 no backend round-trip, safe to call frequently.",Cs="Analyze build errors from a Next.js / TypeScript project. Extracts structured errors with file, line, a human-readable message for the user, and an actionable suggestion. Call with { projectPath } to run `npm run build` and parse the failure; call with { buildOutput } to parse output captured elsewhere (e.g. from a failed mist_build job).",As="Generate a grayscale wireframe sketch of the planned app so the user can review layout + information hierarchy before any code is written. The server returns a structured spec + a wireframePrompt \u2014 the host AI writes the HTML file to .mistflow/mockups/mockup-<planId>.html and opens it. Pass { planId } for the first iteration, { planId, feedback: '...' } to iterate, { planId, approved: true } to lock the design before mist_init. Iterative by design \u2014 expect 1-3 rounds of feedback.";function Es(){let t=[];return t.push("Mistflow is a full-stack app builder that creates and deploys web apps from natural language descriptions. When a user asks to build, create, or make a web app, website, landing page, dashboard, internal tool, marketplace, content site, or browser game, use Mistflow tools. Mistflow creates NEW apps from scratch. It does NOT modify existing non-Mistflow codebases."),t.push(""),t.push('Every capability is an MCP tool. There is no companion CLI. Long-running work (install, build, qa, deploy) uses the fire-and-poll pattern: the first call returns a jobId and `status: "running"`; subsequent calls with that jobId return fresh state. Each call responds in under a second \u2014 no 60s timeout risk.'),t.push(""),t.push(Wr),t.push(""),t.push(Ur),t.push(""),t.push(Lr),t.push(""),t.push(Fr),t.push(""),t.push(qr),t.push(""),t.push(Gr),t.push(""),t.push(zr),t.push(""),t.push("New app workflow:"),t.push("1. Choose destination: if the user didn't already give a path, ask whether to scaffold in the current folder or a new subfolder here. Resolve the absolute path before mist_init."),t.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via AskUserQuestion, collect the answers, and submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick.'),t.push("3. Mockup (optional, recommended): call mist_mockup with the planId \u2014 returns a wireframe prompt. Write the HTML to the returned path, open it for the user, wait for approval. Iterate with { feedback }, lock with { approved: true }."),t.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),t.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),t.push("6. Implement: mist_implement runs one plan step at a time and auto-marks the prior step complete. Call repeatedly until all steps are done."),t.push("7. Build: mist_build { projectPath } starts; poll with { jobId }. On failure, the response has `missingModules[]` \u2014 chain mist_install with those modules then mist_build again without asking."),t.push("8. Deploy: mist_deploy { projectPath } starts tar + upload; poll with { action: 'status', deploymentId }. On complete, response has `qaRequired: true` and a `url` \u2014 do NOT surface the URL to the user until mist_qa passes. Subsequent actions: 'promote' (staging \u2192 prod), 'rollback' (revert to a specific deploymentId)."),t.push("9. QA: mist_qa { projectPath } drives Playwright in-process against the live URL \u2014 single synchronous call (~20\u201345s), returns pass/fail and screenshots inline. Only surface the deploy URL to the user after mist_qa returns status: 'pass'."),t.push(""),t.push(Br),t.push(""),t.push(Hr),t.push(""),t.push("Updating an existing Mistflow app:"),t.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),t.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),t.push("- Feature needing new data model: ask product questions, call mist_project action='get' for context, call mist_plan with existingPlanId, then mist_implement, then mist_build \u2192 mist_deploy."),t.push("- Integration addition: ask product questions, mist_project action='get', mist_plan with existingPlanId, mist_implement, mist_config resource='env' for keys, mist_build \u2192 mist_deploy \u2192 mist_qa."),t.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),t.push(""),t.push("Tool summary:"),t.push("- mist_setup: authentication. Only call when the user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth."),t.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),t.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),t.push("- mist_help: returns the full tool reference. Call once per session."),t.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),t.push("- mist_install / mist_build / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),t.push("- mist_qa: synchronous single call. Drives Playwright in-process against the deployed URL. No jobId / no polling \u2014 one call returns the full QA result with screenshots."),t.join(`
25
+ `)}ft();function c(t,e=!1){let s=t;try{let n=Us();n&&(s=t+n)}catch{}return{content:[{type:"text",text:s}],isError:e}}function Te(t){return c(`This is not a Mistflow project (no mistflow.json found at ${t}).
26
26
 
27
27
  Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
28
28
 
@@ -31,17 +31,17 @@ To get started:
31
31
  2. Call mist_init({ planId, path: "<absolute-path>" })
32
32
  3. Call mist_install({ projectPath }), then mist_implement({ projectPath })
33
33
 
34
- If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function $o(t,e){try{let{getPage:o,takeScreenshot:n}=await Promise.resolve().then(()=>(wn(),Uo)),s=await o();await s.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await s.waitForLoadState("networkidle").catch(()=>{});let a=await n(s,!1);return{content:[{type:"text",text:e},{type:"image",data:a.toString("base64"),mimeType:"image/png"}]}}catch{return c(e)}}import{z as zn}from"zod";import{platform as yi}from"os";import{execFile as Jo}from"child_process";ie();We();var bi=zn.object({apiKey:zn.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:zn.string().optional().describe("Resume polling for a pending device code. Returned by a previous mist_setup call with status 'pending'. Call mist_setup again with this value after ~15 seconds to check if the user approved.")});function wi(t){return"error"in t}function Yo(t){return new Promise(e=>setTimeout(e,t))}function vi(t){return new Promise(e=>{let o=yi();o==="win32"?Jo("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):Jo(o==="darwin"?"open":"xdg-open",[t],s=>{s&&console.error("Could not open browser:",s.message),e(!s)}),setTimeout(()=>e(!1),5e3)})}var xi={fetch:globalThis.fetch,openBrowser:vi,sleep:Yo};async function Ko(t,e,o,n){let s=o,a=n.sleep??Yo;for(let r=0;r<e;r++){await a(s);let i;try{let p=await n.fetch(`${V()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!p.ok)continue;i=await p.json()}catch{continue}if(wi(i))switch(i.error){case"authorization_pending":continue;case"slow_down":s+=5e3;continue;case"expired_token":return c("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return c("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return c("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=i.email||i.org_name||i.org_slug;return kn({apiKey:i.api_key,apiKeyId:i.api_key_id,apiKeyName:i.api_key_name,orgId:i.org_id,orgSlug:i.org_slug,email:i.email}),c(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function ki(t,e=xi){let o=t;if(o?.apiKey)try{let r=await e.fetch(`${V()}/api/org`,{headers:{Authorization:`ApiKey ${o.apiKey}`}});if(!r.ok)return c("Invalid API key. Check the key and try again.",!0);let i=await r.json();return kn({apiKey:o.apiKey,orgId:i.id,orgSlug:i.slug}),c(`Connected to Mistflow as ${i.slug} via API key. You are ready to build and deploy.`)}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(o?.deviceCode){let r=await Ko(o.deviceCode,6,5e3,e);return r||c(JSON.stringify({status:"pending",deviceCode:o.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let r=await e.fetch(`${V()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!r.ok)return c("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await r.json()}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}let s=`${n.verification_uri}?code=${n.user_code}`;console.error(`
35
- Sign in at: ${s}
34
+ If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Fs(t,e){try{let{getPage:s,takeScreenshot:n}=await Promise.resolve().then(()=>(Ut(),Sn)),o=await s();await o.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{});let i=await n(o,!1);return{content:[{type:"text",text:e},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}catch{return c(e)}}import{z as Yn}from"zod";import{platform as xi}from"os";import{execFile as Ks}from"child_process";de();Ze();var ki=Yn.object({apiKey:Yn.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:Yn.string().optional().describe("Resume polling for a pending device code. Returned by a previous mist_setup call with status 'pending'. Call mist_setup again with this value after ~15 seconds to check if the user approved.")});function Si(t){return"error"in t}function Xs(t){return new Promise(e=>setTimeout(e,t))}function Pi(t){return new Promise(e=>{let s=xi();s==="win32"?Ks("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):Ks(s==="darwin"?"open":"xdg-open",[t],o=>{o&&console.error("Could not open browser:",o.message),e(!o)}),setTimeout(()=>e(!1),5e3)})}var Ii={fetch:globalThis.fetch,openBrowser:Pi,sleep:Xs};async function Qs(t,e,s,n){let o=s,i=n.sleep??Xs;for(let r=0;r<e;r++){await i(o);let a;try{let d=await n.fetch(`${Z()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!d.ok)continue;a=await d.json()}catch{continue}if(Si(a))switch(a.error){case"authorization_pending":continue;case"slow_down":o+=5e3;continue;case"expired_token":return c("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return c("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return c("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=a.email||a.org_name||a.org_slug;return Tn({apiKey:a.api_key,apiKeyId:a.api_key_id,apiKeyName:a.api_key_name,orgId:a.org_id,orgSlug:a.org_slug,email:a.email}),c(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function Ti(t,e=Ii){let s=t;if(s?.apiKey)try{let r=await e.fetch(`${Z()}/api/org`,{headers:{Authorization:`ApiKey ${s.apiKey}`}});if(!r.ok)return c("Invalid API key. Check the key and try again.",!0);let a=await r.json();return Tn({apiKey:s.apiKey,orgId:a.id,orgSlug:a.slug}),c(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(s?.deviceCode){let r=await Qs(s.deviceCode,6,5e3,e);return r||c(JSON.stringify({status:"pending",deviceCode:s.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let r=await e.fetch(`${Z()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!r.ok)return c("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await r.json()}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}let o=`${n.verification_uri}?code=${n.user_code}`;console.error(`
35
+ Sign in at: ${o}
36
36
  Your code: ${n.user_code}
37
- `);try{await e.openBrowser(s)}catch{}let a=await Ko(n.device_code,6,5e3,e);return a||c(JSON.stringify({status:"pending",deviceCode:n.device_code,signInUrl:s,userCode:n.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+n.device_code+"' to check if they approved."}))}var Qo={name:"mist_setup",description:ko,inputSchema:bi,handler:t=>ki(t)};import{z as Z}from"zod";import{resolve as Ht}from"path";import{existsSync as Wt,readFileSync as Gt}from"fs";import{join as Vt}from"path";import{z as Re}from"zod";import{resolve as Fi,join as os}from"path";import{existsSync as qi,readFileSync as ss,writeFileSync as Bi}from"fs";import{existsSync as Si,readFileSync as Pi}from"fs";function Xo(t){let e=new Set;if(!Si(t))return e;let o=Pi(t,"utf-8");for(let n of o.split(`
38
- `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a>0){let r=s.slice(0,a).trim(),i=s.slice(a+1).trim();i&&i!=='""'&&i!=="''"&&e.add(r)}}return e}var zi=Re.object({action:Re.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:Re.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:Re.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:Re.object({key:Re.string(),description:Re.string().optional(),setupUrl:Re.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),rs={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Called internally by mist_project; host AIs should use mist_project directly.",inputSchema:zi,handler:async t=>{let e=t,o=Fi(e.projectPath??process.cwd()),n=os(o,"mistflow.json");if(!qi(n))return ke(o);let s;try{s=JSON.parse(ss(n,"utf-8"))}catch{return c("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!s.projectId)try{let{ensureBackendRegistered:y}=await Promise.resolve().then(()=>(Gn(),Wn));await y(o)&&(s=JSON.parse(ss(n,"utf-8")))}catch{}let i=s.plan,l=i?.steps?.filter(y=>y.status==="completed").length??0,p=i?.steps?.length??0,m=Xo(os(o,".env.local")),u=s.env?.required?Object.entries(s.env.required).map(([y,x])=>({name:y,description:x?.description,configured:m.has(y)})):[];s.projectId&&Promise.resolve().then(()=>($e(),xt)).then(({fetchRemoteState:y})=>y(s.projectId)).catch(()=>{});let d=[`Project: ${s.name}`];if(i){d.push(`Plan: ${i.summary??i.name??"unnamed"} \u2014 ${l}/${p} steps complete`);for(let y of i.steps){let x=y.status==="completed"?"\u2713":y.status==="in_progress"?"\u2192":" ";d.push(` [${x}] ${y.number}. ${y.name}`)}}let b=u.filter(y=>!y.configured);b.length>0&&d.push(`Missing env vars: ${b.map(y=>y.name).join(", ")}`),s.deploy?.url?d.push(`Deployed: ${s.deploy.url} (${s.deploy.count??0} deploys)`):d.push("Not deployed yet");let T=[],w=i?.steps?.find(y=>y.status!=="completed");return w?T.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${w.number} (${w.name}).`):i&&l===p&&(s.deploy?.url||T.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),b.length>0&&T.push(`Missing env vars in .env.local: ${b.map(y=>y.name).join(", ")}`),c(JSON.stringify({name:s.name,projectId:s.projectId,planProgress:i?{name:i.name,summary:i.summary,totalSteps:p,completedSteps:l,steps:i.steps}:null,envStatus:u,deploy:s.deploy??null,contextMessage:d.join(`
39
- `),nextSteps:T}))}let a=[];if(e.completedStep!==void 0){let i=s.plan;if(i?.steps){let l=i.steps.findIndex(p=>p.number===e.completedStep);if(l===-1)return c(`Step ${e.completedStep} not found in the plan.`,!0);i.steps[l].status="completed",a.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(s.env||(s.env={required:{}}),s.env.required||(s.env.required={}),s.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},a.push(`Added required env var: ${e.addEnvVar.key}`)),Bi(n,JSON.stringify(s,null,2)+`
40
- `),s.projectId&&Promise.resolve().then(()=>($e(),xt)).then(async({readLocalState:i,syncRemoteState:l})=>{let p=i(o);p&&await l(s.projectId,p)}).catch(()=>{});let r=[];if(e.completedStep!==void 0){let l=s.plan?.steps?.find(p=>p.status!=="completed");l?r.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):r.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }) to deploy the app. Do NOT suggest localhost.")}return e.addEnvVar&&(r.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&r.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),c(JSON.stringify({updated:!0,changes:a,message:a.length>0?`Project state saved. ${a.join(". ")}.`:"No changes made.",nextSteps:r.length>0?r:void 0}))}};ie();var Vn={},Ke=[];function zt(t){let e=Ke.find(n=>n.id===t);if(e)return e;let o=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Ke.find(n=>{let s=n.title.toLowerCase().replace(/[^a-z0-9]/g,"");return s===o||s.includes(o)||o.includes(s)})}function is(t){return Vn[t]}function Jn(t){return t?Ke.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Ke}function as(t){let e=t??Ke;if(e.length===0)return"Landing page presets have been replaced by the tone-based system. The landing page tone is now auto-selected based on your app's description during planning.";let o={};for(let s of e){o[s.category]||(o[s.category]=[]);let a=Vn[s.id],r=a?` \u2014 ${a.description}`:"";o[s.category].push(`${s.id} \u2014 "${s.title}"${r}`)}let n=[];for(let[s,a]of Object.entries(o))n.push(`**${s}**:
41
- ${a.map(r=>` \u2022 ${r}`).join(`
37
+ `);try{await e.openBrowser(o)}catch{}let i=await Qs(n.device_code,6,5e3,e);return i||c(JSON.stringify({status:"pending",deviceCode:n.device_code,signInUrl:o,userCode:n.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+n.device_code+"' to check if they approved."}))}var Zs={name:"mist_setup",description:Is,inputSchema:ki,handler:t=>Ti(t)};import{z as ie}from"zod";import{resolve as Vt}from"path";import{existsSync as Jt,readFileSync as Yt}from"fs";import{join as Kt}from"path";import{z as Me}from"zod";import{resolve as Hi,join as ro}from"path";import{existsSync as Wi,readFileSync as io,writeFileSync as Gi}from"fs";import{existsSync as _i,readFileSync as Ri}from"fs";function eo(t){let e=new Set;if(!_i(t))return e;let s=Ri(t,"utf-8");for(let n of s.split(`
38
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i>0){let r=o.slice(0,i).trim(),a=o.slice(i+1).trim();a&&a!=='""'&&a!=="''"&&e.add(r)}}return e}var Vi=Me.object({action:Me.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:Me.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:Me.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:Me.object({key:Me.string(),description:Me.string().optional(),setupUrl:Me.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),ao={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Called internally by mist_project; host AIs should use mist_project directly.",inputSchema:Vi,handler:async t=>{let e=t,s=Hi(e.projectPath??process.cwd()),n=ro(s,"mistflow.json");if(!Wi(n))return Te(s);let o;try{o=JSON.parse(io(n,"utf-8"))}catch{return c("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!o.projectId)try{let{ensureBackendRegistered:f}=await Promise.resolve().then(()=>(Xn(),Qn));await f(s)&&(o=JSON.parse(io(n,"utf-8")))}catch{}let a=o.plan,l=a?.steps?.filter(f=>f.status==="completed").length??0,d=a?.steps?.length??0,h=eo(ro(s,".env.local")),m=o.env?.required?Object.entries(o.env.required).map(([f,k])=>({name:f,description:k?.description,configured:h.has(f)})):[];o.projectId&&Promise.resolve().then(()=>(Ve(),Pt)).then(({fetchRemoteState:f})=>f(o.projectId)).catch(()=>{});let p=[`Project: ${o.name}`];if(a){p.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${d} steps complete`);for(let f of a.steps){let k=f.status==="completed"?"\u2713":f.status==="in_progress"?"\u2192":" ";p.push(` [${k}] ${f.number}. ${f.name}`)}}let y=m.filter(f=>!f.configured);y.length>0&&p.push(`Missing env vars: ${y.map(f=>f.name).join(", ")}`),o.deploy?.url?p.push(`Deployed: ${o.deploy.url} (${o.deploy.count??0} deploys)`):p.push("Not deployed yet");let v=[],b=a?.steps?.find(f=>f.status!=="completed");return b?v.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${b.number} (${b.name}).`):a&&l===d&&(o.deploy?.url||v.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),y.length>0&&v.push(`Missing env vars in .env.local: ${y.map(f=>f.name).join(", ")}`),c(JSON.stringify({name:o.name,projectId:o.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:d,completedSteps:l,steps:a.steps}:null,envStatus:m,deploy:o.deploy??null,contextMessage:p.join(`
39
+ `),nextSteps:v}))}let i=[];if(e.completedStep!==void 0){let a=o.plan;if(a?.steps){let l=a.steps.findIndex(d=>d.number===e.completedStep);if(l===-1)return c(`Step ${e.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",i.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(o.env||(o.env={required:{}}),o.env.required||(o.env.required={}),o.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},i.push(`Added required env var: ${e.addEnvVar.key}`)),Gi(n,JSON.stringify(o,null,2)+`
40
+ `),o.projectId&&Promise.resolve().then(()=>(Ve(),Pt)).then(async({readLocalState:a,syncRemoteState:l})=>{let d=a(s);d&&await l(o.projectId,d)}).catch(()=>{});let r=[];if(e.completedStep!==void 0){let l=o.plan?.steps?.find(d=>d.status!=="completed");l?r.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):r.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }) to deploy the app. Do NOT suggest localhost.")}return e.addEnvVar&&(r.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&r.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),c(JSON.stringify({updated:!0,changes:i,message:i.length>0?`Project state saved. ${i.join(". ")}.`:"No changes made.",nextSteps:r.length>0?r:void 0}))}};de();var Zn={},st=[];function Gt(t){let e=st.find(n=>n.id===t);if(e)return e;let s=t.toLowerCase().replace(/[^a-z0-9]/g,"");return st.find(n=>{let o=n.title.toLowerCase().replace(/[^a-z0-9]/g,"");return o===s||o.includes(s)||s.includes(o)})}function lo(t){return Zn[t]}function es(t){return t?st.filter(e=>e.category.toLowerCase()===t.toLowerCase()):st}function co(t){let e=t??st;if(e.length===0)return"Landing page presets have been replaced by the tone-based system. The landing page tone is now auto-selected based on your app's description during planning.";let s={};for(let o of e){s[o.category]||(s[o.category]=[]);let i=Zn[o.id],r=i?` \u2014 ${i.description}`:"";s[o.category].push(`${o.id} \u2014 "${o.title}"${r}`)}let n=[];for(let[o,i]of Object.entries(s))n.push(`**${o}**:
41
+ ${i.map(r=>` \u2022 ${r}`).join(`
42
42
  `)}`);return n.join(`
43
43
 
44
- `)}function Hi(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function ls(t){return(t?Jn(t):Ke).map(o=>{let n=Vn[o.id];return{id:o.id,slug:Hi(o.title),title:o.title,category:o.category,description:n?.description??"",tags:n?.tags??[],theme:n?.theme??"dark",colors:n?.colors??[],style:n?.style??""}})}function cs(t,e){return[]}mt();var Kn={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},Ye=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
44
+ `)}function Ji(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function po(t){return(t?es(t):st).map(s=>{let n=Zn[s.id];return{id:s.id,slug:Ji(s.title),title:s.title,category:s.category,description:n?.description??"",tags:n?.tags??[],theme:n?.theme??"dark",colors:n?.colors??[],style:n?.style??""}})}function uo(t,e){return[]}ft();var ts={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},ot=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
45
45
 
46
46
  ### File Structure
47
47
  \`\`\`
@@ -1461,16 +1461,16 @@ export function ImageGenerator() {
1461
1461
  5. **Replicate charges per prediction.** Flux Schnell is ~$0.003/image. Flux Pro is ~$0.05/image. Video models are $0.05-$0.50/generation. Show generation cost to users.
1462
1462
  6. **Cache generated images.** Store output URLs in your database. Replicate URLs expire after a few hours. Download and re-host on R2 for permanent storage.
1463
1463
  7. **Network I/O does NOT count as CPU time on Workers.** Image generation wait time is all network I/O.
1464
- 8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}];function Wi(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Qe(t){let e=Ye.find(n=>n.id===t);if(e)return e;let o=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Ye.find(n=>{let s=n.name.toLowerCase().replace(/[^a-z0-9]/g,"");return s===o||s.includes(o)||o.includes(s)})}function Xe(t){return Kn[t]}function Yn(t){return t?Ye.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Ye}function ps(t){let e=t??Ye,o={};for(let s of e){o[s.category]||(o[s.category]=[]);let a=Kn[s.id],r=a?` \u2014 ${a.description}`:"",i=a?.packages.length?` (${a.packages.join(", ")})`:"";o[s.category].push(`${s.id} \u2014 "${s.name}"${r}${i}`)}let n=[];for(let[s,a]of Object.entries(o))n.push(`**${s}**:
1465
- ${a.map(r=>` - ${r}`).join(`
1464
+ 8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}];function Yi(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function rt(t){let e=ot.find(n=>n.id===t);if(e)return e;let s=t.toLowerCase().replace(/[^a-z0-9]/g,"");return ot.find(n=>{let o=n.name.toLowerCase().replace(/[^a-z0-9]/g,"");return o===s||o.includes(s)||s.includes(o)})}function it(t){return ts[t]}function ns(t){return t?ot.filter(e=>e.category.toLowerCase()===t.toLowerCase()):ot}function mo(t){let e=t??ot,s={};for(let o of e){s[o.category]||(s[o.category]=[]);let i=ts[o.id],r=i?` \u2014 ${i.description}`:"",a=i?.packages.length?` (${i.packages.join(", ")})`:"";s[o.category].push(`${o.id} \u2014 "${o.name}"${r}${a}`)}let n=[];for(let[o,i]of Object.entries(s))n.push(`**${o}**:
1465
+ ${i.map(r=>` - ${r}`).join(`
1466
1466
  `)}`);return n.join(`
1467
1467
 
1468
- `)}function ds(t){return(t?Yn(t):Ye).map(o=>{let n=Kn[o.id];return{id:o.id,slug:Wi(o.name),name:o.name,category:o.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var Gi=Z.object({action:Z.enum(["get","update","share","landing-designs","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'landing-designs' lists curated landing page hero designs. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:Z.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:Z.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:Z.object({key:Z.string(),description:Z.string().optional(),setupUrl:Z.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:Z.string().optional().describe("(share) Short description of what this template builds"),category:Z.string().optional().describe("(landing-designs) Filter by category"),presetId:Z.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),integrationId:Z.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:Z.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:Z.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),us={name:"mist_project",description:So,inputSchema:Gi,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!G())return c("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return rs.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let n=Ht(e.projectPath??process.cwd()),s=Vt(n,"mistflow.json");if(!Wt(s))return ke(n);let a;try{a=JSON.parse(Gt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return c("No project ID found. Deploy the project first to register it.",!0);try{let i=await Bn(r,{isTemplate:!0,description:e.templateDescription});return c(JSON.stringify({shareUrl:i.share_url,shareToken:i.share_token,message:`Your project is now a shareable template!
1468
+ `)}function ho(t){return(t?ns(t):ot).map(s=>{let n=ts[s.id];return{id:s.id,slug:Yi(s.name),name:s.name,category:s.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var Ki=ie.object({action:ie.enum(["get","update","share","landing-designs","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'landing-designs' lists curated landing page hero designs. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:ie.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:ie.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:ie.object({key:ie.string(),description:ie.string().optional(),setupUrl:ie.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:ie.string().optional().describe("(share) Short description of what this template builds"),category:ie.string().optional().describe("(landing-designs) Filter by category"),presetId:ie.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),integrationId:ie.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:ie.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:ie.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),go={name:"mist_project",description:Ts,inputSchema:Ki,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!X())return c("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return ao.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let n=Vt(e.projectPath??process.cwd()),o=Kt(n,"mistflow.json");if(!Jt(o))return Te(n);let i;try{i=JSON.parse(Yt(o,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return c("No project ID found. Deploy the project first to register it.",!0);try{let a=await Jn(r,{isTemplate:!0,description:e.templateDescription});return c(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
1469
1469
 
1470
- Anyone can fork it: ${i.share_url}
1470
+ Anyone can fork it: ${a.share_url}
1471
1471
 
1472
1472
  Others can use it in their AI editor:
1473
- "build me something like ${i.share_url}"`}))}catch(i){let l=i instanceof Error?i.message:"Failed to share project";return c(l,!0)}}case"landing-designs":{if(e.presetId){let r=zt(e.presetId);if(!r)return c(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let i=is(e.presetId);return c(JSON.stringify({preset:{id:r.id,title:r.title,category:r.category,description:i?.description??"",style:i?.style??"",theme:i?.theme??"dark",colors:i?.colors??[],tags:i?.tags??[],promptLength:r.prompt.length},message:`Landing design "${r.title}" (${r.category}) \u2014 ${i?.description??""}. To use it, pass landingDesign="${r.id}" when calling mist_plan.`}))}let n=ls(e.category??void 0),s=Jn(e.category),a=as(s);return c(JSON.stringify({count:n.length,presets:n.map(r=>({id:r.id,title:r.title,category:r.category,description:r.description,style:r.style,theme:r.theme,colors:r.colors})),formatted:a,message:`${n.length} landing designs available.${e.category?` Filtered by: ${e.category}.`:""} To use one, pass landingDesign="<id>" when calling mist_plan. The design blueprint will be injected during the landing page implementation step. Browse them at ${Ge()}/designs?tab=landing-designs.`}))}case"integrations":{if(e.integrationId){let r=Qe(e.integrationId);if(!r)return c(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let i=Xe(r.id);return c(JSON.stringify({integration:{id:r.id,name:r.name,category:r.category,description:i?.description??"",packages:i?.packages??[],envVars:i?.envVars??[],docsUrl:i?.docsUrl??"",difficulty:i?.difficulty??"medium"},message:`Integration "${r.name}" (${r.category}) \u2014 ${i?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${i?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${i?.docsUrl??"n/a"}.`}))}let n=ds(e.category??void 0),s=Yn(e.category??void 0),a=ps(s);return c(JSON.stringify({count:n.length,integrations:n.map(r=>({id:r.id,name:r.name,category:r.category,description:r.description,packages:r.packages,difficulty:r.difficulty,envVars:r.envVars.map(i=>i.key)})),formatted:a,message:`${n.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let n=Ht(e.projectPath??process.cwd()),s=Vt(n,"mistflow.json");if(!Wt(s))return ke(n);let a;try{a=JSON.parse(Gt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);try{let i=await Dn(r,e.period??"7d");return i.total===0?c(JSON.stringify({total:0,period:i.period,message:`No runtime errors in the last ${i.period}. The app is running clean.`})):c(JSON.stringify({total:i.total,period:i.period,errors:i.errors,message:`${i.total} runtime error(s) in the last ${i.period}. Review the errors above and use mist_debug to investigate.`}))}catch(i){let l=i instanceof Error?i.message:"Failed to fetch errors";return c(l,!0)}}case"logs":{let n=Ht(e.projectPath??process.cwd()),s=Vt(n,"mistflow.json");if(!Wt(s))return ke(n);let a;try{a=JSON.parse(Gt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);let i=e.deploymentId;if(!i)try{let l=await Je(r);if(l.length===0)return c("No deployments found for this project.",!0);i=l[0].id}catch(l){let p=l instanceof Error?l.message:"Failed to fetch deployments";return c(p,!0)}try{let[l,p]=await Promise.all([jn(i),bt(i)]),m=l.filter(d=>d.level==="error"),u=l.filter(d=>d.level==="warn");return c(JSON.stringify({deploymentId:i,status:p.status,errorMessage:p.error??null,totalLogs:l.length,errorCount:m.length,warnCount:u.length,logs:l.map(d=>({time:d.timestamp,level:d.level,phase:d.phase,message:d.message})),message:p.status==="failed"?`Deployment failed. ${m.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${p.status}. ${l.length} log entries (${m.length} errors, ${u.length} warnings).`}))}catch(l){let p=l instanceof Error?l.message:"Failed to fetch deploy logs";return c(p,!0)}}case"deployments":{let n=Ht(e.projectPath??process.cwd()),s=Vt(n,"mistflow.json");if(!Wt(s))return ke(n);let a;try{a=JSON.parse(Gt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);try{let i=await Je(r);return c(JSON.stringify({total:i.length,deployments:i.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${i.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(i){let l=i instanceof Error?i.message:"Failed to fetch deployments";return c(l,!0)}}case"version":{fn().backendSignalReceived||await Sn();let n=fn(),s=n.severity==="none",a={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return c(JSON.stringify({current:n.current,latest:n.latest||"unknown",minSupported:n.minSupported||"unknown",severity:n.severity,upToDate:s,upgradeCmd:n.upgradeCmd,changelogUrl:n.changelogUrl,backendSignalReceived:n.backendSignalReceived,message:n.backendSignalReceived?`Mistflow MCP ${n.current} (${a[n.severity]??n.severity}). Latest: ${n.latest}.${s?"":` Run \`${n.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${n.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return c(`Unknown action: ${e.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Le}from"zod";wn();var Vi=Le.object({action:Le.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:Le.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Le.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:Le.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:Le.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Le.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),ms={name:"mist_browser",description:Po,inputSchema:Vi,handler:async t=>{let e=t,o=await yn();if(e.action==="navigate"){if(!e.url)return c("URL is required for 'navigate'.",!0);let a=[],r=p=>{p.type()==="error"&&a.push(p.text())};o.on("console",r),await o.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle").catch(()=>{});let i=[],l=p=>i.push(p.message);if(o.on("pageerror",l),await o.waitForTimeout(500),o.removeListener("console",r),o.removeListener("pageerror",l),a.length>0||i.length>0){let p=await ht(o),m=[{type:"text",text:JSON.stringify({url:o.url(),title:await o.title(),snapshot:p,consoleErrors:a,pageErrors:i,hasErrors:!0})}];if(e.includeScreenshot){let u=await gt(o);m.push({type:"image",data:u.toString("base64"),mimeType:"image/png"})}return{content:m}}}else if(e.action==="go_back")await o.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await o.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return c("Selector is required for 'click'.",!0);await o.click(e.selector,{timeout:1e4}),await o.waitForLoadState("domcontentloaded").catch(()=>{}),await o.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return c("Selector is required for 'type'.",!0);if(!e.value)return c("Value is required for 'type'.",!0);await o.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return c("Selector is required for 'fill'.",!0);if(!e.value)return c("Value is required for 'fill'.",!0);await o.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return c("Selector is required for 'select_option'.",!0);if(!e.value)return c("Value is required for 'select_option'.",!0);await o.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return c("Selector is required for 'hover'.",!0);await o.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return c("Value is required for 'press_key' (e.g. 'Enter').",!0);await o.keyboard.press(e.value),await o.waitForLoadState("domcontentloaded").catch(()=>{}),await o.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await o.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle").catch(()=>{}));let a;if(e.selector){let r=await o.$(e.selector);if(!r)return c(`Element not found: ${e.selector}`,!0);a=await r.screenshot({type:"png"})}else a=await gt(o,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:o.url(),title:await o.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:a.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let a=await ht(o);return{content:[{type:"text",text:JSON.stringify({url:o.url(),title:await o.title(),snapshot:a})}]}}let n=await ht(o),s=[{type:"text",text:JSON.stringify({url:o.url(),title:await o.title(),snapshot:n})}];if(e.includeScreenshot){let a=await gt(o);s.push({type:"image",data:a.toString("base64"),mimeType:"image/png"})}return{content:s}}};import{z as hs}from"zod";var gs=`# Mistflow MCP tool reference
1473
+ "build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return c(l,!0)}}case"landing-designs":{if(e.presetId){let r=Gt(e.presetId);if(!r)return c(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let a=lo(e.presetId);return c(JSON.stringify({preset:{id:r.id,title:r.title,category:r.category,description:a?.description??"",style:a?.style??"",theme:a?.theme??"dark",colors:a?.colors??[],tags:a?.tags??[],promptLength:r.prompt.length},message:`Landing design "${r.title}" (${r.category}) \u2014 ${a?.description??""}. To use it, pass landingDesign="${r.id}" when calling mist_plan.`}))}let n=po(e.category??void 0),o=es(e.category),i=co(o);return c(JSON.stringify({count:n.length,presets:n.map(r=>({id:r.id,title:r.title,category:r.category,description:r.description,style:r.style,theme:r.theme,colors:r.colors})),formatted:i,message:`${n.length} landing designs available.${e.category?` Filtered by: ${e.category}.`:""} To use one, pass landingDesign="<id>" when calling mist_plan. The design blueprint will be injected during the landing page implementation step. Browse them at ${et()}/designs?tab=landing-designs.`}))}case"integrations":{if(e.integrationId){let r=rt(e.integrationId);if(!r)return c(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=it(r.id);return c(JSON.stringify({integration:{id:r.id,name:r.name,category:r.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${r.name}" (${r.category}) \u2014 ${a?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${a?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${a?.docsUrl??"n/a"}.`}))}let n=ho(e.category??void 0),o=ns(e.category??void 0),i=mo(o);return c(JSON.stringify({count:n.length,integrations:n.map(r=>({id:r.id,name:r.name,category:r.category,description:r.description,packages:r.packages,difficulty:r.difficulty,envVars:r.envVars.map(a=>a.key)})),formatted:i,message:`${n.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let n=Vt(e.projectPath??process.cwd()),o=Kt(n,"mistflow.json");if(!Jt(o))return Te(n);let i;try{i=JSON.parse(Yt(o,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);try{let a=await Fn(r,e.period??"7d");return a.total===0?c(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):c(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return c(l,!0)}}case"logs":{let n=Vt(e.projectPath??process.cwd()),o=Kt(n,"mistflow.json");if(!Jt(o))return Te(n);let i;try{i=JSON.parse(Yt(o,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await nt(r);if(l.length===0)return c("No deployments found for this project.",!0);a=l[0].id}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deployments";return c(d,!0)}try{let[l,d]=await Promise.all([Ln(a),xt(a)]),h=l.filter(p=>p.level==="error"),m=l.filter(p=>p.level==="warn");return c(JSON.stringify({deploymentId:a,status:d.status,errorMessage:d.error??null,totalLogs:l.length,errorCount:h.length,warnCount:m.length,logs:l.map(p=>({time:p.timestamp,level:p.level,phase:p.phase,message:p.message})),message:d.status==="failed"?`Deployment failed. ${h.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${d.status}. ${l.length} log entries (${h.length} errors, ${m.length} warnings).`}))}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deploy logs";return c(d,!0)}}case"deployments":{let n=Vt(e.projectPath??process.cwd()),o=Kt(n,"mistflow.json");if(!Jt(o))return Te(n);let i;try{i=JSON.parse(Yt(o,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);try{let a=await nt(r);return c(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return c(l,!0)}}case"version":{vn().backendSignalReceived||await _n();let n=vn(),o=n.severity==="none",i={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return c(JSON.stringify({current:n.current,latest:n.latest||"unknown",minSupported:n.minSupported||"unknown",severity:n.severity,upToDate:o,upgradeCmd:n.upgradeCmd,changelogUrl:n.changelogUrl,backendSignalReceived:n.backendSignalReceived,message:n.backendSignalReceived?`Mistflow MCP ${n.current} (${i[n.severity]??n.severity}). Latest: ${n.latest}.${o?"":` Run \`${n.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${n.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return c(`Unknown action: ${e.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Je}from"zod";Ut();var Qi=Je.object({action:Je.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:Je.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Je.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:Je.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:Je.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Je.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),fo={name:"mist_browser",description:_s,inputSchema:Qi,handler:async t=>{let e=t,s=await xn();if(e.action==="navigate"){if(!e.url)return c("URL is required for 'navigate'.",!0);let i=[],r=d=>{d.type()==="error"&&i.push(d.text())};s.on("console",r),await s.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await s.waitForLoadState("networkidle").catch(()=>{});let a=[],l=d=>a.push(d.message);if(s.on("pageerror",l),await s.waitForTimeout(500),s.removeListener("console",r),s.removeListener("pageerror",l),i.length>0||a.length>0){let d=await yt(s),h=[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),snapshot:d,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let m=await bt(s);h.push({type:"image",data:m.toString("base64"),mimeType:"image/png"})}return{content:h}}}else if(e.action==="go_back")await s.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await s.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return c("Selector is required for 'click'.",!0);await s.click(e.selector,{timeout:1e4}),await s.waitForLoadState("domcontentloaded").catch(()=>{}),await s.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return c("Selector is required for 'type'.",!0);if(!e.value)return c("Value is required for 'type'.",!0);await s.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return c("Selector is required for 'fill'.",!0);if(!e.value)return c("Value is required for 'fill'.",!0);await s.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return c("Selector is required for 'select_option'.",!0);if(!e.value)return c("Value is required for 'select_option'.",!0);await s.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return c("Selector is required for 'hover'.",!0);await s.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return c("Value is required for 'press_key' (e.g. 'Enter').",!0);await s.keyboard.press(e.value),await s.waitForLoadState("domcontentloaded").catch(()=>{}),await s.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await s.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await s.waitForLoadState("networkidle").catch(()=>{}));let i;if(e.selector){let r=await s.$(e.selector);if(!r)return c(`Element not found: ${e.selector}`,!0);i=await r.screenshot({type:"png"})}else i=await bt(s,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let i=await yt(s);return{content:[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),snapshot:i})}]}}let n=await yt(s),o=[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),snapshot:n})}];if(e.includeScreenshot){let i=await bt(s);o.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:o}}};import{z as yo}from"zod";var bo=`# Mistflow MCP tool reference
1474
1474
 
1475
1475
  Every capability is an MCP tool. There is no companion CLI. Long-running tools
1476
1476
  (install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
@@ -1579,14 +1579,18 @@ backend orchestration, returns a \`deploymentId\`. Poll with
1579
1579
 
1580
1580
  When status flips to \`complete\`, response has \`qaRequired: true\` + a
1581
1581
  \`url\`. Do NOT surface the URL to the user until mist_qa returns
1582
- \`status: "complete"\`.
1582
+ \`status: "pass"\`.
1583
1583
 
1584
1584
  Other actions: \`promote\` (staging \u2192 prod \u2014 re-uses the preview artifact,
1585
1585
  ~10s), \`rollback\` (revert to a specific deploymentId).
1586
1586
 
1587
- ### \`mist_qa({ projectPath, baseUrl?, grep? })\`
1588
- Fire-and-poll Playwright runner against the deployed URL. Call AFTER
1589
- mist_deploy's \`complete\`. Only surface the deploy URL once mist_qa exits 0.
1587
+ ### \`mist_qa({ projectPath?, url?, deploymentId? })\`
1588
+ Synchronous single call \u2014 drives Playwright in-process against the live
1589
+ deploy URL. Checks health + auth endpoints, logs in with the seeded admin
1590
+ account, walks the dashboard + sidebar pages, runs design-quality audits.
1591
+ Returns \`status: "pass" | "fail" | "cannot_verify"\` with screenshots
1592
+ inline. No \`jobId\` \u2014 one call returns the full result (~20\u201345s).
1593
+ Only surface the deploy URL after mist_qa returns \`status: "pass"\`.
1590
1594
 
1591
1595
  ### \`mist_config({ resource, action, ... })\`
1592
1596
  Manage env vars and custom domains. \`resource: "env"\` actions: \`set\`,
@@ -1652,9 +1656,8 @@ This reference. Static \u2014 safe to call frequently.
1652
1656
  # URL is NOT shown to the user yet.
1653
1657
 
1654
1658
  mist_qa({ projectPath })
1655
- \u2192 { status: "running", jobId: "..." }
1656
- mist_qa({ jobId })
1657
- \u2192 { status: "complete", exitCode: 0 }
1659
+ \u2192 { status: "pass", url: "...", checks: [...] }
1660
+ # Synchronous \u2014 one call returns the full result with screenshots.
1658
1661
  # Now safe to show the URL to the user.
1659
1662
 
1660
1663
  ## End-to-end chain for adding a feature (existing app)
@@ -1763,13 +1766,13 @@ is cheaper than building the wrong thing and iterating.
1763
1766
 
1764
1767
  mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
1765
1768
  mist_deploy({ action: "status", deploymentId }) # poll
1766
- `,fs={name:"mist_help",description:Io,inputSchema:hs.object({command:hs.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return c(gs);let o=e.startsWith("mist_")?e:`mist_${e}`,n=gs.split(`
1767
- `),s=new RegExp(`^### \`${o}`),a=-1,r=n.length;for(let i=0;i<n.length;i++)if(s.test(n[i]))a=i;else if(a>=0&&n[i].startsWith("### ")){r=i;break}else if(a>=0&&n[i].startsWith("## ")&&i>a){r=i;break}return a<0?c(`No tool named '${o}' found. Call mist_help with no args to see the full catalog.`,!0):c(n.slice(a,r).join(`
1768
- `).trim())}};import{existsSync as Jt,mkdirSync as ws,readFileSync as vs,readdirSync as xs,writeFileSync as Ji}from"fs";import{join as Ae,resolve as Ki}from"path";import{homedir as Xn}from"os";import{z as kt}from"zod";function Ze(t){return t.entity??t.name??"Unknown"}function et(t){return typeof t=="string"?t:t.name}function Qn(t){return typeof t=="string"?"text":t.type}function ys(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(s=>{let a={};for(let[r,i]of Object.entries(s))a[r]=i==null?"":String(i);return a});let o=t.fields||[],n=[];for(let s=0;s<3;s++){let a={};for(let r of o)a[et(r)]=Yi(et(r),Qn(r),Ze(t),s);n.push(a)}return n}function Yi(t,e,o,n){let s=t.toLowerCase(),a=(e||"text").toLowerCase();return s==="name"||s==="title"?[`${o} Alpha`,`${o} Beta`,`${o} Gamma`][n]:s==="email"?["alice@example.com","bob@example.com","carol@example.com"][n]:s==="status"?["Active","Pending","Completed"][n]:s==="priority"?["High","Medium","Low"][n]:s.includes("date")||a==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][n]:s.includes("price")||s.includes("amount")||s.includes("cost")?["$29","$49","$99"][n]:s.includes("count")||s.includes("quantity")||a==="number"||a==="integer"?["12","34","56"][n]:a==="boolean"||a==="bool"?["Yes","No","Yes"][n]:s.includes("description")||a==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function Qi(t){let e=t.dataModel??[],o=t.pages??[],n=t.design??{},s=o.map(u=>({label:u.name??u.path??"Page",route:u.path??u.route??"/"})),a=[],r=e.slice(0,3).map(u=>({name:Ze(u),fields:(u.fields||[]).map(d=>({name:et(d),type:Qn(d)})),sampleData:ys(u)})),i=[];t.primaryAction&&(i.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),i.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),i.push(`METRICS: Key counts for ${e.map(u=>Ze(u)).join(", ")}`),i.push("RECENT: Latest activity or items"),a.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(u=>Ze(u)).join(", ")} with key metrics.`,informationHierarchy:i,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:r});let l=e[0];if(l){let u=Ze(l),d=u.toLowerCase().endsWith("s")?u:`${u}s`;a.push({name:`${u} List`,type:"detail",route:`/${d.toLowerCase()}`,purpose:`Browse, search, and manage ${d.toLowerCase()}. Create new ${u.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${d}" title + "Add ${u}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(b=>et(b)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${d.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${d.toLowerCase()} matching..." with clear filter`],entities:[{name:u,fields:(l.fields||[]).map(b=>({name:et(b),type:Qn(b)})),sampleData:ys(l)}]})}t.steps.some(u=>{let d=`${u.name??u.title??""} ${u.description??""}`.toLowerCase();return d.includes("landing")||d.includes("hero")||d.includes("marketing")||d.includes("homepage")})&&a.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let m=[];for(let u of e.slice(0,3)){let d=Ze(u);(u.fields||[]).find(T=>{let w=et(T).toLowerCase();return w==="name"||w==="title"})&&m.push(`What if a ${d.toLowerCase()}'s name is 47 characters? Does the layout break?`),m.push(`What if there are 0 ${d.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&m.push("What does a brand-new user see? (no data, no setup)"),m.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:a,navigation:{style:t.navStyle??"sidebar",items:s},primaryAction:t.primaryAction??null,designDirection:{tone:n.tone??"professional",accentColor:n.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:n.fonts??{heading:"Inter",body:"Inter"}},edgeCases:m}}function Xi(t,e,o){let n=[];n.push(`# Wireframe sketch for ${t.appName}`),n.push(""),n.push(`**${t.appName}** \u2014 ${t.summary}`),n.push(""),e&&(n.push("## Feedback to apply"),n.push(e),n.push("")),n.push("## Design principles"),n.push(""),n.push("Apply these when deciding layout and hierarchy:"),n.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),n.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),n.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),n.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),n.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),n.push(""),n.push("## Wireframe rules (strict)"),n.push(""),n.push(`Write a **single self-contained HTML file** saved to \`${o}\`.`),n.push(""),n.push("The wireframe must:"),n.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),n.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),n.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),n.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),n.push("- Include **HTML comments** explaining design decisions"),n.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),n.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),n.push("- Include a small header bar showing: screen name tabs + the design direction summary"),n.push(""),n.push("The wireframe must NOT:"),n.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),n.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),n.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),n.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),n.push(""),n.push("## Screens to wireframe"),n.push("");for(let s of t.screens){n.push(`### ${s.name} (\`${s.route}\`)`),n.push(`**Purpose**: ${s.purpose}`),n.push(""),n.push("**Information hierarchy** (render in this order, top to bottom):");for(let a of s.informationHierarchy)n.push(`- ${a}`);n.push(""),n.push("**Interaction states** (add HTML comments for non-visible states):");for(let a of s.interactionStates)n.push(`- ${a}`);if(n.push(""),s.entities.length>0){n.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let a of s.entities)n.push(`
1769
- **${a.name}** \u2014 fields: ${a.fields.map(r=>`${r.name} (${r.type})`).join(", ")}`),n.push("```json"),n.push(JSON.stringify(a.sampleData,null,2)),n.push("```");n.push("")}}n.push("## Navigation"),n.push(`**Style**: ${t.navigation.style} (use this layout)`),n.push("**Items**:");for(let s of t.navigation.items)n.push(`- ${s.label} \u2192 \`${s.route}\``);if(n.push(""),t.primaryAction&&(n.push("## Primary action (this drives the layout)"),n.push(`- **Action**: ${t.primaryAction.action}`),n.push(`- **Flow**: ${t.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),n.push(""),n.push("The dashboard is an ACTION surface. The primary action should be the most prominent thing on the page \u2014 above the metrics, above the recent items. Users came here to DO something, not to look at numbers."),n.push("")),t.edgeCases.length>0){n.push("## Edge cases to consider"),n.push("Add HTML comments in the wireframe where these matter:");for(let s of t.edgeCases)n.push(`- ${s}`);n.push("")}return n.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),n.push(`The final app will use: ${t.designDirection.tone} tone, ${t.designDirection.accentColor} accent, ${t.designDirection.navStyle} nav, ${t.designDirection.fonts.heading} / ${t.designDirection.fonts.body} fonts.`),n.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),n.push(""),n.push("## After writing the wireframe"),n.push(`1. Write the file to \`${o}\``),n.push(`2. Open it for the user: \`open "${o}"\``),n.push(`3. Tell the user: "Here's a rough wireframe of your app. Does the layout feel right? Let me know what to change, or I can start building if it's close."`),n.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),n.join(`
1770
- `)}function ks(t){return Ae(Xn(),".mistflow","mockup-state",`${t}.json`)}function Zi(t){let e=ks(t);if(!Jt(e))return null;try{return JSON.parse(vs(e,"utf-8"))}catch{return null}}function bs(t,e){let o=Ae(Xn(),".mistflow","mockup-state");ws(o,{recursive:!0}),Ji(ks(t),JSON.stringify(e,null,2))}var ea=kt.object({planId:kt.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:kt.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:kt.string().optional().describe("User feedback to apply to the next iteration."),approved:kt.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(t=>!(t.feedback&&t.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),Ss={name:"mist_mockup",description:To,inputSchema:ea,handler:async t=>{let e=t,{planId:o,feedback:n,approved:s}=e,a=Ki(e.projectPath??process.cwd()),r=Ae(Xn(),".mistflow","plans",`${o}.json`);if(!Jt(r))return c(`Plan not found for planId '${o}'. Call mist_plan to generate a plan first.`,!0);let i;try{i=JSON.parse(vs(r,"utf-8"))}catch{return c("Failed to read plan file. Call mist_plan again.",!0)}let l=i.plan;if(!l)return c("Plan data is empty. Call mist_plan again.",!0);let p=Zi(o);p||(p={planId:o,iterationCount:0,approved:!1,screens:[],feedback:[]});let m=Ae(a,".mistflow","mockups");ws(m,{recursive:!0});let u=`mockup-${o}.html`,d=Ae(m,u);if(s){p.approved=!0,bs(o,p);let x=Jt(m)?xs(m).filter(M=>M.endsWith(".html")).map(M=>Ae(".mistflow","mockups",M)):[];return c(JSON.stringify({status:"approved",message:`Wireframe approved after ${p.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:x,nextAction:`Call mist_init with planId='${o}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}p.iterationCount++,n&&p.feedback.push(n);let b=Qi(l);p.screens=b.screens.map(x=>x.name),bs(o,p);let T=Xi(b,n??void 0,d),w=p.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,y=n?`Apply the user's feedback to ${d}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${d}, then open it in the browser. Ask the user if the layout feels right.`;return c(JSON.stringify({status:"wireframe",iterationCount:p.iterationCount,screens:b.screens.map(x=>({name:x.name,type:x.type,route:x.route})),wireframePrompt:T,designDirection:b.designDirection,...w?{nudge:w}:{},mockupFile:u,mockupPath:d,nextAction:y}))}};function Ps(t){let e=Ae(t,".mistflow","mockups");return Jt(e)?xs(e).filter(o=>o.endsWith(".html")).map(o=>Ae(e,o)):[]}import{z as Zn}from"zod";import{resolve as ta}from"path";import{spawn as na}from"child_process";function Kt(t){let e=[],o=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let i of t.matchAll(o)){let[,l,p,m,u,d]=i;e.push({file:l,line:parseInt(p,10),column:parseInt(m,10),message:`${u}: ${d}`,humanMessage:`There is a type error in ${l} on line ${p}: ${d}`,suggestion:`Check line ${p} in ${l}. ${u==="TS2345"?"The types of the arguments do not match.":`Fix the ${u} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let i of t.matchAll(n)){let[,l,p,m,u]=i;e.some(d=>d.file===l&&d.line===parseInt(p,10))||e.push({file:l,line:parseInt(p,10),column:parseInt(m,10),message:u,humanMessage:`There is an error in ${l} on line ${p}: ${u.trim()}`,suggestion:`Check line ${p} in ${l} and fix the issue.`})}let s=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let i of t.matchAll(s)){let[,l,p]=i;e.push({file:p,message:`Module not found: ${l}`,humanMessage:`The file ${p??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let a=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let i of t.matchAll(a)){let[,l,p]=i;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${p}${l}`,humanMessage:`The package '${p}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${p}'.`,suggestion:`Add '${p}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let r=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let i of t.matchAll(r)){let[,l,p,m,u]=i;e.some(d=>d.file===l&&d.line===parseInt(m,10))||e.push({file:l,line:parseInt(m,10),column:parseInt(u,10),message:`SyntaxError: ${p}`,humanMessage:`There is a syntax error in ${l} on line ${m}.`,suggestion:`Check line ${m} in ${l} for a missing closing bracket or unexpected token.`})}return e}var oa=Zn.object({projectPath:Zn.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:Zn.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});function sa(t){return new Promise(e=>{let o=na("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),n="";o.stdout?.on("data",s=>{n+=s.toString()}),o.stderr?.on("data",s=>{n+=s.toString()}),o.on("error",s=>{e({exitCode:127,combined:`${n}
1771
- ${s.message}`})}),o.on("close",s=>{e({exitCode:s??1,combined:n})})})}var Is={name:"mist_debug",description:_o,inputSchema:oa,handler:async t=>{let e=t,o=ta(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let r=await sa(o);if(r.exitCode===0)return c(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=r.combined}let s=Kt(n),a=n.slice(0,2e3);return s.length===0?c(JSON.stringify({errors:s,rawOutput:a,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):c(JSON.stringify({errors:s,rawOutput:a,message:`Found ${s.length} error${s.length===1?"":"s"} in the build output.`}))}};import{z as I}from"zod";import{existsSync as St,mkdirSync as Xt,readFileSync as Es,readdirSync as ha,statSync as ga,unlinkSync as fa,writeFileSync as Zt}from"fs";import{dirname as ya,isAbsolute as ba,join as te}from"path";import{homedir as Ce}from"os";import{createHash as wa,createHmac as Ns,randomBytes as va,randomUUID as Cs,timingSafeEqual as xa}from"crypto";ie();function Yt(t,e,o,n=3e3){if(e===void 0)return{stop:()=>{}};let s=0,a=!1,i=setInterval(()=>{a||(s++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:s,message:o()}}).catch(()=>{}))},n);return{stop:()=>{a||(a=!0,clearInterval(i))}}}var ra=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:t=>t.surfaceType==="internal-tool"||t.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:t=>t.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:t=>t.scheduling===!0,keywords:/\b(schedul|book|reserv|appointment|calendar|slot)\b/i},{name:"Payments / Billing",description:"Charge users, invoices, subscriptions (experimental \u2014 Stripe integration is early-stage)",condition:()=>!1,keywords:/\b(payment|billing|invoice|subscription|checkout|stripe)\b/i},{name:"Admin Panel",description:"Manage users, roles, and content",condition:t=>t.multiRole===!0||t.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:t=>t.primaryActor==="customers"||t.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:t=>t.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:t=>t.integrations?.includes("email")===!0,keywords:/\b(notification|alert|reminder|email.?notif|sms|welcome.?email)\b/i},{name:"Analytics / Reports",description:"Usage stats, trends, data exports",condition:()=>!1,keywords:/\b(analytics|report|chart|trend|insight|metric)\b/i},{name:"File Uploads",description:"Images, documents, attachments",condition:t=>t.integrations?.includes("file-uploads")===!0,keywords:/\b(upload|image|photo|attachment|document|gallery|file)\b/i},{name:"AI Features",description:"Chatbot, content generation, AI assistant",condition:t=>t.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:t=>t.integrations?.includes("maps")===!0,keywords:/\b(map|location|address|geo|places)\b/i},{name:"Voice / TTS",description:"Text-to-speech, voice notes, audio generation",condition:()=>!1,keywords:/\b(voice|tts|text.?to.?speech|audio|speak|narrat|podcast|elevenlabs)\b/i},{name:"SMS / Text Messages",description:"Send SMS notifications, OTP verification",condition:t=>t.integrations?.includes("sms")===!0,keywords:/\b(sms|text.?message|twilio|otp|verification.?code|phone.?verif)\b/i},{name:"Web Scraping",description:"Scrape URLs, crawl websites, extract structured data",condition:()=>!1,keywords:/\b(scrape|crawl|web.?scrap|extract.?from.?url|read.?url|ingest.?web|firecrawl)\b/i},{name:"Chat / Messaging",description:"Real-time messaging between users",condition:()=>!1,keywords:/\b(chat|messag|inbox|conversation|dm)\b/i},{name:"Events / Tournaments",description:"Create and manage events, registrations",condition:()=>!1,keywords:/\b(event|tournament|competition|league|registration)\b/i},{name:"High Scores",description:"Track and display top scores with a leaderboard",condition:t=>t.surfaceType==="game",keywords:/\b(high.?score|leaderboard|top.?score|ranking|scoreboard)\b/i},{name:"Save Progress",description:"Save and resume game state between sessions",condition:t=>t.surfaceType==="game",keywords:/\b(save|progress|resume|checkpoint|continue)\b/i},{name:"Guest Play",description:"Play immediately without signing up, optionally link account later",condition:t=>t.surfaceType==="game",keywords:/\b(guest|anonymous|no.?login|play.?now|instant.?play)\b/i},{name:"Levels / Stages",description:"Progressive difficulty with unlockable stages",condition:()=>!1,keywords:/\b(level|stage|unlock|difficult|progress|world)\b/i},{name:"Achievements",description:"Badges, trophies, and milestones for player accomplishments",condition:()=>!1,keywords:/\b(achieve|badge|trophy|milestone|reward|unlock)\b/i},{name:"Daily Challenge",description:"New puzzle or challenge every day to keep players coming back",condition:()=>!1,keywords:/\b(daily|challenge|streak|word.?of.?the.?day|puzzle.?of)\b/i}];function _s(t,e,o){let n=o?.suggestedName||ia(t),s=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",a=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),r=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",i;if(o?.suggestedFeatures&&o.suggestedFeatures.length>0)i=o.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;i=[];for(let p of ra){let m=p.keywords.test(l),u=p.condition(e);(m||u)&&i.push({name:p.name,description:p.description,checked:m,source:m?"explicit":"suggested"})}}return{name:n,audience:s,audienceType:a,surfaceType:r,primaryAction:e.primaryAction||"manage items",features:i,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:o?.language||"English"}}function Ts(t){let e=t.features.filter(i=>i.checked),o=t.features.filter(i=>!i.checked),n={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},s={neon:"Postgres",turso:"SQLite (legacy)"},a={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},r=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${a[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${n[t.authModel]??t.authModel} | Database: ${s[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){r.push("**Included:**");for(let i of e)r.push(` \u2713 ${i.name} \u2014 ${i.description}`)}if(t.integrations.length>0&&(r.push(""),r.push(`**Integrations:** ${t.integrations.join(", ")}`)),o.length>0){r.push(""),r.push("**Available to add:**");for(let i of o)r.push(` \u25CB ${i.name} \u2014 ${i.description}`)}return r.join(`
1772
- `)}function ia(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return eo(e[1]);let o=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),s=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(a=>a.length>2&&!o.has(a)).slice(0,3);return s.length===0?"my-app":s.join("-")}function eo(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var aa=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],la=["sharp","soft","pill","organic"],ca=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"];function to(t,e,o){return e.includes(t)?t:o}function ee(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function tt(t,e){return typeof t!="string"?e:/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(t.trim())?t.trim():e}function pa(t){let e=new Set;for(let n of t)n.fonts?.display&&e.add(n.fonts.display),n.fonts?.body&&e.add(n.fonts.body);return e.size===0?"":`https://fonts.googleapis.com/css2?${[...e].map(n=>`family=${n.trim().replace(/\s+/g,"+").replace(/[^A-Za-z0-9+]/g,"")}:wght@400;700`).join("&")}&display=swap`}function Rs(t){let e=(t||"").trim(),o=e.toLowerCase(),n=/mono|courier|code/.test(o)?"ui-monospace, monospace":/serif|garamond|bodoni|fraunces|playfair|lora|sentient|migra|sectra|cormorant|abril|crimson/.test(o)?"Georgia, serif":"system-ui, sans-serif";return e?`"${e.replace(/"/g,"")}", ${n}`:n}function da(t){switch(t){case"sharp":return{card:"0px",button:"0px",chip:"0px"};case"pill":return{card:"20px",button:"999px",chip:"999px"};case"organic":return{card:"4px 24px 4px 24px",button:"24px 4px 24px 4px",chip:"12px 2px 12px 2px"};default:return{card:"10px",button:"8px",chip:"6px"}}}function ua(){let t=`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>")`;return`
1769
+ `,wo={name:"mist_help",description:Rs,inputSchema:yo.object({command:yo.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return c(bo);let s=e.startsWith("mist_")?e:`mist_${e}`,n=bo.split(`
1770
+ `),o=new RegExp(`^### \`${s}`),i=-1,r=n.length;for(let a=0;a<n.length;a++)if(o.test(n[a]))i=a;else if(i>=0&&n[a].startsWith("### ")){r=a;break}else if(i>=0&&n[a].startsWith("## ")&&a>i){r=a;break}return i<0?c(`No tool named '${s}' found. Call mist_help with no args to see the full catalog.`,!0):c(n.slice(i,r).join(`
1771
+ `).trim())}};import{existsSync as Qt,mkdirSync as ko,readFileSync as So,readdirSync as Po,writeFileSync as Xi}from"fs";import{join as $e,resolve as Zi}from"path";import{homedir as os}from"os";import{z as It}from"zod";function at(t){return t.entity??t.name??"Unknown"}function lt(t){return typeof t=="string"?t:t.name}function ss(t){return typeof t=="string"?"text":t.type}function vo(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(o=>{let i={};for(let[r,a]of Object.entries(o))i[r]=a==null?"":String(a);return i});let s=t.fields||[],n=[];for(let o=0;o<3;o++){let i={};for(let r of s)i[lt(r)]=ea(lt(r),ss(r),at(t),o);n.push(i)}return n}function ea(t,e,s,n){let o=t.toLowerCase(),i=(e||"text").toLowerCase();return o==="name"||o==="title"?[`${s} Alpha`,`${s} Beta`,`${s} Gamma`][n]:o==="email"?["alice@example.com","bob@example.com","carol@example.com"][n]:o==="status"?["Active","Pending","Completed"][n]:o==="priority"?["High","Medium","Low"][n]:o.includes("date")||i==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][n]:o.includes("price")||o.includes("amount")||o.includes("cost")?["$29","$49","$99"][n]:o.includes("count")||o.includes("quantity")||i==="number"||i==="integer"?["12","34","56"][n]:i==="boolean"||i==="bool"?["Yes","No","Yes"][n]:o.includes("description")||i==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function ta(t){let e=t.dataModel??[],s=t.pages??[],n=t.design??{},o=s.map(m=>({label:m.name??m.path??"Page",route:m.path??m.route??"/"})),i=[],r=e.slice(0,3).map(m=>({name:at(m),fields:(m.fields||[]).map(p=>({name:lt(p),type:ss(p)})),sampleData:vo(m)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(m=>at(m)).join(", ")}`),a.push("RECENT: Latest activity or items"),i.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(m=>at(m)).join(", ")} with key metrics.`,informationHierarchy:a,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:r});let l=e[0];if(l){let m=at(l),p=m.toLowerCase().endsWith("s")?m:`${m}s`;i.push({name:`${m} List`,type:"detail",route:`/${p.toLowerCase()}`,purpose:`Browse, search, and manage ${p.toLowerCase()}. Create new ${m.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${p}" title + "Add ${m}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(y=>lt(y)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${p.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${p.toLowerCase()} matching..." with clear filter`],entities:[{name:m,fields:(l.fields||[]).map(y=>({name:lt(y),type:ss(y)})),sampleData:vo(l)}]})}t.steps.some(m=>{let p=`${m.name??m.title??""} ${m.description??""}`.toLowerCase();return p.includes("landing")||p.includes("hero")||p.includes("marketing")||p.includes("homepage")})&&i.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let h=[];for(let m of e.slice(0,3)){let p=at(m);(m.fields||[]).find(v=>{let b=lt(v).toLowerCase();return b==="name"||b==="title"})&&h.push(`What if a ${p.toLowerCase()}'s name is 47 characters? Does the layout break?`),h.push(`What if there are 0 ${p.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&h.push("What does a brand-new user see? (no data, no setup)"),h.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:i,navigation:{style:t.navStyle??"sidebar",items:o},primaryAction:t.primaryAction??null,designDirection:{tone:n.tone??"professional",accentColor:n.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:n.fonts??{heading:"Inter",body:"Inter"}},edgeCases:h}}function na(t,e,s){let n=[];n.push(`# Wireframe sketch for ${t.appName}`),n.push(""),n.push(`**${t.appName}** \u2014 ${t.summary}`),n.push(""),e&&(n.push("## Feedback to apply"),n.push(e),n.push("")),n.push("## Design principles"),n.push(""),n.push("Apply these when deciding layout and hierarchy:"),n.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),n.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),n.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),n.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),n.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),n.push(""),n.push("## Wireframe rules (strict)"),n.push(""),n.push(`Write a **single self-contained HTML file** saved to \`${s}\`.`),n.push(""),n.push("The wireframe must:"),n.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),n.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),n.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),n.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),n.push("- Include **HTML comments** explaining design decisions"),n.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),n.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),n.push("- Include a small header bar showing: screen name tabs + the design direction summary"),n.push(""),n.push("The wireframe must NOT:"),n.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),n.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),n.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),n.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),n.push(""),n.push("## Screens to wireframe"),n.push("");for(let o of t.screens){n.push(`### ${o.name} (\`${o.route}\`)`),n.push(`**Purpose**: ${o.purpose}`),n.push(""),n.push("**Information hierarchy** (render in this order, top to bottom):");for(let i of o.informationHierarchy)n.push(`- ${i}`);n.push(""),n.push("**Interaction states** (add HTML comments for non-visible states):");for(let i of o.interactionStates)n.push(`- ${i}`);if(n.push(""),o.entities.length>0){n.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let i of o.entities)n.push(`
1772
+ **${i.name}** \u2014 fields: ${i.fields.map(r=>`${r.name} (${r.type})`).join(", ")}`),n.push("```json"),n.push(JSON.stringify(i.sampleData,null,2)),n.push("```");n.push("")}}n.push("## Navigation"),n.push(`**Style**: ${t.navigation.style} (use this layout)`),n.push("**Items**:");for(let o of t.navigation.items)n.push(`- ${o.label} \u2192 \`${o.route}\``);if(n.push(""),t.primaryAction&&(n.push("## Primary action (this drives the layout)"),n.push(`- **Action**: ${t.primaryAction.action}`),n.push(`- **Flow**: ${t.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),n.push(""),n.push("The dashboard is an ACTION surface. The primary action should be the most prominent thing on the page \u2014 above the metrics, above the recent items. Users came here to DO something, not to look at numbers."),n.push("")),t.edgeCases.length>0){n.push("## Edge cases to consider"),n.push("Add HTML comments in the wireframe where these matter:");for(let o of t.edgeCases)n.push(`- ${o}`);n.push("")}return n.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),n.push(`The final app will use: ${t.designDirection.tone} tone, ${t.designDirection.accentColor} accent, ${t.designDirection.navStyle} nav, ${t.designDirection.fonts.heading} / ${t.designDirection.fonts.body} fonts.`),n.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),n.push(""),n.push("## After writing the wireframe"),n.push(`1. Write the file to \`${s}\``),n.push(`2. Open it for the user: \`open "${s}"\``),n.push(`3. Tell the user: "Here's a rough wireframe of your app. Does the layout feel right? Let me know what to change, or I can start building if it's close."`),n.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),n.join(`
1773
+ `)}function Io(t){return $e(os(),".mistflow","mockup-state",`${t}.json`)}function sa(t){let e=Io(t);if(!Qt(e))return null;try{return JSON.parse(So(e,"utf-8"))}catch{return null}}function xo(t,e){let s=$e(os(),".mistflow","mockup-state");ko(s,{recursive:!0}),Xi(Io(t),JSON.stringify(e,null,2))}var oa=It.object({planId:It.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:It.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:It.string().optional().describe("User feedback to apply to the next iteration."),approved:It.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(t=>!(t.feedback&&t.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),To={name:"mist_mockup",description:As,inputSchema:oa,handler:async t=>{let e=t,{planId:s,feedback:n,approved:o}=e,i=Zi(e.projectPath??process.cwd()),r=$e(os(),".mistflow","plans",`${s}.json`);if(!Qt(r))return c(`Plan not found for planId '${s}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(So(r,"utf-8"))}catch{return c("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return c("Plan data is empty. Call mist_plan again.",!0);let d=sa(s);d||(d={planId:s,iterationCount:0,approved:!1,screens:[],feedback:[]});let h=$e(i,".mistflow","mockups");ko(h,{recursive:!0});let m=`mockup-${s}.html`,p=$e(h,m);if(o){d.approved=!0,xo(s,d);let k=Qt(h)?Po(h).filter(_=>_.endsWith(".html")).map(_=>$e(".mistflow","mockups",_)):[];return c(JSON.stringify({status:"approved",message:`Wireframe approved after ${d.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:k,nextAction:`Call mist_init with planId='${s}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}d.iterationCount++,n&&d.feedback.push(n);let y=ta(l);d.screens=y.screens.map(k=>k.name),xo(s,d);let v=na(y,n??void 0,p),b=d.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,f=n?`Apply the user's feedback to ${p}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${p}, then open it in the browser. Ask the user if the layout feels right.`;return c(JSON.stringify({status:"wireframe",iterationCount:d.iterationCount,screens:y.screens.map(k=>({name:k.name,type:k.type,route:k.route})),wireframePrompt:v,designDirection:y.designDirection,...b?{nudge:b}:{},mockupFile:m,mockupPath:p,nextAction:f}))}};function _o(t){let e=$e(t,".mistflow","mockups");return Qt(e)?Po(e).filter(s=>s.endsWith(".html")).map(s=>$e(e,s)):[]}import{z as rs}from"zod";import{resolve as ra}from"path";import{spawn as ia}from"child_process";function Xt(t){let e=[],s=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(s)){let[,l,d,h,m,p]=a;e.push({file:l,line:parseInt(d,10),column:parseInt(h,10),message:`${m}: ${p}`,humanMessage:`There is a type error in ${l} on line ${d}: ${p}`,suggestion:`Check line ${d} in ${l}. ${m==="TS2345"?"The types of the arguments do not match.":`Fix the ${m} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(n)){let[,l,d,h,m]=a;e.some(p=>p.file===l&&p.line===parseInt(d,10))||e.push({file:l,line:parseInt(d,10),column:parseInt(h,10),message:m,humanMessage:`There is an error in ${l} on line ${d}: ${m.trim()}`,suggestion:`Check line ${d} in ${l} and fix the issue.`})}let o=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of t.matchAll(o)){let[,l,d]=a;e.push({file:d,message:`Module not found: ${l}`,humanMessage:`The file ${d??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let i=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(i)){let[,l,d]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${d}${l}`,humanMessage:`The package '${d}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${d}'.`,suggestion:`Add '${d}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let r=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of t.matchAll(r)){let[,l,d,h,m]=a;e.some(p=>p.file===l&&p.line===parseInt(h,10))||e.push({file:l,line:parseInt(h,10),column:parseInt(m,10),message:`SyntaxError: ${d}`,humanMessage:`There is a syntax error in ${l} on line ${h}.`,suggestion:`Check line ${h} in ${l} for a missing closing bracket or unexpected token.`})}return e}var aa=rs.object({projectPath:rs.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:rs.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});function la(t){return new Promise(e=>{let s=ia("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),n="";s.stdout?.on("data",o=>{n+=o.toString()}),s.stderr?.on("data",o=>{n+=o.toString()}),s.on("error",o=>{e({exitCode:127,combined:`${n}
1774
+ ${o.message}`})}),s.on("close",o=>{e({exitCode:o??1,combined:n})})})}var Ro={name:"mist_debug",description:Cs,inputSchema:aa,handler:async t=>{let e=t,s=ra(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let r=await la(s);if(r.exitCode===0)return c(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=r.combined}let o=Xt(n),i=n.slice(0,2e3);return o.length===0?c(JSON.stringify({errors:o,rawOutput:i,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):c(JSON.stringify({errors:o,rawOutput:i,message:`Found ${o.length} error${o.length===1?"":"s"} in the build output.`}))}};import{z as E}from"zod";import{existsSync as Tt,mkdirSync as tn,readFileSync as Do,readdirSync as ba,statSync as wa,unlinkSync as va,writeFileSync as nn}from"fs";import{dirname as xa,isAbsolute as ka,join as le}from"path";import{homedir as Ue}from"os";import{createHash as Sa,createHmac as Oo,randomBytes as Pa,randomUUID as jo,timingSafeEqual as Ia}from"crypto";de();function Zt(t,e,s,n=3e3){if(e===void 0)return{stop:()=>{}};let o=0,i=!1,a=setInterval(()=>{i||(o++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:o,message:s()}}).catch(()=>{}))},n);return{stop:()=>{i||(i=!0,clearInterval(a))}}}var ca=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:t=>t.surfaceType==="internal-tool"||t.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:t=>t.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:t=>t.scheduling===!0,keywords:/\b(schedul|book|reserv|appointment|calendar|slot)\b/i},{name:"Payments / Billing",description:"Charge users, invoices, subscriptions (experimental \u2014 Stripe integration is early-stage)",condition:()=>!1,keywords:/\b(payment|billing|invoice|subscription|checkout|stripe)\b/i},{name:"Admin Panel",description:"Manage users, roles, and content",condition:t=>t.multiRole===!0||t.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:t=>t.primaryActor==="customers"||t.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:t=>t.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:t=>t.integrations?.includes("email")===!0,keywords:/\b(notification|alert|reminder|email.?notif|sms|welcome.?email)\b/i},{name:"Analytics / Reports",description:"Usage stats, trends, data exports",condition:()=>!1,keywords:/\b(analytics|report|chart|trend|insight|metric)\b/i},{name:"File Uploads",description:"Images, documents, attachments",condition:t=>t.integrations?.includes("file-uploads")===!0,keywords:/\b(upload|image|photo|attachment|document|gallery|file)\b/i},{name:"AI Features",description:"Chatbot, content generation, AI assistant",condition:t=>t.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:t=>t.integrations?.includes("maps")===!0,keywords:/\b(map|location|address|geo|places)\b/i},{name:"Voice / TTS",description:"Text-to-speech, voice notes, audio generation",condition:()=>!1,keywords:/\b(voice|tts|text.?to.?speech|audio|speak|narrat|podcast|elevenlabs)\b/i},{name:"SMS / Text Messages",description:"Send SMS notifications, OTP verification",condition:t=>t.integrations?.includes("sms")===!0,keywords:/\b(sms|text.?message|twilio|otp|verification.?code|phone.?verif)\b/i},{name:"Web Scraping",description:"Scrape URLs, crawl websites, extract structured data",condition:()=>!1,keywords:/\b(scrape|crawl|web.?scrap|extract.?from.?url|read.?url|ingest.?web|firecrawl)\b/i},{name:"Chat / Messaging",description:"Real-time messaging between users",condition:()=>!1,keywords:/\b(chat|messag|inbox|conversation|dm)\b/i},{name:"Events / Tournaments",description:"Create and manage events, registrations",condition:()=>!1,keywords:/\b(event|tournament|competition|league|registration)\b/i},{name:"High Scores",description:"Track and display top scores with a leaderboard",condition:t=>t.surfaceType==="game",keywords:/\b(high.?score|leaderboard|top.?score|ranking|scoreboard)\b/i},{name:"Save Progress",description:"Save and resume game state between sessions",condition:t=>t.surfaceType==="game",keywords:/\b(save|progress|resume|checkpoint|continue)\b/i},{name:"Guest Play",description:"Play immediately without signing up, optionally link account later",condition:t=>t.surfaceType==="game",keywords:/\b(guest|anonymous|no.?login|play.?now|instant.?play)\b/i},{name:"Levels / Stages",description:"Progressive difficulty with unlockable stages",condition:()=>!1,keywords:/\b(level|stage|unlock|difficult|progress|world)\b/i},{name:"Achievements",description:"Badges, trophies, and milestones for player accomplishments",condition:()=>!1,keywords:/\b(achieve|badge|trophy|milestone|reward|unlock)\b/i},{name:"Daily Challenge",description:"New puzzle or challenge every day to keep players coming back",condition:()=>!1,keywords:/\b(daily|challenge|streak|word.?of.?the.?day|puzzle.?of)\b/i}];function Co(t,e,s){let n=s?.suggestedName||da(t),o=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",i=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),r=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",a;if(s?.suggestedFeatures&&s.suggestedFeatures.length>0)a=s.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;a=[];for(let d of ca){let h=d.keywords.test(l),m=d.condition(e);(h||m)&&a.push({name:d.name,description:d.description,checked:h,source:h?"explicit":"suggested"})}}return{name:n,audience:o,audienceType:i,surfaceType:r,primaryAction:e.primaryAction||"manage items",features:a,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:s?.language||"English"}}function Ao(t){let e=t.features.filter(a=>a.checked),s=t.features.filter(a=>!a.checked),n={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},o={neon:"Postgres",turso:"SQLite (legacy)"},i={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},r=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${i[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${n[t.authModel]??t.authModel} | Database: ${o[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){r.push("**Included:**");for(let a of e)r.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(r.push(""),r.push(`**Integrations:** ${t.integrations.join(", ")}`)),s.length>0){r.push(""),r.push("**Available to add:**");for(let a of s)r.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return r.join(`
1775
+ `)}function da(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return is(e[1]);let s=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),o=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(i=>i.length>2&&!s.has(i)).slice(0,3);return o.length===0?"my-app":o.join("-")}function is(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var pa=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],ua=["sharp","soft","pill","organic"],ma=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"];function as(t,e,s){return e.includes(t)?t:s}function ae(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ct(t,e){return typeof t!="string"?e:/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(t.trim())?t.trim():e}function ha(t){let e=new Set;for(let n of t)n.fonts?.display&&e.add(n.fonts.display),n.fonts?.body&&e.add(n.fonts.body);return e.size===0?"":`https://fonts.googleapis.com/css2?${[...e].map(n=>`family=${n.trim().replace(/\s+/g,"+").replace(/[^A-Za-z0-9+]/g,"")}:wght@400;700`).join("&")}&display=swap`}function Eo(t){let e=(t||"").trim(),s=e.toLowerCase(),n=/mono|courier|code/.test(s)?"ui-monospace, monospace":/serif|garamond|bodoni|fraunces|playfair|lora|sentient|migra|sectra|cormorant|abril|crimson/.test(s)?"Georgia, serif":"system-ui, sans-serif";return e?`"${e.replace(/"/g,"")}", ${n}`:n}function ga(t){switch(t){case"sharp":return{card:"0px",button:"0px",chip:"0px"};case"pill":return{card:"20px",button:"999px",chip:"999px"};case"organic":return{card:"4px 24px 4px 24px",button:"24px 4px 24px 4px",chip:"12px 2px 12px 2px"};default:return{card:"10px",button:"8px",chip:"6px"}}}function fa(){let t=`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>")`;return`
1773
1776
  .card-hero { position: relative; overflow: hidden; isolation: isolate; }
1774
1777
  .card-hero::before {
1775
1778
  content: "";
@@ -1827,67 +1830,67 @@ ${s.message}`})}),o.on("close",s=>{e({exitCode:s??1,combined:n})})})}var Is={nam
1827
1830
  backdrop-filter: blur(14px);
1828
1831
  mix-blend-mode: normal;
1829
1832
  }
1830
- `}function ma(t,e,o,n){let s=tt(t.colors?.bg??"","#0f0f0f"),a=tt(t.colors?.fg??"","#f5f5f5"),r=tt(t.colors?.accent??"","#7c9cff"),i=ee(t.name),l=ee(t.hero_headline||t.name),p=ee(t.body_sample||t.summary||""),m=ee(t.cta_text||"Continue"),u=`<div class="hero-eyebrow" style="font-family:${o}">${i.toUpperCase()}</div>`,d=`<h2 class="hero-headline" style="font-family:${e}">${l}</h2>`,b=`<p class="hero-body" style="font-family:${o}">${p}</p>`,T=`<button class="hero-cta" style="background:${r};color:${s};font-family:${o};border-radius:${n.button}">${m}</button>`,w=to(t.hero_treatment,aa,"typographic");if(w==="terminal"){let y=`"${(t.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
1831
- ${u}
1832
- <div class="hero-terminal-lines" style="font-family:${y};color:${a}">
1833
+ `}function ya(t,e,s,n){let o=ct(t.colors?.bg??"","#0f0f0f"),i=ct(t.colors?.fg??"","#f5f5f5"),r=ct(t.colors?.accent??"","#7c9cff"),a=ae(t.name),l=ae(t.hero_headline||t.name),d=ae(t.body_sample||t.summary||""),h=ae(t.cta_text||"Continue"),m=`<div class="hero-eyebrow" style="font-family:${s}">${a.toUpperCase()}</div>`,p=`<h2 class="hero-headline" style="font-family:${e}">${l}</h2>`,y=`<p class="hero-body" style="font-family:${s}">${d}</p>`,v=`<button class="hero-cta" style="background:${r};color:${o};font-family:${s};border-radius:${n.button}">${h}</button>`,b=as(t.hero_treatment,pa,"typographic");if(b==="terminal"){let f=`"${(t.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
1834
+ ${m}
1835
+ <div class="hero-terminal-lines" style="font-family:${f};color:${i}">
1833
1836
  <div>$ status --all</div>
1834
1837
  <div>api.service.......<span style="color:${r}">OK</span></div>
1835
1838
  <div>worker.queue......<span style="color:${r}">OK</span></div>
1836
1839
  <div>db.primary.......<span style="color:${r}">OK</span></div>
1837
1840
  </div>
1838
- ${d}
1839
- ${b}
1840
- <div class="hero-cta-row">${T}</div>
1841
- `}return w==="split-panel"?`
1841
+ ${p}
1842
+ ${y}
1843
+ <div class="hero-cta-row">${v}</div>
1844
+ `}return b==="split-panel"?`
1842
1845
  <div class="hero-split">
1843
- <div class="hero-split-left" style="background:${r};color:${s};font-family:${e}">
1844
- <div class="hero-split-mark" style="font-family:${o};color:${s}">${i[0]??"\xB7"}</div>
1846
+ <div class="hero-split-left" style="background:${r};color:${o};font-family:${e}">
1847
+ <div class="hero-split-mark" style="font-family:${s};color:${o}">${a[0]??"\xB7"}</div>
1845
1848
  </div>
1846
1849
  <div class="hero-split-right">
1847
- ${u}
1848
- ${d}
1849
- ${b}
1850
- <div class="hero-cta-row">${T}</div>
1850
+ ${m}
1851
+ ${p}
1852
+ ${y}
1853
+ <div class="hero-cta-row">${v}</div>
1851
1854
  </div>
1852
1855
  </div>
1853
- `:w==="full-bleed-photo"?`
1854
- <div class="hero-photo" style="background: linear-gradient(160deg, ${r}30 0%, ${a}08 35%, ${s} 100%), ${s}">
1855
- <span class="hero-photo-label" style="font-family:${o};color:${a}">photo slot</span>
1856
+ `:b==="full-bleed-photo"?`
1857
+ <div class="hero-photo" style="background: linear-gradient(160deg, ${r}30 0%, ${i}08 35%, ${o} 100%), ${o}">
1858
+ <span class="hero-photo-label" style="font-family:${s};color:${i}">photo slot</span>
1856
1859
  </div>
1857
- ${u}
1858
- ${d}
1859
- ${b}
1860
- <div class="hero-cta-row">${T}</div>
1861
- `:w==="magazine-hero"?`
1862
- ${u}
1860
+ ${m}
1861
+ ${p}
1862
+ ${y}
1863
+ <div class="hero-cta-row">${v}</div>
1864
+ `:b==="magazine-hero"?`
1865
+ ${m}
1863
1866
  <h2 class="hero-headline hero-headline-mag" style="font-family:${e}">${l}</h2>
1864
- <div class="hero-rule" style="background:${a}"></div>
1865
- <p class="hero-body hero-body-mag" style="font-family:${o}">${p}</p>
1866
- <div class="hero-byline" style="font-family:${o};color:${a}">\u2014 Volume 01 \xB7 Issue 01</div>
1867
- <div class="hero-cta-row">${T}</div>
1867
+ <div class="hero-rule" style="background:${i}"></div>
1868
+ <p class="hero-body hero-body-mag" style="font-family:${s}">${d}</p>
1869
+ <div class="hero-byline" style="font-family:${s};color:${i}">\u2014 Volume 01 \xB7 Issue 01</div>
1870
+ <div class="hero-cta-row">${v}</div>
1868
1871
  `:`
1869
- ${u}
1870
- ${d}
1871
- ${b}
1872
- <div class="hero-cta-row">${T}</div>
1873
- `}function As(t,e){let o=pa(e),n=e.map(s=>{let a=tt(s.colors?.bg??"","#0f0f0f"),r=tt(s.colors?.fg??"","#f5f5f5"),i=tt(s.colors?.accent??"","#7c9cff"),l=Rs(s.fonts?.display??""),p=Rs(s.fonts?.body??""),m=to(s.shape_lang,la,"soft"),u=to(s.texture,ca,"flat"),d=da(m),b=ma(s,l,p,d),T=ee(s.name),w=ee(s.id),y=ee(s.fonts?.display??""),x=ee(s.fonts?.body??""),M=ee(s.summary||""),J=ee(s.decoration_hint||""),H=(se,q)=>`<div class="card-meta-row"><span class="card-meta-label">${se}</span><span class="card-meta-value">${q}</span></div>`;return` <article class="card" data-direction-id="${w}" style="border-radius:${d.card}">
1874
- <div class="card-hero texture-${u}" style="background:${a};color:${r}">${b}
1872
+ ${m}
1873
+ ${p}
1874
+ ${y}
1875
+ <div class="hero-cta-row">${v}</div>
1876
+ `}function No(t,e){let s=ha(e),n=e.map(o=>{let i=ct(o.colors?.bg??"","#0f0f0f"),r=ct(o.colors?.fg??"","#f5f5f5"),a=ct(o.colors?.accent??"","#7c9cff"),l=Eo(o.fonts?.display??""),d=Eo(o.fonts?.body??""),h=as(o.shape_lang,ua,"soft"),m=as(o.texture,ma,"flat"),p=ga(h),y=ya(o,l,d,p),v=ae(o.name),b=ae(o.id),f=ae(o.fonts?.display??""),k=ae(o.fonts?.body??""),_=ae(o.summary||""),N=ae(o.decoration_hint||""),S=(D,$)=>`<div class="card-meta-row"><span class="card-meta-label">${D}</span><span class="card-meta-value">${$}</span></div>`;return` <article class="card" data-direction-id="${b}" style="border-radius:${p.card}">
1877
+ <div class="card-hero texture-${m}" style="background:${i};color:${r}">${y}
1875
1878
  </div>
1876
1879
  <div class="card-meta" style="border-top-color:${r}14">
1877
- <div class="card-meta-title">${T}</div>
1878
- <p class="card-meta-summary">${M}</p>
1879
- ${H("Fonts",`${y||"\u2014"} <span class="sep">\xB7</span> ${x||"\u2014"}`)}
1880
- ${H("Palette",`
1880
+ <div class="card-meta-title">${v}</div>
1881
+ <p class="card-meta-summary">${_}</p>
1882
+ ${S("Fonts",`${f||"\u2014"} <span class="sep">\xB7</span> ${k||"\u2014"}`)}
1883
+ ${S("Palette",`
1881
1884
  <span class="card-meta-swatches">
1882
- <span class="card-meta-swatch" title="${a}" style="background:${a}"></span>
1883
- <span class="card-meta-swatch" title="${r}" style="background:${r}"></span>
1884
1885
  <span class="card-meta-swatch" title="${i}" style="background:${i}"></span>
1886
+ <span class="card-meta-swatch" title="${r}" style="background:${r}"></span>
1887
+ <span class="card-meta-swatch" title="${a}" style="background:${a}"></span>
1885
1888
  </span>
1886
1889
  `)}
1887
- ${H("Shape",`<span class="chip" style="border-radius:${d.chip}">${m}</span>`)}
1888
- ${H("Texture",`<span class="chip" style="border-radius:${d.chip}">${ee(u)}</span>`)}
1889
- ${J?H("Decoration",ee(J)):""}
1890
- ${H("Pick with",`<code>${T}</code>`)}
1890
+ ${S("Shape",`<span class="chip" style="border-radius:${p.chip}">${h}</span>`)}
1891
+ ${S("Texture",`<span class="chip" style="border-radius:${p.chip}">${ae(m)}</span>`)}
1892
+ ${N?S("Decoration",ae(N)):""}
1893
+ ${S("Pick with",`<code>${v}</code>`)}
1891
1894
  </div>
1892
1895
  </article>`}).join(`
1893
1896
  `);return`<!DOCTYPE html>
@@ -1895,10 +1898,10 @@ ${s.message}`})}),o.on("close",s=>{e({exitCode:s??1,combined:n})})})}var Is={nam
1895
1898
  <head>
1896
1899
  <meta charset="UTF-8" />
1897
1900
  <meta name="viewport" content="width=device-width,initial-scale=1" />
1898
- <title>Design directions \u2014 ${ee(t)}</title>
1901
+ <title>Design directions \u2014 ${ae(t)}</title>
1899
1902
  <link rel="preconnect" href="https://fonts.googleapis.com" />
1900
1903
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
1901
- ${o?`<link rel="stylesheet" href="${o}" />`:""}
1904
+ ${s?`<link rel="stylesheet" href="${s}" />`:""}
1902
1905
  <style>
1903
1906
  :root {
1904
1907
  --chrome-bg: #f4f3ef;
@@ -2082,7 +2085,7 @@ ${s.message}`})}),o.on("close",s=>{e({exitCode:s??1,combined:n})})})}var Is={nam
2082
2085
  margin-top: 4px;
2083
2086
  }
2084
2087
 
2085
- ${ua()}
2088
+ ${fa()}
2086
2089
 
2087
2090
  /* \u2500\u2500 Card meta footer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2088
2091
  .card-meta {
@@ -2191,7 +2194,7 @@ ${s.message}`})}),o.on("close",s=>{e({exitCode:s??1,combined:n})})})}var Is={nam
2191
2194
  <div class="page">
2192
2195
  <header class="page-header">
2193
2196
  <div class="eyebrow"><span class="eyebrow-dot"></span>Mistflow \xB7 design direction</div>
2194
- <h1 class="page-title">How should <strong>${ee(t)}</strong> feel?</h1>
2197
+ <h1 class="page-title">How should <strong>${ae(t)}</strong> feel?</h1>
2195
2198
  <p class="page-sub">Each card commits to a different extreme \u2014 different fonts, colors, hero layout, corner radius, texture, and voice. Pick one by telling your coding assistant its name, or describe your own.</p>
2196
2199
  </header>
2197
2200
 
@@ -2211,31 +2214,31 @@ ${n}
2211
2214
  </div>
2212
2215
  </body>
2213
2216
  </html>
2214
- `}var Qt="__mistflow_url_choice__",ka=600*1e3;function js(){let t=te(Ce(),".mistflow","confirm-secret");if(St(t))try{return Buffer.from(Es(t,"utf-8").trim(),"hex")}catch{}let e=va(32);return Xt(te(Ce(),".mistflow"),{recursive:!0}),Zt(t,e.toString("hex"),{mode:384}),e}function Ds(t){return wa("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function Sa(t,e){let o={cwd:t,d:Ds(e),exp:Date.now()+ka},n=Buffer.from(JSON.stringify(o)).toString("base64url"),s=Ns("sha256",js()).update(n).digest("base64url");return`${n}.${s}`}function Pa(t,e,o){let n=t.split(".");if(n.length!==2)return!1;let[s,a]=n,r=Ns("sha256",js()).update(s).digest("base64url"),i=Buffer.from(a),l=Buffer.from(r);if(i.length!==l.length||!xa(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!==Ds(o))}catch{return!1}}function Ia(t){let e=t,o=Ce(),n=!1;for(let s=0;s<64;s++){if(St(te(e,"mistflow.json")))return"mistflow";if(!n&&St(te(e,"package.json"))&&(n=!0),e===o)break;let a=ya(e);if(a===e)break;e=a}return n?"foreign":"none"}function _a(t){let e=Ce(),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===te(e,s))return!0;return!1}var Ta=I.object({description:I.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:I.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:I.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:I.record(I.string()).optional().describe("User's answers to the clarifying questions from the previous round. Keys are the questions, values are the answers."),existingPlan:I.record(I.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:I.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:I.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:I.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:I.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.object({id:I.string().optional(),name:I.string().optional(),summary:I.string().optional(),heroHeadline:I.string().optional(),ctaText:I.string().optional(),bodySample:I.string().optional(),fontsHint:I.string().optional(),fonts:I.object({display:I.string(),body:I.string()}).partial().optional(),colorMood:I.string().optional(),colors:I.object({bg:I.string(),fg:I.string(),accent:I.string()}).partial().optional(),heroTreatment:I.string().optional(),shapeLang:I.string().optional(),texture:I.string().optional(),decorationHint:I.string().optional(),custom:I.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.")});function Ra(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 Aa(t){let e=te(Ce(),".mistflow","plans",`${t}.json`);if(!St(e))return null;try{return JSON.parse(Es(e,"utf-8")).plan??null}catch{return null}}async function Ca(t){for(let n=0;n<60;n++){try{let s=await _n(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 Ea(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:T,confirmToken:w,urlChoice:y,designConversationId:x,designDirection:M}=t;if(s&&!o&&!a&&!x&&!M&&!r&&!i&&!l)try{let h=await $t(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}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as questions are ready.`})):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}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the plan is ready.`})):c(JSON.stringify(h))}catch(h){let g=h instanceof Error?h.message:String(h);return c(`Could not poll plan conversation '${s}': ${g}`,!0)}let J=o??"";if(!J.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 H=r;if(!H&&i&&(H=Aa(i)??void 0,!H))return c("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let se=s;if(!G())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let q;if(!se&&!H&&!l){if(!ba(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=Ia(n);if(h!=="mistflow"&&_a(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(`
2215
- `)}),!0);if(h==="foreign"&&!T){if(!(w?Pa(w,n,J):!1)){let S=Sa(n,J);return c(JSON.stringify({status:"confirm_new_project",projectPath:n,description:J,confirmToken:S,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:"Creates a fresh project in this folder without touching the existing code."},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",w?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
2216
- `)}))}q="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"&&T&&(q="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 Fn(l)).plan)return c("This template has no plan to fork. Try a different template.",!0);let g=await qn(l),S=g.plan,P="";if(p&&g.has_source)try{let X=await Lt(g.plan,p),U=X.plan??X,Et=X.diff,F=U?.steps??[],un=new Set([...(Et?.added??[]).map(le=>le.number),...(Et?.modified??[]).map(le=>le.number)]),Pe=F.map(le=>{let Cr=le.number;return un.has(Cr)?{...le,status:"pending"}:{...le,status:"completed",source:"forked"}});U.steps=Pe,S=U;let Me=Pe.filter(le=>le.status==="pending").length;P=` Remixed: ${Pe.filter(le=>le.status==="completed").length} steps unchanged, ${Me} steps need re-implementation.`}catch(X){console.error("[plan] Remix failed, using original plan:",X),P=" (Remix failed \u2014 using original plan. You can modify it later.)"}let W=Cs(),L=te(Ce(),".mistflow","plans");Xt(L,{recursive:!0}),Zt(te(L,`${W}.json`),JSON.stringify({plan:S,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let Y=S?.name??"forked-app",Q=g.has_source,dt=Q?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Oe=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:W,forkedFrom:g.forked_from,projectId:g.id,hasSource:Q,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${P}${Oe} ${dt} NEXT: Call mist_init, name='${Y}', and planId='${W}' to create the project now.`}))}catch(h){let g=h instanceof Error?h.message:"Failed to fork template";return c(g,!0)}if(H){let h;try{h=await Lt(H,J)}catch(L){let Y=L instanceof Error?L.message:"Failed to modify plan";return c(Y,!0)}let g=h.plan,S=h.diff,P=[];if(S?.added?.length){let L=S.added.map(Y=>Y.title);P.push(`Added ${L.length} step(s): ${L.join(", ")}`)}if(S?.removed?.length){let L=S.removed.map(Y=>Y.title);P.push(`Removed ${L.length} step(s): ${L.join(", ")}`)}if(S?.modified?.length){let L=S.modified.map(Y=>Y.title);P.push(`Modified ${L.length} step(s): ${L.join(", ")}`)}let W=P.length>0?P.join(". "):"No changes detected.";return c(JSON.stringify({plan:g,diff:S,message:`Plan modified. ${W}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let v=y?.trim()||void 0,$=a;if(!v&&a&&Qt in a&&(v=a[Qt]),a&&Qt in a){let{[Qt]:h,...g}=a;$=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 K;if(M){K={...M};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,S]of Object.entries(h))M[g]!==void 0&&K[S]===void 0&&(K[S]=M[g])}let ne=a?"Generating plan with your answers (LLM call)":x?"Finalizing design direction":"Thinking through discovery questions",he=e?Yt(e.server,e.progressToken,()=>ne):{stop:()=>{}};e&&(e.cleanup=()=>he.stop());let C;try{se&&!$&&!x&&!H&&!i?C=await $t(se):C=await Tn(J,{conversationId:se,answers:$,autonomous:m,language:u,designConversationId:x,designDirection:K})}catch(h){he.stop();let g=h instanceof Error?h.message:"Failed to generate plan";return c(g,!0)}if(C.status==="clarify_pending"){he.stop();let h=C;return c(JSON.stringify({status:"running",conversationId:h.conversation_id,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${h.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.`}))}if(C.status==="plan_pending"){he.stop();let h=C;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}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(C.status==="design_clarify_pending"&&(ne="Generating creative design directions",C=await Ca(C)),he.stop(),C.status==="clarify"){let h=C.reflection||"",g=C.suggestedName||"",S=C.suggestedFeatures??[],P=C.questions??[],W=P.some(F=>Array.isArray(F.options)&&typeof F.options[0]=="object"&&F.options[0]?.label),L={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"},Y=P.map(F=>{let un=F.decisionKey&&L[F.decisionKey]||Ra(F.question),Pe;return W&&Array.isArray(F.options)?Pe=F.options.map(Me=>({label:Me.label,description:Me.description??""})):Array.isArray(F.options)?Pe=F.options.map((Me,xo)=>({label:xo===0?`${Me} (Recommended)`:String(Me),description:F.why??""})):Pe=[{label:"Yes (Recommended)",description:F.why??""},{label:"No",description:""}],{question:F.question,header:un,options:Pe,multiSelect:!1}}),dt=C.decisions?.audienceType??null,Oe=S.length>0?_s(J,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:dt,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:S,language:u}):null,X=Oe?Ts(Oe):"",U=eo(g||"my-app").slice(0,32);try{let F=await Pn(U);!F.available&&F.suggestion&&(U=F.suggestion)}catch{}X&&(X+=`
2217
-
2218
- **Your app URL:** https://${U}.mistflow.app`);let Et={question:`Your app will be at ${U}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${U}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};return Y.push(Et),c(JSON.stringify({status:"clarify",conversation_id:C.conversation_id,questions:P,questionCount:P.length,suggestedFeatures:S,suggestedName:g,suggestedSubdomain:U,reflection:h,briefText:X,askUserQuestions:Y,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:[...q?[q,""]:[],h?`${h}
2219
- `:"",X?`Here's what I'd build:
2220
-
2221
- ${X}
2222
- `:"",`I have ${P.length} quick question${P.length===1?"":"s"} to pin down the details.`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST call the AskUserQuestion tool (not a text prompt, not a","bash echo, not a chat message) to present these questions. The","user has to click through them. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping AskUserQuestion because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call it: pass each object in the `askUserQuestions` array","below directly to AskUserQuestion. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","If your host does NOT expose AskUserQuestion (Cursor, Codex, some","other MCP clients), present each question one at a time as a","clearly-numbered chat message with all options visible, and WAIT","for a user reply before moving on. Still do NOT infer answers.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${C.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${U}".`,'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(`
2223
- `)}))}if(C.status==="design_clarify"){let h=C.directions??[],g=C.plan.name??"your app",S;try{let Q=h.map(U=>({id:U.id,name:U.name,summary:U.summary,hero_headline:U.hero_headline,cta_text:U.cta_text,body_sample:U.body_sample,fonts:U.fonts,colors:U.colors,hero_treatment:U.hero_treatment,shape_lang:U.shape_lang,texture:U.texture,decoration_hint:U.decoration_hint})),dt=As(g,Q),Oe=te(n,".mistflow");Xt(Oe,{recursive:!0});let X=te(Oe,"design-directions.html");Zt(X,dt,"utf-8"),S=X}catch(Q){console.error(`[mist_plan] design-directions preview render failed: ${Q instanceof Error?Q.message:String(Q)}`)}let P=h.map(Q=>({label:Q.name,description:`${Q.summary} \u2014 ${Q.fonts?.display??""} + ${Q.fonts?.body??""}`}));P.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let W={question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:P,multiSelect:!1},L=S?`A visual preview of all ${h.length} directions has been written to ${S}. 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.",Y=S?`open "${S}"`:"";return c(JSON.stringify({status:"design_clarify",designConversationId:C.design_conversation_id,directions:h,previewPath:S,askUserQuestion:W,instruction:[`The plan for "${g}" is ready. I've proposed ${h.length} creative directions \u2014 each commits to a specific aesthetic (fonts, colors, voice).`,"",L,Y?`Run this command for the user: ${Y}`:"","","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: "${C.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(`
2224
- `)}))}let E=C.plan,ge=E.name??"Untitled App",Se=C.methodology,j=E.steps;if(!Array.isArray(j)||j.length===0)return c("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let oe=E.publicPages;if(!oe||Array.isArray(oe)&&oe.length===0){let h=E.pages,g=j.some(P=>typeof P.name=="string"&&P.name.toLowerCase().includes("landing")||typeof P.title=="string"&&P.title.toLowerCase().includes("landing")),S=Array.isArray(h)&&h.some(P=>P.path==="/"||P.route==="/");g||S?oe=["/","/pricing"]:oe=["/"]}let lt=E.primaryAction;if(!lt){let h=E.features;if(Array.isArray(h)&&h.length>0){let S=h.find(W=>typeof W.priority=="string"&&W.priority.toLowerCase()==="must-have")??h[0];lt={entity:S.name??S.title??"item",action:"create",fromPage:"/dashboard"}}}let Ne=E.nonNegotiables;(!Ne||Array.isArray(Ne)&&Ne.length===0)&&(Ne=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let B=Cs(),Be=te(Ce(),".mistflow","plans");Xt(Be,{recursive:!0});try{let g=Date.now();for(let S of[Be,te(Ce(),".mistflow","mockup-state")])if(St(S))for(let P of ha(S))try{let W=te(S,P),L=ga(W).mtimeMs;g-L>6048e5&&fa(W)}catch{}}catch{}let re;if(d){let h=zt(d);h?re=h.id:console.error(`Landing design '${d}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let je=b||void 0,ae=!!re,ct=j.some(h=>{let g=`${h.name??h.title} ${h.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),fe=!ae&&ct?cs(J,{maxResults:2}):[];fe.length>0&&(re=fe[0].id,console.error(`Auto-assigned landing layout preset (default): ${fe[0].title} (${re})`));let pn={name:E.name,summary:E.summary,dataModel:E.dataModel,pages:E.pages,features:E.features,steps:j.map(h=>({...h,name:h.name??h.title})),design:E.design,landingDesign:re,appStyle:je,dbProvider:E.dbProvider??"neon",authModel:E.authModel,audienceType:E.audienceType??"b2c",roles:E.roles,defaultRole:E.defaultRole,publicPages:oe,navStyle:E.navStyle,multiTenant:E.multiTenant,primaryAction:lt,nonNegotiables:Ne,requestedSubdomain:v,...u&&u.toLowerCase()!=="english"?{language:u}:{}};Zt(te(Be,`${B}.json`),JSON.stringify({plan:pn,methodology:Se}));let dn=j.map(h=>`${h.number}. ${h.name??h.title}`),ve="",pt=[],De;!ae&&fe.length>0&&(pt=fe.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${Ge()}/designs?tab=landing-designs`})),De={question:"What landing page style fits this app?",header:"Landing Design",options:[...fe.map((g,S)=>({label:S===0?`${g.title} (Recommended)`:g.title,description:g.description})),{label:"Design from scratch (Creative)",description:"No template \u2014 the AI designs a bespoke hero from your app's concept using 3D, scroll-driven animation, or particle effects. Higher creative ceiling, takes ~10 min longer, occasionally needs a second pass."},{label:"Browse all landing designs",description:`Not sure? See all landing designs at ${Ge()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},ve=` 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: ${fe.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='${fe[0].id}' explicitly.`);let Ct="",f=[],k=void 0,z=(E.audienceType??"b2c")==="b2c",ye={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:z?"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:z?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},be=" 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.",_="",O=[];for(let h of j){let g=h.name??h.title,S=h.integrationId;if(S){let P=Qe(S);if(P){let W=Xe(P.id);O.push({step:g,presetId:P.id,presetName:P.name,envVars:W?.envVars??[]})}}}if(O.length>0){let h=O.flatMap(P=>P.envVars),g=[...new Set(h.map(P=>P.key))];_=` This plan uses integrations (${O.map(P=>P.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:B,name:E.name,summary:E.summary,stepCount:j.length,steps:dn,design:E.design,...re?{landingDesign:re}:{},...je?{appStyle:je}:{},...f.length>0?{recommendedAppStyles:f}:{},...k?{appStyleQuestion:k}:{},...pt.length>0?{recommendedLandingDesigns:pt}:{},...De?{landingDesignQuestion:De}:{},heroPhotoQuestion:ye,...O.length>0?{integrations:O.map(h=>({step:h.step,preset:h.presetId,name:h.presetName,envVars:h.envVars}))}:{},message:`Plan generated for "${ge}" (${j.length} steps).${re?` Landing layout "${re}" set as default.`:""}${je?` App style "${je}" will be applied across all pages.`:""}${_}${Ct}${ve}${be}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,j.length*3)}\u2013${j.length*5} minutes total across ${j.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_mockup({ planId: '${B}' }). If the user says skip or "just build it", call mist_init({ planId: '${B}', path: '<absolute path>' }) immediately.`,...q?{warning:q}:{}}))}var Os={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(`
2225
- `),inputSchema:Ta,handler:Ea};import{z as Pt}from"zod";import{existsSync as Fe,mkdirSync as ao,writeFileSync as lo,readFileSync as tn,readdirSync as qs,copyFileSync as Da}from"fs";import{join as ue,resolve as Bs,dirname as It,isAbsolute as Oa}from"path";import{homedir as Ma}from"os";import{spawn as Pd}from"child_process";import{randomBytes as Ua}from"crypto";import{simpleGit as La}from"simple-git";ie();$e();function Ms(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 Na(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function ja(t){let e=Ms(t);return e.charAt(0).toLowerCase()+e.slice(1)}function oo(){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(`
2226
- `)}function Us(){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(`
2227
- `)}var no="<!-- mist:contracts:start -->",$s="<!-- mist:contracts:end -->";function so(t){let e=Us();if(t.includes(no)){let n=t.indexOf(no),s=$s,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+$/,"")+`
2228
-
2229
- `+e}function ro(t,e){let o=Ms(t),n=e??ja(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${n} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${o}Schema = createSelectSchema(${n});`,`export type ${o} = z.infer<typeof ${o}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${o}Input = createInsertSchema(${n}).omit({`," id: true,"," createdAt: true,","});",`export type Create${o}Input = z.infer<typeof Create${o}Input>;`,""].join(`
2230
- `)}function io(t){return`contracts/${Na(t)}.ts`}function $a(t){let e=ue(Ma(),".mistflow","plans",`${t}.json`);if(!Fe(e))return null;try{let o=JSON.parse(tn(e,"utf-8"));return o.plan?{plan:o.plan}:null}catch{return null}}function Fa(t){let e=It(Bs(t)),o=10,n=0;for(;n<o&&e!==It(e);){if(Fe(ue(e,"pnpm-workspace.yaml"))||Fe(ue(e,"lerna.json")))return e;let s=ue(e,"package.json");if(Fe(s))try{if(JSON.parse(tn(s,"utf-8")).workspaces)return e}catch{}e=It(e),n++}return null}var qa=Pt.object({name:Pt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:Pt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Pt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Pt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});function R(t,e,o){let n=ue(t,e);ao(It(n),{recursive:!0}),lo(n,o)}function Ba(t){if(!Fe(t))return!0;let e;try{e=qs(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}var za={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Ha=[["--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"]];function Wa(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let o=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},s=o.split(`
2231
- `),a=null,r=null,i=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of s){let p=l.replace(/\r$/,"");if(!p.trim()||p.trim().startsWith("#"))continue;if(p.startsWith("theme:")){let d=i(p.slice(6).trim());(d==="dark"||d==="light")&&(n.theme=d);continue}let m=p.match(/^(colors|typography|rounded|spacing):\s*$/);if(m){a=m[1],r=null;continue}if(a==="typography"){let d=p.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(d){r=d[1].replace(/-/g,"_"),n.typography[r]={};continue}let b=p.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(b&&r){n.typography[r][b[1]]=i(b[2]);continue}}let u=p.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(u&&a){let d=u[1].replace(/-/g,"_"),b=i(u[2]);a==="colors"?n.colors[d]=b:a==="rounded"?n.rounded[d]=b:a==="spacing"&&(n.spacing[d]=b)}}return n}function Ga(t,e){let o=t.colors,s=[["--color-background",o.background],["--color-foreground",o.on_background??o.on_surface],["--color-card",o.surface??o.background],["--color-card-foreground",o.on_surface??o.on_background],["--color-popover",o.surface??o.background],["--color-popover-foreground",o.on_surface??o.on_background],["--color-muted",o.surface_variant??o.outline_variant??o.outline],["--color-muted-foreground",o.on_surface_variant??o.outline],["--color-border",o.outline_variant??o.outline],["--color-input",o.outline_variant??o.outline],["--color-primary",o.primary],["--color-primary-foreground",o.on_primary],["--color-ring",o.primary],["--color-secondary",o.secondary],["--color-secondary-foreground",o.on_secondary],["--color-accent",o.secondary],["--color-accent-foreground",o.on_secondary],["--color-destructive",o.error],["--color-destructive-foreground",o.on_error],["--color-success",o.success],["--color-success-foreground",o.on_success],["--color-warning",o.warning],["--color-warning-foreground",o.on_warning],["--color-info",o.info??o.primary],["--color-info-foreground",o.on_info??o.on_primary]].filter(i=>typeof i[1]=="string").map(([i,l])=>` ${i}: ${l};`).join(`
2232
- `),a=[` --radius-sm: ${t.rounded.sm??"0.25rem"};`,` --radius-md: ${t.rounded.md??e};`,` --radius-lg: ${t.rounded.lg??"0.5rem"};`,` --radius-xl: ${t.rounded.xl??"0.75rem"};`].join(`
2217
+ `}var en="__mistflow_url_choice__",Ta=600*1e3;function Mo(){let t=le(Ue(),".mistflow","confirm-secret");if(Tt(t))try{return Buffer.from(Do(t,"utf-8").trim(),"hex")}catch{}let e=Pa(32);return tn(le(Ue(),".mistflow"),{recursive:!0}),nn(t,e.toString("hex"),{mode:384}),e}function $o(t){return Sa("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function _a(t,e){let s={cwd:t,d:$o(e),exp:Date.now()+Ta},n=Buffer.from(JSON.stringify(s)).toString("base64url"),o=Oo("sha256",Mo()).update(n).digest("base64url");return`${n}.${o}`}function Ra(t,e,s){let n=t.split(".");if(n.length!==2)return!1;let[o,i]=n,r=Oo("sha256",Mo()).update(o).digest("base64url"),a=Buffer.from(i),l=Buffer.from(r);if(a.length!==l.length||!Ia(a,l))return!1;try{let d=JSON.parse(Buffer.from(o,"base64url").toString("utf-8"));return!(typeof d.exp!="number"||Date.now()>d.exp||d.cwd!==e||d.d!==$o(s))}catch{return!1}}function Ca(t){let e=t,s=Ue(),n=!1;for(let o=0;o<64;o++){if(Tt(le(e,"mistflow.json")))return"mistflow";if(!n&&Tt(le(e,"package.json"))&&(n=!0),e===s)break;let i=xa(e);if(i===e)break;e=i}return n?"foreign":"none"}function Aa(t){let e=Ue(),s=t.replace(/\/+$/,"");if(s===e||s==="/"||s===""||s==="/tmp"||s==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let o of n)if(s===le(e,o))return!0;return!1}var Ea=E.object({description:E.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:E.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:E.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:E.record(E.string()).optional().describe("User's answers to the clarifying questions from the previous round. Keys are the questions, values are the answers."),existingPlan:E.record(E.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:E.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:E.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:E.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:E.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.object({id:E.string().optional(),name:E.string().optional(),summary:E.string().optional(),heroHeadline:E.string().optional(),ctaText:E.string().optional(),bodySample:E.string().optional(),fontsHint:E.string().optional(),fonts:E.object({display:E.string(),body:E.string()}).partial().optional(),colorMood:E.string().optional(),colors:E.object({bg:E.string(),fg:E.string(),accent:E.string()}).partial().optional(),heroTreatment:E.string().optional(),shapeLang:E.string().optional(),texture:E.string().optional(),decorationHint:E.string().optional(),custom:E.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.")});function Na(t){let e=[[/payment/i,"Payments"],[/database/i,"Database"],[/auth|sign.?up|login|access/i,"Access"],[/landing.?page/i,"Landing page"],[/who.*using|user|role/i,"Users"],[/design|theme|style/i,"Design"],[/deploy/i,"Deploy"],[/domain/i,"Domain"],[/notification/i,"Notify"],[/email/i,"Email"],[/mobile|responsive/i,"Mobile"],[/integrat/i,"Integration"],[/field|info|propert|detail|contain/i,"Item shape"],[/view|layout|board|grid|list|timeline/i,"View"],[/scope|how many|one.*or.*many|multi/i,"Scope"],[/share|read.?only|viewer|stakeholder/i,"Sharing"],[/workflow|status|state|move|stage|pipeline/i,"Workflow"],[/avoid|bloat|simple|complex|minimal/i,"Constraints"],[/time.*period|quarter|month|sprint/i,"Time periods"],[/swimlane|column|group|categor/i,"Structure"]];for(let[n,o]of e)if(n.test(t))return o;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(n=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(n.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function ja(t){let e=le(Ue(),".mistflow","plans",`${t}.json`);if(!Tt(e))return null;try{return JSON.parse(Do(e,"utf-8")).plan??null}catch{return null}}async function Da(t){for(let n=0;n<60;n++){try{let o=await An(t.design_conversation_id);if(o.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:o.directions,plan:o.plan,methodology:o.methodology};if(o.status==="failed")return{status:"ready",plan:o.plan,methodology:o.methodology}}catch(o){let i=o instanceof Error?o.message:String(o);if(i.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll attempt ${n+1} failed: ${i}`)}await new Promise(o=>setTimeout(o,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:t.plan,methodology:t.methodology}}async function Oa(t,e){let{description:s,projectPath:n,conversationId:o,answers:i,existingPlan:r,existingPlanId:a,templateToken:l,remixDescription:d,autonomous:h,language:m,landingDesign:p,appStyle:y,brandMentioned:v,confirmToken:b,urlChoice:f,designConversationId:k,designDirection:_}=t;if(o&&!s&&!i&&!k&&!_&&!r&&!a&&!l)try{let u=await qt(o);return u.status==="clarify_pending"?c(JSON.stringify({status:"running",conversationId:o,phase:"generating_questions",nextAction:`Still generating. Call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as questions are ready.`})):u.status==="plan_pending"?c(JSON.stringify({status:"running",conversationId:o,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the plan is ready.`})):c(JSON.stringify(u))}catch(u){let g=u instanceof Error?u.message:String(u);return c(`Could not poll plan conversation '${o}': ${g}`,!0)}let N=s??"";if(!N.trim()&&!o&&!r&&!a&&!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 S=r;if(!S&&a&&(S=ja(a)??void 0,!S))return c("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let D=o;if(!X())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let $;if(!D&&!S&&!l){if(!ka(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 u=Ca(n);if(u!=="mistflow"&&Aa(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(`
2218
+ `)}),!0);if(u==="foreign"&&!v){if(!(b?Ra(b,n,N):!1)){let P=_a(n,N);return c(JSON.stringify({status:"confirm_new_project",projectPath:n,description:N,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.",b?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
2219
+ `)}))}$="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else u==="foreign"&&v&&($="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 Gn(l)).plan)return c("This template has no plan to fork. Try a different template.",!0);let g=await Vn(l),P=g.plan,T="";if(d&&g.has_source)try{let re=await Bt(g.plan,d),H=re.plan??re,jt=re.diff,J=H?.steps??[],fn=new Set([...(jt?.added??[]).map(fe=>fe.number),...(jt?.modified??[]).map(fe=>fe.number)]),Ne=J.map(fe=>{let Mr=fe.number;return fn.has(Mr)?{...fe,status:"pending"}:{...fe,status:"completed",source:"forked"}});H.steps=Ne,P=H;let We=Ne.filter(fe=>fe.status==="pending").length;T=` Remixed: ${Ne.filter(fe=>fe.status==="completed").length} steps unchanged, ${We} steps need re-implementation.`}catch(re){console.error("[plan] Remix failed, using original plan:",re),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let K=jo(),V=le(Ue(),".mistflow","plans");tn(V,{recursive:!0}),nn(le(V,`${K}.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 te=P?.name??"forked-app",oe=g.has_source,ht=oe?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",He=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:K,forkedFrom:g.forked_from,projectId:g.id,hasSource:oe,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${T}${He} ${ht} NEXT: Call mist_init, name='${te}', and planId='${K}' to create the project now.`}))}catch(u){let g=u instanceof Error?u.message:"Failed to fork template";return c(g,!0)}if(S){let u;try{u=await Bt(S,N)}catch(V){let te=V instanceof Error?V.message:"Failed to modify plan";return c(te,!0)}let g=u.plan,P=u.diff,T=[];if(P?.added?.length){let V=P.added.map(te=>te.title);T.push(`Added ${V.length} step(s): ${V.join(", ")}`)}if(P?.removed?.length){let V=P.removed.map(te=>te.title);T.push(`Removed ${V.length} step(s): ${V.join(", ")}`)}if(P?.modified?.length){let V=P.modified.map(te=>te.title);T.push(`Modified ${V.length} step(s): ${V.join(", ")}`)}let K=T.length>0?T.join(". "):"No changes detected.";return c(JSON.stringify({plan:g,diff:P,message:`Plan modified. ${K}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let x=f?.trim()||void 0,M=i;if(!x&&i&&en in i&&(x=i[en]),i&&en in i){let{[en]:u,...g}=i;M=Object.keys(g).length>0?g:void 0}if(x&&(x=x.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),x){let u=x.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(u)?x=u:(console.error(`[mist_plan] Discarding urlChoice '${x}' \u2014 does not look like a subdomain. Backend will auto-generate.`),x=void 0)}let z;if(_){z={..._};let u={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[g,P]of Object.entries(u))_[g]!==void 0&&z[P]===void 0&&(z[P]=_[g])}let W=i?"Generating plan with your answers (LLM call)":k?"Finalizing design direction":"Thinking through discovery questions",ne=e?Zt(e.server,e.progressToken,()=>W):{stop:()=>{}};e&&(e.cleanup=()=>ne.stop());let A;try{D&&!M&&!k&&!S&&!a?A=await qt(D):A=await En(N,{conversationId:D,answers:M,autonomous:h,language:m,designConversationId:k,designDirection:z})}catch(u){ne.stop();let g=u instanceof Error?u.message:"Failed to generate plan";return c(g,!0)}if(A.status==="clarify_pending"){ne.stop();let u=A;return c(JSON.stringify({status:"running",conversationId:u.conversation_id,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${u.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.`}))}if(A.status==="plan_pending"){ne.stop();let u=A;return c(JSON.stringify({status:"running",conversationId:u.conversation_id,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${u.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(A.status==="design_clarify_pending"&&(W="Generating creative design directions",A=await Da(A)),ne.stop(),A.status==="clarify"){let u=A.reflection||"",g=A.suggestedName||"",P=A.suggestedFeatures??[],T=A.questions??[],K=T.some(J=>Array.isArray(J.options)&&typeof J.options[0]=="object"&&J.options[0]?.label),V={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"},te=T.map(J=>{let fn=J.decisionKey&&V[J.decisionKey]||Na(J.question),Ne;return K&&Array.isArray(J.options)?Ne=J.options.map(We=>({label:We.label,description:We.description??""})):Array.isArray(J.options)?Ne=J.options.map((We,Ps)=>({label:Ps===0?`${We} (Recommended)`:String(We),description:J.why??""})):Ne=[{label:"Yes (Recommended)",description:J.why??""},{label:"No",description:""}],{question:J.question,header:fn,options:Ne,multiSelect:!1}}),ht=A.decisions?.audienceType??null,He=P.length>0?Co(N,{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:m}):null,re=He?Ao(He):"",H=is(g||"my-app").slice(0,32);try{let J=await Rn(H);!J.available&&J.suggestion&&(H=J.suggestion)}catch{}re&&(re+=`
2220
+
2221
+ **Your app URL:** https://${H}.mistflow.app`);let jt={question:`Your app will be at ${H}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${H}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};return te.push(jt),c(JSON.stringify({status:"clarify",conversation_id:A.conversation_id,questions:T,questionCount:T.length,suggestedFeatures:P,suggestedName:g,suggestedSubdomain:H,reflection:u,briefText:re,askUserQuestions:te,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:[...$?[$,""]:[],u?`${u}
2222
+ `:"",re?`Here's what I'd build:
2223
+
2224
+ ${re}
2225
+ `:"",`I have ${T.length} quick question${T.length===1?"":"s"} to pin down the details.`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST call the AskUserQuestion tool (not a text prompt, not a","bash echo, not a chat message) to present these questions. The","user has to click through them. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping AskUserQuestion because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call it: pass each object in the `askUserQuestions` array","below directly to AskUserQuestion. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","If your host does NOT expose AskUserQuestion (Cursor, Codex, some","other MCP clients), present each question one at a time as a","clearly-numbered chat message with all options visible, and WAIT","for a user reply before moving on. Still do NOT infer answers.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${A.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${H}".`,'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(`
2226
+ `)}))}if(A.status==="design_clarify"){let u=A.directions??[],g=A.plan.name??"your app",P;try{let oe=u.map(H=>({id:H.id,name:H.name,summary:H.summary,hero_headline:H.hero_headline,cta_text:H.cta_text,body_sample:H.body_sample,fonts:H.fonts,colors:H.colors,hero_treatment:H.hero_treatment,shape_lang:H.shape_lang,texture:H.texture,decoration_hint:H.decoration_hint})),ht=No(g,oe),He=le(n,".mistflow");tn(He,{recursive:!0});let re=le(He,"design-directions.html");nn(re,ht,"utf-8"),P=re}catch(oe){console.error(`[mist_plan] design-directions preview render failed: ${oe instanceof Error?oe.message:String(oe)}`)}let T=u.map(oe=>({label:oe.name,description:`${oe.summary} \u2014 ${oe.fonts?.display??""} + ${oe.fonts?.body??""}`}));T.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let K={question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:T,multiSelect:!1},V=P?`A visual preview of all ${u.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.",te=P?`open "${P}"`:"";return c(JSON.stringify({status:"design_clarify",designConversationId:A.design_conversation_id,directions:u,previewPath:P,askUserQuestion:K,instruction:[`The plan for "${g}" is ready. I've proposed ${u.length} creative directions \u2014 each commits to a specific aesthetic (fonts, colors, voice).`,"",V,te?`Run this command for the user: ${te}`:"","","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: "${A.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(`
2227
+ `)}))}let R=A.plan,se=R.name??"Untitled App",ce=A.methodology,j=R.steps;if(!Array.isArray(j)||j.length===0)return c("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let Q=R.publicPages;if(!Q||Array.isArray(Q)&&Q.length===0){let u=R.pages,g=j.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),P=Array.isArray(u)&&u.some(T=>T.path==="/"||T.route==="/");g||P?Q=["/","/pricing"]:Q=["/"]}let Se=R.primaryAction;if(!Se){let u=R.features;if(Array.isArray(u)&&u.length>0){let P=u.find(K=>typeof K.priority=="string"&&K.priority.toLowerCase()==="must-have")??u[0];Se={entity:P.name??P.title??"item",action:"create",fromPage:"/dashboard"}}}let pe=R.nonNegotiables;(!pe||Array.isArray(pe)&&pe.length===0)&&(pe=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Pe=jo(),Fe=le(Ue(),".mistflow","plans");tn(Fe,{recursive:!0});try{let g=Date.now();for(let P of[Fe,le(Ue(),".mistflow","mockup-state")])if(Tt(P))for(let T of ba(P))try{let K=le(P,T),V=wa(K).mtimeMs;g-V>6048e5&&va(K)}catch{}}catch{}let F;if(p){let u=Gt(p);u?F=u.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let C=y||void 0,B=!!F,he=j.some(u=>{let g=`${u.name??u.title} ${u.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),G=!B&&he?uo(N,{maxResults:2}):[];G.length>0&&(F=G[0].id,console.error(`Auto-assigned landing layout preset (default): ${G[0].title} (${F})`));let ke={name:R.name,summary:R.summary,dataModel:R.dataModel,pages:R.pages,features:R.features,steps:j.map(u=>({...u,name:u.name??u.title})),design:R.design,landingDesign:F,appStyle:C,dbProvider:R.dbProvider??"neon",authModel:R.authModel,audienceType:R.audienceType??"b2c",roles:R.roles,defaultRole:R.defaultRole,publicPages:Q,navStyle:R.navStyle,multiTenant:R.multiTenant,primaryAction:Se,nonNegotiables:pe,requestedSubdomain:x,...m&&m.toLowerCase()!=="english"?{language:m}:{}};nn(le(Fe,`${Pe}.json`),JSON.stringify({plan:ke,methodology:ce}));let qe=j.map(u=>`${u.number}. ${u.name??u.title}`),Be="",ze=[],ue;!B&&G.length>0&&(ze=G.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${et()}/designs?tab=landing-designs`})),ue={question:"What landing page style fits this app?",header:"Landing Design",options:[...G.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 ${et()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},Be=` 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: ${G.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='${G[0].id}' explicitly.`);let Ce="",Ae=[],Ee=void 0,I=(R.audienceType??"b2c")==="b2c",q={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:I?"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:I?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},Y=" 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.",ge="",ee=[];for(let u of j){let g=u.name??u.title,P=u.integrationId;if(P){let T=rt(P);if(T){let K=it(T.id);ee.push({step:g,presetId:T.id,presetName:T.name,envVars:K?.envVars??[]})}}}if(ee.length>0){let u=ee.flatMap(T=>T.envVars),g=[...new Set(u.map(T=>T.key))];ge=` This plan uses integrations (${ee.map(T=>T.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return c(JSON.stringify({planId:Pe,name:R.name,summary:R.summary,stepCount:j.length,steps:qe,design:R.design,...F?{landingDesign:F}:{},...C?{appStyle:C}:{},...Ae.length>0?{recommendedAppStyles:Ae}:{},...Ee?{appStyleQuestion:Ee}:{},...ze.length>0?{recommendedLandingDesigns:ze}:{},...ue?{landingDesignQuestion:ue}:{},heroPhotoQuestion:q,...ee.length>0?{integrations:ee.map(u=>({step:u.step,preset:u.presetId,name:u.presetName,envVars:u.envVars}))}:{},message:`Plan generated for "${se}" (${j.length} steps).${F?` Landing layout "${F}" set as default.`:""}${C?` App style "${C}" will be applied across all pages.`:""}${ge}${Ce}${Be}${Y}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,j.length*3)}\u2013${j.length*5} minutes total across ${j.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_mockup({ planId: '${Pe}' }). If the user says skip or "just build it", call mist_init({ planId: '${Pe}', path: '<absolute path>' }) immediately.`,...$?{warning:$}:{}}))}var Uo={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(`
2228
+ `),inputSchema:Ea,handler:Oa};import{z as _t}from"zod";import{existsSync as Ye,mkdirSync as ms,writeFileSync as hs,readFileSync as on,readdirSync as Ho,copyFileSync as Ua}from"fs";import{join as ve,resolve as Wo,dirname as Rt,isAbsolute as La}from"path";import{homedir as Fa}from"os";import{spawn as Op}from"child_process";import{randomBytes as qa}from"crypto";import{simpleGit as za}from"simple-git";de();Ve();function Lo(t){if(!t)return"Item";let e=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return e.length===0?"Item":e.map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")}function Ma(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function $a(t){let e=Lo(t);return e.charAt(0).toLowerCase()+e.slice(1)}function cs(){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(`
2229
+ `)}function Fo(){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(`
2230
+ `)}var ls="<!-- mist:contracts:start -->",qo="<!-- mist:contracts:end -->";function ds(t){let e=Fo();if(t.includes(ls)){let n=t.indexOf(ls),o=qo,i=t.indexOf(o,n);if(i===-1)return t.slice(0,n)+e;let r=t.slice(i+o.length);return t.slice(0,n)+e+r.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
2231
+
2232
+ `+e}function ps(t,e){let s=Lo(t),n=e??$a(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${n} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${s}Schema = createSelectSchema(${n});`,`export type ${s} = z.infer<typeof ${s}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${s}Input = createInsertSchema(${n}).omit({`," id: true,"," createdAt: true,","});",`export type Create${s}Input = z.infer<typeof Create${s}Input>;`,""].join(`
2233
+ `)}function us(t){return`contracts/${Ma(t)}.ts`}function Ba(t){let e=ve(Fa(),".mistflow","plans",`${t}.json`);if(!Ye(e))return null;try{let s=JSON.parse(on(e,"utf-8"));return s.plan?{plan:s.plan}:null}catch{return null}}function Ha(t){let e=Rt(Wo(t)),s=10,n=0;for(;n<s&&e!==Rt(e);){if(Ye(ve(e,"pnpm-workspace.yaml"))||Ye(ve(e,"lerna.json")))return e;let o=ve(e,"package.json");if(Ye(o))try{if(JSON.parse(on(o,"utf-8")).workspaces)return e}catch{}e=Rt(e),n++}return null}var Wa=_t.object({name:_t.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:_t.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:_t.string().optional().describe("Absolute path where the project should be scaffolded."),planId:_t.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});function O(t,e,s){let n=ve(t,e);ms(Rt(n),{recursive:!0}),hs(n,s)}function Ga(t){if(!Ye(t))return!0;let e;try{e=Ho(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}var Va={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Ja=[["--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"]];function Ya(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let s=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},o=s.split(`
2234
+ `),i=null,r=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of o){let d=l.replace(/\r$/,"");if(!d.trim()||d.trim().startsWith("#"))continue;if(d.startsWith("theme:")){let p=a(d.slice(6).trim());(p==="dark"||p==="light")&&(n.theme=p);continue}let h=d.match(/^(colors|typography|rounded|spacing):\s*$/);if(h){i=h[1],r=null;continue}if(i==="typography"){let p=d.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(p){r=p[1].replace(/-/g,"_"),n.typography[r]={};continue}let y=d.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(y&&r){n.typography[r][y[1]]=a(y[2]);continue}}let m=d.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(m&&i){let p=m[1].replace(/-/g,"_"),y=a(m[2]);i==="colors"?n.colors[p]=y:i==="rounded"?n.rounded[p]=y:i==="spacing"&&(n.spacing[p]=y)}}return n}function Ka(t,e){let s=t.colors,o=[["--color-background",s.background],["--color-foreground",s.on_background??s.on_surface],["--color-card",s.surface??s.background],["--color-card-foreground",s.on_surface??s.on_background],["--color-popover",s.surface??s.background],["--color-popover-foreground",s.on_surface??s.on_background],["--color-muted",s.surface_variant??s.outline_variant??s.outline],["--color-muted-foreground",s.on_surface_variant??s.outline],["--color-border",s.outline_variant??s.outline],["--color-input",s.outline_variant??s.outline],["--color-primary",s.primary],["--color-primary-foreground",s.on_primary],["--color-ring",s.primary],["--color-secondary",s.secondary],["--color-secondary-foreground",s.on_secondary],["--color-accent",s.secondary],["--color-accent-foreground",s.on_secondary],["--color-destructive",s.error],["--color-destructive-foreground",s.on_error],["--color-success",s.success],["--color-success-foreground",s.on_success],["--color-warning",s.warning],["--color-warning-foreground",s.on_warning],["--color-info",s.info??s.primary],["--color-info-foreground",s.on_info??s.on_primary]].filter(a=>typeof a[1]=="string").map(([a,l])=>` ${a}: ${l};`).join(`
2235
+ `),i=[` --radius-sm: ${t.rounded.sm??"0.25rem"};`,` --radius-md: ${t.rounded.md??e};`,` --radius-lg: ${t.rounded.lg??"0.5rem"};`,` --radius-xl: ${t.rounded.xl??"0.75rem"};`].join(`
2233
2236
  `);return`@import "tailwindcss";
2234
2237
  @import "tw-animate-css";
2235
2238
 
2236
2239
  @theme {
2237
- ${s}
2238
- ${a}
2240
+ ${o}
2241
+ ${i}
2239
2242
  }
2240
2243
 
2241
2244
 
@@ -2285,11 +2288,11 @@ ${a}
2285
2288
 
2286
2289
  button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
2287
2290
  button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
2288
- `}function Va(t,e,o){let n=t?.borderRadius??"subtle",s=za[n]??"0.375rem";if(o){let r=Wa(o);if(r)return Ga(r,s)}return`@import "tailwindcss";
2291
+ `}function Qa(t,e,s){let n=t?.borderRadius??"subtle",o=Va[n]??"0.375rem";if(s){let r=Ya(s);if(r)return Ka(r,o)}return`@import "tailwindcss";
2289
2292
  @import "tw-animate-css";
2290
2293
 
2291
2294
  @theme {
2292
- ${[...Ha.map(([r,i])=>` ${r}: ${i};`)," --radius-sm: 0.25rem;",` --radius-md: ${s};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
2295
+ ${[...Ja.map(([r,a])=>` ${r}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md: ${o};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
2293
2296
  `)}
2294
2297
  }
2295
2298
 
@@ -2339,7 +2342,7 @@ ${[...Ha.map(([r,i])=>` ${r}: ${i};`)," --radius-sm: 0.25rem;",` --radius-md:
2339
2342
 
2340
2343
  button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
2341
2344
  button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
2342
- `}var Ls={"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"};function Fs(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return Ls[e]?Ls[e]:e.replace(/\s+/g,"_")}function Ja(t){return t?{english:"en",spanish:"es",french:"fr",german:"de",italian:"it",portuguese:"pt",dutch:"nl",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",arabic:"ar",hebrew:"he",hindi:"hi",turkish:"tr",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",thai:"th",vietnamese:"vi",indonesian:"id",malay:"ms",farsi:"fa",persian:"fa",czech:"cs",greek:"el",romanian:"ro",hungarian:"hu",ukrainian:"uk",bengali:"bn",tamil:"ta",telugu:"te",urdu:"ur"}[t.toLowerCase()]??"en":"en"}var Ka=new Set(["ar","he","fa","ur"]);function Ya(t,e,o){let n=t.replace(/[\\"`$]/g,""),s=Ja(o),r=Ka.has(s)?`lang="${s}" dir="rtl"`:`lang="${s}"`,i=e?.fonts?.heading,l=e?.fonts?.body;if(!i&&!l)return`import type { Metadata } from "next";
2345
+ `}var Bo={"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"};function zo(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return Bo[e]?Bo[e]:e.replace(/\s+/g,"_")}function Xa(t){return t?{english:"en",spanish:"es",french:"fr",german:"de",italian:"it",portuguese:"pt",dutch:"nl",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",arabic:"ar",hebrew:"he",hindi:"hi",turkish:"tr",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",thai:"th",vietnamese:"vi",indonesian:"id",malay:"ms",farsi:"fa",persian:"fa",czech:"cs",greek:"el",romanian:"ro",hungarian:"hu",ukrainian:"uk",bengali:"bn",tamil:"ta",telugu:"te",urdu:"ur"}[t.toLowerCase()]??"en":"en"}var Za=new Set(["ar","he","fa","ur"]);function el(t,e,s){let n=t.replace(/[\\"`$]/g,""),o=Xa(s),r=Za.has(o)?`lang="${o}" dir="rtl"`:`lang="${o}"`,a=e?.fonts?.heading,l=e?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
2343
2346
  import { DM_Sans } from "next/font/google";
2344
2347
  import { Toaster } from "sonner";
2345
2348
  import "./globals.css";
@@ -2355,12 +2358,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2355
2358
  </html>
2356
2359
  );
2357
2360
  }
2358
- `;let p=Fs(i??l),m=Fs(l??i);return p===m?`import type { Metadata } from "next";
2359
- import { ${p} } from "next/font/google";
2361
+ `;let d=zo(a??l),h=zo(l??a);return d===h?`import type { Metadata } from "next";
2362
+ import { ${d} } from "next/font/google";
2360
2363
  import { Toaster } from "sonner";
2361
2364
  import "./globals.css";
2362
2365
 
2363
- const font = ${p}({ subsets: ["latin"], variable: "--font-body" });
2366
+ const font = ${d}({ subsets: ["latin"], variable: "--font-body" });
2364
2367
 
2365
2368
  export const metadata: Metadata = { title: "${n}", description: "Built with Mistflow" };
2366
2369
 
@@ -2372,12 +2375,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2372
2375
  );
2373
2376
  }
2374
2377
  `:`import type { Metadata } from "next";
2375
- import { ${p}, ${m} } from "next/font/google";
2378
+ import { ${d}, ${h} } from "next/font/google";
2376
2379
  import { Toaster } from "sonner";
2377
2380
  import "./globals.css";
2378
2381
 
2379
- const heading = ${p}({ subsets: ["latin"], variable: "--font-heading" });
2380
- const body = ${m}({ subsets: ["latin"], variable: "--font-body" });
2382
+ const heading = ${d}({ subsets: ["latin"], variable: "--font-heading" });
2383
+ const body = ${h}({ subsets: ["latin"], variable: "--font-body" });
2381
2384
 
2382
2385
  export const metadata: Metadata = { title: "${n}", description: "Built with Mistflow" };
2383
2386
 
@@ -2388,63 +2391,63 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2388
2391
  </html>
2389
2392
  );
2390
2393
  }
2391
- `}function en(t,...e){let o=JSON.stringify(t).toLowerCase();return e.some(n=>o.includes(n.toLowerCase()))}var Qa={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"};function co(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[o,n]of Object.entries(Qa))if(e.includes(o))return n;return"Circle"}function _t(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Xa(t){if(t.authModel==="none")return null;let e=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed"];if(t.publicPages&&Array.isArray(t.publicPages))for(let a of t.publicPages){if(typeof a!="string"||a.length<1)continue;let r=a.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!r)continue;let i=r.startsWith("/")?r:"/"+r;e.includes(i)||e.push(i)}let o=e.filter(a=>a==="/"),n=e.filter(a=>a!=="/"),s=[];s.push('import { NextRequest, NextResponse } from "next/server";'),s.push(""),s.push("const PUBLIC_PREFIXES = [");for(let a of n)s.push(' "'+a+'",');return s.push("];"),s.push(""),o.length>0&&(s.push('const PUBLIC_EXACT = ["'+o.join('", "')+'"];'),s.push("")),s.push("export function middleware(req: NextRequest) {"),s.push(" const { pathname, search } = req.nextUrl;"),s.push(""),o.length>0&&s.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),s.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),s.push(""),s.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),s.push(" if (!token) {"),s.push(' const loginUrl = new URL("/login", req.url);'),s.push(" const params = new URLSearchParams(search);"),s.push(' for (const key of ["verified", "error"]) {'),s.push(" const v = params.get(key);"),s.push(" if (v) loginUrl.searchParams.set(key, v);"),s.push(" }"),s.push(" return NextResponse.redirect(loginUrl);"),s.push(" }"),s.push(""),s.push(" return NextResponse.next();"),s.push("}"),s.push(""),s.push("export const config = {"),s.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),s.push("};"),s.push(""),s.join(`
2392
- `)}function Za(t){if(t.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],n=(t.pages??[]).filter(l=>{let p=l.path??l.route??"";return p==="/"||p===""||p.includes("[")||p.replace(/^\//,"").split("/").length>1?!1:!e.some(u=>p.startsWith(u))}).map(l=>{let p=l.path??l.route??"",m=p.startsWith("/")?p:"/"+p,u=l.name??_t(p.replace(/^\//,"")),d=co(u);return{label:u,href:m,icon:d}});n.some(l=>l.href==="/dashboard")||n.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let s=t.authModel==="none",a=[...new Set(n.map(l=>l.icon))];s||a.push("LogOut");let r=_t(t.name);if(t.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),s||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+a.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let p of n)l.push(' { label: "'+p.label+'", href: "'+p.href+'", icon: '+p.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+r+"</span>"),l.push(' <div className="flex items-center gap-1">'),l.push(" {NAV_ITEMS.map((item) => ("),l.push(" <Link"),l.push(" key={item.href}"),l.push(" href={item.href}"),l.push(' aria-current={pathname === item.href ? "page" : undefined}'),l.push(" className={cn("),l.push(' "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",'),l.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground"'),l.push(" )}"),l.push(" >"),l.push(' <item.icon className="h-4 w-4" />'),l.push(" {item.label}"),l.push(" </Link>"),l.push(" ))}"),l.push(" </div>"),l.push(" </div>"),s?l.push(' <span className="text-sm text-muted-foreground">{user.name}</span>'):(l.push(' <div className="flex items-center gap-2">'),l.push(' <span className="text-sm text-muted-foreground">{user.email}</span>'),l.push(" <Button"),l.push(' variant="ghost"'),l.push(' size="sm"'),l.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),l.push(" >"),l.push(' <LogOut className="h-4 w-4" />'),l.push(" </Button>"),l.push(" </div>")),l.push(" </div>"),l.push(" </nav>"),l.push(" );"),l.push("}"),l.push(""),{path:"components/topnav.tsx",content:l.join(`
2393
- `)}}let i=[];i.push('"use client";'),i.push(""),i.push('import { useState } from "react";'),i.push('import Link from "next/link";'),i.push('import { usePathname } from "next/navigation";'),s||i.push('import { authClient } from "@/lib/auth-client";'),i.push('import { Button } from "@/components/ui/button";'),i.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),i.push('import { cn } from "@/lib/utils";'),i.push("import { Menu, "+a.join(", ")+' } from "lucide-react";'),i.push(""),i.push("interface SidebarProps {"),i.push(" user: { name: string | null; email: string; role?: string | undefined };"),i.push("}"),i.push(""),i.push("const NAV_ITEMS = [");for(let l of n)i.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return i.push("];"),i.push(""),i.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),i.push(" return ("),i.push(" <>"),i.push(' <div className="flex h-14 items-center border-b px-4">'),i.push(' <span className="text-lg font-semibold">'+r+"</span>"),i.push(" </div>"),i.push(' <nav className="flex-1 space-y-1 p-2">'),i.push(" {NAV_ITEMS.map((item) => ("),i.push(" <Link"),i.push(" key={item.href}"),i.push(" href={item.href}"),i.push(" onClick={onNavigate}"),i.push(' aria-current={pathname === item.href ? "page" : undefined}'),i.push(" className={cn("),i.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),i.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),i.push(" )}"),i.push(" >"),i.push(' <item.icon className="h-4 w-4" />'),i.push(" {item.label}"),i.push(" </Link>"),i.push(" ))}"),i.push(" </nav>"),i.push(' <div className="border-t p-4">'),i.push(' <div className="flex items-center gap-3">'),i.push(' <div className="flex-1 truncate">'),i.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),i.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),i.push(" </div>"),s||(i.push(" <Button"),i.push(' variant="ghost"'),i.push(' size="icon"'),i.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),i.push(" >"),i.push(' <LogOut className="h-4 w-4" />'),i.push(" </Button>")),i.push(" </div>"),i.push(" </div>"),i.push(" </>"),i.push(" );"),i.push("}"),i.push(""),i.push("export default function Sidebar({ user }: SidebarProps) {"),i.push(" const pathname = usePathname();"),i.push(" const [open, setOpen] = useState(false);"),i.push(""),i.push(" return ("),i.push(" <>"),i.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),i.push(" <NavContent pathname={pathname} user={user} />"),i.push(" </aside>"),i.push(' <div className="sticky top-0 z-[var(--z-sticky)] flex h-14 items-center gap-3 border-b bg-card px-4 md:hidden">'),i.push(" <Sheet open={open} onOpenChange={setOpen}>"),i.push(" <SheetTrigger asChild>"),i.push(' <Button variant="ghost" size="icon" className="-ml-2">'),i.push(' <Menu className="h-5 w-5" />'),i.push(" </Button>"),i.push(" </SheetTrigger>"),i.push(' <SheetContent side="left" className="w-64 p-0">'),i.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),i.push(' <div className="flex h-full flex-col">'),i.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),i.push(" </div>"),i.push(" </SheetContent>"),i.push(" </Sheet>"),i.push(' <span className="text-lg font-semibold">'+r+"</span>"),i.push(" </div>"),i.push(" </>"),i.push(" );"),i.push("}"),i.push(""),{path:"components/sidebar.tsx",content:i.join(`
2394
- `)}}function el(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,o=t.defaultRole??e[0],n=[];n.push("export type Role = "+e.map(s=>'"'+s+'"').join(" | ")+";"),n.push(""),n.push("export const ROLES = ["+e.map(s=>'"'+s+'"').join(", ")+"] as const;"),n.push(""),n.push('export const DEFAULT_ROLE: Role = "'+o+'";'),n.push(""),n.push("export const ROLE_LABELS: Record<Role, string> = {");for(let s of e){let a=s.charAt(0).toUpperCase()+s.slice(1);n.push(' "'+s+'": "'+a+'",')}return n.push("};"),n.push(""),n.push("export function getUserRole(user: Record<string, unknown>): Role {"),n.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),n.push(" if (ROLES.includes(role as Role)) return role as Role;"),n.push(" return DEFAULT_ROLE;"),n.push("}"),n.push(""),n.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),n.push(" if (!userRole) return false;"),n.push(" const allowed = Array.isArray(required) ? required : [required];"),n.push(" return allowed.includes(userRole as Role);"),n.push("}"),n.push(""),n.join(`
2395
- `)}function tl(t){let e=_t(t.name);if(t.authModel==="none"){let a=[];return a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),a.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&a.push(' <p className="mt-4 text-lg text-muted-foreground">'+t.summary+"</p>"),a.push(" </main>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
2396
- `)}let o=t.publicPages?.includes("/"),n=t.design?.landingTone;if(o&&n){let a=[];return a.push('import Link from "next/link";'),a.push(""),a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col">'),a.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),a.push(' <h1 className="text-5xl font-bold tracking-tight">'+e+"</h1>"),t.summary&&a.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+t.summary+"</p>"),a.push(' <div className="flex gap-4">'),a.push(' <Link href="/register" className="inline-flex h-11 items-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),a.push(" Get Started"),a.push(" </Link>"),a.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),a.push(" Sign In"),a.push(" </Link>"),a.push(" </div>"),a.push(" </section>"),a.push(" </main>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
2397
- `)}if(o){let a=[];return a.push('import Link from "next/link";'),a.push(""),a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),a.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&a.push(' <p className="text-lg text-muted-foreground">'+t.summary+"</p>"),a.push(' <Link href="/login" className="inline-flex h-10 items-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),a.push(" Sign In"),a.push(" </Link>"),a.push(" </main>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
2398
- `)}let s=[];return s.push('import { headers } from "next/headers";'),s.push('import { redirect } from "next/navigation";'),s.push('import { auth } from "@/lib/auth";'),s.push(""),s.push("export default async function HomePage() {"),s.push(" const session = await auth.api.getSession({ headers: await headers() });"),s.push(' if (session) redirect("/dashboard");'),s.push(' redirect("/login");'),s.push("}"),s.push(""),s.join(`
2399
- `)}function nl(t,e){let o=t.authModel==="none",n=[];o||(n.push('import { Suspense } from "react";'),n.push('import { headers } from "next/headers";'),n.push('import { redirect } from "next/navigation";'),n.push('import { auth } from "@/lib/auth";'),n.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?n.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&n.push('import Sidebar from "@/components/sidebar";'),!o&&t.roles&&t.roles.length>0&&n.push('import { getUserRole } from "@/lib/roles";'),n.push(""),n.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),o?n.push(' const user = { name: "Guest", email: "" };'):(n.push(" const session = await auth.api.getSession({ headers: await headers() });"),n.push(' if (!session) redirect("/login");'),n.push(""),t.roles&&t.roles.length>0?(n.push(" const role = getUserRole(session.user as Record<string, unknown>);"),n.push(" const user = { name: session.user.name, email: session.user.email, role };")):(n.push(" const user = {"),n.push(" name: session.user.name,"),n.push(" email: session.user.email,"),n.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),n.push(" };"))),n.push("");let s=o?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(" <TopNav user={user} />"),n.push(' <main className="mx-auto max-w-7xl p-6">'+s+"{children}</main>"),n.push(" </div>"),n.push(" );")):t.navStyle==="none"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(' <main className="mx-auto max-w-5xl p-6">'+s+"{children}</main>"),n.push(" </div>"),n.push(" );")):(n.push(" return ("),n.push(' <div className="flex flex-col md:flex-row min-h-screen">'),n.push(" <Sidebar user={user} />"),n.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+s+"{children}</main>"),n.push(" </div>"),n.push(" );")),n.push("}"),n.push(""),n.join(`
2400
- `)}function ol(t){let e=_t(t.name),o=t.dataModel??[],n=[];if(o.length>0){let s=o.map(r=>co(r.entity??r.name??"item")),a=[...new Set(s)];n.push('import { Card, CardContent } from "@/components/ui/card";'),n.push("import { "+a.join(", ")+' } from "lucide-react";'),n.push("")}if(n.push("export default function DashboardPage() {"),n.push(" return ("),n.push(' <div className="space-y-6">'),n.push(" <div>"),n.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),t.summary&&n.push(' <p className="mt-1 text-muted-foreground">'+t.summary+"</p>"),n.push(" </div>"),o.length>0){n.push(' <div className="rounded-lg border p-8 text-center">'),n.push(' <h2 className="text-lg font-semibold">Get started</h2>'),n.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),n.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let s of o){let a=s.entity??s.name??"Item",r=co(a),i=_t(a.replace(/_/g,"-"));n.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),n.push(" <"+r+' className="h-5 w-5 text-muted-foreground" />'),n.push(' <span className="text-sm font-medium">Add your first '+i+"</span>"),n.push(" </div>")}n.push(" </div>"),n.push(" </div>")}return n.push(" </div>"),n.push(" );"),n.push("}"),n.push(""),n.join(`
2401
- `)}function sl(t,e=!1){if(!t.multiTenant)return null;let o=[];return e?(o.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),o.push('import { user } from "./auth";'),o.push(""),o.push('export const organization = pgTable("organization", {'),o.push(' id: text("id").primaryKey(),'),o.push(' name: text("name").notNull(),'),o.push(' slug: text("slug").unique().notNull(),'),o.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),o.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),o.push("});"),o.push(""),o.push("export const orgMember = pgTable(")):(o.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),o.push('import { sql } from "drizzle-orm";'),o.push('import { user } from "./auth";'),o.push(""),o.push('export const organization = sqliteTable("organization", {'),o.push(' id: text("id").primaryKey(),'),o.push(' name: text("name").notNull(),'),o.push(' slug: text("slug").unique().notNull(),'),o.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),o.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),o.push("});"),o.push(""),o.push("export const orgMember = sqliteTable(")),o.push(' "org_member",'),o.push(" {"),o.push(' id: text("id").primaryKey(),'),o.push(' orgId: text("org_id").notNull().references(() => organization.id),'),o.push(' userId: text("user_id").notNull().references(() => user.id),'),o.push(' role: text("role").notNull(),'),e?o.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):o.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),o.push(" },"),o.push(" (table) => ({"),o.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),o.push(' userIdx: index("org_member_user_idx").on(table.userId),'),o.push(" }),"),o.push(");"),o.push(""),o.join(`
2402
- `)}function rl(t){if(!t.multiTenant)return null;let e=[];return e.push('import { db } from "./db";'),e.push('import { organization, orgMember } from "@/db/schema/organization";'),e.push('import { eq } from "drizzle-orm";'),e.push(""),e.push("export async function getCurrentOrg(userId: string) {"),e.push(" const membership = await db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.userId, userId))"),e.push(" .limit(1);"),e.push(" if (membership.length === 0) return null;"),e.push(" const org = await db"),e.push(" .select()"),e.push(" .from(organization)"),e.push(" .where(eq(organization.id, membership[0].orgId))"),e.push(" .limit(1);"),e.push(" return org[0] ?? null;"),e.push("}"),e.push(""),e.push("export async function getOrgMembers(orgId: string) {"),e.push(" return db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.orgId, orgId));"),e.push("}"),e.push(""),e.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),e.push(" const id = crypto.randomUUID();"),e.push(" await db.insert(orgMember).values({"),e.push(" id,"),e.push(" orgId,"),e.push(" userId: email,"),e.push(" role,"),e.push(" });"),e.push(" return { id, orgId, email, role };"),e.push("}"),e.push(""),e.join(`
2403
- `)}function il(t){if(!t.multiTenant)return null;let e=[];return e.push('"use client";'),e.push(""),e.push("import {"),e.push(" DropdownMenu,"),e.push(" DropdownMenuContent,"),e.push(" DropdownMenuItem,"),e.push(" DropdownMenuTrigger,"),e.push('} from "@/components/ui/dropdown-menu";'),e.push('import { Button } from "@/components/ui/button";'),e.push('import { ChevronsUpDown } from "lucide-react";'),e.push(""),e.push("interface OrgSwitcherProps {"),e.push(" orgs: Array<{ id: string; name: string }>;"),e.push(" currentOrgId: string;"),e.push("}"),e.push(""),e.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),e.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),e.push(""),e.push(" return ("),e.push(" <DropdownMenu>"),e.push(" <DropdownMenuTrigger asChild>"),e.push(' <Button variant="outline" className="w-full justify-between">'),e.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),e.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),e.push(" </Button>"),e.push(" </DropdownMenuTrigger>"),e.push(' <DropdownMenuContent className="w-56">'),e.push(" {orgs.map((org) => ("),e.push(" <DropdownMenuItem key={org.id}>"),e.push(" {org.name}"),e.push(" </DropdownMenuItem>"),e.push(" ))}"),e.push(" </DropdownMenuContent>"),e.push(" </DropdownMenu>"),e.push(" );"),e.push("}"),e.push(""),e.join(`
2404
- `)}function al(t,e,o){let n=[],s=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");n.push(`# ${s}`),n.push(""),e?.summary&&(n.push(e.summary),n.push(""));let a=e?.features??[];if(a.length>0){n.push("## Features"),n.push("");for(let l of a){let p=l.description?` \u2014 ${l.description}`:"";n.push(`- **${l.name}**${p}`)}n.push("")}n.push("## Tech Stack"),n.push(""),n.push("| Layer | Technology |"),n.push("|-------|------------|"),n.push("| Framework | Next.js 15 (App Router) |"),n.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),n.push("| Auth | Better Auth (email/password, social login) |"),n.push("| Styling | Tailwind CSS + shadcn/ui |"),n.push("| Deployment | Mistflow Cloud |"),o.hasStripe&&n.push("| Payments | Stripe |"),o.hasResend&&n.push("| Email | Resend + React Email |"),o.hasStorage&&n.push("| File Storage | Mistflow Cloud (managed blob storage) |"),o.hasAdmin&&n.push("| Admin | Better Auth admin plugin |"),o.hasAI&&n.push("| AI | Vercel AI SDK + OpenAI |"),n.push("");let r=e?.pages??[];if(r.length>0){n.push("## Pages"),n.push(""),n.push("| Route | Description |"),n.push("|-------|-------------|");for(let l of r){let p=l.path??l.route??l.name??"",m=l.description??"";n.push(`| \`${p.startsWith("/")?p:"/"+p}\` | ${m} |`)}n.push("")}let i=e?.dataModel??[];if(i.length>0){n.push("## Data Model"),n.push("");for(let l of i){let p=l.entity??l.name??"Unknown";if(n.push(`### ${p}`),n.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")n.push(`Fields: ${l.fields.join(", ")}`);else{n.push("| Field | Type |"),n.push("|-------|------|");for(let m of l.fields)n.push(`| ${m.name} | ${m.type} |`)}n.push("")}}}return n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),o.isNeon?n.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(n.push("| `TURSO_URL` | Database connection URL | Yes |"),n.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),n.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),o.hasStripe&&(n.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),n.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),n.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),o.hasResend&&(n.push("| `RESEND_API_KEY` | Resend API key | Yes |"),n.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),o.hasStorage&&(n.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),n.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),o.hasAI&&n.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),n.push(""),n.push("### Local database"),n.push(""),o.isNeon?(n.push("For local development, start a local Postgres server:"),n.push(""),n.push("```bash"),n.push("# Using Docker:"),n.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),n.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),n.push("```")):(n.push("For local development, start a local Turso server:"),n.push(""),n.push("```bash"),n.push("npx turso dev"),n.push("```")),n.push(""),n.push("Then set up the database:"),n.push(""),n.push("```bash"),n.push("npm run db:push"),n.push("```"),n.push(""),n.push("### Run"),n.push(""),n.push("```bash"),n.push("npm run dev"),n.push("```"),n.push(""),n.push("Open [http://localhost:3000](http://localhost:3000)."),n.push(""),n.push("## Project Structure"),n.push(""),n.push("```"),n.push("app/"),n.push(" (auth)/ Login and registration pages"),n.push(" (dashboard)/ Authenticated app pages"),o.hasAdmin&&n.push(" (admin)/ Admin panel pages"),n.push(" api/ API routes (auth, health, webhooks)"),n.push(" layout.tsx Root layout with fonts and providers"),n.push(" globals.css Design tokens and Tailwind config"),n.push("components/ Reusable UI components"),n.push("db/"),n.push(" schema/ Database table definitions"),n.push(" index.ts Schema exports"),n.push("lib/"),n.push(" auth.ts Better Auth server config"),n.push(" auth-client.ts Better Auth client config"),n.push(` db.ts ${o.isNeon?"Postgres":"SQLite"} database connection`),o.hasStripe&&n.push(" stripe.ts Stripe client"),o.hasResend&&(n.push(" resend.ts Resend client"),n.push(" email.ts Email send helpers")),o.hasStorage&&n.push(" storage.ts File upload/download helpers"),o.hasAI&&n.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),o.hasResend&&n.push("emails/ React Email templates"),n.push("```"),n.push(""),n.push("## Deploy"),n.push(""),n.push("Deploy to production with Mistflow:"),n.push(""),n.push("```"),n.push("# In your AI editor (Claude Code, Cursor, etc.):"),n.push("mist_deploy action='deploy'"),n.push("```"),n.push(""),n.push("Your app will be live at `https://<app-name>.mistflow.app`."),n.push(""),e?.design&&(n.push("## Design"),n.push(""),e.design.tone&&n.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(n.push(`- **Heading font**: ${e.design.fonts.heading}`),n.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&n.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&n.push(`- **Border radius**: ${e.design.borderRadius}`),n.push("")),n.push("---"),n.push(""),n.push("Built with [Mistflow](https://mistflow.ai)"),n.push(""),n.join(`
2405
- `)}async function ll(t,e){let{name:o,plan:n,path:s,planId:a}=t;if(!s)return c("mist_init requires an explicit 'path' \u2014 the absolute directory where the project should be scaffolded. Pass the user's project directory (e.g. /Users/alice/projects/my-app). Do not rely on a default.",!0);if(!Oa(s))return c(`mist_init 'path' must be an absolute path \u2014 received '${s}'. Pass the full absolute path to the target directory.`,!0);let r=Bs(s),i=n;if(!i&&a){let f=$a(a);if(!f)return c(`No plan found for planId '${a}'. Call mist_plan first, or pass the plan object inline.`,!0);i=f.plan}let l=i?.design,p=i?.appStyle,m=i?en(i,"stripe","payment","billing","subscription","checkout","pricing"):!1,u=!0,d=i?en(i,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,b=i?en(i,"admin panel","admin dashboard","admin management"):!1,T=i?en(i,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,w=i,y=!0;if(!Ba(r))return c(`A project already exists at this location (${r}). Choose a different name, or delete the existing folder first. (A .mistflow/ folder left over from planning is fine \u2014 init will preserve it.)`,!0);ao(r,{recursive:!0});try{let f=ue(It(r),".mistflow","mockups");if(Fe(f)){let k=qs(f).filter(D=>D.endsWith(".html"));if(k.length>0){let D=ue(r,".mistflow","mockups");ao(D,{recursive:!0});for(let z of k)Da(ue(f,z),ue(D,z));console.error(`Copied ${k.length} mockup file(s) into project`)}}}catch(f){console.error("Could not copy mockup files:",f instanceof Error?f.message:f)}let x=null;try{x=await Un("nextjs")}catch(f){console.error("Could not fetch scaffold from API, using minimal scaffold:",f instanceof Error?f.message:f)}if(x){let f=o.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let _ of x.files){if(_.path==="package.json"||_.path==="middleware.ts"||_.path==="components/sidebar.tsx"||_.path==="components/topnav.tsx"||_.path==="app/(dashboard)/layout.tsx"||_.path==="app/(dashboard)/page.tsx"||_.path==="app/(dashboard)/dashboard/page.tsx"||!m&&(_.path.includes("stripe")||_.path.includes("webhook/stripe"))||!u&&(_.path.includes("resend")||_.path.includes("emails/"))||!b&&(_.path.includes("(admin)")||_.path.includes("admin-sidebar"))||y&&(_.path==="lib/db.ts"||_.path==="lib/auth.ts"||_.path==="drizzle.config.ts"||_.path==="db/schema/auth.ts"))continue;let O=_.content.replace(/\{\{APP_NAME\}\}/g,o).replace(/\{\{WORKER_NAME\}\}/g,f);if(y&&_.path==="next.config.ts"&&(O=O.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),_.path==="next.config.ts"){let h=Fa(r);h&&(console.error(`[init] Project is inside monorepo at ${h} \u2014 adding outputFileTracingRoot`),O.includes("outputFileTracingRoot")||(O=O.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
2394
+ `}function sn(t,...e){let s=JSON.stringify(t).toLowerCase();return e.some(n=>s.includes(n.toLowerCase()))}var tl={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"};function gs(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[s,n]of Object.entries(tl))if(e.includes(s))return n;return"Circle"}function Ct(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function nl(t){if(t.authModel==="none")return null;let e=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed"];if(t.publicPages&&Array.isArray(t.publicPages))for(let i of t.publicPages){if(typeof i!="string"||i.length<1)continue;let r=i.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!r)continue;let a=r.startsWith("/")?r:"/"+r;e.includes(a)||e.push(a)}let s=e.filter(i=>i==="/"),n=e.filter(i=>i!=="/"),o=[];o.push('import { NextRequest, NextResponse } from "next/server";'),o.push(""),o.push("const PUBLIC_PREFIXES = [");for(let i of n)o.push(' "'+i+'",');return o.push("];"),o.push(""),s.length>0&&(o.push('const PUBLIC_EXACT = ["'+s.join('", "')+'"];'),o.push("")),o.push("export function middleware(req: NextRequest) {"),o.push(" const { pathname, search } = req.nextUrl;"),o.push(""),s.length>0&&o.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),o.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),o.push(""),o.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),o.push(" if (!token) {"),o.push(' const loginUrl = new URL("/login", req.url);'),o.push(" const params = new URLSearchParams(search);"),o.push(' for (const key of ["verified", "error"]) {'),o.push(" const v = params.get(key);"),o.push(" if (v) loginUrl.searchParams.set(key, v);"),o.push(" }"),o.push(" return NextResponse.redirect(loginUrl);"),o.push(" }"),o.push(""),o.push(" return NextResponse.next();"),o.push("}"),o.push(""),o.push("export const config = {"),o.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),o.push("};"),o.push(""),o.join(`
2395
+ `)}function sl(t){if(t.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],n=(t.pages??[]).filter(l=>{let d=l.path??l.route??"";return d==="/"||d===""||d.includes("[")||d.replace(/^\//,"").split("/").length>1?!1:!e.some(m=>d.startsWith(m))}).map(l=>{let d=l.path??l.route??"",h=d.startsWith("/")?d:"/"+d,m=l.name??Ct(d.replace(/^\//,"")),p=gs(m);return{label:m,href:h,icon:p}});n.some(l=>l.href==="/dashboard")||n.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let o=t.authModel==="none",i=[...new Set(n.map(l=>l.icon))];o||i.push("LogOut");let r=Ct(t.name);if(t.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),o||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+i.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let d of n)l.push(' { label: "'+d.label+'", href: "'+d.href+'", icon: '+d.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+r+"</span>"),l.push(' <div className="flex items-center gap-1">'),l.push(" {NAV_ITEMS.map((item) => ("),l.push(" <Link"),l.push(" key={item.href}"),l.push(" href={item.href}"),l.push(' aria-current={pathname === item.href ? "page" : undefined}'),l.push(" className={cn("),l.push(' "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",'),l.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground"'),l.push(" )}"),l.push(" >"),l.push(' <item.icon className="h-4 w-4" />'),l.push(" {item.label}"),l.push(" </Link>"),l.push(" ))}"),l.push(" </div>"),l.push(" </div>"),o?l.push(' <span className="text-sm text-muted-foreground">{user.name}</span>'):(l.push(' <div className="flex items-center gap-2">'),l.push(' <span className="text-sm text-muted-foreground">{user.email}</span>'),l.push(" <Button"),l.push(' variant="ghost"'),l.push(' size="sm"'),l.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),l.push(" >"),l.push(' <LogOut className="h-4 w-4" />'),l.push(" </Button>"),l.push(" </div>")),l.push(" </div>"),l.push(" </nav>"),l.push(" );"),l.push("}"),l.push(""),{path:"components/topnav.tsx",content:l.join(`
2396
+ `)}}let a=[];a.push('"use client";'),a.push(""),a.push('import { useState } from "react";'),a.push('import Link from "next/link";'),a.push('import { usePathname } from "next/navigation";'),o||a.push('import { authClient } from "@/lib/auth-client";'),a.push('import { Button } from "@/components/ui/button";'),a.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),a.push('import { cn } from "@/lib/utils";'),a.push("import { Menu, "+i.join(", ")+' } from "lucide-react";'),a.push(""),a.push("interface SidebarProps {"),a.push(" user: { name: string | null; email: string; role?: string | undefined };"),a.push("}"),a.push(""),a.push("const NAV_ITEMS = [");for(let l of n)a.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return a.push("];"),a.push(""),a.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),a.push(" return ("),a.push(" <>"),a.push(' <div className="flex h-14 items-center border-b px-4">'),a.push(' <span className="text-lg font-semibold">'+r+"</span>"),a.push(" </div>"),a.push(' <nav className="flex-1 space-y-1 p-2">'),a.push(" {NAV_ITEMS.map((item) => ("),a.push(" <Link"),a.push(" key={item.href}"),a.push(" href={item.href}"),a.push(" onClick={onNavigate}"),a.push(' aria-current={pathname === item.href ? "page" : undefined}'),a.push(" className={cn("),a.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),a.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),a.push(" )}"),a.push(" >"),a.push(' <item.icon className="h-4 w-4" />'),a.push(" {item.label}"),a.push(" </Link>"),a.push(" ))}"),a.push(" </nav>"),a.push(' <div className="border-t p-4">'),a.push(' <div className="flex items-center gap-3">'),a.push(' <div className="flex-1 truncate">'),a.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),a.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),a.push(" </div>"),o||(a.push(" <Button"),a.push(' variant="ghost"'),a.push(' size="icon"'),a.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),a.push(" >"),a.push(' <LogOut className="h-4 w-4" />'),a.push(" </Button>")),a.push(" </div>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),a.push("export default function Sidebar({ user }: SidebarProps) {"),a.push(" const pathname = usePathname();"),a.push(" const [open, setOpen] = useState(false);"),a.push(""),a.push(" return ("),a.push(" <>"),a.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),a.push(" <NavContent pathname={pathname} user={user} />"),a.push(" </aside>"),a.push(' <div className="sticky top-0 z-[var(--z-sticky)] flex h-14 items-center gap-3 border-b bg-card px-4 md:hidden">'),a.push(" <Sheet open={open} onOpenChange={setOpen}>"),a.push(" <SheetTrigger asChild>"),a.push(' <Button variant="ghost" size="icon" className="-ml-2">'),a.push(' <Menu className="h-5 w-5" />'),a.push(" </Button>"),a.push(" </SheetTrigger>"),a.push(' <SheetContent side="left" className="w-64 p-0">'),a.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),a.push(' <div className="flex h-full flex-col">'),a.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),a.push(" </div>"),a.push(" </SheetContent>"),a.push(" </Sheet>"),a.push(' <span className="text-lg font-semibold">'+r+"</span>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),{path:"components/sidebar.tsx",content:a.join(`
2397
+ `)}}function ol(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,s=t.defaultRole??e[0],n=[];n.push("export type Role = "+e.map(o=>'"'+o+'"').join(" | ")+";"),n.push(""),n.push("export const ROLES = ["+e.map(o=>'"'+o+'"').join(", ")+"] as const;"),n.push(""),n.push('export const DEFAULT_ROLE: Role = "'+s+'";'),n.push(""),n.push("export const ROLE_LABELS: Record<Role, string> = {");for(let o of e){let i=o.charAt(0).toUpperCase()+o.slice(1);n.push(' "'+o+'": "'+i+'",')}return n.push("};"),n.push(""),n.push("export function getUserRole(user: Record<string, unknown>): Role {"),n.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),n.push(" if (ROLES.includes(role as Role)) return role as Role;"),n.push(" return DEFAULT_ROLE;"),n.push("}"),n.push(""),n.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),n.push(" if (!userRole) return false;"),n.push(" const allowed = Array.isArray(required) ? required : [required];"),n.push(" return allowed.includes(userRole as Role);"),n.push("}"),n.push(""),n.join(`
2398
+ `)}function rl(t){let e=Ct(t.name);if(t.authModel==="none"){let i=[];return i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),i.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&i.push(' <p className="mt-4 text-lg text-muted-foreground">'+t.summary+"</p>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
2399
+ `)}let s=t.publicPages?.includes("/"),n=t.design?.landingTone;if(s&&n){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col">'),i.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),i.push(' <h1 className="text-5xl font-bold tracking-tight">'+e+"</h1>"),t.summary&&i.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+t.summary+"</p>"),i.push(' <div className="flex gap-4">'),i.push(' <Link href="/register" className="inline-flex h-11 items-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),i.push(" Get Started"),i.push(" </Link>"),i.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </div>"),i.push(" </section>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
2400
+ `)}if(s){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),i.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&i.push(' <p className="text-lg text-muted-foreground">'+t.summary+"</p>"),i.push(' <Link href="/login" className="inline-flex h-10 items-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
2401
+ `)}let o=[];return o.push('import { headers } from "next/headers";'),o.push('import { redirect } from "next/navigation";'),o.push('import { auth } from "@/lib/auth";'),o.push(""),o.push("export default async function HomePage() {"),o.push(" const session = await auth.api.getSession({ headers: await headers() });"),o.push(' if (session) redirect("/dashboard");'),o.push(' redirect("/login");'),o.push("}"),o.push(""),o.join(`
2402
+ `)}function il(t,e){let s=t.authModel==="none",n=[];s||(n.push('import { Suspense } from "react";'),n.push('import { headers } from "next/headers";'),n.push('import { redirect } from "next/navigation";'),n.push('import { auth } from "@/lib/auth";'),n.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?n.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&n.push('import Sidebar from "@/components/sidebar";'),!s&&t.roles&&t.roles.length>0&&n.push('import { getUserRole } from "@/lib/roles";'),n.push(""),n.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),s?n.push(' const user = { name: "Guest", email: "" };'):(n.push(" const session = await auth.api.getSession({ headers: await headers() });"),n.push(' if (!session) redirect("/login");'),n.push(""),t.roles&&t.roles.length>0?(n.push(" const role = getUserRole(session.user as Record<string, unknown>);"),n.push(" const user = { name: session.user.name, email: session.user.email, role };")):(n.push(" const user = {"),n.push(" name: session.user.name,"),n.push(" email: session.user.email,"),n.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),n.push(" };"))),n.push("");let o=s?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(" <TopNav user={user} />"),n.push(' <main className="mx-auto max-w-7xl p-6">'+o+"{children}</main>"),n.push(" </div>"),n.push(" );")):t.navStyle==="none"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(' <main className="mx-auto max-w-5xl p-6">'+o+"{children}</main>"),n.push(" </div>"),n.push(" );")):(n.push(" return ("),n.push(' <div className="flex flex-col md:flex-row min-h-screen">'),n.push(" <Sidebar user={user} />"),n.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+o+"{children}</main>"),n.push(" </div>"),n.push(" );")),n.push("}"),n.push(""),n.join(`
2403
+ `)}function al(t){let e=Ct(t.name),s=t.dataModel??[],n=[];if(s.length>0){let o=s.map(r=>gs(r.entity??r.name??"item")),i=[...new Set(o)];n.push('import { Card, CardContent } from "@/components/ui/card";'),n.push("import { "+i.join(", ")+' } from "lucide-react";'),n.push("")}if(n.push("export default function DashboardPage() {"),n.push(" return ("),n.push(' <div className="space-y-6">'),n.push(" <div>"),n.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),t.summary&&n.push(' <p className="mt-1 text-muted-foreground">'+t.summary+"</p>"),n.push(" </div>"),s.length>0){n.push(' <div className="rounded-lg border p-8 text-center">'),n.push(' <h2 className="text-lg font-semibold">Get started</h2>'),n.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),n.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let o of s){let i=o.entity??o.name??"Item",r=gs(i),a=Ct(i.replace(/_/g,"-"));n.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),n.push(" <"+r+' className="h-5 w-5 text-muted-foreground" />'),n.push(' <span className="text-sm font-medium">Add your first '+a+"</span>"),n.push(" </div>")}n.push(" </div>"),n.push(" </div>")}return n.push(" </div>"),n.push(" );"),n.push("}"),n.push(""),n.join(`
2404
+ `)}function ll(t,e=!1){if(!t.multiTenant)return null;let s=[];return e?(s.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),s.push('import { user } from "./auth";'),s.push(""),s.push('export const organization = pgTable("organization", {'),s.push(' id: text("id").primaryKey(),'),s.push(' name: text("name").notNull(),'),s.push(' slug: text("slug").unique().notNull(),'),s.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),s.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),s.push("});"),s.push(""),s.push("export const orgMember = pgTable(")):(s.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),s.push('import { sql } from "drizzle-orm";'),s.push('import { user } from "./auth";'),s.push(""),s.push('export const organization = sqliteTable("organization", {'),s.push(' id: text("id").primaryKey(),'),s.push(' name: text("name").notNull(),'),s.push(' slug: text("slug").unique().notNull(),'),s.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),s.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),s.push("});"),s.push(""),s.push("export const orgMember = sqliteTable(")),s.push(' "org_member",'),s.push(" {"),s.push(' id: text("id").primaryKey(),'),s.push(' orgId: text("org_id").notNull().references(() => organization.id),'),s.push(' userId: text("user_id").notNull().references(() => user.id),'),s.push(' role: text("role").notNull(),'),e?s.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):s.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),s.push(" },"),s.push(" (table) => ({"),s.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),s.push(' userIdx: index("org_member_user_idx").on(table.userId),'),s.push(" }),"),s.push(");"),s.push(""),s.join(`
2405
+ `)}function cl(t){if(!t.multiTenant)return null;let e=[];return e.push('import { db } from "./db";'),e.push('import { organization, orgMember } from "@/db/schema/organization";'),e.push('import { eq } from "drizzle-orm";'),e.push(""),e.push("export async function getCurrentOrg(userId: string) {"),e.push(" const membership = await db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.userId, userId))"),e.push(" .limit(1);"),e.push(" if (membership.length === 0) return null;"),e.push(" const org = await db"),e.push(" .select()"),e.push(" .from(organization)"),e.push(" .where(eq(organization.id, membership[0].orgId))"),e.push(" .limit(1);"),e.push(" return org[0] ?? null;"),e.push("}"),e.push(""),e.push("export async function getOrgMembers(orgId: string) {"),e.push(" return db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.orgId, orgId));"),e.push("}"),e.push(""),e.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),e.push(" const id = crypto.randomUUID();"),e.push(" await db.insert(orgMember).values({"),e.push(" id,"),e.push(" orgId,"),e.push(" userId: email,"),e.push(" role,"),e.push(" });"),e.push(" return { id, orgId, email, role };"),e.push("}"),e.push(""),e.join(`
2406
+ `)}function dl(t){if(!t.multiTenant)return null;let e=[];return e.push('"use client";'),e.push(""),e.push("import {"),e.push(" DropdownMenu,"),e.push(" DropdownMenuContent,"),e.push(" DropdownMenuItem,"),e.push(" DropdownMenuTrigger,"),e.push('} from "@/components/ui/dropdown-menu";'),e.push('import { Button } from "@/components/ui/button";'),e.push('import { ChevronsUpDown } from "lucide-react";'),e.push(""),e.push("interface OrgSwitcherProps {"),e.push(" orgs: Array<{ id: string; name: string }>;"),e.push(" currentOrgId: string;"),e.push("}"),e.push(""),e.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),e.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),e.push(""),e.push(" return ("),e.push(" <DropdownMenu>"),e.push(" <DropdownMenuTrigger asChild>"),e.push(' <Button variant="outline" className="w-full justify-between">'),e.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),e.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),e.push(" </Button>"),e.push(" </DropdownMenuTrigger>"),e.push(' <DropdownMenuContent className="w-56">'),e.push(" {orgs.map((org) => ("),e.push(" <DropdownMenuItem key={org.id}>"),e.push(" {org.name}"),e.push(" </DropdownMenuItem>"),e.push(" ))}"),e.push(" </DropdownMenuContent>"),e.push(" </DropdownMenu>"),e.push(" );"),e.push("}"),e.push(""),e.join(`
2407
+ `)}function pl(t,e,s){let n=[],o=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");n.push(`# ${o}`),n.push(""),e?.summary&&(n.push(e.summary),n.push(""));let i=e?.features??[];if(i.length>0){n.push("## Features"),n.push("");for(let l of i){let d=l.description?` \u2014 ${l.description}`:"";n.push(`- **${l.name}**${d}`)}n.push("")}n.push("## Tech Stack"),n.push(""),n.push("| Layer | Technology |"),n.push("|-------|------------|"),n.push("| Framework | Next.js 15 (App Router) |"),n.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),n.push("| Auth | Better Auth (email/password, social login) |"),n.push("| Styling | Tailwind CSS + shadcn/ui |"),n.push("| Deployment | Mistflow Cloud |"),s.hasStripe&&n.push("| Payments | Stripe |"),s.hasResend&&n.push("| Email | Resend + React Email |"),s.hasStorage&&n.push("| File Storage | Mistflow Cloud (managed blob storage) |"),s.hasAdmin&&n.push("| Admin | Better Auth admin plugin |"),s.hasAI&&n.push("| AI | Vercel AI SDK + OpenAI |"),n.push("");let r=e?.pages??[];if(r.length>0){n.push("## Pages"),n.push(""),n.push("| Route | Description |"),n.push("|-------|-------------|");for(let l of r){let d=l.path??l.route??l.name??"",h=l.description??"";n.push(`| \`${d.startsWith("/")?d:"/"+d}\` | ${h} |`)}n.push("")}let a=e?.dataModel??[];if(a.length>0){n.push("## Data Model"),n.push("");for(let l of a){let d=l.entity??l.name??"Unknown";if(n.push(`### ${d}`),n.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")n.push(`Fields: ${l.fields.join(", ")}`);else{n.push("| Field | Type |"),n.push("|-------|------|");for(let h of l.fields)n.push(`| ${h.name} | ${h.type} |`)}n.push("")}}}return n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),s.isNeon?n.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(n.push("| `TURSO_URL` | Database connection URL | Yes |"),n.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),n.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),s.hasStripe&&(n.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),n.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),n.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),s.hasResend&&(n.push("| `RESEND_API_KEY` | Resend API key | Yes |"),n.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),s.hasStorage&&(n.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),n.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),s.hasAI&&n.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),n.push(""),n.push("### Local database"),n.push(""),s.isNeon?(n.push("For local development, start a local Postgres server:"),n.push(""),n.push("```bash"),n.push("# Using Docker:"),n.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),n.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),n.push("```")):(n.push("For local development, start a local Turso server:"),n.push(""),n.push("```bash"),n.push("npx turso dev"),n.push("```")),n.push(""),n.push("Then set up the database:"),n.push(""),n.push("```bash"),n.push("npm run db:push"),n.push("```"),n.push(""),n.push("### Run"),n.push(""),n.push("```bash"),n.push("npm run dev"),n.push("```"),n.push(""),n.push("Open [http://localhost:3000](http://localhost:3000)."),n.push(""),n.push("## Project Structure"),n.push(""),n.push("```"),n.push("app/"),n.push(" (auth)/ Login and registration pages"),n.push(" (dashboard)/ Authenticated app pages"),s.hasAdmin&&n.push(" (admin)/ Admin panel pages"),n.push(" api/ API routes (auth, health, webhooks)"),n.push(" layout.tsx Root layout with fonts and providers"),n.push(" globals.css Design tokens and Tailwind config"),n.push("components/ Reusable UI components"),n.push("db/"),n.push(" schema/ Database table definitions"),n.push(" index.ts Schema exports"),n.push("lib/"),n.push(" auth.ts Better Auth server config"),n.push(" auth-client.ts Better Auth client config"),n.push(` db.ts ${s.isNeon?"Postgres":"SQLite"} database connection`),s.hasStripe&&n.push(" stripe.ts Stripe client"),s.hasResend&&(n.push(" resend.ts Resend client"),n.push(" email.ts Email send helpers")),s.hasStorage&&n.push(" storage.ts File upload/download helpers"),s.hasAI&&n.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),s.hasResend&&n.push("emails/ React Email templates"),n.push("```"),n.push(""),n.push("## Deploy"),n.push(""),n.push("Deploy to production with Mistflow:"),n.push(""),n.push("```"),n.push("# In your AI editor (Claude Code, Cursor, etc.):"),n.push("mist_deploy action='deploy'"),n.push("```"),n.push(""),n.push("Your app will be live at `https://<app-name>.mistflow.app`."),n.push(""),e?.design&&(n.push("## Design"),n.push(""),e.design.tone&&n.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(n.push(`- **Heading font**: ${e.design.fonts.heading}`),n.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&n.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&n.push(`- **Border radius**: ${e.design.borderRadius}`),n.push("")),n.push("---"),n.push(""),n.push("Built with [Mistflow](https://mistflow.ai)"),n.push(""),n.join(`
2408
+ `)}async function ul(t,e){let{name:s,plan:n,path:o,planId:i}=t;if(!o)return c("mist_init requires an explicit 'path' \u2014 the absolute directory where the project should be scaffolded. Pass the user's project directory (e.g. /Users/alice/projects/my-app). Do not rely on a default.",!0);if(!La(o))return c(`mist_init 'path' must be an absolute path \u2014 received '${o}'. Pass the full absolute path to the target directory.`,!0);let r=Wo(o),a=n;if(!a&&i){let w=Ba(i);if(!w)return c(`No plan found for planId '${i}'. Call mist_plan first, or pass the plan object inline.`,!0);a=w.plan}let l=a?.design,d=a?.appStyle,h=a?sn(a,"stripe","payment","billing","subscription","checkout","pricing"):!1,m=!0,p=a?sn(a,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,y=a?sn(a,"admin panel","admin dashboard","admin management"):!1,v=a?sn(a,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,b=a,f=!0;if(!Ga(r))return c(`A project already exists at this location (${r}). Choose a different name, or delete the existing folder first. (A .mistflow/ folder left over from planning is fine \u2014 init will preserve it.)`,!0);ms(r,{recursive:!0});try{let w=ve(Rt(r),".mistflow","mockups");if(Ye(w)){let I=Ho(w).filter(q=>q.endsWith(".html"));if(I.length>0){let q=ve(r,".mistflow","mockups");ms(q,{recursive:!0});for(let Y of I)Ua(ve(w,Y),ve(q,Y));console.error(`Copied ${I.length} mockup file(s) into project`)}}}catch(w){console.error("Could not copy mockup files:",w instanceof Error?w.message:w)}let k=null;try{k=await zn("nextjs")}catch(w){console.error("Could not fetch scaffold from API, using minimal scaffold:",w instanceof Error?w.message:w)}if(k){let w=s.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let u of k.files){if(u.path==="package.json"||u.path==="middleware.ts"||u.path==="components/sidebar.tsx"||u.path==="components/topnav.tsx"||u.path==="app/(dashboard)/layout.tsx"||u.path==="app/(dashboard)/page.tsx"||u.path==="app/(dashboard)/dashboard/page.tsx"||!h&&(u.path.includes("stripe")||u.path.includes("webhook/stripe"))||!m&&(u.path.includes("resend")||u.path.includes("emails/"))||!y&&(u.path.includes("(admin)")||u.path.includes("admin-sidebar"))||f&&(u.path==="lib/db.ts"||u.path==="lib/auth.ts"||u.path==="drizzle.config.ts"||u.path==="db/schema/auth.ts"))continue;let g=u.content.replace(/\{\{APP_NAME\}\}/g,s).replace(/\{\{WORKER_NAME\}\}/g,w);if(f&&u.path==="next.config.ts"&&(g=g.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),u.path==="next.config.ts"){let P=Ha(r);P&&(console.error(`[init] Project is inside monorepo at ${P} \u2014 adding outputFileTracingRoot`),g.includes("outputFileTracingRoot")||(g=g.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
2406
2409
  import { dirname } from "path";
2407
2410
  import { fileURLToPath } from "url";
2408
2411
 
2409
- const __dirname = dirname(fileURLToPath(import.meta.url));`),O=O.replace("images: {",`outputFileTracingRoot: __dirname,
2410
- images: {`)))}!b&&_.path.includes("sidebar")&&(O=O.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),O=O.replace(/, Shield/g,"")),R(r,_.path,O)}let k={...x.dependencies},D={...x.devDependencies};if(k["drizzle-zod"]||(k["drizzle-zod"]="^0.5.1"),y&&(delete k["@libsql/client"],k["@neondatabase/serverless"]="^0.10.0",D["@electric-sql/pglite"]="^0.2.0"),m&&(k.stripe="^17.0.0"),u&&(k.resend="^4.0.0",k["@react-email/components"]="^0.0.31"),T&&(k.ai="^4.0.0",k["@ai-sdk/openai"]="^1.0.0",k.openai="^4.0.0"),R(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:k,devDependencies:D,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1"}},null,2)),x.methodology){let _=x.methodology;y&&(_=_.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")),_=so(_),R(r,"AGENTS.md",_),R(r,"CLAUDE.md",_)}let be=i?.designMd;be&&R(r,"DESIGN.md",be),y&&(R(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(`
2411
- `)),R(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(`
2412
- `)),R(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(`
2413
- `)),R(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(`
2414
- `)),R(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(`
2415
- `)))}else R(r,"package.json",JSON.stringify({name:o,version:"0.1.0",private:!0},null,2));let M=i?.designMd;R(r,"app/globals.css",Va(l,p,M)),R(r,"app/layout.tsx",Ya(o,l,w?.language)),R(r,"README.md",al(o,i,{hasStripe:m,hasResend:u,hasStorage:d,hasAdmin:b,hasAI:T,isNeon:y})),R(r,"contracts/README.md",oo());let J=i?.dataModel??[],H=new Set,se=0;for(let f of J){let k=f.entity??f.name;if(!k||typeof k!="string")continue;let D=io(k);H.has(D)||(H.add(D),R(r,D,ro(k)),se++)}se===0&&R(r,"contracts/.gitkeep","");let q=[],v=i?.publicPages;if(Array.isArray(v))q=v;else if(typeof v=="string"){try{q=JSON.parse(v)}catch{q=[]}Array.isArray(q)||(q=[])}if(!q.includes("/")){let f=i?.steps?.some(D=>{let z=((D.name??"")+" "+(D.description??"")).toLowerCase();return z.includes("landing")||z.includes("marketing")||z.includes("homepage")}),k=i?.pages?.some(D=>D.path==="/");(f||k)&&(q=["/",...q])}let $={name:o,summary:i?.summary,authModel:i?.authModel,roles:i?.roles,defaultRole:i?.defaultRole,publicPages:q,navStyle:i?.navStyle,multiTenant:i?.multiTenant,pages:i?.pages,dataModel:i?.dataModel,design:i?.design},K=Xa($);K&&R(r,"middleware.ts",K);let ne=Za($);ne&&R(r,ne.path,ne.content);let he=el($);if(he&&R(r,"lib/roles.ts",he),R(r,"app/page.tsx",tl($)),R(r,"app/(dashboard)/layout.tsx",nl($,b)),R(r,"app/(dashboard)/dashboard/page.tsx",ol($)),$.multiTenant){let f=sl($,y);f&&R(r,"db/schema/organization.ts",f);let k=rl($);k&&R(r,"lib/org.ts",k);let D=il($);D&&R(r,"components/org-switcher.tsx",D)}R(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&&R(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(`
2416
- `)),u&&(R(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(`
2417
- `)),R(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(`
2418
- `))),d&&(R(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(`
2419
- `)),R(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(`
2420
- `))),T&&(R(r,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
2421
- `)),R(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(`
2422
- `)));let C={name:o,methodologyVersion:x?.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"}}:{}},...T?{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:T,deploy:null};R(r,"mistflow.json",JSON.stringify(C,null,2));let E=Ua(32).toString("hex"),ge=m?`
2412
+ const __dirname = dirname(fileURLToPath(import.meta.url));`),g=g.replace("images: {",`outputFileTracingRoot: __dirname,
2413
+ images: {`)))}!y&&u.path.includes("sidebar")&&(g=g.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),g=g.replace(/, Shield/g,"")),O(r,u.path,g)}let I={...k.dependencies},q={...k.devDependencies};if(I["drizzle-zod"]||(I["drizzle-zod"]="^0.5.1"),f&&(delete I["@libsql/client"],I["@neondatabase/serverless"]="^0.10.0",q["@electric-sql/pglite"]="^0.2.0"),h&&(I.stripe="^17.0.0"),m&&(I.resend="^4.0.0",I["@react-email/components"]="^0.0.31"),v&&(I.ai="^4.0.0",I["@ai-sdk/openai"]="^1.0.0",I.openai="^4.0.0"),O(r,"package.json",JSON.stringify({name:s,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:I,devDependencies:q,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"}},null,2)),k.methodology){let u=k.methodology;f&&(u=u.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres")),u=ds(u),O(r,"AGENTS.md",u),O(r,"CLAUDE.md",u)}let ee=a?.designMd;ee&&O(r,"DESIGN.md",ee),f&&(O(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(`
2414
+ `)),O(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(`
2415
+ `)),O(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(`
2416
+ `)),O(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(`
2417
+ `)),O(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(`
2418
+ `)))}else O(r,"package.json",JSON.stringify({name:s,version:"0.1.0",private:!0},null,2));let _=a?.designMd;O(r,"app/globals.css",Qa(l,d,_)),O(r,"app/layout.tsx",el(s,l,b?.language)),O(r,"README.md",pl(s,a,{hasStripe:h,hasResend:m,hasStorage:p,hasAdmin:y,hasAI:v,isNeon:f})),O(r,"contracts/README.md",cs());let N=a?.dataModel??[],S=new Set,D=0;for(let w of N){let I=w.entity??w.name;if(!I||typeof I!="string")continue;let q=us(I);S.has(q)||(S.add(q),O(r,q,ps(I)),D++)}D===0&&O(r,"contracts/.gitkeep","");let $=[],x=a?.publicPages;if(Array.isArray(x))$=x;else if(typeof x=="string"){try{$=JSON.parse(x)}catch{$=[]}Array.isArray($)||($=[])}if(!$.includes("/")){let w=a?.steps?.some(q=>{let Y=((q.name??"")+" "+(q.description??"")).toLowerCase();return Y.includes("landing")||Y.includes("marketing")||Y.includes("homepage")}),I=a?.pages?.some(q=>q.path==="/");(w||I)&&($=["/",...$])}let M={name:s,summary:a?.summary,authModel:a?.authModel,roles:a?.roles,defaultRole:a?.defaultRole,publicPages:$,navStyle:a?.navStyle,multiTenant:a?.multiTenant,pages:a?.pages,dataModel:a?.dataModel,design:a?.design},z=nl(M);z&&O(r,"middleware.ts",z);let W=sl(M);W&&O(r,W.path,W.content);let ne=ol(M);if(ne&&O(r,"lib/roles.ts",ne),O(r,"app/page.tsx",rl(M)),O(r,"app/(dashboard)/layout.tsx",il(M,y)),O(r,"app/(dashboard)/dashboard/page.tsx",al(M)),M.multiTenant){let w=ll(M,f);w&&O(r,"db/schema/organization.ts",w);let I=cl(M);I&&O(r,"lib/org.ts",I);let q=dl(M);q&&O(r,"components/org-switcher.tsx",q)}O(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)),h&&O(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(`
2419
+ `)),m&&(O(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(`
2420
+ `)),O(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(`
2421
+ `))),p&&(O(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(`
2422
+ `)),O(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(`
2423
+ `))),v&&(O(r,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
2424
+ `)),O(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(`
2425
+ `)));let A=Array.isArray(a?.integrations)?a.integrations.map(w=>({name:w.name,preset:w.preset,envVars:w.envVars??[]})):[],R={};v&&!A.some(w=>w.envVars?.some(I=>I.key==="OPENAI_API_KEY"))&&(R.OPENAI_API_KEY={description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"});for(let w of A)for(let I of w.envVars??[])R[I.key]||(R[I.key]={description:I.description,setupUrl:I.setupUrl,...w.name?{integration:w.name}:{}});let se={name:s,methodologyVersion:k?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},plan:Array.isArray(a?.steps)?{...a,steps:a.steps.map(w=>({number:w.number,name:w.name??w.title,description:w.description,entities:w.entities,pages:w.pages,features:w.features,status:"pending"}))}:a,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...h?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...m?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{},...p?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...Object.keys(R).length>0?{required:R}:{}},authModel:a?.authModel??"email",roles:a?.roles??null,navStyle:a?.navStyle??"sidebar",multiTenant:a?.multiTenant??!1,hasAdmin:y,hasResend:m,hasStorage:p,hasAI:v,deploy:null};O(r,"mistflow.json",JSON.stringify(se,null,2));let ce=qa(32).toString("hex"),j=h?`
2423
2426
  # Stripe
2424
2427
  STRIPE_SECRET_KEY=
2425
2428
  STRIPE_WEBHOOK_SECRET=
2426
2429
  NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
2427
- `:"",Se=u?`
2430
+ `:"",Q=m?`
2428
2431
  # Email (Resend)
2429
2432
  RESEND_API_KEY=
2430
2433
  EMAIL_FROM=onboarding@resend.dev
2431
- `:"",j=d?`
2434
+ `:"",Se=p?`
2432
2435
  # File Storage (Mistflow managed)
2433
2436
  MISTFLOW_API_KEY=
2434
2437
  MISTFLOW_PROJECT_ID=
2435
- `:"",oe=T?`
2438
+ `:"",pe=v?`
2436
2439
  # AI (get your key at https://platform.openai.com/api-keys)
2437
2440
  OPENAI_API_KEY=
2438
- `:"",lt=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2441
+ `:"",Pe=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2439
2442
  # Set DATABASE_URL only for production or to use a remote Postgres
2440
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Ne=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2443
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Fe=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2441
2444
  # Set DATABASE_URL only for production or to use a remote Postgres
2442
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;R(r,".env.local",`${lt}
2443
- AUTH_SECRET=${E}
2444
- ${ge}${Se}${j}${oe}`),R(r,".env.example",`${Ne}
2445
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;O(r,".env.local",`${Pe}
2446
+ AUTH_SECRET=${ce}
2447
+ ${j}${Q}${Se}${pe}`),O(r,".env.example",`${Fe}
2445
2448
  AUTH_SECRET=your-secret-here
2446
- ${ge}${Se}${j}${oe}`);let B=[],Be=(f,k)=>{B.push({phase:f,message:k})},re=(f,k)=>{let D=B.find(z=>z.phase===f&&!z.durationMs);D&&(D.durationMs=k)};if(e){let f=Yt(e.server,e.progressToken,()=>B[B.length-1]?.message??"Setting up project...");e.cleanup=()=>f.stop()}let je=w?.requestedSubdomain||void 0,ae,ct;Be("register","Registering project on Mistflow...");let fe=Date.now();try{let f=await yt(o,void 0,"neon",je);ae=f.id;let k=ue(r,"mistflow.json"),D=JSON.parse(tn(k,"utf-8"));if(D.projectId=ae,lo(k,JSON.stringify(D,null,2)),wt(r,vt(ae,o)),f.managed_env&&Object.keys(f.managed_env).length>0){let z=ue(r,".env.local"),ye=Fe(z)?tn(z,"utf-8"):"";for(let[be,_]of Object.entries(f.managed_env)){let O=new RegExp(`^${be}=.*$`,"m");O.test(ye)?ye=ye.replace(O,`${be}=${_}`):ye+=`
2447
- ${be}=${_}`}lo(z,ye)}try{let{getBaseUrl:z,getAuthHeaders:ye}=await Promise.resolve().then(()=>(ie(),Vo)),be=ye(),_=i?.features,O=i?.steps,h={};Array.isArray(_)&&_.length>0&&(h.features=_.map(g=>g.name)),i&&(h.plan=i),Array.isArray(O)&&O.length>0&&(h.provenance=O.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(`${z()}/api/projects/${encodeURIComponent(ae)}/state`,{method:"PUT",headers:{...be,"Content-Type":"application/json"},body:JSON.stringify(h)})}catch{}B[B.length-1].message=`Registered as ${ae.slice(0,8)}`}catch(f){let k=f instanceof Error?f.message:String(f);console.error("Could not register project on backend:",k),ct=`Project created locally but NOT registered on Mistflow servers (${k}). Deploy will auto-register it.`,B[B.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}re("register",Date.now()-fe),Be("git","Initializing git repository...");let pn=Date.now();try{let f=La(r);await f.init(),await f.add("."),await f.commit("Initial Mistflow project setup"),B[B.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),B[B.length-1].message="Git init skipped"}re("git",Date.now()-pn);let dn=B.reduce((f,k)=>f+(k.durationMs??0),0),ve={projectPath:r,projectId:ae,status:"awaiting_install"},pt=B.map(f=>{let k=f.durationMs?` (${(f.durationMs/1e3).toFixed(1)}s)`:"";return`${f.message}${k}`});ve.progress=pt,ve.totalSetupTime=`${(dn/1e3).toFixed(1)}s`;let De=[];ae||De.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),ct&&(ve.registrationWarning=ct),De.length>0&&(ve.warnings=De);let Ct=`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 ve.nextAction=ae?Ct:`${Ct} 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(ve))}var zs={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:qa,handler:ll};import{z as po}from"zod";import{existsSync as Tt,readFileSync as mo,writeFileSync as uo,mkdirSync as bl}from"fs";import{join as nt,resolve as wl,dirname as vl}from"path";ie();import{createConnection as xl}from"net";var Hs="\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 Ws=`# Landing Page Rules
2449
+ ${j}${Q}${Se}${pe}`);let F=[],C=(w,I)=>{F.push({phase:w,message:I})},B=(w,I)=>{let q=F.find(Y=>Y.phase===w&&!Y.durationMs);q&&(q.durationMs=I)};if(e){let w=Zt(e.server,e.progressToken,()=>F[F.length-1]?.message??"Setting up project...");e.cleanup=()=>w.stop()}let he=b?.requestedSubdomain||void 0,G,ke;C("register","Registering project on Mistflow...");let qe=Date.now();try{let w=await vt(s,void 0,"neon",he);G=w.id;let I=ve(r,"mistflow.json"),q=JSON.parse(on(I,"utf-8"));if(q.projectId=G,hs(I,JSON.stringify(q,null,2)),kt(r,St(G,s)),w.managed_env&&Object.keys(w.managed_env).length>0){let Y=ve(r,".env.local"),ge=Ye(Y)?on(Y,"utf-8"):"";for(let[ee,u]of Object.entries(w.managed_env)){let g=new RegExp(`^${ee}=.*$`,"m");g.test(ge)?ge=ge.replace(g,`${ee}=${u}`):ge+=`
2450
+ ${ee}=${u}`}hs(Y,ge)}try{let{getBaseUrl:Y,getAuthHeaders:ge}=await Promise.resolve().then(()=>(de(),Ys)),ee=ge(),u=a?.features,g=a?.steps,P={};Array.isArray(u)&&u.length>0&&(P.features=u.map(T=>T.name)),a&&(P.plan=a),Array.isArray(g)&&g.length>0&&(P.provenance=g.map(T=>({feature:T.name??T.title??`Step ${T.number??"?"}`,user_intent:(T.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(P).length>0&&await fetch(`${Y()}/api/projects/${encodeURIComponent(G)}/state`,{method:"PUT",headers:{...ee,"Content-Type":"application/json"},body:JSON.stringify(P)})}catch{}F[F.length-1].message=`Registered as ${G.slice(0,8)}`}catch(w){let I=w instanceof Error?w.message:String(w);console.error("Could not register project on backend:",I),ke=`Project created locally but NOT registered on Mistflow servers (${I}). Deploy will auto-register it.`,F[F.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}B("register",Date.now()-qe),C("git","Initializing git repository...");let Be=Date.now();try{let w=za(r);await w.init(),await w.add("."),await w.commit("Initial Mistflow project setup"),F[F.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),F[F.length-1].message="Git init skipped"}B("git",Date.now()-Be);let ze=F.reduce((w,I)=>w+(I.durationMs??0),0),ue={projectPath:r,projectId:G,status:"awaiting_install"},Ce=F.map(w=>{let I=w.durationMs?` (${(w.durationMs/1e3).toFixed(1)}s)`:"";return`${w.message}${I}`});ue.progress=Ce,ue.totalSetupTime=`${(ze/1e3).toFixed(1)}s`;let Ae=[];G||Ae.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),ke&&(ue.registrationWarning=ke),Ae.length>0&&(ue.warnings=Ae);let Ee=`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 ue.nextAction=G?Ee:`${Ee} 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(ue))}var Go={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:Wa,handler:ul};import{z as fs}from"zod";import{existsSync as At,readFileSync as bs,writeFileSync as ys,mkdirSync as kl}from"fs";import{join as dt,resolve as Sl,dirname as Pl}from"path";de();import{createConnection as Il}from"net";var Vo="\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 Jo=`# Landing Page Rules
2448
2451
 
2449
2452
  These rules apply to every landing page. They are non-negotiable.
2450
2453
 
@@ -2841,7 +2844,7 @@ app/
2841
2844
  \`\`\`
2842
2845
 
2843
2846
  Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
2844
- `;var Gs=`# Design Doctrine
2847
+ `;var Yo=`# Design Doctrine
2845
2848
 
2846
2849
  This is the standard for every UI you generate. It is not aspirational. It is the floor.
2847
2850
 
@@ -2907,7 +2910,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
2907
2910
  8. Is there ONE memorable moment on the page (signature typography / orchestrated motion / unexpected layout)? **If zero, add one. If three, keep the strongest one.**
2908
2911
 
2909
2912
  If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
2910
- `;var Vs=`# Typography
2913
+ `;var Ko=`# Typography
2911
2914
 
2912
2915
  Typography is the cheapest way to escape AI slop and the most visible place it shows up. Every generic landing uses Inter. Every remarkable landing picks something you'd notice.
2913
2916
 
@@ -2995,7 +2998,7 @@ Pick exactly one:
2995
2998
  - **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
2996
2999
 
2997
3000
  Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
2998
- `;var Js="# Color\n\nColor is a commitment, not a palette swatch. The #1 failure mode in AI-generated landings is an evenly-distributed palette: a little emerald here, a little amber there, a gradient, a badge. That's visual hedging \u2014 it signals \"I couldn't pick a point of view.\"\n\nPick one color. Use it with intent.\n\n## The Token System\n\nEvery color on every screen goes through a CSS variable defined in `globals.css`. You do not hand-pick hex values in JSX. You do not use Tailwind palette utilities (`bg-emerald-500`, `text-blue-600`, `border-slate-200`). If a color isn't in the token scheme, it doesn't exist for this app.\n\n### Core tokens\n\n- `--color-background` \u2014 page background\n- `--color-foreground` \u2014 default body text\n- `--color-card` \u2014 elevated surface (cards, panels)\n- `--color-card-foreground` \u2014 text on cards\n- `--color-muted` \u2014 low-emphasis surface fill\n- `--color-muted-foreground` \u2014 secondary text (\u2265 WCAG AA contrast vs background)\n- `--color-border` \u2014 subtle dividers\n- `--color-input` \u2014 form input borders\n- `--color-popover` / `--color-popover-foreground` \u2014 dropdowns, tooltips, menus\n\n### Interactive tokens\n\n- `--color-primary` \u2014 primary CTAs, links, active tab, focus ring\n- `--color-primary-foreground` \u2014 text on primary (derived for WCAG AA contrast)\n- `--color-ring` \u2014 focus outline (same hue as primary)\n- `--color-secondary` / `--color-secondary-foreground` \u2014 quieter than primary, more than muted\n- `--color-accent` / `--color-accent-foreground` \u2014 hover states on neutrals\n\n### Semantic tokens\n\n- `--color-success` \u2014 confirmation, \"verified\" banners, positive states\n- `--color-warning` \u2014 pending states, attention, non-destructive caution\n- `--color-destructive` / `--color-destructive-foreground` \u2014 errors, irreversible actions\n- `--color-info` \u2014 neutral system messages, tips\n\n**You use these semantic tokens for all status UI.** When you need a \"green checkmark\" you reach for `text-success`, not `text-emerald-500`. When you need an amber alert you reach for `bg-warning/10 text-warning`, not `bg-amber-50 text-amber-700`.\n\n## Usage Rules\n\n**Primary color:**\n- Primary CTAs, links, the active navigation tab, focus rings.\n- NOT for headings. Black or foreground-colored headings are stronger.\n- NOT for large surface fills (it's a splash of color, not a wash).\n- NOT for borders except focus rings.\n- One bold use of primary beats twenty sprinkled uses.\n\n**Neutrals do the structural work:**\n- Background, cards, borders \u2014 all come from the neutral scale.\n- Text hierarchy via opacity on foreground (`text-foreground`, `text-foreground/80`, `text-muted-foreground`) \u2014 not different colors.\n\n**Semantic colors:**\n- Use `bg-success/10 text-success border border-success/30` for success banners (reproducibility: a light-tinted version of the success color for surface, the solid version for text and border).\n- Same shape for warning, info, destructive.\n\n## Dark Mode\n\nCommit to one theme. If DESIGN.md says the app is dark-themed, make it unambiguously dark \u2014 `#0c0c0c` / near-black base, not neutral-900. If light-themed, commit to light.\n\nDo NOT auto-swap based on `prefers-color-scheme` when the design system declared a theme direction. The appStyle chose a theme for a reason; respect it.\n\n## Forbidden\n\n- Palette utilities: `bg-emerald-500`, `text-blue-600`, `border-slate-200`, `from-purple-500`, `via-pink-300`, `to-amber-400`. Every one of these in your output is a slop indicator.\n- Hex literals inside `className` or inline `style` props.\n- Named colors from CSS (`red`, `lightgrey`, `rebeccapurple`) \u2014 never used in production UI; always a sign of rushed work.\n- Purple gradients on white. The single most overused AI-design pattern.\n- Three-color gradient pills. Rainbow badges. \"Vibrant\" anything.\n\n## Contrast\n\nEvery text/surface pair in DESIGN.md is already WCAG AA-verified by Mistflow's contrast test. You do not need to re-check \u2014 the tokens are safe by construction. You DO need to:\n\n- Not override token combinations with hardcoded classes that might fail contrast.\n- Maintain contrast for overlays (text on images, modals on scrims). When stacking text over a gradient or image, include a scrim (`bg-background/80 backdrop-blur-sm`) so body text stays \u2265 4.5:1.\n\n## Getting Color Wrong\n\nThe specific failure mode to avoid: a page where primary is used in five places, all small and incidental \u2014 a checkmark, a hover state, a tiny badge. That's AI hedging. Either use primary confidently on a hero CTA and mean it, OR don't use primary on the page at all and let neutrals carry the identity.\n";var Ks=`# Motion
3001
+ `;var Qo="# Color\n\nColor is a commitment, not a palette swatch. The #1 failure mode in AI-generated landings is an evenly-distributed palette: a little emerald here, a little amber there, a gradient, a badge. That's visual hedging \u2014 it signals \"I couldn't pick a point of view.\"\n\nPick one color. Use it with intent.\n\n## The Token System\n\nEvery color on every screen goes through a CSS variable defined in `globals.css`. You do not hand-pick hex values in JSX. You do not use Tailwind palette utilities (`bg-emerald-500`, `text-blue-600`, `border-slate-200`). If a color isn't in the token scheme, it doesn't exist for this app.\n\n### Core tokens\n\n- `--color-background` \u2014 page background\n- `--color-foreground` \u2014 default body text\n- `--color-card` \u2014 elevated surface (cards, panels)\n- `--color-card-foreground` \u2014 text on cards\n- `--color-muted` \u2014 low-emphasis surface fill\n- `--color-muted-foreground` \u2014 secondary text (\u2265 WCAG AA contrast vs background)\n- `--color-border` \u2014 subtle dividers\n- `--color-input` \u2014 form input borders\n- `--color-popover` / `--color-popover-foreground` \u2014 dropdowns, tooltips, menus\n\n### Interactive tokens\n\n- `--color-primary` \u2014 primary CTAs, links, active tab, focus ring\n- `--color-primary-foreground` \u2014 text on primary (derived for WCAG AA contrast)\n- `--color-ring` \u2014 focus outline (same hue as primary)\n- `--color-secondary` / `--color-secondary-foreground` \u2014 quieter than primary, more than muted\n- `--color-accent` / `--color-accent-foreground` \u2014 hover states on neutrals\n\n### Semantic tokens\n\n- `--color-success` \u2014 confirmation, \"verified\" banners, positive states\n- `--color-warning` \u2014 pending states, attention, non-destructive caution\n- `--color-destructive` / `--color-destructive-foreground` \u2014 errors, irreversible actions\n- `--color-info` \u2014 neutral system messages, tips\n\n**You use these semantic tokens for all status UI.** When you need a \"green checkmark\" you reach for `text-success`, not `text-emerald-500`. When you need an amber alert you reach for `bg-warning/10 text-warning`, not `bg-amber-50 text-amber-700`.\n\n## Usage Rules\n\n**Primary color:**\n- Primary CTAs, links, the active navigation tab, focus rings.\n- NOT for headings. Black or foreground-colored headings are stronger.\n- NOT for large surface fills (it's a splash of color, not a wash).\n- NOT for borders except focus rings.\n- One bold use of primary beats twenty sprinkled uses.\n\n**Neutrals do the structural work:**\n- Background, cards, borders \u2014 all come from the neutral scale.\n- Text hierarchy via opacity on foreground (`text-foreground`, `text-foreground/80`, `text-muted-foreground`) \u2014 not different colors.\n\n**Semantic colors:**\n- Use `bg-success/10 text-success border border-success/30` for success banners (reproducibility: a light-tinted version of the success color for surface, the solid version for text and border).\n- Same shape for warning, info, destructive.\n\n## Dark Mode\n\nCommit to one theme. If DESIGN.md says the app is dark-themed, make it unambiguously dark \u2014 `#0c0c0c` / near-black base, not neutral-900. If light-themed, commit to light.\n\nDo NOT auto-swap based on `prefers-color-scheme` when the design system declared a theme direction. The appStyle chose a theme for a reason; respect it.\n\n## Forbidden\n\n- Palette utilities: `bg-emerald-500`, `text-blue-600`, `border-slate-200`, `from-purple-500`, `via-pink-300`, `to-amber-400`. Every one of these in your output is a slop indicator.\n- Hex literals inside `className` or inline `style` props.\n- Named colors from CSS (`red`, `lightgrey`, `rebeccapurple`) \u2014 never used in production UI; always a sign of rushed work.\n- Purple gradients on white. The single most overused AI-design pattern.\n- Three-color gradient pills. Rainbow badges. \"Vibrant\" anything.\n\n## Contrast\n\nEvery text/surface pair in DESIGN.md is already WCAG AA-verified by Mistflow's contrast test. You do not need to re-check \u2014 the tokens are safe by construction. You DO need to:\n\n- Not override token combinations with hardcoded classes that might fail contrast.\n- Maintain contrast for overlays (text on images, modals on scrims). When stacking text over a gradient or image, include a scrim (`bg-background/80 backdrop-blur-sm`) so body text stays \u2265 4.5:1.\n\n## Getting Color Wrong\n\nThe specific failure mode to avoid: a page where primary is used in five places, all small and incidental \u2014 a checkmark, a hover state, a tiny badge. That's AI hedging. Either use primary confidently on a hero CTA and mean it, OR don't use primary on the page at all and let neutrals carry the identity.\n";var Xo=`# Motion
2999
3002
 
3000
3003
  Motion is the most-ignored dimension of AI-generated UI. Generic landings either have no motion or sprinkle tiny fades on everything. Remarkable landings pick ONE orchestrated moment and execute it precisely.
3001
3004
 
@@ -3073,7 +3076,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
3073
3076
  ## One-Line Motion Rule
3074
3077
 
3075
3078
  If the motion you're about to add could be described as "subtle animation on scroll", delete it. Design motion is specific, named, and described in one sentence: "the headline lines drop in from above with a 50ms stagger at page load." If you can't describe it that specifically, you don't have a motion design \u2014 you have motion noise.
3076
- `;var Ys=`# Spatial Composition
3079
+ `;var Zo=`# Spatial Composition
3077
3080
 
3078
3081
  Layout is where AI-slop is most visible. A centered single-column hero with a pill, headline, subhead, and two CTAs is the most-recognizable generic-SaaS pattern on the internet. It is the layout you must not use.
3079
3082
 
@@ -3143,7 +3146,7 @@ To signal "designed, not templated":
3143
3146
  Negative space is a design element. A hero with \`py-32\` and a tight \`max-w-2xl\` text block in a wide viewport reads as confident. A hero that fills every pixel with checkmarks, logos, and counters reads as scared.
3144
3147
 
3145
3148
  Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
3146
- `;var Qs=`# Interaction
3149
+ `;var er=`# Interaction
3147
3150
 
3148
3151
  Every interactive element has a designed state for every phase: rest, hover, focus, active, disabled. The difference between remarkable and adequate lives in these states.
3149
3152
 
@@ -3228,7 +3231,7 @@ Small moments that add up to "designed":
3228
3231
  - **Empty states** offer a specific next action, not "No data yet".
3229
3232
 
3230
3233
  These micro-interactions are the texture of a designed product. Ship them.
3231
- `;var Xs=`# UX Writing
3234
+ `;var tr=`# UX Writing
3232
3235
 
3233
3236
  Copy is design. A remarkable page has copy that could only be about this specific product. A generic page has copy that could describe a hundred.
3234
3237
 
@@ -3304,14 +3307,14 @@ If there's a pricing page:
3304
3307
  ## The Footer
3305
3308
 
3306
3309
  A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is fine, but the company name / tagline should be specific. "StandupSync \u2014 async updates, human-sized" is better than "\xA9 2026 StandupSync Inc."
3307
- `;function kl(t){return new Promise(e=>{let o=xl({port:t,host:"127.0.0.1"});o.on("connect",()=>{o.destroy(),e(!0)}),o.on("error",()=>{e(!1)})})}var Sl=po.object({projectPath:po.string().optional().describe("Path to the project directory (default: cwd)"),step:po.number().optional().describe("Specific step number to implement (default: next incomplete step)")});function Pl(t){let e=nt(t,"mistflow.json");if(!Tt(e))return null;try{return JSON.parse(mo(e,"utf-8"))}catch{return null}}function Zs(t,e){let o=nt(t,"mistflow.json");uo(o,JSON.stringify(e,null,2)+`
3308
- `)}function nn(t){return t.entity??t.name??"Unknown"}function Il(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function er(t){return t.path??t.route??t.name??""}function _l(t){let e=(t||"text").toLowerCase();return e==="string"||e==="varchar"||e==="char"?"text":e==="integer"||e==="int"||e==="number"||e==="float"||e==="decimal"||e==="double"?"number":e==="boolean"||e==="bool"?"boolean":e==="date"||e==="datetime"||e==="timestamp"?"date":e==="email"?"email":e==="url"||e==="uri"?"url":e==="enum"||e==="select"?"select":e==="text"||e==="longtext"||e==="textarea"?"textarea":"text"}function tr(t,e){if(!t.entities||t.entities.length===0)return e;let o=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let s=nn(n).toLowerCase();return o.some(a=>s.includes(a)||a.includes(s))})}function Tl(t,e){if(!t.pages||t.pages.length===0)return[];let o=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let s=(n.name??"").toLowerCase(),a=er(n).toLowerCase();return o.some(r=>s.includes(r)||r.includes(s)||a.includes(r))})}var Rl=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function Al(t){let e=t.stepType;if(e&&Rl.has(e))return e;if(t.integrationId)return"integration";let o=`${t.name} ${t.description}`.toLowerCase();return o.includes("crud")||o.includes("list")&&o.includes("create")?"crud":o.includes("auth")||o.includes("login")||o.includes("register")?"auth":o.includes("admin")&&(o.includes("panel")||o.includes("dashboard")||o.includes("manage")||o.includes("users"))?"admin":o.includes("dashboard")||o.includes("overview")||o.includes("analytics")?"dashboard":o.includes("schema")||o.includes("database")||o.includes("model")?"schema":o.includes("layout")||o.includes("sidebar")||o.includes("navigation")?"layout":o.includes("deploy")||o.includes("cloudflare")?"deploy":o.includes("organization")||o.includes("team")||o.includes("workspace")||o.includes("multi-tenant")||o.includes("invite member")?"multi-tenant":o.includes("landing")||o.includes("hero")||o.includes("marketing")||o.includes("homepage")?"landing":o.includes("design")||o.includes("theme")||o.includes("styling")||o.includes("ui polish")||o.includes("visual")?"design":"general"}function Cl(t){switch(t){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function El(t,e){let o=[];if(o.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&o.push(`- **App tone**: ${t.tone}`),t.fonts&&(o.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),o.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),o.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),o.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let n={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};o.push(`- **Border radius**: ${t.borderRadius} (${n[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let n={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};o.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${n[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let n={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};o.push(`- **Card style**: ${t.cardStyle} \u2014 ${n[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&o.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let n=t.visualStrategy,s=t.heroPhoto!==!1,a=s&&!!n.heroImages?.length;if(o.push(""),o.push("### Visual strategy:"),a&&n.heroImages&&n.heroImages.length>0){o.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let r=n.heroImages[0];o.push(`- URL: ${r.url}`),o.push(`- Alt text for img tag: "${r.alt||"Hero image"} \u2014 Photo by ${r.photographer} on Unsplash"`),o.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else s&&!n.heroImages?.length?o.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/page.tsx.'"):s||o.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(n.sectionImages?.length){o.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let r of n.sectionImages)o.push(`- ${r.url} \u2014 alt: "${r.alt||"section image"} \u2014 Photo by ${r.photographer} on Unsplash"`)}(a||n.sectionImages?.length)&&o.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page."),o.push(""),o.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),o.push("The hero uses a split layout with text on the left and a product preview on the right. This is non-negotiable for consumer apps and SaaS/tool apps alike."),o.push(""),o.push("```"),o.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),o.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),o.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),o.push("\u2502 \u2502"),o.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),o.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),o.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),o.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),o.push("\u2502 \u2502 real app data \u2502 \u2502"),o.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),o.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),o.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),o.push("\u2502 \u2502"),o.push("\u2502 500+ 25K+ 99% \u2502"),o.push("\u2502 Label Label Label \u2502"),o.push("\u2502 \u2502"),a?o.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):o.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),o.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),o.push("```"),o.push(""),o.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),o.push("**Right side (~45%)**: A glassmorphic floating card that previews what the app looks like inside:"),o.push("- Style: `bg-white/10 backdrop-blur-lg border border-white/20 rounded-2xl shadow-2xl p-6` (over dark/photo bg) OR `bg-white/60 backdrop-blur-lg border border-black/5 rounded-2xl shadow-2xl p-6` (over light bg)"),o.push("- Content: Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows"),o.push("- Must be DOMAIN-SPECIFIC: a library app shows book catalog rows, a gym app shows check-in stats, a CRM shows pipeline cards"),o.push("- Add subtle inner elements with `bg-white/5` or `bg-white/10` for depth"),o.push("**Stats row**: 3 proof-point numbers at the bottom of the left side (e.g., '500+ Gyms', '25K+ Members', '99% Uptime'). Match text color to the background contrast.")}return o.push(""),o.push(Hs),o.join(`
3309
- `)}async function Nl(t){try{let e=await $n("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
3310
+ `;function Tl(t){return new Promise(e=>{let s=Il({port:t,host:"127.0.0.1"});s.on("connect",()=>{s.destroy(),e(!0)}),s.on("error",()=>{e(!1)})})}var _l=fs.object({projectPath:fs.string().optional().describe("Path to the project directory (default: cwd)"),step:fs.number().optional().describe("Specific step number to implement (default: next incomplete step)")});function Rl(t){let e=dt(t,"mistflow.json");if(!At(e))return null;try{return JSON.parse(bs(e,"utf-8"))}catch{return null}}function nr(t,e){let s=dt(t,"mistflow.json");ys(s,JSON.stringify(e,null,2)+`
3311
+ `)}function rn(t){return t.entity??t.name??"Unknown"}function Cl(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function sr(t){return t.path??t.route??t.name??""}function Al(t){let e=(t||"text").toLowerCase();return e==="string"||e==="varchar"||e==="char"?"text":e==="integer"||e==="int"||e==="number"||e==="float"||e==="decimal"||e==="double"?"number":e==="boolean"||e==="bool"?"boolean":e==="date"||e==="datetime"||e==="timestamp"?"date":e==="email"?"email":e==="url"||e==="uri"?"url":e==="enum"||e==="select"?"select":e==="text"||e==="longtext"||e==="textarea"?"textarea":"text"}function or(t,e){if(!t.entities||t.entities.length===0)return e;let s=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let o=rn(n).toLowerCase();return s.some(i=>o.includes(i)||i.includes(o))})}function El(t,e){if(!t.pages||t.pages.length===0)return[];let s=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let o=(n.name??"").toLowerCase(),i=sr(n).toLowerCase();return s.some(r=>o.includes(r)||r.includes(o)||i.includes(r))})}var Nl=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function jl(t){let e=t.stepType;if(e&&Nl.has(e))return e;if(t.integrationId)return"integration";let s=`${t.name} ${t.description}`.toLowerCase();return s.includes("crud")||s.includes("list")&&s.includes("create")?"crud":s.includes("auth")||s.includes("login")||s.includes("register")?"auth":s.includes("admin")&&(s.includes("panel")||s.includes("dashboard")||s.includes("manage")||s.includes("users"))?"admin":s.includes("dashboard")||s.includes("overview")||s.includes("analytics")?"dashboard":s.includes("schema")||s.includes("database")||s.includes("model")?"schema":s.includes("layout")||s.includes("sidebar")||s.includes("navigation")?"layout":s.includes("deploy")||s.includes("cloudflare")?"deploy":s.includes("organization")||s.includes("team")||s.includes("workspace")||s.includes("multi-tenant")||s.includes("invite member")?"multi-tenant":s.includes("landing")||s.includes("hero")||s.includes("marketing")||s.includes("homepage")?"landing":s.includes("design")||s.includes("theme")||s.includes("styling")||s.includes("ui polish")||s.includes("visual")?"design":"general"}function Dl(t){switch(t){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function Ol(t,e){let s=[];if(s.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&s.push(`- **App tone**: ${t.tone}`),t.fonts&&(s.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),s.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),s.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),s.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let n={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};s.push(`- **Border radius**: ${t.borderRadius} (${n[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let n={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};s.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${n[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let n={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};s.push(`- **Card style**: ${t.cardStyle} \u2014 ${n[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&s.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let n=t.visualStrategy,o=t.heroPhoto!==!1,i=o&&!!n.heroImages?.length;if(s.push(""),s.push("### Visual strategy:"),i&&n.heroImages&&n.heroImages.length>0){s.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let r=n.heroImages[0];s.push(`- URL: ${r.url}`),s.push(`- Alt text for img tag: "${r.alt||"Hero image"} \u2014 Photo by ${r.photographer} on Unsplash"`),s.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else o&&!n.heroImages?.length?s.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/page.tsx.'"):o||s.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(n.sectionImages?.length){s.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let r of n.sectionImages)s.push(`- ${r.url} \u2014 alt: "${r.alt||"section image"} \u2014 Photo by ${r.photographer} on Unsplash"`)}(i||n.sectionImages?.length)&&s.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page."),s.push(""),s.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),s.push("The hero uses a split layout with text on the left and a product preview on the right. This is non-negotiable for consumer apps and SaaS/tool apps alike."),s.push(""),s.push("```"),s.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),s.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),s.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),s.push("\u2502 \u2502"),s.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),s.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),s.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),s.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),s.push("\u2502 \u2502 real app data \u2502 \u2502"),s.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),s.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),s.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),s.push("\u2502 \u2502"),s.push("\u2502 500+ 25K+ 99% \u2502"),s.push("\u2502 Label Label Label \u2502"),s.push("\u2502 \u2502"),i?s.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):s.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),s.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),s.push("```"),s.push(""),s.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),s.push("**Right side (~45%)**: A glassmorphic floating card that previews what the app looks like inside:"),s.push("- Style: `bg-white/10 backdrop-blur-lg border border-white/20 rounded-2xl shadow-2xl p-6` (over dark/photo bg) OR `bg-white/60 backdrop-blur-lg border border-black/5 rounded-2xl shadow-2xl p-6` (over light bg)"),s.push("- Content: Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows"),s.push("- Must be DOMAIN-SPECIFIC: a library app shows book catalog rows, a gym app shows check-in stats, a CRM shows pipeline cards"),s.push("- Add subtle inner elements with `bg-white/5` or `bg-white/10` for depth"),s.push("**Stats row**: 3 proof-point numbers at the bottom of the left side (e.g., '500+ Gyms', '25K+ Members', '99% Uptime'). Match text color to the background contrast.")}return s.push(""),s.push(Vo),s.join(`
3312
+ `)}async function Ml(t){try{let e=await Hn("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
3310
3313
  - Follow existing patterns in the codebase
3311
- - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function jl(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(El(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=Ps(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 x=y.replace(a,"").replace(/^\//,"");r.push(`- \`${x}\``)}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?tr(t,e.dataModel):[];m.length>0&&(r.push("### Data model (from plan):"),m.forEach(w=>{let y=nn(w),x=Il(w.fields);r.push(`- **${y}**: ${x}`),r.push(` Schema file: \`db/schema/${y.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),r.push(""));let u=e.pages?Tl(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(`- \`${er(w)}\`${y}`)}),r.push("")),s==="crud"&&m.length>0&&m.forEach(w=>{let y=nn(w),x=y.toLowerCase().replace(/\s+/g,"-"),M=x.endsWith("s")?x:`${x}s`;r.push(`### Files for ${y} CRUD:`),r.push(`- List page: \`app/(dashboard)/${M}/page.tsx\` (Server Component)`),r.push(`- Detail page: \`app/(dashboard)/${M}/[id]/page.tsx\``),r.push(`- Create page: \`app/(dashboard)/${M}/new/page.tsx\``),r.push(`- Server Actions: \`app/(dashboard)/${M}/actions.ts\``),r.push(`- DataTable columns: \`components/${x}-table-columns.tsx\``),r.push(`- Form: \`components/${x}-form.tsx\``),r.push("")}),l){r.push("## Design Doctrine (the standard for every UI step)"),r.push(""),r.push(Gs),r.push(""),r.push("## Design Reference Library"),r.push(""),r.push("### Typography"),r.push(Vs),r.push(""),r.push("### Color"),r.push(Js),r.push(""),r.push("### Motion"),r.push(Ks),r.push(""),r.push("### Spatial Composition"),r.push(Ys),r.push(""),r.push("### Interaction"),r.push(Qs),r.push(""),r.push("### UX Writing"),r.push(Xs),r.push("");let w=a?nt(a,"DESIGN.md"):void 0,y=w&&Tt(w)?(()=>{try{return mo(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(Ws),r.push(""));let d=t.integrationId?Qe(t.integrationId):void 0;if(d){let w=Xe(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:T}=await Nl(s);return r.push(b),r.push(""),T&&!(s==="landing"&&e.landingDesign==="freeform")&&(r.push(`### ${s} reference:`),r.push(T),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(`
3312
- `)}async function Dl(t){let{projectPath:e,step:o}=t,n=wl(e??process.cwd()),s=Pl(n);if(!s)return ke(n);if(!Tt(nt(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:$}=await Promise.resolve().then(()=>(Gn(),Wn));await v(n);let K=await $(n);K.failed?console.error(`[implement] ${K.failed}`):K.installed.length>0&&console.error(`[implement] installed ${K.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($=>$.number===i.number);v!==-1&&(a.steps[v].status="completed",r=`Auto-completed step ${i.number} (${i.name})`,Zs(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(()=>($e(),xt)),u=m(n),d=Al(l),b=[];if((d==="crud"||d==="schema")&&a.dataModel&&l.entities&&l.entities.length>0){let v=tr(l,a.dataModel);for(let $ of v){let K=nn($);try{let ne=($.fields||[]).map(j=>typeof j=="string"?{name:j,type:"text"}:{name:j.name,type:_l(j.type),required:j.required!==!1});if(ne.length===0)continue;let he=s.dbProvider==="neon"?"nextjs-neon":"nextjs",C=await Ln(he,K,ne),E=0,ge=0;for(let j of C.files){let oe=nt(n,j.path);if(Tt(oe)){ge++;continue}bl(vl(oe),{recursive:!0}),uo(oe,j.content),E++}let Se=nt(n,"db","index.ts");if(Tt(Se)){let j=mo(Se,"utf-8");j.includes(C.dbExport)||uo(Se,j.trimEnd()+`
3313
- `+C.dbExport+`
3314
- `)}E>0?b.push(`${C.entityPascal} CRUD (${E} new files${ge>0?`, ${ge} existing skipped`:""})`):ge>0&&b.push(`${C.entityPascal} CRUD (all ${ge} files already exist \u2014 skipped)`)}catch(ne){console.error(`Module generation failed for ${K} (non-fatal):`,ne instanceof Error?ne.message:ne)}}}let T=await jl(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",Zs(n,s)),u&&s.projectId){let{syncRemoteState:v}=await Promise.resolve().then(()=>($e(),xt));v(s.projectId,u).catch(()=>{})}let y=a.steps.every(v=>v.status==="completed"||v.number===l.number),x;y?x=`THIS IS THE LAST STEP. Rules for speed:
3314
+ - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function $l(t,e,s,n,o,i){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(o);if(e.design&&l?(r.push(Ol(e.design,{hasDesignPreset:!!e.landingDesign&&(o==="landing"||o==="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("")),i){let b=_o(i);if(b.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 f of b){let k=f.replace(i,"").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 d=["landing","design","auth","general","crud","dashboard"];e.audienceType&&d.includes(o)&&(e.audienceType==="b2c"?(r.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),r.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),r.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),r.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),r.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),r.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),r.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),r.push("")):e.audienceType==="b2b"?(r.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),r.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),r.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),r.push("- Testimonials: from business owners who use the platform"),r.push("- Features: business benefits ('Track dietary preferences across all orders')"),r.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),r.push("")):e.audienceType==="internal"&&(r.push("### Audience: internal staff tool. No marketing copy needed."),r.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),r.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),r.push(""))),s.length>0&&(r.push("### Already completed:"),s.forEach(b=>r.push(`- ${b}`)),r.push(""));let h=e.dataModel?or(t,e.dataModel):[];h.length>0&&(r.push("### Data model (from plan):"),h.forEach(b=>{let f=rn(b),k=Cl(b.fields);r.push(`- **${f}**: ${k}`),r.push(` Schema file: \`db/schema/${f.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),r.push(""));let m=e.pages?El(t,e.pages):[];if(m.length>0&&(r.push("### Pages to create/update:"),m.forEach(b=>{let f=b.description?` \u2014 ${b.description}`:"";r.push(`- \`${sr(b)}\`${f}`)}),r.push("")),o==="crud"&&h.length>0&&h.forEach(b=>{let f=rn(b),k=f.toLowerCase().replace(/\s+/g,"-"),_=k.endsWith("s")?k:`${k}s`;r.push(`### Files for ${f} CRUD:`),r.push(`- List page: \`app/(dashboard)/${_}/page.tsx\` (Server Component)`),r.push(`- Detail page: \`app/(dashboard)/${_}/[id]/page.tsx\``),r.push(`- Create page: \`app/(dashboard)/${_}/new/page.tsx\``),r.push(`- Server Actions: \`app/(dashboard)/${_}/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(Yo),r.push(""),r.push("## Design Reference Library"),r.push(""),r.push("### Typography"),r.push(Ko),r.push(""),r.push("### Color"),r.push(Qo),r.push(""),r.push("### Motion"),r.push(Xo),r.push(""),r.push("### Spatial Composition"),r.push(Zo),r.push(""),r.push("### Interaction"),r.push(er),r.push(""),r.push("### UX Writing"),r.push(tr),r.push("");let b=i?dt(i,"DESIGN.md"):void 0,f=b&&At(b)?(()=>{try{return bs(b,"utf-8")}catch{return null}})():null;f&&(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(f),r.push(""))}(o==="landing"||o==="design")&&(r.push(Jo),r.push(""));let p=t.integrationId?rt(t.integrationId):void 0;if(p){let b=it(p.id);if(r.push("### Integration blueprint (follow this closely):"),r.push(""),r.push(`Using integration: **${p.name}** (${p.category})`),b?.docsUrl&&r.push(`Official docs: ${b.docsUrl}`),b?.envVars?.length){r.push(""),r.push("**Required environment variables:**");for(let f of b.envVars)r.push(`- \`${f.key}\`: ${f.description} \u2014 Get it at ${f.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.")}b?.packages?.length&&(r.push(""),r.push(`**Packages to install:** \`npm install ${b.packages.join(" ")}\``)),r.push(""),r.push("---"),r.push(p.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:y,skill:v}=await Ml(o);return r.push(y),r.push(""),v&&!(o==="landing"&&e.landingDesign==="freeform")&&(r.push(`### ${o} reference:`),r.push(v),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(`
3315
+ `)}async function Ul(t){let{projectPath:e,step:s}=t,n=Sl(e??process.cwd()),o=Rl(n);if(!o)return Te(n);if(!At(dt(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:x,ensureShadcnComponents:M}=await Promise.resolve().then(()=>(Xn(),Qn));await x(n);let z=await M(n);z.failed?console.error(`[implement] ${z.failed}`):z.installed.length>0&&console.error(`[implement] installed ${z.installed.length} shadcn components`)}catch(x){console.error("[implement] self-heal skipped:",x instanceof Error?x.message:String(x))}let i=o.plan;if(!i||!i.steps||i.steps.length===0)return c("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let r,a=i.steps.find(x=>x.status==="in_progress");if(a){let x=i.steps.findIndex(M=>M.number===a.number);x!==-1&&(i.steps[x].status="completed",r=`Auto-completed step ${a.number} (${a.name})`,nr(n,o))}let l;if(s!==void 0){if(l=i.steps.find(x=>x.number===s),!l)return c(`Step ${s} not found. The plan has ${i.steps.length} steps (numbered ${i.steps[0].number} to ${i.steps[i.steps.length-1].number}).`,!0)}else if(l=i.steps.find(x=>x.status!=="completed"),!l)return c(JSON.stringify({message:"All plan steps are completed!",completedSteps:i.steps.map(x=>x.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let d=i.steps.filter(x=>x.status==="completed").map(x=>`Step ${x.number}: ${x.name}`),{readLocalState:h}=await Promise.resolve().then(()=>(Ve(),Pt)),m=h(n),p=jl(l),y=[];if((p==="crud"||p==="schema")&&i.dataModel&&l.entities&&l.entities.length>0){let x=or(l,i.dataModel);for(let M of x){let z=rn(M);try{let W=(M.fields||[]).map(j=>typeof j=="string"?{name:j,type:"text"}:{name:j.name,type:Al(j.type),required:j.required!==!1});if(W.length===0)continue;let ne=o.dbProvider==="neon"?"nextjs-neon":"nextjs",A=await Wn(ne,z,W),R=0,se=0;for(let j of A.files){let Q=dt(n,j.path);if(At(Q)){se++;continue}kl(Pl(Q),{recursive:!0}),ys(Q,j.content),R++}let ce=dt(n,"db","index.ts");if(At(ce)){let j=bs(ce,"utf-8");j.includes(A.dbExport)||ys(ce,j.trimEnd()+`
3316
+ `+A.dbExport+`
3317
+ `)}R>0?y.push(`${A.entityPascal} CRUD (${R} new files${se>0?`, ${se} existing skipped`:""})`):se>0&&y.push(`${A.entityPascal} CRUD (all ${se} files already exist \u2014 skipped)`)}catch(W){console.error(`Module generation failed for ${z} (non-fatal):`,W instanceof Error?W.message:W)}}}let v=await $l(l,i,d,null,p,n),b=i.steps.findIndex(x=>x.number===l.number);if(b!==-1&&(o.plan.steps[b].status="in_progress",nr(n,o)),m&&o.projectId){let{syncRemoteState:x}=await Promise.resolve().then(()=>(Ve(),Pt));x(o.projectId,m).catch(()=>{})}let f=i.steps.every(x=>x.status==="completed"||x.number===l.number),k;f?k=`THIS IS THE LAST STEP. Rules for speed:
3315
3318
 
3316
3319
  1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
3317
3320
  2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
@@ -3320,14 +3323,14 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
3320
3323
  - app/page.tsx must be a real landing page, NOT a redirect to /login
3321
3324
  - middleware.ts must have "/" in PUBLIC_EXACT or PUBLIC_PREFIXES
3322
3325
  - Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
3323
- 5. Call mist_build({ projectPath }) (fire-and-poll \u2014 re-call with the returned jobId until status 'complete'), then mist_deploy({ action: 'deploy', projectPath }). Do NOT pause between these two calls to ask the user \u2014 the build is expected, the deploy is expected, just chain them.`:x=`IMPLEMENT THIS STEP NOW. Rules for speed:
3326
+ 5. Call mist_build({ projectPath }) (fire-and-poll \u2014 re-call with the returned jobId until status 'complete'), then mist_deploy({ action: 'deploy', projectPath }). Do NOT pause between these two calls to ask the user \u2014 the build is expected, the deploy is expected, just chain them.`:k=`IMPLEMENT THIS STEP NOW. Rules for speed:
3324
3327
 
3325
3328
  1. BEFORE writing any files, tell the user: "[stepTiming.announcement]" \u2014 use the exact announcement string from the stepTiming field so they know what's happening and how long it'll take. This is a one-line status update, NOT a request for permission.
3326
3329
  2. Write ALL files for this step using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message. Do NOT write one file at a time.
3327
3330
  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.
3328
3331
  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).
3329
- 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 M=Cl(d),J={stepNumber:l.number,totalSteps:a.steps.length,estimatedMinutes:M,announcement:`Starting step ${l.number} of ${a.steps.length}: ${l.name}. This step usually takes ${M.min}\u2013${M.max} minutes.`},se=JSON.stringify({instruction:T,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:J,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:x});return await kl(3e3)?$o("http://localhost:3000",se):c(se)}var 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:Sl,handler:Dl};import{z as me}from"zod";import{z as Ee}from"zod";import{resolve as Ol}from"path";ie();We();var uu=Ee.object({projectPath:Ee.string().optional().describe("Path to the project directory (default: cwd)"),action:Ee.enum(["set","list","delete"]).describe("Action to perform"),key:Ee.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:Ee.string().optional().describe("Environment variable value (required for 'set')"),category:Ee.string().optional().describe("Category for the env var (default: 'custom')"),description:Ee.string().optional().describe("Description of what this env var is for"),setupUrl:Ee.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function or(t){let{projectPath:e,action:o,key:n,value:s,category:a,description:r,setupUrl:i}=t,l=Ol(e??process.cwd());if(!G())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let m=_e(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 En(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 Cn(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 Nn(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 A)return c(u.message,!0);let d=u instanceof Error?u.message:"An unexpected error occurred";return c(d,!0)}}import{z as Rt}from"zod";import{resolve as Ml,join as Ul}from"path";import{existsSync as $l,readFileSync as Ll,writeFileSync as Fl}from"fs";ie();We();var vu=Rt.object({projectPath:Rt.string().optional().describe("Path to the project directory (default: cwd)"),action:Rt.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:Rt.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:Rt.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function ho(t,e){let o=Ul(t,"mistflow.json");if(!$l(o))return;let n;try{n=JSON.parse(Ll(o,"utf-8"))}catch{return}n.domains=e,Fl(o,JSON.stringify(n,null,2)+`
3330
- `)}async function sr(t){let{projectPath:e,action:o,domain:n,domainId:s}=t,a=Ml(e??process.cwd());if(!G())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let i=_e(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 Rn(i,n),p=await Te(i);return ho(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 Te(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 Te(i)).find(d=>d.domain===n);if(u){let d=await Ft(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 Ft(i,s),p=await Te(i);return ho(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 Te(i)).find(d=>d.domain===n);if(!u)return c(`Domain '${n}' not found.`,!0);l=u.id}await An(i,l);let p=await Te(i);return ho(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 A)return c(l.message,!0);let p=l instanceof Error?l.message:"An unexpected error occurred";return c(p,!0)}}var ql=me.object({resource:me.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:me.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:me.string().optional().describe("Path to the project directory (default: cwd)"),key:me.string().optional().describe("(env) Variable name"),value:me.string().optional().describe("(env set) Variable value"),category:me.string().optional().describe("(env set) Category"),description:me.string().optional().describe("(env set) Description"),setupUrl:me.string().optional().describe("(env set) URL to obtain the value"),domain:me.string().optional().describe("(domain) Domain name"),domainId:me.string().optional().describe("(domain) Domain ID")}),rr={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:ql,handler:async t=>{let e=t;switch(e.resource){case"env":return or({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return sr({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{z as yo}from"zod";import{resolve as nc}from"path";import{existsSync as oc}from"fs";import{join as sc}from"path";import{spawn as Bl,execFileSync as zl}from"child_process";import{existsSync as on,mkdirSync as lr,openSync as go,closeSync as fo,readSync as Hl,readFileSync as cr,writeFileSync as pr,renameSync as dr,unlinkSync as Wl,readdirSync as Au,statSync as Gl}from"fs";import{homedir as ur}from"os";import{join as we,dirname as mr}from"path";import{randomBytes as hr,randomUUID as Vl}from"crypto";var gr=1,Jl=`// Generated by @mistflow-ai/mcp local-jobs (v${gr}). Do not edit.
3332
+ 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 _=Dl(p),N={stepNumber:l.number,totalSteps:i.steps.length,estimatedMinutes:_,announcement:`Starting step ${l.number} of ${i.steps.length}: ${l.name}. This step usually takes ${_.min}\u2013${_.max} minutes.`},D=JSON.stringify({instruction:v,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:N,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}:{},...y.length>0?{generatedModules:y,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${d.length}/${i.steps.length} steps done`,nextAction:k});return await Tl(3e3)?Fs("http://localhost:3000",D):c(D)}var rr={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:_l,handler:Ul};import{z as xe}from"zod";import{z as Le}from"zod";import{resolve as Ll}from"path";de();Ze();var Su=Le.object({projectPath:Le.string().optional().describe("Path to the project directory (default: cwd)"),action:Le.enum(["set","list","delete"]).describe("Action to perform"),key:Le.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:Le.string().optional().describe("Environment variable value (required for 'set')"),category:Le.string().optional().describe("Category for the env var (default: 'custom')"),description:Le.string().optional().describe("Description of what this env var is for"),setupUrl:Le.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function ir(t){let{projectPath:e,action:s,key:n,value:o,category:i,description:r,setupUrl:a}=t,l=Ll(e??process.cwd());if(!X())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let h=De(l)?.projectId;if(!h)return c("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(s){case"set":return n?o?(await $n(h,n,o,{category:i,description:r,setupUrl:a}),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 m=await Mn(h);return m.length===0?c(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):c(JSON.stringify({envVars:m.map(p=>({key:p.key,category:p.category,description:p.description,hasValue:p.has_value})),message:`${m.length} environment variable(s) configured.`}))}case"delete":return n?(await Un(h,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: ${s}. Use set, list, or delete.`,!0)}}catch(m){if(m instanceof U)return c(m.message,!0);let p=m instanceof Error?m.message:"An unexpected error occurred";return c(p,!0)}}import{z as Et}from"zod";import{resolve as Fl,join as ql}from"path";import{existsSync as Bl,readFileSync as zl,writeFileSync as Hl}from"fs";de();Ze();var Eu=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')")});function ws(t,e){let s=ql(t,"mistflow.json");if(!Bl(s))return;let n;try{n=JSON.parse(zl(s,"utf-8"))}catch{return}n.domains=e,Hl(s,JSON.stringify(n,null,2)+`
3333
+ `)}async function ar(t){let{projectPath:e,action:s,domain:n,domainId:o}=t,i=Fl(e??process.cwd());if(!X())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=De(i)?.projectId;if(!a)return c("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(s){case"add":{if(!n)return c("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Nn(a,n),d=await Oe(a);return ws(i,d.map(h=>({domain:h.domain,status:h.status}))),c(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await Oe(a);return l.length===0?c(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):c(JSON.stringify({domains:l.map(d=>({id:d.id,domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message}))}))}case"verify":{if(!o){if(n){let m=(await Oe(a)).find(p=>p.domain===n);if(m){let p=await zt(a,m.id);return c(JSON.stringify({domain:p.domain,status:p.status,ssl:p.ssl_status,error:p.error_message,message:p.status==="active"?`Domain '${p.domain}' is active and serving traffic.`:`Domain '${p.domain}' is ${p.status}. Make sure DNS records are configured correctly.`}))}return c(`Domain '${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(a,o),d=await Oe(a);return ws(i,d.map(h=>({domain:h.domain,status:h.status}))),c(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!o&&!n)return c("Provide either domainId or domain name to remove.",!0);let l=o;if(!l&&n){let m=(await Oe(a)).find(p=>p.domain===n);if(!m)return c(`Domain '${n}' not found.`,!0);l=m.id}await jn(a,l);let d=await Oe(a);return ws(i,d.map(h=>({domain:h.domain,status:h.status}))),c(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return c(`Unknown action: ${s}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof U)return c(l.message,!0);let d=l instanceof Error?l.message:"An unexpected error occurred";return c(d,!0)}}var Wl=xe.object({resource:xe.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:xe.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:xe.string().optional().describe("Path to the project directory (default: cwd)"),key:xe.string().optional().describe("(env) Variable name"),value:xe.string().optional().describe("(env set) Variable value"),category:xe.string().optional().describe("(env set) Category"),description:xe.string().optional().describe("(env set) Description"),setupUrl:xe.string().optional().describe("(env set) URL to obtain the value"),domain:xe.string().optional().describe("(domain) Domain name"),domainId:xe.string().optional().describe("(domain) Domain ID")}),lr={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:Wl,handler:async t=>{let e=t;switch(e.resource){case"env":return ir({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return ar({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{z as ks}from"zod";import{resolve as ic}from"path";import{existsSync as ac}from"fs";import{join as lc}from"path";import{spawn as Gl,execFileSync as Vl}from"child_process";import{existsSync as an,mkdirSync as pr,openSync as vs,closeSync as xs,readSync as Jl,readFileSync as ur,writeFileSync as mr,renameSync as hr,unlinkSync as Yl,readdirSync as Fu,statSync as Kl}from"fs";import{homedir as gr}from"os";import{join as me,dirname as fr}from"path";import{randomBytes as yr,randomUUID as Ql}from"crypto";var br=1,Xl=`// Generated by @mistflow-ai/mcp local-jobs (v${br}). Do not edit.
3331
3334
  const { spawn } = require('node:child_process');
3332
3335
  const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
3333
3336
  const { join, dirname } = require('node:path');
@@ -3391,10 +3394,22 @@ child.on('error', (err) => {
3391
3394
  });
3392
3395
  process.exit(1);
3393
3396
  });
3394
- `;function rn(){return we(ur(),".mistflow","jobs")}function Kl(){return we(ur(),".mistflow","job-wrapper.cjs")}function Yl(){let t=Kl(),e=mr(t);on(e)||lr(e,{recursive:!0});let o=`v${gr}`;if(on(t))try{if(cr(t,"utf-8").includes(o))return t}catch{}let n=we(e,`.job-wrapper.tmp.${hr(6).toString("hex")}`);return pr(n,Jl),dr(n,t),t}function sn(t){return we(rn(),t)}function fr(t){return we(sn(t),"status.json")}function ir(t,e){let o=fr(t),n=we(mr(o),`.status.tmp.${hr(6).toString("hex")}`);try{pr(n,JSON.stringify(e,null,2)+`
3395
- `),dr(n,o)}catch(s){try{Wl(n)}catch{}throw s}}function Ql(t){let e=fr(t);if(!on(e))return null;try{return JSON.parse(cr(e,"utf-8"))}catch{return null}}async function ot(t){let e=`job_${Vl().replace(/-/g,"").slice(0,12)}`,o=sn(e);lr(o,{recursive:!0}),fo(go(we(o,"stdout.log"),"a")),fo(go(we(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};ir(e,s);let a=Yl(),r={...process.env,...t.env??{}},i=Bl("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 ir(e,l),l}function Xl(t){let e=t.trim();if(!e)return NaN;let o=Date.parse(e);return Number.isFinite(o)?o:NaN}function Zl(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let o=zl("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=Xl(o),s=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(s)&&Math.abs(n-s)>2e3)return!1}catch{}return!0}function ec(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 ar(t,e){if(!on(t))return"";let o=Gl(t);if(o.size===0)return"";let n=o.size>e?o.size-e:0,s=o.size-n,a=go(t,"r");try{let r=Buffer.alloc(s);return Hl(a,r,0,s,n),r.toString("utf-8")}finally{fo(a)}}function tc(t,e=20){let o=ar(we(sn(t),"stdout.log"),16384),n=ar(we(sn(t),"stderr.log"),16*1024),s=[];return o.trim()&&s.push(...o.split(`
3396
- `).slice(-e).map(a=>`[out] ${a}`)),n.trim()&&s.push(...n.split(`
3397
- `).slice(-e).map(a=>`[err] ${a}`)),s.filter(a=>a.trim().length>0).join(`
3398
- `)}async function st(t){let e=Ql(t);if(!e)return null;let o=e;return(e.status==="running"||e.status==="starting")&&!Zl(e)&&(o={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...o,elapsed:ec(o.startedAt,o.endedAt),logTail:tc(t)}}var rc=yo.object({projectPath:yo.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:yo.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."}),yr={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:rc,handler:async t=>{let e=t;if(e.jobId){let i=await st(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=nc(e.projectPath);if(!oc(sc(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 ot({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 an}from"zod";import{resolve as ic,join as rt}from"path";import{existsSync as it,readFileSync as br}from"fs";var ac=an.object({projectPath:an.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:an.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:an.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."});function lc(t){let e=rt(rn(),t,"stdout.log"),o=rt(rn(),t,"stderr.log"),n="";try{it(e)&&(n+=br(e,"utf-8"))}catch{}try{it(o)&&(n+=`
3399
- `+br(o,"utf-8"))}catch{}return n}function cc(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 wr={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:ac,handler:async t=>{let e=t;if(e.jobId){let l=await st(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=lc(l.id),m=Kt(p),u=cc(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=ic(e.projectPath);if(!it(rt(o,"package.json")))return c(`No package.json at ${o}. Run mist_init first.`,!0);if(!it(rt(o,"node_modules")))return c(`node_modules not installed. Run mist_install { projectPath: '${o}' } first.`,!0);let n,s,a,r=it(rt(o,"open-next.config.ts"))||it(rt(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 ot({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 At}from"zod";import{resolve as pc,join as bo}from"path";import{existsSync as wo}from"fs";var dc=At.object({projectPath:At.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:At.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),baseUrl:At.string().optional().describe("Override the URL Playwright tests hit \u2014 defaults to the project's configured base URL."),grep:At.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."}),vr={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:dc,handler:async t=>{let e=t;if(e.jobId){let i=await st(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=pc(e.projectPath);if(!wo(bo(o,"package.json")))return c(`No package.json at ${o}. Run mist_init first.`,!0);if(!(wo(bo(o,"playwright.config.ts"))||wo(bo(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 ot({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{z as at}from"zod";import{resolve as gc,join as fc}from"path";import{existsSync as yc}from"fs";ie();We();import{existsSync as ln,readdirSync as uc,statSync as xr,unlinkSync as kr}from"fs";import{join as qe}from"path";import{execFile as mc}from"child_process";function hc(t,e){let o=0;for(let n of e){let s=qe(t,n);if(ln(s))try{let a=xr(s);if(a.isFile())o++;else if(a.isDirectory()){let r=[s];for(;r.length;){let i=r.pop(),l=uc(i,{withFileTypes:!0});for(let p of l){let m=qe(i,p.name);p.isDirectory()?r.push(m):o++}}}}catch{}}return o}function Sr(t,e,o){return new Promise(n=>{mc("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 Pr(t){let e=qe(t,".open-next-build.tar.gz"),o=[".open-next"];ln(qe(t,"db"))&&o.push("db"),ln(qe(t,"drizzle.config.ts"))&&o.push("drizzle.config.ts"),ln(qe(t,"package.json"))&&o.push("package.json");let n=hc(t,o),s=await Sr(["-czf",e,"-C",t,...o],t,12e4);if(!s.success){try{kr(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(s.stderr?`
3400
- ${s.stderr.slice(-500)}`:""))}let a=0;try{a=xr(e).size}catch{}return{path:e,sizeBytes:a,fileCount:n}}async function Ir(t){let e=qe(t,".mistflow-source.tar.gz");return(await Sr(["-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 vo(t){if(t)try{kr(t)}catch{}}function _r(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function Tr(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 bc=at.object({action:at.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:at.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:at.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:at.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:at.string().optional().describe("Admin email injected as BETTER_AUTH_ADMIN_EMAIL on first deploy of an auth-enabled project.")});function wc(t){return yc(fc(t,".open-next"))}function vc(t){return _e(t)?.deploy?.strategy==="staging"?"preview":null}async function xc(t){let e=gc(t.projectPath);if(!G())return c("Not signed in. Call mist_setup first.",!0);let n=_e(e)?.projectId;if(!n)return c(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);if(!wc(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??vc(e)??"production",a=null,r=null;try{a=await Pr(e),r=await Ir(e);let i=await In(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:_r(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 A||i instanceof Error?i.message:String(i);return c(`Deploy upload failed: ${l}`,!0)}finally{vo(a?.path),vo(r)}}async function kc(t){try{let e=await bt(t),o=Tr(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 A||e instanceof Error?e.message:String(e);return c(`Could not fetch deploy status: ${o}`,!0)}}async function Sc(t,e){if(!G())return c("Not signed in. Call mist_setup first.",!0);let n=_e(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 Je(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 A?a.message:String(a);return c(`Could not list deployments: ${r}`,!0)}try{let a=await On(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 A||a instanceof Error?a.message:String(a);return c(`Promote failed: ${r}`,!0)}}async function Pc(t){if(!G())return c("Not signed in. Call mist_setup first.",!0);try{let e=await Mn(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 A||e instanceof Error?e.message:String(e);return c(`Rollback failed: ${o}`,!0)}}var Rr={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:bc,handler:async t=>{let e=t;switch(e.action??"deploy"){case"deploy":return e.projectPath?xc({projectPath:e.projectPath,environment:e.environment,adminEmail:e.adminEmail}):c("projectPath is required for action='deploy'.",!0);case"status":return e.deploymentId?kc(e.deploymentId):c("deploymentId is required for action='status'.",!0);case"promote":return e.projectPath?Sc(e.projectPath,e.deploymentId):c("projectPath is required for action='promote'.",!0);case"rollback":return e.deploymentId?Pc(e.deploymentId):c("deploymentId is required for action='rollback'.",!0)}}};var cn=new Ic({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Ro()}),Ar=[Qo,us,ms,fs,Os,zs,Ss,nr,Is,rr,yr,wr,vr,Rr];cn.setRequestHandler(Rc,async()=>({tools:Ar.map(t=>({name:t.name,description:t.description,inputSchema:Ac(t.inputSchema)}))}));cn.setRequestHandler(Tc,async t=>{let e=Ar.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:cn,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)}});async function Cc(){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 _c;await cn.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}Cc().catch(t=>{console.error("Fatal error:",t),process.exit(1)});
3397
+ `;function ln(){return me(gr(),".mistflow","jobs")}function Zl(){return me(gr(),".mistflow","job-wrapper.cjs")}function ec(){let t=Zl(),e=fr(t);an(e)||pr(e,{recursive:!0});let s=`v${br}`;if(an(t))try{if(ur(t,"utf-8").includes(s))return t}catch{}let n=me(e,`.job-wrapper.tmp.${yr(6).toString("hex")}`);return mr(n,Xl),hr(n,t),t}function pt(t){return me(ln(),t)}function wr(t){return me(pt(t),"status.json")}function cr(t,e){let s=wr(t),n=me(fr(s),`.status.tmp.${yr(6).toString("hex")}`);try{mr(n,JSON.stringify(e,null,2)+`
3398
+ `),hr(n,s)}catch(o){try{Yl(n)}catch{}throw o}}function tc(t){let e=wr(t);if(!an(e))return null;try{return JSON.parse(ur(e,"utf-8"))}catch{return null}}async function cn(t){let e=`job_${Ql().replace(/-/g,"").slice(0,12)}`,s=pt(e);pr(s,{recursive:!0}),xs(vs(me(s,"stdout.log"),"a")),xs(vs(me(s,"stderr.log"),"a"));let n=new Date().toISOString(),o={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:n,cmd:t.cmd,args:t.args,cwd:t.cwd};cr(e,o);let i=ec(),r={...process.env,...t.env??{}},a=Gl("node",[i,s,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:r});a.unref();let l={...o,wrapperPid:a.pid??0};return cr(e,l),l}function nc(t){let e=t.trim();if(!e)return NaN;let s=Date.parse(e);return Number.isFinite(s)?s:NaN}function sc(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let s=Vl("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=nc(s),o=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(o)&&Math.abs(n-o)>2e3)return!1}catch{}return!0}function oc(t,e){let s=Date.parse(t),n=e?Date.parse(e):Date.now();if(!Number.isFinite(s)||!Number.isFinite(n))return"0s";let o=Math.max(0,n-s),i=Math.floor(o/1e3);if(i<60)return`${i}s`;let r=Math.floor(i/60),a=i%60;return r<60?`${r}m ${a}s`:`${Math.floor(r/60)}h ${r%60}m`}function dr(t,e){if(!an(t))return"";let s=Kl(t);if(s.size===0)return"";let n=s.size>e?s.size-e:0,o=s.size-n,i=vs(t,"r");try{let r=Buffer.alloc(o);return Jl(i,r,0,o,n),r.toString("utf-8")}finally{xs(i)}}function rc(t,e=200){let s=dr(me(pt(t),"stdout.log"),65536),n=dr(me(pt(t),"stderr.log"),64*1024),o=[];return s.trim()&&o.push(...s.split(`
3399
+ `).slice(-e).map(i=>`[out] ${i}`)),n.trim()&&o.push(...n.split(`
3400
+ `).slice(-e).map(i=>`[err] ${i}`)),o.filter(i=>i.trim().length>0).join(`
3401
+ `)}function Nt(t){return{stdout:me(pt(t),"stdout.log"),stderr:me(pt(t),"stderr.log")}}async function dn(t){let e=tc(t);if(!e)return null;let s=e;return(e.status==="running"||e.status==="starting")&&!sc(e)&&(s={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...s,elapsed:oc(s.startedAt,s.endedAt),logTail:rc(t)}}var cc=ks.object({projectPath:ks.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:ks.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."}),vr={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:cc,handler:async t=>{let e=t;if(e.jobId){let a=await dn(e.jobId);if(!a)return c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No install job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0);if(a.status==="running"||a.status==="starting")return c(JSON.stringify({status:"running",jobId:a.id,elapsed:a.elapsed,logTail:a.logTail,nextAction:"Still running. Call mist_install with the same jobId in ~15-30s to check progress."}));if(a.status==="complete")return c(JSON.stringify({status:"complete",jobId:a.id,elapsed:a.elapsed,exitCode:a.exitCode,nextAction:"Dependencies installed. Run mist_implement next to start executing plan steps."}));let l=Nt(a.id);return c(JSON.stringify({status:a.status,jobId:a.id,elapsed:a.elapsed,exitCode:a.exitCode,logTail:a.logTail,logPaths:l,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${l.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let s=ic(e.projectPath);if(!ac(lc(s,"package.json")))return c(`No package.json at ${s}. Confirm the path and that mist_init has scaffolded the project.`,!0);let i=`npm install && (${`npx --yes shadcn@latest add -y -o ${["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"].join(" ")}`} || echo 'shadcn add failed \u2014 implement will retry lazily')`,r=await cn({type:"install",cmd:"sh",args:["-c",i],cwd:s,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return c(JSON.stringify({status:"running",jobId:r.id,startedAt:r.startedAt,cwd:s,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 pn}from"zod";import{resolve as dc,join as _e}from"path";import{existsSync as Re,readFileSync as xr,statSync as pc}from"fs";var kr=10*1024;function uc(t){if(!(Re(_e(t,"open-next.config.ts"))||Re(_e(t,"open-next.config.js"))))return null;let s=_e(t,".open-next","worker.js");if(!Re(s))return`Build exited 0 but .open-next/worker.js is missing at ${s}. The Cloudflare adapter did not produce a worker bundle. Common causes: (1) open-next.config.ts is misconfigured, (2) a client component imports a Node-only API (fs, path, crypto node:* imports in 'use client' files), (3) the adapter crashed silently mid-build. Check the logTail above for "error"/"failed" messages, fix the offending file, and re-run mist_build.`;try{let n=pc(s).size;if(n<kr)return`Build exited 0 but .open-next/worker.js is only ${n} bytes (expected at least ${kr}). The worker bundle is too small to be a working app \u2014 the adapter likely failed to bundle most of the code. Check open-next.config.ts and the logTail above for errors, fix them, and re-run mist_build.`}catch(n){return`Could not stat .open-next/worker.js: ${n instanceof Error?n.message:String(n)}. Re-run mist_build.`}return null}var mc=pn.object({projectPath:pn.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:pn.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:pn.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."});function hc(t){let e=_e(ln(),t,"stdout.log"),s=_e(ln(),t,"stderr.log"),n="";try{Re(e)&&(n+=xr(e,"utf-8"))}catch{}try{Re(s)&&(n+=`
3402
+ `+xr(s,"utf-8"))}catch{}return n}function gc(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,s=new Set;for(let n of t.matchAll(e)){let o=n[1];if(o.startsWith(".")||o.startsWith("@/")||o.startsWith("~/"))continue;let i=o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0];i&&s.add(i)}return[...s]}var Sr={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:mc,handler:async t=>{let e=t;if(e.jobId){let l=await dn(e.jobId);if(!l)return c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No build job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0);if(l.status==="running"||l.status==="starting")return c(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:l.logTail,nextAction:"Build still running. Call mist_build again with the same jobId in ~20-40s."}));if(l.status==="complete"){let b=uc(l.cwd);if(b){let f=Nt(l.id);return c(JSON.stringify({status:"failed",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:f,error:b,nextAction:b+` Full build log: ${f.stdout} and ${f.stderr}.`}),!0)}return c(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let d=hc(l.id),h=Xt(d),m=gc(d),p=Nt(l.id),y=` Full log: ${p.stdout} and ${p.stderr}.`,v=m.length>0?`Build failed with missing modules: ${m.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${y}`:h.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${y}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${y}`;return c(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,errors:h,missingModules:m,logTail:l.logTail,logPaths:p,nextAction:v}),!0)}let s=dc(e.projectPath);if(!Re(_e(s,"package.json")))return c(`No package.json at ${s}. Run mist_init first.`,!0);if(!Re(_e(s,"node_modules")))return c(`node_modules not installed. Run mist_install { projectPath: '${s}' } first.`,!0);let n,o,i,r=Re(_e(s,"open-next.config.ts"))||Re(_e(s,"open-next.config.js"));e.script?(n="npm",o=["run",e.script],i=e.script):r?(n="npx",o=["-y","@opennextjs/cloudflare","build"],i="@opennextjs/cloudflare build"):(n="npm",o=["run","build"],i="build");let a=await cn({type:"build",cmd:n,args:o,cwd:s});return c(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:s,script:i,nextAction:`Build started. Call mist_build again with { jobId: '${a.id}' } in ~30s to check progress. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}};import{existsSync as fc,readFileSync as yc}from"fs";import{join as bc}from"path";import{z as un}from"zod";de();var wc=un.object({projectPath:un.string().optional().describe("Absolute path to the Mistflow project. Defaults to the current working directory. Used to read mistflow.json for the deploy URL + projectId."),url:un.string().optional().describe("Override the deploy URL to QA. Useful for previews or when mistflow.json doesn't yet have the URL recorded. Defaults to mistflow.json's deploy.url."),deploymentId:un.string().optional().describe("Deployment ID to associate QA results with. When set, results are uploaded to the backend and surfaced on the dashboard deployment card.")}),Tr={name:"mist_qa",description:"Post-deploy QA: drives Playwright in-process against the live deploy URL. Checks health + auth endpoints, logs in with a seeded admin account, walks the dashboard and sidebar pages, and runs design-quality audits (typography, color, layout, slop patterns). Returns pass/fail + screenshots inline. Call ONCE after mist_deploy completes. Do NOT surface the deploy URL to the user until mist_qa returns status: 'pass'.",inputSchema:wc,handler:async t=>kc(t)};function vc(t){let e=bc(t,"mistflow.json");if(!fc(e))return null;try{return JSON.parse(yc(e,"utf-8"))}catch{return null}}async function Pr(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),s=await e.text();return{status:e.status,body:s}}catch(e){return{status:0,body:String(e)}}}async function xc(t,e,s){try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...s??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),o=await n.text(),i;try{i=JSON.parse(o)}catch{}return{status:n.status,json:i}}catch{return{status:0}}}async function Ir(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function ut(t,e,s){let n=[],o=i=>{i.type()==="error"&&n.push(i.text())};t.on("console",o);try{let i=await s(),r=await Ir(t);return{name:e,status:i.pass?"pass":"fail",detail:i.detail,fix:i.fix,screenshot:r,consoleErrors:n.length>0?n:void 0}}catch(i){let r=await Ir(t);return{name:e,status:"fail",detail:`Unexpected error: ${i instanceof Error?i.message:String(i)}`,screenshot:r,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",o)}}async function kc(t){let e=t.projectPath??process.cwd(),s=vc(e),n=t.url;if(n||(n=s?.deploy?.url),!n)return c("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);n.startsWith("http")||(n=`https://${n}`);let o=s?.projectId,i=[],r=await Pr(`${n}/api/health`);if(r.status!==200)return i.push({name:"Health endpoint",status:"fail",detail:`Returns ${r.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),mn(n,i);i.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Pr(`${n}/api/auth/ok`);if(a.status!==200)return i.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${a.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),mn(n,i);i.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,d,h;if(o){let y=await Dn(o);if(y){console.error("[qa] Calling seed endpoint for session token");let v=await xc(`${n}/api/admin/seed`,{token:y.seedToken,email:y.email,password:"QaTemp1!"});v.status===200&&v.json?(l=v.json.sessionToken,d=v.json.email,v.json.seeded?(h=v.json.password,console.error("[qa] New admin seeded \u2014 login form test available")):console.error("[qa] Admin already exists \u2014 session injection only")):console.error(`[qa] Seed endpoint returned ${v.status}`)}}if(!l)return i.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy process injects ADMIN_SEED_TOKEN into the worker env and stores the seed token on the backend. If the seed endpoint at /api/admin/seed is missing, ensure app/api/admin/seed/route.ts exists in the scaffold."}),mn(n,i);let m,p;try{let{getIsolatedContext:y}=await Promise.resolve().then(()=>(Ut(),Sn)),v=await y();m=v.context,p=v.page}catch(y){let v=y instanceof Error?y.message:String(y);return c(JSON.stringify({status:"cannot_verify",url:n,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:v,httpChecks:i.map(({screenshot:b,...f})=>f),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${n}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${n}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_qa again for full verification."].join(`
3403
+ `)}),!1)}try{let y=await ut(p,"Landing page",async()=>{await p.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await p.waitForLoadState("networkidle").catch(()=>{});let b=await p.evaluate(()=>{let k=document.body;if(!k)return"";let _=document.createTreeWalker(k,NodeFilter.SHOW_TEXT),N="",S;for(;S=_.nextNode();){let D=S.parentElement;if(D){let $=window.getComputedStyle(D);$.display!=="none"&&$.visibility!=="hidden"&&parseFloat($.opacity)>0&&(N+=S.textContent?.trim()+" ")}}return N.trim()});if(b.length<50)return{pass:!1,detail:`Landing page appears blank (${b.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let f=p.url();return f.includes("/login")||f.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${b.length} chars)`}});i.push(y);let v=!1;if(h){let b=await ut(p,"Login",async()=>{await p.goto(`${n}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let f=p.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),k=p.locator('input[type="password"], input[name="password"]');try{await f.first().waitFor({state:"visible",timeout:1e4})}catch{return{pass:!1,detail:"Login page has no visible email input field",fix:"Check app/(auth)/login/page.tsx renders a login form with email and password inputs."}}await f.first().fill(d),await k.first().fill(h),await p.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await p.waitForURL(N=>!N.pathname.includes("/login"),{timeout:1e4})}catch{let N=await p.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:N?`Login failed: ${N}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified admin account."}}return v=!0,{pass:!0,detail:`Logged in, redirected to ${p.url()}`}});i.push(b)}else i.push({name:"Login",status:"pass",detail:"Skipped form login (redeploy, password unavailable). Using session injection."});if(!v&&l){let b=new URL(n).hostname,f=n.startsWith("https");await m.addCookies([{name:f?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:b,path:"/",httpOnly:!0,secure:f,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let b=await ut(p,"Dashboard",async()=>{p.url().includes("/dashboard")||(await p.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let N=await p.content();return N.length<1e3?{pass:!1,detail:`Dashboard page is very small (${N.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await p.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled null/undefined or missing database tables."}:{pass:!0,detail:`Loads (${N.length} bytes)`}});i.push(b);let f=await p.evaluate(()=>{let _=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(S=>{let D=S.getAttribute("href");D&&D.startsWith("/")&&!D.startsWith("/api")&&!D.includes("[")&&D!=="/dashboard"&&D!=="/"&&!D.includes("/login")&&!D.includes("/sign")&&_.push(D)}),[...new Set(_)]});if(f.length>0){let _=0,N=[];for(let S of f.slice(0,8)){let D=await ut(p,`Page: ${S}`,async()=>{await p.goto(`${n}${S}`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let $=await p.title(),x=await p.content();return $.toLowerCase().includes("500")||$.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 server error",fix:"Server component crashed. Common causes: 1) Database tables missing. 2) Wrong ORM dialect (pgTable vs sqliteTable). 3) Unhandled null/undefined in server component."}:$.toLowerCase().includes("404")||$.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${S} not found. Create the page or remove the nav link.`}:await p.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:x.length<500?{pass:!1,detail:`Page is very small (${x.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});D.status==="fail"&&(_++,N.push(S)),i.push(D)}}let k=await ut(p,"Design quality",async()=>{let _=p.url().includes("/dashboard")?p.url():`${n}/dashboard`;p.url().includes("/dashboard")||(await p.goto(_,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let N=await p.evaluate(()=>{let S=[],D=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),$=new Set;D.forEach(C=>{$.add(window.getComputedStyle(C).fontSize)}),D.length>=3&&$.size<2&&S.push("TYPOGRAPHY: All headings appear the same size. Create clear hierarchy with 3+ distinct sizes using a modular scale (1.25-1.5x ratio).");let x=Array.from(D).map(C=>parseInt(C.tagName.charAt(1),10));for(let C=1;C<x.length;C++)if(x[C]-x[C-1]>1){S.push(`TYPOGRAPHY: Heading level skipped (h${x[C-1]} -> h${x[C]}). Use sequential heading levels for accessibility.`);break}let M=document.querySelectorAll("*"),z=!1,W=!1;M.forEach(C=>{let B=window.getComputedStyle(C);B.backgroundColor==="rgb(0, 0, 0)"&&C.clientHeight>100&&C.clientWidth>200&&(z=!0);let he=B.backgroundColor,G=B.color;if(he&&!he.includes("0, 0, 0")&&!he.includes("255, 255, 255")&&he!=="rgba(0, 0, 0, 0)"&&he!=="transparent"&&G.match(/rgb\((\d+), (\d+), (\d+)\)/)){let ke=G.match(/rgb\((\d+), (\d+), (\d+)\)/);if(ke){let[qe,Be,ze]=[parseInt(ke[1]),parseInt(ke[2]),parseInt(ke[3])],ue=Math.abs(qe-Be)<10&&Math.abs(Be-ze)<10&&qe>80&&qe<180,Ce=he.match(/rgb\((\d+), (\d+), (\d+)\)/);if(ue&&Ce){let[Ae,Ee,w]=[parseInt(Ce[1]),parseInt(Ce[2]),parseInt(Ce[3])];!(Math.abs(Ae-Ee)<15&&Math.abs(Ee-w)<15)&&C.textContent&&C.textContent.trim().length>0&&(W=!0)}}}}),z&&S.push("COLOR: Pure black (#000) background detected on a large element. Use a tinted dark color instead (e.g. oklch(15% 0.01 hue) or a deep navy/charcoal)."),W&&S.push("COLOR: Gray text on a colored background detected. Gray looks washed out on color. Use a darker shade of the background color or white instead.");let ne=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),A=!1;ne.forEach(C=>{C.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(A=!0)}),A&&S.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let R=document.querySelectorAll("p, li, span, div"),se=0,ce=0;R.forEach(C=>{C.textContent&&C.textContent.trim().length>20&&C.clientHeight>0&&(ce++,window.getComputedStyle(C).textAlign==="center"&&se++)}),ce>5&&se/ce>.7&&S.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let j=new Set;M.forEach(C=>{let B=window.getComputedStyle(C);B.gap&&B.gap!=="normal"&&B.gap!=="0px"&&j.add(B.gap)}),j.size===1&&M.length>20&&S.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let Q=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(C=>{C.querySelectorAll("tbody tr").length===0&&(C.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||S.push("UX: Empty table with no empty state. Add a helpful message explaining what will appear here and a CTA to create the first item."))});let pe=document.querySelectorAll("style"),Pe=!1;pe.forEach(C=>{let B=C.textContent||"";(B.includes("bounce")||B.includes("elastic")||B.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Pe=!0)}),Pe&&S.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let Fe=document.querySelectorAll("button, a, input, select, [role='button']"),F=0;return Fe.forEach(C=>{let B=C.getBoundingClientRect();B.width>0&&B.height>0&&(B.width<32||B.height<32)&&F++}),F>3&&S.push(`ACCESSIBILITY: ${F} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),S});return N.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${N.length} design quality issue(s) found:
3404
+ ${N.map((S,D)=>`${D+1}. ${S}`).join(`
3405
+ `)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});if(i.push(k),i.find(_=>_.name==="Landing page"&&_.status==="pass")){let _=await ut(p,"Landing design quality",async()=>{await p.goto(n,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let N=await p.evaluate(()=>{let S=[];document.querySelectorAll("*").forEach(M=>{let z=window.getComputedStyle(M);(z.getPropertyValue("-webkit-background-clip")||z.getPropertyValue("background-clip"))==="text"&&M.textContent&&M.textContent.trim().length>0&&S.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let $=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if($){let M=($.textContent||"").toLowerCase(),z=["transform your","unlock the power","revolutionize your","take your .* to the next level","the future of","welcome to","get started today","join thousands","powerful analytics","seamless integration","lightning fast"];for(let W of z)if(M.match(new RegExp(W))){S.push(`COPY: Generic hero text detected ('${W}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(M=>{let W=window.getComputedStyle(M).gridTemplateColumns;if(W){let ne=W.split(" ").filter(R=>R!=="").length,A=M.children;if(ne===3&&A.length===3){let R=Array.from(A).map(j=>j.offsetHeight),se=R.every(j=>Math.abs(j-R[0])<5),ce=Array.from(A).every(j=>{let Q=j.querySelectorAll("svg"),Se=j.querySelectorAll("h2, h3, h4"),pe=j.querySelectorAll("p");return Q.length>=1&&Se.length>=1&&pe.length>=1});se&&ce&&S.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),S});return N.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${N.length} landing design issue(s):
3406
+ ${N.map((S,D)=>`${D+1}. ${S}`).join(`
3407
+ `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(_)}}}finally{m&&await m.close().catch(()=>{})}if(t.deploymentId){let y=i.filter(f=>f.status==="fail"),v=i.filter(f=>f.status==="pass"),b=Date.now();await On(t.deploymentId,{checks:i.map(({screenshot:f,...k})=>k),overall:y.length===0?"pass":"fail",passed:v.length,failed:y.length,duration_ms:Date.now()-b}).catch(()=>{})}return mn(n,i)}function mn(t,e){let s=e.filter(i=>i.status==="fail"),n=e.filter(i=>i.status==="pass"),o=[];if(s.length===0)o.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${e.length} checks OK. The app is working correctly.`,url:t,checks:e.map(({screenshot:i,...r})=>r)})});else{let i=s.map((r,a)=>`${a+1}. **${r.name}**: ${r.detail}
3408
+ Fix: ${r.fix}`).join(`
3409
+
3410
+ `);o.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${s.length} issue(s) on the live app. Fix them and redeploy.`,url:t,passed:n.length,failed:s.length,checks:e.map(({screenshot:r,...a})=>a),fixInstructions:`The deployed app at ${t} has ${s.length} issue(s):
3411
+
3412
+ ${i}
3413
+
3414
+ Fix these issues in the source code, then call mist_deploy with action='deploy'${t.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let i of e)i.screenshot&&o.push({type:"image",data:i.screenshot,mimeType:"image/png"});return{content:o}}import{z as mt}from"zod";import{resolve as Tc,join as _c}from"path";import{existsSync as Rc}from"fs";de();Ze();import{existsSync as hn,readdirSync as Sc,statSync as _r,unlinkSync as Rr}from"fs";import{join as Ke}from"path";import{execFile as Pc}from"child_process";function Ic(t,e){let s=0;for(let n of e){let o=Ke(t,n);if(hn(o))try{let i=_r(o);if(i.isFile())s++;else if(i.isDirectory()){let r=[o];for(;r.length;){let a=r.pop(),l=Sc(a,{withFileTypes:!0});for(let d of l){let h=Ke(a,d.name);d.isDirectory()?r.push(h):s++}}}}catch{}}return s}function Cr(t,e,s){return new Promise(n=>{Pc("tar",t,{cwd:e,timeout:s,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(o,i,r)=>{n({success:!o,stderr:r?.toString()??""})})})}async function Ar(t){let e=Ke(t,".open-next-build.tar.gz"),s=[".open-next"];hn(Ke(t,"db"))&&s.push("db"),hn(Ke(t,"drizzle.config.ts"))&&s.push("drizzle.config.ts"),hn(Ke(t,"package.json"))&&s.push("package.json");let n=Ic(t,s),o=await Cr(["-czf",e,"-C",t,...s],t,12e4);if(!o.success){try{Rr(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(o.stderr?`
3415
+ ${o.stderr.slice(-500)}`:""))}let i=0;try{i=_r(e).size}catch{}return{path:e,sizeBytes:i,fileCount:n}}async function Er(t){let e=Ke(t,".mistflow-source.tar.gz");return(await Cr(["-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 Ss(t){if(t)try{Rr(t)}catch{}}function Nr(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function jr(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 Cc=mt.object({action:mt.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:mt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:mt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:mt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:mt.string().optional().describe("Admin email injected as BETTER_AUTH_ADMIN_EMAIL on first deploy of an auth-enabled project.")});function Ac(t){return Rc(_c(t,".open-next"))}function Ec(t){return De(t)?.deploy?.strategy==="staging"?"preview":null}async function Nc(t){let e=Tc(t.projectPath);if(!X())return c("Not signed in. Call mist_setup first.",!0);let n=De(e)?.projectId;if(!n)return c(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);if(!Ac(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 o=t.environment??Ec(e)??"production",i=null,r=null;try{i=await Ar(e),r=await Er(e);let a=await Cn(n,i.path,o,t.adminEmail,void 0,r??void 0,void 0);return c(JSON.stringify({status:"running",jobId:a.deployment_id,deploymentId:a.deployment_id,environment:a.environment??o,buildSize:Nr(i.sizeBytes),buildFileCount:i.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${a.deployment_id}' } in ~5-10s to poll deployment progress. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(a){let l=a instanceof U||a instanceof Error?a.message:String(a);return c(`Deploy upload failed: ${l}`,!0)}finally{Ss(i?.path),Ss(r)}}async function jc(t){try{let e=await xt(t),s=jr(e.status);return e.status==="live"?c(JSON.stringify({status:"complete",jobId:e.id,deploymentId:e.id,url:e.url,completedAt:e.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${e.url??""}', deploymentId: '${e.id??""}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`})):e.status==="failed"?c(JSON.stringify({status:"failed",jobId:e.id,deploymentId:e.id,error:e.error,phase:s,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:s,phaseCode:e.status,nextAction:`Still ${e.status}. Call mist_deploy { action: 'status', deploymentId: '${e.id}' } again in ~5-10s.`}))}catch(e){let s=e instanceof U||e instanceof Error?e.message:String(e);return c(`Could not fetch deploy status: ${s}`,!0)}}async function Dc(t,e){if(!X())return c("Not signed in. Call mist_setup first.",!0);let n=De(t)?.projectId;if(!n)return c(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let o=e;if(!o)try{let r=(await nt(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!r)return c("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);o=r.id}catch(i){let r=i instanceof U?i.message:String(i);return c(`Could not list deployments: ${r}`,!0)}try{let i=await qn(n,o);return c(JSON.stringify({status:"running",jobId:i.deployment_id,deploymentId:i.deployment_id,promotedFrom:o,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${i.deployment_id}' } to poll. Promotion re-uses the preview artifact so it typically completes in ~10s.`}))}catch(i){let r=i instanceof U||i instanceof Error?i.message:String(i);return c(`Promote failed: ${r}`,!0)}}async function Oc(t){if(!X())return c("Not signed in. Call mist_setup first.",!0);try{let e=await Bn(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 s=e instanceof U||e instanceof Error?e.message:String(e);return c(`Rollback failed: ${s}`,!0)}}var Dr={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:Cc,handler:async t=>{let e=t;switch(e.action??"deploy"){case"deploy":return e.projectPath?Nc({projectPath:e.projectPath,environment:e.environment,adminEmail:e.adminEmail}):c("projectPath is required for action='deploy'.",!0);case"status":return e.deploymentId?jc(e.deploymentId):c("deploymentId is required for action='status'.",!0);case"promote":return e.projectPath?Dc(e.projectPath,e.deploymentId):c("projectPath is required for action='promote'.",!0);case"rollback":return e.deploymentId?Oc(e.deploymentId):c("deploymentId is required for action='rollback'.",!0)}}};var gn=new Mc({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Es()}),Or=[Zs,go,fo,wo,Uo,Go,To,rr,Ro,lr,vr,Sr,Tr,Dr];gn.setRequestHandler(Lc,async()=>({tools:Or.map(t=>({name:t.name,description:t.description,inputSchema:Fc(t.inputSchema)}))}));gn.setRequestHandler(Uc,async t=>{let e=Or.find(s=>s.name===t.params.name);if(!e)return c(`Unknown tool: ${t.params.name}`,!0);try{let s=e.inputSchema.safeParse(t.params.arguments);if(!s.success){let i=s.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join(", ");return c(`Invalid input: ${i}`,!0)}let n=t.params._meta?.progressToken,o={server:gn,progressToken:n};try{return await e.handler(s.data,o)}finally{o.cleanup?.()}}catch(s){let n=s instanceof Error?s.message:"An unexpected error occurred";return console.error("Tool error:",s),c(n,!0)}});async function qc(){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 $c;await gn.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}qc().catch(t=>{console.error("Fatal error:",t),process.exit(1)});