@mistflow-ai/mcp 1.0.17 → 1.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +173 -177
- package/dist/index.js +170 -174
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,{mode:384})}catch{}}function
|
|
3
|
-
What's new: ${r.changelogUrl}`:"";return
|
|
1
|
+
var js=Object.defineProperty;var Ve=(t,e)=>()=>(t&&(e=t(t=0)),e);var It=(t,e)=>{for(var r in e)js(t,r,{get:e[r],enumerable:!0})};import{existsSync as fo,readFileSync as Sr,writeFileSync as Hs,mkdirSync as Ws}from"fs";import{join as ho,dirname as go}from"path";import{homedir as Gs}from"os";import{fileURLToPath as Vs}from"url";function ge(){if(At)return At;try{let t=Vs(import.meta.url),e=go(t);for(let r=0;r<6;r++){let o=ho(e,"package.json");if(fo(o)){let i=JSON.parse(Sr(o,"utf-8"));if(i.name==="@mistflow-ai/mcp"&&typeof i.version=="string")return At=i.version,i.version}let s=go(e);if(s===e)break;e=s}}catch{}return At="0.0.0","0.0.0"}function _t(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 vr(t,e){let r=_t(t),o=_t(e);if(!r||!o)return 0;for(let s=0;s<3;s++){if(r[s]<o[s])return-1;if(r[s]>o[s])return 1}return 0}function Tr(t,e,r){if(r&&vr(t,r)<0)return"unsupported";if(!e||vr(t,e)>=0)return"none";let s=_t(t),i=_t(e);return!s||!i?"none":s[0]<i[0]?"major":s[1]<i[1]?"minor":"patch"}function st(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",o=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||(he={latest:e,minSupported:r,changelogUrl:o})}function Pr(){let t=process.env.MISTFLOW_STATE_DIR||ho(Gs(),".mistflow");return ho(t,"upgrade-state.json")}function Ks(){try{let t=Pr();return fo(t)?JSON.parse(Sr(t,"utf-8")):{}}catch{return{}}}function Js(t){try{let e=Pr(),r=go(e);fo(r)||Ws(r,{recursive:!0}),Hs(e,JSON.stringify(t,null,2)+`
|
|
2
|
+
`,{mode:384})}catch{}}function Ys(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Cr(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!he)return null;let t=ge();if(t==="0.0.0")return null;let e=Tr(t,he.latest,he.minSupported);if(e==="none")return null;if(e==="unsupported")return xr(e,t,he);if(kr)return null;let r=Ks(),o=Date.now(),s=Ys(e);return r.dismissedForVersion===he.latest&&e!=="major"||r.lastLatestSeen===he.latest&&r.lastShownMs&&o-r.lastShownMs<s?null:(kr=!0,Js({...r,lastShownMs:o,lastLatestSeen:he.latest}),xr(e,t,he))}function xr(t,e,r){let o="npx -y mistflow-ai install",s=r.changelogUrl?`
|
|
3
|
+
What's new: ${r.changelogUrl}`:"";return t==="unsupported"?`
|
|
4
4
|
|
|
5
5
|
---
|
|
6
|
-
Mistflow ${
|
|
6
|
+
Mistflow ${e} is no longer supported.
|
|
7
7
|
You must upgrade to ${r.latest} or newer to continue:
|
|
8
8
|
|
|
9
9
|
${o}
|
|
10
10
|
|
|
11
11
|
After upgrading, restart your AI editor.${s}
|
|
12
|
-
---`:
|
|
12
|
+
---`:t==="major"?`
|
|
13
13
|
|
|
14
14
|
---
|
|
15
|
-
Mistflow ${r.latest} is available (you have ${
|
|
15
|
+
Mistflow ${r.latest} is available (you have ${e}).
|
|
16
16
|
This is a major update. Run \`${o}\` and restart your editor.${s}
|
|
17
|
-
---`:
|
|
17
|
+
---`:t==="minor"?`
|
|
18
18
|
|
|
19
|
-
--- Mistflow update available: ${
|
|
19
|
+
--- Mistflow update available: ${e} -> ${r.latest} ---
|
|
20
20
|
Run \`${o}\` to upgrade, then restart your editor.${s}`:`
|
|
21
21
|
|
|
22
|
-
(Mistflow ${r.latest} is out, you have ${
|
|
23
|
-
`,{mode:384}),vi(i,t)}catch(n){try{ki(i)}catch{}throw n}}function Vr(){let e=Je();return e.ok?e.creds:null}function ce(){return Je().ok}function Be(e){let t=Do(e,"mistflow.json");if(!No(t))return null;try{return JSON.parse(Hr(t,"utf-8"))}catch{return null}}var Pi,Ye=nt(()=>{"use strict";Pi="https://api.mistflow.ai"});var Zr={};qt(Zr,{MistflowApiError:()=>F,addDomain:()=>Uo,checkAuth:()=>_i,checkAuthDetailed:()=>Qr,checkSubdomain:()=>Kt,createDeployment:()=>Ei,createProject:()=>Ct,deleteEnvVar:()=>Ho,discoverDecisions:()=>Ni,downloadSource:()=>Oi,downloadSourceWithToken:()=>Xr,fetchDesignDirections:()=>Lo,fetchModule:()=>Qo,fetchPlanConversation:()=>Jt,fetchScaffold:()=>Jo,fetchStepContext:()=>Yo,forkTemplate:()=>Zo,generatePlan:()=>Yt,getAuthHeaders:()=>Qe,getBaseUrl:()=>de,getDashboardUrl:()=>Ci,getDbCredentials:()=>Di,getDeployLogs:()=>Wo,getDeploymentStatus:()=>It,getProject:()=>Ri,getProjectErrors:()=>Go,getSeedInfo:()=>Fo,getSiteUrl:()=>st,getTemplate:()=>Xo,hasCredentialsOnDisk:()=>ce,hasLocalCredentials:()=>Yr,listDeployments:()=>at,listDomains:()=>ze,listEnvVars:()=>Bo,markLocalSetupDone:()=>Mi,modifyPlan:()=>Qt,pingBackend:()=>Oo,promotePreview:()=>Vo,redeployProject:()=>ji,removeDomain:()=>$o,rollbackDeployment:()=>Ko,shareProject:()=>er,uploadAndDeploy:()=>Mo,uploadQAResults:()=>qo,upsertEnvVar:()=>zo,verifyDomain:()=>Xt});function de(){return Gt()}function st(){let e=process.env.MISTFLOW_API_URL;if(e){if(e.includes("mistflow.localhost"))return e.replace("api.mistflow","mistflow");if(e.includes("localhost:9100"))return e.replace(":9100",":9102")}return"https://mistflow.ai"}function Ci(){let e=process.env.MISTFLOW_API_URL;if(e){if(e.includes("mistflow.localhost"))return e.replace("api.mistflow","app.mistflow");if(e.includes("localhost:9100"))return e.replace(":9100",":9101")}return"https://app.mistflow.ai"}function Qe(){let e=Je();if(!e.ok)throw new F("auth_missing","No Mistflow credentials found.",401);return Ii(e.creds)}function Ii(e){return{Authorization:`ApiKey ${e.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":Ie()}}function it(e){try{vt(e.headers)}catch{}}async function Oo(){try{let e=await fetch(`${de()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});it(e)}catch{}}async function Jr(e,t,r,o){for(let s=0;s<2;s++)try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(i){let n=i instanceof Error&&i.name==="TimeoutError",a=i instanceof TypeError;if(o&&s===0&&(n||a)){console.error(`[api] Retrying ${e} after ${n?"timeout":"network error"}`);continue}throw i}throw new Error("fetchWithRetry: exhausted retries")}async function Pt(e){let t=null;try{t=await e.json()}catch{t=null}let r=t&&typeof t.code=="string"?t.code:void 0,o=t&&typeof t.message=="string"?t.message:t&&typeof t.detail=="string"?t.detail:e.statusText||"Request failed";if(r)return new F(r,o,e.status,t?.details);let s=e.status;return s===401?new F("auth_invalid",o,s):s===403?new F("permission_denied",o,s):s===404?new F("not_found",o,s):s===409?new F("conflict",o,s):s===422?new F("validation_error",o,s):s===429?new F("rate_limited",o,s):s>=500?new F("server_error",e.statusText||"Internal server error",s):new F("client_error",o,s)}async function H(e,t={}){let r=Qe(),{timeoutMs:o,idempotent:s,...i}=t,n=o??3e4,a=(i.method??"GET").toUpperCase(),l=s??(a==="GET"||a==="HEAD"),c;try{c=await Jr(`${de()}${e}`,{...i,headers:{...r,...i.headers}},n,l)}catch(h){throw h instanceof Error&&h.name==="TimeoutError"?new F("network_error","Request timed out. Try again in a moment."):new F("network_error","Cannot reach Mistflow servers. Check your network.")}if(it(c),!c.ok)throw await Pt(c);return c.json()}function Yr(){return Je().ok}async function _i(){return(await Qr()).ok}async function Qr(){if(Vt!==null&&Date.now()<Kr)return Vt?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Yr())return{ok:!1,reason:"no_credentials"};try{return await H("/api/org"),Vt=!0,Kr=Date.now()+Ai,{ok:!0}}catch(e){if(Vt=null,!(e instanceof F))return{ok:!1,reason:"network_error"};switch(e.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 Ri(e){return H(`/api/projects/${encodeURIComponent(e)}`)}async function Kt(e){return H(`/api/projects/check-subdomain?name=${encodeURIComponent(e)}`)}async function Ct(e,t,r="neon",o){return H("/api/projects",{method:"POST",body:JSON.stringify({name:e,template:t,db_provider:r,requested_subdomain:o})})}async function Ei(e,t){return H("/api/deploy",{method:"POST",body:JSON.stringify({project_id:e,build_output_url:t})})}async function Mo(e,t,r="production",o,s,i,n){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=Je();if(!c.ok)throw new F("auth_missing","No Mistflow credentials found.",401);let h=c.creds,m=a(t),u=new Blob([m],{type:"application/gzip"}),w=new FormData;if(w.append("project_id",e),w.append("build",u,l(t)),r!=="production"&&w.append("environment",r),o&&w.append("admin_email",o),s&&w.append("schema_pushed","true"),i){let{existsSync:x}=await import("fs");if(x(i)){let f=a(i),P=new Blob([f],{type:"application/gzip"});w.append("source",P,"source.tar.gz")}}n&&w.append("git_commit_sha",n);let D;try{D=await fetch(`${de()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":Ie()},body:w,signal:AbortSignal.timeout(3e5)})}catch{throw new F("network_error","Cannot reach Mistflow servers. Check your network.")}if(it(D),!D.ok)throw await Pt(D);let S=await D.json();return{...S,id:S.deployment_id}}async function It(e,t){let r=t?.waitSeconds??0,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return H(`/api/deploy/${encodeURIComponent(e)}/status${o}`,r>0?{timeoutMs:s}:void 0)}async function Lo(e){return H(`/api/plan/design-directions/${encodeURIComponent(e)}`,{timeoutMs:15e3})}async function Jt(e,t){let r=t?.waitSeconds??20,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return H(`/api/plan/conversations/${encodeURIComponent(e)}${o}`,{timeoutMs:s})}async function Yt(e,t){let r={description:e,conversation_id:t?.conversationId,answers:t?.answers};t?.autonomous&&(r.autonomous=!0),t?.language&&t.language.toLowerCase()!=="english"&&(r.language=t.language),t?.designConversationId&&(r.design_conversation_id=t.designConversationId),t?.designDirection&&(r.design_direction=t.designDirection);let o=t?.conversationId||t?.answers||t?.designConversationId?18e4:6e4;return H("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:o,idempotent:!1})}async function Qt(e,t){return H("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:e,modification:t})})}async function Ni(e){return H("/api/plan/discover",{method:"POST",body:JSON.stringify({description:e})})}async function Uo(e,t){return H(`/api/projects/${encodeURIComponent(e)}/domains`,{method:"POST",body:JSON.stringify({domain:t})})}async function ze(e){return H(`/api/projects/${encodeURIComponent(e)}/domains`)}async function Xt(e,t){return H(`/api/projects/${encodeURIComponent(e)}/domains/${encodeURIComponent(t)}/verify`)}async function $o(e,t){return H(`/api/projects/${encodeURIComponent(e)}/domains/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Di(e){return H(`/api/projects/${encodeURIComponent(e)}/db-credentials`)}async function Fo(e){try{return await H(`/api/projects/${encodeURIComponent(e)}/test-accounts`)}catch(t){return t instanceof F&&(t.statusCode===404||t.code==="not_found")||console.error("[api] Failed to fetch seed info:",t instanceof Error?t.message:t),null}}async function qo(e,t){try{return await H(`/api/deploy/${encodeURIComponent(e)}/qa-results`,{method:"POST",body:JSON.stringify(t)})}catch(r){return console.error("[api] Failed to upload QA results:",r instanceof Error?r.message:r),null}}async function Bo(e){return H(`/api/projects/${encodeURIComponent(e)}/env`)}async function zo(e,t,r,o){return H(`/api/projects/${encodeURIComponent(e)}/env`,{method:"PUT",body:JSON.stringify({key:t,value:r,category:o?.category??"custom",description:o?.description,setup_url:o?.setupUrl})})}async function Ho(e,t){return H(`/api/projects/${encodeURIComponent(e)}/env/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Wo(e){return H(`/api/deploy/${encodeURIComponent(e)}/logs`)}async function Go(e,t="7d"){return H(`/api/projects/${encodeURIComponent(e)}/errors?period=${encodeURIComponent(t)}`)}async function at(e){return H(`/api/projects/${encodeURIComponent(e)}/deployments`)}async function ji(e){return H(`/api/deploy/${encodeURIComponent(e)}/redeploy`,{method:"POST"})}async function Vo(e,t){let r=new URLSearchParams({preview_deployment_id:t});return H(`/api/deploy/${encodeURIComponent(e)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Ko(e){return H(`/api/deploy/${encodeURIComponent(e)}/rollback`,{method:"POST"})}async function Oi(e,t){let r=Je();if(!r.ok)throw new F("auth_missing","Not authenticated.",401);let o=r.creds,s=await fetch(`${de()}/api/deploy/${encodeURIComponent(e)}/source`,{headers:{Authorization:`ApiKey ${o.apiKey}`,"X-Mistflow-MCP-Version":Ie()},signal:AbortSignal.timeout(12e4)});if(it(s),!s.ok)throw await Pt(s);let{writeFileSync:i}=await import("fs"),n=Buffer.from(await s.arrayBuffer());i(t,n)}async function Zt(e,t){let{timeoutMs:r,idempotent:o,...s}=t??{},i=r??3e4,n=(s.method??"GET").toUpperCase(),a=o??(n==="GET"||n==="HEAD"),l;try{l=await Jr(`${de()}${e}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":Ie()},...s},i,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new F("network_error","Request timed out. Try again in a moment."):new F("network_error","Cannot reach Mistflow servers. Check your network.")}if(it(l),!l.ok)throw await Pt(l);return l.json()}async function Jo(e="nextjs"){return Zt(`/api/scaffold/${encodeURIComponent(e)}`)}async function Yo(e,t){return Zt(`/api/scaffold/${encodeURIComponent(e)}/context?step_type=${encodeURIComponent(t)}`)}async function Qo(e,t,r,o){return Zt(`/api/scaffold/${encodeURIComponent(e)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:t,fields:r,entity_plural:o})})}async function Xo(e){return Zt(`/api/templates/${encodeURIComponent(e)}`)}async function Zo(e){return H(`/api/templates/${encodeURIComponent(e)}/fork`,{method:"POST"})}async function Xr(e,t,r){let o;try{o=await fetch(`${de()}/api/deploy/${encodeURIComponent(e)}/fork-source?fork_token=${encodeURIComponent(t)}`,{headers:{"X-Mistflow-MCP-Version":Ie()},signal:AbortSignal.timeout(12e4)})}catch{throw new F("network_error","Cannot reach Mistflow servers. Check your network.")}if(it(o),!o.ok)throw o.status===401?new F("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",o.status):await Pt(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(r,i)}async function Mi(e){await H(`/api/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function er(e,t){return H(`/api/projects/${encodeURIComponent(e)}/share`,{method:"POST",body:JSON.stringify({is_template:t?.isTemplate??!1,template_description:t?.description})})}var F,Vt,Kr,Ai,be=nt(()=>{"use strict";Ye();kt();F=class extends Error{constructor(r,o,s,i){super(o);this.code=r;this.statusCode=s;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"}};Vt=null,Kr=0,Ai=300*1e3});var Rt={};qt(Rt,{emptyState:()=>_t,fetchRemoteState:()=>Ji,fuzzyMatch:()=>Qi,getLocalStatePath:()=>or,readLocalState:()=>Ki,syncRemoteState:()=>Yi,writeLocalState:()=>At});import{existsSync as sn,readFileSync as Wi,writeFileSync as Gi,mkdirSync as Vi}from"fs";import{join as an}from"path";function or(e){return an(e,".mistflow","state.json")}function Ki(e){let t=or(e);if(!sn(t))return null;try{return JSON.parse(Wi(t,"utf-8"))}catch{return null}}function At(e,t){let r=an(e,".mistflow");sn(r)||Vi(r,{recursive:!0}),Gi(or(e),JSON.stringify(t,null,2)+`
|
|
24
|
-
`)}function _t(e,t){return{projectId:e,name:t,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Ji(e){let t;try{t=Qe()}catch{return null}try{let r=await fetch(`${de()}/api/projects/${encodeURIComponent(e)}/state`,{headers:{...t,"Content-Type":"application/json","X-Mistflow-MCP-Version":Ie()}});try{vt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function Yi(e,t){let r;try{r=Qe()}catch{return!1}try{let o=await fetch(`${de()}/api/projects/${encodeURIComponent(e)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":Ie()},body:JSON.stringify(t)});try{vt(o.headers)}catch{}return o.ok}catch{return!1}}function Qi(e,t){let r=e.toLowerCase(),o=t.toLowerCase();return o.includes(r)||r.includes(o)?!0:r.split(/\s+/).some(i=>i.length>=3&&o.includes(i))}var Xe=nt(()=>{"use strict";be();kt()});var rr={};qt(rr,{ensureBackendRegistered:()=>na,ensureShadcnComponents:()=>sa});import{existsSync as cn,readFileSync as Xi,writeFileSync as Zi}from"fs";import{join as eo}from"path";import{spawn as ea}from"child_process";function ta(e,t,r,o,s){return new Promise(i=>{let n=ea(e,t,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:o,...s?{env:{...process.env,...s}}:{}}),a="",l="";n.stdout?.on("data",c=>{a+=c.toString()}),n.stderr?.on("data",c=>{l+=c.toString()}),n.on("close",c=>i({success:c===0,stdout:a,stderr:l})),n.on("error",c=>i({success:!1,stdout:a,stderr:l+c.message}))})}function oa(e){let t=eo(e,"mistflow.json");if(!cn(t))return null;try{return JSON.parse(Xi(t,"utf-8"))}catch{return null}}function ra(e,t){Zi(eo(e,"mistflow.json"),JSON.stringify(t,null,2))}async function ln(e,t){try{let r=t.features,o=t.steps,s={plan:t};Array.isArray(r)&&r.length>0&&(s.features=r.map(i=>i.name)),Array.isArray(o)&&o.length>0&&(s.provenance=o.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(`${de()}/api/projects/${encodeURIComponent(e)}/state`,{method:"PUT",headers:{...Qe(),"Content-Type":"application/json"},body:JSON.stringify(s)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function na(e,t={}){let r=oa(e);if(r){if(!ce())return r.projectId;if(!r.projectId)try{let s=r.plan?.requestedSubdomain,i=await Ct(r.name,void 0,r.dbProvider??"neon",s);return r.projectId=i.id,ra(e,r),At(e,_t(i.id,r.name)),r.plan&&await ln(i.id,r.plan),console.error(`[self-heal] registered project ${i.id.slice(0,8)} with backend`),i.id}catch(o){console.error("[self-heal] createProject failed:",o instanceof Error?o.message:String(o));return}return t.forceSync&&r.plan&&r.projectId&&await ln(r.projectId,r.plan),r.projectId}}async function sa(e,t){let r=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],o=t&&t.length>0?t:r,s=eo(e,"components","ui"),i=[],n=[];for(let c of o)cn(eo(s,`${c}.tsx`))?i.push(c):n.push(c);if(n.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await ta("npx",["--yes","shadcn@latest","add","-y","-o",...n],e,18e4,a);return l.success?{installed:n,alreadyPresent:i}:{installed:[],alreadyPresent:i,failed:`shadcn add failed for: ${n.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var nr=nt(()=>{"use strict";be();Xe()});import{Server as yd}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as bd}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as wd,ListToolsRequestSchema as vd}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as kd}from"zod-to-json-schema";var ei="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.",ti='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"`.',oi="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.",ri="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.",ni='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.',si="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.",ii="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.",ai='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.',li="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST ask the user and WAIT for their actual answer before submitting anything back. Use your host's native structured-question UI: `AskUserQuestion` in Claude Code, quick pick in Cursor, `request_user_input` in OpenAI Codex (available in Plan mode \u2014 if Codex returns 'request_user_input is unavailable in <mode> mode', you are in default mode; stop your turn and print the questions as a numbered chat message, then wait for the user's next message). For any host that does not expose a structured question tool, stop your turn immediately, print the questions verbatim as a numbered list with all options visible, and wait \u2014 the user's next message is the answer. The rule across every host: you never submit answers to `mist_plan` in the same turn you received the questions. That is always wrong, regardless of how obvious the `recommended` choice looks, regardless of whether you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode. The `recommended` field is a hint FOR the user, not permission FOR you. Anti-example from a real transcript: the host AI received 7 discovery questions, wrote 'I'll lock in the defaults with Azure OpenAI as the only override,' submitted answers the user never saw, and the user ended up with a plan they didn't choose. That behavior is a regression bug. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to perform that submission step; that is your job.",Ar="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).",_r="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.",Rr="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.",Er="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.",Nr="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).",Dr="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 jr(){let e=[];return e.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."),e.push(""),e.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.'),e.push(""),e.push(ai),e.push(""),e.push(ei),e.push(""),e.push(ti),e.push(""),e.push(oi),e.push(""),e.push(ri),e.push(""),e.push(li),e.push(""),e.push(si),e.push(""),e.push("New app workflow:"),e.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."),e.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via your host\'s native question tool (AskUserQuestion in Claude Code / request_user_input in Codex Plan mode / quick pick in Cursor / stop-and-wait for hosts without one \u2014 see RULE_SENTINEL_HANDLING), collect the user\'s actual answers, then submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick via mist_plan with `designConversationId` + `designDirection` (NOT `conversationId` alone).'),e.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 }."),e.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),e.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),e.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."),e.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."),e.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)."),e.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'."),e.push(""),e.push(ni),e.push(""),e.push(ii),e.push(""),e.push("Updating an existing Mistflow app:"),e.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),e.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),e.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."),e.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."),e.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),e.push(""),e.push("Tool summary:"),e.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."),e.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),e.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),e.push("- mist_help: returns the full tool reference. Call once per session."),e.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),e.push("- mist_install / mist_build / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),e.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."),e.join(`
|
|
25
|
-
`)}
|
|
22
|
+
(Mistflow ${r.latest} is out, you have ${e}. Run \`${o}\` when convenient.)`}function yo(){let t=ge(),e=he??{latest:"",minSupported:"",changelogUrl:""},r=Tr(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:he!==null}}var At,he,kr,it=Ve(()=>{"use strict";At=null;he=null;kr=!1});var Et={};It(Et,{closeBrowser:()=>wo,getIsolatedContext:()=>Xs,getPage:()=>bo,getSnapshot:()=>at,takeScreenshot:()=>lt});async function Ir(){try{return await import("playwright")}catch{throw new Error("Playwright is not installed. Run: cd packages/mcp-server && pnpm add playwright && npx playwright install chromium")}}async function Qs(){let t=await Ir();return(!fe||!fe.isConnected())&&(fe=await t.chromium.launch({headless:!0})),_e&&(await _e.close().catch(()=>{}),_e=null),_e=await fe.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Ie=await _e.newPage(),Ie}async function bo(){return Ie&&!Ie.isClosed()?Ie:(Rt||(Rt=Qs().finally(()=>{Rt=null})),Rt)}async function wo(){Ie&&!Ie.isClosed()&&await Ie.close().catch(()=>{}),_e&&await _e.close().catch(()=>{}),fe?.isConnected()&&await fe.close().catch(()=>{}),Ie=null,_e=null,fe=null}async function Xs(){let t=await Ir();(!fe||!fe.isConnected())&&(fe=await t.chromium.launch({headless:!0}));let e=await fe.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function at(t){return await t.locator("body").ariaSnapshot()}async function lt(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var fe,_e,Ie,Rt,ct=Ve(()=>{"use strict";fe=null,_e=null,Ie=null,Rt=null;process.once("SIGTERM",()=>{wo().finally(()=>process.exit(0))});process.once("SIGINT",()=>{wo().finally(()=>process.exit(0))})});import{readFileSync as _r,existsSync as vo,writeFileSync as Zs,mkdirSync as ei,renameSync as ti,unlinkSync as oi}from"fs";import{join as ko,dirname as ri}from"path";import{homedir as ni}from"os";import{randomBytes as si}from"crypto";function Rr(){return ko(ni(),".mistflow","credentials.json")}function Nt(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function Er(){let t=Rr();if(!vo(t))return null;try{let e=JSON.parse(_r(t,"utf-8"));return typeof e.apiKey=="string"?{[ii]:e}:e}catch{return null}}function Le(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=Er();if(!e)return{ok:!1,reason:"missing"};let r=Nt(),o=e[r];return o&&typeof o.apiKey=="string"&&o.apiKey&&typeof o.orgId=="string"?{ok:!0,creds:o}:{ok:!1,reason:"missing"}}function xo(t){let e=Rr(),r=ri(e);vo(r)||ei(r,{recursive:!0});let o=Er()??{},s=Nt();o[s]=t;let i=ko(r,`.credentials.tmp.${si(8).toString("hex")}`);try{Zs(i,JSON.stringify(o,null,2)+`
|
|
23
|
+
`,{mode:384}),ti(i,e)}catch(n){try{oi(i)}catch{}throw n}}function Nr(){let t=Le();return t.ok?t.creds:null}function ne(){return Le().ok}function Re(t){let e=ko(t,"mistflow.json");if(!vo(e))return null;try{return JSON.parse(_r(e,"utf-8"))}catch{return null}}var ii,$e=Ve(()=>{"use strict";ii="https://api.mistflow.ai"});var Lr={};It(Lr,{MistflowApiError:()=>W,addDomain:()=>Co,checkAuth:()=>pi,checkAuthDetailed:()=>Mr,checkSubdomain:()=>jt,createDeployment:()=>mi,createProject:()=>pt,deleteEnvVar:()=>No,discoverDecisions:()=>hi,downloadSource:()=>yi,downloadSourceWithToken:()=>Ur,fetchDesignDirections:()=>Po,fetchModule:()=>$o,fetchPlanConversation:()=>Ot,fetchScaffold:()=>Uo,fetchStepContext:()=>Lo,forkTemplate:()=>qo,generatePlan:()=>Mt,getAuthHeaders:()=>Fe,getBaseUrl:()=>se,getDashboardUrl:()=>li,getDbCredentials:()=>gi,getDeployLogs:()=>Do,getDeploymentStatus:()=>ut,getProject:()=>ui,getProjectErrors:()=>jo,getSeedInfo:()=>Ao,getSiteUrl:()=>ai,getTemplate:()=>Fo,hasCredentialsOnDisk:()=>ne,hasLocalCredentials:()=>Or,listDeployments:()=>Je,listDomains:()=>Ee,listEnvVars:()=>Ro,markLocalSetupDone:()=>bi,modifyPlan:()=>Ut,pingBackend:()=>So,promotePreview:()=>Oo,redeployProject:()=>fi,removeDomain:()=>Io,rollbackDeployment:()=>Mo,shareProject:()=>Bo,uploadAndDeploy:()=>To,uploadQAResults:()=>_o,upsertEnvVar:()=>Eo,verifyDomain:()=>Lt});function se(){return Nt()}function ai(){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 li(){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 Fe(){let t=Le();if(!t.ok)throw new W("auth_missing","No Mistflow credentials found.",401);return ci(t.creds)}function ci(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":ge()}}function Ke(t){try{st(t.headers)}catch{}}async function So(){try{let t=await fetch(`${se()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Ke(t)}catch{}}async function jr(t,e,r,o){for(let s=0;s<2;s++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(i){let n=i instanceof Error&&i.name==="TimeoutError",a=i instanceof TypeError;if(o&&s===0&&(n||a)){console.error(`[api] Retrying ${t} after ${n?"timeout":"network error"}`);continue}throw i}throw new Error("fetchWithRetry: exhausted retries")}async function dt(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,o=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new W(r,o,t.status,e?.details);let s=t.status;return s===401?new W("auth_invalid",o,s):s===403?new W("permission_denied",o,s):s===404?new W("not_found",o,s):s===409?new W("conflict",o,s):s===422?new W("validation_error",o,s):s===429?new W("rate_limited",o,s):s>=500?new W("server_error",t.statusText||"Internal server error",s):new W("client_error",o,s)}async function G(t,e={}){let r=Fe(),{timeoutMs:o,idempotent:s,...i}=e,n=o??3e4,a=(i.method??"GET").toUpperCase(),l=s??(a==="GET"||a==="HEAD"),c;try{c=await jr(`${se()}${t}`,{...i,headers:{...r,...i.headers}},n,l)}catch(m){throw m instanceof Error&&m.name==="TimeoutError"?new W("network_error","Request timed out. Try again in a moment."):new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ke(c),!c.ok)throw await dt(c);return c.json()}function Or(){return Le().ok}async function pi(){return(await Mr()).ok}async function Mr(){if(Dt!==null&&Date.now()<Dr)return Dt?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Or())return{ok:!1,reason:"no_credentials"};try{return await G("/api/org"),Dt=!0,Dr=Date.now()+di,{ok:!0}}catch(t){if(Dt=null,!(t instanceof W))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function ui(t){return G(`/api/projects/${encodeURIComponent(t)}`)}async function jt(t){return G(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function pt(t,e,r="neon",o){return G("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e,db_provider:r,requested_subdomain:o})})}async function mi(t,e){return G("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function To(t,e,r="production",o,s,i,n){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=Le();if(!c.ok)throw new W("auth_missing","No Mistflow credentials found.",401);let m=c.creds,p=a(e),u=new Blob([p],{type:"application/gzip"}),w=new FormData;if(w.append("project_id",t),w.append("build",u,l(e)),r!=="production"&&w.append("environment",r),o&&w.append("admin_email",o),s&&w.append("schema_pushed","true"),i){let{existsSync:S}=await import("fs");if(S(i)){let f=a(i),A=new Blob([f],{type:"application/gzip"});w.append("source",A,"source.tar.gz")}}n&&w.append("git_commit_sha",n);let N;try{N=await fetch(`${se()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":ge()},body:w,signal:AbortSignal.timeout(3e5)})}catch{throw new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ke(N),!N.ok)throw await dt(N);let x=await N.json();return{...x,id:x.deployment_id}}async function ut(t,e){let r=e?.waitSeconds??0,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return G(`/api/deploy/${encodeURIComponent(t)}/status${o}`,r>0?{timeoutMs:s}:void 0)}async function Po(t){return G(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Ot(t,e){let r=e?.waitSeconds??20,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return G(`/api/plan/conversations/${encodeURIComponent(t)}${o}`,{timeoutMs:s})}async function Mt(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&(r.design_conversation_id=e.designConversationId),e?.designDirection&&(r.design_direction=e.designDirection);let o=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return G("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:o,idempotent:!1})}async function Ut(t,e){return G("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function hi(t){return G("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Co(t,e){return G(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function Ee(t){return G(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Lt(t,e){return G(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Io(t,e){return G(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function gi(t){return G(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Ao(t){try{return await G(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof W&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function _o(t,e){try{return await G(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(r){return console.error("[api] Failed to upload QA results:",r instanceof Error?r.message:r),null}}async function Ro(t){return G(`/api/projects/${encodeURIComponent(t)}/env`)}async function Eo(t,e,r,o){return G(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:r,category:o?.category??"custom",description:o?.description,setup_url:o?.setupUrl})})}async function No(t,e){return G(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Do(t){return G(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function jo(t,e="7d"){return G(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Je(t){return G(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function fi(t){return G(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Oo(t,e){let r=new URLSearchParams({preview_deployment_id:e});return G(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Mo(t){return G(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function yi(t,e){let r=Le();if(!r.ok)throw new W("auth_missing","Not authenticated.",401);let o=r.creds,s=await fetch(`${se()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${o.apiKey}`,"X-Mistflow-MCP-Version":ge()},signal:AbortSignal.timeout(12e4)});if(Ke(s),!s.ok)throw await dt(s);let{writeFileSync:i}=await import("fs"),n=Buffer.from(await s.arrayBuffer());i(e,n)}async function $t(t,e){let{timeoutMs:r,idempotent:o,...s}=e??{},i=r??3e4,n=(s.method??"GET").toUpperCase(),a=o??(n==="GET"||n==="HEAD"),l;try{l=await jr(`${se()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":ge()},...s},i,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new W("network_error","Request timed out. Try again in a moment."):new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ke(l),!l.ok)throw await dt(l);return l.json()}async function Uo(t="nextjs"){return $t(`/api/scaffold/${encodeURIComponent(t)}`)}async function Lo(t,e){return $t(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function $o(t,e,r,o){return $t(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:r,entity_plural:o})})}async function Fo(t){return $t(`/api/templates/${encodeURIComponent(t)}`)}async function qo(t){return G(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Ur(t,e,r){let o;try{o=await fetch(`${se()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":ge()},signal:AbortSignal.timeout(12e4)})}catch{throw new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ke(o),!o.ok)throw o.status===401?new W("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",o.status):await dt(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(r,i)}async function bi(t){await G(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Bo(t,e){return G(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}var W,Dt,Dr,di,le=Ve(()=>{"use strict";$e();it();W=class extends Error{constructor(r,o,s,i){super(o);this.code=r;this.statusCode=s;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"}};Dt=null,Dr=0,di=300*1e3});var gt={};It(gt,{emptyState:()=>ht,fetchRemoteState:()=>Ei,fuzzyMatch:()=>Di,getLocalStatePath:()=>Ho,readLocalState:()=>Ri,syncRemoteState:()=>Ni,writeLocalState:()=>mt});import{existsSync as Hr,readFileSync as Ii,writeFileSync as Ai,mkdirSync as _i}from"fs";import{join as Wr}from"path";function Ho(t){return Wr(t,".mistflow","state.json")}function Ri(t){let e=Ho(t);if(!Hr(e))return null;try{return JSON.parse(Ii(e,"utf-8"))}catch{return null}}function mt(t,e){let r=Wr(t,".mistflow");Hr(r)||_i(r,{recursive:!0}),Ai(Ho(t),JSON.stringify(e,null,2)+`
|
|
24
|
+
`)}function ht(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Ei(t){let e;try{e=Fe()}catch{return null}try{let r=await fetch(`${se()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":ge()}});try{st(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function Ni(t,e){let r;try{r=Fe()}catch{return!1}try{let o=await fetch(`${se()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":ge()},body:JSON.stringify(e)});try{st(o.headers)}catch{}return o.ok}catch{return!1}}function Di(t,e){let r=t.toLowerCase(),o=e.toLowerCase();return o.includes(r)||r.includes(o)?!0:r.split(/\s+/).some(i=>i.length>=3&&o.includes(i))}var qe=Ve(()=>{"use strict";le();it()});var Wo={};It(Wo,{ensureBackendRegistered:()=>Fi,ensureShadcnComponents:()=>qi});import{existsSync as Vr,readFileSync as ji,writeFileSync as Oi}from"fs";import{join as Ft}from"path";import{spawn as Mi}from"child_process";function Ui(t,e,r,o,s){return new Promise(i=>{let n=Mi(t,e,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:o,...s?{env:{...process.env,...s}}:{}}),a="",l="";n.stdout?.on("data",c=>{a+=c.toString()}),n.stderr?.on("data",c=>{l+=c.toString()}),n.on("close",c=>i({success:c===0,stdout:a,stderr:l})),n.on("error",c=>i({success:!1,stdout:a,stderr:l+c.message}))})}function Li(t){let e=Ft(t,"mistflow.json");if(!Vr(e))return null;try{return JSON.parse(ji(e,"utf-8"))}catch{return null}}function $i(t,e){Oi(Ft(t,"mistflow.json"),JSON.stringify(e,null,2))}async function Gr(t,e){try{let r=e.features,o=e.steps,s={plan:e};Array.isArray(r)&&r.length>0&&(s.features=r.map(i=>i.name)),Array.isArray(o)&&o.length>0&&(s.provenance=o.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(`${se()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify(s)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function Fi(t,e={}){let r=Li(t);if(r){if(!ne())return r.projectId;if(!r.projectId)try{let s=r.plan?.requestedSubdomain,i=await pt(r.name,void 0,r.dbProvider??"neon",s);return r.projectId=i.id,$i(t,r),mt(t,ht(i.id,r.name)),r.plan&&await Gr(i.id,r.plan),console.error(`[self-heal] registered project ${i.id.slice(0,8)} with backend`),i.id}catch(o){console.error("[self-heal] createProject failed:",o instanceof Error?o.message:String(o));return}return e.forceSync&&r.plan&&r.projectId&&await Gr(r.projectId,r.plan),r.projectId}}async function qi(t,e){let r=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],o=e&&e.length>0?e:r,s=Ft(t,"components","ui"),i=[],n=[];for(let c of o)Vr(Ft(s,`${c}.tsx`))?i.push(c):n.push(c);if(n.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Ui("npx",["--yes","shadcn@latest","add","-y","-o",...n],t,18e4,a);return l.success?{installed:n,alreadyPresent:i}:{installed:[],alreadyPresent:i,failed:`shadcn add failed for: ${n.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Go=Ve(()=>{"use strict";le();qe()});import{Server as rd}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as nd}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as sd,ListToolsRequestSchema as id}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as ad}from"zod-to-json-schema";var Os="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.",Ms='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"`.',Us="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.",Ls="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.",$s='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.',Fs="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.",qs="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.",Bs='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.',zs="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST ask the user and WAIT for their actual answer before submitting anything back. Use your host's native structured-question UI: `AskUserQuestion` in Claude Code, quick pick in Cursor, `request_user_input` in OpenAI Codex (available in Plan mode \u2014 if Codex returns 'request_user_input is unavailable in <mode> mode', you are in default mode; stop your turn and print the questions as a numbered chat message, then wait for the user's next message). For any host that does not expose a structured question tool, stop your turn immediately, print the questions verbatim as a numbered list with all options visible, and wait \u2014 the user's next message is the answer. The rule across every host: you never submit answers to `mist_plan` in the same turn you received the questions. That is always wrong, regardless of how obvious the `recommended` choice looks, regardless of whether you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode. The `recommended` field is a hint FOR the user, not permission FOR you. Anti-example from a real transcript: the host AI received 7 discovery questions, wrote 'I'll lock in the defaults with Azure OpenAI as the only override,' submitted answers the user never saw, and the user ended up with a plan they didn't choose. That behavior is a regression bug. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to perform that submission step; that is your job.",mr="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).",hr="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'integrations' browses the curated integration blueprint catalog (pass integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",gr="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.",fr="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.",yr="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).",br="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 wr(){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(Bs),t.push(""),t.push(Os),t.push(""),t.push(Ms),t.push(""),t.push(Us),t.push(""),t.push(Ls),t.push(""),t.push(zs),t.push(""),t.push(Fs),t.push(""),t.push("New app workflow:"),t.push("1. Choose destination: if the user didn't already give a path, ask whether to scaffold in the current folder or a new subfolder here. Resolve the absolute path before mist_init."),t.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via your host\'s native question tool (AskUserQuestion in Claude Code / request_user_input in Codex Plan mode / quick pick in Cursor / stop-and-wait for hosts without one \u2014 see RULE_SENTINEL_HANDLING), collect the user\'s actual answers, then submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick via mist_plan with `designConversationId` + `designDirection` (NOT `conversationId` alone).'),t.push("3. Mockup (optional, recommended): call mist_mockup with the planId \u2014 returns a wireframe prompt. Write the HTML to the returned path, open it for the user, wait for approval. Iterate with { feedback }, lock with { approved: true }."),t.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),t.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),t.push("6. Implement: mist_implement runs one plan step at a time and auto-marks the prior step complete. Call repeatedly until all steps are done."),t.push("7. Build: mist_build { projectPath } starts; poll with { jobId }. On failure, the response has `missingModules[]` \u2014 chain mist_install with those modules then mist_build again without asking."),t.push("8. Deploy: mist_deploy { projectPath } starts tar + upload; poll with { action: 'status', deploymentId }. On complete, response has `qaRequired: true` and a `url` \u2014 do NOT surface the URL to the user until mist_qa passes. Subsequent actions: 'promote' (staging \u2192 prod), 'rollback' (revert to a specific deploymentId)."),t.push("9. QA: mist_qa { projectPath } drives Playwright in-process against the live URL \u2014 single synchronous call (~20\u201345s), returns pass/fail and screenshots inline. Only surface the deploy URL to the user after mist_qa returns status: 'pass'."),t.push(""),t.push($s),t.push(""),t.push(qs),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
|
+
`)}it();function d(t,e=!1){let r=t;try{let o=Cr();o&&(r=t+o)}catch{}return{content:[{type:"text",text:r}],isError:e}}function Ae(t){return d(`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,13 @@ 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
|
|
34
|
+
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Ar(t,e){try{let{getPage:r,takeScreenshot:o}=await Promise.resolve().then(()=>(ct(),Et)),s=await r();await s.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await s.waitForLoadState("networkidle").catch(()=>{});let i=await o(s,!1);return{content:[{type:"text",text:e},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}catch{return d(e)}}import{z as zo}from"zod";import{platform as wi}from"os";import{execFile as $r}from"child_process";le();$e();var vi=zo.object({apiKey:zo.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:zo.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 ki(t){return"error"in t}function qr(t){return new Promise(e=>setTimeout(e,t))}function xi(t){return new Promise(e=>{let r=wi();r==="win32"?$r("cmd.exe",["/c","start","",t],o=>{o&&console.error("Could not open browser:",o.message),e(!o)}):$r(r==="darwin"?"open":"xdg-open",[t],s=>{s&&console.error("Could not open browser:",s.message),e(!s)}),setTimeout(()=>e(!1),5e3)})}var Si={fetch:globalThis.fetch,openBrowser:xi,sleep:qr};async function Fr(t,e,r,o){let s=r,i=o.sleep??qr;for(let n=0;n<e;n++){await i(s);let a;try{let c=await o.fetch(`${se()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!c.ok)continue;a=await c.json()}catch{continue}if(ki(a))switch(a.error){case"authorization_pending":continue;case"slow_down":s+=5e3;continue;case"expired_token":return d("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return d("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return d("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=a.email||a.org_name||a.org_slug;return xo({apiKey:a.api_key,apiKeyId:a.api_key_id,apiKeyName:a.api_key_name,orgId:a.org_id,orgSlug:a.org_slug,email:a.email}),d(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function Ti(t,e=Si){let r=t;if(r?.apiKey)try{let n=await e.fetch(`${se()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!n.ok)return d("Invalid API key. Check the key and try again.",!0);let a=await n.json();return xo({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),d(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let n=await Fr(r.deviceCode,6,5e3,e);return n||d(JSON.stringify({status:"pending",deviceCode:r.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let o;try{let n=await e.fetch(`${se()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);o=await n.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let s=`${o.verification_uri}?code=${o.user_code}`;console.error(`
|
|
35
35
|
Sign in at: ${s}
|
|
36
36
|
Your code: ${o.user_code}
|
|
37
|
-
`);try{await
|
|
38
|
-
`)){let s=o.trim();if(!s||s.startsWith("#"))continue;let i=s.indexOf("=");if(i>0){let n=s.slice(0,i).trim(),a=s.slice(i+1).trim();a&&a!=='""'&&a!=="''"&&
|
|
39
|
-
`),nextSteps:
|
|
40
|
-
`),s.projectId&&Promise.resolve().then(()=>(
|
|
41
|
-
${i.map(n=>` \u2022 ${n}`).join(`
|
|
42
|
-
`)}`);return o.join(`
|
|
43
|
-
|
|
44
|
-
`)}function da(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function gn(e){return(e?ir(e):lt).map(r=>{let o=sr[r.id];return{id:r.id,slug:da(r.title),title:r.title,category:r.category,description:o?.description??"",tags:o?.tags??[],theme:o?.theme??"dark",colors:o?.colors??[],style:o?.style??""}})}function fn(e,t){return[]}kt();var ar={"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"}},ct=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
|
|
37
|
+
`);try{await e.openBrowser(s)}catch{}let i=await Fr(o.device_code,6,5e3,e);return i||d(JSON.stringify({status:"pending",deviceCode:o.device_code,signInUrl:s,userCode:o.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+o.device_code+"' to check if they approved."}))}var Br={name:"mist_setup",description:mr,inputSchema:vi,handler:t=>Ti(t)};import{z as ce}from"zod";import{resolve as qt}from"path";import{existsSync as Bt,readFileSync as zt}from"fs";import{join as Ht}from"path";import{z as Ne}from"zod";import{resolve as Bi,join as Kr}from"path";import{existsSync as zi,readFileSync as Jr,writeFileSync as Hi}from"fs";import{existsSync as Pi,readFileSync as Ci}from"fs";function zr(t){let e=new Set;if(!Pi(t))return e;let r=Ci(t,"utf-8");for(let o of r.split(`
|
|
38
|
+
`)){let s=o.trim();if(!s||s.startsWith("#"))continue;let i=s.indexOf("=");if(i>0){let n=s.slice(0,i).trim(),a=s.slice(i+1).trim();a&&a!=='""'&&a!=="''"&&e.add(n)}}return e}var Wi=Ne.object({action:Ne.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:Ne.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:Ne.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:Ne.object({key:Ne.string(),description:Ne.string().optional(),setupUrl:Ne.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),Yr={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:Wi,handler:async t=>{let e=t,r=Bi(e.projectPath??process.cwd()),o=Kr(r,"mistflow.json");if(!zi(o))return Ae(r);let s;try{s=JSON.parse(Jr(o,"utf-8"))}catch{return d("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!s.projectId)try{let{ensureBackendRegistered:S}=await Promise.resolve().then(()=>(Go(),Wo));await S(r)&&(s=JSON.parse(Jr(o,"utf-8")))}catch{}let a=s.plan,l=a?.steps?.filter(S=>S.status==="completed").length??0,c=a?.steps?.length??0,m=zr(Kr(r,".env.local")),p=s.env?.required?Object.entries(s.env.required).map(([S,f])=>({name:S,description:f?.description,configured:m.has(S)})):[];s.projectId&&Promise.resolve().then(()=>(qe(),gt)).then(({fetchRemoteState:S})=>S(s.projectId)).catch(()=>{});let u=[`Project: ${s.name}`];if(a){u.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let S of a.steps){let f=S.status==="completed"?"\u2713":S.status==="in_progress"?"\u2192":" ";u.push(` [${f}] ${S.number}. ${S.name}`)}}let w=p.filter(S=>!S.configured);w.length>0&&u.push(`Missing env vars: ${w.map(S=>S.name).join(", ")}`),s.deploy?.url?u.push(`Deployed: ${s.deploy.url} (${s.deploy.count??0} deploys)`):u.push("Not deployed yet");let N=[],x=a?.steps?.find(S=>S.status!=="completed");return x?N.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${x.number} (${x.name}).`):a&&l===c&&(s.deploy?.url||N.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),w.length>0&&N.push(`Missing env vars in .env.local: ${w.map(S=>S.name).join(", ")}`),d(JSON.stringify({name:s.name,projectId:s.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:c,completedSteps:l,steps:a.steps}:null,envStatus:p,deploy:s.deploy??null,contextMessage:u.join(`
|
|
39
|
+
`),nextSteps:N}))}let i=[];if(e.completedStep!==void 0){let a=s.plan;if(a?.steps){let l=a.steps.findIndex(c=>c.number===e.completedStep);if(l===-1)return d(`Step ${e.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",i.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(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},i.push(`Added required env var: ${e.addEnvVar.key}`)),Hi(o,JSON.stringify(s,null,2)+`
|
|
40
|
+
`),s.projectId&&Promise.resolve().then(()=>(qe(),gt)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(r);c&&await l(s.projectId,c)}).catch(()=>{});let n=[];if(e.completedStep!==void 0){let l=s.plan?.steps?.find(c=>c.status!=="completed");l?n.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):n.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&&(n.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&n.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),d(JSON.stringify({updated:!0,changes:i,message:i.length>0?`Project state saved. ${i.join(". ")}.`:"No changes made.",nextSteps:n.length>0?n:void 0}))}};le();it();var Vo={"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
|
|
45
41
|
|
|
46
42
|
### File Structure
|
|
47
43
|
\`\`\`
|
|
@@ -1461,16 +1457,16 @@ export function ImageGenerator() {
|
|
|
1461
1457
|
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
1458
|
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
1459
|
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
|
|
1460
|
+
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 Gi(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Qe(t){let e=Ye.find(o=>o.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Ye.find(o=>{let s=o.name.toLowerCase().replace(/[^a-z0-9]/g,"");return s===r||s.includes(r)||r.includes(s)})}function Xe(t){return Vo[t]}function Ko(t){return t?Ye.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Ye}function Qr(t){let e=t??Ye,r={};for(let s of e){r[s.category]||(r[s.category]=[]);let i=Vo[s.id],n=i?` \u2014 ${i.description}`:"",a=i?.packages.length?` (${i.packages.join(", ")})`:"";r[s.category].push(`${s.id} \u2014 "${s.name}"${n}${a}`)}let o=[];for(let[s,i]of Object.entries(r))o.push(`**${s}**:
|
|
1465
1461
|
${i.map(n=>` - ${n}`).join(`
|
|
1466
1462
|
`)}`);return o.join(`
|
|
1467
1463
|
|
|
1468
|
-
`)}function
|
|
1464
|
+
`)}function Xr(t){return(t?Ko(t):Ye).map(r=>{let o=Vo[r.id];return{id:r.id,slug:Gi(r.name),name:r.name,category:r.category,description:o?.description??"",tags:o?.tags??[],envVars:o?.envVars??[],docsUrl:o?.docsUrl??"",packages:o?.packages??[],difficulty:o?.difficulty??"medium"}})}var Vi=ce.object({action:ce.enum(["get","update","share","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:ce.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:ce.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:ce.object({key:ce.string(),description:ce.string().optional(),setupUrl:ce.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:ce.string().optional().describe("(share) Short description of what this template builds"),category:ce.string().optional().describe("(integrations) Filter integrations by category"),integrationId:ce.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:ce.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:ce.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),Zr={name:"mist_project",description:hr,inputSchema:Vi,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!ne())return d("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return Yr.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let o=qt(e.projectPath??process.cwd()),s=Ht(o,"mistflow.json");if(!Bt(s))return Ae(o);let i;try{i=JSON.parse(zt(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first to register it.",!0);try{let a=await Bo(n,{isTemplate:!0,description:e.templateDescription});return d(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
|
|
1469
1465
|
|
|
1470
1466
|
Anyone can fork it: ${a.share_url}
|
|
1471
1467
|
|
|
1472
1468
|
Others can use it in their AI editor:
|
|
1473
|
-
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return d(l,!0)}}case"landing-designs":{if(t.presetId){let n=to(t.presetId);if(!n)return d(`Preset '${t.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let a=mn(t.presetId);return d(JSON.stringify({preset:{id:n.id,title:n.title,category:n.category,description:a?.description??"",style:a?.style??"",theme:a?.theme??"dark",colors:a?.colors??[],tags:a?.tags??[],promptLength:n.prompt.length},message:`Landing design "${n.title}" (${n.category}) \u2014 ${a?.description??""}. To use it, pass landingDesign="${n.id}" when calling mist_plan.`}))}let o=gn(t.category??void 0),s=ir(t.category),i=hn(s);return d(JSON.stringify({count:o.length,presets:o.map(n=>({id:n.id,title:n.title,category:n.category,description:n.description,style:n.style,theme:n.theme,colors:n.colors})),formatted:i,message:`${o.length} landing designs available.${t.category?` Filtered by: ${t.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 ${st()}/designs?tab=landing-designs.`}))}case"integrations":{if(t.integrationId){let n=dt(t.integrationId);if(!n)return d(`Integration '${t.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=pt(n.id);return d(JSON.stringify({integration:{id:n.id,name:n.name,category:n.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${n.name}" (${n.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 o=bn(t.category??void 0),s=lr(t.category??void 0),i=yn(s);return d(JSON.stringify({count:o.length,integrations:o.map(n=>({id:n.id,name:n.name,category:n.category,description:n.description,packages:n.packages,difficulty:n.difficulty,envVars:n.envVars.map(a=>a.key)})),formatted:i,message:`${o.length} integration blueprints available.${t.category?` Filtered by: ${t.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let o=oo(t.projectPath??process.cwd()),s=so(o,"mistflow.json");if(!ro(s))return $e(o);let i;try{i=JSON.parse(no(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);try{let a=await Go(n,t.period??"7d");return a.total===0?d(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):d(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return d(l,!0)}}case"logs":{let o=oo(t.projectPath??process.cwd()),s=so(o,"mistflow.json");if(!ro(s))return $e(o);let i;try{i=JSON.parse(no(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);let a=t.deploymentId;if(!a)try{let l=await at(n);if(l.length===0)return d("No deployments found for this project.",!0);a=l[0].id}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return d(c,!0)}try{let[l,c]=await Promise.all([Wo(a),It(a)]),h=l.filter(u=>u.level==="error"),m=l.filter(u=>u.level==="warn");return d(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:h.length,warnCount:m.length,logs:l.map(u=>({time:u.timestamp,level:u.level,phase:u.phase,message:u.message})),message:c.status==="failed"?`Deployment failed. ${h.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${h.length} errors, ${m.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return d(c,!0)}}case"deployments":{let o=oo(t.projectPath??process.cwd()),s=so(o,"mistflow.json");if(!ro(s))return $e(o);let i;try{i=JSON.parse(no(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);try{let a=await at(n);return d(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return d(l,!0)}}case"version":{_o().backendSignalReceived||await Oo();let o=_o(),s=o.severity==="none",i={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return d(JSON.stringify({current:o.current,latest:o.latest||"unknown",minSupported:o.minSupported||"unknown",severity:o.severity,upToDate:s,upgradeCmd:o.upgradeCmd,changelogUrl:o.changelogUrl,backendSignalReceived:o.backendSignalReceived,message:o.backendSignalReceived?`Mistflow MCP ${o.current} (${i[o.severity]??o.severity}). Latest: ${o.latest}.${s?"":` Run \`${o.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${o.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return d(`Unknown action: ${t.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Ze}from"zod";Tt();var ma=Ze.object({action:Ze.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:Ze.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Ze.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:Ze.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:Ze.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Ze.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),vn={name:"mist_browser",description:Rr,inputSchema:ma,handler:async e=>{let t=e,r=await Ro();if(t.action==="navigate"){if(!t.url)return d("URL is required for 'navigate'.",!0);let i=[],n=c=>{c.type()==="error"&&i.push(c.text())};r.on("console",n),await r.goto(t.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=c=>a.push(c.message);if(r.on("pageerror",l),await r.waitForTimeout(500),r.removeListener("console",n),r.removeListener("pageerror",l),i.length>0||a.length>0){let c=await xt(r),h=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(t.includeScreenshot){let m=await St(r);h.push({type:"image",data:m.toString("base64"),mimeType:"image/png"})}return{content:h}}}else if(t.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(t.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(t.action==="click"){if(!t.selector)return d("Selector is required for 'click'.",!0);await r.click(t.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(t.action==="type"){if(!t.selector)return d("Selector is required for 'type'.",!0);if(!t.value)return d("Value is required for 'type'.",!0);await r.type(t.selector,t.value,{delay:50})}else if(t.action==="fill"){if(!t.selector)return d("Selector is required for 'fill'.",!0);if(!t.value)return d("Value is required for 'fill'.",!0);await r.fill(t.selector,t.value)}else if(t.action==="select_option"){if(!t.selector)return d("Selector is required for 'select_option'.",!0);if(!t.value)return d("Value is required for 'select_option'.",!0);await r.selectOption(t.selector,t.value)}else if(t.action==="hover"){if(!t.selector)return d("Selector is required for 'hover'.",!0);await r.hover(t.selector,{timeout:1e4})}else if(t.action==="press_key"){if(!t.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(t.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(t.action==="screenshot"){t.url&&(await r.goto(t.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let i;if(t.selector){let n=await r.$(t.selector);if(!n)return d(`Element not found: ${t.selector}`,!0);i=await n.screenshot({type:"png"})}else i=await St(r,t.fullPage);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),message:`Screenshot captured (${t.fullPage?"full page":"viewport"})`})},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}else if(t.action==="snapshot"){let i=await xt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:i})}]}}let o=await xt(r),s=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}];if(t.includeScreenshot){let i=await St(r);s.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:s}}};import{z as kn}from"zod";var xn=`# Mistflow MCP tool reference
|
|
1469
|
+
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return d(l,!0)}}case"integrations":{if(e.integrationId){let n=Qe(e.integrationId);if(!n)return d(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=Xe(n.id);return d(JSON.stringify({integration:{id:n.id,name:n.name,category:n.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${n.name}" (${n.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 o=Xr(e.category??void 0),s=Ko(e.category??void 0),i=Qr(s);return d(JSON.stringify({count:o.length,integrations:o.map(n=>({id:n.id,name:n.name,category:n.category,description:n.description,packages:n.packages,difficulty:n.difficulty,envVars:n.envVars.map(a=>a.key)})),formatted:i,message:`${o.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let o=qt(e.projectPath??process.cwd()),s=Ht(o,"mistflow.json");if(!Bt(s))return Ae(o);let i;try{i=JSON.parse(zt(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);try{let a=await jo(n,e.period??"7d");return a.total===0?d(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):d(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return d(l,!0)}}case"logs":{let o=qt(e.projectPath??process.cwd()),s=Ht(o,"mistflow.json");if(!Bt(s))return Ae(o);let i;try{i=JSON.parse(zt(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await Je(n);if(l.length===0)return d("No deployments found for this project.",!0);a=l[0].id}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return d(c,!0)}try{let[l,c]=await Promise.all([Do(a),ut(a)]),m=l.filter(u=>u.level==="error"),p=l.filter(u=>u.level==="warn");return d(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:m.length,warnCount:p.length,logs:l.map(u=>({time:u.timestamp,level:u.level,phase:u.phase,message:u.message})),message:c.status==="failed"?`Deployment failed. ${m.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${m.length} errors, ${p.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return d(c,!0)}}case"deployments":{let o=qt(e.projectPath??process.cwd()),s=Ht(o,"mistflow.json");if(!Bt(s))return Ae(o);let i;try{i=JSON.parse(zt(s,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return d("No project ID found. Deploy the project first.",!0);try{let a=await Je(n);return d(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return d(l,!0)}}case"version":{yo().backendSignalReceived||await So();let o=yo(),s=o.severity==="none",i={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return d(JSON.stringify({current:o.current,latest:o.latest||"unknown",minSupported:o.minSupported||"unknown",severity:o.severity,upToDate:s,upgradeCmd:o.upgradeCmd,changelogUrl:o.changelogUrl,backendSignalReceived:o.backendSignalReceived,message:o.backendSignalReceived?`Mistflow MCP ${o.current} (${i[o.severity]??o.severity}). Latest: ${o.latest}.${s?"":` Run \`${o.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${o.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return d(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Be}from"zod";ct();var Ki=Be.object({action:Be.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:Be.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Be.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:Be.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:Be.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Be.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),en={name:"mist_browser",description:gr,inputSchema:Ki,handler:async t=>{let e=t,r=await bo();if(e.action==="navigate"){if(!e.url)return d("URL is required for 'navigate'.",!0);let i=[],n=c=>{c.type()==="error"&&i.push(c.text())};r.on("console",n),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=c=>a.push(c.message);if(r.on("pageerror",l),await r.waitForTimeout(500),r.removeListener("console",n),r.removeListener("pageerror",l),i.length>0||a.length>0){let c=await at(r),m=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let p=await lt(r);m.push({type:"image",data:p.toString("base64"),mimeType:"image/png"})}return{content:m}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return d("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return d("Selector is required for 'type'.",!0);if(!e.value)return d("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return d("Selector is required for 'fill'.",!0);if(!e.value)return d("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return d("Selector is required for 'select_option'.",!0);if(!e.value)return d("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return d("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let i;if(e.selector){let n=await r.$(e.selector);if(!n)return d(`Element not found: ${e.selector}`,!0);i=await n.screenshot({type:"png"})}else i=await lt(r,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let i=await at(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:i})}]}}let o=await at(r),s=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}];if(e.includeScreenshot){let i=await lt(r);s.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:s}}};import{z as tn}from"zod";var on=`# Mistflow MCP tool reference
|
|
1474
1470
|
|
|
1475
1471
|
Every capability is an MCP tool. There is no companion CLI. Long-running tools
|
|
1476
1472
|
(install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
|
|
@@ -1533,8 +1529,7 @@ returned \`auth_missing\` / \`auth_revoked\`. Do NOT call in response to 500s,
|
|
|
1533
1529
|
### \`mist_project({ action: "get" })\`
|
|
1534
1530
|
Load plan progress, env vars, deploy info. Call before editing an existing
|
|
1535
1531
|
Mistflow project so you understand its shape. Other actions: \`update\`,
|
|
1536
|
-
\`share\`, \`
|
|
1537
|
-
\`deployments\`, \`version\`.
|
|
1532
|
+
\`share\`, \`integrations\`, \`errors\`, \`logs\`, \`deployments\`, \`version\`.
|
|
1538
1533
|
|
|
1539
1534
|
### \`mist_plan({ description })\`
|
|
1540
1535
|
Start a new plan. Pass the user's description EXACTLY as written \u2014 do NOT
|
|
@@ -1778,14 +1773,14 @@ is cheaper than building the wrong thing and iterating.
|
|
|
1778
1773
|
|
|
1779
1774
|
mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
|
|
1780
1775
|
mist_deploy({ action: "status", deploymentId }) # poll
|
|
1781
|
-
`,
|
|
1776
|
+
`,rn={name:"mist_help",description:fr,inputSchema:tn.object({command:tn.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return d(on);let r=e.startsWith("mist_")?e:`mist_${e}`,o=on.split(`
|
|
1782
1777
|
`),s=new RegExp(`^### \`${r}`),i=-1,n=o.length;for(let a=0;a<o.length;a++)if(s.test(o[a]))i=a;else if(i>=0&&o[a].startsWith("### ")){n=a;break}else if(i>=0&&o[a].startsWith("## ")&&a>i){n=a;break}return i<0?d(`No tool named '${r}' found. Call mist_help with no args to see the full catalog.`,!0):d(o.slice(i,n).join(`
|
|
1783
|
-
`).trim())}};import{existsSync as
|
|
1784
|
-
**${i.name}** \u2014 fields: ${i.fields.map(n=>`${n.name} (${n.type})`).join(", ")}`),o.push("```json"),o.push(JSON.stringify(i.sampleData,null,2)),o.push("```");o.push("")}}o.push("## Navigation"),o.push(`**Style**: ${
|
|
1785
|
-
`)}function
|
|
1786
|
-
${s.message}`})}),r.on("close",s=>{
|
|
1787
|
-
Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}`:void 0,enum:u,enumNames:u,...n.recommended&&
|
|
1788
|
-
`)}function
|
|
1778
|
+
`).trim())}};import{existsSync as Wt,mkdirSync as an,readFileSync as ln,readdirSync as cn,writeFileSync as Ji}from"fs";import{join as De,resolve as Yi}from"path";import{homedir as Yo}from"os";import{z as ft}from"zod";function Ze(t){return t.entity??t.name??"Unknown"}function et(t){return typeof t=="string"?t:t.name}function Jo(t){return typeof t=="string"?"text":t.type}function nn(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(s=>{let i={};for(let[n,a]of Object.entries(s))i[n]=a==null?"":String(a);return i});let r=t.fields||[],o=[];for(let s=0;s<3;s++){let i={};for(let n of r)i[et(n)]=Qi(et(n),Jo(n),Ze(t),s);o.push(i)}return o}function Qi(t,e,r,o){let s=t.toLowerCase(),i=(e||"text").toLowerCase();return s==="name"||s==="title"?[`${r} Alpha`,`${r} Beta`,`${r} Gamma`][o]:s==="email"?["alice@example.com","bob@example.com","carol@example.com"][o]:s==="status"?["Active","Pending","Completed"][o]:s==="priority"?["High","Medium","Low"][o]:s.includes("date")||i==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][o]:s.includes("price")||s.includes("amount")||s.includes("cost")?["$29","$49","$99"][o]:s.includes("count")||s.includes("quantity")||i==="number"||i==="integer"?["12","34","56"][o]:i==="boolean"||i==="bool"?["Yes","No","Yes"][o]:s.includes("description")||i==="textarea"?["Brief description here","Another example entry","Third sample item"][o]:`Sample ${o+1}`}function Xi(t){let e=t.dataModel??[],r=t.pages??[],o=t.design??{},s=r.map(p=>({label:p.name??p.path??"Page",route:p.path??p.route??"/"})),i=[],n=e.slice(0,3).map(p=>({name:Ze(p),fields:(p.fields||[]).map(u=>({name:et(u),type:Jo(u)})),sampleData:nn(p)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(p=>Ze(p)).join(", ")}`),a.push("RECENT: Latest activity or items"),i.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(p=>Ze(p)).join(", ")} with key metrics.`,informationHierarchy:a,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:n});let l=e[0];if(l){let p=Ze(l),u=p.toLowerCase().endsWith("s")?p:`${p}s`;i.push({name:`${p} List`,type:"detail",route:`/${u.toLowerCase()}`,purpose:`Browse, search, and manage ${u.toLowerCase()}. Create new ${p.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${u}" title + "Add ${p}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(w=>et(w)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${u.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${u.toLowerCase()} matching..." with clear filter`],entities:[{name:p,fields:(l.fields||[]).map(w=>({name:et(w),type:Jo(w)})),sampleData:nn(l)}]})}t.steps.some(p=>{let u=`${p.name??p.title??""} ${p.description??""}`.toLowerCase();return u.includes("landing")||u.includes("hero")||u.includes("marketing")||u.includes("homepage")})&&i.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let m=[];for(let p of e.slice(0,3)){let u=Ze(p);(p.fields||[]).find(N=>{let x=et(N).toLowerCase();return x==="name"||x==="title"})&&m.push(`What if a ${u.toLowerCase()}'s name is 47 characters? Does the layout break?`),m.push(`What if there are 0 ${u.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&m.push("What does a brand-new user see? (no data, no setup)"),m.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:i,navigation:{style:t.navStyle??"sidebar",items:s},primaryAction:t.primaryAction??null,designDirection:{tone:o.tone??"professional",accentColor:o.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:o.fonts??{heading:"Inter",body:"Inter"}},edgeCases:m}}function Zi(t,e,r){let o=[];o.push(`# Wireframe sketch for ${t.appName}`),o.push(""),o.push(`**${t.appName}** \u2014 ${t.summary}`),o.push(""),e&&(o.push("## Feedback to apply"),o.push(e),o.push("")),o.push("## Design principles"),o.push(""),o.push("Apply these when deciding layout and hierarchy:"),o.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."),o.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),o.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."),o.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),o.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),o.push(""),o.push("## Wireframe rules (strict)"),o.push(""),o.push(`Write a **single self-contained HTML file** saved to \`${r}\`.`),o.push(""),o.push("The wireframe must:"),o.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),o.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),o.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),o.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),o.push("- Include **HTML comments** explaining design decisions"),o.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),o.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),o.push("- Include a small header bar showing: screen name tabs + the design direction summary"),o.push(""),o.push("The wireframe must NOT:"),o.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),o.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),o.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),o.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),o.push(""),o.push("## Screens to wireframe"),o.push("");for(let s of t.screens){o.push(`### ${s.name} (\`${s.route}\`)`),o.push(`**Purpose**: ${s.purpose}`),o.push(""),o.push("**Information hierarchy** (render in this order, top to bottom):");for(let i of s.informationHierarchy)o.push(`- ${i}`);o.push(""),o.push("**Interaction states** (add HTML comments for non-visible states):");for(let i of s.interactionStates)o.push(`- ${i}`);if(o.push(""),s.entities.length>0){o.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let i of s.entities)o.push(`
|
|
1779
|
+
**${i.name}** \u2014 fields: ${i.fields.map(n=>`${n.name} (${n.type})`).join(", ")}`),o.push("```json"),o.push(JSON.stringify(i.sampleData,null,2)),o.push("```");o.push("")}}o.push("## Navigation"),o.push(`**Style**: ${t.navigation.style} (use this layout)`),o.push("**Items**:");for(let s of t.navigation.items)o.push(`- ${s.label} \u2192 \`${s.route}\``);if(o.push(""),t.primaryAction&&(o.push("## Primary action (this drives the layout)"),o.push(`- **Action**: ${t.primaryAction.action}`),o.push(`- **Flow**: ${t.primaryAction.flow}`),o.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),o.push(""),o.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."),o.push("")),t.edgeCases.length>0){o.push("## Edge cases to consider"),o.push("Add HTML comments in the wireframe where these matter:");for(let s of t.edgeCases)o.push(`- ${s}`);o.push("")}return o.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),o.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.`),o.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),o.push(""),o.push("## After writing the wireframe"),o.push(`1. Write the file to \`${r}\``),o.push(`2. Open it for the user: \`open "${r}"\``),o.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."`),o.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),o.join(`
|
|
1780
|
+
`)}function dn(t){return De(Yo(),".mistflow","mockup-state",`${t}.json`)}function ea(t){let e=dn(t);if(!Wt(e))return null;try{return JSON.parse(ln(e,"utf-8"))}catch{return null}}function sn(t,e){let r=De(Yo(),".mistflow","mockup-state");an(r,{recursive:!0}),Ji(dn(t),JSON.stringify(e,null,2))}var ta=ft.object({planId:ft.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:ft.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:ft.string().optional().describe("User feedback to apply to the next iteration."),approved:ft.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."}),pn={name:"mist_mockup",description:br,inputSchema:ta,handler:async t=>{let e=t,{planId:r,feedback:o,approved:s}=e,i=Yi(e.projectPath??process.cwd()),n=De(Yo(),".mistflow","plans",`${r}.json`);if(!Wt(n))return d(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(ln(n,"utf-8"))}catch{return d("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return d("Plan data is empty. Call mist_plan again.",!0);let c=ea(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let m=De(i,".mistflow","mockups");an(m,{recursive:!0});let p=`mockup-${r}.html`,u=De(m,p);if(s){c.approved=!0,sn(r,c);let f=Wt(m)?cn(m).filter(A=>A.endsWith(".html")).map(A=>De(".mistflow","mockups",A)):[];return d(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:f,nextAction:`Call mist_init with planId='${r}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}c.iterationCount++,o&&c.feedback.push(o);let w=Xi(l);c.screens=w.screens.map(f=>f.name),sn(r,c);let N=Zi(w,o??void 0,u),x=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,S=o?`Apply the user's feedback to ${u}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${u}, then open it in the browser. Ask the user if the layout feels right.`;return d(JSON.stringify({status:"wireframe",iterationCount:c.iterationCount,screens:w.screens.map(f=>({name:f.name,type:f.type,route:f.route})),wireframePrompt:N,designDirection:w.designDirection,...x?{nudge:x}:{},mockupFile:p,mockupPath:u,nextAction:S}))}};function un(t){let e=De(t,".mistflow","mockups");return Wt(e)?cn(e).filter(r=>r.endsWith(".html")).map(r=>De(e,r)):[]}import{z as Qo}from"zod";import{resolve as oa}from"path";import{spawn as ra}from"child_process";function Gt(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,c,m,p,u]=a;e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:`${p}: ${u}`,humanMessage:`There is a type error in ${l} on line ${c}: ${u}`,suggestion:`Check line ${c} in ${l}. ${p==="TS2345"?"The types of the arguments do not match.":`Fix the ${p} error.`}`})}let o=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(o)){let[,l,c,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(c,10))||e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:p,humanMessage:`There is an error in ${l} on line ${c}: ${p.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let s=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of t.matchAll(s)){let[,l,c]=a;e.push({file:c,message:`Module not found: ${l}`,humanMessage:`The file ${c??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let i=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(i)){let[,l,c]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${c}${l}`,humanMessage:`The package '${c}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${c}'.`,suggestion:`Add '${c}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let n=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of t.matchAll(n)){let[,l,c,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(m,10))||e.push({file:l,line:parseInt(m,10),column:parseInt(p,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${m}.`,suggestion:`Check line ${m} in ${l} for a missing closing bracket or unexpected token.`})}return e}var na=Qo.object({projectPath:Qo.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:Qo.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});function sa(t){return new Promise(e=>{let r=ra("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),o="";r.stdout?.on("data",s=>{o+=s.toString()}),r.stderr?.on("data",s=>{o+=s.toString()}),r.on("error",s=>{e({exitCode:127,combined:`${o}
|
|
1781
|
+
${s.message}`})}),r.on("close",s=>{e({exitCode:s??1,combined:o})})})}var mn={name:"mist_debug",description:yr,inputSchema:na,handler:async t=>{let e=t,r=oa(e.projectPath??process.cwd()),o=e.buildOutput??"";if(!e.buildOutput){let n=await sa(r);if(n.exitCode===0)return d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));o=n.combined}let s=Gt(o),i=o.slice(0,2e3);return s.length===0?d(JSON.stringify({errors:s,rawOutput:i,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):d(JSON.stringify({errors:s,rawOutput:i,message:`Found ${s.length} error${s.length===1?"":"s"} in the build output.`}))}};import{z as O}from"zod";import{existsSync as yt,mkdirSync as Yt,readFileSync as wn,readdirSync as va,statSync as ka,unlinkSync as xa,writeFileSync as Qt}from"fs";import{dirname as Sa,isAbsolute as Ta,join as ie}from"path";import{homedir as je}from"os";import{createHash as Pa,createHmac as vn,randomBytes as Ca,randomUUID as bn,timingSafeEqual as Ia}from"crypto";le();function xe(t,e,r,o=3e3){if(e===void 0)return{stop:()=>{}};let s=0,i=!1,a=setInterval(()=>{i||(s++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:s,message:r()}}).catch(()=>{}))},o);return{stop:()=>{i||(i=!0,clearInterval(a))}}}function ia(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function aa(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function la(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function ca(t){let e={},r=[],o=[],s=new Set;for(let i=0;i<t.length;i++){let n=t[i],a=n.decisionKey?la(n.decisionKey):`q_${i+1}`,l=a,c=2;for(;s.has(l);)l=`${a}_${c}`,c++;s.add(l);let m=n.freetext?"":`${l}_other`;if(m&&s.add(m),o.push({primary:l,other:m,question:n}),n.freetext){e[l]={type:"string",title:n.question,description:n.why,...n.recommended?{default:n.recommended}:{}},r.push(l);continue}let p=(n.options??[]).map(w=>typeof w=="string"?w:w.label),u=n.noOtherSentinel?[...p]:[...p,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:n.question,description:n.why?`${n.why}${n.recommended?`
|
|
1782
|
+
Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}`:void 0,enum:u,enumNames:u,...n.recommended&&p.includes(n.recommended)?{default:n.recommended}:{}},r.push(l),e[m]={type:"string",title:n.otherFieldTitle??"If 'Other' selected above: type your answer",description:"Leave blank if you picked an option from the list."}}return{schema:{type:"object",properties:e,required:r},fieldKeys:o}}function da(t,e){let r=[],o;for(let{primary:s,other:i,question:n}of e){let a=String(t[s]??"").trim(),l;if(n.freetext)l=a||n.recommended||"";else{let m=i?String(t[i]??"").trim():"",p=a.toLowerCase(),u=p.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(p);m?l=m:u?l=n.recommended??(n.options?.[0]&&typeof n.options[0]=="object"?n.options[0].label:"")??a:l=a}let c=n.decisionKey??"";if(c==="urlChoice"){o=l;continue}r.push({question:n.question,decisionKey:c,answer:l})}return{answers:r,urlChoice:o}}async function Vt(t,e,r){if(aa())return{outcome:"unsupported"};if(!ia(t))return{outcome:"unsupported"};if(e.length===0)return{outcome:"submitted",answers:[]};let{schema:o,fieldKeys:s}=ca(e),i;try{i=await t.elicitInput({message:r,requestedSchema:o,mode:"form"},{timeout:300*1e3})}catch(l){let c=l instanceof Error?l.message:String(l);return c.toLowerCase().includes("not support")?{outcome:"unsupported"}:{outcome:"error",errorMessage:c}}if(i.action==="decline")return{outcome:"declined"};if(i.action==="cancel")return{outcome:"cancelled"};if(i.action!=="accept"||!i.content)return{outcome:"error",errorMessage:`Unexpected elicitation result: ${i.action}`};let{answers:n,urlChoice:a}=da(i.content,s);return{outcome:"submitted",answers:n,urlChoice:a}}var pa=[{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 hn(t,e,r){let o=r?.suggestedName||ua(t),s=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")),n=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",a;if(r?.suggestedFeatures&&r.suggestedFeatures.length>0)a=r.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;a=[];for(let c of pa){let m=c.keywords.test(l),p=c.condition(e);(m||p)&&a.push({name:c.name,description:c.description,checked:m,source:m?"explicit":"suggested"})}}return{name:o,audience:s,audienceType:i,surfaceType:n,primaryAction:e.primaryAction||"manage items",features:a,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:r?.language||"English"}}function gn(t){let e=t.features.filter(a=>a.checked),r=t.features.filter(a=>!a.checked),o={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},s={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)"},n=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${i[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${o[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){n.push("**Included:**");for(let a of e)n.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(n.push(""),n.push(`**Integrations:** ${t.integrations.join(", ")}`)),r.length>0){n.push(""),n.push("**Available to add:**");for(let a of r)n.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return n.join(`
|
|
1783
|
+
`)}function ua(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return Kt(e[1]);let r=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),s=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(i=>i.length>2&&!r.has(i)).slice(0,3);return s.length===0?"my-app":s.join("-")}function Kt(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var ma=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],ha=["sharp","soft","pill","organic"],ga=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"];function Xo(t,e,r){return e.includes(t)?t:r}function ae(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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 fa(t){let e=new Set;for(let o of t)o.fonts?.display&&e.add(o.fonts.display),o.fonts?.body&&e.add(o.fonts.body);return e.size===0?"":`https://fonts.googleapis.com/css2?${[...e].map(o=>`family=${o.trim().replace(/\s+/g,"+").replace(/[^A-Za-z0-9+]/g,"")}:wght@400;700`).join("&")}&display=swap`}function fn(t){let e=(t||"").trim(),r=e.toLowerCase(),o=/mono|courier|code/.test(r)?"ui-monospace, monospace":/serif|garamond|bodoni|fraunces|playfair|lora|sentient|migra|sectra|cormorant|abril|crimson/.test(r)?"Georgia, serif":"system-ui, sans-serif";return e?`"${e.replace(/"/g,"")}", ${o}`:o}function ya(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 ba(){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`
|
|
1789
1784
|
.card-hero { position: relative; overflow: hidden; isolation: isolate; }
|
|
1790
1785
|
.card-hero::before {
|
|
1791
1786
|
content: "";
|
|
@@ -1802,17 +1797,17 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
1802
1797
|
|
|
1803
1798
|
.card-hero.texture-paper-grain::before {
|
|
1804
1799
|
opacity: 0.35;
|
|
1805
|
-
background-image: ${
|
|
1800
|
+
background-image: ${t};
|
|
1806
1801
|
mix-blend-mode: multiply;
|
|
1807
1802
|
}
|
|
1808
1803
|
.card-hero.texture-film-grain::before {
|
|
1809
1804
|
opacity: 0.5;
|
|
1810
|
-
background-image: ${
|
|
1805
|
+
background-image: ${t};
|
|
1811
1806
|
mix-blend-mode: overlay;
|
|
1812
1807
|
}
|
|
1813
1808
|
.card-hero.texture-noise::before {
|
|
1814
1809
|
opacity: 0.25;
|
|
1815
|
-
background-image: ${
|
|
1810
|
+
background-image: ${t};
|
|
1816
1811
|
mix-blend-mode: overlay;
|
|
1817
1812
|
}
|
|
1818
1813
|
.card-hero.texture-scanlines::before {
|
|
@@ -1843,9 +1838,9 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
1843
1838
|
backdrop-filter: blur(14px);
|
|
1844
1839
|
mix-blend-mode: normal;
|
|
1845
1840
|
}
|
|
1846
|
-
`}function
|
|
1847
|
-
${
|
|
1848
|
-
<div class="hero-terminal-lines" style="font-family:${
|
|
1841
|
+
`}function wa(t,e,r,o){let s=tt(t.colors?.bg??"","#0f0f0f"),i=tt(t.colors?.fg??"","#f5f5f5"),n=tt(t.colors?.accent??"","#7c9cff"),a=ae(t.name),l=ae(t.hero_headline||t.name),c=ae(t.body_sample||t.summary||""),m=ae(t.cta_text||"Continue"),p=`<div class="hero-eyebrow" style="font-family:${r}">${a.toUpperCase()}</div>`,u=`<h2 class="hero-headline" style="font-family:${e}">${l}</h2>`,w=`<p class="hero-body" style="font-family:${r}">${c}</p>`,N=`<button class="hero-cta" style="background:${n};color:${s};font-family:${r};border-radius:${o.button}">${m}</button>`,x=Xo(t.hero_treatment,ma,"typographic");if(x==="terminal"){let S=`"${(t.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
|
|
1842
|
+
${p}
|
|
1843
|
+
<div class="hero-terminal-lines" style="font-family:${S};color:${i}">
|
|
1849
1844
|
<div>$ status --all</div>
|
|
1850
1845
|
<div>api.service.......<span style="color:${n}">OK</span></div>
|
|
1851
1846
|
<div>worker.queue......<span style="color:${n}">OK</span></div>
|
|
@@ -1853,57 +1848,57 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
1853
1848
|
</div>
|
|
1854
1849
|
${u}
|
|
1855
1850
|
${w}
|
|
1856
|
-
<div class="hero-cta-row">${
|
|
1857
|
-
`}return
|
|
1851
|
+
<div class="hero-cta-row">${N}</div>
|
|
1852
|
+
`}return x==="split-panel"?`
|
|
1858
1853
|
<div class="hero-split">
|
|
1859
|
-
<div class="hero-split-left" style="background:${n};color:${s};font-family:${
|
|
1854
|
+
<div class="hero-split-left" style="background:${n};color:${s};font-family:${e}">
|
|
1860
1855
|
<div class="hero-split-mark" style="font-family:${r};color:${s}">${a[0]??"\xB7"}</div>
|
|
1861
1856
|
</div>
|
|
1862
1857
|
<div class="hero-split-right">
|
|
1863
|
-
${
|
|
1858
|
+
${p}
|
|
1864
1859
|
${u}
|
|
1865
1860
|
${w}
|
|
1866
|
-
<div class="hero-cta-row">${
|
|
1861
|
+
<div class="hero-cta-row">${N}</div>
|
|
1867
1862
|
</div>
|
|
1868
1863
|
</div>
|
|
1869
|
-
`:
|
|
1864
|
+
`:x==="full-bleed-photo"?`
|
|
1870
1865
|
<div class="hero-photo" style="background: linear-gradient(160deg, ${n}30 0%, ${i}08 35%, ${s} 100%), ${s}">
|
|
1871
1866
|
<span class="hero-photo-label" style="font-family:${r};color:${i}">photo slot</span>
|
|
1872
1867
|
</div>
|
|
1873
|
-
${
|
|
1868
|
+
${p}
|
|
1874
1869
|
${u}
|
|
1875
1870
|
${w}
|
|
1876
|
-
<div class="hero-cta-row">${
|
|
1877
|
-
`:
|
|
1878
|
-
${
|
|
1879
|
-
<h2 class="hero-headline hero-headline-mag" style="font-family:${
|
|
1871
|
+
<div class="hero-cta-row">${N}</div>
|
|
1872
|
+
`:x==="magazine-hero"?`
|
|
1873
|
+
${p}
|
|
1874
|
+
<h2 class="hero-headline hero-headline-mag" style="font-family:${e}">${l}</h2>
|
|
1880
1875
|
<div class="hero-rule" style="background:${i}"></div>
|
|
1881
1876
|
<p class="hero-body hero-body-mag" style="font-family:${r}">${c}</p>
|
|
1882
1877
|
<div class="hero-byline" style="font-family:${r};color:${i}">\u2014 Volume 01 \xB7 Issue 01</div>
|
|
1883
|
-
<div class="hero-cta-row">${
|
|
1878
|
+
<div class="hero-cta-row">${N}</div>
|
|
1884
1879
|
`:`
|
|
1885
|
-
${
|
|
1880
|
+
${p}
|
|
1886
1881
|
${u}
|
|
1887
1882
|
${w}
|
|
1888
|
-
<div class="hero-cta-row">${
|
|
1889
|
-
`}function
|
|
1890
|
-
<div class="card-hero texture-${
|
|
1883
|
+
<div class="hero-cta-row">${N}</div>
|
|
1884
|
+
`}function yn(t,e){let r=fa(e),o=e.map(s=>{let i=tt(s.colors?.bg??"","#0f0f0f"),n=tt(s.colors?.fg??"","#f5f5f5"),a=tt(s.colors?.accent??"","#7c9cff"),l=fn(s.fonts?.display??""),c=fn(s.fonts?.body??""),m=Xo(s.shape_lang,ha,"soft"),p=Xo(s.texture,ga,"flat"),u=ya(m),w=wa(s,l,c,u),N=ae(s.name),x=ae(s.id),S=ae(s.fonts?.display??""),f=ae(s.fonts?.body??""),A=ae(s.summary||""),U=ae(s.decoration_hint||""),H=(_,K)=>`<div class="card-meta-row"><span class="card-meta-label">${_}</span><span class="card-meta-value">${K}</span></div>`;return` <article class="card" data-direction-id="${x}" style="border-radius:${u.card}">
|
|
1885
|
+
<div class="card-hero texture-${p}" style="background:${i};color:${n}">${w}
|
|
1891
1886
|
</div>
|
|
1892
1887
|
<div class="card-meta" style="border-top-color:${n}14">
|
|
1893
|
-
<div class="card-meta-title">${
|
|
1894
|
-
<p class="card-meta-summary">${
|
|
1895
|
-
${
|
|
1896
|
-
${
|
|
1888
|
+
<div class="card-meta-title">${N}</div>
|
|
1889
|
+
<p class="card-meta-summary">${A}</p>
|
|
1890
|
+
${H("Fonts",`${S||"\u2014"} <span class="sep">\xB7</span> ${f||"\u2014"}`)}
|
|
1891
|
+
${H("Palette",`
|
|
1897
1892
|
<span class="card-meta-swatches">
|
|
1898
1893
|
<span class="card-meta-swatch" title="${i}" style="background:${i}"></span>
|
|
1899
1894
|
<span class="card-meta-swatch" title="${n}" style="background:${n}"></span>
|
|
1900
1895
|
<span class="card-meta-swatch" title="${a}" style="background:${a}"></span>
|
|
1901
1896
|
</span>
|
|
1902
1897
|
`)}
|
|
1903
|
-
${
|
|
1904
|
-
${
|
|
1905
|
-
${
|
|
1906
|
-
${
|
|
1898
|
+
${H("Shape",`<span class="chip" style="border-radius:${u.chip}">${m}</span>`)}
|
|
1899
|
+
${H("Texture",`<span class="chip" style="border-radius:${u.chip}">${ae(p)}</span>`)}
|
|
1900
|
+
${U?H("Decoration",ae(U)):""}
|
|
1901
|
+
${H("Pick with",`<code>${N}</code>`)}
|
|
1907
1902
|
</div>
|
|
1908
1903
|
</article>`}).join(`
|
|
1909
1904
|
`);return`<!DOCTYPE html>
|
|
@@ -1911,7 +1906,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
1911
1906
|
<head>
|
|
1912
1907
|
<meta charset="UTF-8" />
|
|
1913
1908
|
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
1914
|
-
<title>Design directions \u2014 ${
|
|
1909
|
+
<title>Design directions \u2014 ${ae(t)}</title>
|
|
1915
1910
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
1916
1911
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
1917
1912
|
${r?`<link rel="stylesheet" href="${r}" />`:""}
|
|
@@ -2098,7 +2093,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
2098
2093
|
margin-top: 4px;
|
|
2099
2094
|
}
|
|
2100
2095
|
|
|
2101
|
-
${
|
|
2096
|
+
${ba()}
|
|
2102
2097
|
|
|
2103
2098
|
/* \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 */
|
|
2104
2099
|
.card-meta {
|
|
@@ -2207,7 +2202,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
2207
2202
|
<div class="page">
|
|
2208
2203
|
<header class="page-header">
|
|
2209
2204
|
<div class="eyebrow"><span class="eyebrow-dot"></span>Mistflow \xB7 design direction</div>
|
|
2210
|
-
<h1 class="page-title">How should <strong>${
|
|
2205
|
+
<h1 class="page-title">How should <strong>${ae(t)}</strong> feel?</h1>
|
|
2211
2206
|
<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>
|
|
2212
2207
|
</header>
|
|
2213
2208
|
|
|
@@ -2227,30 +2222,30 @@ ${o}
|
|
|
2227
2222
|
</div>
|
|
2228
2223
|
</body>
|
|
2229
2224
|
</html>
|
|
2230
|
-
`}var po="__mistflow_url_choice__",Va=600*1e3;function Fn(){let e=ue(Ge(),".mistflow","confirm-secret");if(Nt(e))try{return Buffer.from(Un(e,"utf-8").trim(),"hex")}catch{}let t=Wa(32);return uo(ue(Ge(),".mistflow"),{recursive:!0}),mo(e,t.toString("hex"),{mode:384}),t}function qn(e){return Ha("sha256").update(e.trim().toLowerCase()).digest("hex").slice(0,16)}function Ka(e,t){let r={cwd:e,d:qn(t),exp:Date.now()+Va},o=Buffer.from(JSON.stringify(r)).toString("base64url"),s=$n("sha256",Fn()).update(o).digest("base64url");return`${o}.${s}`}function Ja(e,t,r){let o=e.split(".");if(o.length!==2)return!1;let[s,i]=o,n=$n("sha256",Fn()).update(s).digest("base64url"),a=Buffer.from(i),l=Buffer.from(n);if(a.length!==l.length||!Ga(a,l))return!1;try{let c=JSON.parse(Buffer.from(s,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==t||c.d!==qn(r))}catch{return!1}}function Ya(e){let t=e,r=Ge(),o=!1;for(let s=0;s<64;s++){if(Nt(ue(t,"mistflow.json")))return"mistflow";if(!o&&Nt(ue(t,"package.json"))&&(o=!0),t===r)break;let i=Ba(t);if(i===t)break;t=i}return o?"foreign":"none"}function Qa(e){let t=Ge(),r=e.replace(/\/+$/,"");if(r===t||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let o=["Desktop","Documents","Downloads"];for(let s of o)if(r===ue(t,s))return!0;return!1}var Xa=N.object({description:N.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:N.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:N.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:N.union([N.record(N.string()),N.array(N.object({question:N.string().optional(),decisionKey:N.string().optional(),answer:N.string()}))]).optional().describe("User's answers to the clarifying questions. Preferred shape: array of { question, decisionKey, answer } objects (supports duplicate decisionKeys). Legacy shape: { '<question text>': '<answer label>' } object map. Both are accepted; the server normalizes either."),existingPlan:N.record(N.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:N.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:N.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:N.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:N.boolean().optional().describe("DANGER \u2014 only set this to `true` when the user has EXPLICITLY asked to skip discovery questions (phrases like 'no questions', 'just build it', 'autonomous mode', 'don't ask'). Default is `false` and should stay that way in every other case. Do NOT set autonomous=true as a retry strategy after a plan-gen failure \u2014 it doesn't make things more reliable, it just removes the user's control over discovery answers (roles, integrations, auth model, etc.) and Sonnet ends up guessing. If a plan call fails, retry the SAME call with the same parameters, not a more aggressive one. Do NOT set autonomous=true to speed things up \u2014 the server already runs plan-gen in the background and polls, so there is no speed benefit. When set, skips the clarify round and generates the plan straight from the description. The user loses the chance to pick any option."),landingDesign:N.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:N.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:N.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:N.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:N.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:N.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:N.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:N.object({id:N.string().optional(),name:N.string().optional(),summary:N.string().optional(),heroHeadline:N.string().optional(),ctaText:N.string().optional(),bodySample:N.string().optional(),fontsHint:N.string().optional(),fonts:N.object({display:N.string(),body:N.string()}).partial().optional(),colorMood:N.string().optional(),colors:N.object({bg:N.string(),fg:N.string(),accent:N.string()}).partial().optional(),heroTreatment:N.string().optional(),shapeLang:N.string().optional(),texture:N.string().optional(),decorationHint:N.string().optional(),custom:N.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 Za(e){let t=[[/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[o,s]of t)if(o.test(e))return s;return e.replace(/[?.,!]/g,"").split(/\s+/).filter(o=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(o.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function el(e){let t=ue(Ge(),".mistflow","plans",`${e}.json`);if(!Nt(t))return null;try{return JSON.parse(Un(t,"utf-8")).plan??null}catch{return null}}async function tl(e){for(let o=0;o<60;o++){try{let s=await Lo(e.design_conversation_id);if(s.status==="ready")return{status:"design_clarify",design_conversation_id:e.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 i=s instanceof Error?s.message:String(s);if(i.toLowerCase().includes("not found"))return{status:"ready",plan:e.plan,methodology:e.methodology};console.error(`[plan] directions poll attempt ${o+1} failed: ${i}`)}await new Promise(s=>setTimeout(s,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:e.plan,methodology:e.methodology}}async function ol(e,t){let{description:r,projectPath:o,conversationId:s,answers:i,existingPlan:n,existingPlanId:a,templateToken:l,remixDescription:c,autonomous:h,language:m,landingDesign:u,appStyle:w,brandMentioned:D,confirmToken:S,urlChoice:x,designConversationId:f,designDirection:P}=e;if(s&&!r&&!i&&!f&&!P&&!n&&!a&&!l)try{let p=await Jt(s);if(p.status==="clarify_pending"||p.status==="plan_pending"){let g=typeof p.phase_hint=="string"?p.phase_hint:null,k=typeof p.elapsed_seconds=="number"?p.elapsed_seconds:null,I=typeof p.progress=="number"?p.progress:null,J=p.status==="plan_pending",K=J?"generating_plan":"generating_questions",ee=g?`${g}${k!==null?` (${k}s elapsed)`:""}`:J?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return d(JSON.stringify({status:"running",conversationId:s,phase:K,...g?{phaseHint:g}:{},...k!==null?{elapsedSeconds:k}:{},...I!==null?{progress:I}:{},nextAction:`${ee}. Tell the user briefly what's happening (e.g. "${g??(J?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${s}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}return d(JSON.stringify(p))}catch(p){let g=p instanceof Error?p.message:String(p);return d(`Could not poll plan conversation '${s}': ${g}`,!0)}let R=r??"";if(!R.trim()&&!s&&!f&&!n&&!a&&!l)return d("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(f&&!P&&!R.trim()&&!i)return d(`You passed designConversationId='${f}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${f}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let U=n;if(!U&&a&&(U=el(a)??void 0,!U))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let G=s;if(!ce())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let B;if(!G&&!U&&!l){if(!za(o))return d(`projectPath must be an absolute path \u2014 received '${o}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let p=Ya(o);if(p!=="mistflow"&&Qa(o))return d(JSON.stringify({status:"unsafe_cwd",projectPath:o,instruction:[`The projectPath you passed (${o}) 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 ${o}/<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(`
|
|
2231
|
-
`)}),!0);if(
|
|
2225
|
+
`}var Jt="__mistflow_url_choice__",Aa=600*1e3;function kn(){let t=ie(je(),".mistflow","confirm-secret");if(yt(t))try{return Buffer.from(wn(t,"utf-8").trim(),"hex")}catch{}let e=Ca(32);return Yt(ie(je(),".mistflow"),{recursive:!0}),Qt(t,e.toString("hex"),{mode:384}),e}function xn(t){return Pa("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function _a(t,e){let r={cwd:t,d:xn(e),exp:Date.now()+Aa},o=Buffer.from(JSON.stringify(r)).toString("base64url"),s=vn("sha256",kn()).update(o).digest("base64url");return`${o}.${s}`}function Ra(t,e,r){let o=t.split(".");if(o.length!==2)return!1;let[s,i]=o,n=vn("sha256",kn()).update(s).digest("base64url"),a=Buffer.from(i),l=Buffer.from(n);if(a.length!==l.length||!Ia(a,l))return!1;try{let c=JSON.parse(Buffer.from(s,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==e||c.d!==xn(r))}catch{return!1}}function Ea(t){let e=t,r=je(),o=!1;for(let s=0;s<64;s++){if(yt(ie(e,"mistflow.json")))return"mistflow";if(!o&&yt(ie(e,"package.json"))&&(o=!0),e===r)break;let i=Sa(e);if(i===e)break;e=i}return o?"foreign":"none"}function Na(t){let e=je(),r=t.replace(/\/+$/,"");if(r===e||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let o=["Desktop","Documents","Downloads"];for(let s of o)if(r===ie(e,s))return!0;return!1}var Da=O.object({description:O.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:O.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:O.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:O.union([O.record(O.string()),O.array(O.object({question:O.string().optional(),decisionKey:O.string().optional(),answer:O.string()}))]).optional().describe("User's answers to the clarifying questions. Preferred shape: array of { question, decisionKey, answer } objects (supports duplicate decisionKeys). Legacy shape: { '<question text>': '<answer label>' } object map. Both are accepted; the server normalizes either."),existingPlan:O.record(O.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:O.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:O.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:O.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:O.boolean().optional().describe("DANGER \u2014 only set this to `true` when the user has EXPLICITLY asked to skip discovery questions (phrases like 'no questions', 'just build it', 'autonomous mode', 'don't ask'). Default is `false` and should stay that way in every other case. Do NOT set autonomous=true as a retry strategy after a plan-gen failure \u2014 it doesn't make things more reliable, it just removes the user's control over discovery answers (roles, integrations, auth model, etc.) and Sonnet ends up guessing. If a plan call fails, retry the SAME call with the same parameters, not a more aggressive one. Do NOT set autonomous=true to speed things up \u2014 the server already runs plan-gen in the background and polls, so there is no speed benefit. When set, skips the clarify round and generates the plan straight from the description. The user loses the chance to pick any option."),language:O.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:O.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:O.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:O.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:O.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:O.object({id:O.string().optional(),name:O.string().optional(),summary:O.string().optional(),heroHeadline:O.string().optional(),ctaText:O.string().optional(),bodySample:O.string().optional(),fontsHint:O.string().optional(),fonts:O.object({display:O.string(),body:O.string()}).partial().optional(),colorMood:O.string().optional(),colors:O.object({bg:O.string(),fg:O.string(),accent:O.string()}).partial().optional(),heroTreatment:O.string().optional(),shapeLang:O.string().optional(),texture:O.string().optional(),decorationHint:O.string().optional(),custom:O.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 ja(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[o,s]of e)if(o.test(t))return s;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(o=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(o.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function Oa(t){let e=ie(je(),".mistflow","plans",`${t}.json`);if(!yt(e))return null;try{return JSON.parse(wn(e,"utf-8")).plan??null}catch{return null}}async function Ma(t){for(let o=0;o<60;o++){try{let s=await Po(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 i=s instanceof Error?s.message:String(s);if(i.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll attempt ${o+1} failed: ${i}`)}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 Ua(t,e){let{description:r,projectPath:o,conversationId:s,answers:i,existingPlan:n,existingPlanId:a,templateToken:l,remixDescription:c,autonomous:m,language:p,brandMentioned:u,confirmToken:w,urlChoice:N,designConversationId:x,designDirection:S}=t;if(s&&!r&&!i&&!x&&!S&&!n&&!a&&!l)try{let h=await Ot(s);if(h.status==="clarify_pending"||h.status==="plan_pending"){let b=typeof h.phase_hint=="string"?h.phase_hint:null,y=typeof h.elapsed_seconds=="number"?h.elapsed_seconds:null,v=typeof h.progress=="number"?h.progress:null,q=h.status==="plan_pending",g=q?"generating_plan":"generating_questions",k=b?`${b}${y!==null?` (${y}s elapsed)`:""}`:q?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return d(JSON.stringify({status:"running",conversationId:s,phase:g,...b?{phaseHint:b}:{},...y!==null?{elapsedSeconds:y}:{},...v!==null?{progress:v}:{},nextAction:`${k}. Tell the user briefly what's happening (e.g. "${b??(q?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${s}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}return d(JSON.stringify(h))}catch(h){let b=h instanceof Error?h.message:String(h);return d(`Could not poll plan conversation '${s}': ${b}`,!0)}let f=r??"";if(!f.trim()&&!s&&!x&&!n&&!a&&!l)return d("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(x&&!S&&!f.trim()&&!i)return d(`You passed designConversationId='${x}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${x}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let A=n;if(!A&&a&&(A=Oa(a)??void 0,!A))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let U=s;if(!ne())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let H;if(!U&&!A&&!l){if(!Ta(o))return d(`projectPath must be an absolute path \u2014 received '${o}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let h=Ea(o);if(h!=="mistflow"&&Na(o))return d(JSON.stringify({status:"unsafe_cwd",projectPath:o,instruction:[`The projectPath you passed (${o}) 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 ${o}/<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(`
|
|
2226
|
+
`)}),!0);if(h==="foreign"&&!(w?Ra(w,o,f):!1)){let y=_a(o,f),v=f.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().split(/\s+/).slice(0,3).join("-").slice(0,40)||"new-app",q=ie(o,v);if(e?.server){let g=await Vt(e.server,[{question:"You're inside an existing project. Where should Mistflow scaffold the new app?",decisionKey:"scopeChoice",recommended:`Create at: ${q}`,why:"Mistflow creates a NEW app and never modifies the surrounding codebase. The default puts it in a subdirectory of the current path, named after your description. You can pick a custom path or cancel if you actually want to edit the existing project instead.",options:[{label:`Create at: ${q}`,description:"Default \u2014 uses your description as the folder name."},{label:"Choose a different path",description:"Type a custom absolute path in the textbox below."},{label:"Cancel \u2014 I wanted to edit the existing project",description:"Stop Mistflow. Handle the request by editing files in the current project instead."}]}],`## Existing project detected
|
|
2232
2227
|
|
|
2233
2228
|
You're inside \`${o}\` which has a \`package.json\`. Mistflow will create a NEW app in a subdirectory \u2014 it won't modify the existing code.
|
|
2234
2229
|
|
|
2235
|
-
Default path: \`${
|
|
2236
|
-
`)}))}else return d(JSON.stringify({status:"confirm_new_project",projectPath:o,description:
|
|
2237
|
-
`)}))}}if(l)try{if(!(await
|
|
2238
|
-
|
|
2239
|
-
**Your app URL (you can change this before scaffolding):** https://${
|
|
2240
|
-
`),
|
|
2241
|
-
`)}))}if(
|
|
2242
|
-
`):"No visual preview rendered (see server logs). The question options below carry fonts + mood so the user can still pick, but warn them the HTML preview didn't land.",
|
|
2243
|
-
`)}))}let
|
|
2244
|
-
|
|
2245
|
-
The plan is ready. One last decision before I scaffold: what's the app's URL?`);if(p.outcome==="submitted"){let g=p.urlChoice?.trim()||p.answers?.[0]?.answer.trim()||"";g=g.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(g)||!g)&&(g=V);let k=g.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(k)?y=k:(console.error(`[mist_plan] URL elicitation returned '${g}' \u2014 does not look like a subdomain. Using default '${V}'.`),y=V)}else p.outcome==="declined"||p.outcome,y=V}else y||(y=V);let re=v.publicPages;if(!re||Array.isArray(re)&&re.length===0){let p=v.pages,g=A.some(I=>typeof I.name=="string"&&I.name.toLowerCase().includes("landing")||typeof I.title=="string"&&I.title.toLowerCase().includes("landing")),k=Array.isArray(p)&&p.some(I=>I.path==="/"||I.route==="/");g||k?re=["/","/pricing"]:re=["/"]}let Ne=v.primaryAction;if(!Ne){let p=v.features;if(Array.isArray(p)&&p.length>0){let k=p.find(J=>typeof J.priority=="string"&&J.priority.toLowerCase()==="must-have")??p[0];Ne={entity:k.name??k.title??"item",action:"create",fromPage:"/dashboard"}}}let we=v.nonNegotiables;(!we||Array.isArray(we)&&we.length===0)&&(we=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let ae=Ln(),Q=ue(Ge(),".mistflow","plans");uo(Q,{recursive:!0});try{let g=Date.now();for(let k of[Q,ue(Ge(),".mistflow","mockup-state")])if(Nt(k))for(let I of $a(k))try{let J=ue(k,I),K=Fa(J).mtimeMs;g-K>6048e5&&qa(J)}catch{}}catch{}let ne;if(u){let p=to(u);p?ne=p.id:console.error(`Landing design '${u}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let fe=w||void 0,yt=!!ne,xe=A.some(p=>{let g=`${p.name??p.title} ${p.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),me=!yt&&xe?fn(R,{maxResults:2}):[];me.length>0&&(ne=me[0].id,console.error(`Auto-assigned landing layout preset (default): ${me[0].title} (${ne})`));let rt={name:v.name,summary:v.summary,dataModel:v.dataModel,pages:v.pages,features:v.features,steps:A.map(p=>({...p,name:p.name??p.title})),design:v.design,landingDesign:ne,appStyle:fe,dbProvider:v.dbProvider??"neon",authModel:v.authModel,audienceType:v.audienceType??"b2c",roles:v.roles,defaultRole:v.defaultRole,publicPages:re,navStyle:v.navStyle,multiTenant:v.multiTenant,primaryAction:Ne,nonNegotiables:we,requestedSubdomain:y,...m&&m.toLowerCase()!=="english"?{language:m}:{}};mo(ue(Q,`${ae}.json`),JSON.stringify({plan:rt,methodology:W}));let bt=A.map(p=>`${p.number}. ${p.name??p.title}`),Fe="",O=[],Y;!yt&&me.length>0&&(O=me.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${st()}/designs?tab=landing-designs`})),Y={question:"What landing page style fits this app?",header:"Landing Design",options:[...me.map((g,k)=>({label:k===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 ${st()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},Fe=` 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: ${me.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='${me[0].id}' explicitly.`);let ye="",Me=[],b=void 0,z=(v.audienceType??"b2c")==="b2c",te={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},ve=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call.",le="",_=[];for(let p of A){let g=p.name??p.title,k=p.integrationId;if(k){let I=dt(k);if(I){let J=pt(I.id);_.push({step:g,presetId:I.id,presetName:I.name,envVars:J?.envVars??[]})}}}if(_.length>0){let p=_.flatMap(I=>I.envVars),g=[...new Set(p.map(I=>I.key))];le=` This plan uses integrations (${_.map(I=>I.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return d(JSON.stringify({planId:ae,name:v.name,summary:v.summary,stepCount:A.length,steps:bt,design:v.design,...ne?{landingDesign:ne}:{},...fe?{appStyle:fe}:{},...Me.length>0?{recommendedAppStyles:Me}:{},...b?{appStyleQuestion:b}:{},...O.length>0?{recommendedLandingDesigns:O}:{},...Y?{landingDesignQuestion:Y}:{},heroPhotoQuestion:te,..._.length>0?{integrations:_.map(p=>({step:p.step,preset:p.presetId,name:p.presetName,envVars:p.envVars}))}:{},message:`Plan generated for "${M}" (${A.length} steps).${ne?` Landing layout "${ne}" set as default.`:""}${fe?` App style "${fe}" will be applied across all pages.`:""}${le}${ye}${Fe}${ve}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,A.length*3)}\u2013${A.length*5} minutes total across ${A.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: '${ae}' }). If the user says skip or "just build it", call mist_init({ planId: '${ae}', path: '<absolute path>' }) immediately.`,...B?{warning:B}:{}}))}var Bn={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(`
|
|
2246
|
-
`),inputSchema:
|
|
2247
|
-
`)}function
|
|
2248
|
-
`)}var
|
|
2249
|
-
|
|
2250
|
-
`+
|
|
2251
|
-
`)}function
|
|
2252
|
-
`),i=null,n=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of s){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let u=a(c.slice(6).trim());(u==="dark"||u==="light")&&(o.theme=u);continue}let
|
|
2253
|
-
`),i=[` --radius-sm: ${
|
|
2230
|
+
Default path: \`${q}\``);if(g.outcome==="submitted"){let k=g.answers?.[0]?.answer??"",E=k.toLowerCase(),V=k.startsWith("/")?k:null;if(V||E.startsWith("create at:")||E.startsWith("choose a different path")){let Z=V||(E.startsWith("choose a different path")?null:q);if(!Z)return d("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);H=`Note: Mistflow will scaffold the new app at \`${Z}\`. The existing project at \`${o}\` is not modified. When the user runs mist_init later, pass path: "${Z}".`}else return E.startsWith("cancel")?d("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):d(`User submitted an unrecognized scope choice: ${k}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return g.outcome==="declined"||g.outcome==="cancelled"?d("User cancelled the scope confirmation. They didn't pick \u2014 ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.",!0):d(JSON.stringify({status:"confirm_new_project",projectPath:o,description:f,confirmToken:y,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(`
|
|
2231
|
+
`)}))}else return d(JSON.stringify({status:"confirm_new_project",projectPath:o,description:f,confirmToken:y,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(`
|
|
2232
|
+
`)}))}}if(l)try{if(!(await Fo(l)).plan)return d("This template has no plan to fork. Try a different template.",!0);let b=await qo(l),y=b.plan,v="";if(c&&b.has_source)try{let Q=await Ut(b.plan,c),P=Q.plan??Q,j=Q.diff,X=P?.steps??[],te=new Set([...(j?.added??[]).map(me=>me.number),...(j?.modified??[]).map(me=>me.number)]),oe=X.map(me=>{let Ds=me.number;return te.has(Ds)?{...me,status:"pending"}:{...me,status:"completed",source:"forked"}});P.steps=oe,y=P;let re=oe.filter(me=>me.status==="pending").length;v=` Remixed: ${oe.filter(me=>me.status==="completed").length} steps unchanged, ${re} steps need re-implementation.`}catch(Q){console.error("[plan] Remix failed, using original plan:",Q),v=" (Remix failed \u2014 using original plan. You can modify it later.)"}let q=bn(),g=ie(je(),".mistflow","plans");Yt(g,{recursive:!0}),Qt(ie(g,`${q}.json`),JSON.stringify({plan:y,projectId:b.id,sourceDeploymentId:b.source_deployment_id,forkToken:b.fork_token,requiredEnvVars:b.required_env_vars,dbProvider:b.db_provider}));let k=y?.name??"forked-app",E=b.has_source,V=E?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Z=b.deploy_url?` Instant deploy started \u2014 your app will be live at ${b.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:q,forkedFrom:b.forked_from,projectId:b.id,hasSource:E,deployUrl:b.deploy_url,message:`Forked "${b.forked_from}" into your workspace.${v}${Z} ${V} NEXT: Call mist_init, name='${k}', and planId='${q}' to create the project now.`}))}catch(h){let b=h instanceof Error?h.message:"Failed to fork template";return d(b,!0)}if(A){let h;try{h=await Ut(A,f)}catch(g){let k=g instanceof Error?g.message:"Failed to modify plan";return d(k,!0)}let b=h.plan,y=h.diff,v=[];if(y?.added?.length){let g=y.added.map(k=>k.title);v.push(`Added ${g.length} step(s): ${g.join(", ")}`)}if(y?.removed?.length){let g=y.removed.map(k=>k.title);v.push(`Removed ${g.length} step(s): ${g.join(", ")}`)}if(y?.modified?.length){let g=y.modified.map(k=>k.title);v.push(`Modified ${g.length} step(s): ${g.join(", ")}`)}let q=v.length>0?v.join(". "):"No changes detected.";return d(JSON.stringify({plan:b,diff:y,message:`Plan modified. ${q}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let _=N?.trim()||void 0,K=i;if(Array.isArray(i)){let h=i.findIndex(b=>b&&typeof b=="object"&&b.decisionKey==="urlChoice");if(h>=0){let b=i[h];!_&&b.answer&&(_=b.answer);let y=i.slice(0,h).concat(i.slice(h+1));K=y.length>0?y:void 0}}else if(i!=null){let h=i;if(!_&&Jt in h&&(_=h[Jt]),!_&&"urlChoice"in h&&(_=h.urlChoice),Jt in h||"urlChoice"in h){let{[Jt]:b,urlChoice:y,...v}=h;K=Object.keys(v).length>0?v:void 0}}if(_&&(_=_.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),_){let h=_.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(h)?_=h:(console.error(`[mist_plan] Discarding urlChoice '${_}' \u2014 does not look like a subdomain. Backend will auto-generate.`),_=void 0)}let F;if(S){F={...S};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[b,y]of Object.entries(h))S[b]!==void 0&&F[y]===void 0&&(F[y]=S[b])}let T=i?"Generating plan with your answers (LLM call)":x?"Finalizing design direction":"Thinking through discovery questions",R=e?xe(e.server,e.progressToken,()=>T):{stop:()=>{}};e&&(e.cleanup=()=>R.stop());let C;try{U&&!K&&!x&&!A&&!a?C=await Ot(U):C=await Mt(f,{conversationId:U,answers:K,autonomous:m,language:p,designConversationId:x,designDirection:F})}catch(h){R.stop();let b=h instanceof Error?h.message:"Failed to generate plan";return d(b,!0)}if(C.status==="clarify_pending"){R.stop();let h=C;return d(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"){R.stop();let h=C;return d(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"&&(T="Generating creative design directions",C=await Ma(C)),R.stop(),C.status==="clarify"){let h=C.reflection||"",b=C.suggestedName||"",y=C.suggestedFeatures??[],v=C.questions??[],q=v.some(j=>Array.isArray(j.options)&&typeof j.options[0]=="object"&&j.options[0]?.label),g={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"},k=v.map(j=>{let X=j.decisionKey&&g[j.decisionKey]||ja(j.question),te;return q&&Array.isArray(j.options)?te=j.options.map(oe=>({label:oe.label,description:oe.description??""})):Array.isArray(j.options)?te=j.options.map((oe,re)=>({label:re===0?`${oe} (Recommended)`:String(oe),description:j.why??""})):te=[{label:"Yes (Recommended)",description:j.why??""},{label:"No",description:""}],{question:j.question,header:X,options:te,multiSelect:!1}}),V=C.decisions?.audienceType??null,Z=y.length>0?hn(f,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:V,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:b,suggestedFeatures:y,language:p}):null,Q=Z?gn(Z):"",P=Kt(b||"my-app").slice(0,32);try{let j=await jt(P);!j.available&&j.suggestion&&(P=j.suggestion)}catch{}if(Q&&(Q+=`
|
|
2233
|
+
|
|
2234
|
+
**Your app URL (you can change this before scaffolding):** https://${P}.mistflow.app`),e?.server){let j=[b?`## ${b}`:"## Pick a few details","",`${v.length} quick question${v.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
|
|
2235
|
+
`),X=await Vt(e.server,v,j);if(X.outcome==="submitted"){R.stop();let te={};for(let re of X.answers??[])re.decisionKey?te[re.decisionKey]=re.answer:te[re.question]=re.answer;let oe=X.urlChoice?.trim();oe&&(oe=oe.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let re=await Mt(f,{conversationId:C.conversation_id,answers:te,autonomous:m,language:p});if(re.status==="plan_pending"){let nt=re;return d(JSON.stringify({status:"running",conversationId:nt.conversation_id,phase:"generating_plan",...oe?{urlChoice:oe}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${nt.conversation_id}"${oe?`, urlChoice: "${oe}"`:""} } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll up to ~10s and returns when the plan lands. Pass urlChoice on every poll so it threads through to the saved plan.`}))}C=re}catch(re){let nt=re instanceof Error?re.message:String(re);return d(`Submitting your answers failed: ${nt}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(X.outcome==="declined")return R.stop(),d("User declined the planning flow via the form. They likely want a different approach \u2014 ask them what they'd prefer instead of re-running mist_plan.",!0);if(X.outcome==="cancelled")return R.stop(),d("User cancelled the planning form without picking. The conversation is still alive \u2014 re-run mist_plan with the same conversationId if they want to retry, or start a fresh plan if they want to change the description.",!0);X.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${X.errorMessage}) \u2014 falling back to prose flow.`)}}return d(JSON.stringify({status:"clarify",nextAction:"STOP \u2014 DO NOT submit answers yourself. Render every entry in `askUserQuestions` via your host's native question tool (AskUserQuestion in Claude Code, request_user_input in OpenAI Codex Plan mode, quick pick in Cursor) and WAIT for the user to actually answer. If your host has no native question tool, stop your turn, print the questions verbatim as a numbered list with all options visible, and wait for the user's next message. Calling mist_plan with answers in the same turn you received the questions is ALWAYS wrong, regardless of how obvious `recommended` looks.",conversation_id:C.conversation_id,questions:v,questionCount:v.length,suggestedFeatures:y,suggestedName:b,suggestedSubdomain:P,reflection:h,briefText:Q,askUserQuestions:k,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:["\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST ask the user via your host's native structured-question","tool (not a text prompt, not a bash echo, not a chat message).","The user has to actually choose. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","Per host (use whichever applies):"," \u2022 Claude Code \u2192 AskUserQuestion tool"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) \u2192 request_user_input returns"," 'unavailable in <mode> mode'. When you see that error, STOP"," your turn, print the questions as a numbered chat message"," with all options visible, and wait for the user's next"," message. Do NOT resume by picking answers yourself."," \u2022 Any host without a native question tool \u2192 same as above:"," stop your turn, print the questions, wait.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 'Locking in the defaults with X as the only override.'"," (inferring answers from the original spec)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping the question UI because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call the tool (when available): pass each object in the","`askUserQuestions` array below. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${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: "${P}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.',...h||Q?["","\u2500\u2500\u2500 BACKGROUND (not for you to summarize and proceed \u2014 it's what the user will see when you show them the questions) \u2500\u2500\u2500",...h?[h]:[],...Q?["",Q]:[]]:[],...H?["",H]:[]].join(`
|
|
2236
|
+
`)}))}if(C.status==="design_clarify"){let h=C.directions??[],b=C.plan.name??"your app",y;try{let E=h.map(P=>({id:P.id,name:P.name,summary:P.summary,hero_headline:P.hero_headline,cta_text:P.cta_text,body_sample:P.body_sample,fonts:P.fonts,colors:P.colors,hero_treatment:P.hero_treatment,shape_lang:P.shape_lang,texture:P.texture,decoration_hint:P.decoration_hint})),V=yn(b,E),Z=ie(o,".mistflow");Yt(Z,{recursive:!0});let Q=ie(Z,"design-directions.html");Qt(Q,V,"utf-8"),y=Q}catch(E){console.error(`[mist_plan] design-directions preview render failed: ${E instanceof Error?E.message:String(E)}`)}let v=h.map(E=>({label:E.name,description:`${E.summary} \u2014 ${E.fonts?.display??""} + ${E.fonts?.body??""}`}));v.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let q={question:`${b} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:v,multiSelect:!1},g=y?[`A visual preview of all ${h.length} directions has been written to:`,` ${y}`,"Each card is rendered in its direction's own fonts + palette so the user can see what they're picking \u2014 the picker is meaningless without it.","","OPEN THE PREVIEW NOW. Pick whichever works in your host:",` \u2022 macOS: run open "${y}"`,` \u2022 Linux: run xdg-open "${y}"`,` \u2022 Windows: run start "" "${y}"`," \u2022 No shell access: tell the user the exact path and ask them to open it in their browser before they answer.",'Do NOT skip the preview. "I described the options in text" is NOT a replacement \u2014 the user needs to SEE the directions.'].join(`
|
|
2237
|
+
`):"No visual preview rendered (see server logs). The question options below carry fonts + mood so the user can still pick, but warn them the HTML preview didn't land.",k=y?`open "${y}"`:"";return d(JSON.stringify({status:"design_clarify",designConversationId:C.design_conversation_id,directions:h,previewPath:y,askUserQuestion:q,instruction:[`The plan for "${b}" is ready. I've proposed ${h.length} creative directions \u2014 each commits to a specific aesthetic (fonts, colors, voice).`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT PICK A DIRECTION YOURSELF. THE USER PICKS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","",g,k?`Run this command to open the preview for the user: ${k}`:"","","Then ASK THE USER which direction they want. Use whichever your host supports:"," \u2022 Claude Code \u2192 AskUserQuestion tool with the directionQuestion payload above"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) OR any host without a native question tool:"," STOP your turn. Print the direction names + one-line summaries as a"," numbered chat message and wait for the user's reply. Do NOT resume.","","What NOT to do (these have all happened in production transcripts and are unacceptable):"," \u2717 'I'll go with a custom ops-focused brief that fits better than the default.'"," (auto-picking a direction the user never chose)"," \u2717 'Submitting a custom design brief now so we can keep moving.'"," \u2717 Calling mist_plan with designDirection: { custom: '<your own description>' }"," because the user didn't respond fast enough."," \u2717 Skipping this picker because you already decided on the design yourself."," \u2717 Opening the HTML preview but not actually asking the user anything.","","Once the user picks a direction, call mist_plan with:",` designConversationId: "${C.design_conversation_id}"`," designDirection: <the full direction object from the 'directions' array that the user picked>","(No description needed \u2014 server has it from the first call.)","","IF the user picks 'Describe your own direction':"," Ask them a short open question ('How should the app feel? Any fonts or colors in mind?'),"," wait for a real answer, then call mist_plan with"," designDirection: { custom: '<their exact words>' } + the same designConversationId.","","The next mist_plan call takes ~10-20s \u2014 that's the LLM generating the final DESIGN.md with the picked direction. Tell the user 'Locking in the direction now \u2014 this takes about 15 seconds.' before calling."].filter(Boolean).join(`
|
|
2238
|
+
`)}))}let I=C.plan,L=I.name??"Untitled App",M=C.methodology,D=I.steps;if(!Array.isArray(D)||D.length===0)return d("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let $=I.suggestedSubdomain??Kt(L).slice(0,32)??"my-app";if(!_&&e?.server){try{let b=await jt($);!b.available&&b.suggestion&&($=b.suggestion)}catch{}let h=await Vt(e.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${$}.mistflow.app`,why:"Subdomains lock in at scaffold time and are baked into auth callbacks, share links, and analytics. Pick the default to ship now, or type a custom subdomain in the textbox below.",options:[{label:`Keep ${$}.mistflow.app`,description:"Use the suggested subdomain"},{label:"Type a different subdomain",description:"Custom subdomain \u2014 fill the textbox below"}],noOtherSentinel:!0,otherFieldTitle:"Custom subdomain (e.g. 'sales-comm') \u2014 lowercase, alphanumeric + hyphens, 3-32 chars"}],`## ${L} \u2014 pick the URL
|
|
2239
|
+
|
|
2240
|
+
The plan is ready. One last decision before I scaffold: what's the app's URL?`);if(h.outcome==="submitted"){let b=h.urlChoice?.trim()||h.answers?.[0]?.answer.trim()||"";b=b.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(b)||!b)&&(b=$);let y=b.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(y)?_=y:(console.error(`[mist_plan] URL elicitation returned '${b}' \u2014 does not look like a subdomain. Using default '${$}'.`),_=$)}else h.outcome==="declined"||h.outcome,_=$}else _||(_=$);let z=I.publicPages;if(!z||Array.isArray(z)&&z.length===0){let h=I.pages,b=D.some(v=>typeof v.name=="string"&&v.name.toLowerCase().includes("landing")||typeof v.title=="string"&&v.title.toLowerCase().includes("landing")),y=Array.isArray(h)&&h.some(v=>v.path==="/"||v.route==="/");b||y?z=["/","/pricing"]:z=["/"]}let J=I.primaryAction;if(!J){let h=I.features;if(Array.isArray(h)&&h.length>0){let y=h.find(q=>typeof q.priority=="string"&&q.priority.toLowerCase()==="must-have")??h[0];J={entity:y.name??y.title??"item",action:"create",fromPage:"/dashboard"}}}let ee=I.nonNegotiables;(!ee||Array.isArray(ee)&&ee.length===0)&&(ee=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let ve=bn(),ke=ie(je(),".mistflow","plans");Yt(ke,{recursive:!0});try{let b=Date.now();for(let y of[ke,ie(je(),".mistflow","mockup-state")])if(yt(y))for(let v of va(y))try{let q=ie(y,v),g=ka(q).mtimeMs;b-g>6048e5&&xa(q)}catch{}}catch{}let Y={name:I.name,summary:I.summary,dataModel:I.dataModel,pages:I.pages,features:I.features,steps:D.map(h=>({...h,name:h.name??h.title})),design:I.design,dbProvider:I.dbProvider??"neon",authModel:I.authModel,audienceType:I.audienceType??"b2c",roles:I.roles,defaultRole:I.defaultRole,publicPages:z,navStyle:I.navStyle,multiTenant:I.multiTenant,primaryAction:J,nonNegotiables:ee,requestedSubdomain:_,...p&&p.toLowerCase()!=="english"?{language:p}:{}};Qt(ie(ke,`${ve}.json`),JSON.stringify({plan:Y,methodology:M}));let Te=D.map(h=>`${h.number}. ${h.name??h.title}`),Ce=(I.audienceType??"b2c")==="b2c",pe={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:Ce?"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:Ce?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},We=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call.",Ge="",ue=[];for(let h of D){let b=h.name??h.title,y=h.integrationId;if(y){let v=Qe(y);if(v){let q=Xe(v.id);ue.push({step:b,presetId:v.id,presetName:v.name,envVars:q?.envVars??[]})}}}if(ue.length>0){let h=ue.flatMap(v=>v.envVars),b=[...new Set(h.map(v=>v.key))];Ge=` This plan uses integrations (${ue.map(v=>v.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${b.length>0?` The user will need these API keys: ${b.join(", ")}.`:""}`}return d(JSON.stringify({planId:ve,name:I.name,summary:I.summary,stepCount:D.length,steps:Te,design:I.design,heroPhotoQuestion:pe,...ue.length>0?{integrations:ue.map(h=>({step:h.step,preset:h.presetId,name:h.presetName,envVars:h.envVars}))}:{},message:`Plan generated for "${L}" (${D.length} steps).${Ge}${We}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,D.length*3)}\u2013${D.length*5} minutes total across ${D.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_mockup({ planId: '${ve}' }). If the user says skip or "just build it", call mist_init({ planId: '${ve}', path: '<absolute path>' }) immediately.`,...H?{warning:H}:{}}))}var Sn={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. The aesthetic (fonts, colors, motion) is decided by the design-direction picker step \u2014 the host AI doesn't pick a catalog ID."].join(`
|
|
2241
|
+
`),inputSchema:Da,handler:Ua};import{z as bt}from"zod";import{existsSync as ze,mkdirSync as nr,writeFileSync as sr,readFileSync as Zt,readdirSync as _n,copyFileSync as Fa}from"fs";import{join as ye,resolve as Rn,dirname as wt,isAbsolute as qa}from"path";import{homedir as Ba}from"os";import{spawn as tu}from"child_process";import{randomBytes as za}from"crypto";import{simpleGit as Wa}from"simple-git";le();qe();function Tn(t){if(!t)return"Item";let e=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return e.length===0?"Item":e.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}function La(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=Tn(t);return e.charAt(0).toLowerCase()+e.slice(1)}function er(){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(`
|
|
2242
|
+
`)}function Pn(){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(`
|
|
2243
|
+
`)}var Zo="<!-- mist:contracts:start -->",Cn="<!-- mist:contracts:end -->";function tr(t){let e=Pn();if(t.includes(Zo)){let o=t.indexOf(Zo),s=Cn,i=t.indexOf(s,o);if(i===-1)return t.slice(0,o)+e;let n=t.slice(i+s.length);return t.slice(0,o)+e+n.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
|
|
2244
|
+
|
|
2245
|
+
`+e}function or(t,e){let r=Tn(t),o=e??$a(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${o} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${r}Schema = createSelectSchema(${o});`,`export type ${r} = z.infer<typeof ${r}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${r}Input = createInsertSchema(${o}).omit({`," id: true,"," createdAt: true,","});",`export type Create${r}Input = z.infer<typeof Create${r}Input>;`,""].join(`
|
|
2246
|
+
`)}function rr(t){return`contracts/${La(t)}.ts`}function Ha(t){let e=ye(Ba(),".mistflow","plans",`${t}.json`);if(!ze(e))return null;try{let r=JSON.parse(Zt(e,"utf-8"));return r.plan?{plan:r.plan}:null}catch{return null}}function Ga(t){let e=wt(Rn(t)),r=10,o=0;for(;o<r&&e!==wt(e);){if(ze(ye(e,"pnpm-workspace.yaml"))||ze(ye(e,"lerna.json")))return e;let s=ye(e,"package.json");if(ze(s))try{if(JSON.parse(Zt(s,"utf-8")).workspaces)return e}catch{}e=wt(e),o++}return null}var Va=bt.object({name:bt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:bt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:bt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:bt.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 B(t,e,r){let o=ye(t,e);nr(wt(o),{recursive:!0}),sr(o,r)}function Ka(t){if(!ze(t))return!0;let e;try{e=_n(t)}catch{return!1}return e.filter(o=>o!==".mistflow").length===0}var Ja={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Ya=[["--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 Qa(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let r=e[1],o={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},s=r.split(`
|
|
2247
|
+
`),i=null,n=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of s){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let u=a(c.slice(6).trim());(u==="dark"||u==="light")&&(o.theme=u);continue}let m=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(m){i=m[1],n=null;continue}if(i==="typography"){let u=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(u){n=u[1].replace(/-/g,"_"),o.typography[n]={};continue}let w=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(w&&n){o.typography[n][w[1]]=a(w[2]);continue}}let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(p&&i){let u=p[1].replace(/-/g,"_"),w=a(p[2]);i==="colors"?o.colors[u]=w:i==="rounded"?o.rounded[u]=w:i==="spacing"&&(o.spacing[u]=w)}}return o}function Xa(t,e){let r=t.colors,s=[["--color-background",r.background],["--color-foreground",r.on_background??r.on_surface],["--color-card",r.surface??r.background],["--color-card-foreground",r.on_surface??r.on_background],["--color-popover",r.surface??r.background],["--color-popover-foreground",r.on_surface??r.on_background],["--color-muted",r.surface_variant??r.outline_variant??r.outline],["--color-muted-foreground",r.on_surface_variant??r.outline],["--color-border",r.outline_variant??r.outline],["--color-input",r.outline_variant??r.outline],["--color-primary",r.primary],["--color-primary-foreground",r.on_primary],["--color-ring",r.primary],["--color-secondary",r.secondary],["--color-secondary-foreground",r.on_secondary],["--color-accent",r.secondary],["--color-accent-foreground",r.on_secondary],["--color-destructive",r.error],["--color-destructive-foreground",r.on_error],["--color-success",r.success],["--color-success-foreground",r.on_success],["--color-warning",r.warning],["--color-warning-foreground",r.on_warning],["--color-info",r.info??r.primary],["--color-info-foreground",r.on_info??r.on_primary]].filter(a=>typeof a[1]=="string").map(([a,l])=>` ${a}: ${l};`).join(`
|
|
2248
|
+
`),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(`
|
|
2254
2249
|
`);return`@import "tailwindcss";
|
|
2255
2250
|
@import "tw-animate-css";
|
|
2256
2251
|
|
|
@@ -2306,11 +2301,11 @@ ${i}
|
|
|
2306
2301
|
|
|
2307
2302
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2308
2303
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2309
|
-
`}function
|
|
2304
|
+
`}function Za(t,e){let r=t?.borderRadius??"subtle",o=Ja[r]??"0.375rem";if(e){let i=Qa(e);if(i)return Xa(i,o)}return`@import "tailwindcss";
|
|
2310
2305
|
@import "tw-animate-css";
|
|
2311
2306
|
|
|
2312
2307
|
@theme {
|
|
2313
|
-
${[...
|
|
2308
|
+
${[...Ya.map(([i,n])=>` ${i}: ${n};`)," --radius-sm: 0.25rem;",` --radius-md: ${o};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
|
|
2314
2309
|
`)}
|
|
2315
2310
|
}
|
|
2316
2311
|
|
|
@@ -2360,7 +2355,7 @@ ${[...gl.map(([n,a])=>` ${n}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md:
|
|
|
2360
2355
|
|
|
2361
2356
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2362
2357
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2363
|
-
`}var
|
|
2358
|
+
`}var In={"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 An(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return In[e]?In[e]:e.replace(/\s+/g,"_")}function el(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 tl=new Set(["ar","he","fa","ur"]);function ol(t,e,r){let o=t.replace(/[\\"`$]/g,""),s=el(r),n=tl.has(s)?`lang="${s}" dir="rtl"`:`lang="${s}"`,a=e?.fonts?.heading,l=e?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
|
|
2364
2359
|
import { DM_Sans } from "next/font/google";
|
|
2365
2360
|
import { Toaster } from "sonner";
|
|
2366
2361
|
import "./globals.css";
|
|
@@ -2376,7 +2371,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2376
2371
|
</html>
|
|
2377
2372
|
);
|
|
2378
2373
|
}
|
|
2379
|
-
`;let c=
|
|
2374
|
+
`;let c=An(a??l),m=An(l??a);return c===m?`import type { Metadata } from "next";
|
|
2380
2375
|
import { ${c} } from "next/font/google";
|
|
2381
2376
|
import { Toaster } from "sonner";
|
|
2382
2377
|
import "./globals.css";
|
|
@@ -2393,12 +2388,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2393
2388
|
);
|
|
2394
2389
|
}
|
|
2395
2390
|
`:`import type { Metadata } from "next";
|
|
2396
|
-
import { ${c}, ${
|
|
2391
|
+
import { ${c}, ${m} } from "next/font/google";
|
|
2397
2392
|
import { Toaster } from "sonner";
|
|
2398
2393
|
import "./globals.css";
|
|
2399
2394
|
|
|
2400
2395
|
const heading = ${c}({ subsets: ["latin"], variable: "--font-heading" });
|
|
2401
|
-
const body = ${
|
|
2396
|
+
const body = ${m}({ subsets: ["latin"], variable: "--font-body" });
|
|
2402
2397
|
|
|
2403
2398
|
export const metadata: Metadata = { title: "${o}", description: "Built with Mistflow" };
|
|
2404
2399
|
|
|
@@ -2409,63 +2404,63 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2409
2404
|
</html>
|
|
2410
2405
|
);
|
|
2411
2406
|
}
|
|
2412
|
-
`}function
|
|
2413
|
-
`)}function
|
|
2407
|
+
`}function Xt(t,...e){let r=JSON.stringify(t).toLowerCase();return e.some(o=>r.includes(o.toLowerCase()))}var rl={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 ir(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[r,o]of Object.entries(rl))if(e.includes(r))return o;return"Circle"}function vt(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 n=i.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!n)continue;let a=n.startsWith("/")?n:"/"+n;e.includes(a)||e.push(a)}let r=e.filter(i=>i==="/"),o=e.filter(i=>i!=="/"),s=[];s.push('import { NextRequest, NextResponse } from "next/server";'),s.push(""),s.push("const PUBLIC_PREFIXES = [");for(let i of o)s.push(' "'+i+'",');return s.push("];"),s.push(""),r.length>0&&(s.push('const PUBLIC_EXACT = ["'+r.join('", "')+'"];'),s.push("")),s.push("export function middleware(req: NextRequest) {"),s.push(" const { pathname, search } = req.nextUrl;"),s.push(""),r.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(`
|
|
2408
|
+
`)}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"],o=(t.pages??[]).filter(l=>{let c=l.path??l.route??"";return c==="/"||c===""||c.includes("[")||c.replace(/^\//,"").split("/").length>1?!1:!e.some(p=>c.startsWith(p))}).map(l=>{let c=l.path??l.route??"",m=c.startsWith("/")?c:"/"+c,p=l.name??vt(c.replace(/^\//,"")),u=ir(p);return{label:p,href:m,icon:u}});o.some(l=>l.href==="/dashboard")||o.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let s=t.authModel==="none",i=[...new Set(o.map(l=>l.icon))];s||i.push("LogOut");let n=vt(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 { "+i.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let c of o)l.push(' { label: "'+c.label+'", href: "'+c.href+'", icon: '+c.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+n+"</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(`
|
|
2414
2409
|
`)}}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";'),s||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 o)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">'+n+"</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>"),s||(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">'+n+"</span>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),{path:"components/sidebar.tsx",content:a.join(`
|
|
2415
|
-
`)}}function
|
|
2416
|
-
`)}function
|
|
2417
|
-
`)}let r=
|
|
2418
|
-
`)}if(r){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">'+
|
|
2410
|
+
`)}}function il(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,r=t.defaultRole??e[0],o=[];o.push("export type Role = "+e.map(s=>'"'+s+'"').join(" | ")+";"),o.push(""),o.push("export const ROLES = ["+e.map(s=>'"'+s+'"').join(", ")+"] as const;"),o.push(""),o.push('export const DEFAULT_ROLE: Role = "'+r+'";'),o.push(""),o.push("export const ROLE_LABELS: Record<Role, string> = {");for(let s of e){let i=s.charAt(0).toUpperCase()+s.slice(1);o.push(' "'+s+'": "'+i+'",')}return o.push("};"),o.push(""),o.push("export function getUserRole(user: Record<string, unknown>): Role {"),o.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),o.push(" if (ROLES.includes(role as Role)) return role as Role;"),o.push(" return DEFAULT_ROLE;"),o.push("}"),o.push(""),o.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),o.push(" if (!userRole) return false;"),o.push(" const allowed = Array.isArray(required) ? required : [required];"),o.push(" return allowed.includes(userRole as Role);"),o.push("}"),o.push(""),o.join(`
|
|
2411
|
+
`)}function al(t){let e=vt(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(`
|
|
2412
|
+
`)}let r=t.publicPages?.includes("/"),o=t.design?.landingTone;if(r&&o){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(`
|
|
2413
|
+
`)}if(r){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(`
|
|
2419
2414
|
`)}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(`
|
|
2420
|
-
`)}function
|
|
2421
|
-
`)}function
|
|
2422
|
-
`)}function
|
|
2423
|
-
`)}function
|
|
2424
|
-
`)}function
|
|
2425
|
-
`)}function
|
|
2426
|
-
`)}async function
|
|
2415
|
+
`)}function ll(t,e){let r=t.authModel==="none",o=[];r||(o.push('import { Suspense } from "react";'),o.push('import { headers } from "next/headers";'),o.push('import { redirect } from "next/navigation";'),o.push('import { auth } from "@/lib/auth";'),o.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?o.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&o.push('import Sidebar from "@/components/sidebar";'),!r&&t.roles&&t.roles.length>0&&o.push('import { getUserRole } from "@/lib/roles";'),o.push(""),o.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),r?o.push(' const user = { name: "Guest", email: "" };'):(o.push(" const session = await auth.api.getSession({ headers: await headers() });"),o.push(' if (!session) redirect("/login");'),o.push(""),t.roles&&t.roles.length>0?(o.push(" const role = getUserRole(session.user as Record<string, unknown>);"),o.push(" const user = { name: session.user.name, email: session.user.email, role };")):(o.push(" const user = {"),o.push(" name: session.user.name,"),o.push(" email: session.user.email,"),o.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),o.push(" };"))),o.push("");let s=r?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(o.push(" return ("),o.push(' <div className="min-h-screen">'),o.push(" <TopNav user={user} />"),o.push(' <main className="mx-auto max-w-7xl p-6">'+s+"{children}</main>"),o.push(" </div>"),o.push(" );")):t.navStyle==="none"?(o.push(" return ("),o.push(' <div className="min-h-screen">'),o.push(' <main className="mx-auto max-w-5xl p-6">'+s+"{children}</main>"),o.push(" </div>"),o.push(" );")):(o.push(" return ("),o.push(' <div className="flex flex-col md:flex-row min-h-screen">'),o.push(" <Sidebar user={user} />"),o.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+s+"{children}</main>"),o.push(" </div>"),o.push(" );")),o.push("}"),o.push(""),o.join(`
|
|
2416
|
+
`)}function cl(t){let e=vt(t.name),r=t.dataModel??[],o=[];if(r.length>0){let s=r.map(n=>ir(n.entity??n.name??"item")),i=[...new Set(s)];o.push('import { Card, CardContent } from "@/components/ui/card";'),o.push("import { "+i.join(", ")+' } from "lucide-react";'),o.push("")}if(o.push("export default function DashboardPage() {"),o.push(" return ("),o.push(' <div className="space-y-6">'),o.push(" <div>"),o.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),t.summary&&o.push(' <p className="mt-1 text-muted-foreground">'+t.summary+"</p>"),o.push(" </div>"),r.length>0){o.push(' <div className="rounded-lg border p-8 text-center">'),o.push(' <h2 className="text-lg font-semibold">Get started</h2>'),o.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),o.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let s of r){let i=s.entity??s.name??"Item",n=ir(i),a=vt(i.replace(/_/g,"-"));o.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),o.push(" <"+n+' className="h-5 w-5 text-muted-foreground" />'),o.push(' <span className="text-sm font-medium">Add your first '+a+"</span>"),o.push(" </div>")}o.push(" </div>"),o.push(" </div>")}return o.push(" </div>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
|
|
2417
|
+
`)}function dl(t,e=!1){if(!t.multiTenant)return null;let r=[];return e?(r.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = pgTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),r.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = pgTable(")):(r.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),r.push('import { sql } from "drizzle-orm";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = sqliteTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = sqliteTable(")),r.push(' "org_member",'),r.push(" {"),r.push(' id: text("id").primaryKey(),'),r.push(' orgId: text("org_id").notNull().references(() => organization.id),'),r.push(' userId: text("user_id").notNull().references(() => user.id),'),r.push(' role: text("role").notNull(),'),e?r.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):r.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(" },"),r.push(" (table) => ({"),r.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),r.push(' userIdx: index("org_member_user_idx").on(table.userId),'),r.push(" }),"),r.push(");"),r.push(""),r.join(`
|
|
2418
|
+
`)}function pl(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(`
|
|
2419
|
+
`)}function ul(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(`
|
|
2420
|
+
`)}function ml(t,e,r){let o=[],s=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");o.push(`# ${s}`),o.push(""),e?.summary&&(o.push(e.summary),o.push(""));let i=e?.features??[];if(i.length>0){o.push("## Features"),o.push("");for(let l of i){let c=l.description?` \u2014 ${l.description}`:"";o.push(`- **${l.name}**${c}`)}o.push("")}o.push("## Tech Stack"),o.push(""),o.push("| Layer | Technology |"),o.push("|-------|------------|"),o.push("| Framework | Next.js 15 (App Router) |"),o.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),o.push("| Auth | Better Auth (email/password, social login) |"),o.push("| Styling | Tailwind CSS + shadcn/ui |"),o.push("| Deployment | Mistflow Cloud |"),r.hasStripe&&o.push("| Payments | Stripe |"),r.hasResend&&o.push("| Email | Resend + React Email |"),r.hasStorage&&o.push("| File Storage | Mistflow Cloud (managed blob storage) |"),r.hasAdmin&&o.push("| Admin | Better Auth admin plugin |"),r.hasAI&&o.push("| AI | Vercel AI SDK + OpenAI |"),o.push("");let n=e?.pages??[];if(n.length>0){o.push("## Pages"),o.push(""),o.push("| Route | Description |"),o.push("|-------|-------------|");for(let l of n){let c=l.path??l.route??l.name??"",m=l.description??"";o.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${m} |`)}o.push("")}let a=e?.dataModel??[];if(a.length>0){o.push("## Data Model"),o.push("");for(let l of a){let c=l.entity??l.name??"Unknown";if(o.push(`### ${c}`),o.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")o.push(`Fields: ${l.fields.join(", ")}`);else{o.push("| Field | Type |"),o.push("|-------|------|");for(let m of l.fields)o.push(`| ${m.name} | ${m.type} |`)}o.push("")}}}return o.push("## Getting Started"),o.push(""),o.push("### Prerequisites"),o.push(""),o.push("- Node.js 20+"),o.push("- npm"),o.push(""),o.push("### Install"),o.push(""),o.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),o.push(""),o.push("```bash"),o.push("npm install"),o.push("```"),o.push(""),o.push("### Set up environment"),o.push(""),o.push("Copy `.env.example` to `.env.local` and fill in the values:"),o.push(""),o.push("```bash"),o.push("cp .env.example .env.local"),o.push("```"),o.push(""),o.push("| Variable | Description | Required |"),o.push("|----------|-------------|----------|"),r.isNeon?o.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(o.push("| `TURSO_URL` | Database connection URL | Yes |"),o.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),o.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),r.hasStripe&&(o.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),o.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),o.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),r.hasResend&&(o.push("| `RESEND_API_KEY` | Resend API key | Yes |"),o.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),r.hasStorage&&(o.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),o.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),r.hasAI&&o.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),o.push(""),o.push("### Local database"),o.push(""),r.isNeon?(o.push("For local development, start a local Postgres server:"),o.push(""),o.push("```bash"),o.push("# Using Docker:"),o.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),o.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),o.push("```")):(o.push("For local development, start a local Turso server:"),o.push(""),o.push("```bash"),o.push("npx turso dev"),o.push("```")),o.push(""),o.push("Then set up the database:"),o.push(""),o.push("```bash"),o.push("npm run db:push"),o.push("```"),o.push(""),o.push("### Run"),o.push(""),o.push("```bash"),o.push("npm run dev"),o.push("```"),o.push(""),o.push("Open [http://localhost:3000](http://localhost:3000)."),o.push(""),o.push("## Project Structure"),o.push(""),o.push("```"),o.push("app/"),o.push(" (auth)/ Login and registration pages"),o.push(" (dashboard)/ Authenticated app pages"),r.hasAdmin&&o.push(" (admin)/ Admin panel pages"),o.push(" api/ API routes (auth, health, webhooks)"),o.push(" layout.tsx Root layout with fonts and providers"),o.push(" globals.css Design tokens and Tailwind config"),o.push("components/ Reusable UI components"),o.push("db/"),o.push(" schema/ Database table definitions"),o.push(" index.ts Schema exports"),o.push("lib/"),o.push(" auth.ts Better Auth server config"),o.push(" auth-client.ts Better Auth client config"),o.push(` db.ts ${r.isNeon?"Postgres":"SQLite"} database connection`),r.hasStripe&&o.push(" stripe.ts Stripe client"),r.hasResend&&(o.push(" resend.ts Resend client"),o.push(" email.ts Email send helpers")),r.hasStorage&&o.push(" storage.ts File upload/download helpers"),r.hasAI&&o.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),r.hasResend&&o.push("emails/ React Email templates"),o.push("```"),o.push(""),o.push("## Deploy"),o.push(""),o.push("Deploy to production with Mistflow:"),o.push(""),o.push("```"),o.push("# In your AI editor (Claude Code, Cursor, etc.):"),o.push("mist_deploy action='deploy'"),o.push("```"),o.push(""),o.push("Your app will be live at `https://<app-name>.mistflow.app`."),o.push(""),e?.design&&(o.push("## Design"),o.push(""),e.design.tone&&o.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(o.push(`- **Heading font**: ${e.design.fonts.heading}`),o.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&o.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&o.push(`- **Border radius**: ${e.design.borderRadius}`),o.push("")),o.push("---"),o.push(""),o.push("Built with [Mistflow](https://mistflow.ai)"),o.push(""),o.join(`
|
|
2421
|
+
`)}async function hl(t,e){let{name:r,plan:o,path:s,planId:i}=t;if(!s)return d("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(!qa(s))return d(`mist_init 'path' must be an absolute path \u2014 received '${s}'. Pass the full absolute path to the target directory.`,!0);let n=Rn(s),a=o;if(!a&&i){let g=Ha(i);if(!g)return d(`No plan found for planId '${i}'. Call mist_plan first, or pass the plan object inline.`,!0);a=g.plan}let l=a?.design,c=a?Xt(a,"stripe","payment","billing","subscription","checkout","pricing"):!1,m=!0,p=a?Xt(a,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,u=a?Xt(a,"admin panel","admin dashboard","admin management"):!1,w=a?Xt(a,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,N=a,x=!0;if(!Ka(n))return d(`A project already exists at this location (${n}). 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);nr(n,{recursive:!0});try{let g=ye(wt(n),".mistflow","mockups");if(ze(g)){let k=_n(g).filter(E=>E.endsWith(".html"));if(k.length>0){let E=ye(n,".mistflow","mockups");nr(E,{recursive:!0});for(let V of k)Fa(ye(g,V),ye(E,V));console.error(`Copied ${k.length} mockup file(s) into project`)}}}catch(g){console.error("Could not copy mockup files:",g instanceof Error?g.message:g)}let S=null;try{S=await Uo("nextjs")}catch(g){console.error("Could not fetch scaffold from API, using minimal scaffold:",g instanceof Error?g.message:g)}if(S){let g=r.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let P of S.files){if(P.path==="package.json"||P.path==="middleware.ts"||P.path==="components/sidebar.tsx"||P.path==="components/topnav.tsx"||P.path==="app/(dashboard)/layout.tsx"||P.path==="app/(dashboard)/page.tsx"||P.path==="app/(dashboard)/dashboard/page.tsx"||!c&&(P.path.includes("stripe")||P.path.includes("webhook/stripe"))||!m&&(P.path.includes("resend")||P.path.includes("emails/"))||!u&&(P.path.includes("(admin)")||P.path.includes("admin-sidebar"))||x&&(P.path==="lib/db.ts"||P.path==="lib/auth.ts"||P.path==="drizzle.config.ts"||P.path==="db/schema/auth.ts"))continue;let j=P.content.replace(/\{\{APP_NAME\}\}/g,r).replace(/\{\{WORKER_NAME\}\}/g,g);if(x&&P.path==="next.config.ts"&&(j=j.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),P.path==="next.config.ts"){let X=Ga(n);X&&(console.error(`[init] Project is inside monorepo at ${X} \u2014 adding outputFileTracingRoot`),j.includes("outputFileTracingRoot")||(j=j.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
2427
2422
|
import { dirname } from "path";
|
|
2428
2423
|
import { fileURLToPath } from "url";
|
|
2429
2424
|
|
|
2430
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));`),
|
|
2431
|
-
images: {`)))}!
|
|
2432
|
-
`)),
|
|
2433
|
-
`)),
|
|
2434
|
-
`)),
|
|
2435
|
-
`));let
|
|
2436
|
-
`))}}else
|
|
2437
|
-
`)),m&&(
|
|
2438
|
-
`)),
|
|
2439
|
-
`))),
|
|
2440
|
-
`)),
|
|
2441
|
-
`))),
|
|
2442
|
-
`)),
|
|
2443
|
-
`)));let
|
|
2425
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));`),j=j.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
2426
|
+
images: {`)))}!u&&P.path.includes("sidebar")&&(j=j.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),j=j.replace(/, Shield/g,"")),B(n,P.path,j)}let k={...S.dependencies},E={...S.devDependencies};if(k["drizzle-zod"]||(k["drizzle-zod"]="^0.5.1"),x&&(delete k["@libsql/client"],k["@neondatabase/serverless"]="^0.10.0",E["@electric-sql/pglite"]="^0.2.0"),c&&(k.stripe="^17.0.0"),m&&(k.resend="^4.0.0",k["@react-email/components"]="^0.0.31"),w&&(k.ai="^4.0.0",k["@ai-sdk/openai"]="^1.0.0",k.openai="^4.0.0"),B(n,"package.json",JSON.stringify({name:r,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:E,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)),S.methodology){let P=S.methodology;x&&(P=P.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")),P=tr(P),B(n,"AGENTS.md",P),B(n,"CLAUDE.md",P)}let Q=a?.designMd;if(Q&&B(n,"DESIGN.md",Q),x){B(n,"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(`
|
|
2427
|
+
`)),B(n,"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(`
|
|
2428
|
+
`)),B(n,"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(`
|
|
2429
|
+
`)),B(n,"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(`
|
|
2430
|
+
`));let P=a.defaultRole??"user";B(n,"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: "${P}" }), 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(`
|
|
2431
|
+
`))}}else B(n,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0},null,2));let f=a?.designMd;B(n,"app/globals.css",Za(l,f)),B(n,"app/layout.tsx",ol(r,l,N?.language)),B(n,"README.md",ml(r,a,{hasStripe:c,hasResend:m,hasStorage:p,hasAdmin:u,hasAI:w,isNeon:x})),B(n,"contracts/README.md",er());let A=a?.dataModel??[],U=new Set,H=0;for(let g of A){let k=g.entity??g.name;if(!k||typeof k!="string")continue;let E=rr(k);U.has(E)||(U.add(E),B(n,E,or(k)),H++)}H===0&&B(n,"contracts/.gitkeep","");let _=[],K=a?.publicPages;if(Array.isArray(K))_=K;else if(typeof K=="string"){try{_=JSON.parse(K)}catch{_=[]}Array.isArray(_)||(_=[])}if(!_.includes("/")){let g=a?.steps?.some(E=>{let V=((E.name??"")+" "+(E.description??"")).toLowerCase();return V.includes("landing")||V.includes("marketing")||V.includes("homepage")}),k=a?.pages?.some(E=>E.path==="/");(g||k)&&(_=["/",..._])}let F={name:r,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},T=nl(F);T&&B(n,"middleware.ts",T);let R=sl(F);R&&B(n,R.path,R.content);let C=il(F);if(C&&B(n,"lib/roles.ts",C),B(n,"app/page.tsx",al(F)),B(n,"app/(dashboard)/layout.tsx",ll(F,u)),B(n,"app/(dashboard)/dashboard/page.tsx",cl(F)),F.multiTenant){let g=dl(F,x);g&&B(n,"db/schema/organization.ts",g);let k=pl(F);k&&B(n,"lib/org.ts",k);let E=ul(F);E&&B(n,"components/org-switcher.tsx",E)}B(n,"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)),c&&B(n,"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(`
|
|
2432
|
+
`)),m&&(B(n,"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(`
|
|
2433
|
+
`)),B(n,"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(`
|
|
2434
|
+
`))),p&&(B(n,"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(`
|
|
2435
|
+
`)),B(n,"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(`
|
|
2436
|
+
`))),w&&(B(n,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
|
|
2437
|
+
`)),B(n,"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(`
|
|
2438
|
+
`)));let I=Array.isArray(a?.integrations)?a.integrations.map(g=>({name:g.name,preset:g.preset,envVars:g.envVars??[]})):[],L={};w&&!I.some(g=>g.envVars?.some(k=>k.key==="OPENAI_API_KEY"))&&(L.OPENAI_API_KEY={description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"});for(let g of I)for(let k of g.envVars??[])L[k.key]||(L[k.key]={description:k.description,setupUrl:k.setupUrl,...g.name?{integration:g.name}:{}});let M={name:r,methodologyVersion:S?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},plan:Array.isArray(a?.steps)?{...a,steps:a.steps.map(g=>({number:g.number,name:g.name??g.title,description:g.description,entities:g.entities,pages:g.pages,features:g.features,status:"pending"}))}:a,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...c?{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(L).length>0?{required:L}:{}},authModel:a?.authModel??"email",roles:a?.roles??null,navStyle:a?.navStyle??"sidebar",multiTenant:a?.multiTenant??!1,hasAdmin:u,hasResend:m,hasStorage:p,hasAI:w,deploy:null};B(n,"mistflow.json",JSON.stringify(M,null,2));let D=za(32).toString("hex"),$=c?`
|
|
2444
2439
|
# Stripe
|
|
2445
2440
|
STRIPE_SECRET_KEY=
|
|
2446
2441
|
STRIPE_WEBHOOK_SECRET=
|
|
2447
2442
|
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
|
2448
|
-
`:"",
|
|
2443
|
+
`:"",z=m?`
|
|
2449
2444
|
# Email (Resend)
|
|
2450
2445
|
RESEND_API_KEY=
|
|
2451
2446
|
EMAIL_FROM=onboarding@resend.dev
|
|
2452
|
-
`:"",
|
|
2447
|
+
`:"",J=p?`
|
|
2453
2448
|
# File Storage (Mistflow managed)
|
|
2454
2449
|
MISTFLOW_API_KEY=
|
|
2455
2450
|
MISTFLOW_PROJECT_ID=
|
|
2456
|
-
`:"",
|
|
2451
|
+
`:"",ee=w?`
|
|
2457
2452
|
# AI (get your key at https://platform.openai.com/api-keys)
|
|
2458
2453
|
OPENAI_API_KEY=
|
|
2459
|
-
`:"",
|
|
2454
|
+
`:"",ve=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2460
2455
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2461
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,
|
|
2456
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,ke=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2462
2457
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2463
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;
|
|
2464
|
-
AUTH_SECRET=${
|
|
2465
|
-
${
|
|
2458
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;B(n,".env.local",`${ve}
|
|
2459
|
+
AUTH_SECRET=${D}
|
|
2460
|
+
${$}${z}${J}${ee}`),B(n,".env.example",`${ke}
|
|
2466
2461
|
AUTH_SECRET=your-secret-here
|
|
2467
|
-
${
|
|
2468
|
-
${le}=${_}`}wr(te,ve)}try{let{getBaseUrl:te,getAuthHeaders:ve}=await Promise.resolve().then(()=>(be(),Zr)),le=ve(),_=a?.features,p=a?.steps,g={};Array.isArray(_)&&_.length>0&&(g.features=_.map(k=>k.name)),a&&(g.plan=a),Array.isArray(p)&&p.length>0&&(g.provenance=p.map(k=>({feature:k.name??k.title??`Step ${k.number??"?"}`,user_intent:(k.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(g).length>0&&await fetch(`${te()}/api/projects/${encodeURIComponent(xe)}/state`,{method:"PUT",headers:{...le,"Content-Type":"application/json"},body:JSON.stringify(g)})}catch{}Q[Q.length-1].message=`Registered as ${xe.slice(0,8)}`}catch(b){let C=b instanceof Error?b.message:String(b);console.error("Could not register project on backend:",C),me=`Project created locally but NOT registered on Mistflow servers (${C}). Deploy will auto-register it.`,Q[Q.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}fe("register",Date.now()-rt),ne("git","Initializing git repository...");let bt=Date.now();try{let b=dl(n);await b.init(),await b.add("."),await b.commit("Initial Mistflow project setup"),Q[Q.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),Q[Q.length-1].message="Git init skipped"}fe("git",Date.now()-bt);let Fe=Q.reduce((b,C)=>b+(C.durationMs??0),0),O={projectPath:n,projectId:xe,status:"awaiting_install"},Y=Q.map(b=>{let C=b.durationMs?` (${(b.durationMs/1e3).toFixed(1)}s)`:"";return`${b.message}${C}`});O.progress=Y,O.totalSetupTime=`${(Fe/1e3).toFixed(1)}s`;let ye=[];xe||ye.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),me&&(O.registrationWarning=me),ye.length>0&&(O.warnings=ye);let Me=`NEXT: Call mist_install({ projectPath: "${n}" }). 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: "${n}" }) to build the first plan step.`;return O.nextAction=xe?Me:`${Me} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,d(JSON.stringify(O))}var Yn={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:ul,handler:Dl};import{z as kr}from"zod";import{existsSync as Mt,readFileSync as Sr,writeFileSync as xr,mkdirSync as Zl}from"fs";import{join as gt,resolve as ec,dirname as tc}from"path";be();import{createConnection as oc}from"net";var Qn="\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 Xn=`# Consumer Warm Archetype
|
|
2462
|
+
${$}${z}${J}${ee}`);let Y=[],Te=(g,k)=>{Y.push({phase:g,message:k})},Pe=(g,k)=>{let E=Y.find(V=>V.phase===g&&!V.durationMs);E&&(E.durationMs=k)};if(e){let g=xe(e.server,e.progressToken,()=>Y[Y.length-1]?.message??"Setting up project...");e.cleanup=()=>g.stop()}let Ce=N?.requestedSubdomain||void 0,pe,We;Te("register","Registering project on Mistflow...");let Ge=Date.now();try{let g=await pt(r,void 0,"neon",Ce);pe=g.id;let k=ye(n,"mistflow.json"),E=JSON.parse(Zt(k,"utf-8"));if(E.projectId=pe,sr(k,JSON.stringify(E,null,2)),mt(n,ht(pe,r)),g.managed_env&&Object.keys(g.managed_env).length>0){let V=ye(n,".env.local"),Z=ze(V)?Zt(V,"utf-8"):"";for(let[Q,P]of Object.entries(g.managed_env)){let j=new RegExp(`^${Q}=.*$`,"m");j.test(Z)?Z=Z.replace(j,`${Q}=${P}`):Z+=`
|
|
2463
|
+
${Q}=${P}`}sr(V,Z)}try{let{getBaseUrl:V,getAuthHeaders:Z}=await Promise.resolve().then(()=>(le(),Lr)),Q=Z(),P=a?.features,j=a?.steps,X={};Array.isArray(P)&&P.length>0&&(X.features=P.map(te=>te.name)),a&&(X.plan=a),Array.isArray(j)&&j.length>0&&(X.provenance=j.map(te=>({feature:te.name??te.title??`Step ${te.number??"?"}`,user_intent:(te.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(X).length>0&&await fetch(`${V()}/api/projects/${encodeURIComponent(pe)}/state`,{method:"PUT",headers:{...Q,"Content-Type":"application/json"},body:JSON.stringify(X)})}catch{}Y[Y.length-1].message=`Registered as ${pe.slice(0,8)}`}catch(g){let k=g instanceof Error?g.message:String(g);console.error("Could not register project on backend:",k),We=`Project created locally but NOT registered on Mistflow servers (${k}). Deploy will auto-register it.`,Y[Y.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}Pe("register",Date.now()-Ge),Te("git","Initializing git repository...");let ue=Date.now();try{let g=Wa(n);await g.init(),await g.add("."),await g.commit("Initial Mistflow project setup"),Y[Y.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),Y[Y.length-1].message="Git init skipped"}Pe("git",Date.now()-ue);let h=Y.reduce((g,k)=>g+(k.durationMs??0),0),b={projectPath:n,projectId:pe,status:"awaiting_install"},y=Y.map(g=>{let k=g.durationMs?` (${(g.durationMs/1e3).toFixed(1)}s)`:"";return`${g.message}${k}`});b.progress=y,b.totalSetupTime=`${(h/1e3).toFixed(1)}s`;let v=[];pe||v.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),We&&(b.registrationWarning=We),v.length>0&&(b.warnings=v);let q=`NEXT: Call mist_install({ projectPath: "${n}" }). 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: "${n}" }) to build the first plan step.`;return b.nextAction=pe?q:`${q} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,d(JSON.stringify(b))}var En={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:Va,handler:hl};import{z as oo}from"zod";import{existsSync as xt,readFileSync as lr,writeFileSync as ar,mkdirSync as $l}from"fs";import{join as ot,resolve as Fl,dirname as ql}from"path";le();import{createConnection as Bl}from"net";var Nn="\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 Dn=`# Consumer Warm Archetype
|
|
2469
2464
|
|
|
2470
2465
|
Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
|
|
2471
2466
|
|
|
@@ -2632,7 +2627,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
|
|
|
2632
2627
|
- Small touch targets. Phone-first means \`h-12\` minimum.
|
|
2633
2628
|
- Empty states that just say "No data." Be encouraging.
|
|
2634
2629
|
- Dark theme as default. Consumer warm apps default to light.
|
|
2635
|
-
`;var
|
|
2630
|
+
`;var jn=`# Consumer Bold Archetype
|
|
2636
2631
|
|
|
2637
2632
|
Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
|
|
2638
2633
|
|
|
@@ -2803,7 +2798,7 @@ Social/competitive apps need an activity feed:
|
|
|
2803
2798
|
- Card-only layouts with no hierarchy. Use hero cards + supporting cards.
|
|
2804
2799
|
- Missing achievement/progress systems. The gamification IS the product.
|
|
2805
2800
|
- Light-touch buttons. CTAs should be unmissable.
|
|
2806
|
-
`;var
|
|
2801
|
+
`;var On=`# Professional Clean Archetype
|
|
2807
2802
|
|
|
2808
2803
|
Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
|
|
2809
2804
|
|
|
@@ -3015,7 +3010,7 @@ h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
|
|
|
3015
3010
|
- Missing status workflows. Every booking/appointment needs a clear state machine.
|
|
3016
3011
|
- Dark theme as default. Clients associate light themes with professionalism.
|
|
3017
3012
|
- Emoji in the UI. Professional context.
|
|
3018
|
-
`;var
|
|
3013
|
+
`;var Mn=`# Education Structured Archetype
|
|
3019
3014
|
|
|
3020
3015
|
Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
|
|
3021
3016
|
|
|
@@ -3215,7 +3210,7 @@ border-2 border-destructive bg-destructive/5 rounded-xl p-4
|
|
|
3215
3210
|
- Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
|
|
3216
3211
|
- Long lesson pages with no progress indicator. Users need to know where they are.
|
|
3217
3212
|
- Multiple competing elements per view. One thing at a time. One question at a time.
|
|
3218
|
-
`;var
|
|
3213
|
+
`;var Un=`# Marketplace Browse Archetype
|
|
3219
3214
|
|
|
3220
3215
|
Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
|
|
3221
3216
|
|
|
@@ -3439,7 +3434,7 @@ border-b border-border/30 py-4
|
|
|
3439
3434
|
- Small product images. The image is the primary decision-making element.
|
|
3440
3435
|
- No empty state for zero search results. "No results for 'xyz'. Try broader terms."
|
|
3441
3436
|
- Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
|
|
3442
|
-
`;var
|
|
3437
|
+
`;var Ln=`# SaaS Analytical Archetype
|
|
3443
3438
|
|
|
3444
3439
|
Component-level design guidance for B2B SaaS tools, CRMs, analytics dashboards, admin panels, ops tooling, and team productivity apps. This is the biggest category \u2014 most apps that don't fit consumer, marketplace, or booking archetypes land here.
|
|
3445
3440
|
|
|
@@ -3620,7 +3615,7 @@ The most recognizable B2B SaaS landing pattern.
|
|
|
3620
3615
|
- **Inter as the only font.** Pair it with a distinctive heading font or swap it entirely.
|
|
3621
3616
|
- **Centered text + centered image below.** The most overused AI hero. Use split or offset layouts.
|
|
3622
3617
|
- **Animation on every element.** Efficient motion only: hero entrance, card reveals on scroll, number counters. Nothing else.
|
|
3623
|
-
`;var
|
|
3618
|
+
`;var $n=`# Content Editorial Archetype
|
|
3624
3619
|
|
|
3625
3620
|
Component-level design guidance for blogs, newsletters, magazines, publications, documentation sites, knowledge bases, and wiki-style content tools. Substack, The Verge, Medium, Linear's changelog, Stripe's docs are the reference bar.
|
|
3626
3621
|
|
|
@@ -3827,7 +3822,7 @@ Below the hero: 3 featured pieces laid out as a horizontal strip with **oversize
|
|
|
3827
3822
|
- **Dark mode as default for a reading tool.** Offer it as a toggle, not the default.
|
|
3828
3823
|
- **Flashy motion while reading.** Scroll hijacking, parallax on body text, animated backgrounds behind paragraphs \u2014 all break reading flow.
|
|
3829
3824
|
- **More than 2 fonts.** Heading + body is enough. Adding a third font for captions or metadata dilutes the identity.
|
|
3830
|
-
`;var
|
|
3825
|
+
`;var Fn=`# Devtool Technical Archetype
|
|
3831
3826
|
|
|
3832
3827
|
Component-level design guidance for developer tools, APIs, CLIs, SDKs, infrastructure platforms, monitoring/observability, AI/ML platforms, deployment targets, and CI/CD tooling. Vercel, Linear, Supabase, Sentry, Warp, Raycast, Cursor, Neon, Anthropic Console are the reference bar.
|
|
3833
3828
|
|
|
@@ -4016,7 +4011,7 @@ Numbers styled as terminal output: \`> 47,293 deploys this week\`, \`> 99.98% up
|
|
|
4016
4011
|
- **Marketing testimonials.** Replace with GitHub star count, StackOverflow mentions, a few short founder-quoted specifics ("Cut our deploy time from 12min to 18sec" from a named engineer at a known company).
|
|
4017
4012
|
- **Feature cards with rocket / lightning / puzzle icons.** Use technical icons (terminal, code, database, network) or skip icons entirely.
|
|
4018
4013
|
- **Motion on code blocks** while the user is trying to read them. Type out ONCE on load, then leave them alone.
|
|
4019
|
-
`;var
|
|
4014
|
+
`;var qn=`# Creative Showcase Archetype
|
|
4020
4015
|
|
|
4021
4016
|
Component-level design guidance for portfolios, design agencies, creative studios, photographers, artists, architects, filmmakers, and any brand whose primary selling point is "look at the work we've made." Apple, Dribbble, Behance, Pentagram, IDEO are the reference bar.
|
|
4022
4017
|
|
|
@@ -4233,7 +4228,7 @@ Premium agency touch: on first load, a full-screen loading component shows the s
|
|
|
4233
4228
|
- **Scroll hijacking through the whole site.** Use sparingly \u2014 one or two scroll-pinned sections maximum.
|
|
4234
4229
|
- **Mystery-meat navigation.** Clever is bad here. "Work / About / Contact" is fine. Don't make visitors guess.
|
|
4235
4230
|
- **No contact info.** The primary purpose of this site is to generate inquiries. Make it stupid-easy to contact you.
|
|
4236
|
-
`;var
|
|
4231
|
+
`;var Bn=`# Finance Clarity Archetype
|
|
4237
4232
|
|
|
4238
4233
|
Component-level design guidance for fintech apps, invoicing tools, expense trackers, budget apps, payroll, accounting software, banking dashboards, and any product where **money is the primary data type**. Stripe, Wise, Revolut, Mercury, Brex, QuickBooks, Ramp are the reference bar.
|
|
4239
4234
|
|
|
@@ -4452,7 +4447,7 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
|
|
|
4452
4447
|
- **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
|
|
4453
4448
|
- **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
|
|
4454
4449
|
- **Confidence-shaking UX:** progress bars that stall, skeletons that flash between states, tiny fonts for fine print. Users are nervous about their money; give them stability.
|
|
4455
|
-
`;var
|
|
4450
|
+
`;var zn={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Dn},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:jn},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:On},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Mn},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Un},"saas-analytical":{id:"saas-analytical",name:"SaaS Analytical",description:"B2B SaaS, CRM, analytics, admin panels, ops tooling, team productivity (Linear, Notion, Stripe reference bar)",content:Ln},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:$n},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:Fn},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:qn},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:Bn}};var Nu=Object.keys(zn);function Hn(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return zn[e]}var Wn=`# Landing Page Rules
|
|
4456
4451
|
|
|
4457
4452
|
These rules apply to every landing page. They are non-negotiable.
|
|
4458
4453
|
|
|
@@ -4849,7 +4844,7 @@ app/
|
|
|
4849
4844
|
\`\`\`
|
|
4850
4845
|
|
|
4851
4846
|
Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
|
|
4852
|
-
`;var
|
|
4847
|
+
`;var Gn=`# Design Doctrine
|
|
4853
4848
|
|
|
4854
4849
|
This is the standard for every UI you generate. It is not aspirational. It is the floor.
|
|
4855
4850
|
|
|
@@ -4915,7 +4910,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
|
|
|
4915
4910
|
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.**
|
|
4916
4911
|
|
|
4917
4912
|
If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
|
|
4918
|
-
`;var
|
|
4913
|
+
`;var Vn=`# Typography
|
|
4919
4914
|
|
|
4920
4915
|
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.
|
|
4921
4916
|
|
|
@@ -5003,7 +4998,7 @@ Pick exactly one:
|
|
|
5003
4998
|
- **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
|
|
5004
4999
|
|
|
5005
5000
|
Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
|
|
5006
|
-
`;var
|
|
5001
|
+
`;var Kn="# Color\n\nColor is a commitment, not a palette swatch. The #1 failure mode in AI-generated landings is an evenly-distributed palette: a little emerald here, a little amber there, a gradient, a badge. That's visual hedging \u2014 it signals \"I couldn't pick a point of view.\"\n\nPick one color. Use it with intent.\n\n## The Token System\n\nEvery color on every screen goes through a CSS variable defined in `globals.css`. You do not hand-pick hex values in JSX. You do not use Tailwind palette utilities (`bg-emerald-500`, `text-blue-600`, `border-slate-200`). If a color isn't in the token scheme, it doesn't exist for this app.\n\n### Core tokens\n\n- `--color-background` \u2014 page background\n- `--color-foreground` \u2014 default body text\n- `--color-card` \u2014 elevated surface (cards, panels)\n- `--color-card-foreground` \u2014 text on cards\n- `--color-muted` \u2014 low-emphasis surface fill\n- `--color-muted-foreground` \u2014 secondary text (\u2265 WCAG AA contrast vs background)\n- `--color-border` \u2014 subtle dividers\n- `--color-input` \u2014 form input borders\n- `--color-popover` / `--color-popover-foreground` \u2014 dropdowns, tooltips, menus\n\n### Interactive tokens\n\n- `--color-primary` \u2014 primary CTAs, links, active tab, focus ring\n- `--color-primary-foreground` \u2014 text on primary (derived for WCAG AA contrast)\n- `--color-ring` \u2014 focus outline (same hue as primary)\n- `--color-secondary` / `--color-secondary-foreground` \u2014 quieter than primary, more than muted\n- `--color-accent` / `--color-accent-foreground` \u2014 hover states on neutrals\n\n### Semantic tokens\n\n- `--color-success` \u2014 confirmation, \"verified\" banners, positive states\n- `--color-warning` \u2014 pending states, attention, non-destructive caution\n- `--color-destructive` / `--color-destructive-foreground` \u2014 errors, irreversible actions\n- `--color-info` \u2014 neutral system messages, tips\n\n**You use these semantic tokens for all status UI.** When you need a \"green checkmark\" you reach for `text-success`, not `text-emerald-500`. When you need an amber alert you reach for `bg-warning/10 text-warning`, not `bg-amber-50 text-amber-700`.\n\n## Usage Rules\n\n**Primary color:**\n- Primary CTAs, links, the active navigation tab, focus rings.\n- NOT for headings. Black or foreground-colored headings are stronger.\n- NOT for large surface fills (it's a splash of color, not a wash).\n- NOT for borders except focus rings.\n- One bold use of primary beats twenty sprinkled uses.\n\n**Neutrals do the structural work:**\n- Background, cards, borders \u2014 all come from the neutral scale.\n- Text hierarchy via opacity on foreground (`text-foreground`, `text-foreground/80`, `text-muted-foreground`) \u2014 not different colors.\n\n**Semantic colors:**\n- Use `bg-success/10 text-success border border-success/30` for success banners (reproducibility: a light-tinted version of the success color for surface, the solid version for text and border).\n- Same shape for warning, info, destructive.\n\n## Dark Mode\n\nCommit to one theme. If DESIGN.md says the app is dark-themed, make it unambiguously dark \u2014 `#0c0c0c` / near-black base, not neutral-900. If light-themed, commit to light.\n\nDo NOT auto-swap based on `prefers-color-scheme` when DESIGN.md declared a theme direction. It chose a theme for a reason; respect it.\n\n## Forbidden\n\n- Palette utilities: `bg-emerald-500`, `text-blue-600`, `border-slate-200`, `from-purple-500`, `via-pink-300`, `to-amber-400`. Every one of these in your output is a slop indicator.\n- Hex literals inside `className` or inline `style` props.\n- Named colors from CSS (`red`, `lightgrey`, `rebeccapurple`) \u2014 never used in production UI; always a sign of rushed work.\n- Purple gradients on white. The single most overused AI-design pattern.\n- Three-color gradient pills. Rainbow badges. \"Vibrant\" anything.\n\n## Contrast\n\nEvery text/surface pair in DESIGN.md is already WCAG AA-verified by Mistflow's contrast test. You do not need to re-check \u2014 the tokens are safe by construction. You DO need to:\n\n- Not override token combinations with hardcoded classes that might fail contrast.\n- Maintain contrast for overlays (text on images, modals on scrims). When stacking text over a gradient or image, include a scrim (`bg-background/80 backdrop-blur-sm`) so body text stays \u2265 4.5:1.\n\n## Getting Color Wrong\n\nThe specific failure mode to avoid: a page where primary is used in five places, all small and incidental \u2014 a checkmark, a hover state, a tiny badge. That's AI hedging. Either use primary confidently on a hero CTA and mean it, OR don't use primary on the page at all and let neutrals carry the identity.\n";var Jn=`# Motion
|
|
5007
5002
|
|
|
5008
5003
|
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.
|
|
5009
5004
|
|
|
@@ -5081,7 +5076,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
|
|
|
5081
5076
|
## One-Line Motion Rule
|
|
5082
5077
|
|
|
5083
5078
|
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.
|
|
5084
|
-
`;var
|
|
5079
|
+
`;var Yn=`# Spatial Composition
|
|
5085
5080
|
|
|
5086
5081
|
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.
|
|
5087
5082
|
|
|
@@ -5151,7 +5146,7 @@ To signal "designed, not templated":
|
|
|
5151
5146
|
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.
|
|
5152
5147
|
|
|
5153
5148
|
Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
|
|
5154
|
-
`;var
|
|
5149
|
+
`;var Qn=`# Interaction
|
|
5155
5150
|
|
|
5156
5151
|
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.
|
|
5157
5152
|
|
|
@@ -5236,7 +5231,7 @@ Small moments that add up to "designed":
|
|
|
5236
5231
|
- **Empty states** offer a specific next action, not "No data yet".
|
|
5237
5232
|
|
|
5238
5233
|
These micro-interactions are the texture of a designed product. Ship them.
|
|
5239
|
-
`;var
|
|
5234
|
+
`;var Xn=`# UX Writing
|
|
5240
5235
|
|
|
5241
5236
|
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.
|
|
5242
5237
|
|
|
@@ -5312,14 +5307,15 @@ If there's a pricing page:
|
|
|
5312
5307
|
## The Footer
|
|
5313
5308
|
|
|
5314
5309
|
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."
|
|
5315
|
-
`;
|
|
5316
|
-
`)}function fo(e){return e.entity??e.name??"Unknown"}function ic(e){return e.length===0?"":typeof e[0]=="string"?e.join(", "):e.map(t=>`${t.name} (${t.type})`).join(", ")}function ws(e){return e.path??e.route??e.name??""}function ac(e){let t=(e||"text").toLowerCase();return t==="string"||t==="varchar"||t==="char"?"text":t==="integer"||t==="int"||t==="number"||t==="float"||t==="decimal"||t==="double"?"number":t==="boolean"||t==="bool"?"boolean":t==="date"||t==="datetime"||t==="timestamp"?"date":t==="email"?"email":t==="url"||t==="uri"?"url":t==="enum"||t==="select"?"select":t==="text"||t==="longtext"||t==="textarea"?"textarea":"text"}function vs(e,t){if(!e.entities||e.entities.length===0)return t;let r=e.entities.map(o=>o.toLowerCase());return t.filter(o=>{let s=fo(o).toLowerCase();return r.some(i=>s.includes(i)||i.includes(s))})}function lc(e,t){if(!e.pages||e.pages.length===0)return[];let r=e.pages.map(o=>o.toLowerCase());return t.filter(o=>{let s=(o.name??"").toLowerCase(),i=ws(o).toLowerCase();return r.some(n=>s.includes(n)||n.includes(s)||i.includes(n))})}var cc=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function dc(e){let t=e.stepType;if(t&&cc.has(t))return t;if(e.integrationId)return"integration";let r=`${e.name} ${e.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function pc(e){switch(e){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 uc(e,t){let r=[];if(r.push("### Design choices (decided at plan time \u2014 follow these exactly):"),e.tone&&r.push(`- **App tone**: ${e.tone}`),e.fonts&&(r.push(`- **Heading font**: ${e.fonts.heading} (load from Google Fonts)`),r.push(`- **Body font**: ${e.fonts.body} (load from Google Fonts)`)),r.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."),r.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)."),e.borderRadius){let o={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};r.push(`- **Border radius**: ${e.borderRadius} (${o[e.borderRadius]??e.borderRadius}) \u2014 set as --radius in globals.css`)}if(e.shadowStyle){let o={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"};r.push(`- **Shadow style**: ${e.shadowStyle} \u2014 ${o[e.shadowStyle]??e.shadowStyle}`)}if(e.cardStyle){let o={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"};r.push(`- **Card style**: ${e.cardStyle} \u2014 ${o[e.cardStyle]??e.cardStyle}`)}if(e.landingTone&&r.push(`- **Landing page tone**: ${e.landingTone}`),e.visualStrategy){let o=e.visualStrategy,s=e.heroPhoto!==!1,i=s&&!!o.heroImages?.length;if(r.push(""),r.push("### Visual strategy:"),i&&o.heroImages&&o.heroImages.length>0){r.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let a=o.heroImages[0];r.push(`- URL: ${a.url}`),r.push(`- Alt text for img tag: "${a.alt||"Hero image"} \u2014 Photo by ${a.photographer} on Unsplash"`),r.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&&!o.heroImages?.length?r.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||r.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(o.sectionImages?.length){r.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let a of o.sectionImages)r.push(`- ${a.url} \u2014 alt: "${a.alt||"section image"} \u2014 Photo by ${a.photographer} on Unsplash"`)}(i||o.sectionImages?.length)&&r.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let n=cs(e);n?(r.push(""),r.push(`### Page composition \u2014 ${n.name} archetype`),r.push(`This plan was classified as **${n.id}** \u2014 ${n.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),r.push(""),r.push(n.content)):(r.push(""),r.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),r.push(""),r.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),r.push("The hero uses a split layout with text on the left and a product preview on the right."),r.push(""),r.push("```"),r.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"),r.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),r.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"),r.push("\u2502 \u2502"),r.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"),r.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),r.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),r.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),r.push("\u2502 \u2502 real app data \u2502 \u2502"),r.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),r.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),r.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"),r.push("\u2502 \u2502"),r.push("\u2502 500+ 25K+ 99% \u2502"),r.push("\u2502 Label Label Label \u2502"),r.push("\u2502 \u2502"),i?r.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):r.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),r.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"),r.push("```"),r.push(""),r.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"),r.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows. Must be DOMAIN-SPECIFIC."),r.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return r.push(""),r.push(Qn),r.join(`
|
|
5317
|
-
`)}async function mc(e){try{let t=await Yo("nextjs",e);return{reminders:t.reminders,skill:t.skill}}catch{return{reminders:`### ${e} step
|
|
5310
|
+
`;import{existsSync as jl,readFileSync as Ol,writeFileSync as Ml}from"fs";import{join as Ul}from"path";import{z as kt}from"zod";var eo=kt.object({key:kt.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:kt.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:kt.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:kt.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),Ll=/^[A-Z][A-Z0-9_]*$/;function to(t,e){if(e.length===0)return{added:[],skipped:[]};let r=Ul(t,"mistflow.json");if(!jl(r))throw new Error(`mistflow.json not found at ${t}`);let o=Ol(r,"utf-8"),s=JSON.parse(o);s.env=s.env??{},s.env.required=s.env.required??{};let i=s.env.required,n=[],a=[];for(let l of e)if(!(!l?.key||typeof l.key!="string"||!Ll.test(l.key))){if(i[l.key]){a.push(l.key);continue}i[l.key]={description:typeof l.description=="string"?l.description:"",...typeof l.setupUrl=="string"&&l.setupUrl?{setupUrl:l.setupUrl}:{},...typeof l.integration=="string"&&l.integration?{integration:l.integration}:{}},n.push(l.key)}return n.length>0&&Ml(r,JSON.stringify(s,null,2)+`
|
|
5311
|
+
`),{added:n,skipped:a}}function zl(t){return new Promise(e=>{let r=Bl({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}var Hl=oo.object({projectPath:oo.string().optional().describe("Path to the project directory (default: cwd)"),step:oo.number().optional().describe("Specific step number to implement (default: next incomplete step)"),envVarsRequired:oo.array(eo).optional().describe("Declare any env vars the code you just wrote uses (process.env.X) that aren't already in mistflow.json env.required. Server merges these into the manifest so missing values surface as warnings on deploy. Skip keys already covered by integration presets (Stripe, Resend, etc. \u2014 those are pre-declared). Only declare ad-hoc keys you introduced. First declaration wins; re-declaring is a no-op.")});function Wl(t){let e=ot(t,"mistflow.json");if(!xt(e))return null;try{return JSON.parse(lr(e,"utf-8"))}catch{return null}}function Zn(t,e){let r=ot(t,"mistflow.json");ar(r,JSON.stringify(e,null,2)+`
|
|
5312
|
+
`)}function ro(t){return t.entity??t.name??"Unknown"}function Gl(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function es(t){return t.path??t.route??t.name??""}function Vl(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 ts(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(o=>o.toLowerCase());return e.filter(o=>{let s=ro(o).toLowerCase();return r.some(i=>s.includes(i)||i.includes(s))})}function Kl(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(o=>o.toLowerCase());return e.filter(o=>{let s=(o.name??"").toLowerCase(),i=es(o).toLowerCase();return r.some(n=>s.includes(n)||n.includes(s)||i.includes(n))})}var Jl=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function Yl(t){let e=t.stepType;if(e&&Jl.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name} ${t.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function Ql(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 Xl(t){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&e.push(`- **App tone**: ${t.tone}`),t.fonts&&(e.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let r={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${t.borderRadius} (${r[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let r={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${r[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let r={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${t.cardStyle} \u2014 ${r[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&e.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let r=t.visualStrategy,o=t.heroPhoto!==!1,s=o&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),s&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let n=r.heroImages[0];e.push(`- URL: ${n.url}`),e.push(`- Alt text for img tag: "${n.alt||"Hero image"} \u2014 Photo by ${n.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else o&&!r.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/page.tsx.'"):o||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(r.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let n of r.sectionImages)e.push(`- ${n.url} \u2014 alt: "${n.alt||"section image"} \u2014 Photo by ${n.photographer} on Unsplash"`)}(s||r.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let i=Hn(t);i?(e.push(""),e.push(`### Page composition \u2014 ${i.name} archetype`),e.push(`This plan was classified as **${i.id}** \u2014 ${i.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),e.push(""),e.push(i.content)):(e.push(""),e.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),s?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows. Must be DOMAIN-SPECIFIC."),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return e.push(""),e.push(Nn),e.join(`
|
|
5313
|
+
`)}async function Zl(t){try{let e=await Lo("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
|
|
5318
5314
|
- Follow existing patterns in the codebase
|
|
5319
|
-
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function hc(e,t,r,o,s,i){let n=[];n.push(`## Step ${e.number}: ${e.name}`),n.push(""),n.push("### What to build:"),n.push(e.description),n.push(""),t.primaryAction&&(n.push("### Primary user action (non-negotiable):"),n.push(`- **Core action**: ${t.primaryAction.action}`),n.push(`- **User flow**: ${t.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),n.push(""),n.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."),n.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(s);if(t.design&&l?(n.push(uc(t.design,{hasDesignPreset:!!t.landingDesign&&(s==="landing"||s==="design")})),n.push("")):t.design&&!l&&(n.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),t.design.fonts&&n.push(`- Fonts: ${t.design.fonts.heading} / ${t.design.fonts.body}`),n.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),n.push("")),i){let S=En(i);if(S.length>0){n.push("### Approved wireframe (MUST READ before writing any files):"),n.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let x of S){let f=x.replace(i,"").replace(/^\//,"");n.push(`- \`${f}\``)}n.push(""),n.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."),n.push(""),n.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),n.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),n.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),n.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),n.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),n.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"),n.push("")}}t.roles&&Array.isArray(t.roles)&&t.roles.length>0&&(n.push("### Role system (from plan):"),n.push(`- Roles: ${t.roles.join(", ")}`),n.push(`- Default role for new signups: ${t.defaultRole??t.roles[0]}`),n.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),n.push("")),t.multiTenant&&(n.push("### Multi-tenant (from plan):"),n.push("- Organization tables are in `db/schema/organization.ts`"),n.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),n.push("- All data queries MUST be scoped to the current org (filter by orgId)"),n.push("- Org switcher component is at `components/org-switcher.tsx`"),n.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."),n.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."),n.push("")),t.language&&(n.push(`### Language: ${t.language}`),n.push(`ALL user-facing text must be written in ${t.language}:`),n.push("- Page titles, headings, labels, button text, placeholder text"),n.push("- Navigation items, menu labels, footer text"),n.push("- Error messages, success messages, empty states"),n.push("- Landing page copy, marketing text, CTAs"),n.push("- Form labels and validation messages"),n.push("Code (variable names, comments, file names) stays in English."),n.push(`Set the HTML lang attribute to the appropriate locale code for ${t.language}.`),n.push(""));let c=["landing","design","auth","general","crud","dashboard"];t.audienceType&&c.includes(s)&&(t.audienceType==="b2c"?(n.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),n.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),n.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),n.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),n.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),n.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),n.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),n.push("")):t.audienceType==="b2b"?(n.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),n.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),n.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),n.push("- Testimonials: from business owners who use the platform"),n.push("- Features: business benefits ('Track dietary preferences across all orders')"),n.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),n.push("")):t.audienceType==="internal"&&(n.push("### Audience: internal staff tool. No marketing copy needed."),n.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),n.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),n.push(""))),r.length>0&&(n.push("### Already completed:"),r.forEach(S=>n.push(`- ${S}`)),n.push(""));let h=t.dataModel?vs(e,t.dataModel):[];h.length>0&&(n.push("### Data model (from plan):"),h.forEach(S=>{let x=fo(S),f=ic(S.fields);n.push(`- **${x}**: ${f}`),n.push(` Schema file: \`db/schema/${x.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),n.push(""));let m=t.pages?lc(e,t.pages):[];if(m.length>0&&(n.push("### Pages to create/update:"),m.forEach(S=>{let x=S.description?` \u2014 ${S.description}`:"";n.push(`- \`${ws(S)}\`${x}`)}),n.push("")),s==="crud"&&h.length>0&&h.forEach(S=>{let x=fo(S),f=x.toLowerCase().replace(/\s+/g,"-"),P=f.endsWith("s")?f:`${f}s`;n.push(`### Files for ${x} CRUD:`),n.push(`- List page: \`app/(dashboard)/${P}/page.tsx\` (Server Component)`),n.push(`- Detail page: \`app/(dashboard)/${P}/[id]/page.tsx\``),n.push(`- Create page: \`app/(dashboard)/${P}/new/page.tsx\``),n.push(`- Server Actions: \`app/(dashboard)/${P}/actions.ts\``),n.push(`- DataTable columns: \`components/${f}-table-columns.tsx\``),n.push(`- Form: \`components/${f}-form.tsx\``),n.push("")}),l){n.push("## Design Doctrine (the standard for every UI step)"),n.push(""),n.push(ps),n.push(""),n.push("## Design Reference Library"),n.push(""),n.push("### Typography"),n.push(us),n.push(""),n.push("### Color"),n.push(ms),n.push(""),n.push("### Motion"),n.push(hs),n.push(""),n.push("### Spatial Composition"),n.push(gs),n.push(""),n.push("### Interaction"),n.push(fs),n.push(""),n.push("### UX Writing"),n.push(ys),n.push("");let S=i?gt(i,"DESIGN.md"):void 0,x=S&&Mt(S)?(()=>{try{return Sr(S,"utf-8")}catch{return null}})():null;x&&(n.push("### Design system (source of truth: DESIGN.md):"),n.push(""),n.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."),n.push(""),n.push(x),n.push(""))}(s==="landing"||s==="design")&&(n.push(ds),n.push(""));let u=e.integrationId?dt(e.integrationId):void 0;if(u){let S=pt(u.id);if(n.push("### Integration blueprint (follow this closely):"),n.push(""),n.push(`Using integration: **${u.name}** (${u.category})`),S?.docsUrl&&n.push(`Official docs: ${S.docsUrl}`),S?.envVars?.length){n.push(""),n.push("**Required environment variables:**");for(let x of S.envVars)n.push(`- \`${x.key}\`: ${x.description} \u2014 Get it at ${x.setupUrl}`);n.push(""),n.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.")}S?.packages?.length&&(n.push(""),n.push(`**Packages to install:** \`npm install ${S.packages.join(" ")}\``)),n.push(""),n.push("---"),n.push(u.prompt),n.push("---"),n.push(""),n.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."),n.push("")}let{reminders:w,skill:D}=await mc(s);return n.push(w),n.push(""),D&&!(s==="landing"&&t.landingDesign==="freeform")&&(n.push(`### ${s} reference:`),n.push(D),n.push("")),l&&(n.push("## Self-Audit \u2014 run before submitting this file"),n.push(""),n.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.`),n.push(""),n.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.'),n.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."),n.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),n.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),n.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."),n.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),n.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),n.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.'),n.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).'),n.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)."),n.push(""),n.push(`If every answer is "no, I'm good" \u2014 then submit.`),n.push("")),n.join(`
|
|
5320
|
-
`)}async function
|
|
5321
|
-
`+
|
|
5322
|
-
`)}
|
|
5315
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function ec(t,e,r,o,s,i){let n=[];n.push(`## Step ${t.number}: ${t.name}`),n.push(""),n.push("### What to build:"),n.push(t.description),n.push(""),e.primaryAction&&(n.push("### Primary user action (non-negotiable):"),n.push(`- **Core action**: ${e.primaryAction.action}`),n.push(`- **User flow**: ${e.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),n.push(""),n.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."),n.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(s);if(e.design&&l?(n.push(Xl(e.design)),n.push("")):e.design&&!l&&(n.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&n.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),n.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),n.push("")),i){let x=un(i);if(x.length>0){n.push("### Approved wireframe (MUST READ before writing any files):"),n.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let S of x){let f=S.replace(i,"").replace(/^\//,"");n.push(`- \`${f}\``)}n.push(""),n.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."),n.push(""),n.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),n.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),n.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),n.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),n.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),n.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"),n.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(n.push("### Role system (from plan):"),n.push(`- Roles: ${e.roles.join(", ")}`),n.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),n.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),n.push("")),e.multiTenant&&(n.push("### Multi-tenant (from plan):"),n.push("- Organization tables are in `db/schema/organization.ts`"),n.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),n.push("- All data queries MUST be scoped to the current org (filter by orgId)"),n.push("- Org switcher component is at `components/org-switcher.tsx`"),n.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."),n.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."),n.push("")),e.language&&(n.push(`### Language: ${e.language}`),n.push(`ALL user-facing text must be written in ${e.language}:`),n.push("- Page titles, headings, labels, button text, placeholder text"),n.push("- Navigation items, menu labels, footer text"),n.push("- Error messages, success messages, empty states"),n.push("- Landing page copy, marketing text, CTAs"),n.push("- Form labels and validation messages"),n.push("Code (variable names, comments, file names) stays in English."),n.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),n.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(s)&&(e.audienceType==="b2c"?(n.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),n.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),n.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),n.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),n.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),n.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),n.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),n.push("")):e.audienceType==="b2b"?(n.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),n.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),n.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),n.push("- Testimonials: from business owners who use the platform"),n.push("- Features: business benefits ('Track dietary preferences across all orders')"),n.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),n.push("")):e.audienceType==="internal"&&(n.push("### Audience: internal staff tool. No marketing copy needed."),n.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),n.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),n.push(""))),r.length>0&&(n.push("### Already completed:"),r.forEach(x=>n.push(`- ${x}`)),n.push(""));let m=e.dataModel?ts(t,e.dataModel):[];m.length>0&&(n.push("### Data model (from plan):"),m.forEach(x=>{let S=ro(x),f=Gl(x.fields);n.push(`- **${S}**: ${f}`),n.push(` Schema file: \`db/schema/${S.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),n.push(""));let p=e.pages?Kl(t,e.pages):[];if(p.length>0&&(n.push("### Pages to create/update:"),p.forEach(x=>{let S=x.description?` \u2014 ${x.description}`:"";n.push(`- \`${es(x)}\`${S}`)}),n.push("")),s==="crud"&&m.length>0&&m.forEach(x=>{let S=ro(x),f=S.toLowerCase().replace(/\s+/g,"-"),A=f.endsWith("s")?f:`${f}s`;n.push(`### Files for ${S} CRUD:`),n.push(`- List page: \`app/(dashboard)/${A}/page.tsx\` (Server Component)`),n.push(`- Detail page: \`app/(dashboard)/${A}/[id]/page.tsx\``),n.push(`- Create page: \`app/(dashboard)/${A}/new/page.tsx\``),n.push(`- Server Actions: \`app/(dashboard)/${A}/actions.ts\``),n.push(`- DataTable columns: \`components/${f}-table-columns.tsx\``),n.push(`- Form: \`components/${f}-form.tsx\``),n.push("")}),l){n.push("## Design Doctrine (the standard for every UI step)"),n.push(""),n.push(Gn),n.push(""),n.push("## Design Reference Library"),n.push(""),n.push("### Typography"),n.push(Vn),n.push(""),n.push("### Color"),n.push(Kn),n.push(""),n.push("### Motion"),n.push(Jn),n.push(""),n.push("### Spatial Composition"),n.push(Yn),n.push(""),n.push("### Interaction"),n.push(Qn),n.push(""),n.push("### UX Writing"),n.push(Xn),n.push("");let x=i?ot(i,"DESIGN.md"):void 0,S=x&&xt(x)?(()=>{try{return lr(x,"utf-8")}catch{return null}})():null;S&&(n.push("### Design system (source of truth: DESIGN.md):"),n.push(""),n.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."),n.push(""),n.push(S),n.push(""))}(s==="landing"||s==="design")&&(n.push(Wn),n.push(""));let u=t.integrationId?Qe(t.integrationId):void 0;if(u){let x=Xe(u.id);if(n.push("### Integration blueprint (follow this closely):"),n.push(""),n.push(`Using integration: **${u.name}** (${u.category})`),x?.docsUrl&&n.push(`Official docs: ${x.docsUrl}`),x?.envVars?.length){n.push(""),n.push("**Required environment variables:**");for(let S of x.envVars)n.push(`- \`${S.key}\`: ${S.description} \u2014 Get it at ${S.setupUrl}`);n.push(""),n.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.")}x?.packages?.length&&(n.push(""),n.push(`**Packages to install:** \`npm install ${x.packages.join(" ")}\``)),n.push(""),n.push("---"),n.push(u.prompt),n.push("---"),n.push(""),n.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."),n.push("")}let{reminders:w,skill:N}=await Zl(s);return n.push(w),n.push(""),N&&(n.push(`### ${s} reference:`),n.push(N),n.push("")),l&&(n.push("## Self-Audit \u2014 run before submitting this file"),n.push(""),n.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.`),n.push(""),n.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.'),n.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."),n.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),n.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),n.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."),n.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),n.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),n.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.'),n.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).'),n.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)."),n.push(""),n.push(`If every answer is "no, I'm good" \u2014 then submit.`),n.push("")),n.join(`
|
|
5316
|
+
`)}async function tc(t){let{projectPath:e,step:r,envVarsRequired:o}=t,s=Fl(e??process.cwd());if(o&&o.length>0)try{let T=to(s,o);T.added.length>0&&console.error(`[implement] declared env.required: ${T.added.join(", ")}`)}catch(T){console.error("[implement] env var merge skipped:",T instanceof Error?T.message:String(T))}let i=Wl(s);if(!i)return Ae(s);if(!xt(ot(s,"node_modules")))return d(`Dependencies are not installed at ${s}. Call mist_install and projectPath='${s}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:T,ensureShadcnComponents:R}=await Promise.resolve().then(()=>(Go(),Wo));await T(s);let C=await R(s);C.failed?console.error(`[implement] ${C.failed}`):C.installed.length>0&&console.error(`[implement] installed ${C.installed.length} shadcn components`)}catch(T){console.error("[implement] self-heal skipped:",T instanceof Error?T.message:String(T))}let n=i.plan;if(!n||!n.steps||n.steps.length===0)return d("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let a,l=n.steps.find(T=>T.status==="in_progress");if(l){let T=n.steps.findIndex(R=>R.number===l.number);T!==-1&&(n.steps[T].status="completed",a=`Auto-completed step ${l.number} (${l.name})`,Zn(s,i))}let c;if(r!==void 0){if(c=n.steps.find(T=>T.number===r),!c)return d(`Step ${r} not found. The plan has ${n.steps.length} steps (numbered ${n.steps[0].number} to ${n.steps[n.steps.length-1].number}).`,!0)}else if(c=n.steps.find(T=>T.status!=="completed"),!c)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:n.steps.map(T=>T.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let m=n.steps.filter(T=>T.status==="completed").map(T=>`Step ${T.number}: ${T.name}`),{readLocalState:p}=await Promise.resolve().then(()=>(qe(),gt)),u=p(s),w=Yl(c),N=[];if((w==="crud"||w==="schema")&&n.dataModel&&c.entities&&c.entities.length>0){let T=ts(c,n.dataModel);for(let R of T){let C=ro(R);try{let I=(R.fields||[]).map(J=>typeof J=="string"?{name:J,type:"text"}:{name:J.name,type:Vl(J.type),required:J.required!==!1});if(I.length===0)continue;let L=i.dbProvider==="neon"?"nextjs-neon":"nextjs",M=await $o(L,C,I),D=0,$=0;for(let J of M.files){let ee=ot(s,J.path);if(xt(ee)){$++;continue}$l(ql(ee),{recursive:!0}),ar(ee,J.content),D++}let z=ot(s,"db","index.ts");if(xt(z)){let J=lr(z,"utf-8");J.includes(M.dbExport)||ar(z,J.trimEnd()+`
|
|
5317
|
+
`+M.dbExport+`
|
|
5318
|
+
`)}D>0?N.push(`${M.entityPascal} CRUD (${D} new files${$>0?`, ${$} existing skipped`:""})`):$>0&&N.push(`${M.entityPascal} CRUD (all ${$} files already exist \u2014 skipped)`)}catch(I){console.error(`Module generation failed for ${C} (non-fatal):`,I instanceof Error?I.message:I)}}}let x=await ec(c,n,m,null,w,s),S=n.steps.findIndex(T=>T.number===c.number);if(S!==-1&&(i.plan.steps[S].status="in_progress",Zn(s,i)),u&&i.projectId){let{syncRemoteState:T}=await Promise.resolve().then(()=>(qe(),gt));T(i.projectId,u).catch(()=>{})}let f=n.steps.every(T=>T.status==="completed"||T.number===c.number),A;f?A=`THIS IS THE LAST STEP. Rules for speed:
|
|
5323
5319
|
|
|
5324
5320
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
5325
5321
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -5328,14 +5324,14 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
5328
5324
|
- app/page.tsx must be a real landing page, NOT a redirect to /login
|
|
5329
5325
|
- middleware.ts must have "/" in PUBLIC_EXACT or PUBLIC_PREFIXES
|
|
5330
5326
|
- Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
|
|
5331
|
-
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.`:
|
|
5327
|
+
5. Call mist_build({ projectPath }) (fire-and-poll \u2014 re-call with the returned jobId until status 'complete'), then mist_deploy({ action: 'deploy', projectPath, envVarsRequired: [...] }). Pass envVarsRequired on the deploy call if your code uses any process.env.X that isn't already in mistflow.json env.required (skip keys covered by integration presets \u2014 those are pre-declared). Do NOT pause between these two calls to ask the user \u2014 the build is expected, the deploy is expected, just chain them.`:A=`IMPLEMENT THIS STEP NOW. Rules for speed:
|
|
5332
5328
|
|
|
5333
5329
|
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.
|
|
5334
5330
|
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.
|
|
5335
5331
|
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.
|
|
5336
5332
|
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).
|
|
5337
|
-
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
|
|
5338
|
-
`)}async function
|
|
5333
|
+
5. After writing ALL files, call mist_implement to move to the next step. If you used any process.env.X that isn't already in mistflow.json env.required, pass it via envVarsRequired on this call so the dashboard can prompt the user for it (skip keys covered by integration presets \u2014 those are pre-declared). Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let U=Ql(w),H={stepNumber:c.number,totalSteps:n.steps.length,estimatedMinutes:U,announcement:`Starting step ${c.number} of ${n.steps.length}: ${c.name}. This step usually takes ${U.min}\u2013${U.max} minutes.`},K=JSON.stringify({instruction:x,step:{number:c.number,name:c.name,description:c.description,status:"in_progress"},stepTiming:H,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_implement again immediately after the compaction finishes. The tool finds the in-progress step and returns fresh context \u2014 you don't need to re-read files or re-derive state.",...a?{autoCompleted:a}:{},...N.length>0?{generatedModules:N,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${m.length}/${n.steps.length} steps done`,nextAction:A});return await zl(3e3)?Ar("http://localhost:3000",K):d(K)}var os={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:Hl,handler:tc};import{z as be}from"zod";import{z as Oe}from"zod";import{resolve as oc}from"path";le();$e();var ym=Oe.object({projectPath:Oe.string().optional().describe("Path to the project directory (default: cwd)"),action:Oe.enum(["set","list","delete"]).describe("Action to perform"),key:Oe.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:Oe.string().optional().describe("Environment variable value (required for 'set')"),category:Oe.string().optional().describe("Category for the env var (default: 'custom')"),description:Oe.string().optional().describe("Description of what this env var is for"),setupUrl:Oe.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function rs(t){let{projectPath:e,action:r,key:o,value:s,category:i,description:n,setupUrl:a}=t,l=oc(e??process.cwd());if(!ne())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let m=Re(l)?.projectId;if(!m)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"set":return o?s?(await Eo(m,o,s,{category:i,description:n,setupUrl:a}),d(JSON.stringify({set:!0,key:o,message:`Environment variable '${o}' has been set. It will be available on your next deployment.`}))):d("Value is required. Provide the env var value.",!0):d("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let p=await Ro(m);return p.length===0?d(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):d(JSON.stringify({envVars:p.map(u=>({key:u.key,category:u.category,description:u.description,hasValue:u.has_value})),message:`${p.length} environment variable(s) configured.`}))}case"delete":return o?(await No(m,o),d(JSON.stringify({deleted:!0,key:o,message:`Environment variable '${o}' has been removed.`}))):d("Key is required. Provide the env var name to delete.",!0);default:return d(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(p){if(p instanceof W)return d(p.message,!0);let u=p instanceof Error?p.message:"An unexpected error occurred";return d(u,!0)}}import{z as St}from"zod";import{resolve as rc,join as nc}from"path";import{existsSync as sc,readFileSync as ic,writeFileSync as ac}from"fs";le();$e();var Pm=St.object({projectPath:St.string().optional().describe("Path to the project directory (default: cwd)"),action:St.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:St.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:St.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function cr(t,e){let r=nc(t,"mistflow.json");if(!sc(r))return;let o;try{o=JSON.parse(ic(r,"utf-8"))}catch{return}o.domains=e,ac(r,JSON.stringify(o,null,2)+`
|
|
5334
|
+
`)}async function ns(t){let{projectPath:e,action:r,domain:o,domainId:s}=t,i=rc(e??process.cwd());if(!ne())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=Re(i)?.projectId;if(!a)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!o)return d("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Co(a,o),c=await Ee(a);return cr(i,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await Ee(a);return l.length===0?d(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):d(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!s){if(o){let p=(await Ee(a)).find(u=>u.domain===o);if(p){let u=await Lt(a,p.id);return d(JSON.stringify({domain:u.domain,status:u.status,ssl:u.ssl_status,error:u.error_message,message:u.status==="active"?`Domain '${u.domain}' is active and serving traffic.`:`Domain '${u.domain}' is ${u.status}. Make sure DNS records are configured correctly.`}))}return d(`Domain '${o}' not found. Use action 'list' to see configured domains.`,!0)}return d("Provide either domainId or domain name to verify.",!0)}let l=await Lt(a,s),c=await Ee(a);return cr(i,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!s&&!o)return d("Provide either domainId or domain name to remove.",!0);let l=s;if(!l&&o){let p=(await Ee(a)).find(u=>u.domain===o);if(!p)return d(`Domain '${o}' not found.`,!0);l=p.id}await Io(a,l);let c=await Ee(a);return cr(i,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return d(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof W)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var lc=be.object({resource:be.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:be.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:be.string().optional().describe("Path to the project directory (default: cwd)"),key:be.string().optional().describe("(env) Variable name"),value:be.string().optional().describe("(env set) Variable value"),category:be.string().optional().describe("(env set) Category"),description:be.string().optional().describe("(env set) Description"),setupUrl:be.string().optional().describe("(env set) URL to obtain the value"),domain:be.string().optional().describe("(domain) Domain name"),domainId:be.string().optional().describe("(domain) Domain ID")}),ss={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:lc,handler:async t=>{let e=t;switch(e.resource){case"env":return rs({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return ns({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return d(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}};import{z as lo}from"zod";import{resolve as Sc}from"path";import{existsSync as Tc}from"fs";import{join as Pc}from"path";import{spawn as cc,execFileSync as dc}from"child_process";import{existsSync as no,mkdirSync as ls,openSync as dr,closeSync as pr,readSync as pc,readFileSync as cs,writeFileSync as ds,renameSync as ps,unlinkSync as uc,readdirSync as jm,statSync as mc}from"fs";import{homedir as us}from"os";import{join as de,dirname as ms}from"path";import{randomBytes as hs,randomUUID as hc}from"crypto";var gs=1,gc=`// Generated by @mistflow-ai/mcp local-jobs (v${gs}). Do not edit.
|
|
5339
5335
|
const { spawn } = require('node:child_process');
|
|
5340
5336
|
const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
|
|
5341
5337
|
const { join, dirname } = require('node:path');
|
|
@@ -5399,26 +5395,26 @@ child.on('error', (err) => {
|
|
|
5399
5395
|
});
|
|
5400
5396
|
process.exit(1);
|
|
5401
5397
|
});
|
|
5402
|
-
`;function
|
|
5403
|
-
`),
|
|
5404
|
-
`).slice(-
|
|
5405
|
-
`).slice(-
|
|
5406
|
-
`)}function
|
|
5407
|
-
`).filter(o=>o.length>0);return r.length<=t
|
|
5408
|
-
`)}var
|
|
5409
|
-
`+
|
|
5410
|
-
`).filter(o=>o.length>0);return r.length<=t
|
|
5411
|
-
`)}function
|
|
5412
|
-
`)}),!1)}try{let
|
|
5413
|
-
${
|
|
5414
|
-
`)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});i.push(
|
|
5415
|
-
${
|
|
5416
|
-
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(
|
|
5398
|
+
`;function so(){return de(us(),".mistflow","jobs")}function fc(){return de(us(),".mistflow","job-wrapper.cjs")}function yc(){let t=fc(),e=ms(t);no(e)||ls(e,{recursive:!0});let r=`v${gs}`;if(no(t))try{if(cs(t,"utf-8").includes(r))return t}catch{}let o=de(e,`.job-wrapper.tmp.${hs(6).toString("hex")}`);return ds(o,gc),ps(o,t),t}function rt(t){return de(so(),t)}function fs(t){return de(rt(t),"status.json")}function is(t,e){let r=fs(t),o=de(ms(r),`.status.tmp.${hs(6).toString("hex")}`);try{ds(o,JSON.stringify(e,null,2)+`
|
|
5399
|
+
`),ps(o,r)}catch(s){try{uc(o)}catch{}throw s}}function bc(t){let e=fs(t);if(!no(e))return null;try{return JSON.parse(cs(e,"utf-8"))}catch{return null}}async function io(t){let e=`job_${hc().replace(/-/g,"").slice(0,12)}`,r=rt(e);ls(r,{recursive:!0}),pr(dr(de(r,"stdout.log"),"a")),pr(dr(de(r,"stderr.log"),"a"));let o=new Date().toISOString(),s={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:o,cmd:t.cmd,args:t.args,cwd:t.cwd};is(e,s);let i=yc(),n={...process.env,...t.env??{}},a=cc("node",[i,r,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:n});a.unref();let l={...s,wrapperPid:a.pid??0};return is(e,l),l}function wc(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function vc(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=dc("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),o=wc(r),s=Date.parse(t.startedAt);if(Number.isFinite(o)&&Number.isFinite(s)&&Math.abs(o-s)>2e3)return!1}catch{}return!0}function kc(t,e){let r=Date.parse(t),o=e?Date.parse(e):Date.now();if(!Number.isFinite(r)||!Number.isFinite(o))return"0s";let s=Math.max(0,o-r),i=Math.floor(s/1e3);if(i<60)return`${i}s`;let n=Math.floor(i/60),a=i%60;return n<60?`${n}m ${a}s`:`${Math.floor(n/60)}h ${n%60}m`}function as(t,e){if(!no(t))return"";let r=mc(t);if(r.size===0)return"";let o=r.size>e?r.size-e:0,s=r.size-o,i=dr(t,"r");try{let n=Buffer.alloc(s);return pc(i,n,0,s,o),n.toString("utf-8")}finally{pr(i)}}function xc(t,e=200){let r=as(de(rt(t),"stdout.log"),65536),o=as(de(rt(t),"stderr.log"),64*1024),s=[];return r.trim()&&s.push(...r.split(`
|
|
5400
|
+
`).slice(-e).map(i=>`[out] ${i}`)),o.trim()&&s.push(...o.split(`
|
|
5401
|
+
`).slice(-e).map(i=>`[err] ${i}`)),s.filter(i=>i.trim().length>0).join(`
|
|
5402
|
+
`)}function Tt(t){return{stdout:de(rt(t),"stdout.log"),stderr:de(rt(t),"stderr.log")}}async function Pt(t){let e=bc(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!vc(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:kc(r.startedAt,r.endedAt),logTail:xc(t)}}async function ao(t,e){let r=Math.max(100,e.pollIntervalMs??500),o=Date.now()+Math.max(0,e.timeoutMs),s=["complete","failed","unknown_exit"];for(;;){let i=await Pt(t);if(!i)return null;try{e.onPoll?.(i)}catch{}if(s.includes(i.status))return i;let n=o-Date.now();if(n<=0)return i;await new Promise(a=>setTimeout(a,Math.min(r,n)))}}function Cc(t,e=15){let r=t.split(`
|
|
5403
|
+
`).filter(o=>o.length>0);return r.length<=e?t:r.slice(-e).join(`
|
|
5404
|
+
`)}var Ic=lo.object({projectPath:lo.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:lo.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:lo.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical install fits in 2 round-trips instead of 5-6. Default 20. Set 0 to disable.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),ys={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:Ic,handler:async(t,e)=>{let r=t;if(r.jobId){let l=await Pt(r.jobId);if(!l)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No install job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let c=r.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let p=l.elapsed,u=e?xe(e.server,e.progressToken,()=>`Install running (${p}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let w=await ao(r.jobId,{timeoutMs:c*1e3,onPoll:N=>{p=N.elapsed}});w&&(l=w)}finally{u.stop()}}if(l.status==="running"||l.status==="starting")return d(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:Cc(l.logTail),nextAction:"Install still running after long-poll window. Call mist_install again with the same jobId to continue waiting."}));if(l.status==="complete")return d(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,nextAction:"Dependencies installed. Run mist_implement next to start executing plan steps."}));let m=Tt(l.id);return d(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:m,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${m.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let o=Sc(r.projectPath);if(!Tc(Pc(o,"package.json")))return d(`No package.json at ${o}. Confirm the path and that mist_init has scaffolded the project.`,!0);let n=`npm install && (${`npx --yes shadcn@latest add -y -o ${["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"].join(" ")}`} || echo 'shadcn add failed \u2014 implement will retry lazily')`,a=await io({type:"install",cmd:"sh",args:["-c",n],cwd:o,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return d(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:o,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+a.id+"' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s."}))}};import{z as Ct}from"zod";import{resolve as Ac,join as we}from"path";import{existsSync as Se,readFileSync as bs,statSync as _c,readdirSync as Rc}from"fs";var ws=100*1024;function Ec(t){let e=0,r=0,o=[t];for(;o.length>0&&r<1e4;){let s=o.pop();r++;let i;try{i=Rc(s)}catch{continue}for(let n of i){let a=we(s,n),l;try{l=_c(a)}catch{continue}l.isDirectory()?o.push(a):l.isFile()&&(e+=l.size)}}return e}function Nc(t){if(!(Se(we(t,"open-next.config.ts"))||Se(we(t,"open-next.config.js"))))return null;let r=we(t,".open-next","worker.js");if(!Se(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker entrypoint. Common causes: (1) open-next.config.ts is misconfigured, (2) a client component imports a Node-only API (fs, path, crypto node:* imports in 'use client' files), (3) the adapter crashed silently mid-build. Check the logTail above for "error"/"failed" messages, fix the offending file, and re-run mist_build.`;let o=we(t,".open-next","server-functions","default");if(!Se(o))return'Build exited 0 and .open-next/worker.js exists, but .open-next/server-functions/default/ is missing. The OpenNext adapter produced an orchestrator with no server bundle to import. Check the logTail above for "error"/"failed" messages near "Building server function: default..." and re-run mist_build.';let s=Ec(o);return s<ws?`Build exited 0 but the server-functions bundle is only ${s} bytes (expected at least ${ws}). A healthy Next.js + OpenNext bundle is 5-50MB. This size suggests the adapter failed to bundle most of the app. Check the logTail for bundling errors and re-run mist_build.`:null}var Dc=Ct.object({projectPath:Ct.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Ct.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Ct.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls."),waitSeconds:Ct.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical build fits in 2 round-trips instead of 6-8. Default 20. Set 0 to disable.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});function jc(t){let e=we(so(),t,"stdout.log"),r=we(so(),t,"stderr.log"),o="";try{Se(e)&&(o+=bs(e,"utf-8"))}catch{}try{Se(r)&&(o+=`
|
|
5405
|
+
`+bs(r,"utf-8"))}catch{}return o}function Oc(t,e=15){let r=t.split(`
|
|
5406
|
+
`).filter(o=>o.length>0);return r.length<=e?t:r.slice(-e).join(`
|
|
5407
|
+
`)}function Mc(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let o of t.matchAll(e)){let s=o[1];if(s.startsWith(".")||s.startsWith("@/")||s.startsWith("~/"))continue;let i=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];i&&r.add(i)}return[...r]}var vs={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:Dc,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await Pt(r.jobId);if(!c)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let m=r.waitSeconds??20;if(m>0&&(c.status==="running"||c.status==="starting")){let f=c.elapsed,A=e?xe(e.server,e.progressToken,()=>`Build running (${f}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let U=await ao(r.jobId,{timeoutMs:m*1e3,onPoll:H=>{f=H.elapsed}});U&&(c=U)}finally{A.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Oc(c.logTail),nextAction:"Build still running after long-poll window. Call mist_build again with the same jobId to continue waiting."}));if(c.status==="complete"){let f=Nc(c.cwd);if(f){let A=Tt(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:A,error:f,nextAction:f+` Full build log: ${A.stdout} and ${A.stderr}.`}),!0)}return d(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let p=jc(c.id),u=Gt(p),w=Mc(p),N=Tt(c.id),x=` Full log: ${N.stdout} and ${N.stderr}.`,S=w.length>0?`Build failed with missing modules: ${w.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${x}`:u.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${x}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${x}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:u,missingModules:w,logTail:c.logTail,logPaths:N,nextAction:S}),!0)}let o=Ac(r.projectPath);if(!Se(we(o,"package.json")))return d(`No package.json at ${o}. Run mist_init first.`,!0);if(!Se(we(o,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${o}' } first.`,!0);let s,i,n,a=Se(we(o,"open-next.config.ts"))||Se(we(o,"open-next.config.js"));r.script?(s="npm",i=["run",r.script],n=r.script):a?(s="npx",i=["-y","@opennextjs/cloudflare","build"],n="@opennextjs/cloudflare build"):(s="npm",i=["run","build"],n="build");let l=await io({type:"build",cmd:s,args:i,cwd:o});return d(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:o,script:n,nextAction:`Build started. Call mist_build again with { jobId: '${l.id}' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}};import{existsSync as Uc,readFileSync as Lc}from"fs";import{join as $c}from"path";import{z as co}from"zod";le();var Fc=co.object({projectPath:co.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:co.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:co.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.")}),Ss={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:Fc,handler:async t=>zc(t)};function qc(t){let e=$c(t,"mistflow.json");if(!Uc(e))return null;try{return JSON.parse(Lc(e,"utf-8"))}catch{return null}}async function ks(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await e.text();return{status:e.status,body:r}}catch(e){return{status:0,body:String(e)}}}async function Bc(t,e,r){try{let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),s=await o.text(),i;try{i=JSON.parse(s)}catch{}return{status:o.status,json:i}}catch{return{status:0}}}async function xs(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function Me(t,e,r){let o=[],s=i=>{i.type()==="error"&&o.push(i.text())};t.on("console",s);try{let i=await r(),n=await xs(t);return{name:e,status:i.pass?"pass":"fail",detail:i.detail,fix:i.fix,screenshot:n,consoleErrors:o.length>0?o:void 0}}catch(i){let n=await xs(t);return{name:e,status:"fail",detail:`Unexpected error: ${i instanceof Error?i.message:String(i)}`,screenshot:n,consoleErrors:o.length>0?o:void 0}}finally{t.removeListener("console",s)}}async function zc(t){let e=t.projectPath??process.cwd(),r=qc(e),o=t.url;if(o||(o=r?.deploy?.url),!o)return d("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);o.startsWith("http")||(o=`https://${o}`);let s=r?.projectId,i=[],n=await ks(`${o}/api/health`);if(n.status!==200)return i.push({name:"Health endpoint",status:"fail",detail:`Returns ${n.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),po(o,i);i.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await ks(`${o}/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."}),po(o,i);i.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",m="QaTemp1!",p="single",u="user",w=[];async function N(A,U,H,_){let K=await Bc(`${o}/api/admin/seed`,{token:_,email:U,password:m,role:H});if(K.status!==200||!K.json)return console.error(`[qa] Seed (${A}) returned ${K.status}`),null;let F=K.json.sessionToken;if(!F)return null;let T=K.json.seeded===!0;return{role:A,email:U,sessionToken:F,password:T?m:void 0}}if(s){let A=await Ao(s);if(A){if(p=A.authMode??"single",u=A.defaultRole??"user",console.error(`[qa] auth_mode=${p}, default_role=${u}`),p!=="none"){let H=await N("actor",l,p==="multi"?"admin":u,A.seedToken);if(H&&w.push(H),p==="multi"){let _=await N("user",c,u,A.seedToken);_?w.push(_):i.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${u}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),p="none"}if(p!=="none"&&w.length===0)return i.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy injects ADMIN_SEED_TOKEN and stores it on the backend; the scaffold's /api/admin/seed route accepts { token, email, password, role } and creates synthetic QA users with the requested role."}),po(o,i);let x,S,f;try{let{getIsolatedContext:A}=await Promise.resolve().then(()=>(ct(),Et)),U=await A();x=U.context,f=U.page}catch(A){let U=A instanceof Error?A.message:String(A);return d(JSON.stringify({status:"cannot_verify",url:o,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:U,httpChecks:i.map(({screenshot:H,..._})=>_),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${o}. 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 ${o}. 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(`
|
|
5408
|
+
`)}),!1)}try{let A=await Me(f,"Landing page",async()=>{await f.goto(o,{waitUntil:"domcontentloaded",timeout:3e4}),await f.waitForLoadState("networkidle").catch(()=>{});let F=await f.evaluate(()=>{let R=document.body;if(!R)return"";let C=document.createTreeWalker(R,NodeFilter.SHOW_TEXT),I="",L;for(;L=C.nextNode();){let M=L.parentElement;if(M){let D=window.getComputedStyle(M);D.display!=="none"&&D.visibility!=="hidden"&&parseFloat(D.opacity)>0&&(I+=L.textContent?.trim()+" ")}}return I.trim()});if(F.length<50)return{pass:!1,detail:`Landing page appears blank (${F.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 T=f.url();return T.includes("/login")||T.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 (${F.length} chars)`}});i.push(A),p==="none"&&i.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let U=w[0],H=(F,T)=>w.length>1&&F?`${T} (${F.role})`:T,_=!1;if(U?.password){let F=await Me(f,H(U,"Login"),async()=>{await f.goto(`${o}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{});let T=f.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),R=f.locator('input[type="password"], input[name="password"]');try{await T.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 T.first().fill(U.email),await R.first().fill(U.password),await f.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await f.waitForURL(I=>!I.pathname.includes("/login"),{timeout:1e4})}catch{let I=await f.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:I?`Login failed: ${I}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified QA accounts."}}return _=!0,{pass:!0,detail:`Logged in, redirected to ${f.url()}`}});i.push(F)}else U&&i.push({name:H(U,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!_&&U){let F=new URL(o).hostname,T=o.startsWith("https");await x.addCookies([{name:T?"__Secure-better-auth.session_token":"better-auth.session_token",value:U.sessionToken,domain:F,path:"/",httpOnly:!0,secure:T,sameSite:"Lax"}]),console.error(`[qa] Injected ${U.role} cookie for primary walk`)}if(U){let F=await Me(f,H(U,"Dashboard"),async()=>{f.url().includes("/dashboard")||(await f.goto(`${o}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{}),new URL(f.url()).pathname==="/"&&(await f.goto(`${o}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{})));let C=await f.content();return C.length<1e3?{pass:!1,detail:`Dashboard page is very small (${C.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await f.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 (${C.length} bytes)`}});i.push(F);let T=await f.evaluate(()=>{let C=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(L=>{let M=L.getAttribute("href");M&&M.startsWith("/")&&!M.startsWith("/api")&&!M.includes("[")&&M!=="/dashboard"&&M!=="/"&&!M.includes("/login")&&!M.includes("/sign")&&C.push(M)}),[...new Set(C)]});if(T.length>0){let C=0,I=[];for(let L of T.slice(0,8)){let M=await Me(f,H(U,`Page: ${L}`),async()=>{await f.goto(`${o}${L}`,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{});let D=await f.title(),$=await f.content();return D.toLowerCase().includes("500")||D.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."}:D.toLowerCase().includes("404")||D.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${L} not found. Create the page or remove the nav link.`}:await f.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:$.length<500?{pass:!1,detail:`Page is very small (${$.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});M.status==="fail"&&(C++,I.push(L)),i.push(M)}}let R=await Me(f,"Design quality",async()=>{let C=f.url().includes("/dashboard")?f.url():`${o}/dashboard`;f.url().includes("/dashboard")||(await f.goto(C,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{}));let I=await f.evaluate(()=>{let L=[],M=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),D=new Set;M.forEach(y=>{D.add(window.getComputedStyle(y).fontSize)}),M.length>=3&&D.size<2&&L.push("TYPOGRAPHY: All headings appear the same size. Create clear hierarchy with 3+ distinct sizes using a modular scale (1.25-1.5x ratio).");let $=Array.from(M).map(y=>parseInt(y.tagName.charAt(1),10));for(let y=1;y<$.length;y++)if($[y]-$[y-1]>1){L.push(`TYPOGRAPHY: Heading level skipped (h${$[y-1]} -> h${$[y]}). Use sequential heading levels for accessibility.`);break}let z=document.querySelectorAll("*"),J=!1,ee=!1;z.forEach(y=>{let v=window.getComputedStyle(y);v.backgroundColor==="rgb(0, 0, 0)"&&y.clientHeight>100&&y.clientWidth>200&&(J=!0);let q=v.backgroundColor,g=v.color;if(q&&!q.includes("0, 0, 0")&&!q.includes("255, 255, 255")&&q!=="rgba(0, 0, 0, 0)"&&q!=="transparent"&&g.match(/rgb\((\d+), (\d+), (\d+)\)/)){let k=g.match(/rgb\((\d+), (\d+), (\d+)\)/);if(k){let[E,V,Z]=[parseInt(k[1]),parseInt(k[2]),parseInt(k[3])],Q=Math.abs(E-V)<10&&Math.abs(V-Z)<10&&E>80&&E<180,P=q.match(/rgb\((\d+), (\d+), (\d+)\)/);if(Q&&P){let[j,X,te]=[parseInt(P[1]),parseInt(P[2]),parseInt(P[3])];!(Math.abs(j-X)<15&&Math.abs(X-te)<15)&&y.textContent&&y.textContent.trim().length>0&&(ee=!0)}}}}),J&&L.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)."),ee&&L.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 ve=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),ke=!1;ve.forEach(y=>{y.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(ke=!0)}),ke&&L.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let Y=document.querySelectorAll("p, li, span, div"),Te=0,Pe=0;Y.forEach(y=>{y.textContent&&y.textContent.trim().length>20&&y.clientHeight>0&&(Pe++,window.getComputedStyle(y).textAlign==="center"&&Te++)}),Pe>5&&Te/Pe>.7&&L.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let Ce=new Set;z.forEach(y=>{let v=window.getComputedStyle(y);v.gap&&v.gap!=="normal"&&v.gap!=="0px"&&Ce.add(v.gap)}),Ce.size===1&&z.length>20&&L.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let pe=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(y=>{y.querySelectorAll("tbody tr").length===0&&(y.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||L.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 Ge=document.querySelectorAll("style"),ue=!1;Ge.forEach(y=>{let v=y.textContent||"";(v.includes("bounce")||v.includes("elastic")||v.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(ue=!0)}),ue&&L.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let h=document.querySelectorAll("button, a, input, select, [role='button']"),b=0;return h.forEach(y=>{let v=y.getBoundingClientRect();v.width>0&&v.height>0&&(v.width<32||v.height<32)&&b++}),b>3&&L.push(`ACCESSIBILITY: ${b} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),L});return I.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${I.length} design quality issue(s) found:
|
|
5409
|
+
${I.map((L,M)=>`${M+1}. ${L}`).join(`
|
|
5410
|
+
`)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});i.push(R)}if(i.find(F=>F.name==="Landing page"&&F.status==="pass")){let F=await Me(f,"Landing design quality",async()=>{await f.goto(o,{waitUntil:"domcontentloaded",timeout:15e3}),await f.waitForLoadState("networkidle").catch(()=>{});let T=await f.evaluate(()=>{let R=[];document.querySelectorAll("*").forEach(M=>{let D=window.getComputedStyle(M);(D.getPropertyValue("-webkit-background-clip")||D.getPropertyValue("background-clip"))==="text"&&M.textContent&&M.textContent.trim().length>0&&R.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let I=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(I){let M=(I.textContent||"").toLowerCase(),D=["transform your","unlock the power","revolutionize your","take your .* to the next level","the future of","welcome to","get started today","join thousands","powerful analytics","seamless integration","lightning fast"];for(let $ of D)if(M.match(new RegExp($))){R.push(`COPY: Generic hero text detected ('${$}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(M=>{let $=window.getComputedStyle(M).gridTemplateColumns;if($){let z=$.split(" ").filter(ee=>ee!=="").length,J=M.children;if(z===3&&J.length===3){let ee=Array.from(J).map(Y=>Y.offsetHeight),ve=ee.every(Y=>Math.abs(Y-ee[0])<5),ke=Array.from(J).every(Y=>{let Te=Y.querySelectorAll("svg"),Pe=Y.querySelectorAll("h2, h3, h4"),Ce=Y.querySelectorAll("p");return Te.length>=1&&Pe.length>=1&&Ce.length>=1});ve&&ke&&R.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),R});return T.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${T.length} landing design issue(s):
|
|
5411
|
+
${T.map((R,C)=>`${C+1}. ${R}`).join(`
|
|
5412
|
+
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(F)}let K=w[1];if(K){let{getIsolatedContext:F}=await Promise.resolve().then(()=>(ct(),Et)),T=await F();S=T.context;let R=T.page,C=new URL(o).hostname,I=o.startsWith("https");await S.addCookies([{name:I?"__Secure-better-auth.session_token":"better-auth.session_token",value:K.sessionToken,domain:C,path:"/",httpOnly:!0,secure:I,sameSite:"Lax"}]),console.error(`[qa] Injected ${K.role} cookie for secondary walk`);let L=await Me(R,H(K,"Dashboard"),async()=>{await R.goto(`${o}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await R.waitForLoadState("networkidle").catch(()=>{}),new URL(R.url()).pathname==="/"&&(await R.goto(`${o}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await R.waitForLoadState("networkidle").catch(()=>{}));let D=await R.content();return D.length<1e3?{pass:!1,detail:`Dashboard is very small (${D.length} bytes) for the default-role user`,fix:"The default-role user dashboard crashed or rendered empty. Check that role-gated server components handle non-admin roles without throwing."}:await R.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary for the default-role user",fix:"A server component crashed under the non-admin role. Likely a role check that throws instead of redirecting."}:{pass:!0,detail:`Loads (${D.length} bytes)`}});i.push(L);let M=await R.evaluate(()=>{let D=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach($=>{let z=$.getAttribute("href");z&&z.startsWith("/")&&!z.startsWith("/api")&&!z.includes("[")&&z!=="/dashboard"&&z!=="/"&&!z.includes("/login")&&!z.includes("/sign")&&D.push(z)}),[...new Set(D)]});for(let D of M.slice(0,8)){let $=await Me(R,H(K,`Page: ${D}`),async()=>{await R.goto(`${o}${D}`,{waitUntil:"domcontentloaded",timeout:15e3}),await R.waitForLoadState("networkidle").catch(()=>{});let z=await R.title(),J=await R.content();return z.toLowerCase().includes("500")||z.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 for the default-role user",fix:"Server component crashed under the non-admin role. Check role gates use redirect() not throw."}:z.toLowerCase().includes("404")||z.toLowerCase().includes("not found")?{pass:!0,detail:"404 (likely admin-only \u2014 acceptable)"}:await R.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Error boundary on page for default-role user",fix:"Role-gated content crashed. Use a graceful fallback."}:J.length<500?{pass:!1,detail:`Page very small (${J.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});i.push($)}}}finally{x&&await x.close().catch(()=>{}),S&&await S.close().catch(()=>{})}if(t.deploymentId){let A=i.filter(_=>_.status==="fail"),U=i.filter(_=>_.status==="pass"),H=Date.now();await _o(t.deploymentId,{checks:i.map(({screenshot:_,...K})=>K),overall:A.length===0?"pass":"fail",passed:U.length,failed:A.length,duration_ms:Date.now()-H}).catch(()=>{})}return po(o,i)}function po(t,e){let r=e.filter(i=>i.status==="fail"),o=e.filter(i=>i.status==="pass"),s=[];if(r.length===0)s.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,...n})=>n)})});else{let i=r.map((n,a)=>`${a+1}. **${n.name}**: ${n.detail}
|
|
5417
5413
|
Fix: ${n.fix}`).join(`
|
|
5418
5414
|
|
|
5419
|
-
`);s.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${r.length} issue(s) on the live app. Fix them and redeploy.`,url:
|
|
5415
|
+
`);s.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${r.length} issue(s) on the live app. Fix them and redeploy.`,url:t,passed:o.length,failed:r.length,checks:e.map(({screenshot:n,...a})=>a),fixInstructions:`The deployed app at ${t} has ${r.length} issue(s):
|
|
5420
5416
|
|
|
5421
5417
|
${i}
|
|
5422
5418
|
|
|
5423
|
-
Fix these issues in the source code, then call mist_deploy with action='deploy'${
|
|
5424
|
-
${s.stderr.slice(-500)}`:""))}let i=0;try{i=
|
|
5419
|
+
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&&s.push({type:"image",data:i.screenshot,mimeType:"image/png"});return{content:s}}import{z as Ue}from"zod";import{resolve as Vc,join as Kc}from"path";import{existsSync as Jc}from"fs";le();$e();$e();import{existsSync as uo,readdirSync as Hc,statSync as Ts,unlinkSync as Ps}from"fs";import{join as He}from"path";import{execFile as Wc}from"child_process";function Gc(t,e){let r=0;for(let o of e){let s=He(t,o);if(uo(s))try{let i=Ts(s);if(i.isFile())r++;else if(i.isDirectory()){let n=[s];for(;n.length;){let a=n.pop(),l=Hc(a,{withFileTypes:!0});for(let c of l){let m=He(a,c.name);c.isDirectory()?n.push(m):r++}}}}catch{}}return r}function Cs(t,e,r){return new Promise(o=>{Wc("tar",t,{cwd:e,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(s,i,n)=>{o({success:!s,stderr:n?.toString()??""})})})}async function Is(t){let e=He(t,".open-next-build.tar.gz"),r=[".open-next"];uo(He(t,"db"))&&r.push("db"),uo(He(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),uo(He(t,"package.json"))&&r.push("package.json");let o=Gc(t,r),s=await Cs(["-czf",e,"-C",t,...r],t,12e4);if(!s.success){try{Ps(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(s.stderr?`
|
|
5420
|
+
${s.stderr.slice(-500)}`:""))}let i=0;try{i=Ts(e).size}catch{}return{path:e,sizeBytes:i,fileCount:o}}async function As(t){let e=He(t,".mistflow-source.tar.gz");return(await Cs(["-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 ur(t){if(t)try{Ps(t)}catch{}}function _s(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function Rs(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 Yc=Ue.object({action:Ue.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:Ue.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:Ue.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:Ue.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:Ue.string().optional().describe("Optional override for the owner email. Defaults to the email of whoever ran mist_setup (read from ~/.mistflow/credentials.json). Multi-role apps auto-promote this email to admin on first signup; single-role apps just attach it to the project for the dashboard's Owner Access card. Pass explicitly only when the deploying user is not the intended owner."),waitSeconds:Ue.number().min(0).max(20).optional().describe("On action='status' calls: long-poll the backend for up to N seconds (0-20) before returning, so a typical deploy fits in 1-2 round-trips instead of 6-12. Default 20. Ignored for non-status actions."),envVarsRequired:Ue.array(eo).optional().describe("Last chance to declare env vars introduced since the last implement call. Merged into mistflow.json env.required before the build is tarred, so the backend's deploy-time check picks them up. Skip keys covered by integration presets (Stripe, Resend, etc.). Only used for action='deploy'.")});function Qc(t){return Jc(Kc(t,".open-next"))}function Xc(t){return Re(t)?.deploy?.strategy==="staging"?"preview":null}async function Zc(t){let e=Vc(t.projectPath);if(!ne())return d("Not signed in. Call mist_setup first.",!0);let o=Re(e)?.projectId;if(!o)return d(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);if(!Qc(e))return d(`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??Xc(e)??"production",i=t.adminEmail??Nr()?.email,n=null,a=null;try{n=await Is(e),a=await As(e);let l=await To(o,n.path,s,i,void 0,a??void 0,void 0);return d(JSON.stringify({status:"running",jobId:l.deployment_id,deploymentId:l.deployment_id,environment:l.environment??s,buildSize:_s(n.sizeBytes),buildFileCount:n.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${l.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side, so there's no need to sleep between calls. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(l){let c=l instanceof W||l instanceof Error?l.message:String(l);return d(`Deploy upload failed: ${c}`,!0)}finally{ur(n?.path),ur(a)}}async function ed(t,e){let r=e.ctx?xe(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let o=await ut(t,{waitSeconds:e.waitSeconds}),s=Rs(o.status);return o.status==="live"?d(JSON.stringify({status:"complete",jobId:o.id,deploymentId:o.id,url:o.url,completedAt:o.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${o.url??""}', deploymentId: '${o.id??""}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`})):o.status==="failed"?d(JSON.stringify({status:"failed",jobId:o.id,deploymentId:o.id,error:o.error,phase:s,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):d(JSON.stringify({status:"running",jobId:o.id,deploymentId:o.id,phase:s,phaseCode:o.status,nextAction:`Still ${o.status} after the ${e.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${o.id}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(o){let s=o instanceof W||o instanceof Error?o.message:String(o);return d(`Could not fetch deploy status: ${s}`,!0)}finally{r.stop()}}async function td(t,e){if(!ne())return d("Not signed in. Call mist_setup first.",!0);let o=Re(t)?.projectId;if(!o)return d(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let s=e;if(!s)try{let n=(await Je(o)).find(a=>a.environment==="preview"&&a.status==="live");if(!n)return d("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);s=n.id}catch(i){let n=i instanceof W?i.message:String(i);return d(`Could not list deployments: ${n}`,!0)}try{let i=await Oo(o,s);return d(JSON.stringify({status:"running",jobId:i.deployment_id,deploymentId:i.deployment_id,promotedFrom:s,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${i.deployment_id}' } immediately \u2014 long-polls for up to 20s. Promotion re-uses the preview artifact and typically completes in ~10s, so one poll usually finishes the job.`}))}catch(i){let n=i instanceof W||i instanceof Error?i.message:String(i);return d(`Promote failed: ${n}`,!0)}}async function od(t){if(!ne())return d("Not signed in. Call mist_setup first.",!0);try{let e=await Mo(t);return d(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let r=e instanceof W||e instanceof Error?e.message:String(e);return d(`Rollback failed: ${r}`,!0)}}var Es={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:Yc,handler:async(t,e)=>{let r=t;switch(r.action??"deploy"){case"deploy":{if(!r.projectPath)return d("projectPath is required for action='deploy'.",!0);if(r.envVarsRequired&&r.envVarsRequired.length>0)try{let s=to(r.projectPath,r.envVarsRequired);s.added.length>0&&console.error(`[deploy] declared env.required: ${s.added.join(", ")}`)}catch(s){console.error("[deploy] env var merge skipped:",s instanceof Error?s.message:String(s))}return Zc({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail})}case"status":return r.deploymentId?ed(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e}):d("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?td(r.projectPath,r.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?od(r.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}};var mo=new rd({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:wr()}),Ns=[Br,Zr,en,rn,Sn,En,pn,os,mn,ss,ys,vs,Ss,Es];mo.setRequestHandler(id,async()=>({tools:Ns.map(t=>({name:t.name,description:t.description,inputSchema:ad(t.inputSchema)}))}));mo.setRequestHandler(sd,async t=>{let e=Ns.find(r=>r.name===t.params.name);if(!e)return d(`Unknown tool: ${t.params.name}`,!0);try{let r=e.inputSchema.safeParse(t.params.arguments);if(!r.success){let i=r.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join(", ");return d(`Invalid input: ${i}`,!0)}let o=t.params._meta?.progressToken,s={server:mo,progressToken:o};try{return await e.handler(r.data,s)}finally{s.cleanup?.()}}catch(r){let o=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),d(o,!0)}});async function ld(){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 nd;await mo.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}ld().catch(t=>{console.error("Fatal error:",t),process.exit(1)});
|