@mistflow-ai/mcp 1.0.12 → 1.0.13
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 +154 -150
- package/dist/index.js +142 -138
- 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 Qs=Object.defineProperty;var tt=(e,t)=>()=>(e&&(t=e(e=0)),t);var $t=(e,t)=>{for(var r in t)Qs(e,r,{get:t[r],enumerable:!0})};import{existsSync as To,readFileSync as Ur,writeFileSync as ai,mkdirSync as li}from"fs";import{join as ko,dirname as So}from"path";import{homedir as ci}from"os";import{fileURLToPath as di}from"url";function ve(){if(Ft)return Ft;try{let e=di(import.meta.url),t=So(e);for(let r=0;r<6;r++){let o=ko(t,"package.json");if(To(o)){let i=JSON.parse(Ur(o,"utf-8"));if(i.name==="@mistflow-ai/mcp"&&typeof i.version=="string")return Ft=i.version,i.version}let s=So(t);if(s===t)break;t=s}}catch{}return Ft="0.0.0","0.0.0"}function qt(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim());return t?[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)]:null}function Or(e,t){let r=qt(e),o=qt(t);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 $r(e,t,r){if(r&&Or(e,r)<0)return"unsupported";if(!t||Or(e,t)>=0)return"none";let s=qt(e),i=qt(t);return!s||!i?"none":s[0]<i[0]?"major":s[1]<i[1]?"minor":"patch"}function bt(e){let t=e.get("x-mistflow-mcp-latest")??"",r=e.get("x-mistflow-mcp-min-supported")??"",o=e.get("x-mistflow-mcp-changelog-url")??"";!t&&!r||(we={latest:t,minSupported:r,changelogUrl:o})}function Fr(){let e=process.env.MISTFLOW_STATE_DIR||ko(ci(),".mistflow");return ko(e,"upgrade-state.json")}function pi(){try{let e=Fr();return To(e)?JSON.parse(Ur(e,"utf-8")):{}}catch{return{}}}function ui(e){try{let t=Fr(),r=So(t);To(r)||li(r,{recursive:!0}),ai(t,JSON.stringify(e,null,2)+`
|
|
2
|
+
`,{mode:384})}catch{}}function mi(e){return e==="patch"?7*864e5:e==="minor"?1*864e5:0}function qr(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!we)return null;let e=ve();if(e==="0.0.0")return null;let t=$r(e,we.latest,we.minSupported);if(t==="none")return null;if(t==="unsupported")return Lr(t,e,we);if(Mr)return null;let r=pi(),o=Date.now(),s=mi(t);return r.dismissedForVersion===we.latest&&t!=="major"||r.lastLatestSeen===we.latest&&r.lastShownMs&&o-r.lastShownMs<s?null:(Mr=!0,ui({...r,lastShownMs:o,lastLatestSeen:we.latest}),Lr(t,e,we))}function Lr(e,t,r){let o="npx -y mistflow-ai install",s=r.changelogUrl?`
|
|
3
|
+
What's new: ${r.changelogUrl}`:"";return e==="unsupported"?`
|
|
4
4
|
|
|
5
5
|
---
|
|
6
|
-
Mistflow ${
|
|
6
|
+
Mistflow ${t} 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
|
+
---`:e==="major"?`
|
|
13
13
|
|
|
14
14
|
---
|
|
15
|
-
Mistflow ${r.latest} is available (you have ${
|
|
15
|
+
Mistflow ${r.latest} is available (you have ${t}).
|
|
16
16
|
This is a major update. Run \`${o}\` and restart your editor.${s}
|
|
17
|
-
---`:
|
|
17
|
+
---`:e==="minor"?`
|
|
18
18
|
|
|
19
|
-
--- Mistflow update available: ${
|
|
19
|
+
--- Mistflow update available: ${t} -> ${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}),yi(i,e)}catch(n){try{bi(i)}catch{}throw n}}function ee(){return et().ok}function Me(t){let e=Ao(t,"mistflow.json");if(!Co(e))return null;try{return JSON.parse(zr(e,"utf-8"))}catch{return null}}var xi,tt=Ze(()=>{"use strict";xi="https://api.mistflow.ai"});var Qr={};Mt(Qr,{MistflowApiError:()=>U,addDomain:()=>jo,checkAuth:()=>Ii,checkAuthDetailed:()=>Jr,checkSubdomain:()=>Eo,createDeployment:()=>Ai,createProject:()=>xt,deleteEnvVar:()=>Fo,discoverDecisions:()=>_i,downloadSource:()=>Ni,downloadSourceWithToken:()=>Yr,fetchDesignDirections:()=>Do,fetchModule:()=>Vo,fetchPlanConversation:()=>zt,fetchScaffold:()=>Wo,fetchStepContext:()=>Go,forkTemplate:()=>Jo,generatePlan:()=>Ht,getAuthHeaders:()=>Ve,getBaseUrl:()=>te,getDashboardUrl:()=>Si,getDbCredentials:()=>Ri,getDeployLogs:()=>qo,getDeploymentStatus:()=>St,getProject:()=>Ci,getProjectErrors:()=>Bo,getSeedInfo:()=>Mo,getSiteUrl:()=>ot,getTemplate:()=>Ko,hasCredentialsOnDisk:()=>ee,hasLocalCredentials:()=>Kr,listDeployments:()=>nt,listDomains:()=>Le,listEnvVars:()=>Uo,markLocalSetupDone:()=>Di,modifyPlan:()=>Wt,pingBackend:()=>Ro,promotePreview:()=>zo,redeployProject:()=>Ei,removeDomain:()=>Oo,rollbackDeployment:()=>Ho,shareProject:()=>Yo,uploadAndDeploy:()=>No,uploadQAResults:()=>Lo,upsertEnvVar:()=>$o,verifyDomain:()=>Gt});function te(){return qt()}function ot(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9102")}return"https://mistflow.ai"}function Si(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function Ve(){let t=et();if(!t.ok)throw new U("auth_missing","No Mistflow credentials found.",401);return Ti(t.creds)}function Ti(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":ve()}}function rt(t){try{yt(t.headers)}catch{}}async function Ro(){try{let t=await fetch(`${te()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});rt(t)}catch{}}async function Vr(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 kt(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 U(r,o,t.status,e?.details);let s=t.status;return s===401?new U("auth_invalid",o,s):s===403?new U("permission_denied",o,s):s===404?new U("not_found",o,s):s===409?new U("conflict",o,s):s===422?new U("validation_error",o,s):s===429?new U("rate_limited",o,s):s>=500?new U("server_error",t.statusText||"Internal server error",s):new U("client_error",o,s)}async function $(t,e={}){let r=Ve(),{timeoutMs:o,idempotent:s,...i}=e,n=o??3e4,a=(i.method??"GET").toUpperCase(),l=s??(a==="GET"||a==="HEAD"),d;try{d=await Vr(`${te()}${t}`,{...i,headers:{...r,...i.headers}},n,l)}catch(h){throw h instanceof Error&&h.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(rt(d),!d.ok)throw await kt(d);return d.json()}function Kr(){return et().ok}async function Ii(){return(await Jr()).ok}async function Jr(){if(Bt!==null&&Date.now()<Gr)return Bt?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Kr())return{ok:!1,reason:"no_credentials"};try{return await $("/api/org"),Bt=!0,Gr=Date.now()+Pi,{ok:!0}}catch(t){if(Bt=null,!(t instanceof U))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function Ci(t){return $(`/api/projects/${encodeURIComponent(t)}`)}async function Eo(t){return $(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function xt(t,e,r="neon",o){return $("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e,db_provider:r,requested_subdomain:o})})}async function Ai(t,e){return $("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function No(t,e,r="production",o,s,i,n){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),d=et();if(!d.ok)throw new U("auth_missing","No Mistflow credentials found.",401);let h=d.creds,m=a(e),p=new Blob([m],{type:"application/gzip"}),y=new FormData;if(y.append("project_id",t),y.append("build",p,l(e)),r!=="production"&&y.append("environment",r),o&&y.append("admin_email",o),s&&y.append("schema_pushed","true"),i){let{existsSync:f}=await import("fs");if(f(i)){let T=a(i),A=new Blob([T],{type:"application/gzip"});y.append("source",A,"source.tar.gz")}}n&&y.append("git_commit_sha",n);let x;try{x=await fetch(`${te()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":ve()},body:y,signal:AbortSignal.timeout(3e5)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(rt(x),!x.ok)throw await kt(x);let b=await x.json();return{...b,id:b.deployment_id}}async function St(t){return $(`/api/deploy/${encodeURIComponent(t)}/status`)}async function Do(t){return $(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function zt(t,e){let r=e?.waitSeconds??20,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return $(`/api/plan/conversations/${encodeURIComponent(t)}${o}`,{timeoutMs:s})}async function Ht(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 $("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:o,idempotent:!1})}async function Wt(t,e){return $("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function _i(t){return $("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function jo(t,e){return $(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function Le(t){return $(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Gt(t,e){return $(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Oo(t,e){return $(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ri(t){return $(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Mo(t){try{return await $(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof U&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Lo(t,e){try{return await $(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(r){return console.error("[api] Failed to upload QA results:",r instanceof Error?r.message:r),null}}async function Uo(t){return $(`/api/projects/${encodeURIComponent(t)}/env`)}async function $o(t,e,r,o){return $(`/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 Fo(t,e){return $(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function qo(t){return $(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Bo(t,e="7d"){return $(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function nt(t){return $(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function Ei(t){return $(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function zo(t,e){let r=new URLSearchParams({preview_deployment_id:e});return $(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Ho(t){return $(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function Ni(t,e){let r=et();if(!r.ok)throw new U("auth_missing","Not authenticated.",401);let o=r.creds,s=await fetch(`${te()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${o.apiKey}`,"X-Mistflow-MCP-Version":ve()},signal:AbortSignal.timeout(12e4)});if(rt(s),!s.ok)throw await kt(s);let{writeFileSync:i}=await import("fs"),n=Buffer.from(await s.arrayBuffer());i(e,n)}async function Vt(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 Vr(`${te()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":ve()},...s},i,a)}catch(d){throw d instanceof Error&&d.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(rt(l),!l.ok)throw await kt(l);return l.json()}async function Wo(t="nextjs"){return Vt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Go(t,e){return Vt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Vo(t,e,r,o){return Vt(`/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 Ko(t){return Vt(`/api/templates/${encodeURIComponent(t)}`)}async function Jo(t){return $(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Yr(t,e,r){let o;try{o=await fetch(`${te()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":ve()},signal:AbortSignal.timeout(12e4)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(rt(o),!o.ok)throw o.status===401?new U("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",o.status):await kt(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(r,i)}async function Di(t){await $(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Yo(t,e){return $(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}var U,Bt,Gr,Pi,me=Ze(()=>{"use strict";tt();bt();U=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"}};Bt=null,Gr=0,Pi=300*1e3});var It={};Mt(It,{emptyState:()=>Pt,fetchRemoteState:()=>Gi,fuzzyMatch:()=>Ki,getLocalStatePath:()=>Xo,readLocalState:()=>Wi,syncRemoteState:()=>Vi,writeLocalState:()=>Tt});import{existsSync as rn,readFileSync as Bi,writeFileSync as zi,mkdirSync as Hi}from"fs";import{join as nn}from"path";function Xo(t){return nn(t,".mistflow","state.json")}function Wi(t){let e=Xo(t);if(!rn(e))return null;try{return JSON.parse(Bi(e,"utf-8"))}catch{return null}}function Tt(t,e){let r=nn(t,".mistflow");rn(r)||Hi(r,{recursive:!0}),zi(Xo(t),JSON.stringify(e,null,2)+`
|
|
24
|
-
`)}function Pt(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Gi(t){let e;try{e=Ve()}catch{return null}try{let r=await fetch(`${te()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":ve()}});try{yt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function Vi(t,e){let r;try{r=Ve()}catch{return!1}try{let o=await fetch(`${te()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":ve()},body:JSON.stringify(e)});try{yt(o.headers)}catch{}return o.ok}catch{return!1}}function Ki(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 Ke=Ze(()=>{"use strict";me();bt()});var Zo={};Mt(Zo,{ensureBackendRegistered:()=>ta,ensureShadcnComponents:()=>oa});import{existsSync as an,readFileSync as Ji,writeFileSync as Yi}from"fs";import{join as Kt}from"path";import{spawn as Qi}from"child_process";function Xi(t,e,r,o,s){return new Promise(i=>{let n=Qi(t,e,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:o,...s?{env:{...process.env,...s}}:{}}),a="",l="";n.stdout?.on("data",d=>{a+=d.toString()}),n.stderr?.on("data",d=>{l+=d.toString()}),n.on("close",d=>i({success:d===0,stdout:a,stderr:l})),n.on("error",d=>i({success:!1,stdout:a,stderr:l+d.message}))})}function Zi(t){let e=Kt(t,"mistflow.json");if(!an(e))return null;try{return JSON.parse(Ji(e,"utf-8"))}catch{return null}}function ea(t,e){Yi(Kt(t,"mistflow.json"),JSON.stringify(e,null,2))}async function sn(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(`${te()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...Ve(),"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 ta(t,e={}){let r=Zi(t);if(r){if(!ee())return r.projectId;if(!r.projectId)try{let s=r.plan?.requestedSubdomain,i=await xt(r.name,void 0,r.dbProvider??"neon",s);return r.projectId=i.id,ea(t,r),Tt(t,Pt(i.id,r.name)),r.plan&&await sn(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 sn(r.projectId,r.plan),r.projectId}}async function oa(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=Kt(t,"components","ui"),i=[],n=[];for(let d of o)an(Kt(s,`${d}.tsx`))?i.push(d):n.push(d);if(n.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Xi("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 er=Ze(()=>{"use strict";me();Ke()});import{Server as dd}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as pd}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as ud,ListToolsRequestSchema as md}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as hd}from"zod-to-json-schema";var Qs="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.",Xs='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"`.',Zs="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.",ei="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.",ti='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.',oi="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.",ri="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.",ni='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.',si="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.",Cr="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).",Ar="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.",_r="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.",Rr="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.",Er="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).",Nr="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 Dr(){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(ni),t.push(""),t.push(Qs),t.push(""),t.push(Xs),t.push(""),t.push(Zs),t.push(""),t.push(ei),t.push(""),t.push(si),t.push(""),t.push(oi),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(ti),t.push(""),t.push(ri),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
|
-
`)}
|
|
22
|
+
(Mistflow ${r.latest} is out, you have ${t}. Run \`${o}\` when convenient.)`}function Po(){let e=ve(),t=we??{latest:"",minSupported:"",changelogUrl:""},r=$r(e,t.latest,t.minSupported);return{current:e,latest:t.latest,minSupported:t.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:t.changelogUrl,backendSignalReceived:we!==null}}var Ft,we,Mr,wt=tt(()=>{"use strict";Ft=null;we=null;Mr=!1});var Ao={};$t(Ao,{closeBrowser:()=>Co,getIsolatedContext:()=>gi,getPage:()=>Io,getSnapshot:()=>vt,takeScreenshot:()=>xt});async function Br(){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 hi(){let e=await Br();return(!xe||!xe.isConnected())&&(xe=await e.chromium.launch({headless:!0})),Me&&(await Me.close().catch(()=>{}),Me=null),Me=await xe.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),_e=await Me.newPage(),_e}async function Io(){return _e&&!_e.isClosed()?_e:(Bt||(Bt=hi().finally(()=>{Bt=null})),Bt)}async function Co(){_e&&!_e.isClosed()&&await _e.close().catch(()=>{}),Me&&await Me.close().catch(()=>{}),xe?.isConnected()&&await xe.close().catch(()=>{}),_e=null,Me=null,xe=null}async function gi(){let e=await Br();(!xe||!xe.isConnected())&&(xe=await e.chromium.launch({headless:!0}));let t=await xe.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await t.newPage();return{context:t,page:r}}async function vt(e){return await e.locator("body").ariaSnapshot()}async function xt(e,t=!1){return await e.screenshot({fullPage:t,type:"png"})}var xe,Me,_e,Bt,zt=tt(()=>{"use strict";xe=null,Me=null,_e=null,Bt=null;process.once("SIGTERM",()=>{Co().finally(()=>process.exit(0))});process.once("SIGINT",()=>{Co().finally(()=>process.exit(0))})});import{readFileSync as Hr,existsSync as _o,writeFileSync as fi,mkdirSync as yi,renameSync as bi,unlinkSync as wi}from"fs";import{join as Ro,dirname as vi}from"path";import{homedir as xi}from"os";import{randomBytes as ki}from"crypto";function Wr(){return Ro(xi(),".mistflow","credentials.json")}function Ht(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function Gr(){let e=Wr();if(!_o(e))return null;try{let t=JSON.parse(Hr(e,"utf-8"));return typeof t.apiKey=="string"?{[Si]:t}:t}catch{return null}}function ot(){let e=process.env.MISTFLOW_API_KEY;if(e)return{ok:!0,creds:{apiKey:e,orgId:"",orgSlug:"env"}};let t=Gr();if(!t)return{ok:!1,reason:"missing"};let r=Ht(),o=t[r];return o&&typeof o.apiKey=="string"&&o.apiKey&&typeof o.orgId=="string"?{ok:!0,creds:o}:{ok:!1,reason:"missing"}}function Eo(e){let t=Wr(),r=vi(t);_o(r)||yi(r,{recursive:!0});let o=Gr()??{},s=Ht();o[s]=e;let i=Ro(r,`.credentials.tmp.${ki(8).toString("hex")}`);try{fi(i,JSON.stringify(o,null,2)+`
|
|
23
|
+
`,{mode:384}),bi(i,t)}catch(n){try{wi(i)}catch{}throw n}}function ee(){return ot().ok}function Le(e){let t=Ro(e,"mistflow.json");if(!_o(t))return null;try{return JSON.parse(Hr(t,"utf-8"))}catch{return null}}var Si,rt=tt(()=>{"use strict";Si="https://api.mistflow.ai"});var Xr={};$t(Xr,{MistflowApiError:()=>U,addDomain:()=>Mo,checkAuth:()=>Ci,checkAuthDetailed:()=>Yr,checkSubdomain:()=>Do,createDeployment:()=>_i,createProject:()=>St,deleteEnvVar:()=>Bo,discoverDecisions:()=>Ri,downloadSource:()=>Di,downloadSourceWithToken:()=>Qr,fetchDesignDirections:()=>Oo,fetchModule:()=>Jo,fetchPlanConversation:()=>Gt,fetchScaffold:()=>Vo,fetchStepContext:()=>Ko,forkTemplate:()=>Qo,generatePlan:()=>Vt,getAuthHeaders:()=>Ke,getBaseUrl:()=>te,getDashboardUrl:()=>Ti,getDbCredentials:()=>Ei,getDeployLogs:()=>zo,getDeploymentStatus:()=>Tt,getProject:()=>Ai,getProjectErrors:()=>Ho,getSeedInfo:()=>Uo,getSiteUrl:()=>nt,getTemplate:()=>Yo,hasCredentialsOnDisk:()=>ee,hasLocalCredentials:()=>Jr,listDeployments:()=>it,listDomains:()=>Ue,listEnvVars:()=>Fo,markLocalSetupDone:()=>ji,modifyPlan:()=>Kt,pingBackend:()=>No,promotePreview:()=>Wo,redeployProject:()=>Ni,removeDomain:()=>Lo,rollbackDeployment:()=>Go,shareProject:()=>Xo,uploadAndDeploy:()=>jo,uploadQAResults:()=>$o,upsertEnvVar:()=>qo,verifyDomain:()=>Jt});function te(){return Ht()}function nt(){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 Ti(){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 Ke(){let e=ot();if(!e.ok)throw new U("auth_missing","No Mistflow credentials found.",401);return Pi(e.creds)}function Pi(e){return{Authorization:`ApiKey ${e.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":ve()}}function st(e){try{bt(e.headers)}catch{}}async function No(){try{let e=await fetch(`${te()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});st(e)}catch{}}async function Kr(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 kt(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 U(r,o,e.status,t?.details);let s=e.status;return s===401?new U("auth_invalid",o,s):s===403?new U("permission_denied",o,s):s===404?new U("not_found",o,s):s===409?new U("conflict",o,s):s===422?new U("validation_error",o,s):s===429?new U("rate_limited",o,s):s>=500?new U("server_error",e.statusText||"Internal server error",s):new U("client_error",o,s)}async function $(e,t={}){let r=Ke(),{timeoutMs:o,idempotent:s,...i}=t,n=o??3e4,a=(i.method??"GET").toUpperCase(),l=s??(a==="GET"||a==="HEAD"),c;try{c=await Kr(`${te()}${e}`,{...i,headers:{...r,...i.headers}},n,l)}catch(h){throw h instanceof Error&&h.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(st(c),!c.ok)throw await kt(c);return c.json()}function Jr(){return ot().ok}async function Ci(){return(await Yr()).ok}async function Yr(){if(Wt!==null&&Date.now()<Vr)return Wt?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Jr())return{ok:!1,reason:"no_credentials"};try{return await $("/api/org"),Wt=!0,Vr=Date.now()+Ii,{ok:!0}}catch(e){if(Wt=null,!(e instanceof U))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 Ai(e){return $(`/api/projects/${encodeURIComponent(e)}`)}async function Do(e){return $(`/api/projects/check-subdomain?name=${encodeURIComponent(e)}`)}async function St(e,t,r="neon",o){return $("/api/projects",{method:"POST",body:JSON.stringify({name:e,template:t,db_provider:r,requested_subdomain:o})})}async function _i(e,t){return $("/api/deploy",{method:"POST",body:JSON.stringify({project_id:e,build_output_url:t})})}async function jo(e,t,r="production",o,s,i,n){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=ot();if(!c.ok)throw new U("auth_missing","No Mistflow credentials found.",401);let h=c.creds,m=a(t),p=new Blob([m],{type:"application/gzip"}),f=new FormData;if(f.append("project_id",e),f.append("build",p,l(t)),r!=="production"&&f.append("environment",r),o&&f.append("admin_email",o),s&&f.append("schema_pushed","true"),i){let{existsSync:y}=await import("fs");if(y(i)){let v=a(i),C=new Blob([v],{type:"application/gzip"});f.append("source",C,"source.tar.gz")}}n&&f.append("git_commit_sha",n);let x;try{x=await fetch(`${te()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":ve()},body:f,signal:AbortSignal.timeout(3e5)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(st(x),!x.ok)throw await kt(x);let b=await x.json();return{...b,id:b.deployment_id}}async function Tt(e,t){let r=t?.waitSeconds??0,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return $(`/api/deploy/${encodeURIComponent(e)}/status${o}`,r>0?{timeoutMs:s}:void 0)}async function Oo(e){return $(`/api/plan/design-directions/${encodeURIComponent(e)}`,{timeoutMs:15e3})}async function Gt(e,t){let r=t?.waitSeconds??20,o=r>0?`?wait=${r}`:"",s=Math.min(6e4,(r+5)*1e3);return $(`/api/plan/conversations/${encodeURIComponent(e)}${o}`,{timeoutMs:s})}async function Vt(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 $("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:o,idempotent:!1})}async function Kt(e,t){return $("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:e,modification:t})})}async function Ri(e){return $("/api/plan/discover",{method:"POST",body:JSON.stringify({description:e})})}async function Mo(e,t){return $(`/api/projects/${encodeURIComponent(e)}/domains`,{method:"POST",body:JSON.stringify({domain:t})})}async function Ue(e){return $(`/api/projects/${encodeURIComponent(e)}/domains`)}async function Jt(e,t){return $(`/api/projects/${encodeURIComponent(e)}/domains/${encodeURIComponent(t)}/verify`)}async function Lo(e,t){return $(`/api/projects/${encodeURIComponent(e)}/domains/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Ei(e){return $(`/api/projects/${encodeURIComponent(e)}/db-credentials`)}async function Uo(e){try{return await $(`/api/projects/${encodeURIComponent(e)}/test-accounts`)}catch(t){return t instanceof U&&(t.statusCode===404||t.code==="not_found")||console.error("[api] Failed to fetch seed info:",t instanceof Error?t.message:t),null}}async function $o(e,t){try{return await $(`/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 Fo(e){return $(`/api/projects/${encodeURIComponent(e)}/env`)}async function qo(e,t,r,o){return $(`/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 Bo(e,t){return $(`/api/projects/${encodeURIComponent(e)}/env/${encodeURIComponent(t)}`,{method:"DELETE"})}async function zo(e){return $(`/api/deploy/${encodeURIComponent(e)}/logs`)}async function Ho(e,t="7d"){return $(`/api/projects/${encodeURIComponent(e)}/errors?period=${encodeURIComponent(t)}`)}async function it(e){return $(`/api/projects/${encodeURIComponent(e)}/deployments`)}async function Ni(e){return $(`/api/deploy/${encodeURIComponent(e)}/redeploy`,{method:"POST"})}async function Wo(e,t){let r=new URLSearchParams({preview_deployment_id:t});return $(`/api/deploy/${encodeURIComponent(e)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Go(e){return $(`/api/deploy/${encodeURIComponent(e)}/rollback`,{method:"POST"})}async function Di(e,t){let r=ot();if(!r.ok)throw new U("auth_missing","Not authenticated.",401);let o=r.creds,s=await fetch(`${te()}/api/deploy/${encodeURIComponent(e)}/source`,{headers:{Authorization:`ApiKey ${o.apiKey}`,"X-Mistflow-MCP-Version":ve()},signal:AbortSignal.timeout(12e4)});if(st(s),!s.ok)throw await kt(s);let{writeFileSync:i}=await import("fs"),n=Buffer.from(await s.arrayBuffer());i(t,n)}async function Yt(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 Kr(`${te()}${e}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":ve()},...s},i,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(st(l),!l.ok)throw await kt(l);return l.json()}async function Vo(e="nextjs"){return Yt(`/api/scaffold/${encodeURIComponent(e)}`)}async function Ko(e,t){return Yt(`/api/scaffold/${encodeURIComponent(e)}/context?step_type=${encodeURIComponent(t)}`)}async function Jo(e,t,r,o){return Yt(`/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 Yo(e){return Yt(`/api/templates/${encodeURIComponent(e)}`)}async function Qo(e){return $(`/api/templates/${encodeURIComponent(e)}/fork`,{method:"POST"})}async function Qr(e,t,r){let o;try{o=await fetch(`${te()}/api/deploy/${encodeURIComponent(e)}/fork-source?fork_token=${encodeURIComponent(t)}`,{headers:{"X-Mistflow-MCP-Version":ve()},signal:AbortSignal.timeout(12e4)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(st(o),!o.ok)throw o.status===401?new U("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",o.status):await kt(o);let{writeFileSync:s}=await import("fs"),i=Buffer.from(await o.arrayBuffer());s(r,i)}async function ji(e){await $(`/api/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Xo(e,t){return $(`/api/projects/${encodeURIComponent(e)}/share`,{method:"POST",body:JSON.stringify({is_template:t?.isTemplate??!1,template_description:t?.description})})}var U,Wt,Vr,Ii,me=tt(()=>{"use strict";rt();wt();U=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"}};Wt=null,Vr=0,Ii=300*1e3});var Ct={};$t(Ct,{emptyState:()=>It,fetchRemoteState:()=>Vi,fuzzyMatch:()=>Ji,getLocalStatePath:()=>er,readLocalState:()=>Gi,syncRemoteState:()=>Ki,writeLocalState:()=>Pt});import{existsSync as nn,readFileSync as zi,writeFileSync as Hi,mkdirSync as Wi}from"fs";import{join as sn}from"path";function er(e){return sn(e,".mistflow","state.json")}function Gi(e){let t=er(e);if(!nn(t))return null;try{return JSON.parse(zi(t,"utf-8"))}catch{return null}}function Pt(e,t){let r=sn(e,".mistflow");nn(r)||Wi(r,{recursive:!0}),Hi(er(e),JSON.stringify(t,null,2)+`
|
|
24
|
+
`)}function It(e,t){return{projectId:e,name:t,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Vi(e){let t;try{t=Ke()}catch{return null}try{let r=await fetch(`${te()}/api/projects/${encodeURIComponent(e)}/state`,{headers:{...t,"Content-Type":"application/json","X-Mistflow-MCP-Version":ve()}});try{bt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function Ki(e,t){let r;try{r=Ke()}catch{return!1}try{let o=await fetch(`${te()}/api/projects/${encodeURIComponent(e)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":ve()},body:JSON.stringify(t)});try{bt(o.headers)}catch{}return o.ok}catch{return!1}}function Ji(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 Je=tt(()=>{"use strict";me();wt()});var tr={};$t(tr,{ensureBackendRegistered:()=>oa,ensureShadcnComponents:()=>ra});import{existsSync as ln,readFileSync as Yi,writeFileSync as Qi}from"fs";import{join as Qt}from"path";import{spawn as Xi}from"child_process";function Zi(e,t,r,o,s){return new Promise(i=>{let n=Xi(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 ea(e){let t=Qt(e,"mistflow.json");if(!ln(t))return null;try{return JSON.parse(Yi(t,"utf-8"))}catch{return null}}function ta(e,t){Qi(Qt(e,"mistflow.json"),JSON.stringify(t,null,2))}async function an(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(`${te()}/api/projects/${encodeURIComponent(e)}/state`,{method:"PUT",headers:{...Ke(),"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 oa(e,t={}){let r=ea(e);if(r){if(!ee())return r.projectId;if(!r.projectId)try{let s=r.plan?.requestedSubdomain,i=await St(r.name,void 0,r.dbProvider??"neon",s);return r.projectId=i.id,ta(e,r),Pt(e,It(i.id,r.name)),r.plan&&await an(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 an(r.projectId,r.plan),r.projectId}}async function ra(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=Qt(e,"components","ui"),i=[],n=[];for(let c of o)ln(Qt(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 Zi("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 or=tt(()=>{"use strict";me();Je()});import{Server as md}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as hd}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as gd,ListToolsRequestSchema as fd}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as yd}from"zod-to-json-schema";var Xs="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.",Zs='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"`.',ei="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.",ti="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.",oi='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.',ri="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.",ni="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.",si='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.',ii="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(si),e.push(""),e.push(Xs),e.push(""),e.push(Zs),e.push(""),e.push(ei),e.push(""),e.push(ti),e.push(""),e.push(ii),e.push(""),e.push(ri),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(oi),e.push(""),e.push(ni),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
|
+
`)}wt();function d(e,t=!1){let r=e;try{let o=qr();o&&(r=e+o)}catch{}return{content:[{type:"text",text:r}],isError:t}}function Re(e){return d(`This is not a Mistflow project (no mistflow.json found at ${e}).
|
|
26
26
|
|
|
27
27
|
Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
|
|
28
28
|
|
|
@@ -31,17 +31,17 @@ To get started:
|
|
|
31
31
|
2. Call mist_init({ planId, path: "<absolute-path>" })
|
|
32
32
|
3. Call mist_install({ projectPath }), then mist_implement({ projectPath })
|
|
33
33
|
|
|
34
|
-
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function
|
|
34
|
+
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function zr(e,t){try{let{getPage:r,takeScreenshot:o}=await Promise.resolve().then(()=>(zt(),Ao)),s=await r();await s.goto(e,{waitUntil:"domcontentloaded",timeout:15e3}),await s.waitForLoadState("networkidle").catch(()=>{});let i=await o(s,!1);return{content:[{type:"text",text:t},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}catch{return d(t)}}import{z as Zo}from"zod";import{platform as Oi}from"os";import{execFile as Zr}from"child_process";me();rt();var Mi=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 Li(e){return"error"in e}function tn(e){return new Promise(t=>setTimeout(t,e))}function Ui(e){return new Promise(t=>{let r=Oi();r==="win32"?Zr("cmd.exe",["/c","start","",e],o=>{o&&console.error("Could not open browser:",o.message),t(!o)}):Zr(r==="darwin"?"open":"xdg-open",[e],s=>{s&&console.error("Could not open browser:",s.message),t(!s)}),setTimeout(()=>t(!1),5e3)})}var $i={fetch:globalThis.fetch,openBrowser:Ui,sleep:tn};async function en(e,t,r,o){let s=r,i=o.sleep??tn;for(let n=0;n<t;n++){await i(s);let a;try{let c=await o.fetch(`${te()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e})});if(!c.ok)continue;a=await c.json()}catch{continue}if(Li(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 Eo({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 Fi(e,t=$i){let r=e;if(r?.apiKey)try{let n=await t.fetch(`${te()}/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 Eo({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 en(r.deviceCode,6,5e3,t);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 t.fetch(`${te()}/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:x}))}let i=[];if(
|
|
40
|
-
`),s.projectId&&Promise.resolve().then(()=>(
|
|
37
|
+
`);try{await t.openBrowser(s)}catch{}let i=await en(o.device_code,6,5e3,t);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 on={name:"mist_setup",description:Ar,inputSchema:Mi,handler:e=>Fi(e)};import{z as le}from"zod";import{resolve as Zt}from"path";import{existsSync as eo,readFileSync as to}from"fs";import{join as oo}from"path";import{z as $e}from"zod";import{resolve as na,join as cn}from"path";import{existsSync as sa,readFileSync as dn,writeFileSync as ia}from"fs";import{existsSync as qi,readFileSync as Bi}from"fs";function rn(e){let t=new Set;if(!qi(e))return t;let r=Bi(e,"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!=="''"&&t.add(n)}}return t}var aa=$e.object({action:$e.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:$e.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:$e.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:$e.object({key:$e.string(),description:$e.string().optional(),setupUrl:$e.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),pn={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:aa,handler:async e=>{let t=e,r=na(t.projectPath??process.cwd()),o=cn(r,"mistflow.json");if(!sa(o))return Re(r);let s;try{s=JSON.parse(dn(o,"utf-8"))}catch{return d("Failed to parse mistflow.json.",!0)}if(t.action==="get"){if(!s.projectId)try{let{ensureBackendRegistered:y}=await Promise.resolve().then(()=>(or(),tr));await y(r)&&(s=JSON.parse(dn(o,"utf-8")))}catch{}let a=s.plan,l=a?.steps?.filter(y=>y.status==="completed").length??0,c=a?.steps?.length??0,h=rn(cn(r,".env.local")),m=s.env?.required?Object.entries(s.env.required).map(([y,v])=>({name:y,description:v?.description,configured:h.has(y)})):[];s.projectId&&Promise.resolve().then(()=>(Je(),Ct)).then(({fetchRemoteState:y})=>y(s.projectId)).catch(()=>{});let p=[`Project: ${s.name}`];if(a){p.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let y of a.steps){let v=y.status==="completed"?"\u2713":y.status==="in_progress"?"\u2192":" ";p.push(` [${v}] ${y.number}. ${y.name}`)}}let f=m.filter(y=>!y.configured);f.length>0&&p.push(`Missing env vars: ${f.map(y=>y.name).join(", ")}`),s.deploy?.url?p.push(`Deployed: ${s.deploy.url} (${s.deploy.count??0} deploys)`):p.push("Not deployed yet");let x=[],b=a?.steps?.find(y=>y.status!=="completed");return b?x.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${b.number} (${b.name}).`):a&&l===c&&(s.deploy?.url||x.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),f.length>0&&x.push(`Missing env vars in .env.local: ${f.map(y=>y.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:m,deploy:s.deploy??null,contextMessage:p.join(`
|
|
39
|
+
`),nextSteps:x}))}let i=[];if(t.completedStep!==void 0){let a=s.plan;if(a?.steps){let l=a.steps.findIndex(c=>c.number===t.completedStep);if(l===-1)return d(`Step ${t.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",i.push(`Step ${t.completedStep} marked as completed`)}}t.addEnvVar&&(s.env||(s.env={required:{}}),s.env.required||(s.env.required={}),s.env.required[t.addEnvVar.key]={description:t.addEnvVar.description,setupUrl:t.addEnvVar.setupUrl},i.push(`Added required env var: ${t.addEnvVar.key}`)),ia(o,JSON.stringify(s,null,2)+`
|
|
40
|
+
`),s.projectId&&Promise.resolve().then(()=>(Je(),Ct)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(r);c&&await l(s.projectId,c)}).catch(()=>{});let n=[];if(t.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 t.addEnvVar&&(n.push(`Add ${t.addEnvVar.key} to your .env.local file`),t.addEnvVar.setupUrl&&n.push(`Get the value from: ${t.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}))}};me();var rr={},at=[];function Xt(e){let t=at.find(o=>o.id===e);if(t)return t;let r=e.toLowerCase().replace(/[^a-z0-9]/g,"");return at.find(o=>{let s=o.title.toLowerCase().replace(/[^a-z0-9]/g,"");return s===r||s.includes(r)||r.includes(s)})}function un(e){return rr[e]}function nr(e){return e?at.filter(t=>t.category.toLowerCase()===e.toLowerCase()):at}function mn(e){let t=e??at;if(t.length===0)return"Landing page presets have been replaced by the tone-based system. The landing page tone is now auto-selected based on your app's description during planning.";let r={};for(let s of t){r[s.category]||(r[s.category]=[]);let i=rr[s.id],n=i?` \u2014 ${i.description}`:"";r[s.category].push(`${s.id} \u2014 "${s.title}"${n}`)}let o=[];for(let[s,i]of Object.entries(r))o.push(`**${s}**:
|
|
41
41
|
${i.map(n=>` \u2022 ${n}`).join(`
|
|
42
42
|
`)}`);return o.join(`
|
|
43
43
|
|
|
44
|
-
`)}function
|
|
44
|
+
`)}function la(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function hn(e){return(e?nr(e):at).map(r=>{let o=rr[r.id];return{id:r.id,slug:la(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 gn(e,t){return[]}wt();var sr={"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"}},lt=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
|
|
45
45
|
|
|
46
46
|
### File Structure
|
|
47
47
|
\`\`\`
|
|
@@ -1461,16 +1461,16 @@ export function ImageGenerator() {
|
|
|
1461
1461
|
5. **Replicate charges per prediction.** Flux Schnell is ~$0.003/image. Flux Pro is ~$0.05/image. Video models are $0.05-$0.50/generation. Show generation cost to users.
|
|
1462
1462
|
6. **Cache generated images.** Store output URLs in your database. Replicate URLs expire after a few hours. Download and re-host on R2 for permanent storage.
|
|
1463
1463
|
7. **Network I/O does NOT count as CPU time on Workers.** Image generation wait time is all network I/O.
|
|
1464
|
-
8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}];function
|
|
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 ca(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function ct(e){let t=lt.find(o=>o.id===e);if(t)return t;let r=e.toLowerCase().replace(/[^a-z0-9]/g,"");return lt.find(o=>{let s=o.name.toLowerCase().replace(/[^a-z0-9]/g,"");return s===r||s.includes(r)||r.includes(s)})}function dt(e){return sr[e]}function ir(e){return e?lt.filter(t=>t.category.toLowerCase()===e.toLowerCase()):lt}function fn(e){let t=e??lt,r={};for(let s of t){r[s.category]||(r[s.category]=[]);let i=sr[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
1465
|
${i.map(n=>` - ${n}`).join(`
|
|
1466
1466
|
`)}`);return o.join(`
|
|
1467
1467
|
|
|
1468
|
-
`)}function
|
|
1468
|
+
`)}function yn(e){return(e?ir(e):lt).map(r=>{let o=sr[r.id];return{id:r.id,slug:ca(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 da=le.object({action:le.enum(["get","update","share","landing-designs","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'landing-designs' lists curated landing page hero designs. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:le.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:le.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:le.object({key:le.string(),description:le.string().optional(),setupUrl:le.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:le.string().optional().describe("(share) Short description of what this template builds"),category:le.string().optional().describe("(landing-designs) Filter by category"),presetId:le.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),integrationId:le.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:le.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:le.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),bn={name:"mist_project",description:_r,inputSchema:da,handler:async e=>{let t=e;if(["share","errors","logs","deployments"].includes(t.action)&&!ee())return d("You need to sign in first. Run mist_setup to connect your account.",!0);switch(t.action){case"get":case"update":return pn.handler({action:t.action,projectPath:t.projectPath,completedStep:t.completedStep,addEnvVar:t.addEnvVar});case"share":{let o=Zt(t.projectPath??process.cwd()),s=oo(o,"mistflow.json");if(!eo(s))return Re(o);let i;try{i=JSON.parse(to(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 Xo(n,{isTemplate:!0,description:t.templateDescription});return d(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
|
|
1469
1469
|
|
|
1470
1470
|
Anyone can fork it: ${a.share_url}
|
|
1471
1471
|
|
|
1472
1472
|
Others can use it in their AI editor:
|
|
1473
|
-
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return c(l,!0)}}case"landing-designs":{if(e.presetId){let n=Jt(e.presetId);if(!n)return c(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let a=pn(e.presetId);return c(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=mn(e.category??void 0),s=or(e.category),i=un(s);return c(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.${e.category?` Filtered by: ${e.category}.`:""} To use one, pass landingDesign="<id>" when calling mist_plan. The design blueprint will be injected during the landing page implementation step. Browse them at ${ot()}/designs?tab=landing-designs.`}))}case"integrations":{if(e.integrationId){let n=at(e.integrationId);if(!n)return c(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=lt(n.id);return c(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=fn(e.category??void 0),s=nr(e.category??void 0),i=gn(s);return c(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=Yt(e.projectPath??process.cwd()),s=Zt(o,"mistflow.json");if(!Qt(s))return _e(o);let i;try{i=JSON.parse(Xt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return c("No project ID found. Deploy the project first.",!0);try{let a=await Bo(n,e.period??"7d");return a.total===0?c(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):c(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return c(l,!0)}}case"logs":{let o=Yt(e.projectPath??process.cwd()),s=Zt(o,"mistflow.json");if(!Qt(s))return _e(o);let i;try{i=JSON.parse(Xt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return c("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await nt(n);if(l.length===0)return c("No deployments found for this project.",!0);a=l[0].id}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deployments";return c(d,!0)}try{let[l,d]=await Promise.all([qo(a),St(a)]),h=l.filter(p=>p.level==="error"),m=l.filter(p=>p.level==="warn");return c(JSON.stringify({deploymentId:a,status:d.status,errorMessage:d.error??null,totalLogs:l.length,errorCount:h.length,warnCount:m.length,logs:l.map(p=>({time:p.timestamp,level:p.level,phase:p.phase,message:p.message})),message:d.status==="failed"?`Deployment failed. ${h.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${d.status}. ${l.length} log entries (${h.length} errors, ${m.length} warnings).`}))}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deploy logs";return c(d,!0)}}case"deployments":{let o=Yt(e.projectPath??process.cwd()),s=Zt(o,"mistflow.json");if(!Qt(s))return _e(o);let i;try{i=JSON.parse(Xt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let n=i.projectId;if(!n)return c("No project ID found. Deploy the project first.",!0);try{let a=await nt(n);return c(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return c(l,!0)}}case"version":{So().backendSignalReceived||await Ro();let o=So(),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 c(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 c(`Unknown action: ${e.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Je}from"zod";Ft();var da=Je.object({action:Je.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:Je.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Je.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:Je.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:Je.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Je.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),bn={name:"mist_browser",description:_r,inputSchema:da,handler:async t=>{let e=t,r=await To();if(e.action==="navigate"){if(!e.url)return c("URL is required for 'navigate'.",!0);let i=[],n=d=>{d.type()==="error"&&i.push(d.text())};r.on("console",n),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=d=>a.push(d.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 d=await wt(r),h=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:d,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let m=await vt(r);h.push({type:"image",data:m.toString("base64"),mimeType:"image/png"})}return{content:h}}}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 c("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 c("Selector is required for 'type'.",!0);if(!e.value)return c("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return c("Selector is required for 'fill'.",!0);if(!e.value)return c("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return c("Selector is required for 'select_option'.",!0);if(!e.value)return c("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return c("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return c("Value is required for 'press_key' (e.g. 'Enter').",!0);await 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 c(`Element not found: ${e.selector}`,!0);i=await n.screenshot({type:"png"})}else i=await vt(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 wt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:i})}]}}let o=await wt(r),s=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}];if(e.includeScreenshot){let i=await vt(r);s.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:s}}};import{z as wn}from"zod";var vn=`# Mistflow MCP tool reference
|
|
1473
|
+
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return d(l,!0)}}case"landing-designs":{if(t.presetId){let n=Xt(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=un(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=hn(t.category??void 0),s=nr(t.category),i=mn(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 ${nt()}/designs?tab=landing-designs.`}))}case"integrations":{if(t.integrationId){let n=ct(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=dt(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=yn(t.category??void 0),s=ir(t.category??void 0),i=fn(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=Zt(t.projectPath??process.cwd()),s=oo(o,"mistflow.json");if(!eo(s))return Re(o);let i;try{i=JSON.parse(to(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 Ho(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=Zt(t.projectPath??process.cwd()),s=oo(o,"mistflow.json");if(!eo(s))return Re(o);let i;try{i=JSON.parse(to(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 it(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([zo(a),Tt(a)]),h=l.filter(p=>p.level==="error"),m=l.filter(p=>p.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(p=>({time:p.timestamp,level:p.level,phase:p.phase,message:p.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=Zt(t.projectPath??process.cwd()),s=oo(o,"mistflow.json");if(!eo(s))return Re(o);let i;try{i=JSON.parse(to(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 it(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":{Po().backendSignalReceived||await No();let o=Po(),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 Ye}from"zod";zt();var pa=Ye.object({action:Ye.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:Ye.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Ye.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:Ye.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:Ye.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Ye.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),wn={name:"mist_browser",description:Rr,inputSchema:pa,handler:async e=>{let t=e,r=await Io();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 vt(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 xt(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 xt(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 vt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:i})}]}}let o=await vt(r),s=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}];if(t.includeScreenshot){let i=await xt(r);s.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:s}}};import{z as vn}from"zod";var xn=`# Mistflow MCP tool reference
|
|
1474
1474
|
|
|
1475
1475
|
Every capability is an MCP tool. There is no companion CLI. Long-running tools
|
|
1476
1476
|
(install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
|
|
@@ -1778,14 +1778,14 @@ is cheaper than building the wrong thing and iterating.
|
|
|
1778
1778
|
|
|
1779
1779
|
mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
|
|
1780
1780
|
mist_deploy({ action: "status", deploymentId }) # poll
|
|
1781
|
-
`,kn={name:"mist_help",description:
|
|
1782
|
-
`),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?
|
|
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:p,enumNames:p,...n.recommended&&m.includes(n.recommended)?{default:n.recommended}:{}},r.push(l),
|
|
1788
|
-
`)}function
|
|
1781
|
+
`,kn={name:"mist_help",description:Er,inputSchema:vn.object({command:vn.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 e=>{let{command:t}=e;if(!t)return d(xn);let r=t.startsWith("mist_")?t:`mist_${t}`,o=xn.split(`
|
|
1782
|
+
`),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 ro,mkdirSync as Pn,readFileSync as In,readdirSync as Cn,writeFileSync as ua}from"fs";import{join as Fe,resolve as ma}from"path";import{homedir as lr}from"os";import{z as At}from"zod";function pt(e){return e.entity??e.name??"Unknown"}function ut(e){return typeof e=="string"?e:e.name}function ar(e){return typeof e=="string"?"text":e.type}function Sn(e){let t=e.sampleRows;if(Array.isArray(t)&&t.length>0)return t.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=e.fields||[],o=[];for(let s=0;s<3;s++){let i={};for(let n of r)i[ut(n)]=ha(ut(n),ar(n),pt(e),s);o.push(i)}return o}function ha(e,t,r,o){let s=e.toLowerCase(),i=(t||"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 ga(e){let t=e.dataModel??[],r=e.pages??[],o=e.design??{},s=r.map(m=>({label:m.name??m.path??"Page",route:m.path??m.route??"/"})),i=[],n=t.slice(0,3).map(m=>({name:pt(m),fields:(m.fields||[]).map(p=>({name:ut(p),type:ar(p)})),sampleData:Sn(m)})),a=[];e.primaryAction&&(a.push(`PRIMARY: ${e.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${e.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${t.map(m=>pt(m)).join(", ")}`),a.push("RECENT: Latest activity or items"),i.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:e.primaryAction?`Action surface \u2014 user comes here to ${e.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${t.map(m=>pt(m)).join(", ")} with key metrics.`,informationHierarchy:a,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:n});let l=t[0];if(l){let m=pt(l),p=m.toLowerCase().endsWith("s")?m:`${m}s`;i.push({name:`${m} List`,type:"detail",route:`/${p.toLowerCase()}`,purpose:`Browse, search, and manage ${p.toLowerCase()}. Create new ${m.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${p}" title + "Add ${m}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(f=>ut(f)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${p.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${p.toLowerCase()} matching..." with clear filter`],entities:[{name:m,fields:(l.fields||[]).map(f=>({name:ut(f),type:ar(f)})),sampleData:Sn(l)}]})}e.steps.some(m=>{let p=`${m.name??m.title??""} ${m.description??""}`.toLowerCase();return p.includes("landing")||p.includes("hero")||p.includes("marketing")||p.includes("homepage")})&&i.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${e.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${e.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let h=[];for(let m of t.slice(0,3)){let p=pt(m);(m.fields||[]).find(x=>{let b=ut(x).toLowerCase();return b==="name"||b==="title"})&&h.push(`What if a ${p.toLowerCase()}'s name is 47 characters? Does the layout break?`),h.push(`What if there are 0 ${p.toLowerCase()}s? 1? 500?`)}return e.authModel&&e.authModel!=="none"&&h.push("What does a brand-new user see? (no data, no setup)"),h.push("What if the network is slow? What loads first?"),{appName:e.name,summary:e.summary??"",screens:i,navigation:{style:e.navStyle??"sidebar",items:s},primaryAction:e.primaryAction??null,designDirection:{tone:o.tone??"professional",accentColor:o.accentColor??"blue",navStyle:e.navStyle??"sidebar",fonts:o.fonts??{heading:"Inter",body:"Inter"}},edgeCases:h}}function fa(e,t,r){let o=[];o.push(`# Wireframe sketch for ${e.appName}`),o.push(""),o.push(`**${e.appName}** \u2014 ${e.summary}`),o.push(""),t&&(o.push("## Feedback to apply"),o.push(t),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 e.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(`
|
|
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**: ${e.navigation.style} (use this layout)`),o.push("**Items**:");for(let s of e.navigation.items)o.push(`- ${s.label} \u2192 \`${s.route}\``);if(o.push(""),e.primaryAction&&(o.push("## Primary action (this drives the layout)"),o.push(`- **Action**: ${e.primaryAction.action}`),o.push(`- **Flow**: ${e.primaryAction.flow}`),o.push(`- **Dashboard must show**: ${e.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("")),e.edgeCases.length>0){o.push("## Edge cases to consider"),o.push("Add HTML comments in the wireframe where these matter:");for(let s of e.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: ${e.designDirection.tone} tone, ${e.designDirection.accentColor} accent, ${e.designDirection.navStyle} nav, ${e.designDirection.fonts.heading} / ${e.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(`
|
|
1785
|
+
`)}function An(e){return Fe(lr(),".mistflow","mockup-state",`${e}.json`)}function ya(e){let t=An(e);if(!ro(t))return null;try{return JSON.parse(In(t,"utf-8"))}catch{return null}}function Tn(e,t){let r=Fe(lr(),".mistflow","mockup-state");Pn(r,{recursive:!0}),ua(An(e),JSON.stringify(t,null,2))}var ba=At.object({planId:At.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:At.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:At.string().optional().describe("User feedback to apply to the next iteration."),approved:At.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(e=>!(e.feedback&&e.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),_n={name:"mist_mockup",description:Dr,inputSchema:ba,handler:async e=>{let t=e,{planId:r,feedback:o,approved:s}=t,i=ma(t.projectPath??process.cwd()),n=Fe(lr(),".mistflow","plans",`${r}.json`);if(!ro(n))return d(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(In(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=ya(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let h=Fe(i,".mistflow","mockups");Pn(h,{recursive:!0});let m=`mockup-${r}.html`,p=Fe(h,m);if(s){c.approved=!0,Tn(r,c);let v=ro(h)?Cn(h).filter(C=>C.endsWith(".html")).map(C=>Fe(".mistflow","mockups",C)):[];return d(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:v,nextAction:`Call mist_init with planId='${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 f=ga(l);c.screens=f.screens.map(v=>v.name),Tn(r,c);let x=fa(f,o??void 0,p),b=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,y=o?`Apply the user's feedback to ${p}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${p}, then open it in the browser. Ask the user if the layout feels right.`;return d(JSON.stringify({status:"wireframe",iterationCount:c.iterationCount,screens:f.screens.map(v=>({name:v.name,type:v.type,route:v.route})),wireframePrompt:x,designDirection:f.designDirection,...b?{nudge:b}:{},mockupFile:m,mockupPath:p,nextAction:y}))}};function Rn(e){let t=Fe(e,".mistflow","mockups");return ro(t)?Cn(t).filter(r=>r.endsWith(".html")).map(r=>Fe(t,r)):[]}import{z as cr}from"zod";import{resolve as wa}from"path";import{spawn as va}from"child_process";function no(e){let t=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of e.matchAll(r)){let[,l,c,h,m,p]=a;t.push({file:l,line:parseInt(c,10),column:parseInt(h,10),message:`${m}: ${p}`,humanMessage:`There is a type error in ${l} on line ${c}: ${p}`,suggestion:`Check line ${c} in ${l}. ${m==="TS2345"?"The types of the arguments do not match.":`Fix the ${m} error.`}`})}let o=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of e.matchAll(o)){let[,l,c,h,m]=a;t.some(p=>p.file===l&&p.line===parseInt(c,10))||t.push({file:l,line:parseInt(c,10),column:parseInt(h,10),message:m,humanMessage:`There is an error in ${l} on line ${c}: ${m.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 e.matchAll(s)){let[,l,c]=a;t.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 e.matchAll(i)){let[,l,c]=a;t.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 e.matchAll(n)){let[,l,c,h,m]=a;t.some(p=>p.file===l&&p.line===parseInt(h,10))||t.push({file:l,line:parseInt(h,10),column:parseInt(m,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${h}.`,suggestion:`Check line ${h} in ${l} for a missing closing bracket or unexpected token.`})}return t}var xa=cr.object({projectPath:cr.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:cr.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});function ka(e){return new Promise(t=>{let r=va("npm",["run","build"],{cwd:e,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=>{t({exitCode:127,combined:`${o}
|
|
1786
|
+
${s.message}`})}),r.on("close",s=>{t({exitCode:s??1,combined:o})})})}var En={name:"mist_debug",description:Nr,inputSchema:xa,handler:async e=>{let t=e,r=wa(t.projectPath??process.cwd()),o=t.buildOutput??"";if(!t.buildOutput){let n=await ka(r);if(n.exitCode===0)return d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));o=n.combined}let s=no(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 A}from"zod";import{existsSync as _t,mkdirSync as io,readFileSync as Ln,readdirSync as La,statSync as Ua,unlinkSync as $a,writeFileSync as ao}from"fs";import{dirname as Fa,isAbsolute as qa,join as de}from"path";import{homedir as qe}from"os";import{createHash as Ba,createHmac as Un,randomBytes as za,randomUUID as Mn,timingSafeEqual as Ha}from"crypto";me();function Ie(e,t,r,o=3e3){if(t===void 0)return{stop:()=>{}};let s=0,i=!1,a=setInterval(()=>{i||(s++,e.notification({method:"notifications/progress",params:{progressToken:t,progress:s,message:r()}}).catch(()=>{}))},o);return{stop:()=>{i||(i=!0,clearInterval(a))}}}function Sa(e){try{return!!e.getClientCapabilities()?.elicitation}catch{return!1}}function Ta(){let e=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return e==="off"||e==="false"||e==="0"||e==="disabled"}function Pa(e){let t=e.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(t)?t:`_${t}`}function Ia(e){let t={},r=[],o=[],s=new Set;for(let i=0;i<e.length;i++){let n=e[i],a=n.decisionKey?Pa(n.decisionKey):`q_${i+1}`,l=a,c=2;for(;s.has(l);)l=`${a}_${c}`,c++;s.add(l);let h=n.freetext?"":`${l}_other`;if(h&&s.add(h),o.push({primary:l,other:h,question:n}),n.freetext){t[l]={type:"string",title:n.question,description:n.why,...n.recommended?{default:n.recommended}:{}},r.push(l);continue}let m=(n.options??[]).map(f=>typeof f=="string"?f:f.label),p=[...m,"Other (specify in the 'Other' field below)"];t[l]={type:"string",title:n.question,description:n.why?`${n.why}${n.recommended?`
|
|
1787
|
+
Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}`:void 0,enum:p,enumNames:p,...n.recommended&&m.includes(n.recommended)?{default:n.recommended}:{}},r.push(l),t[h]={type:"string",title:"If 'Other' selected above: type your answer",description:"Leave blank if you picked an option from the list."}}return{schema:{type:"object",properties:t,required:r},fieldKeys:o}}function Ca(e,t){let r=[],o;for(let{primary:s,other:i,question:n}of t){let a=String(e[s]??"").trim(),l;if(n.freetext)l=a||n.recommended||"";else{let h=i?String(e[i]??"").trim():"",m=a.toLowerCase().startsWith("other");h?l=h:m?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 dr(e,t,r){if(Ta())return{outcome:"unsupported"};if(!Sa(e))return{outcome:"unsupported"};if(t.length===0)return{outcome:"submitted",answers:[]};let{schema:o,fieldKeys:s}=Ia(t),i;try{i=await e.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}=Ca(i.content,s);return{outcome:"submitted",answers:n,urlChoice:a}}var Aa=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:e=>e.surfaceType==="internal-tool"||e.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:e=>e.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:e=>e.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:e=>e.multiRole===!0||e.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:e=>e.primaryActor==="customers"||e.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:e=>e.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:e=>e.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:e=>e.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:e=>e.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:e=>e.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:e=>e.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:e=>e.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:e=>e.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:e=>e.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 Nn(e,t,r){let o=r?.suggestedName||_a(e),s=t.primaryActor==="both"?"Staff + Customers":t.primaryActor==="staff"?"Staff / Admin":t.primaryActor==="customers"?"End Users":"Users",i=t.audienceType??(t.surfaceType==="internal-tool"?"internal":(t.primaryActor==="customers"||t.primaryActor==="both","b2c")),n=t.surfaceType==="internal-tool"?"Internal tool":t.surfaceType==="marketplace"?"Marketplace":t.surfaceType==="content-site"?"Content site":t.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=`${e} ${t.primaryAction||""}`;a=[];for(let c of Aa){let h=c.keywords.test(l),m=c.condition(t);(h||m)&&a.push({name:c.name,description:c.description,checked:h,source:h?"explicit":"suggested"})}}return{name:o,audience:s,audienceType:i,surfaceType:n,primaryAction:t.primaryAction||"manage items",features:a,publicLanding:t.publicLanding??!0,authModel:t.authModel??"email",dbProvider:t.dbProvider??"neon",integrations:t.integrations??[],language:r?.language||"English"}}function Dn(e){let t=e.features.filter(a=>a.checked),r=e.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=[`**${e.name}** \u2014 ${e.surfaceType} for ${e.audience}`,`Audience: ${i[e.audienceType]??e.audienceType}`,`Primary action: ${e.primaryAction}`,`Access: ${o[e.authModel]??e.authModel} | Database: ${s[e.dbProvider]??e.dbProvider}${e.publicLanding?" | Landing page: Yes":""}${e.language&&e.language!=="English"?` | Language: ${e.language}`:""}`,""];if(t.length>0){n.push("**Included:**");for(let a of t)n.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(e.integrations.length>0&&(n.push(""),n.push(`**Integrations:** ${e.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(`
|
|
1788
|
+
`)}function _a(e){let t=e.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(t)return pr(t[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=e.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 pr(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Ra=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],Ea=["sharp","soft","pill","organic"],Na=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"];function ur(e,t,r){return t.includes(e)?e:r}function ce(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function mt(e,t){return typeof e!="string"?t:/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(e.trim())?e.trim():t}function Da(e){let t=new Set;for(let o of e)o.fonts?.display&&t.add(o.fonts.display),o.fonts?.body&&t.add(o.fonts.body);return t.size===0?"":`https://fonts.googleapis.com/css2?${[...t].map(o=>`family=${o.trim().replace(/\s+/g,"+").replace(/[^A-Za-z0-9+]/g,"")}:wght@400;700`).join("&")}&display=swap`}function jn(e){let t=(e||"").trim(),r=t.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 t?`"${t.replace(/"/g,"")}", ${o}`:o}function ja(e){switch(e){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 Oa(){let e=`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
1789
|
.card-hero { position: relative; overflow: hidden; isolation: isolate; }
|
|
1790
1790
|
.card-hero::before {
|
|
1791
1791
|
content: "";
|
|
@@ -1802,17 +1802,17 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
1802
1802
|
|
|
1803
1803
|
.card-hero.texture-paper-grain::before {
|
|
1804
1804
|
opacity: 0.35;
|
|
1805
|
-
background-image: ${
|
|
1805
|
+
background-image: ${e};
|
|
1806
1806
|
mix-blend-mode: multiply;
|
|
1807
1807
|
}
|
|
1808
1808
|
.card-hero.texture-film-grain::before {
|
|
1809
1809
|
opacity: 0.5;
|
|
1810
|
-
background-image: ${
|
|
1810
|
+
background-image: ${e};
|
|
1811
1811
|
mix-blend-mode: overlay;
|
|
1812
1812
|
}
|
|
1813
1813
|
.card-hero.texture-noise::before {
|
|
1814
1814
|
opacity: 0.25;
|
|
1815
|
-
background-image: ${
|
|
1815
|
+
background-image: ${e};
|
|
1816
1816
|
mix-blend-mode: overlay;
|
|
1817
1817
|
}
|
|
1818
1818
|
.card-hero.texture-scanlines::before {
|
|
@@ -1843,26 +1843,26 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
1843
1843
|
backdrop-filter: blur(14px);
|
|
1844
1844
|
mix-blend-mode: normal;
|
|
1845
1845
|
}
|
|
1846
|
-
`}function
|
|
1846
|
+
`}function Ma(e,t,r,o){let s=mt(e.colors?.bg??"","#0f0f0f"),i=mt(e.colors?.fg??"","#f5f5f5"),n=mt(e.colors?.accent??"","#7c9cff"),a=ce(e.name),l=ce(e.hero_headline||e.name),c=ce(e.body_sample||e.summary||""),h=ce(e.cta_text||"Continue"),m=`<div class="hero-eyebrow" style="font-family:${r}">${a.toUpperCase()}</div>`,p=`<h2 class="hero-headline" style="font-family:${t}">${l}</h2>`,f=`<p class="hero-body" style="font-family:${r}">${c}</p>`,x=`<button class="hero-cta" style="background:${n};color:${s};font-family:${r};border-radius:${o.button}">${h}</button>`,b=ur(e.hero_treatment,Ra,"typographic");if(b==="terminal"){let y=`"${(e.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
|
|
1847
1847
|
${m}
|
|
1848
|
-
<div class="hero-terminal-lines" style="font-family:${
|
|
1848
|
+
<div class="hero-terminal-lines" style="font-family:${y};color:${i}">
|
|
1849
1849
|
<div>$ status --all</div>
|
|
1850
1850
|
<div>api.service.......<span style="color:${n}">OK</span></div>
|
|
1851
1851
|
<div>worker.queue......<span style="color:${n}">OK</span></div>
|
|
1852
1852
|
<div>db.primary.......<span style="color:${n}">OK</span></div>
|
|
1853
1853
|
</div>
|
|
1854
1854
|
${p}
|
|
1855
|
-
${
|
|
1855
|
+
${f}
|
|
1856
1856
|
<div class="hero-cta-row">${x}</div>
|
|
1857
1857
|
`}return b==="split-panel"?`
|
|
1858
1858
|
<div class="hero-split">
|
|
1859
|
-
<div class="hero-split-left" style="background:${n};color:${s};font-family:${
|
|
1859
|
+
<div class="hero-split-left" style="background:${n};color:${s};font-family:${t}">
|
|
1860
1860
|
<div class="hero-split-mark" style="font-family:${r};color:${s}">${a[0]??"\xB7"}</div>
|
|
1861
1861
|
</div>
|
|
1862
1862
|
<div class="hero-split-right">
|
|
1863
1863
|
${m}
|
|
1864
1864
|
${p}
|
|
1865
|
-
${
|
|
1865
|
+
${f}
|
|
1866
1866
|
<div class="hero-cta-row">${x}</div>
|
|
1867
1867
|
</div>
|
|
1868
1868
|
</div>
|
|
@@ -1872,27 +1872,27 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
1872
1872
|
</div>
|
|
1873
1873
|
${m}
|
|
1874
1874
|
${p}
|
|
1875
|
-
${
|
|
1875
|
+
${f}
|
|
1876
1876
|
<div class="hero-cta-row">${x}</div>
|
|
1877
1877
|
`:b==="magazine-hero"?`
|
|
1878
1878
|
${m}
|
|
1879
|
-
<h2 class="hero-headline hero-headline-mag" style="font-family:${
|
|
1879
|
+
<h2 class="hero-headline hero-headline-mag" style="font-family:${t}">${l}</h2>
|
|
1880
1880
|
<div class="hero-rule" style="background:${i}"></div>
|
|
1881
|
-
<p class="hero-body hero-body-mag" style="font-family:${r}">${
|
|
1881
|
+
<p class="hero-body hero-body-mag" style="font-family:${r}">${c}</p>
|
|
1882
1882
|
<div class="hero-byline" style="font-family:${r};color:${i}">\u2014 Volume 01 \xB7 Issue 01</div>
|
|
1883
1883
|
<div class="hero-cta-row">${x}</div>
|
|
1884
1884
|
`:`
|
|
1885
1885
|
${m}
|
|
1886
1886
|
${p}
|
|
1887
|
-
${
|
|
1887
|
+
${f}
|
|
1888
1888
|
<div class="hero-cta-row">${x}</div>
|
|
1889
|
-
`}function
|
|
1890
|
-
<div class="card-hero texture-${m}" style="background:${i};color:${n}">${
|
|
1889
|
+
`}function On(e,t){let r=Da(t),o=t.map(s=>{let i=mt(s.colors?.bg??"","#0f0f0f"),n=mt(s.colors?.fg??"","#f5f5f5"),a=mt(s.colors?.accent??"","#7c9cff"),l=jn(s.fonts?.display??""),c=jn(s.fonts?.body??""),h=ur(s.shape_lang,Ea,"soft"),m=ur(s.texture,Na,"flat"),p=ja(h),f=Ma(s,l,c,p),x=ce(s.name),b=ce(s.id),y=ce(s.fonts?.display??""),v=ce(s.fonts?.body??""),C=ce(s.summary||""),_=ce(s.decoration_hint||""),P=(j,L)=>`<div class="card-meta-row"><span class="card-meta-label">${j}</span><span class="card-meta-value">${L}</span></div>`;return` <article class="card" data-direction-id="${b}" style="border-radius:${p.card}">
|
|
1890
|
+
<div class="card-hero texture-${m}" style="background:${i};color:${n}">${f}
|
|
1891
1891
|
</div>
|
|
1892
1892
|
<div class="card-meta" style="border-top-color:${n}14">
|
|
1893
1893
|
<div class="card-meta-title">${x}</div>
|
|
1894
|
-
<p class="card-meta-summary">${
|
|
1895
|
-
${P("Fonts",`${
|
|
1894
|
+
<p class="card-meta-summary">${C}</p>
|
|
1895
|
+
${P("Fonts",`${y||"\u2014"} <span class="sep">\xB7</span> ${v||"\u2014"}`)}
|
|
1896
1896
|
${P("Palette",`
|
|
1897
1897
|
<span class="card-meta-swatches">
|
|
1898
1898
|
<span class="card-meta-swatch" title="${i}" style="background:${i}"></span>
|
|
@@ -1902,7 +1902,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
1902
1902
|
`)}
|
|
1903
1903
|
${P("Shape",`<span class="chip" style="border-radius:${p.chip}">${h}</span>`)}
|
|
1904
1904
|
${P("Texture",`<span class="chip" style="border-radius:${p.chip}">${ce(m)}</span>`)}
|
|
1905
|
-
${
|
|
1905
|
+
${_?P("Decoration",ce(_)):""}
|
|
1906
1906
|
${P("Pick with",`<code>${x}</code>`)}
|
|
1907
1907
|
</div>
|
|
1908
1908
|
</article>`}).join(`
|
|
@@ -1911,7 +1911,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
1911
1911
|
<head>
|
|
1912
1912
|
<meta charset="UTF-8" />
|
|
1913
1913
|
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
1914
|
-
<title>Design directions \u2014 ${ce(
|
|
1914
|
+
<title>Design directions \u2014 ${ce(e)}</title>
|
|
1915
1915
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
1916
1916
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
1917
1917
|
${r?`<link rel="stylesheet" href="${r}" />`:""}
|
|
@@ -2098,7 +2098,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
2098
2098
|
margin-top: 4px;
|
|
2099
2099
|
}
|
|
2100
2100
|
|
|
2101
|
-
${
|
|
2101
|
+
${Oa()}
|
|
2102
2102
|
|
|
2103
2103
|
/* \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
2104
|
.card-meta {
|
|
@@ -2207,7 +2207,7 @@ Recommended: ${n.recommended}`:""}`:n.recommended?`Recommended: ${n.recommended}
|
|
|
2207
2207
|
<div class="page">
|
|
2208
2208
|
<header class="page-header">
|
|
2209
2209
|
<div class="eyebrow"><span class="eyebrow-dot"></span>Mistflow \xB7 design direction</div>
|
|
2210
|
-
<h1 class="page-title">How should <strong>${ce(
|
|
2210
|
+
<h1 class="page-title">How should <strong>${ce(e)}</strong> feel?</h1>
|
|
2211
2211
|
<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
2212
|
</header>
|
|
2213
2213
|
|
|
@@ -2227,24 +2227,24 @@ ${o}
|
|
|
2227
2227
|
</div>
|
|
2228
2228
|
</body>
|
|
2229
2229
|
</html>
|
|
2230
|
-
`}var ro="__mistflow_url_choice__",Ha=600*1e3;function Un(){let t=de(Fe(),".mistflow","confirm-secret");if(At(t))try{return Buffer.from(Mn(t,"utf-8").trim(),"hex")}catch{}let e=Ba(32);return no(de(Fe(),".mistflow"),{recursive:!0}),so(t,e.toString("hex"),{mode:384}),e}function $n(t){return qa("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function Wa(t,e){let r={cwd:t,d:$n(e),exp:Date.now()+Ha},o=Buffer.from(JSON.stringify(r)).toString("base64url"),s=Ln("sha256",Un()).update(o).digest("base64url");return`${o}.${s}`}function Ga(t,e,r){let o=t.split(".");if(o.length!==2)return!1;let[s,i]=o,n=Ln("sha256",Un()).update(s).digest("base64url"),a=Buffer.from(i),l=Buffer.from(n);if(a.length!==l.length||!za(a,l))return!1;try{let d=JSON.parse(Buffer.from(s,"base64url").toString("utf-8"));return!(typeof d.exp!="number"||Date.now()>d.exp||d.cwd!==e||d.d!==$n(r))}catch{return!1}}function Va(t){let e=t,r=Fe(),o=!1;for(let s=0;s<64;s++){if(At(de(e,"mistflow.json")))return"mistflow";if(!o&&At(de(e,"package.json"))&&(o=!0),e===r)break;let i=$a(e);if(i===e)break;e=i}return o?"foreign":"none"}function Ka(t){let e=Fe(),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===de(e,s))return!0;return!1}var Ja=C.object({description:C.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:C.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:C.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:C.union([C.record(C.string()),C.array(C.object({question:C.string().optional(),decisionKey:C.string().optional(),answer:C.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:C.record(C.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:C.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:C.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:C.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:C.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:C.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:C.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:C.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:C.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:C.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:C.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:C.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:C.object({id:C.string().optional(),name:C.string().optional(),summary:C.string().optional(),heroHeadline:C.string().optional(),ctaText:C.string().optional(),bodySample:C.string().optional(),fontsHint:C.string().optional(),fonts:C.object({display:C.string(),body:C.string()}).partial().optional(),colorMood:C.string().optional(),colors:C.object({bg:C.string(),fg:C.string(),accent:C.string()}).partial().optional(),heroTreatment:C.string().optional(),shapeLang:C.string().optional(),texture:C.string().optional(),decorationHint:C.string().optional(),custom:C.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 Ya(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 Qa(t){let e=de(Fe(),".mistflow","plans",`${t}.json`);if(!At(e))return null;try{return JSON.parse(Mn(e,"utf-8")).plan??null}catch{return null}}async function Xa(t){for(let o=0;o<60;o++){try{let s=await Do(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 Za(t,e){let{description:r,projectPath:o,conversationId:s,answers:i,existingPlan:n,existingPlanId:a,templateToken:l,remixDescription:d,autonomous:h,language:m,landingDesign:p,appStyle:y,brandMentioned:x,confirmToken:b,urlChoice:f,designConversationId:T,designDirection:A}=t;if(s&&!r&&!i&&!T&&!A&&!n&&!a&&!l)try{let u=await zt(s);return u.status==="clarify_pending"?c(JSON.stringify({status:"running",conversationId:s,phase:"generating_questions",nextAction:`Still generating. Call mist_plan with { projectPath, conversationId: "${s}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as questions are ready.`})):u.status==="plan_pending"?c(JSON.stringify({status:"running",conversationId:s,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${s}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the plan is ready.`})):c(JSON.stringify(u))}catch(u){let g=u instanceof Error?u.message:String(u);return c(`Could not poll plan conversation '${s}': ${g}`,!0)}let R=r??"";if(!R.trim()&&!s&&!T&&!n&&!a&&!l)return c("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(T&&!A&&!R.trim()&&!i)return c(`You passed designConversationId='${T}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${T}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let P=n;if(!P&&a&&(P=Qa(a)??void 0,!P))return c("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let j=s;if(!ee())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let L;if(!j&&!P&&!l){if(!Fa(o))return c(`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 u=Va(o);if(u!=="mistflow"&&Ka(o))return c(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(u==="foreign"&&!x){if(!(b?
|
|
2232
|
-
`)}))}else return
|
|
2233
|
-
`)}))}L="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else u==="foreign"&&x&&(L="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await
|
|
2234
|
-
|
|
2235
|
-
**Your app URL:** https://${B}.mistflow.app`);let
|
|
2236
|
-
`),ue=await
|
|
2237
|
-
`)}))}if(
|
|
2238
|
-
`):"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.",re=
|
|
2239
|
-
`)}))}let E=_.plan,se=E.name??"Untitled App",pe=_.methodology,D=E.steps;if(!Array.isArray(D)||D.length===0)return c("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let Z=E.publicPages;if(!Z||Array.isArray(Z)&&Z.length===0){let u=E.pages,g=D.some(S=>typeof S.name=="string"&&S.name.toLowerCase().includes("landing")||typeof S.title=="string"&&S.title.toLowerCase().includes("landing")),k=Array.isArray(u)&&u.some(S=>S.path==="/"||S.route==="/");g||k?Z=["/","/pricing"]:Z=["/"]}let Ie=E.primaryAction;if(!Ie){let u=E.features;if(Array.isArray(u)&&u.length>0){let k=u.find(Q=>typeof Q.priority=="string"&&Q.priority.toLowerCase()==="must-have")??u[0];Ie={entity:k.name??k.title??"item",action:"create",fromPage:"/dashboard"}}}let he=E.nonNegotiables;(!he||Array.isArray(he)&&he.length===0)&&(he=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Ce=On(),Be=de(Fe(),".mistflow","plans");no(Be,{recursive:!0});try{let g=Date.now();for(let k of[Be,de(Fe(),".mistflow","mockup-state")])if(At(k))for(let S of Ma(k))try{let Q=de(k,S),J=La(Q).mtimeMs;g-J>6048e5&&Ua(Q)}catch{}}catch{}let F;if(p){let u=Jt(p);u?F=u.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let N=y||void 0,H=!!F,ye=D.some(u=>{let g=`${u.name??u.title} ${u.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),K=!H&&ye?hn(R,{maxResults:2}):[];K.length>0&&(F=K[0].id,console.error(`Auto-assigned landing layout preset (default): ${K[0].title} (${F})`));let Te={name:E.name,summary:E.summary,dataModel:E.dataModel,pages:E.pages,features:E.features,steps:D.map(u=>({...u,name:u.name??u.title})),design:E.design,landingDesign:F,appStyle:N,dbProvider:E.dbProvider??"neon",authModel:E.authModel,audienceType:E.audienceType??"b2c",roles:E.roles,defaultRole:E.defaultRole,publicPages:Z,navStyle:E.navStyle,multiTenant:E.multiTenant,primaryAction:Ie,nonNegotiables:he,requestedSubdomain:v,...m&&m.toLowerCase()!=="english"?{language:m}:{}};so(de(Be,`${Ce}.json`),JSON.stringify({plan:Te,methodology:pe}));let ze=D.map(u=>`${u.number}. ${u.name??u.title}`),He="",We=[],ge;!H&&K.length>0&&(We=K.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${ot()}/designs?tab=landing-designs`})),ge={question:"What landing page style fits this app?",header:"Landing Design",options:[...K.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 ${ot()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},He=` 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: ${K.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='${K[0].id}' explicitly.`);let Ne="",De=[],je=void 0,I=(E.audienceType??"b2c")==="b2c",q={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:I?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:I?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},Y=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call.",be="",oe=[];for(let u of D){let g=u.name??u.title,k=u.integrationId;if(k){let S=at(k);if(S){let Q=lt(S.id);oe.push({step:g,presetId:S.id,presetName:S.name,envVars:Q?.envVars??[]})}}}if(oe.length>0){let u=oe.flatMap(S=>S.envVars),g=[...new Set(u.map(S=>S.key))];be=` This plan uses integrations (${oe.map(S=>S.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return c(JSON.stringify({planId:Ce,name:E.name,summary:E.summary,stepCount:D.length,steps:ze,design:E.design,...F?{landingDesign:F}:{},...N?{appStyle:N}:{},...De.length>0?{recommendedAppStyles:De}:{},...je?{appStyleQuestion:je}:{},...We.length>0?{recommendedLandingDesigns:We}:{},...ge?{landingDesignQuestion:ge}:{},heroPhotoQuestion:q,...oe.length>0?{integrations:oe.map(u=>({step:u.step,preset:u.presetId,name:u.presetName,envVars:u.envVars}))}:{},message:`Plan generated for "${se}" (${D.length} steps).${F?` Landing layout "${F}" set as default.`:""}${N?` App style "${N}" will be applied across all pages.`:""}${be}${Ne}${He}${Y}`,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: '${Ce}' }). If the user says skip or "just build it", call mist_init({ planId: '${Ce}', path: '<absolute path>' }) immediately.`,...L?{warning:L}:{}}))}var Fn={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(`
|
|
2240
|
-
`),inputSchema:
|
|
2241
|
-
`)}function
|
|
2242
|
-
`)}var
|
|
2243
|
-
|
|
2244
|
-
`+
|
|
2245
|
-
`)}function
|
|
2246
|
-
`),i=null,n=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of s){let
|
|
2247
|
-
`),i=[` --radius-sm: ${
|
|
2230
|
+
`}var so="__mistflow_url_choice__",Wa=600*1e3;function $n(){let e=de(qe(),".mistflow","confirm-secret");if(_t(e))try{return Buffer.from(Ln(e,"utf-8").trim(),"hex")}catch{}let t=za(32);return io(de(qe(),".mistflow"),{recursive:!0}),ao(e,t.toString("hex"),{mode:384}),t}function Fn(e){return Ba("sha256").update(e.trim().toLowerCase()).digest("hex").slice(0,16)}function Ga(e,t){let r={cwd:e,d:Fn(t),exp:Date.now()+Wa},o=Buffer.from(JSON.stringify(r)).toString("base64url"),s=Un("sha256",$n()).update(o).digest("base64url");return`${o}.${s}`}function Va(e,t,r){let o=e.split(".");if(o.length!==2)return!1;let[s,i]=o,n=Un("sha256",$n()).update(s).digest("base64url"),a=Buffer.from(i),l=Buffer.from(n);if(a.length!==l.length||!Ha(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!==Fn(r))}catch{return!1}}function Ka(e){let t=e,r=qe(),o=!1;for(let s=0;s<64;s++){if(_t(de(t,"mistflow.json")))return"mistflow";if(!o&&_t(de(t,"package.json"))&&(o=!0),t===r)break;let i=Fa(t);if(i===t)break;t=i}return o?"foreign":"none"}function Ja(e){let t=qe(),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===de(t,s))return!0;return!1}var Ya=A.object({description:A.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:A.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:A.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:A.union([A.record(A.string()),A.array(A.object({question:A.string().optional(),decisionKey:A.string().optional(),answer:A.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:A.record(A.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:A.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.object({id:A.string().optional(),name:A.string().optional(),summary:A.string().optional(),heroHeadline:A.string().optional(),ctaText:A.string().optional(),bodySample:A.string().optional(),fontsHint:A.string().optional(),fonts:A.object({display:A.string(),body:A.string()}).partial().optional(),colorMood:A.string().optional(),colors:A.object({bg:A.string(),fg:A.string(),accent:A.string()}).partial().optional(),heroTreatment:A.string().optional(),shapeLang:A.string().optional(),texture:A.string().optional(),decorationHint:A.string().optional(),custom:A.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 Qa(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 Xa(e){let t=de(qe(),".mistflow","plans",`${e}.json`);if(!_t(t))return null;try{return JSON.parse(Ln(t,"utf-8")).plan??null}catch{return null}}async function Za(e){for(let o=0;o<60;o++){try{let s=await Oo(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 el(e,t){let{description:r,projectPath:o,conversationId:s,answers:i,existingPlan:n,existingPlanId:a,templateToken:l,remixDescription:c,autonomous:h,language:m,landingDesign:p,appStyle:f,brandMentioned:x,confirmToken:b,urlChoice:y,designConversationId:v,designDirection:C}=e;if(s&&!r&&!i&&!v&&!C&&!n&&!a&&!l)try{let u=await Gt(s);return u.status==="clarify_pending"?d(JSON.stringify({status:"running",conversationId:s,phase:"generating_questions",nextAction:`Still generating. Call mist_plan with { projectPath, conversationId: "${s}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as questions are ready.`})):u.status==="plan_pending"?d(JSON.stringify({status:"running",conversationId:s,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${s}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the plan is ready.`})):d(JSON.stringify(u))}catch(u){let g=u instanceof Error?u.message:String(u);return d(`Could not poll plan conversation '${s}': ${g}`,!0)}let _=r??"";if(!_.trim()&&!s&&!v&&!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(v&&!C&&!_.trim()&&!i)return d(`You passed designConversationId='${v}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${v}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let P=n;if(!P&&a&&(P=Xa(a)??void 0,!P))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let j=s;if(!ee())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let L;if(!j&&!P&&!l){if(!qa(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 u=Ka(o);if(u!=="mistflow"&&Ja(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(u==="foreign"&&!x){if(!(b?Va(b,o,_):!1)){let S=Ga(o,_);if(t?.server){let T=await dr(t.server,[{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",decisionKey:"scopeChoice",recommended:"Scaffold a new Mistflow app in a subdirectory",why:"Mistflow creates a NEW app in a subdirectory \u2014 it does not modify the existing codebase. Pick 'Edit existing' if you wanted to change files in the current project instead of creating a new Mistflow app.",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."}]}],"## Existing project detected\n\nYou're inside a directory that already has a project (no `mistflow.json` though). What do you want to do?");if(T.outcome==="submitted")if((T.answers?.[0]?.answer??"").toLowerCase().startsWith("scaffold"))L="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.";else return d("User chose to edit the existing codebase directly. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0);else return T.outcome==="declined"||T.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:_,confirmToken:S,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:"Creates a fresh project in this folder without touching the existing code."},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",b?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
2232
|
+
`)}))}else return d(JSON.stringify({status:"confirm_new_project",projectPath:o,description:_,confirmToken:S,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:"Creates a fresh project in this folder without touching the existing code."},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",b?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
2233
|
+
`)}))}L="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else u==="foreign"&&x&&(L="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await Yo(l)).plan)return d("This template has no plan to fork. Try a different template.",!0);let g=await Qo(l),S=g.plan,T="";if(c&&g.has_source)try{let ne=await Kt(g.plan,c),B=ne.plan??ne,Ut=ne.diff,xo=B?.steps??[],V=new Set([...(Ut?.added??[]).map(z=>z.number),...(Ut?.modified??[]).map(z=>z.number)]),ue=xo.map(z=>{let et=z.number;return V.has(et)?{...z,status:"pending"}:{...z,status:"completed",source:"forked"}});B.steps=ue,S=B;let Pe=ue.filter(z=>z.status==="pending").length;T=` Remixed: ${ue.filter(z=>z.status==="completed").length} steps unchanged, ${Pe} steps need re-implementation.`}catch(ne){console.error("[plan] Remix failed, using original plan:",ne),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let Q=Mn(),J=de(qe(),".mistflow","plans");io(J,{recursive:!0}),ao(de(J,`${Q}.json`),JSON.stringify({plan:S,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let re=S?.name??"forked-app",ie=g.has_source,yt=ie?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Ve=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:Q,forkedFrom:g.forked_from,projectId:g.id,hasSource:ie,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${T}${Ve} ${yt} NEXT: Call mist_init, name='${re}', and planId='${Q}' to create the project now.`}))}catch(u){let g=u instanceof Error?u.message:"Failed to fork template";return d(g,!0)}if(P){let u;try{u=await Kt(P,_)}catch(J){let re=J instanceof Error?J.message:"Failed to modify plan";return d(re,!0)}let g=u.plan,S=u.diff,T=[];if(S?.added?.length){let J=S.added.map(re=>re.title);T.push(`Added ${J.length} step(s): ${J.join(", ")}`)}if(S?.removed?.length){let J=S.removed.map(re=>re.title);T.push(`Removed ${J.length} step(s): ${J.join(", ")}`)}if(S?.modified?.length){let J=S.modified.map(re=>re.title);T.push(`Modified ${J.length} step(s): ${J.join(", ")}`)}let Q=T.length>0?T.join(". "):"No changes detected.";return d(JSON.stringify({plan:g,diff:S,message:`Plan modified. ${Q}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let k=y?.trim()||void 0,M=i;if(Array.isArray(i)){let u=i.findIndex(g=>g&&typeof g=="object"&&g.decisionKey==="urlChoice");if(u>=0){let g=i[u];!k&&g.answer&&(k=g.answer);let S=i.slice(0,u).concat(i.slice(u+1));M=S.length>0?S:void 0}}else if(i!=null){let u=i;if(!k&&so in u&&(k=u[so]),!k&&"urlChoice"in u&&(k=u.urlChoice),so in u||"urlChoice"in u){let{[so]:g,urlChoice:S,...T}=u;M=Object.keys(T).length>0?T:void 0}}if(k&&(k=k.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),k){let u=k.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(u)?k=u:(console.error(`[mist_plan] Discarding urlChoice '${k}' \u2014 does not look like a subdomain. Backend will auto-generate.`),k=void 0)}let W;if(C){W={...C};let u={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[g,S]of Object.entries(u))C[g]!==void 0&&W[S]===void 0&&(W[S]=C[g])}let G=i?"Generating plan with your answers (LLM call)":v?"Finalizing design direction":"Thinking through discovery questions",X=t?Ie(t.server,t.progressToken,()=>G):{stop:()=>{}};t&&(t.cleanup=()=>X.stop());let R;try{j&&!M&&!v&&!P&&!a?R=await Gt(j):R=await Vt(_,{conversationId:j,answers:M,autonomous:h,language:m,designConversationId:v,designDirection:W})}catch(u){X.stop();let g=u instanceof Error?u.message:"Failed to generate plan";return d(g,!0)}if(R.status==="clarify_pending"){X.stop();let u=R;return d(JSON.stringify({status:"running",conversationId:u.conversation_id,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${u.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.`}))}if(R.status==="plan_pending"){X.stop();let u=R;return d(JSON.stringify({status:"running",conversationId:u.conversation_id,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${u.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(R.status==="design_clarify_pending"&&(G="Generating creative design directions",R=await Za(R)),X.stop(),R.status==="clarify"){let u=R.reflection||"",g=R.suggestedName||"",S=R.suggestedFeatures??[],T=R.questions??[],Q=T.some(V=>Array.isArray(V.options)&&typeof V.options[0]=="object"&&V.options[0]?.label),J={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},re=T.map(V=>{let ue=V.decisionKey&&J[V.decisionKey]||Qa(V.question),Pe;return Q&&Array.isArray(V.options)?Pe=V.options.map(ae=>({label:ae.label,description:ae.description??""})):Array.isArray(V.options)?Pe=V.options.map((ae,z)=>({label:z===0?`${ae} (Recommended)`:String(ae),description:V.why??""})):Pe=[{label:"Yes (Recommended)",description:V.why??""},{label:"No",description:""}],{question:V.question,header:ue,options:Pe,multiSelect:!1}}),yt=R.decisions?.audienceType??null,Ve=S.length>0?Nn(_,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:yt,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:S,language:m}):null,ne=Ve?Dn(Ve):"",B=pr(g||"my-app").slice(0,32);try{let V=await Do(B);!V.available&&V.suggestion&&(B=V.suggestion)}catch{}ne&&(ne+=`
|
|
2234
|
+
|
|
2235
|
+
**Your app URL:** https://${B}.mistflow.app`);let Ut={question:"Your app URL \u2014 keep the suggested subdomain or type your own",decisionKey:"urlChoice",freetext:!0,recommended:B,why:`Your app will be at <subdomain>.mistflow.app. Subdomains are locked at scaffold time. Keep '${B}' or type your preferred subdomain (lowercase, alphanumeric + hyphens, 3-32 chars).`,options:[{label:`Keep ${B}.mistflow.app`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}]};T.push(Ut);let xo={question:`Your app will be at ${B}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${B}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};if(re.push(xo),t?.server){let V=[g?`## ${g}`:"## Pick a few details","",`${T.length} quick question${T.length===1?"":"s"} to pin down the build.`,"Pick from each dropdown \u2014 or pick `Other` and type your own answer below it."].join(`
|
|
2236
|
+
`),ue=await dr(t.server,T,V);if(ue.outcome==="submitted"){X.stop();let Pe={};for(let z of ue.answers??[])z.decisionKey?Pe[z.decisionKey]=z.answer:Pe[z.question]=z.answer;let ae=ue.urlChoice?.trim();ae&&(ae=ae.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let z=await Vt(_,{conversationId:R.conversation_id,answers:Pe,autonomous:h,language:m});if(z.status==="plan_pending"){let et=z;return d(JSON.stringify({status:"running",conversationId:et.conversation_id,phase:"generating_plan",...ae?{urlChoice:ae}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${et.conversation_id}"${ae?`, urlChoice: "${ae}"`:""} } 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.`}))}R=z}catch(z){let et=z instanceof Error?z.message:String(z);return d(`Submitting your answers failed: ${et}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(ue.outcome==="declined")return X.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(ue.outcome==="cancelled")return X.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);ue.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${ue.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:R.conversation_id,questions:T,questionCount:T.length,suggestedFeatures:S,suggestedName:g,suggestedSubdomain:B,reflection:u,briefText:ne,askUserQuestions:re,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: "${R.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: "${B}".`,'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.',...u||ne?["","\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",...u?[u]:[],...ne?["",ne]:[]]:[],...L?["",L]:[]].join(`
|
|
2237
|
+
`)}))}if(R.status==="design_clarify"){let u=R.directions??[],g=R.plan.name??"your app",S;try{let ie=u.map(B=>({id:B.id,name:B.name,summary:B.summary,hero_headline:B.hero_headline,cta_text:B.cta_text,body_sample:B.body_sample,fonts:B.fonts,colors:B.colors,hero_treatment:B.hero_treatment,shape_lang:B.shape_lang,texture:B.texture,decoration_hint:B.decoration_hint})),yt=On(g,ie),Ve=de(o,".mistflow");io(Ve,{recursive:!0});let ne=de(Ve,"design-directions.html");ao(ne,yt,"utf-8"),S=ne}catch(ie){console.error(`[mist_plan] design-directions preview render failed: ${ie instanceof Error?ie.message:String(ie)}`)}let T=u.map(ie=>({label:ie.name,description:`${ie.summary} \u2014 ${ie.fonts?.display??""} + ${ie.fonts?.body??""}`}));T.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let Q={question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:T,multiSelect:!1},J=S?[`A visual preview of all ${u.length} directions has been written to:`,` ${S}`,"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 "${S}"`,` \u2022 Linux: run xdg-open "${S}"`,` \u2022 Windows: run start "" "${S}"`," \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(`
|
|
2238
|
+
`):"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.",re=S?`open "${S}"`:"";return d(JSON.stringify({status:"design_clarify",designConversationId:R.design_conversation_id,directions:u,previewPath:S,askUserQuestion:Q,instruction:[`The plan for "${g}" is ready. I've proposed ${u.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","",J,re?`Run this command to open the preview for the user: ${re}`:"","","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: "${R.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(`
|
|
2239
|
+
`)}))}let E=R.plan,se=E.name??"Untitled App",pe=R.methodology,D=E.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 Z=E.publicPages;if(!Z||Array.isArray(Z)&&Z.length===0){let u=E.pages,g=D.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),S=Array.isArray(u)&&u.some(T=>T.path==="/"||T.route==="/");g||S?Z=["/","/pricing"]:Z=["/"]}let Ce=E.primaryAction;if(!Ce){let u=E.features;if(Array.isArray(u)&&u.length>0){let S=u.find(Q=>typeof Q.priority=="string"&&Q.priority.toLowerCase()==="must-have")??u[0];Ce={entity:S.name??S.title??"item",action:"create",fromPage:"/dashboard"}}}let he=E.nonNegotiables;(!he||Array.isArray(he)&&he.length===0)&&(he=["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=Mn(),ze=de(qe(),".mistflow","plans");io(ze,{recursive:!0});try{let g=Date.now();for(let S of[ze,de(qe(),".mistflow","mockup-state")])if(_t(S))for(let T of La(S))try{let Q=de(S,T),J=Ua(Q).mtimeMs;g-J>6048e5&&$a(Q)}catch{}}catch{}let F;if(p){let u=Xt(p);u?F=u.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let N=f||void 0,H=!!F,ye=D.some(u=>{let g=`${u.name??u.title} ${u.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),K=!H&&ye?gn(_,{maxResults:2}):[];K.length>0&&(F=K[0].id,console.error(`Auto-assigned landing layout preset (default): ${K[0].title} (${F})`));let Te={name:E.name,summary:E.summary,dataModel:E.dataModel,pages:E.pages,features:E.features,steps:D.map(u=>({...u,name:u.name??u.title})),design:E.design,landingDesign:F,appStyle:N,dbProvider:E.dbProvider??"neon",authModel:E.authModel,audienceType:E.audienceType??"b2c",roles:E.roles,defaultRole:E.defaultRole,publicPages:Z,navStyle:E.navStyle,multiTenant:E.multiTenant,primaryAction:Ce,nonNegotiables:he,requestedSubdomain:k,...m&&m.toLowerCase()!=="english"?{language:m}:{}};ao(de(ze,`${Ae}.json`),JSON.stringify({plan:Te,methodology:pe}));let He=D.map(u=>`${u.number}. ${u.name??u.title}`),We="",Ge=[],ge;!H&&K.length>0&&(Ge=K.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${nt()}/designs?tab=landing-designs`})),ge={question:"What landing page style fits this app?",header:"Landing Design",options:[...K.map((g,S)=>({label:S===0?`${g.title} (Recommended)`:g.title,description:g.description})),{label:"Design from scratch (Creative)",description:"No template \u2014 the AI designs a bespoke hero from your app's concept using 3D, scroll-driven animation, or particle effects. Higher creative ceiling, takes ~10 min longer, occasionally needs a second pass."},{label:"Browse all landing designs",description:`Not sure? See all landing designs at ${nt()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},We=` 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: ${K.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='${K[0].id}' explicitly.`);let De="",je=[],Oe=void 0,I=(E.audienceType??"b2c")==="b2c",q={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:I?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:I?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},Y=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call.",be="",oe=[];for(let u of D){let g=u.name??u.title,S=u.integrationId;if(S){let T=ct(S);if(T){let Q=dt(T.id);oe.push({step:g,presetId:T.id,presetName:T.name,envVars:Q?.envVars??[]})}}}if(oe.length>0){let u=oe.flatMap(T=>T.envVars),g=[...new Set(u.map(T=>T.key))];be=` This plan uses integrations (${oe.map(T=>T.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return d(JSON.stringify({planId:Ae,name:E.name,summary:E.summary,stepCount:D.length,steps:He,design:E.design,...F?{landingDesign:F}:{},...N?{appStyle:N}:{},...je.length>0?{recommendedAppStyles:je}:{},...Oe?{appStyleQuestion:Oe}:{},...Ge.length>0?{recommendedLandingDesigns:Ge}:{},...ge?{landingDesignQuestion:ge}:{},heroPhotoQuestion:q,...oe.length>0?{integrations:oe.map(u=>({step:u.step,preset:u.presetId,name:u.presetName,envVars:u.envVars}))}:{},message:`Plan generated for "${se}" (${D.length} steps).${F?` Landing layout "${F}" set as default.`:""}${N?` App style "${N}" will be applied across all pages.`:""}${be}${De}${We}${Y}`,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: '${Ae}' }). If the user says skip or "just build it", call mist_init({ planId: '${Ae}', path: '<absolute path>' }) immediately.`,...L?{warning:L}:{}}))}var qn={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(`
|
|
2240
|
+
`),inputSchema:Ya,handler:el};import{z as Rt}from"zod";import{existsSync as Qe,mkdirSync as br,writeFileSync as wr,readFileSync as co,readdirSync as Vn,copyFileSync as rl}from"fs";import{join as ke,resolve as Kn,dirname as Et,isAbsolute as nl}from"path";import{homedir as sl}from"os";import{spawn as hu}from"child_process";import{randomBytes as il}from"crypto";import{simpleGit as ll}from"simple-git";me();Je();function Bn(e){if(!e)return"Item";let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return t.length===0?"Item":t.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}function tl(e){return e&&e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function ol(e){let t=Bn(e);return t.charAt(0).toLowerCase()+t.slice(1)}function hr(){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(`
|
|
2241
|
+
`)}function zn(){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(`
|
|
2242
|
+
`)}var mr="<!-- mist:contracts:start -->",Hn="<!-- mist:contracts:end -->";function gr(e){let t=zn();if(e.includes(mr)){let o=e.indexOf(mr),s=Hn,i=e.indexOf(s,o);if(i===-1)return e.slice(0,o)+t;let n=e.slice(i+s.length);return e.slice(0,o)+t+n.replace(/^\n+/,"")}return e.replace(/\s+$/,"")+`
|
|
2243
|
+
|
|
2244
|
+
`+t}function fr(e,t){let r=Bn(e),o=t??ol(e);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(`
|
|
2245
|
+
`)}function yr(e){return`contracts/${tl(e)}.ts`}function al(e){let t=ke(sl(),".mistflow","plans",`${e}.json`);if(!Qe(t))return null;try{let r=JSON.parse(co(t,"utf-8"));return r.plan?{plan:r.plan}:null}catch{return null}}function cl(e){let t=Et(Kn(e)),r=10,o=0;for(;o<r&&t!==Et(t);){if(Qe(ke(t,"pnpm-workspace.yaml"))||Qe(ke(t,"lerna.json")))return t;let s=ke(t,"package.json");if(Qe(s))try{if(JSON.parse(co(s,"utf-8")).workspaces)return t}catch{}t=Et(t),o++}return null}var dl=Rt.object({name:Rt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:Rt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Rt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Rt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});function O(e,t,r){let o=ke(e,t);br(Et(o),{recursive:!0}),wr(o,r)}function pl(e){if(!Qe(e))return!0;let t;try{t=Vn(e)}catch{return!1}return t.filter(o=>o!==".mistflow").length===0}var ul={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},ml=[["--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 hl(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let r=t[1],o={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},s=r.split(`
|
|
2246
|
+
`),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 p=a(c.slice(6).trim());(p==="dark"||p==="light")&&(o.theme=p);continue}let h=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(h){i=h[1],n=null;continue}if(i==="typography"){let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(p){n=p[1].replace(/-/g,"_"),o.typography[n]={};continue}let f=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(f&&n){o.typography[n][f[1]]=a(f[2]);continue}}let m=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(m&&i){let p=m[1].replace(/-/g,"_"),f=a(m[2]);i==="colors"?o.colors[p]=f:i==="rounded"?o.rounded[p]=f:i==="spacing"&&(o.spacing[p]=f)}}return o}function gl(e,t){let r=e.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(`
|
|
2247
|
+
`),i=[` --radius-sm: ${e.rounded.sm??"0.25rem"};`,` --radius-md: ${e.rounded.md??t};`,` --radius-lg: ${e.rounded.lg??"0.5rem"};`,` --radius-xl: ${e.rounded.xl??"0.75rem"};`].join(`
|
|
2248
2248
|
`);return`@import "tailwindcss";
|
|
2249
2249
|
@import "tw-animate-css";
|
|
2250
2250
|
|
|
@@ -2300,11 +2300,11 @@ ${i}
|
|
|
2300
2300
|
|
|
2301
2301
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2302
2302
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2303
|
-
`}function
|
|
2303
|
+
`}function fl(e,t,r){let o=e?.borderRadius??"subtle",s=ul[o]??"0.375rem";if(r){let n=hl(r);if(n)return gl(n,s)}return`@import "tailwindcss";
|
|
2304
2304
|
@import "tw-animate-css";
|
|
2305
2305
|
|
|
2306
2306
|
@theme {
|
|
2307
|
-
${[...
|
|
2307
|
+
${[...ml.map(([n,a])=>` ${n}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md: ${s};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
|
|
2308
2308
|
`)}
|
|
2309
2309
|
}
|
|
2310
2310
|
|
|
@@ -2354,7 +2354,7 @@ ${[...ul.map(([n,a])=>` ${n}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md:
|
|
|
2354
2354
|
|
|
2355
2355
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2356
2356
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2357
|
-
`}var
|
|
2357
|
+
`}var Wn={"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 Gn(e){let t=e.replace(/[^A-Za-z0-9_ -]/g,"");return Wn[t]?Wn[t]:t.replace(/\s+/g,"_")}function yl(e){return e?{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"}[e.toLowerCase()]??"en":"en"}var bl=new Set(["ar","he","fa","ur"]);function wl(e,t,r){let o=e.replace(/[\\"`$]/g,""),s=yl(r),n=bl.has(s)?`lang="${s}" dir="rtl"`:`lang="${s}"`,a=t?.fonts?.heading,l=t?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
|
|
2358
2358
|
import { DM_Sans } from "next/font/google";
|
|
2359
2359
|
import { Toaster } from "sonner";
|
|
2360
2360
|
import "./globals.css";
|
|
@@ -2370,12 +2370,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2370
2370
|
</html>
|
|
2371
2371
|
);
|
|
2372
2372
|
}
|
|
2373
|
-
`;let
|
|
2374
|
-
import { ${
|
|
2373
|
+
`;let c=Gn(a??l),h=Gn(l??a);return c===h?`import type { Metadata } from "next";
|
|
2374
|
+
import { ${c} } from "next/font/google";
|
|
2375
2375
|
import { Toaster } from "sonner";
|
|
2376
2376
|
import "./globals.css";
|
|
2377
2377
|
|
|
2378
|
-
const font = ${
|
|
2378
|
+
const font = ${c}({ subsets: ["latin"], variable: "--font-body" });
|
|
2379
2379
|
|
|
2380
2380
|
export const metadata: Metadata = { title: "${o}", description: "Built with Mistflow" };
|
|
2381
2381
|
|
|
@@ -2387,11 +2387,11 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2387
2387
|
);
|
|
2388
2388
|
}
|
|
2389
2389
|
`:`import type { Metadata } from "next";
|
|
2390
|
-
import { ${
|
|
2390
|
+
import { ${c}, ${h} } from "next/font/google";
|
|
2391
2391
|
import { Toaster } from "sonner";
|
|
2392
2392
|
import "./globals.css";
|
|
2393
2393
|
|
|
2394
|
-
const heading = ${
|
|
2394
|
+
const heading = ${c}({ subsets: ["latin"], variable: "--font-heading" });
|
|
2395
2395
|
const body = ${h}({ subsets: ["latin"], variable: "--font-body" });
|
|
2396
2396
|
|
|
2397
2397
|
export const metadata: Metadata = { title: "${o}", description: "Built with Mistflow" };
|
|
@@ -2403,38 +2403,38 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2403
2403
|
</html>
|
|
2404
2404
|
);
|
|
2405
2405
|
}
|
|
2406
|
-
`}function
|
|
2407
|
-
`)}function kl(
|
|
2406
|
+
`}function lo(e,...t){let r=JSON.stringify(e).toLowerCase();return t.some(o=>r.includes(o.toLowerCase()))}var vl={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 vr(e){let t=e.toLowerCase().replace(/[^a-z]/g,"");for(let[r,o]of Object.entries(vl))if(t.includes(r))return o;return"Circle"}function Nt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function xl(e){if(e.authModel==="none")return null;let t=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed"];if(e.publicPages&&Array.isArray(e.publicPages))for(let i of e.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;t.includes(a)||t.push(a)}let r=t.filter(i=>i==="/"),o=t.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(`
|
|
2407
|
+
`)}function kl(e){if(e.navStyle==="none")return null;let t=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],o=(e.pages??[]).filter(l=>{let c=l.path??l.route??"";return c==="/"||c===""||c.includes("[")||c.replace(/^\//,"").split("/").length>1?!1:!t.some(m=>c.startsWith(m))}).map(l=>{let c=l.path??l.route??"",h=c.startsWith("/")?c:"/"+c,m=l.name??Nt(c.replace(/^\//,"")),p=vr(m);return{label:m,href:h,icon:p}});o.some(l=>l.href==="/dashboard")||o.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let s=e.authModel==="none",i=[...new Set(o.map(l=>l.icon))];s||i.push("LogOut");let n=Nt(e.name);if(e.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(`
|
|
2408
2408
|
`)}}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(`
|
|
2409
|
-
`)}}function
|
|
2410
|
-
`)}function
|
|
2411
|
-
`)}let r=
|
|
2412
|
-
`)}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">'+
|
|
2409
|
+
`)}}function Sl(e){if(!e.roles||e.roles.length===0)return null;let t=e.roles,r=e.defaultRole??t[0],o=[];o.push("export type Role = "+t.map(s=>'"'+s+'"').join(" | ")+";"),o.push(""),o.push("export const ROLES = ["+t.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 t){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(`
|
|
2410
|
+
`)}function Tl(e){let t=Nt(e.name);if(e.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">'+t+"</h1>"),e.summary&&i.push(' <p className="mt-4 text-lg text-muted-foreground">'+e.summary+"</p>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
|
|
2411
|
+
`)}let r=e.publicPages?.includes("/"),o=e.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">'+t+"</h1>"),e.summary&&i.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+e.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(`
|
|
2412
|
+
`)}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">'+t+"</h1>"),e.summary&&i.push(' <p className="text-lg text-muted-foreground">'+e.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(`
|
|
2413
2413
|
`)}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(`
|
|
2414
|
-
`)}function
|
|
2415
|
-
`)}function
|
|
2416
|
-
`)}function
|
|
2417
|
-
`)}function
|
|
2418
|
-
`)}function
|
|
2419
|
-
`)}function
|
|
2420
|
-
`)}async function
|
|
2414
|
+
`)}function Pl(e,t){let r=e.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";')),e.navStyle==="topbar"?o.push('import TopNav from "@/components/topnav";'):e.navStyle!=="none"&&o.push('import Sidebar from "@/components/sidebar";'),!r&&e.roles&&e.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(""),e.roles&&e.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 e.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(" );")):e.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(`
|
|
2415
|
+
`)}function Il(e){let t=Nt(e.name),r=e.dataModel??[],o=[];if(r.length>0){let s=r.map(n=>vr(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">'+t+"</h1>"),e.summary&&o.push(' <p className="mt-1 text-muted-foreground">'+e.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=vr(i),a=Nt(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(`
|
|
2416
|
+
`)}function Cl(e,t=!1){if(!e.multiTenant)return null;let r=[];return t?(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(),'),t?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(`
|
|
2417
|
+
`)}function Al(e){if(!e.multiTenant)return null;let t=[];return t.push('import { db } from "./db";'),t.push('import { organization, orgMember } from "@/db/schema/organization";'),t.push('import { eq } from "drizzle-orm";'),t.push(""),t.push("export async function getCurrentOrg(userId: string) {"),t.push(" const membership = await db"),t.push(" .select()"),t.push(" .from(orgMember)"),t.push(" .where(eq(orgMember.userId, userId))"),t.push(" .limit(1);"),t.push(" if (membership.length === 0) return null;"),t.push(" const org = await db"),t.push(" .select()"),t.push(" .from(organization)"),t.push(" .where(eq(organization.id, membership[0].orgId))"),t.push(" .limit(1);"),t.push(" return org[0] ?? null;"),t.push("}"),t.push(""),t.push("export async function getOrgMembers(orgId: string) {"),t.push(" return db"),t.push(" .select()"),t.push(" .from(orgMember)"),t.push(" .where(eq(orgMember.orgId, orgId));"),t.push("}"),t.push(""),t.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),t.push(" const id = crypto.randomUUID();"),t.push(" await db.insert(orgMember).values({"),t.push(" id,"),t.push(" orgId,"),t.push(" userId: email,"),t.push(" role,"),t.push(" });"),t.push(" return { id, orgId, email, role };"),t.push("}"),t.push(""),t.join(`
|
|
2418
|
+
`)}function _l(e){if(!e.multiTenant)return null;let t=[];return t.push('"use client";'),t.push(""),t.push("import {"),t.push(" DropdownMenu,"),t.push(" DropdownMenuContent,"),t.push(" DropdownMenuItem,"),t.push(" DropdownMenuTrigger,"),t.push('} from "@/components/ui/dropdown-menu";'),t.push('import { Button } from "@/components/ui/button";'),t.push('import { ChevronsUpDown } from "lucide-react";'),t.push(""),t.push("interface OrgSwitcherProps {"),t.push(" orgs: Array<{ id: string; name: string }>;"),t.push(" currentOrgId: string;"),t.push("}"),t.push(""),t.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),t.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),t.push(""),t.push(" return ("),t.push(" <DropdownMenu>"),t.push(" <DropdownMenuTrigger asChild>"),t.push(' <Button variant="outline" className="w-full justify-between">'),t.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),t.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),t.push(" </Button>"),t.push(" </DropdownMenuTrigger>"),t.push(' <DropdownMenuContent className="w-56">'),t.push(" {orgs.map((org) => ("),t.push(" <DropdownMenuItem key={org.id}>"),t.push(" {org.name}"),t.push(" </DropdownMenuItem>"),t.push(" ))}"),t.push(" </DropdownMenuContent>"),t.push(" </DropdownMenu>"),t.push(" );"),t.push("}"),t.push(""),t.join(`
|
|
2419
|
+
`)}function Rl(e,t,r){let o=[],s=e.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");o.push(`# ${s}`),o.push(""),t?.summary&&(o.push(t.summary),o.push(""));let i=t?.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=t?.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??"",h=l.description??"";o.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${h} |`)}o.push("")}let a=t?.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 h of l.fields)o.push(`| ${h.name} | ${h.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(""),t?.design&&(o.push("## Design"),o.push(""),t.design.tone&&o.push(`- **Tone**: ${t.design.tone}`),t.design.fonts&&(o.push(`- **Heading font**: ${t.design.fonts.heading}`),o.push(`- **Body font**: ${t.design.fonts.body}`)),t.design.accentColor&&o.push(`- **Accent color**: ${t.design.accentColor}`),t.design.borderRadius&&o.push(`- **Border radius**: ${t.design.borderRadius}`),o.push("")),o.push("---"),o.push(""),o.push("Built with [Mistflow](https://mistflow.ai)"),o.push(""),o.join(`
|
|
2420
|
+
`)}async function El(e,t){let{name:r,plan:o,path:s,planId:i}=e;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(!nl(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=Kn(s),a=o;if(!a&&i){let w=al(i);if(!w)return d(`No plan found for planId '${i}'. Call mist_plan first, or pass the plan object inline.`,!0);a=w.plan}let l=a?.design,c=a?.appStyle,h=a?lo(a,"stripe","payment","billing","subscription","checkout","pricing"):!1,m=!0,p=a?lo(a,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,f=a?lo(a,"admin panel","admin dashboard","admin management"):!1,x=a?lo(a,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,b=a,y=!0;if(!pl(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);br(n,{recursive:!0});try{let w=ke(Et(n),".mistflow","mockups");if(Qe(w)){let I=Vn(w).filter(q=>q.endsWith(".html"));if(I.length>0){let q=ke(n,".mistflow","mockups");br(q,{recursive:!0});for(let Y of I)rl(ke(w,Y),ke(q,Y));console.error(`Copied ${I.length} mockup file(s) into project`)}}}catch(w){console.error("Could not copy mockup files:",w instanceof Error?w.message:w)}let v=null;try{v=await Vo("nextjs")}catch(w){console.error("Could not fetch scaffold from API, using minimal scaffold:",w instanceof Error?w.message:w)}if(v){let w=r.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let u of v.files){if(u.path==="package.json"||u.path==="middleware.ts"||u.path==="components/sidebar.tsx"||u.path==="components/topnav.tsx"||u.path==="app/(dashboard)/layout.tsx"||u.path==="app/(dashboard)/page.tsx"||u.path==="app/(dashboard)/dashboard/page.tsx"||!h&&(u.path.includes("stripe")||u.path.includes("webhook/stripe"))||!m&&(u.path.includes("resend")||u.path.includes("emails/"))||!f&&(u.path.includes("(admin)")||u.path.includes("admin-sidebar"))||y&&(u.path==="lib/db.ts"||u.path==="lib/auth.ts"||u.path==="drizzle.config.ts"||u.path==="db/schema/auth.ts"))continue;let g=u.content.replace(/\{\{APP_NAME\}\}/g,r).replace(/\{\{WORKER_NAME\}\}/g,w);if(y&&u.path==="next.config.ts"&&(g=g.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),u.path==="next.config.ts"){let S=cl(n);S&&(console.error(`[init] Project is inside monorepo at ${S} \u2014 adding outputFileTracingRoot`),g.includes("outputFileTracingRoot")||(g=g.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
2421
2421
|
import { dirname } from "path";
|
|
2422
2422
|
import { fileURLToPath } from "url";
|
|
2423
2423
|
|
|
2424
2424
|
const __dirname = dirname(fileURLToPath(import.meta.url));`),g=g.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
2425
|
-
images: {`)))}!
|
|
2425
|
+
images: {`)))}!f&&u.path.includes("sidebar")&&(g=g.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),g=g.replace(/, Shield/g,"")),O(n,u.path,g)}let I={...v.dependencies},q={...v.devDependencies};if(I["drizzle-zod"]||(I["drizzle-zod"]="^0.5.1"),y&&(delete I["@libsql/client"],I["@neondatabase/serverless"]="^0.10.0",q["@electric-sql/pglite"]="^0.2.0"),h&&(I.stripe="^17.0.0"),m&&(I.resend="^4.0.0",I["@react-email/components"]="^0.0.31"),x&&(I.ai="^4.0.0",I["@ai-sdk/openai"]="^1.0.0",I.openai="^4.0.0"),O(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:I,devDependencies:q,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"}},null,2)),v.methodology){let u=v.methodology;y&&(u=u.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres")),u=gr(u),O(n,"AGENTS.md",u),O(n,"CLAUDE.md",u)}let oe=a?.designMd;oe&&O(n,"DESIGN.md",oe),y&&(O(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(`
|
|
2426
2426
|
`)),O(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(`
|
|
2427
2427
|
`)),O(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(`
|
|
2428
2428
|
`)),O(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(`
|
|
2429
2429
|
`)),O(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: "user" }), nextCookies()],'," databaseHooks: {"," user: {"," create: {"," // Auto-promote the app owner to admin on first signup. ADMIN_EMAIL"," // is injected by the Mistflow deploy pipeline (the email of the"," // account that ran mist_deploy). Email verification still gates"," // login when Resend is configured, so a collision attempt can't"," // actually sign in without clicking a link delivered to the"," // owner's inbox."," before: async (user: { email?: string; [k: string]: unknown }) => {"," const adminEmail = process.env.ADMIN_EMAIL;"," if (adminEmail && user.email?.toLowerCase() === adminEmail.toLowerCase()) {",' return { data: { ...user, role: "admin" } };'," }"," return { data: user };"," },"," },"," },"," },"," socialProviders: {"," ...(process.env.GOOGLE_CLIENT_ID ? {"," google: {"," clientId: process.env.GOOGLE_CLIENT_ID,"," clientSecret: process.env.GOOGLE_CLIENT_SECRET!,"," },"," } : {}),"," ...(process.env.GITHUB_CLIENT_ID ? {"," github: {"," clientId: process.env.GITHUB_CLIENT_ID,"," clientSecret: process.env.GITHUB_CLIENT_SECRET!,"," },"," } : {}),"," },"," });","}","","// Lazy init \u2014 process.env isn't populated at module scope on Cloudflare Workers.","// The `has` trap is required: better-auth's toNextJsHandler does",'// `"handler" in auth ? auth.handler(request) : auth(request)` \u2014 without a `has`',"// trap the default forwards to the empty target object, returns false, and the","// handler tries to call the Proxy as a function, which throws TypeError and","// returns 500 on every /api/auth/* request.","let _auth: ReturnType<typeof createAuth> | null = null;","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_target, prop, receiver) {"," if (!_auth) _auth = createAuth();"," const value = Reflect.get(_auth, prop, receiver);",' if (typeof value === "function") return value.bind(_auth);'," return value;"," },"," has(_target, prop) {"," if (!_auth) _auth = createAuth();"," return prop in _auth;"," },","});",""].join(`
|
|
2430
|
-
`)))}else O(n,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0},null,2));let
|
|
2430
|
+
`)))}else O(n,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0},null,2));let C=a?.designMd;O(n,"app/globals.css",fl(l,c,C)),O(n,"app/layout.tsx",wl(r,l,b?.language)),O(n,"README.md",Rl(r,a,{hasStripe:h,hasResend:m,hasStorage:p,hasAdmin:f,hasAI:x,isNeon:y})),O(n,"contracts/README.md",hr());let _=a?.dataModel??[],P=new Set,j=0;for(let w of _){let I=w.entity??w.name;if(!I||typeof I!="string")continue;let q=yr(I);P.has(q)||(P.add(q),O(n,q,fr(I)),j++)}j===0&&O(n,"contracts/.gitkeep","");let L=[],k=a?.publicPages;if(Array.isArray(k))L=k;else if(typeof k=="string"){try{L=JSON.parse(k)}catch{L=[]}Array.isArray(L)||(L=[])}if(!L.includes("/")){let w=a?.steps?.some(q=>{let Y=((q.name??"")+" "+(q.description??"")).toLowerCase();return Y.includes("landing")||Y.includes("marketing")||Y.includes("homepage")}),I=a?.pages?.some(q=>q.path==="/");(w||I)&&(L=["/",...L])}let M={name:r,summary:a?.summary,authModel:a?.authModel,roles:a?.roles,defaultRole:a?.defaultRole,publicPages:L,navStyle:a?.navStyle,multiTenant:a?.multiTenant,pages:a?.pages,dataModel:a?.dataModel,design:a?.design},W=xl(M);W&&O(n,"middleware.ts",W);let G=kl(M);G&&O(n,G.path,G.content);let X=Sl(M);if(X&&O(n,"lib/roles.ts",X),O(n,"app/page.tsx",Tl(M)),O(n,"app/(dashboard)/layout.tsx",Pl(M,f)),O(n,"app/(dashboard)/dashboard/page.tsx",Il(M)),M.multiTenant){let w=Cl(M,y);w&&O(n,"db/schema/organization.ts",w);let I=Al(M);I&&O(n,"lib/org.ts",I);let q=_l(M);q&&O(n,"components/org-switcher.tsx",q)}O(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)),h&&O(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(`
|
|
2431
2431
|
`)),m&&(O(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(`
|
|
2432
2432
|
`)),O(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(`
|
|
2433
2433
|
`))),p&&(O(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(`
|
|
2434
2434
|
`)),O(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(`
|
|
2435
2435
|
`))),x&&(O(n,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
|
|
2436
2436
|
`)),O(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(`
|
|
2437
|
-
`)));let
|
|
2437
|
+
`)));let R=Array.isArray(a?.integrations)?a.integrations.map(w=>({name:w.name,preset:w.preset,envVars:w.envVars??[]})):[],E={};x&&!R.some(w=>w.envVars?.some(I=>I.key==="OPENAI_API_KEY"))&&(E.OPENAI_API_KEY={description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"});for(let w of R)for(let I of w.envVars??[])E[I.key]||(E[I.key]={description:I.description,setupUrl:I.setupUrl,...w.name?{integration:w.name}:{}});let se={name:r,methodologyVersion:v?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},plan:Array.isArray(a?.steps)?{...a,steps:a.steps.map(w=>({number:w.number,name:w.name??w.title,description:w.description,entities:w.entities,pages:w.pages,features:w.features,status:"pending"}))}:a,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...h?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...m?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{},...p?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...Object.keys(E).length>0?{required:E}:{}},authModel:a?.authModel??"email",roles:a?.roles??null,navStyle:a?.navStyle??"sidebar",multiTenant:a?.multiTenant??!1,hasAdmin:f,hasResend:m,hasStorage:p,hasAI:x,deploy:null};O(n,"mistflow.json",JSON.stringify(se,null,2));let pe=il(32).toString("hex"),D=h?`
|
|
2438
2438
|
# Stripe
|
|
2439
2439
|
STRIPE_SECRET_KEY=
|
|
2440
2440
|
STRIPE_WEBHOOK_SECRET=
|
|
@@ -2443,23 +2443,23 @@ NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
|
|
2443
2443
|
# Email (Resend)
|
|
2444
2444
|
RESEND_API_KEY=
|
|
2445
2445
|
EMAIL_FROM=onboarding@resend.dev
|
|
2446
|
-
`:"",
|
|
2446
|
+
`:"",Ce=p?`
|
|
2447
2447
|
# File Storage (Mistflow managed)
|
|
2448
2448
|
MISTFLOW_API_KEY=
|
|
2449
2449
|
MISTFLOW_PROJECT_ID=
|
|
2450
2450
|
`:"",he=x?`
|
|
2451
2451
|
# AI (get your key at https://platform.openai.com/api-keys)
|
|
2452
2452
|
OPENAI_API_KEY=
|
|
2453
|
-
`:"",
|
|
2453
|
+
`:"",Ae=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2454
2454
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2455
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,
|
|
2455
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,ze=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2456
2456
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2457
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;O(n,".env.local",`${
|
|
2457
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;O(n,".env.local",`${Ae}
|
|
2458
2458
|
AUTH_SECRET=${pe}
|
|
2459
|
-
${D}${Z}${
|
|
2459
|
+
${D}${Z}${Ce}${he}`),O(n,".env.example",`${ze}
|
|
2460
2460
|
AUTH_SECRET=your-secret-here
|
|
2461
|
-
${D}${Z}${
|
|
2462
|
-
${oe}=${u}`}yr(Y,be)}try{let{getBaseUrl:Y,getAuthHeaders:be}=await Promise.resolve().then(()=>(me(),Qr)),oe=be(),u=a?.features,g=a?.steps,k={};Array.isArray(u)&&u.length>0&&(k.features=u.map(S=>S.name)),a&&(k.plan=a),Array.isArray(g)&&g.length>0&&(k.provenance=g.map(S=>({feature:S.name??S.title??`Step ${S.number??"?"}`,user_intent:(S.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(k).length>0&&await fetch(`${Y()}/api/projects/${encodeURIComponent(K)}/state`,{method:"PUT",headers:{...oe,"Content-Type":"application/json"},body:JSON.stringify(k)})}catch{}F[F.length-1].message=`Registered as ${K.slice(0,8)}`}catch(w){let I=w instanceof Error?w.message:String(w);console.error("Could not register project on backend:",I),Te=`Project created locally but NOT registered on Mistflow servers (${I}). Deploy will auto-register it.`,F[F.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}H("register",Date.now()-ze),N("git","Initializing git repository...");let He=Date.now();try{let w=al(n);await w.init(),await w.add("."),await w.commit("Initial Mistflow project setup"),F[F.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),F[F.length-1].message="Git init skipped"}H("git",Date.now()-He);let We=F.reduce((w,I)=>w+(I.durationMs??0),0),ge={projectPath:n,projectId:K,status:"awaiting_install"},Ne=F.map(w=>{let I=w.durationMs?` (${(w.durationMs/1e3).toFixed(1)}s)`:"";return`${w.message}${I}`});ge.progress=Ne,ge.totalSetupTime=`${(We/1e3).toFixed(1)}s`;let De=[];K||De.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),Te&&(ge.registrationWarning=Te),De.length>0&&(ge.warnings=De);let je=`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 ge.nextAction=K?je:`${je} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,c(JSON.stringify(ge))}var Kn={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:cl,handler:Rl};import{z as wr}from"zod";import{existsSync as Nt,readFileSync as kr,writeFileSync as vr,mkdirSync as Yl}from"fs";import{join as ut,resolve as Ql,dirname as Xl}from"path";me();import{createConnection as Zl}from"net";var Jn="\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 Yn=`# Consumer Warm Archetype
|
|
2461
|
+
${D}${Z}${Ce}${he}`);let F=[],N=(w,I)=>{F.push({phase:w,message:I})},H=(w,I)=>{let q=F.find(Y=>Y.phase===w&&!Y.durationMs);q&&(q.durationMs=I)};if(t){let w=Ie(t.server,t.progressToken,()=>F[F.length-1]?.message??"Setting up project...");t.cleanup=()=>w.stop()}let ye=b?.requestedSubdomain||void 0,K,Te;N("register","Registering project on Mistflow...");let He=Date.now();try{let w=await St(r,void 0,"neon",ye);K=w.id;let I=ke(n,"mistflow.json"),q=JSON.parse(co(I,"utf-8"));if(q.projectId=K,wr(I,JSON.stringify(q,null,2)),Pt(n,It(K,r)),w.managed_env&&Object.keys(w.managed_env).length>0){let Y=ke(n,".env.local"),be=Qe(Y)?co(Y,"utf-8"):"";for(let[oe,u]of Object.entries(w.managed_env)){let g=new RegExp(`^${oe}=.*$`,"m");g.test(be)?be=be.replace(g,`${oe}=${u}`):be+=`
|
|
2462
|
+
${oe}=${u}`}wr(Y,be)}try{let{getBaseUrl:Y,getAuthHeaders:be}=await Promise.resolve().then(()=>(me(),Xr)),oe=be(),u=a?.features,g=a?.steps,S={};Array.isArray(u)&&u.length>0&&(S.features=u.map(T=>T.name)),a&&(S.plan=a),Array.isArray(g)&&g.length>0&&(S.provenance=g.map(T=>({feature:T.name??T.title??`Step ${T.number??"?"}`,user_intent:(T.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(S).length>0&&await fetch(`${Y()}/api/projects/${encodeURIComponent(K)}/state`,{method:"PUT",headers:{...oe,"Content-Type":"application/json"},body:JSON.stringify(S)})}catch{}F[F.length-1].message=`Registered as ${K.slice(0,8)}`}catch(w){let I=w instanceof Error?w.message:String(w);console.error("Could not register project on backend:",I),Te=`Project created locally but NOT registered on Mistflow servers (${I}). Deploy will auto-register it.`,F[F.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}H("register",Date.now()-He),N("git","Initializing git repository...");let We=Date.now();try{let w=ll(n);await w.init(),await w.add("."),await w.commit("Initial Mistflow project setup"),F[F.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),F[F.length-1].message="Git init skipped"}H("git",Date.now()-We);let Ge=F.reduce((w,I)=>w+(I.durationMs??0),0),ge={projectPath:n,projectId:K,status:"awaiting_install"},De=F.map(w=>{let I=w.durationMs?` (${(w.durationMs/1e3).toFixed(1)}s)`:"";return`${w.message}${I}`});ge.progress=De,ge.totalSetupTime=`${(Ge/1e3).toFixed(1)}s`;let je=[];K||je.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),Te&&(ge.registrationWarning=Te),je.length>0&&(ge.warnings=je);let Oe=`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 ge.nextAction=K?Oe:`${Oe} 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(ge))}var Jn={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:dl,handler:El};import{z as xr}from"zod";import{existsSync as Dt,readFileSync as Sr,writeFileSync as kr,mkdirSync as Ql}from"fs";import{join as ht,resolve as Xl,dirname as Zl}from"path";me();import{createConnection as ec}from"net";var Yn="\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 Qn=`# Consumer Warm Archetype
|
|
2463
2463
|
|
|
2464
2464
|
Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
|
|
2465
2465
|
|
|
@@ -2626,7 +2626,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
|
|
|
2626
2626
|
- Small touch targets. Phone-first means \`h-12\` minimum.
|
|
2627
2627
|
- Empty states that just say "No data." Be encouraging.
|
|
2628
2628
|
- Dark theme as default. Consumer warm apps default to light.
|
|
2629
|
-
`;var
|
|
2629
|
+
`;var Xn=`# Consumer Bold Archetype
|
|
2630
2630
|
|
|
2631
2631
|
Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
|
|
2632
2632
|
|
|
@@ -2797,7 +2797,7 @@ Social/competitive apps need an activity feed:
|
|
|
2797
2797
|
- Card-only layouts with no hierarchy. Use hero cards + supporting cards.
|
|
2798
2798
|
- Missing achievement/progress systems. The gamification IS the product.
|
|
2799
2799
|
- Light-touch buttons. CTAs should be unmissable.
|
|
2800
|
-
`;var
|
|
2800
|
+
`;var Zn=`# Professional Clean Archetype
|
|
2801
2801
|
|
|
2802
2802
|
Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
|
|
2803
2803
|
|
|
@@ -3009,7 +3009,7 @@ h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
|
|
|
3009
3009
|
- Missing status workflows. Every booking/appointment needs a clear state machine.
|
|
3010
3010
|
- Dark theme as default. Clients associate light themes with professionalism.
|
|
3011
3011
|
- Emoji in the UI. Professional context.
|
|
3012
|
-
`;var
|
|
3012
|
+
`;var es=`# Education Structured Archetype
|
|
3013
3013
|
|
|
3014
3014
|
Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
|
|
3015
3015
|
|
|
@@ -3209,7 +3209,7 @@ border-2 border-destructive bg-destructive/5 rounded-xl p-4
|
|
|
3209
3209
|
- Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
|
|
3210
3210
|
- Long lesson pages with no progress indicator. Users need to know where they are.
|
|
3211
3211
|
- Multiple competing elements per view. One thing at a time. One question at a time.
|
|
3212
|
-
`;var
|
|
3212
|
+
`;var ts=`# Marketplace Browse Archetype
|
|
3213
3213
|
|
|
3214
3214
|
Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
|
|
3215
3215
|
|
|
@@ -3433,7 +3433,7 @@ border-b border-border/30 py-4
|
|
|
3433
3433
|
- Small product images. The image is the primary decision-making element.
|
|
3434
3434
|
- No empty state for zero search results. "No results for 'xyz'. Try broader terms."
|
|
3435
3435
|
- Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
|
|
3436
|
-
`;var
|
|
3436
|
+
`;var os=`# SaaS Analytical Archetype
|
|
3437
3437
|
|
|
3438
3438
|
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.
|
|
3439
3439
|
|
|
@@ -3614,7 +3614,7 @@ The most recognizable B2B SaaS landing pattern.
|
|
|
3614
3614
|
- **Inter as the only font.** Pair it with a distinctive heading font or swap it entirely.
|
|
3615
3615
|
- **Centered text + centered image below.** The most overused AI hero. Use split or offset layouts.
|
|
3616
3616
|
- **Animation on every element.** Efficient motion only: hero entrance, card reveals on scroll, number counters. Nothing else.
|
|
3617
|
-
`;var
|
|
3617
|
+
`;var rs=`# Content Editorial Archetype
|
|
3618
3618
|
|
|
3619
3619
|
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.
|
|
3620
3620
|
|
|
@@ -3821,7 +3821,7 @@ Below the hero: 3 featured pieces laid out as a horizontal strip with **oversize
|
|
|
3821
3821
|
- **Dark mode as default for a reading tool.** Offer it as a toggle, not the default.
|
|
3822
3822
|
- **Flashy motion while reading.** Scroll hijacking, parallax on body text, animated backgrounds behind paragraphs \u2014 all break reading flow.
|
|
3823
3823
|
- **More than 2 fonts.** Heading + body is enough. Adding a third font for captions or metadata dilutes the identity.
|
|
3824
|
-
`;var
|
|
3824
|
+
`;var ns=`# Devtool Technical Archetype
|
|
3825
3825
|
|
|
3826
3826
|
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.
|
|
3827
3827
|
|
|
@@ -4010,7 +4010,7 @@ Numbers styled as terminal output: \`> 47,293 deploys this week\`, \`> 99.98% up
|
|
|
4010
4010
|
- **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).
|
|
4011
4011
|
- **Feature cards with rocket / lightning / puzzle icons.** Use technical icons (terminal, code, database, network) or skip icons entirely.
|
|
4012
4012
|
- **Motion on code blocks** while the user is trying to read them. Type out ONCE on load, then leave them alone.
|
|
4013
|
-
`;var
|
|
4013
|
+
`;var ss=`# Creative Showcase Archetype
|
|
4014
4014
|
|
|
4015
4015
|
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.
|
|
4016
4016
|
|
|
@@ -4227,7 +4227,7 @@ Premium agency touch: on first load, a full-screen loading component shows the s
|
|
|
4227
4227
|
- **Scroll hijacking through the whole site.** Use sparingly \u2014 one or two scroll-pinned sections maximum.
|
|
4228
4228
|
- **Mystery-meat navigation.** Clever is bad here. "Work / About / Contact" is fine. Don't make visitors guess.
|
|
4229
4229
|
- **No contact info.** The primary purpose of this site is to generate inquiries. Make it stupid-easy to contact you.
|
|
4230
|
-
`;var
|
|
4230
|
+
`;var is=`# Finance Clarity Archetype
|
|
4231
4231
|
|
|
4232
4232
|
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.
|
|
4233
4233
|
|
|
@@ -4446,7 +4446,7 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
|
|
|
4446
4446
|
- **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
|
|
4447
4447
|
- **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
|
|
4448
4448
|
- **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.
|
|
4449
|
-
`;var
|
|
4449
|
+
`;var as={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Qn},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:Xn},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Zn},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:es},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:ts},"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:os},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:rs},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:ns},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:ss},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:is}};var Wu=Object.keys(as);function ls(e){let t=e?.archetype;if(!(!t||typeof t!="string"))return as[t]}var cs=`# Landing Page Rules
|
|
4450
4450
|
|
|
4451
4451
|
These rules apply to every landing page. They are non-negotiable.
|
|
4452
4452
|
|
|
@@ -4843,7 +4843,7 @@ app/
|
|
|
4843
4843
|
\`\`\`
|
|
4844
4844
|
|
|
4845
4845
|
Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
|
|
4846
|
-
`;var
|
|
4846
|
+
`;var ds=`# Design Doctrine
|
|
4847
4847
|
|
|
4848
4848
|
This is the standard for every UI you generate. It is not aspirational. It is the floor.
|
|
4849
4849
|
|
|
@@ -4909,7 +4909,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
|
|
|
4909
4909
|
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.**
|
|
4910
4910
|
|
|
4911
4911
|
If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
|
|
4912
|
-
`;var
|
|
4912
|
+
`;var ps=`# Typography
|
|
4913
4913
|
|
|
4914
4914
|
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.
|
|
4915
4915
|
|
|
@@ -4997,7 +4997,7 @@ Pick exactly one:
|
|
|
4997
4997
|
- **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
|
|
4998
4998
|
|
|
4999
4999
|
Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
|
|
5000
|
-
`;var
|
|
5000
|
+
`;var us="# Color\n\nColor is a commitment, not a palette swatch. The #1 failure mode in AI-generated landings is an evenly-distributed palette: a little emerald here, a little amber there, a gradient, a badge. That's visual hedging \u2014 it signals \"I couldn't pick a point of view.\"\n\nPick one color. Use it with intent.\n\n## The Token System\n\nEvery color on every screen goes through a CSS variable defined in `globals.css`. You do not hand-pick hex values in JSX. You do not use Tailwind palette utilities (`bg-emerald-500`, `text-blue-600`, `border-slate-200`). If a color isn't in the token scheme, it doesn't exist for this app.\n\n### Core tokens\n\n- `--color-background` \u2014 page background\n- `--color-foreground` \u2014 default body text\n- `--color-card` \u2014 elevated surface (cards, panels)\n- `--color-card-foreground` \u2014 text on cards\n- `--color-muted` \u2014 low-emphasis surface fill\n- `--color-muted-foreground` \u2014 secondary text (\u2265 WCAG AA contrast vs background)\n- `--color-border` \u2014 subtle dividers\n- `--color-input` \u2014 form input borders\n- `--color-popover` / `--color-popover-foreground` \u2014 dropdowns, tooltips, menus\n\n### Interactive tokens\n\n- `--color-primary` \u2014 primary CTAs, links, active tab, focus ring\n- `--color-primary-foreground` \u2014 text on primary (derived for WCAG AA contrast)\n- `--color-ring` \u2014 focus outline (same hue as primary)\n- `--color-secondary` / `--color-secondary-foreground` \u2014 quieter than primary, more than muted\n- `--color-accent` / `--color-accent-foreground` \u2014 hover states on neutrals\n\n### Semantic tokens\n\n- `--color-success` \u2014 confirmation, \"verified\" banners, positive states\n- `--color-warning` \u2014 pending states, attention, non-destructive caution\n- `--color-destructive` / `--color-destructive-foreground` \u2014 errors, irreversible actions\n- `--color-info` \u2014 neutral system messages, tips\n\n**You use these semantic tokens for all status UI.** When you need a \"green checkmark\" you reach for `text-success`, not `text-emerald-500`. When you need an amber alert you reach for `bg-warning/10 text-warning`, not `bg-amber-50 text-amber-700`.\n\n## Usage Rules\n\n**Primary color:**\n- Primary CTAs, links, the active navigation tab, focus rings.\n- NOT for headings. Black or foreground-colored headings are stronger.\n- NOT for large surface fills (it's a splash of color, not a wash).\n- NOT for borders except focus rings.\n- One bold use of primary beats twenty sprinkled uses.\n\n**Neutrals do the structural work:**\n- Background, cards, borders \u2014 all come from the neutral scale.\n- Text hierarchy via opacity on foreground (`text-foreground`, `text-foreground/80`, `text-muted-foreground`) \u2014 not different colors.\n\n**Semantic colors:**\n- Use `bg-success/10 text-success border border-success/30` for success banners (reproducibility: a light-tinted version of the success color for surface, the solid version for text and border).\n- Same shape for warning, info, destructive.\n\n## Dark Mode\n\nCommit to one theme. If DESIGN.md says the app is dark-themed, make it unambiguously dark \u2014 `#0c0c0c` / near-black base, not neutral-900. If light-themed, commit to light.\n\nDo NOT auto-swap based on `prefers-color-scheme` when the design system declared a theme direction. The appStyle chose a theme for a reason; respect it.\n\n## Forbidden\n\n- Palette utilities: `bg-emerald-500`, `text-blue-600`, `border-slate-200`, `from-purple-500`, `via-pink-300`, `to-amber-400`. Every one of these in your output is a slop indicator.\n- Hex literals inside `className` or inline `style` props.\n- Named colors from CSS (`red`, `lightgrey`, `rebeccapurple`) \u2014 never used in production UI; always a sign of rushed work.\n- Purple gradients on white. The single most overused AI-design pattern.\n- Three-color gradient pills. Rainbow badges. \"Vibrant\" anything.\n\n## Contrast\n\nEvery text/surface pair in DESIGN.md is already WCAG AA-verified by Mistflow's contrast test. You do not need to re-check \u2014 the tokens are safe by construction. You DO need to:\n\n- Not override token combinations with hardcoded classes that might fail contrast.\n- Maintain contrast for overlays (text on images, modals on scrims). When stacking text over a gradient or image, include a scrim (`bg-background/80 backdrop-blur-sm`) so body text stays \u2265 4.5:1.\n\n## Getting Color Wrong\n\nThe specific failure mode to avoid: a page where primary is used in five places, all small and incidental \u2014 a checkmark, a hover state, a tiny badge. That's AI hedging. Either use primary confidently on a hero CTA and mean it, OR don't use primary on the page at all and let neutrals carry the identity.\n";var ms=`# Motion
|
|
5001
5001
|
|
|
5002
5002
|
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.
|
|
5003
5003
|
|
|
@@ -5075,7 +5075,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
|
|
|
5075
5075
|
## One-Line Motion Rule
|
|
5076
5076
|
|
|
5077
5077
|
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.
|
|
5078
|
-
`;var
|
|
5078
|
+
`;var hs=`# Spatial Composition
|
|
5079
5079
|
|
|
5080
5080
|
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.
|
|
5081
5081
|
|
|
@@ -5145,7 +5145,7 @@ To signal "designed, not templated":
|
|
|
5145
5145
|
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.
|
|
5146
5146
|
|
|
5147
5147
|
Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
|
|
5148
|
-
`;var
|
|
5148
|
+
`;var gs=`# Interaction
|
|
5149
5149
|
|
|
5150
5150
|
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.
|
|
5151
5151
|
|
|
@@ -5230,7 +5230,7 @@ Small moments that add up to "designed":
|
|
|
5230
5230
|
- **Empty states** offer a specific next action, not "No data yet".
|
|
5231
5231
|
|
|
5232
5232
|
These micro-interactions are the texture of a designed product. Ship them.
|
|
5233
|
-
`;var
|
|
5233
|
+
`;var fs=`# UX Writing
|
|
5234
5234
|
|
|
5235
5235
|
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.
|
|
5236
5236
|
|
|
@@ -5306,14 +5306,14 @@ If there's a pricing page:
|
|
|
5306
5306
|
## The Footer
|
|
5307
5307
|
|
|
5308
5308
|
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."
|
|
5309
|
-
`;function
|
|
5310
|
-
`)}function lo(t){return t.entity??t.name??"Unknown"}function rc(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function ys(t){return t.path??t.route??t.name??""}function nc(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 bs(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=lo(o).toLowerCase();return r.some(i=>s.includes(i)||i.includes(s))})}function sc(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=ys(o).toLowerCase();return r.some(n=>s.includes(n)||n.includes(s)||i.includes(n))})}var ic=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function ac(t){let e=t.stepType;if(e&&ic.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 lc(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 cc(t,e){let r=[];if(r.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&r.push(`- **App tone**: ${t.tone}`),t.fonts&&(r.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),r.push(`- **Body font**: ${t.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)."),t.borderRadius){let o={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};r.push(`- **Border radius**: ${t.borderRadius} (${o[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.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**: ${t.shadowStyle} \u2014 ${o[t.shadowStyle]??t.shadowStyle}`)}if(t.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**: ${t.cardStyle} \u2014 ${o[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&r.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let o=t.visualStrategy,s=t.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=as(t);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(Jn),r.join(`
|
|
5311
|
-
`)}async function
|
|
5309
|
+
`;function tc(e){return new Promise(t=>{let r=ec({port:e,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),t(!0)}),r.on("error",()=>{t(!1)})})}var oc=xr.object({projectPath:xr.string().optional().describe("Path to the project directory (default: cwd)"),step:xr.number().optional().describe("Specific step number to implement (default: next incomplete step)")});function rc(e){let t=ht(e,"mistflow.json");if(!Dt(t))return null;try{return JSON.parse(Sr(t,"utf-8"))}catch{return null}}function ys(e,t){let r=ht(e,"mistflow.json");kr(r,JSON.stringify(t,null,2)+`
|
|
5310
|
+
`)}function po(e){return e.entity??e.name??"Unknown"}function nc(e){return e.length===0?"":typeof e[0]=="string"?e.join(", "):e.map(t=>`${t.name} (${t.type})`).join(", ")}function bs(e){return e.path??e.route??e.name??""}function sc(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 ws(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=po(o).toLowerCase();return r.some(i=>s.includes(i)||i.includes(s))})}function ic(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=bs(o).toLowerCase();return r.some(n=>s.includes(n)||n.includes(s)||i.includes(n))})}var ac=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function lc(e){let t=e.stepType;if(t&&ac.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 cc(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 dc(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=ls(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(Yn),r.join(`
|
|
5311
|
+
`)}async function pc(e){try{let t=await Ko("nextjs",e);return{reminders:t.reminders,skill:t.skill}}catch{return{reminders:`### ${e} step
|
|
5312
5312
|
- Follow existing patterns in the codebase
|
|
5313
|
-
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function pc(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(cc(e.design,{hasDesignPreset:!!e.landingDesign&&(s==="landing"||s==="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 b=_n(i);if(b.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 f of b){let T=f.replace(i,"").replace(/^\//,"");n.push(`- \`${T}\``)}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 d=["landing","design","auth","general","crud","dashboard"];e.audienceType&&d.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(b=>n.push(`- ${b}`)),n.push(""));let h=e.dataModel?bs(t,e.dataModel):[];h.length>0&&(n.push("### Data model (from plan):"),h.forEach(b=>{let f=lo(b),T=rc(b.fields);n.push(`- **${f}**: ${T}`),n.push(` Schema file: \`db/schema/${f.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),n.push(""));let m=e.pages?sc(t,e.pages):[];if(m.length>0&&(n.push("### Pages to create/update:"),m.forEach(b=>{let f=b.description?` \u2014 ${b.description}`:"";n.push(`- \`${ys(b)}\`${f}`)}),n.push("")),s==="crud"&&h.length>0&&h.forEach(b=>{let f=lo(b),T=f.toLowerCase().replace(/\s+/g,"-"),A=T.endsWith("s")?T:`${T}s`;n.push(`### Files for ${f} 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/${T}-table-columns.tsx\``),n.push(`- Form: \`components/${T}-form.tsx\``),n.push("")}),l){n.push("## Design Doctrine (the standard for every UI step)"),n.push(""),n.push(cs),n.push(""),n.push("## Design Reference Library"),n.push(""),n.push("### Typography"),n.push(ds),n.push(""),n.push("### Color"),n.push(ps),n.push(""),n.push("### Motion"),n.push(us),n.push(""),n.push("### Spatial Composition"),n.push(ms),n.push(""),n.push("### Interaction"),n.push(hs),n.push(""),n.push("### UX Writing"),n.push(gs),n.push("");let b=i?ut(i,"DESIGN.md"):void 0,f=b&&Nt(b)?(()=>{try{return kr(b,"utf-8")}catch{return null}})():null;f&&(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(f),n.push(""))}(s==="landing"||s==="design")&&(n.push(ls),n.push(""));let p=t.integrationId?at(t.integrationId):void 0;if(p){let b=lt(p.id);if(n.push("### Integration blueprint (follow this closely):"),n.push(""),n.push(`Using integration: **${p.name}** (${p.category})`),b?.docsUrl&&n.push(`Official docs: ${b.docsUrl}`),b?.envVars?.length){n.push(""),n.push("**Required environment variables:**");for(let f of b.envVars)n.push(`- \`${f.key}\`: ${f.description} \u2014 Get it at ${f.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.")}b?.packages?.length&&(n.push(""),n.push(`**Packages to install:** \`npm install ${b.packages.join(" ")}\``)),n.push(""),n.push("---"),n.push(p.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:y,skill:x}=await dc(s);return n.push(y),n.push(""),x&&!(s==="landing"&&e.landingDesign==="freeform")&&(n.push(`### ${s} reference:`),n.push(x),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(`
|
|
5314
|
-
`)}async function
|
|
5315
|
-
`+
|
|
5316
|
-
`)}E>0?
|
|
5313
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function uc(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(dc(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 b=Rn(i);if(b.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 y of b){let v=y.replace(i,"").replace(/^\//,"");n.push(`- \`${v}\``)}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(b=>n.push(`- ${b}`)),n.push(""));let h=t.dataModel?ws(e,t.dataModel):[];h.length>0&&(n.push("### Data model (from plan):"),h.forEach(b=>{let y=po(b),v=nc(b.fields);n.push(`- **${y}**: ${v}`),n.push(` Schema file: \`db/schema/${y.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),n.push(""));let m=t.pages?ic(e,t.pages):[];if(m.length>0&&(n.push("### Pages to create/update:"),m.forEach(b=>{let y=b.description?` \u2014 ${b.description}`:"";n.push(`- \`${bs(b)}\`${y}`)}),n.push("")),s==="crud"&&h.length>0&&h.forEach(b=>{let y=po(b),v=y.toLowerCase().replace(/\s+/g,"-"),C=v.endsWith("s")?v:`${v}s`;n.push(`### Files for ${y} CRUD:`),n.push(`- List page: \`app/(dashboard)/${C}/page.tsx\` (Server Component)`),n.push(`- Detail page: \`app/(dashboard)/${C}/[id]/page.tsx\``),n.push(`- Create page: \`app/(dashboard)/${C}/new/page.tsx\``),n.push(`- Server Actions: \`app/(dashboard)/${C}/actions.ts\``),n.push(`- DataTable columns: \`components/${v}-table-columns.tsx\``),n.push(`- Form: \`components/${v}-form.tsx\``),n.push("")}),l){n.push("## Design Doctrine (the standard for every UI step)"),n.push(""),n.push(ds),n.push(""),n.push("## Design Reference Library"),n.push(""),n.push("### Typography"),n.push(ps),n.push(""),n.push("### Color"),n.push(us),n.push(""),n.push("### Motion"),n.push(ms),n.push(""),n.push("### Spatial Composition"),n.push(hs),n.push(""),n.push("### Interaction"),n.push(gs),n.push(""),n.push("### UX Writing"),n.push(fs),n.push("");let b=i?ht(i,"DESIGN.md"):void 0,y=b&&Dt(b)?(()=>{try{return Sr(b,"utf-8")}catch{return null}})():null;y&&(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(y),n.push(""))}(s==="landing"||s==="design")&&(n.push(cs),n.push(""));let p=e.integrationId?ct(e.integrationId):void 0;if(p){let b=dt(p.id);if(n.push("### Integration blueprint (follow this closely):"),n.push(""),n.push(`Using integration: **${p.name}** (${p.category})`),b?.docsUrl&&n.push(`Official docs: ${b.docsUrl}`),b?.envVars?.length){n.push(""),n.push("**Required environment variables:**");for(let y of b.envVars)n.push(`- \`${y.key}\`: ${y.description} \u2014 Get it at ${y.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.")}b?.packages?.length&&(n.push(""),n.push(`**Packages to install:** \`npm install ${b.packages.join(" ")}\``)),n.push(""),n.push("---"),n.push(p.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:f,skill:x}=await pc(s);return n.push(f),n.push(""),x&&!(s==="landing"&&t.landingDesign==="freeform")&&(n.push(`### ${s} reference:`),n.push(x),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(`
|
|
5314
|
+
`)}async function mc(e){let{projectPath:t,step:r}=e,o=Xl(t??process.cwd()),s=rc(o);if(!s)return Re(o);if(!Dt(ht(o,"node_modules")))return d(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:k,ensureShadcnComponents:M}=await Promise.resolve().then(()=>(or(),tr));await k(o);let W=await M(o);W.failed?console.error(`[implement] ${W.failed}`):W.installed.length>0&&console.error(`[implement] installed ${W.installed.length} shadcn components`)}catch(k){console.error("[implement] self-heal skipped:",k instanceof Error?k.message:String(k))}let i=s.plan;if(!i||!i.steps||i.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 n,a=i.steps.find(k=>k.status==="in_progress");if(a){let k=i.steps.findIndex(M=>M.number===a.number);k!==-1&&(i.steps[k].status="completed",n=`Auto-completed step ${a.number} (${a.name})`,ys(o,s))}let l;if(r!==void 0){if(l=i.steps.find(k=>k.number===r),!l)return d(`Step ${r} not found. The plan has ${i.steps.length} steps (numbered ${i.steps[0].number} to ${i.steps[i.steps.length-1].number}).`,!0)}else if(l=i.steps.find(k=>k.status!=="completed"),!l)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:i.steps.map(k=>k.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let c=i.steps.filter(k=>k.status==="completed").map(k=>`Step ${k.number}: ${k.name}`),{readLocalState:h}=await Promise.resolve().then(()=>(Je(),Ct)),m=h(o),p=lc(l),f=[];if((p==="crud"||p==="schema")&&i.dataModel&&l.entities&&l.entities.length>0){let k=ws(l,i.dataModel);for(let M of k){let W=po(M);try{let G=(M.fields||[]).map(D=>typeof D=="string"?{name:D,type:"text"}:{name:D.name,type:sc(D.type),required:D.required!==!1});if(G.length===0)continue;let X=s.dbProvider==="neon"?"nextjs-neon":"nextjs",R=await Jo(X,W,G),E=0,se=0;for(let D of R.files){let Z=ht(o,D.path);if(Dt(Z)){se++;continue}Ql(Zl(Z),{recursive:!0}),kr(Z,D.content),E++}let pe=ht(o,"db","index.ts");if(Dt(pe)){let D=Sr(pe,"utf-8");D.includes(R.dbExport)||kr(pe,D.trimEnd()+`
|
|
5315
|
+
`+R.dbExport+`
|
|
5316
|
+
`)}E>0?f.push(`${R.entityPascal} CRUD (${E} new files${se>0?`, ${se} existing skipped`:""})`):se>0&&f.push(`${R.entityPascal} CRUD (all ${se} files already exist \u2014 skipped)`)}catch(G){console.error(`Module generation failed for ${W} (non-fatal):`,G instanceof Error?G.message:G)}}}let x=await uc(l,i,c,null,p,o),b=i.steps.findIndex(k=>k.number===l.number);if(b!==-1&&(s.plan.steps[b].status="in_progress",ys(o,s)),m&&s.projectId){let{syncRemoteState:k}=await Promise.resolve().then(()=>(Je(),Ct));k(s.projectId,m).catch(()=>{})}let y=i.steps.every(k=>k.status==="completed"||k.number===l.number),v;y?v=`THIS IS THE LAST STEP. Rules for speed:
|
|
5317
5317
|
|
|
5318
5318
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
5319
5319
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -5322,14 +5322,14 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
5322
5322
|
- app/page.tsx must be a real landing page, NOT a redirect to /login
|
|
5323
5323
|
- middleware.ts must have "/" in PUBLIC_EXACT or PUBLIC_PREFIXES
|
|
5324
5324
|
- Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
|
|
5325
|
-
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.`:
|
|
5325
|
+
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.`:v=`IMPLEMENT THIS STEP NOW. Rules for speed:
|
|
5326
5326
|
|
|
5327
5327
|
1. BEFORE writing any files, tell the user: "[stepTiming.announcement]" \u2014 use the exact announcement string from the stepTiming field so they know what's happening and how long it'll take. This is a one-line status update, NOT a request for permission.
|
|
5328
5328
|
2. Write ALL files for this step using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message. Do NOT write one file at a time.
|
|
5329
5329
|
3. Do NOT read files you already know: AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts, drizzle.config.ts \u2014 these haven't changed.
|
|
5330
5330
|
4. Only read a file if you need to MODIFY it (e.g. sidebar.tsx to add a nav link, db/index.ts to add an export).
|
|
5331
|
-
5. After writing ALL files, call mist_implement to move to the next step. Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let
|
|
5332
|
-
`)}async function ks(
|
|
5331
|
+
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 C=cc(p),_={stepNumber:l.number,totalSteps:i.steps.length,estimatedMinutes:C,announcement:`Starting step ${l.number} of ${i.steps.length}: ${l.name}. This step usually takes ${C.min}\u2013${C.max} minutes.`},j=JSON.stringify({instruction:x,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:_,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.",...n?{autoCompleted:n}:{},...f.length>0?{generatedModules:f,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:`${c.length}/${i.steps.length} steps done`,nextAction:v});return await tc(3e3)?zr("http://localhost:3000",j):d(j)}var vs={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:oc,handler:mc};import{z as Se}from"zod";import{z as Be}from"zod";import{resolve as hc}from"path";me();rt();var Pm=Be.object({projectPath:Be.string().optional().describe("Path to the project directory (default: cwd)"),action:Be.enum(["set","list","delete"]).describe("Action to perform"),key:Be.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:Be.string().optional().describe("Environment variable value (required for 'set')"),category:Be.string().optional().describe("Category for the env var (default: 'custom')"),description:Be.string().optional().describe("Description of what this env var is for"),setupUrl:Be.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function xs(e){let{projectPath:t,action:r,key:o,value:s,category:i,description:n,setupUrl:a}=e,l=hc(t??process.cwd());if(!ee())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let h=Le(l)?.projectId;if(!h)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 qo(h,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 m=await Fo(h);return m.length===0?d(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):d(JSON.stringify({envVars:m.map(p=>({key:p.key,category:p.category,description:p.description,hasValue:p.has_value})),message:`${m.length} environment variable(s) configured.`}))}case"delete":return o?(await Bo(h,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(m){if(m instanceof U)return d(m.message,!0);let p=m instanceof Error?m.message:"An unexpected error occurred";return d(p,!0)}}import{z as jt}from"zod";import{resolve as gc,join as fc}from"path";import{existsSync as yc,readFileSync as bc,writeFileSync as wc}from"fs";me();rt();var Dm=jt.object({projectPath:jt.string().optional().describe("Path to the project directory (default: cwd)"),action:jt.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:jt.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:jt.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function Tr(e,t){let r=fc(e,"mistflow.json");if(!yc(r))return;let o;try{o=JSON.parse(bc(r,"utf-8"))}catch{return}o.domains=t,wc(r,JSON.stringify(o,null,2)+`
|
|
5332
|
+
`)}async function ks(e){let{projectPath:t,action:r,domain:o,domainId:s}=e,i=gc(t??process.cwd());if(!ee())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=Le(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 Mo(a,o),c=await Ue(a);return Tr(i,c.map(h=>({domain:h.domain,status:h.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 Ue(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 m=(await Ue(a)).find(p=>p.domain===o);if(m){let p=await Jt(a,m.id);return d(JSON.stringify({domain:p.domain,status:p.status,ssl:p.ssl_status,error:p.error_message,message:p.status==="active"?`Domain '${p.domain}' is active and serving traffic.`:`Domain '${p.domain}' is ${p.status}. Make sure DNS records are configured correctly.`}))}return 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 Jt(a,s),c=await Ue(a);return Tr(i,c.map(h=>({domain:h.domain,status:h.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 m=(await Ue(a)).find(p=>p.domain===o);if(!m)return d(`Domain '${o}' not found.`,!0);l=m.id}await Lo(a,l);let c=await Ue(a);return Tr(i,c.map(h=>({domain:h.domain,status:h.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 U)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var vc=Se.object({resource:Se.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Se.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Se.string().optional().describe("Path to the project directory (default: cwd)"),key:Se.string().optional().describe("(env) Variable name"),value:Se.string().optional().describe("(env set) Variable value"),category:Se.string().optional().describe("(env set) Category"),description:Se.string().optional().describe("(env set) Description"),setupUrl:Se.string().optional().describe("(env set) URL to obtain the value"),domain:Se.string().optional().describe("(domain) Domain name"),domainId:Se.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:vc,handler:async e=>{let t=e;switch(t.resource){case"env":return xs({projectPath:t.projectPath,action:t.action,key:t.key,value:t.value,category:t.category,description:t.description,setupUrl:t.setupUrl});case"domain":return ks({projectPath:t.projectPath,action:t.action,domain:t.domain,domainId:t.domainId});default:return d(`Unknown resource: ${t.resource}. Use env or domain.`,!0)}}};import{z as fo}from"zod";import{resolve as Oc}from"path";import{existsSync as Mc}from"fs";import{join as Lc}from"path";import{spawn as xc,execFileSync as kc}from"child_process";import{existsSync as uo,mkdirSync as Is,openSync as Pr,closeSync as Ir,readSync as Sc,readFileSync as Cs,writeFileSync as As,renameSync as _s,unlinkSync as Tc,readdirSync as Bm,statSync as Pc}from"fs";import{homedir as Rs}from"os";import{join as fe,dirname as Es}from"path";import{randomBytes as Ns,randomUUID as Ic}from"crypto";var Ds=1,Cc=`// Generated by @mistflow-ai/mcp local-jobs (v${Ds}). Do not edit.
|
|
5333
5333
|
const { spawn } = require('node:child_process');
|
|
5334
5334
|
const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
|
|
5335
5335
|
const { join, dirname } = require('node:path');
|
|
@@ -5393,22 +5393,26 @@ child.on('error', (err) => {
|
|
|
5393
5393
|
});
|
|
5394
5394
|
process.exit(1);
|
|
5395
5395
|
});
|
|
5396
|
-
`;function
|
|
5397
|
-
`),
|
|
5398
|
-
`).slice(-
|
|
5399
|
-
`).slice(-
|
|
5400
|
-
`)}function
|
|
5401
|
-
|
|
5402
|
-
`)}
|
|
5403
|
-
|
|
5404
|
-
`)
|
|
5405
|
-
${
|
|
5406
|
-
`)}
|
|
5396
|
+
`;function mo(){return fe(Rs(),".mistflow","jobs")}function Ac(){return fe(Rs(),".mistflow","job-wrapper.cjs")}function _c(){let e=Ac(),t=Es(e);uo(t)||Is(t,{recursive:!0});let r=`v${Ds}`;if(uo(e))try{if(Cs(e,"utf-8").includes(r))return e}catch{}let o=fe(t,`.job-wrapper.tmp.${Ns(6).toString("hex")}`);return As(o,Cc),_s(o,e),e}function gt(e){return fe(mo(),e)}function js(e){return fe(gt(e),"status.json")}function Ts(e,t){let r=js(e),o=fe(Es(r),`.status.tmp.${Ns(6).toString("hex")}`);try{As(o,JSON.stringify(t,null,2)+`
|
|
5397
|
+
`),_s(o,r)}catch(s){try{Tc(o)}catch{}throw s}}function Rc(e){let t=js(e);if(!uo(t))return null;try{return JSON.parse(Cs(t,"utf-8"))}catch{return null}}async function ho(e){let t=`job_${Ic().replace(/-/g,"").slice(0,12)}`,r=gt(t);Is(r,{recursive:!0}),Ir(Pr(fe(r,"stdout.log"),"a")),Ir(Pr(fe(r,"stderr.log"),"a"));let o=new Date().toISOString(),s={id:t,type:e.type,status:"starting",pid:0,wrapperPid:0,startedAt:o,cmd:e.cmd,args:e.args,cwd:e.cwd};Ts(t,s);let i=_c(),n={...process.env,...e.env??{}},a=xc("node",[i,r,e.cwd,e.cmd,...e.args],{detached:!0,stdio:"ignore",env:n});a.unref();let l={...s,wrapperPid:a.pid??0};return Ts(t,l),l}function Ec(e){let t=e.trim();if(!t)return NaN;let r=Date.parse(t);return Number.isFinite(r)?r:NaN}function Nc(e){let t=e.pid||e.wrapperPid;if(!t)return!1;try{process.kill(t,0)}catch{return!1}try{let r=kc("ps",["-o","lstart=","-p",String(t)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),o=Ec(r),s=Date.parse(e.startedAt);if(Number.isFinite(o)&&Number.isFinite(s)&&Math.abs(o-s)>2e3)return!1}catch{}return!0}function Dc(e,t){let r=Date.parse(e),o=t?Date.parse(t):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 Ps(e,t){if(!uo(e))return"";let r=Pc(e);if(r.size===0)return"";let o=r.size>t?r.size-t:0,s=r.size-o,i=Pr(e,"r");try{let n=Buffer.alloc(s);return Sc(i,n,0,s,o),n.toString("utf-8")}finally{Ir(i)}}function jc(e,t=200){let r=Ps(fe(gt(e),"stdout.log"),65536),o=Ps(fe(gt(e),"stderr.log"),64*1024),s=[];return r.trim()&&s.push(...r.split(`
|
|
5398
|
+
`).slice(-t).map(i=>`[out] ${i}`)),o.trim()&&s.push(...o.split(`
|
|
5399
|
+
`).slice(-t).map(i=>`[err] ${i}`)),s.filter(i=>i.trim().length>0).join(`
|
|
5400
|
+
`)}function Ot(e){return{stdout:fe(gt(e),"stdout.log"),stderr:fe(gt(e),"stderr.log")}}async function Mt(e){let t=Rc(e);if(!t)return null;let r=t;return(t.status==="running"||t.status==="starting")&&!Nc(t)&&(r={...t,status:"unknown_exit",endedAt:t.endedAt??new Date().toISOString()}),{...r,elapsed:Dc(r.startedAt,r.endedAt),logTail:jc(e)}}async function go(e,t){let r=Math.max(100,t.pollIntervalMs??500),o=Date.now()+Math.max(0,t.timeoutMs),s=["complete","failed","unknown_exit"];for(;;){let i=await Mt(e);if(!i)return null;try{t.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 Uc(e,t=15){let r=e.split(`
|
|
5401
|
+
`).filter(o=>o.length>0);return r.length<=t?e:r.slice(-t).join(`
|
|
5402
|
+
`)}var $c=fo.object({projectPath:fo.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:fo.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:fo.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(e=>!!e.projectPath||!!e.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),Os={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:$c,handler:async(e,t)=>{let r=e;if(r.jobId){let l=await Mt(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 m=l.elapsed,p=t?Ie(t.server,t.progressToken,()=>`Install running (${m}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let f=await go(r.jobId,{timeoutMs:c*1e3,onPoll:x=>{m=x.elapsed}});f&&(l=f)}finally{p.stop()}}if(l.status==="running"||l.status==="starting")return d(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:Uc(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 h=Ot(l.id);return d(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:h,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 (${h.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let o=Oc(r.projectPath);if(!Mc(Lc(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 ho({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 Lt}from"zod";import{resolve as Fc,join as Ee}from"path";import{existsSync as Ne,readFileSync as Ms,statSync as qc}from"fs";var Ls=10*1024;function Bc(e){if(!(Ne(Ee(e,"open-next.config.ts"))||Ne(Ee(e,"open-next.config.js"))))return null;let r=Ee(e,".open-next","worker.js");if(!Ne(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker bundle. Common causes: (1) open-next.config.ts is misconfigured, (2) a client component imports a Node-only API (fs, path, crypto node:* imports in 'use client' files), (3) the adapter crashed silently mid-build. Check the logTail above for "error"/"failed" messages, fix the offending file, and re-run mist_build.`;try{let o=qc(r).size;if(o<Ls)return`Build exited 0 but .open-next/worker.js is only ${o} bytes (expected at least ${Ls}). The worker bundle is too small to be a working app \u2014 the adapter likely failed to bundle most of the code. Check open-next.config.ts and the logTail above for errors, fix them, and re-run mist_build.`}catch(o){return`Could not stat .open-next/worker.js: ${o instanceof Error?o.message:String(o)}. Re-run mist_build.`}return null}var zc=Lt.object({projectPath:Lt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Lt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Lt.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:Lt.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(e=>!!e.projectPath||!!e.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});function Hc(e){let t=Ee(mo(),e,"stdout.log"),r=Ee(mo(),e,"stderr.log"),o="";try{Ne(t)&&(o+=Ms(t,"utf-8"))}catch{}try{Ne(r)&&(o+=`
|
|
5403
|
+
`+Ms(r,"utf-8"))}catch{}return o}function Wc(e,t=15){let r=e.split(`
|
|
5404
|
+
`).filter(o=>o.length>0);return r.length<=t?e:r.slice(-t).join(`
|
|
5405
|
+
`)}function Gc(e){let t=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let o of e.matchAll(t)){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 Us={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:zc,handler:async(e,t)=>{let r=e;if(r.jobId){let c=await Mt(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 h=r.waitSeconds??20;if(h>0&&(c.status==="running"||c.status==="starting")){let v=c.elapsed,C=t?Ie(t.server,t.progressToken,()=>`Build running (${v}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let _=await go(r.jobId,{timeoutMs:h*1e3,onPoll:P=>{v=P.elapsed}});_&&(c=_)}finally{C.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Wc(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 v=Bc(c.cwd);if(v){let C=Ot(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:C,error:v,nextAction:v+` Full build log: ${C.stdout} and ${C.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 m=Hc(c.id),p=no(m),f=Gc(m),x=Ot(c.id),b=` Full log: ${x.stdout} and ${x.stderr}.`,y=f.length>0?`Build failed with missing modules: ${f.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.${b}`:p.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${b}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${b}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:p,missingModules:f,logTail:c.logTail,logPaths:x,nextAction:y}),!0)}let o=Fc(r.projectPath);if(!Ne(Ee(o,"package.json")))return d(`No package.json at ${o}. Run mist_init first.`,!0);if(!Ne(Ee(o,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${o}' } first.`,!0);let s,i,n,a=Ne(Ee(o,"open-next.config.ts"))||Ne(Ee(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 ho({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 Vc,readFileSync as Kc}from"fs";import{join as Jc}from"path";import{z as yo}from"zod";me();var Yc=yo.object({projectPath:yo.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:yo.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:yo.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.")}),qs={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:Yc,handler:async e=>Zc(e)};function Qc(e){let t=Jc(e,"mistflow.json");if(!Vc(t))return null;try{return JSON.parse(Kc(t,"utf-8"))}catch{return null}}async function $s(e){try{let t=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await t.text();return{status:t.status,body:r}}catch(t){return{status:0,body:String(t)}}}async function Xc(e,t,r){try{let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(t),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 Fs(e){try{let t=await e.screenshot({type:"png"});return Buffer.from(t).toString("base64")}catch{return}}async function ft(e,t,r){let o=[],s=i=>{i.type()==="error"&&o.push(i.text())};e.on("console",s);try{let i=await r(),n=await Fs(e);return{name:t,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 Fs(e);return{name:t,status:"fail",detail:`Unexpected error: ${i instanceof Error?i.message:String(i)}`,screenshot:n,consoleErrors:o.length>0?o:void 0}}finally{e.removeListener("console",s)}}async function Zc(e){let t=e.projectPath??process.cwd(),r=Qc(t),o=e.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 $s(`${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."}),bo(o,i);i.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await $s(`${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."}),bo(o,i);i.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,c,h;if(s){let f=await Uo(s);if(f){console.error("[qa] Calling seed endpoint for session token");let x=await Xc(`${o}/api/admin/seed`,{token:f.seedToken,email:f.email,password:"QaTemp1!"});x.status===200&&x.json?(l=x.json.sessionToken,c=x.json.email,x.json.seeded?(h=x.json.password,console.error("[qa] New admin seeded \u2014 login form test available")):console.error("[qa] Admin already exists \u2014 session injection only")):console.error(`[qa] Seed endpoint returned ${x.status}`)}}if(!l)return i.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy process injects ADMIN_SEED_TOKEN into the worker env and stores the seed token on the backend. If the seed endpoint at /api/admin/seed is missing, ensure app/api/admin/seed/route.ts exists in the scaffold."}),bo(o,i);let m,p;try{let{getIsolatedContext:f}=await Promise.resolve().then(()=>(zt(),Ao)),x=await f();m=x.context,p=x.page}catch(f){let x=f instanceof Error?f.message:String(f);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:x,httpChecks:i.map(({screenshot:b,...y})=>y),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(`
|
|
5406
|
+
`)}),!1)}try{let f=await ft(p,"Landing page",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:3e4}),await p.waitForLoadState("networkidle").catch(()=>{});let b=await p.evaluate(()=>{let v=document.body;if(!v)return"";let C=document.createTreeWalker(v,NodeFilter.SHOW_TEXT),_="",P;for(;P=C.nextNode();){let j=P.parentElement;if(j){let L=window.getComputedStyle(j);L.display!=="none"&&L.visibility!=="hidden"&&parseFloat(L.opacity)>0&&(_+=P.textContent?.trim()+" ")}}return _.trim()});if(b.length<50)return{pass:!1,detail:`Landing page appears blank (${b.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let y=p.url();return y.includes("/login")||y.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${b.length} chars)`}});i.push(f);let x=!1;if(h){let b=await ft(p,"Login",async()=>{await p.goto(`${o}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let y=p.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),v=p.locator('input[type="password"], input[name="password"]');try{await y.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 y.first().fill(c),await v.first().fill(h),await p.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await p.waitForURL(_=>!_.pathname.includes("/login"),{timeout:1e4})}catch{let _=await p.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:_?`Login failed: ${_}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified admin account."}}return x=!0,{pass:!0,detail:`Logged in, redirected to ${p.url()}`}});i.push(b)}else i.push({name:"Login",status:"pass",detail:"Skipped form login (redeploy, password unavailable). Using session injection."});if(!x&&l){let b=new URL(o).hostname,y=o.startsWith("https");await m.addCookies([{name:y?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:b,path:"/",httpOnly:!0,secure:y,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let b=await ft(p,"Dashboard",async()=>{p.url().includes("/dashboard")||(await p.goto(`${o}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let _=await p.content();return _.length<1e3?{pass:!1,detail:`Dashboard page is very small (${_.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await p.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled null/undefined or missing database tables."}:{pass:!0,detail:`Loads (${_.length} bytes)`}});i.push(b);let y=await p.evaluate(()=>{let C=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(P=>{let j=P.getAttribute("href");j&&j.startsWith("/")&&!j.startsWith("/api")&&!j.includes("[")&&j!=="/dashboard"&&j!=="/"&&!j.includes("/login")&&!j.includes("/sign")&&C.push(j)}),[...new Set(C)]});if(y.length>0){let C=0,_=[];for(let P of y.slice(0,8)){let j=await ft(p,`Page: ${P}`,async()=>{await p.goto(`${o}${P}`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let L=await p.title(),k=await p.content();return L.toLowerCase().includes("500")||L.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."}:L.toLowerCase().includes("404")||L.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${P} not found. Create the page or remove the nav link.`}:await p.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:k.length<500?{pass:!1,detail:`Page is very small (${k.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});j.status==="fail"&&(C++,_.push(P)),i.push(j)}}let v=await ft(p,"Design quality",async()=>{let C=p.url().includes("/dashboard")?p.url():`${o}/dashboard`;p.url().includes("/dashboard")||(await p.goto(C,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let _=await p.evaluate(()=>{let P=[],j=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),L=new Set;j.forEach(N=>{L.add(window.getComputedStyle(N).fontSize)}),j.length>=3&&L.size<2&&P.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 k=Array.from(j).map(N=>parseInt(N.tagName.charAt(1),10));for(let N=1;N<k.length;N++)if(k[N]-k[N-1]>1){P.push(`TYPOGRAPHY: Heading level skipped (h${k[N-1]} -> h${k[N]}). Use sequential heading levels for accessibility.`);break}let M=document.querySelectorAll("*"),W=!1,G=!1;M.forEach(N=>{let H=window.getComputedStyle(N);H.backgroundColor==="rgb(0, 0, 0)"&&N.clientHeight>100&&N.clientWidth>200&&(W=!0);let ye=H.backgroundColor,K=H.color;if(ye&&!ye.includes("0, 0, 0")&&!ye.includes("255, 255, 255")&&ye!=="rgba(0, 0, 0, 0)"&&ye!=="transparent"&&K.match(/rgb\((\d+), (\d+), (\d+)\)/)){let Te=K.match(/rgb\((\d+), (\d+), (\d+)\)/);if(Te){let[He,We,Ge]=[parseInt(Te[1]),parseInt(Te[2]),parseInt(Te[3])],ge=Math.abs(He-We)<10&&Math.abs(We-Ge)<10&&He>80&&He<180,De=ye.match(/rgb\((\d+), (\d+), (\d+)\)/);if(ge&&De){let[je,Oe,w]=[parseInt(De[1]),parseInt(De[2]),parseInt(De[3])];!(Math.abs(je-Oe)<15&&Math.abs(Oe-w)<15)&&N.textContent&&N.textContent.trim().length>0&&(G=!0)}}}}),W&&P.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)."),G&&P.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 X=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),R=!1;X.forEach(N=>{N.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(R=!0)}),R&&P.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let E=document.querySelectorAll("p, li, span, div"),se=0,pe=0;E.forEach(N=>{N.textContent&&N.textContent.trim().length>20&&N.clientHeight>0&&(pe++,window.getComputedStyle(N).textAlign==="center"&&se++)}),pe>5&&se/pe>.7&&P.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let D=new Set;M.forEach(N=>{let H=window.getComputedStyle(N);H.gap&&H.gap!=="normal"&&H.gap!=="0px"&&D.add(H.gap)}),D.size===1&&M.length>20&&P.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let Z=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(N=>{N.querySelectorAll("tbody tr").length===0&&(N.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||P.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 he=document.querySelectorAll("style"),Ae=!1;he.forEach(N=>{let H=N.textContent||"";(H.includes("bounce")||H.includes("elastic")||H.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Ae=!0)}),Ae&&P.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let ze=document.querySelectorAll("button, a, input, select, [role='button']"),F=0;return ze.forEach(N=>{let H=N.getBoundingClientRect();H.width>0&&H.height>0&&(H.width<32||H.height<32)&&F++}),F>3&&P.push(`ACCESSIBILITY: ${F} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),P});return _.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${_.length} design quality issue(s) found:
|
|
5407
|
+
${_.map((P,j)=>`${j+1}. ${P}`).join(`
|
|
5408
|
+
`)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});if(i.push(v),i.find(C=>C.name==="Landing page"&&C.status==="pass")){let C=await ft(p,"Landing design quality",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let _=await p.evaluate(()=>{let P=[];document.querySelectorAll("*").forEach(M=>{let W=window.getComputedStyle(M);(W.getPropertyValue("-webkit-background-clip")||W.getPropertyValue("background-clip"))==="text"&&M.textContent&&M.textContent.trim().length>0&&P.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let L=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(L){let M=(L.textContent||"").toLowerCase(),W=["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 G of W)if(M.match(new RegExp(G))){P.push(`COPY: Generic hero text detected ('${G}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(M=>{let G=window.getComputedStyle(M).gridTemplateColumns;if(G){let X=G.split(" ").filter(E=>E!=="").length,R=M.children;if(X===3&&R.length===3){let E=Array.from(R).map(D=>D.offsetHeight),se=E.every(D=>Math.abs(D-E[0])<5),pe=Array.from(R).every(D=>{let Z=D.querySelectorAll("svg"),Ce=D.querySelectorAll("h2, h3, h4"),he=D.querySelectorAll("p");return Z.length>=1&&Ce.length>=1&&he.length>=1});se&&pe&&P.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.")}}}),P});return _.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${_.length} landing design issue(s):
|
|
5409
|
+
${_.map((P,j)=>`${j+1}. ${P}`).join(`
|
|
5410
|
+
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(C)}}}finally{m&&await m.close().catch(()=>{})}if(e.deploymentId){let f=i.filter(y=>y.status==="fail"),x=i.filter(y=>y.status==="pass"),b=Date.now();await $o(e.deploymentId,{checks:i.map(({screenshot:y,...v})=>v),overall:f.length===0?"pass":"fail",passed:x.length,failed:f.length,duration_ms:Date.now()-b}).catch(()=>{})}return bo(o,i)}function bo(e,t){let r=t.filter(i=>i.status==="fail"),o=t.filter(i=>i.status==="pass"),s=[];if(r.length===0)s.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${t.length} checks OK. The app is working correctly.`,url:e,checks:t.map(({screenshot:i,...n})=>n)})});else{let i=r.map((n,a)=>`${a+1}. **${n.name}**: ${n.detail}
|
|
5407
5411
|
Fix: ${n.fix}`).join(`
|
|
5408
5412
|
|
|
5409
|
-
`);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:
|
|
5413
|
+
`);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:e,passed:o.length,failed:r.length,checks:t.map(({screenshot:n,...a})=>a),fixInstructions:`The deployed app at ${e} has ${r.length} issue(s):
|
|
5410
5414
|
|
|
5411
5415
|
${i}
|
|
5412
5416
|
|
|
5413
|
-
Fix these issues in the source code, then call mist_deploy with action='deploy'${
|
|
5414
|
-
${s.stderr.slice(-500)}`:""))}let i=0;try{i=
|
|
5417
|
+
Fix these issues in the source code, then call mist_deploy with action='deploy'${e.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let i of t)i.screenshot&&s.push({type:"image",data:i.screenshot,mimeType:"image/png"});return{content:s}}import{z as Ze}from"zod";import{resolve as rd,join as nd}from"path";import{existsSync as sd}from"fs";me();rt();import{existsSync as wo,readdirSync as ed,statSync as Bs,unlinkSync as zs}from"fs";import{join as Xe}from"path";import{execFile as td}from"child_process";function od(e,t){let r=0;for(let o of t){let s=Xe(e,o);if(wo(s))try{let i=Bs(s);if(i.isFile())r++;else if(i.isDirectory()){let n=[s];for(;n.length;){let a=n.pop(),l=ed(a,{withFileTypes:!0});for(let c of l){let h=Xe(a,c.name);c.isDirectory()?n.push(h):r++}}}}catch{}}return r}function Hs(e,t,r){return new Promise(o=>{td("tar",e,{cwd:t,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(s,i,n)=>{o({success:!s,stderr:n?.toString()??""})})})}async function Ws(e){let t=Xe(e,".open-next-build.tar.gz"),r=[".open-next"];wo(Xe(e,"db"))&&r.push("db"),wo(Xe(e,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),wo(Xe(e,"package.json"))&&r.push("package.json");let o=od(e,r),s=await Hs(["-czf",t,"-C",e,...r],e,12e4);if(!s.success){try{zs(t)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(s.stderr?`
|
|
5418
|
+
${s.stderr.slice(-500)}`:""))}let i=0;try{i=Bs(t).size}catch{}return{path:t,sizeBytes:i,fileCount:o}}async function Gs(e){let t=Xe(e,".mistflow-source.tar.gz");return(await Hs(["-czf",t,"-C",e,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],e,12e4)).success?t:null}function Cr(e){if(e)try{zs(e)}catch{}}function Vs(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function Ks(e){switch(e){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: ${e}`}}var id=Ze.object({action:Ze.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:Ze.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:Ze.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:Ze.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:Ze.string().optional().describe("Admin email injected as BETTER_AUTH_ADMIN_EMAIL on first deploy of an auth-enabled project."),waitSeconds:Ze.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.")});function ad(e){return sd(nd(e,".open-next"))}function ld(e){return Le(e)?.deploy?.strategy==="staging"?"preview":null}async function cd(e){let t=rd(e.projectPath);if(!ee())return d("Not signed in. Call mist_setup first.",!0);let o=Le(t)?.projectId;if(!o)return d(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);if(!ad(t))return d(`No .open-next build output at ${t}. Run mist_build first \u2014 the deploy tool ships the build artifact, not the raw source.`,!0);let s=e.environment??ld(t)??"production",i=null,n=null;try{i=await Ws(t),n=await Gs(t);let a=await jo(o,i.path,s,e.adminEmail,void 0,n??void 0,void 0);return d(JSON.stringify({status:"running",jobId:a.deployment_id,deploymentId:a.deployment_id,environment:a.environment??s,buildSize:Vs(i.sizeBytes),buildFileCount:i.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${a.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side, so there's no need to sleep between calls. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(a){let l=a instanceof U||a instanceof Error?a.message:String(a);return d(`Deploy upload failed: ${l}`,!0)}finally{Cr(i?.path),Cr(n)}}async function dd(e,t){let r=t.ctx?Ie(t.ctx.server,t.ctx.progressToken,()=>`Deploy ${e} \u2014 waiting for terminal state`):{stop:()=>{}};try{let o=await Tt(e,{waitSeconds:t.waitSeconds}),s=Ks(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 ${t.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 U||o instanceof Error?o.message:String(o);return d(`Could not fetch deploy status: ${s}`,!0)}finally{r.stop()}}async function pd(e,t){if(!ee())return d("Not signed in. Call mist_setup first.",!0);let o=Le(e)?.projectId;if(!o)return d(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);let s=t;if(!s)try{let n=(await it(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 U?i.message:String(i);return d(`Could not list deployments: ${n}`,!0)}try{let i=await Wo(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 U||i instanceof Error?i.message:String(i);return d(`Promote failed: ${n}`,!0)}}async function ud(e){if(!ee())return d("Not signed in. Call mist_setup first.",!0);try{let t=await Go(e);return d(JSON.stringify({status:"running",jobId:t.deployment_id,deploymentId:t.deployment_id,rollbackFrom:t.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${t.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(t){let r=t instanceof U||t instanceof Error?t.message:String(t);return d(`Rollback failed: ${r}`,!0)}}var Js={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:id,handler:async(e,t)=>{let r=e;switch(r.action??"deploy"){case"deploy":return r.projectPath?cd({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail}):d("projectPath is required for action='deploy'.",!0);case"status":return r.deploymentId?dd(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:t}):d("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?pd(r.projectPath,r.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?ud(r.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}};var vo=new md({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:jr()}),Ys=[on,bn,wn,kn,qn,Jn,_n,vs,En,Ss,Os,Us,qs,Js];vo.setRequestHandler(fd,async()=>({tools:Ys.map(e=>({name:e.name,description:e.description,inputSchema:yd(e.inputSchema)}))}));vo.setRequestHandler(gd,async e=>{let t=Ys.find(r=>r.name===e.params.name);if(!t)return d(`Unknown tool: ${e.params.name}`,!0);try{let r=t.inputSchema.safeParse(e.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=e.params._meta?.progressToken,s={server:vo,progressToken:o};try{return await t.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 bd(){let e=process.argv.indexOf("--api-url");e!==-1&&process.argv[e+1]&&(process.env.MISTFLOW_API_URL=process.argv[e+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let t=new hd;await vo.connect(t),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}bd().catch(e=>{console.error("Fatal error:",e),process.exit(1)});
|