@mistflow-ai/mcp 1.5.0 → 1.5.1
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 +73 -73
- package/dist/index.js +37 -37
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -19,9 +19,9 @@ This is a major update. Run \`${n}\` and restart your editor.${i}
|
|
|
19
19
|
--- Mistflow update available: ${e} -> ${r.latest} ---
|
|
20
20
|
Run \`${n}\` to upgrade, then restart your editor.${i}`:`
|
|
21
21
|
|
|
22
|
-
(Mistflow ${r.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function pr(){let t=Le(),e=Me??{latest:"",minSupported:"",changelogUrl:""},r=Ps(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:Me!==null}}var vn,Me,Ts,Jt=Pt(()=>{"use strict";vn=null;Me=null;Ts=!1});var Xt={};wn(Xt,{closeBrowser:()=>mr,getIsolatedContext:()=>Aa,getPage:()=>ur,getSnapshot:()=>Yt,takeScreenshot:()=>Qt});async function Rs(){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 Ca(){let t=await Rs();return(!Ue||!Ue.isConnected())&&(Ue=await t.chromium.launch({headless:!0})),nt&&(await nt.close().catch(()=>{}),nt=null),nt=await Ue.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Ge=await nt.newPage(),Ge}async function ur(){return Ge&&!Ge.isClosed()?Ge:(xn||(xn=Ca().finally(()=>{xn=null})),xn)}async function mr(){Ge&&!Ge.isClosed()&&await Ge.close().catch(()=>{}),nt&&await nt.close().catch(()=>{}),Ue?.isConnected()&&await Ue.close().catch(()=>{}),Ge=null,nt=null,Ue=null}async function Aa(){let t=await Rs();(!Ue||!Ue.isConnected())&&(Ue=await t.chromium.launch({headless:!0}));let e=await Ue.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function Yt(t){return await t.locator("body").ariaSnapshot()}async function Qt(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var Ue,nt,Ge,xn,Ct=Pt(()=>{"use strict";Ue=null,nt=null,Ge=null,xn=null;process.once("SIGTERM",()=>{mr().finally(()=>process.exit(0))});process.once("SIGINT",()=>{mr().finally(()=>process.exit(0))})});import{readFileSync as hr,existsSync as Sn,writeFileSync as Ns,mkdirSync as Na,renameSync as Oa,unlinkSync as
|
|
23
|
-
`,{mode:384}),Oa(o,e)}catch(s){try{
|
|
24
|
-
`,"utf-8")}catch{}}var Ua,yt=Pt(()=>{"use strict";Ua="https://api.mistflow.ai"});var Bs={};wn(Bs,{MistflowApiError:()=>W,addDomain:()=>kr,bindWorkspace:()=>tn,cancelSession:()=>$r,checkAuth:()=>za,checkAuthDetailed:()=>$s,checkSubdomain:()=>Pn,checkToolGuard:()=>Fr,createDeployment:()=>Wa,createProject:()=>wt,deleteEnvVar:()=>Ir,discoverDecisions:()=>Va,downloadImageryAsset:()=>wr,downloadSource:()=>Ya,downloadSourceWithToken:()=>Fs,fetchAcceptanceCriteria:()=>en,fetchActiveSessionPlan:()=>el,fetchDesignDirections:()=>Cn,fetchDesignPick:()=>Ga,fetchDesignRenders:()=>Rn,fetchDoc:()=>jr,fetchDocsList:()=>Or,fetchModule:()=>Dr,fetchPlanConversation:()=>En,fetchProjectImagery:()=>br,fetchScaffold:()=>Er,fetchSessionNext:()=>Nt,fetchSessionPlanRevisions:()=>qs,fetchStepContext:()=>Nr,forkTemplate:()=>Lr,generatePlan:()=>Nn,getAuthHeaders:()=>bt,getBaseUrl:()=>Te,getDashboardUrl:()=>Fa,getDbCredentials:()=>Ka,getDeployLogs:()=>Pr,getDeploymentStatus:()=>st,getProject:()=>Ha,getProjectErrors:()=>Cr,getSeedInfo:()=>Dn,getSession:()=>Mn,getSiteUrl:()=>$a,getTemplate:()=>Mr,hasCredentialsOnDisk:()=>ke,hasLocalCredentials:()=>Us,listDeployments:()=>Rt,listDomains:()=>ot,listEnvVars:()=>Tr,listSessionsForMachine:()=>nn,markLocalSetupDone:()=>Qa,modifyPlan:()=>On,pingBackend:()=>yr,promotePreview:()=>Ar,redeployProject:()=>Ja,removeDomain:()=>xr,rollbackDeployment:()=>Rr,shareProject:()=>Ur,startSession:()=>Xa,submitAcceptanceResults:()=>qr,submitDesignPick:()=>An,submitSessionAnswers:()=>Za,uploadAndDeploy:()=>vr,uploadQAResults:()=>Sr,upsertEnvVar:()=>_r,verifyDomain:()=>jn});function Te(){return _n()}function $a(){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 Fa(){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 bt(){let t=ft();if(!t.ok)throw new W("auth_missing","No Mistflow credentials found.",401);return qa(t.creds)}function qa(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":Le()}}function At(t){try{Kt(t.headers)}catch{}}async function yr(){try{let t=await fetch(`${Te()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});At(t)}catch{}}async function Ls(t,e,r,n){for(let i=0;i<2;i++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(o){let s=o instanceof Error&&o.name==="TimeoutError",a=o instanceof TypeError;if(n&&i===0&&(s||a)){console.error(`[api] Retrying ${t} after ${s?"timeout":"network error"}`);continue}throw o}throw new Error("fetchWithRetry: exhausted retries")}async function Zt(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new W(r,n,t.status,e?.details);let i=t.status;return i===401?new W("auth_invalid",n,i):i===403?new W("permission_denied",n,i):i===404?new W("not_found",n,i):i===409?new W("conflict",n,i):i===422?new W("validation_error",n,i):i===429?new W("rate_limited",n,i):i>=500?new W("server_error",t.statusText||"Internal server error",i):new W("client_error",n,i)}async function L(t,e={}){let r=bt(),{timeoutMs:n,idempotent:i,...o}=e,s=n??3e4,a=(o.method??"GET").toUpperCase(),l=i??(a==="GET"||a==="HEAD"),c;try{c=await Ls(`${Te()}${t}`,{...o,headers:{...r,...o.headers}},s,l)}catch(u){throw u instanceof Error&&u.name==="TimeoutError"?new W("network_error","Request timed out. Try again in a moment."):new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(At(c),!c.ok)throw await Zt(c);return c.json()}function Us(){return ft().ok}async function za(){return(await $s()).ok}async function $s(){if(In!==null&&Date.now()<Ms)return In?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Us())return{ok:!1,reason:"no_credentials"};try{return await L("/api/org"),In=!0,Ms=Date.now()+Ba,{ok:!0}}catch(t){if(In=null,!(t instanceof W))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function Ha(t){return L(`/api/projects/${encodeURIComponent(t)}`)}async function Pn(t){return L(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function wt(t,e={}){return L("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e.template,db_provider:e.dbProvider??"neon",requested_subdomain:e.requestedSubdomain,picked_direction:e.pickedDirection,imagery_brief:e.imageryBrief,plan_context:e.planContext,design_conversation_id:e.designConversationId,session_id:e.sessionId})})}async function br(t){return L(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function wr(t){let e=await fetch(t);if(!e.ok)throw new Error(`Failed to download imagery asset: HTTP ${e.status} ${e.statusText}`);let r=await e.arrayBuffer();return Buffer.from(r)}async function Wa(t,e){return L("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function vr(t,e,r="production",n,i,o,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=ft();if(!c.ok)throw new W("auth_missing","No Mistflow credentials found.",401);let u=c.creds,h=a(e),d=new Blob([h],{type:"application/gzip"}),v=new FormData;if(v.append("project_id",t),v.append("build",d,l(e)),r!=="production"&&v.append("environment",r),n&&v.append("admin_email",n),i&&v.append("schema_pushed","true"),o){let{existsSync:k}=await import("fs");if(k(o)){let y=a(o),C=new Blob([y],{type:"application/gzip"});v.append("source",C,"source.tar.gz")}}s&&v.append("git_commit_sha",s);let H;try{H=await fetch(`${Te()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${u.apiKey}`,"X-Mistflow-MCP-Version":Le()},body:v,signal:AbortSignal.timeout(3e5)})}catch{throw new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(At(H),!H.ok)throw await Zt(H);let _=await H.json();return{..._,id:_.deployment_id}}async function st(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return L(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:i}:void 0)}async function Cn(t){return L(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Ga(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return L(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:i})}async function An(t,e){return L(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json"},timeoutMs:6e4})}async function Rn(t){try{return await L(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function En(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return L(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:i})}async function Nn(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};if(e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&e?.designDirection){let i=e.designDirection,o=256,s=4e3,a=typeof i.id=="string"?i.id:void 0,l=typeof i.custom=="string"?i.custom:void 0,c=a&&a.length>0&&a.length<=o?a:void 0,u=(()=>{if(l&&l.length>0)return l.length<=s?l:l.slice(0,s)+" (truncated)";if(!c){let v=JSON.stringify(i);return v.length<=s?v:v.slice(0,s)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${o}; falling back to custom`);let h=c?{direction_id:c}:{custom:u};e.conversationId&&(h.conversation_id=e.conversationId);let d=await An(e.designConversationId,h);return{status:"ready",plan:d.plan??{},methodology:d.methodology??"",...d.designMd?{designMd:d.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return L("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function On(t,e,r={}){return L("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function Va(t){return L("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function kr(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function ot(t){return L(`/api/projects/${encodeURIComponent(t)}/domains`)}async function jn(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function xr(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ka(t){return L(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Dn(t){try{return await L(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof W&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Sr(t,e){try{return await L(`/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 Tr(t){return L(`/api/projects/${encodeURIComponent(t)}/env`)}async function _r(t,e,r,n){return L(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:r,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function Ir(t,e){return L(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Pr(t){return L(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Cr(t,e="7d"){return L(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Rt(t){return L(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function Ja(t){return L(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Ar(t,e){let r=new URLSearchParams({preview_deployment_id:e});return L(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Rr(t){return L(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function Ya(t,e){let r=ft();if(!r.ok)throw new W("auth_missing","Not authenticated.",401);let n=r.creds,i=await fetch(`${Te()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":Le()},signal:AbortSignal.timeout(12e4)});if(At(i),!i.ok)throw await Zt(i);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await i.arrayBuffer());o(e,s)}async function Et(t,e){let{timeoutMs:r,idempotent:n,...i}=e??{},o=r??3e4,s=(i.method??"GET").toUpperCase(),a=n??(s==="GET"||s==="HEAD"),l;try{l=await Ls(`${Te()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":Le()},...i},o,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new W("network_error","Request timed out. Try again in a moment."):new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(At(l),!l.ok)throw await Zt(l);return l.json()}async function Er(t="nextjs"){return Et(`/api/scaffold/${encodeURIComponent(t)}`)}async function Nr(t,e){return Et(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Or(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return Et(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function jr(t,e){return Et(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function Dr(t,e,r,n){return Et(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:r,entity_plural:n})})}async function Mr(t){return Et(`/api/templates/${encodeURIComponent(t)}`)}async function Lr(t){return L(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Fs(t,e,r){let n;try{n=await fetch(`${Te()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":Le()},signal:AbortSignal.timeout(12e4)})}catch{throw new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(At(n),!n.ok)throw n.status===401?new W("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await Zt(n);let{writeFileSync:i}=await import("fs"),o=Buffer.from(await n.arrayBuffer());i(r,o)}async function Qa(t){await L(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Ur(t,e){return L(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function Xa(t){return L("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function Mn(t){return L(`/api/sessions/${t}`)}async function $r(t,e){return L(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Nt(t){return L(`/api/sessions/${t}/next`)}async function Za(t,e){return L(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Fr(t,e){return L(`/api/sessions/${t}/can/${e}`)}async function en(t){return L(`/api/sessions/${t}/acceptance`)}async function qs(t){return L(`/api/sessions/${t}/revisions`)}async function el(t){let e=await qs(t),r=[...e].reverse().find(n=>n.status==="active")??e.at(-1);return!r||!r.body||typeof r.body!="object"||Array.isArray(r.body)?null:{plan:r.body,planRevisionId:r.id}}async function tn(t,e){return L(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function nn(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return L(`/api/sessions/me/workspaces?${n}`)}async function qr(t,e,r){return L(`/api/sessions/${t}/acceptance/results`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({results:e,plan_revision_id:r??null}),idempotent:!1})}var W,In,Ms,Ba,Se=Pt(()=>{"use strict";yt();Jt();W=class extends Error{constructor(r,n,i,o){super(n);this.code=r;this.statusCode=i;this.details=o;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"}};In=null,Ms=0,Ba=300*1e3});var on={};wn(on,{emptyState:()=>sn,fetchRemoteState:()=>ml,fuzzyMatch:()=>gl,getLocalStatePath:()=>zr,readLocalState:()=>ul,syncRemoteState:()=>hl,writeLocalState:()=>rn});import{existsSync as Ks,readFileSync as cl,writeFileSync as dl,mkdirSync as pl}from"fs";import{join as Js}from"path";function zr(t){return Js(t,".mistflow","state.json")}function ul(t){let e=zr(t);if(!Ks(e))return null;try{return JSON.parse(cl(e,"utf-8"))}catch{return null}}function rn(t,e){let r=Js(t,".mistflow");Ks(r)||pl(r,{recursive:!0}),dl(zr(t),JSON.stringify(e,null,2)+`
|
|
22
|
+
(Mistflow ${r.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function pr(){let t=Le(),e=Me??{latest:"",minSupported:"",changelogUrl:""},r=Ps(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:Me!==null}}var vn,Me,Ts,Jt=Pt(()=>{"use strict";vn=null;Me=null;Ts=!1});var Xt={};wn(Xt,{closeBrowser:()=>mr,getIsolatedContext:()=>Aa,getPage:()=>ur,getSnapshot:()=>Yt,takeScreenshot:()=>Qt});async function Rs(){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 Ca(){let t=await Rs();return(!Ue||!Ue.isConnected())&&(Ue=await t.chromium.launch({headless:!0})),nt&&(await nt.close().catch(()=>{}),nt=null),nt=await Ue.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Ge=await nt.newPage(),Ge}async function ur(){return Ge&&!Ge.isClosed()?Ge:(xn||(xn=Ca().finally(()=>{xn=null})),xn)}async function mr(){Ge&&!Ge.isClosed()&&await Ge.close().catch(()=>{}),nt&&await nt.close().catch(()=>{}),Ue?.isConnected()&&await Ue.close().catch(()=>{}),Ge=null,nt=null,Ue=null}async function Aa(){let t=await Rs();(!Ue||!Ue.isConnected())&&(Ue=await t.chromium.launch({headless:!0}));let e=await Ue.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function Yt(t){return await t.locator("body").ariaSnapshot()}async function Qt(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var Ue,nt,Ge,xn,Ct=Pt(()=>{"use strict";Ue=null,nt=null,Ge=null,xn=null;process.once("SIGTERM",()=>{mr().finally(()=>process.exit(0))});process.once("SIGINT",()=>{mr().finally(()=>process.exit(0))})});import{readFileSync as hr,existsSync as Sn,writeFileSync as Ns,mkdirSync as Na,renameSync as Oa,unlinkSync as Da}from"fs";import{join as Tn,dirname as ja}from"path";import{homedir as Ma}from"os";import{randomBytes as La}from"crypto";function Os(){return Tn(Ma(),".mistflow","credentials.json")}function _n(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function Ds(){let t=Os();if(!Sn(t))return null;try{let e=JSON.parse(hr(t,"utf-8"));return typeof e.apiKey=="string"?{[Ua]:e}:e}catch{return null}}function ft(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=Ds();if(!e)return{ok:!1,reason:"missing"};let r=_n(),n=e[r];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function gr(t){let e=Os(),r=ja(e);Sn(r)||Na(r,{recursive:!0});let n=Ds()??{},i=_n();n[i]=t;let o=Tn(r,`.credentials.tmp.${La(8).toString("hex")}`);try{Ns(o,JSON.stringify(n,null,2)+`
|
|
23
|
+
`,{mode:384}),Oa(o,e)}catch(s){try{Da(o)}catch{}throw s}}function js(){let t=ft();return t.ok?t.creds:null}function ke(){return ft().ok}function rt(t){let e=Tn(t,"mistflow.json");if(!Sn(e))return null;try{return JSON.parse(hr(e,"utf-8"))}catch{return null}}function fr(t,e){let r=Tn(t,"mistflow.json");if(Sn(r))try{let i={...JSON.parse(hr(r,"utf-8")),...e};Ns(r,JSON.stringify(i,null,2)+`
|
|
24
|
+
`,"utf-8")}catch{}}var Ua,yt=Pt(()=>{"use strict";Ua="https://api.mistflow.ai"});var Bs={};wn(Bs,{MistflowApiError:()=>W,addDomain:()=>kr,bindWorkspace:()=>tn,cancelSession:()=>$r,checkAuth:()=>za,checkAuthDetailed:()=>$s,checkSubdomain:()=>Pn,checkToolGuard:()=>Fr,createDeployment:()=>Wa,createProject:()=>wt,deleteEnvVar:()=>Ir,discoverDecisions:()=>Va,downloadImageryAsset:()=>wr,downloadSource:()=>Ya,downloadSourceWithToken:()=>Fs,fetchAcceptanceCriteria:()=>en,fetchActiveSessionPlan:()=>el,fetchDesignDirections:()=>Cn,fetchDesignPick:()=>Ga,fetchDesignRenders:()=>Rn,fetchDoc:()=>Dr,fetchDocsList:()=>Or,fetchModule:()=>jr,fetchPlanConversation:()=>En,fetchProjectImagery:()=>br,fetchScaffold:()=>Er,fetchSessionNext:()=>Nt,fetchSessionPlanRevisions:()=>qs,fetchStepContext:()=>Nr,forkTemplate:()=>Lr,generatePlan:()=>Nn,getAuthHeaders:()=>bt,getBaseUrl:()=>Te,getDashboardUrl:()=>Fa,getDbCredentials:()=>Ka,getDeployLogs:()=>Pr,getDeploymentStatus:()=>st,getProject:()=>Ha,getProjectErrors:()=>Cr,getSeedInfo:()=>jn,getSession:()=>Mn,getSiteUrl:()=>$a,getTemplate:()=>Mr,hasCredentialsOnDisk:()=>ke,hasLocalCredentials:()=>Us,listDeployments:()=>Rt,listDomains:()=>ot,listEnvVars:()=>Tr,listSessionsForMachine:()=>nn,markLocalSetupDone:()=>Qa,modifyPlan:()=>On,pingBackend:()=>yr,promotePreview:()=>Ar,redeployProject:()=>Ja,removeDomain:()=>xr,rollbackDeployment:()=>Rr,shareProject:()=>Ur,startSession:()=>Xa,submitAcceptanceResults:()=>qr,submitDesignPick:()=>An,submitSessionAnswers:()=>Za,uploadAndDeploy:()=>vr,uploadQAResults:()=>Sr,upsertEnvVar:()=>_r,verifyDomain:()=>Dn});function Te(){return _n()}function $a(){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 Fa(){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 bt(){let t=ft();if(!t.ok)throw new W("auth_missing","No Mistflow credentials found.",401);return qa(t.creds)}function qa(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":Le()}}function At(t){try{Kt(t.headers)}catch{}}async function yr(){try{let t=await fetch(`${Te()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});At(t)}catch{}}async function Ls(t,e,r,n){for(let i=0;i<2;i++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(o){let s=o instanceof Error&&o.name==="TimeoutError",a=o instanceof TypeError;if(n&&i===0&&(s||a)){console.error(`[api] Retrying ${t} after ${s?"timeout":"network error"}`);continue}throw o}throw new Error("fetchWithRetry: exhausted retries")}async function Zt(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new W(r,n,t.status,e?.details);let i=t.status;return i===401?new W("auth_invalid",n,i):i===403?new W("permission_denied",n,i):i===404?new W("not_found",n,i):i===409?new W("conflict",n,i):i===422?new W("validation_error",n,i):i===429?new W("rate_limited",n,i):i>=500?new W("server_error",t.statusText||"Internal server error",i):new W("client_error",n,i)}async function L(t,e={}){let r=bt(),{timeoutMs:n,idempotent:i,...o}=e,s=n??3e4,a=(o.method??"GET").toUpperCase(),l=i??(a==="GET"||a==="HEAD"),c;try{c=await Ls(`${Te()}${t}`,{...o,headers:{...r,...o.headers}},s,l)}catch(u){throw u instanceof Error&&u.name==="TimeoutError"?new W("network_error","Request timed out. Try again in a moment."):new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(At(c),!c.ok)throw await Zt(c);return c.json()}function Us(){return ft().ok}async function za(){return(await $s()).ok}async function $s(){if(In!==null&&Date.now()<Ms)return In?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Us())return{ok:!1,reason:"no_credentials"};try{return await L("/api/org"),In=!0,Ms=Date.now()+Ba,{ok:!0}}catch(t){if(In=null,!(t instanceof W))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function Ha(t){return L(`/api/projects/${encodeURIComponent(t)}`)}async function Pn(t){return L(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function wt(t,e={}){return L("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e.template,db_provider:e.dbProvider??"neon",requested_subdomain:e.requestedSubdomain,picked_direction:e.pickedDirection,imagery_brief:e.imageryBrief,plan_context:e.planContext,design_conversation_id:e.designConversationId,session_id:e.sessionId})})}async function br(t){return L(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function wr(t){let e=await fetch(t);if(!e.ok)throw new Error(`Failed to download imagery asset: HTTP ${e.status} ${e.statusText}`);let r=await e.arrayBuffer();return Buffer.from(r)}async function Wa(t,e){return L("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function vr(t,e,r="production",n,i,o,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=ft();if(!c.ok)throw new W("auth_missing","No Mistflow credentials found.",401);let u=c.creds,h=a(e),d=new Blob([h],{type:"application/gzip"}),v=new FormData;if(v.append("project_id",t),v.append("build",d,l(e)),r!=="production"&&v.append("environment",r),n&&v.append("admin_email",n),i&&v.append("schema_pushed","true"),o){let{existsSync:k}=await import("fs");if(k(o)){let y=a(o),C=new Blob([y],{type:"application/gzip"});v.append("source",C,"source.tar.gz")}}s&&v.append("git_commit_sha",s);let H;try{H=await fetch(`${Te()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${u.apiKey}`,"X-Mistflow-MCP-Version":Le()},body:v,signal:AbortSignal.timeout(3e5)})}catch{throw new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(At(H),!H.ok)throw await Zt(H);let _=await H.json();return{..._,id:_.deployment_id}}async function st(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return L(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:i}:void 0)}async function Cn(t){return L(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Ga(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return L(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:i})}async function An(t,e){return L(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),timeoutMs:6e4})}async function Rn(t){try{return await L(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function En(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return L(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:i})}async function Nn(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};if(e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&e?.designDirection){let i=e.designDirection,o=256,s=4e3,a=typeof i.id=="string"?i.id:void 0,l=typeof i.custom=="string"?i.custom:void 0,c=a&&a.length>0&&a.length<=o?a:void 0,u=(()=>{if(l&&l.length>0)return l.length<=s?l:l.slice(0,s)+" (truncated)";if(!c){let v=JSON.stringify(i);return v.length<=s?v:v.slice(0,s)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${o}; falling back to custom`);let h=c?{direction_id:c}:{custom:u};e.conversationId&&(h.conversation_id=e.conversationId);let d=await An(e.designConversationId,h);return{status:"ready",plan:d.plan??{},methodology:d.methodology??"",...d.designMd?{designMd:d.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return L("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function On(t,e,r={}){return L("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function Va(t){return L("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function kr(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function ot(t){return L(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Dn(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function xr(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ka(t){return L(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function jn(t){try{return await L(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof W&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Sr(t,e){try{return await L(`/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 Tr(t){return L(`/api/projects/${encodeURIComponent(t)}/env`)}async function _r(t,e,r,n){return L(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:r,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function Ir(t,e){return L(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Pr(t){return L(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Cr(t,e="7d"){return L(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Rt(t){return L(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function Ja(t){return L(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Ar(t,e){let r=new URLSearchParams({preview_deployment_id:e});return L(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Rr(t){return L(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function Ya(t,e){let r=ft();if(!r.ok)throw new W("auth_missing","Not authenticated.",401);let n=r.creds,i=await fetch(`${Te()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":Le()},signal:AbortSignal.timeout(12e4)});if(At(i),!i.ok)throw await Zt(i);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await i.arrayBuffer());o(e,s)}async function Et(t,e){let{timeoutMs:r,idempotent:n,...i}=e??{},o=r??3e4,s=(i.method??"GET").toUpperCase(),a=n??(s==="GET"||s==="HEAD"),l;try{l=await Ls(`${Te()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":Le()},...i},o,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new W("network_error","Request timed out. Try again in a moment."):new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(At(l),!l.ok)throw await Zt(l);return l.json()}async function Er(t="nextjs"){return Et(`/api/scaffold/${encodeURIComponent(t)}`)}async function Nr(t,e){return Et(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Or(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return Et(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function Dr(t,e){return Et(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function jr(t,e,r,n){return Et(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:r,entity_plural:n})})}async function Mr(t){return Et(`/api/templates/${encodeURIComponent(t)}`)}async function Lr(t){return L(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Fs(t,e,r){let n;try{n=await fetch(`${Te()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":Le()},signal:AbortSignal.timeout(12e4)})}catch{throw new W("network_error","Cannot reach Mistflow servers. Check your network.")}if(At(n),!n.ok)throw n.status===401?new W("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await Zt(n);let{writeFileSync:i}=await import("fs"),o=Buffer.from(await n.arrayBuffer());i(r,o)}async function Qa(t){await L(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Ur(t,e){return L(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function Xa(t){return L("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function Mn(t){return L(`/api/sessions/${t}`)}async function $r(t,e){return L(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Nt(t){return L(`/api/sessions/${t}/next`)}async function Za(t,e){return L(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Fr(t,e){return L(`/api/sessions/${t}/can/${e}`)}async function en(t){return L(`/api/sessions/${t}/acceptance`)}async function qs(t){return L(`/api/sessions/${t}/revisions`)}async function el(t){let e=await qs(t),r=[...e].reverse().find(n=>n.status==="active")??e.at(-1);return!r||!r.body||typeof r.body!="object"||Array.isArray(r.body)?null:{plan:r.body,planRevisionId:r.id}}async function tn(t,e){return L(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function nn(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return L(`/api/sessions/me/workspaces?${n}`)}async function qr(t,e,r){return L(`/api/sessions/${t}/acceptance/results`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({results:e,plan_revision_id:r??null}),idempotent:!1})}var W,In,Ms,Ba,Se=Pt(()=>{"use strict";yt();Jt();W=class extends Error{constructor(r,n,i,o){super(n);this.code=r;this.statusCode=i;this.details=o;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"}};In=null,Ms=0,Ba=300*1e3});var on={};wn(on,{emptyState:()=>sn,fetchRemoteState:()=>ml,fuzzyMatch:()=>gl,getLocalStatePath:()=>zr,readLocalState:()=>ul,syncRemoteState:()=>hl,writeLocalState:()=>rn});import{existsSync as Ks,readFileSync as cl,writeFileSync as dl,mkdirSync as pl}from"fs";import{join as Js}from"path";function zr(t){return Js(t,".mistflow","state.json")}function ul(t){let e=zr(t);if(!Ks(e))return null;try{return JSON.parse(cl(e,"utf-8"))}catch{return null}}function rn(t,e){let r=Js(t,".mistflow");Ks(r)||pl(r,{recursive:!0}),dl(zr(t),JSON.stringify(e,null,2)+`
|
|
25
25
|
`)}function sn(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function ml(t){let e;try{e=bt()}catch{return null}try{let r=await fetch(`${Te()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":Le()}});try{Kt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function hl(t,e){let r;try{r=bt()}catch{return!1}try{let n=await fetch(`${Te()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":Le()},body:JSON.stringify(e)});try{Kt(n.headers)}catch{}return n.ok}catch{return!1}}function gl(t,e){let r=t.toLowerCase(),n=e.toLowerCase();return n.includes(r)||r.includes(n)?!0:r.split(/\s+/).some(o=>o.length>=3&&n.includes(o))}var vt=Pt(()=>{"use strict";Se();Jt()});var Hr={};wn(Hr,{ensureBackendRegistered:()=>xl,ensureShadcnComponents:()=>Sl});import{existsSync as Qs,readFileSync as fl,writeFileSync as yl}from"fs";import{join as Ln}from"path";import{spawn as bl}from"child_process";function wl(t,e,r,n,i){return new Promise(o=>{let s=bl(t,e,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:n,...i?{env:{...process.env,...i}}:{}}),a="",l="";s.stdout?.on("data",c=>{a+=c.toString()}),s.stderr?.on("data",c=>{l+=c.toString()}),s.on("close",c=>o({success:c===0,stdout:a,stderr:l})),s.on("error",c=>o({success:!1,stdout:a,stderr:l+c.message}))})}function vl(t){let e=Ln(t,"mistflow.json");if(!Qs(e))return null;try{return JSON.parse(fl(e,"utf-8"))}catch{return null}}function kl(t,e){yl(Ln(t,"mistflow.json"),JSON.stringify(e,null,2))}async function Ys(t,e){try{let r=e.features,n=e.steps,i={plan:e};Array.isArray(r)&&r.length>0&&(i.features=r.map(o=>o.name)),Array.isArray(n)&&n.length>0&&(i.provenance=n.map(o=>({feature:o.name??o.title??`Step ${o.number??"?"}`,user_intent:(o.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${Te()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...bt(),"Content-Type":"application/json"},body:JSON.stringify(i)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function xl(t,e={}){let r=vl(t);if(r){if(!ke())return r.projectId;if(!r.projectId)try{let i=r.plan?.requestedSubdomain,o=await wt(r.name,{dbProvider:r.dbProvider??"neon",requestedSubdomain:i});return r.projectId=o.id,kl(t,r),rn(t,sn(o.id,r.name)),r.plan&&await Ys(o.id,r.plan),console.error(`[self-heal] registered project ${o.id.slice(0,8)} with backend`),o.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&r.plan&&r.projectId&&await Ys(r.projectId,r.plan),r.projectId}}async function Sl(t,e){let r=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],n=e&&e.length>0?e:r,i=Ln(t,"components","ui"),o=[],s=[];for(let c of n)Qs(Ln(i,`${c}.tsx`))?o.push(c):s.push(c);if(s.length===0)return{installed:[],alreadyPresent:o};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await wl("npx",["--yes","shadcn@latest","add","-y","-o",...s],t,18e4,a);return l.success?{installed:s,alreadyPresent:o}:{installed:[],alreadyPresent:o,failed:`shadcn add failed for: ${s.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Wr=Pt(()=>{"use strict";Se();vt()});import{Server as fu}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as yu}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as bu,ListToolsRequestSchema as wu}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as vu}from"zod-to-json-schema";var ua="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.",ma='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"`.',ha="When submitting discovery answers back to `mist_plan` (conversationId + answers), pass `answers` as an ARRAY of objects directly: `answers: [{question, decisionKey, answer}, ...]`. Do NOT JSON-stringify the array \u2014 pass the raw array literal. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",ga="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.",fa='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.',ya="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.",ba="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.",wa='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.',va="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.",gs="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).",fs="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'integrations' browses the curated integration blueprint catalog (pass integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",ys="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.",bs="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.",ws="Fetch a per-topic Mistflow methodology doc on demand. Two actions: `list` returns the catalog (id, title, kind, description) so you can discover what's available; `get` returns the full markdown for one topic. Topic kinds: 'stack' (framework patterns \u2014 Drizzle, Better Auth, server actions, components, styling), 'skill' (design + structural patterns \u2014 auth-design, app-design, admin-panel, blob-storage), 'integration' (third-party services \u2014 Stripe, Resend, OpenAI, Anthropic, Twilio, etc.). Call BEFORE writing or modifying code that touches an integration or a stack-specific pattern. Lazy-loaded \u2014 pulls only the topic you need instead of paying for the full AGENTS.md monolith every turn. Same content as AGENTS.md / .claude/skills/<topic>/SKILL.md / .cursor/rules/<topic>.mdc on disk; use this tool when those aren't auto-discovered by your host.",vs="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).",ks="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 xs(){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(wa),t.push(""),t.push(ua),t.push(""),t.push(ma),t.push(""),t.push(ha),t.push(""),t.push(ga),t.push(""),t.push(va),t.push(""),t.push(ya),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(fa),t.push(""),t.push(ba),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(`
|
|
26
26
|
`)}Jt();function p(t,e=!1){let r=t;try{let n=As();n&&(r=t+n)}catch{}return{content:[{type:"text",text:r}],isError:e}}function Ae(t){let e={status:"setup_required",reason:"no_credentials",intent:t,instruction:`You must sign in to Mistflow before you can ${t}. Call mist_setup({}) \u2014 it walks the user through device-code authentication (typically <60s). Only retry the original call AFTER mist_setup has fully completed sign-in (status field is no longer "pending").`,nextAction:`Step 1: Call mist_setup({}) now. Do not ask the user for permission first \u2014 sign-in is a precondition for this flow, not a decision point. Step 2: mist_setup returns immediately with a signInUrl + userCode. Show the URL and code to the user and wait for them to approve in their browser. Step 3: If the response had status: "pending", call mist_setup again with the returned deviceCode every ~15s until it returns a non-pending status. Step 4: Only then retry the call that produced this response with the same arguments. Do NOT retry while mist_setup is still pending \u2014 the credentials aren't on disk yet and you'll loop right back into this same response.`};return p(JSON.stringify(e),!0)}function Ve(t){return p(`This is not a Mistflow project (no mistflow.json found at ${t}).
|
|
27
27
|
|
|
@@ -1587,7 +1587,7 @@ export async function searchDocumentsHybrid(query: string, limit = 10) {
|
|
|
1587
1587
|
3. **Do not regenerate embeddings on every render.** Generate on create/update or in an explicit reindex action.
|
|
1588
1588
|
4. **Chunk long content.** Store chunks of 500-1,000 tokens with stable \`sourceType\`, \`sourceId\`, and \`chunkIndex\`.
|
|
1589
1589
|
5. **Use hybrid search for user-facing search.** Vector search handles meaning; full-text search protects exact names, codes, and phrases.
|
|
1590
|
-
6. **Never ask the user to paste OPENAI_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}];function Cl(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function
|
|
1590
|
+
6. **Never ask the user to paste OPENAI_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}];function Cl(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Dt(t){let e=Ot.find(n=>n.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Ot.find(n=>{let i=n.name.toLowerCase().replace(/[^a-z0-9]/g,"");return i===r||i.includes(r)||r.includes(i)})}function jt(t){return Gr[t]}function Vr(t){return t?Ot.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Ot}function to(t){let e=t??Ot,r={};for(let i of e){r[i.category]||(r[i.category]=[]);let o=Gr[i.id],s=o?` \u2014 ${o.description}`:"",a=o?.packages.length?` (${o.packages.join(", ")})`:"";r[i.category].push(`${i.id} \u2014 "${i.name}"${s}${a}`)}let n=[];for(let[i,o]of Object.entries(r))n.push(`**${i}**:
|
|
1591
1591
|
${o.map(s=>` - ${s}`).join(`
|
|
1592
1592
|
`)}`);return n.join(`
|
|
1593
1593
|
|
|
@@ -1596,7 +1596,7 @@ ${o.map(s=>` - ${s}`).join(`
|
|
|
1596
1596
|
Anyone can fork it: ${a.share_url}
|
|
1597
1597
|
|
|
1598
1598
|
Others can use it in their AI editor:
|
|
1599
|
-
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return p(l,!0)}}case"integrations":{if(e.integrationId){let s=
|
|
1599
|
+
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return p(l,!0)}}case"integrations":{if(e.integrationId){let s=Dt(e.integrationId);if(!s)return p(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=jt(s.id);return p(JSON.stringify({integration:{id:s.id,name:s.name,category:s.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${s.name}" (${s.category}) \u2014 ${a?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${a?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${a?.docsUrl??"n/a"}.`}))}let n=no(e.category??void 0),i=Vr(e.category??void 0),o=to(i);return p(JSON.stringify({count:n.length,integrations:n.map(s=>({id:s.id,name:s.name,category:s.category,description:s.description,packages:s.packages,difficulty:s.difficulty,envVars:s.envVars.map(a=>a.key)})),formatted:o,message:`${n.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let n=Un(e.projectPath??process.cwd()),i=qn(n,"mistflow.json");if(!$n(i))return Ve(n);let o;try{o=JSON.parse(Fn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first.",!0);try{let a=await Cr(s,e.period??"7d");return a.total===0?p(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):p(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 p(l,!0)}}case"logs":{let n=Un(e.projectPath??process.cwd()),i=qn(n,"mistflow.json");if(!$n(i))return Ve(n);let o;try{o=JSON.parse(Fn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await Rt(s);if(l.length===0)return p("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 p(c,!0)}try{let[l,c]=await Promise.all([Pr(a),st(a)]),u=l.filter(d=>d.level==="error"),h=l.filter(d=>d.level==="warn");return p(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:u.length,warnCount:h.length,logs:l.map(d=>({time:d.timestamp,level:d.level,phase:d.phase,message:d.message})),message:c.status==="failed"?`Deployment failed. ${u.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${u.length} errors, ${h.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return p(c,!0)}}case"deployments":{let n=Un(e.projectPath??process.cwd()),i=qn(n,"mistflow.json");if(!$n(i))return Ve(n);let o;try{o=JSON.parse(Fn(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return p("No project ID found. Deploy the project first.",!0);try{let a=await Rt(s);return p(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 p(l,!0)}}case"version":{pr().backendSignalReceived||await yr();let n=pr(),i=n.severity==="none",o={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return p(JSON.stringify({current:n.current,latest:n.latest||"unknown",minSupported:n.minSupported||"unknown",severity:n.severity,upToDate:i,upgradeCmd:n.upgradeCmd,changelogUrl:n.changelogUrl,backendSignalReceived:n.backendSignalReceived,message:n.backendSignalReceived?`Mistflow MCP ${n.current} (${o[n.severity]??n.severity}). Latest: ${n.latest}.${i?"":` Run \`${n.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${n.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return p(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as kt}from"zod";Ct();var Rl=kt.object({action:kt.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:kt.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:kt.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:kt.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:kt.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:kt.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),so={name:"mist_browser",description:ys,inputSchema:Rl,handler:async t=>{let e=t,r=await ur();if(e.action==="navigate"){if(!e.url)return p("URL is required for 'navigate'.",!0);let o=[],s=c=>{c.type()==="error"&&o.push(c.text())};r.on("console",s),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=c=>a.push(c.message);if(r.on("pageerror",l),await r.waitForTimeout(500),r.removeListener("console",s),r.removeListener("pageerror",l),o.length>0||a.length>0){let c=await Yt(r),u=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:o,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let h=await Qt(r);u.push({type:"image",data:h.toString("base64"),mimeType:"image/png"})}return{content:u}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return p("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return p("Selector is required for 'type'.",!0);if(!e.value)return p("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return p("Selector is required for 'fill'.",!0);if(!e.value)return p("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return p("Selector is required for 'select_option'.",!0);if(!e.value)return p("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return p("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return p("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let o;if(e.selector){let s=await r.$(e.selector);if(!s)return p(`Element not found: ${e.selector}`,!0);o=await s.screenshot({type:"png"})}else o=await Qt(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:o.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let o=await Yt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}]}}let n=await Yt(r),i=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:n})}];if(e.includeScreenshot){let o=await Qt(r);i.push({type:"image",data:o.toString("base64"),mimeType:"image/png"})}return{content:i}}};import{z as oo}from"zod";var io=`# Mistflow MCP tool reference
|
|
1600
1600
|
|
|
1601
1601
|
Every capability is an MCP tool. There is no companion CLI. Long-running tools
|
|
1602
1602
|
(install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
|
|
@@ -1918,7 +1918,7 @@ is cheaper than building the wrong thing and iterating.
|
|
|
1918
1918
|
`).trim())}};import{z as an}from"zod";Se();var lo=an.object({action:an.enum(["list","get"]).default("get").describe("'get' (default) returns the full markdown for one topic \u2014 pass `topic`. 'list' returns the topic catalog so you can discover what's available \u2014 use to answer 'is there a doc for X?' before falling back to web search."),topic:an.string().optional().describe("Required for action='get'. Stable topic id (e.g. 'auth-design', 'stripe-integration', 'better-auth'). Call action='list' to discover ids."),kind:an.enum(["stack","skill","integration"]).optional().describe("Optional filter for action='list'. 'stack' = framework methodology, 'skill' = design + structural patterns, 'integration' = third-party services."),stack:an.string().optional().default("nextjs").describe("Stack slug. Defaults to 'nextjs' (currently the only supported stack).")}),co={name:"mist_docs",description:ws,inputSchema:lo,handler:async t=>{let{action:e,topic:r,kind:n,stack:i}=lo.parse(t);try{if(e==="list"){let a=await Or(i,n),l=[];l.push(`# Mistflow docs catalog (${a.stack})
|
|
1919
1919
|
${a.topics.length} topics. Call \`mist_docs({ action: "get", topic: "<id>" })\` to fetch one.
|
|
1920
1920
|
`);let c={};for(let h of a.topics)(c[h.kind]??=[]).push(h);let u=["stack","skill","integration"];for(let h of u){let d=c[h];if(!(!d||d.length===0)){l.push(`## ${h}`);for(let v of d)l.push(`- **${v.id}** \u2014 ${v.title}: ${v.description}`);l.push("")}}return p(l.join(`
|
|
1921
|
-
`).trim())}if(!r)return p("Missing `topic`. Pass action='get' with a topic id, or action='list' to see available topics.",!0);let o=await
|
|
1921
|
+
`).trim())}if(!r)return p("Missing `topic`. Pass action='get' with a topic id, or action='list' to see available topics.",!0);let o=await Dr(i,r),s=`<!-- mist_docs: topic=${o.topic} kind=${o.kind} stack=${o.stack} -->
|
|
1922
1922
|
# ${o.title}
|
|
1923
1923
|
|
|
1924
1924
|
${o.description}
|
|
@@ -1927,10 +1927,10 @@ ${o.description}
|
|
|
1927
1927
|
|
|
1928
1928
|
`;return p(s+o.content)}catch(o){if(o instanceof W&&o.statusCode===404)return p(o.message,!0);let s=o instanceof Error?o.message:String(o);return p(`mist_docs failed: ${s}
|
|
1929
1929
|
|
|
1930
|
-
If this looks like a network issue, retry. If it persists, you can fall back to reading AGENTS.md / .claude/skills/ in the user's project for the same content.`,!0)}}};import{existsSync as Bn,mkdirSync as mo,readFileSync as ho,readdirSync as go,writeFileSync as El}from"fs";import{join as at,resolve as Nl}from"path";import{homedir as Jr}from"os";import{z as ln}from"zod";function Mt(t){return t.entity??t.name??"Unknown"}function Lt(t){return typeof t=="string"?t:t.name}function Kr(t){return typeof t=="string"?"text":t.type}function po(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(i=>{let o={};for(let[s,a]of Object.entries(i))o[s]=a==null?"":String(a);return o});let r=t.fields||[],n=[];for(let i=0;i<3;i++){let o={};for(let s of r)o[Lt(s)]=Ol(Lt(s),Kr(s),Mt(t),i);n.push(o)}return n}function Ol(t,e,r,n){let i=t.toLowerCase(),o=(e||"text").toLowerCase();return i==="name"||i==="title"?[`${r} Alpha`,`${r} Beta`,`${r} Gamma`][n]:i==="email"?["alice@example.com","bob@example.com","carol@example.com"][n]:i==="status"?["Active","Pending","Completed"][n]:i==="priority"?["High","Medium","Low"][n]:i.includes("date")||o==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][n]:i.includes("price")||i.includes("amount")||i.includes("cost")?["$29","$49","$99"][n]:i.includes("count")||i.includes("quantity")||o==="number"||o==="integer"?["12","34","56"][n]:o==="boolean"||o==="bool"?["Yes","No","Yes"][n]:i.includes("description")||o==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function
|
|
1930
|
+
If this looks like a network issue, retry. If it persists, you can fall back to reading AGENTS.md / .claude/skills/ in the user's project for the same content.`,!0)}}};import{existsSync as Bn,mkdirSync as mo,readFileSync as ho,readdirSync as go,writeFileSync as El}from"fs";import{join as at,resolve as Nl}from"path";import{homedir as Jr}from"os";import{z as ln}from"zod";function Mt(t){return t.entity??t.name??"Unknown"}function Lt(t){return typeof t=="string"?t:t.name}function Kr(t){return typeof t=="string"?"text":t.type}function po(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(i=>{let o={};for(let[s,a]of Object.entries(i))o[s]=a==null?"":String(a);return o});let r=t.fields||[],n=[];for(let i=0;i<3;i++){let o={};for(let s of r)o[Lt(s)]=Ol(Lt(s),Kr(s),Mt(t),i);n.push(o)}return n}function Ol(t,e,r,n){let i=t.toLowerCase(),o=(e||"text").toLowerCase();return i==="name"||i==="title"?[`${r} Alpha`,`${r} Beta`,`${r} Gamma`][n]:i==="email"?["alice@example.com","bob@example.com","carol@example.com"][n]:i==="status"?["Active","Pending","Completed"][n]:i==="priority"?["High","Medium","Low"][n]:i.includes("date")||o==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][n]:i.includes("price")||i.includes("amount")||i.includes("cost")?["$29","$49","$99"][n]:i.includes("count")||i.includes("quantity")||o==="number"||o==="integer"?["12","34","56"][n]:o==="boolean"||o==="bool"?["Yes","No","Yes"][n]:i.includes("description")||o==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function Dl(t){let e=t.dataModel??[],r=t.pages??[],n=t.design??{},i=r.map(h=>({label:h.name??h.path??"Page",route:h.path??h.route??"/"})),o=[],s=e.slice(0,3).map(h=>({name:Mt(h),fields:(h.fields||[]).map(d=>({name:Lt(d),type:Kr(d)})),sampleData:po(h)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(h=>Mt(h)).join(", ")}`),a.push("RECENT: Latest activity or items"),o.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(h=>Mt(h)).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:s});let l=e[0];if(l){let h=Mt(l),d=h.toLowerCase().endsWith("s")?h:`${h}s`;o.push({name:`${h} List`,type:"detail",route:`/${d.toLowerCase()}`,purpose:`Browse, search, and manage ${d.toLowerCase()}. Create new ${h.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${d}" title + "Add ${h}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(v=>Lt(v)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${d.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${d.toLowerCase()} matching..." with clear filter`],entities:[{name:h,fields:(l.fields||[]).map(v=>({name:Lt(v),type:Kr(v)})),sampleData:po(l)}]})}t.steps.some(h=>{let d=`${h.name??h.title??""} ${h.description??""}`.toLowerCase();return d.includes("landing")||d.includes("hero")||d.includes("marketing")||d.includes("homepage")})&&o.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let u=[];for(let h of e.slice(0,3)){let d=Mt(h);(h.fields||[]).find(H=>{let _=Lt(H).toLowerCase();return _==="name"||_==="title"})&&u.push(`What if a ${d.toLowerCase()}'s name is 47 characters? Does the layout break?`),u.push(`What if there are 0 ${d.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&u.push("What does a brand-new user see? (no data, no setup)"),u.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:o,navigation:{style:t.navStyle??"sidebar",items:i},primaryAction:t.primaryAction??null,designDirection:{tone:n.tone??"professional",accentColor:n.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:n.fonts??{heading:"Inter",body:"Inter"}},edgeCases:u}}function jl(t,e,r){let n=[];n.push(`# Wireframe sketch for ${t.appName}`),n.push(""),n.push(`**${t.appName}** \u2014 ${t.summary}`),n.push(""),e&&(n.push("## Feedback to apply"),n.push(e),n.push("")),n.push("## Design principles"),n.push(""),n.push("Apply these when deciding layout and hierarchy:"),n.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),n.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),n.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),n.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),n.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),n.push(""),n.push("## Wireframe rules (strict)"),n.push(""),n.push(`Write a **single self-contained HTML file** saved to \`${r}\`.`),n.push(""),n.push("The wireframe must:"),n.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),n.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),n.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),n.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),n.push("- Include **HTML comments** explaining design decisions"),n.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),n.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),n.push("- Include a small header bar showing: screen name tabs + the design direction summary"),n.push(""),n.push("The wireframe must NOT:"),n.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),n.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),n.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),n.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),n.push(""),n.push("## Screens to wireframe"),n.push("");for(let i of t.screens){n.push(`### ${i.name} (\`${i.route}\`)`),n.push(`**Purpose**: ${i.purpose}`),n.push(""),n.push("**Information hierarchy** (render in this order, top to bottom):");for(let o of i.informationHierarchy)n.push(`- ${o}`);n.push(""),n.push("**Interaction states** (add HTML comments for non-visible states):");for(let o of i.interactionStates)n.push(`- ${o}`);if(n.push(""),i.entities.length>0){n.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let o of i.entities)n.push(`
|
|
1931
1931
|
**${o.name}** \u2014 fields: ${o.fields.map(s=>`${s.name} (${s.type})`).join(", ")}`),n.push("```json"),n.push(JSON.stringify(o.sampleData,null,2)),n.push("```");n.push("")}}n.push("## Navigation"),n.push(`**Style**: ${t.navigation.style} (use this layout)`),n.push("**Items**:");for(let i of t.navigation.items)n.push(`- ${i.label} \u2192 \`${i.route}\``);if(n.push(""),t.primaryAction&&(n.push("## Primary action (this drives the layout)"),n.push(`- **Action**: ${t.primaryAction.action}`),n.push(`- **Flow**: ${t.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),n.push(""),n.push("The dashboard is an ACTION surface. The primary action should be the most prominent thing on the page \u2014 above the metrics, above the recent items. Users came here to DO something, not to look at numbers."),n.push("")),t.edgeCases.length>0){n.push("## Edge cases to consider"),n.push("Add HTML comments in the wireframe where these matter:");for(let i of t.edgeCases)n.push(`- ${i}`);n.push("")}return n.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),n.push(`The final app will use: ${t.designDirection.tone} tone, ${t.designDirection.accentColor} accent, ${t.designDirection.navStyle} nav, ${t.designDirection.fonts.heading} / ${t.designDirection.fonts.body} fonts.`),n.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),n.push(""),n.push("## After writing the wireframe"),n.push(`1. Write the file to \`${r}\``),n.push(`2. Open it for the user: \`open "${r}"\``),n.push(`3. Tell the user: "Here's a rough wireframe of your app. Does the layout feel right? Let me know what to change, or I can start building if it's close."`),n.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),n.join(`
|
|
1932
|
-
`)}function fo(t){return at(Jr(),".mistflow","mockup-state",`${t}.json`)}function Ml(t){let e=fo(t);if(!Bn(e))return null;try{return JSON.parse(ho(e,"utf-8"))}catch{return null}}function uo(t,e){let r=at(Jr(),".mistflow","mockup-state");mo(r,{recursive:!0}),El(fo(t),JSON.stringify(e,null,2))}var Ll=ln.object({planId:ln.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:ln.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:ln.string().optional().describe("User feedback to apply to the next iteration."),approved:ln.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(t=>!(t.feedback&&t.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),yo={name:"mist_mockup",description:ks,inputSchema:Ll,handler:async t=>{let e=t,{planId:r,feedback:n,approved:i}=e,o=Nl(e.projectPath??process.cwd()),s=at(Jr(),".mistflow","plans",`${r}.json`);if(!Bn(s))return p(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(ho(s,"utf-8"))}catch{return p("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return p("Plan data is empty. Call mist_plan again.",!0);let c=Ml(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let u=at(o,".mistflow","mockups");mo(u,{recursive:!0});let h=`mockup-${r}.html`,d=at(u,h);if(i){c.approved=!0,uo(r,c);let y=Bn(u)?go(u).filter(C=>C.endsWith(".html")).map(C=>at(".mistflow","mockups",C)):[];return p(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:y,nextAction:`Call mist_init with planId='${r}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}c.iterationCount++,n&&c.feedback.push(n);let v=
|
|
1933
|
-
${i.message}`})}),r.on("close",i=>{e({exitCode:i??1,combined:n})})})}var wo={name:"mist_debug",description:vs,inputSchema:Fl,handler:async t=>{let e=t,r=Ul(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let s=await ql(r);if(s.exitCode===0)return p(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=s.combined}let i=zn(n),o=n.slice(0,2e3);return i.length===0?p(JSON.stringify({errors:i,rawOutput:o,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):p(JSON.stringify({errors:i,rawOutput:o,message:`Found ${i.length} error${i.length===1?"":"s"} in the build output.`}))}};import{z as
|
|
1932
|
+
`)}function fo(t){return at(Jr(),".mistflow","mockup-state",`${t}.json`)}function Ml(t){let e=fo(t);if(!Bn(e))return null;try{return JSON.parse(ho(e,"utf-8"))}catch{return null}}function uo(t,e){let r=at(Jr(),".mistflow","mockup-state");mo(r,{recursive:!0}),El(fo(t),JSON.stringify(e,null,2))}var Ll=ln.object({planId:ln.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:ln.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:ln.string().optional().describe("User feedback to apply to the next iteration."),approved:ln.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(t=>!(t.feedback&&t.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),yo={name:"mist_mockup",description:ks,inputSchema:Ll,handler:async t=>{let e=t,{planId:r,feedback:n,approved:i}=e,o=Nl(e.projectPath??process.cwd()),s=at(Jr(),".mistflow","plans",`${r}.json`);if(!Bn(s))return p(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(ho(s,"utf-8"))}catch{return p("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return p("Plan data is empty. Call mist_plan again.",!0);let c=Ml(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let u=at(o,".mistflow","mockups");mo(u,{recursive:!0});let h=`mockup-${r}.html`,d=at(u,h);if(i){c.approved=!0,uo(r,c);let y=Bn(u)?go(u).filter(C=>C.endsWith(".html")).map(C=>at(".mistflow","mockups",C)):[];return p(JSON.stringify({status:"approved",message:`Wireframe approved after ${c.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:y,nextAction:`Call mist_init with planId='${r}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}c.iterationCount++,n&&c.feedback.push(n);let v=Dl(l);c.screens=v.screens.map(y=>y.name),uo(r,c);let H=jl(v,n??void 0,d),_=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,k=n?`Apply the user's feedback to ${d}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${d}, then open it in the browser. Ask the user if the layout feels right.`;return p(JSON.stringify({status:"wireframe",requires_user_input:!0,iterationCount:c.iterationCount,screens:v.screens.map(y=>({name:y.name,type:y.type,route:y.route})),wireframePrompt:H,designDirection:v.designDirection,..._?{nudge:_}:{},mockupFile:h,mockupPath:d,nextAction:k}))}};function bo(t){let e=at(t,".mistflow","mockups");return Bn(e)?go(e).filter(r=>r.endsWith(".html")).map(r=>at(e,r)):[]}import{z as Yr}from"zod";import{resolve as Ul}from"path";import{spawn as $l}from"child_process";function zn(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,c,u,h,d]=a;e.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:`${h}: ${d}`,humanMessage:`There is a type error in ${l} on line ${c}: ${d}`,suggestion:`Check line ${c} in ${l}. ${h==="TS2345"?"The types of the arguments do not match.":`Fix the ${h} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(n)){let[,l,c,u,h]=a;e.some(d=>d.file===l&&d.line===parseInt(c,10))||e.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:h,humanMessage:`There is an error in ${l} on line ${c}: ${h.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let i=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of t.matchAll(i)){let[,l,c]=a;e.push({file:c,message:`Module not found: ${l}`,humanMessage:`The file ${c??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let o=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(o)){let[,l,c]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${c}${l}`,humanMessage:`The package '${c}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${c}'.`,suggestion:`Add '${c}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let s=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let a of t.matchAll(s)){let[,l,c,u,h]=a;e.some(d=>d.file===l&&d.line===parseInt(u,10))||e.push({file:l,line:parseInt(u,10),column:parseInt(h,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${u}.`,suggestion:`Check line ${u} in ${l} for a missing closing bracket or unexpected token.`})}return e}var Fl=Yr.object({projectPath:Yr.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:Yr.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});function ql(t){return new Promise(e=>{let r=$l("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),n="";r.stdout?.on("data",i=>{n+=i.toString()}),r.stderr?.on("data",i=>{n+=i.toString()}),r.on("error",i=>{e({exitCode:127,combined:`${n}
|
|
1933
|
+
${i.message}`})}),r.on("close",i=>{e({exitCode:i??1,combined:n})})})}var wo={name:"mist_debug",description:vs,inputSchema:Fl,handler:async t=>{let e=t,r=Ul(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let s=await ql(r);if(s.exitCode===0)return p(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=s.combined}let i=zn(n),o=n.slice(0,2e3);return i.length===0?p(JSON.stringify({errors:i,rawOutput:o,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):p(JSON.stringify({errors:i,rawOutput:o,message:`Found ${i.length} error${i.length===1?"":"s"} in the build output.`}))}};import{z as D}from"zod";import{existsSync as Je,mkdirSync as xt,readFileSync as pn,readdirSync as Co,statSync as Ao,unlinkSync as Ql,writeFileSync as lt}from"fs";import{dirname as Xl,isAbsolute as Zl,join as fe}from"path";import{homedir as ct,hostname as xo}from"os";import{createHash as ec,createHmac as Ro,randomBytes as tc,randomUUID as So,timingSafeEqual as nc}from"crypto";Se();import{spawn as Bl}from"child_process";function Qr(t){if(process.env.MISTFLOW_AUTO_OPEN_PICKER==="false")return{opened:!1,reason:"MISTFLOW_AUTO_OPEN_PICKER=false"};let e;try{e=new URL(t)}catch{return{opened:!1,reason:"invalid URL"}}if(e.protocol!=="http:"&&e.protocol!=="https:"&&e.protocol!=="file:")return{opened:!1,reason:`unsupported protocol ${e.protocol}`};if(zl())return{opened:!1,reason:"headless environment detected"};let r=process.platform,n,i;r==="darwin"?(n="open",i=[e.href]):r==="win32"?(n="cmd",i=["/c","start","",e.href]):(n="xdg-open",i=[e.href]);try{let o=Bl(n,i,{shell:!1,stdio:"ignore",detached:!0});return o.on("error",()=>{}),o.unref(),{opened:!0}}catch(o){return{opened:!1,reason:o instanceof Error?o.message:"spawn failed"}}}function zl(){if(process.env.SSH_TTY||process.env.SSH_CONNECTION)return!0;for(let t of["CI","BUILDKITE","GITHUB_ACTIONS","CIRCLECI","GITLAB_CI"])if(process.env[t])return!0;return process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY&&!process.env.WSL_DISTRO_NAME}function $e(t,e,r,n=3e3){if(e===void 0)return{stop:()=>{}};let i=0,o=!1,a=setInterval(()=>{o||(i++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:i,message:r()}}).catch(()=>{}))},n);return{stop:()=>{o||(o=!0,clearInterval(a))}}}function Hl(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function Wl(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function Gl(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function Vl(t){let e={},r=[],n=[],i=new Set;for(let o=0;o<t.length;o++){let s=t[o],a=s.decisionKey?Gl(s.decisionKey):`q_${o+1}`,l=a,c=2;for(;i.has(l);)l=`${a}_${c}`,c++;i.add(l);let u=s.freetext?"":`${l}_other`;if(u&&i.add(u),n.push({primary:l,other:u,question:s}),s.freetext){e[l]={type:"string",title:s.question,description:s.why,...s.recommended?{default:s.recommended}:{}},r.push(l);continue}let h=(s.options??[]).map(v=>typeof v=="string"?v:v.label),d=s.noOtherSentinel?[...h]:[...h,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:s.question,description:s.why?`${s.why}${s.recommended?`
|
|
1934
1934
|
Recommended: ${s.recommended}`:""}`:s.recommended?`Recommended: ${s.recommended}`:void 0,enum:d,enumNames:d,...s.recommended&&h.includes(s.recommended)?{default:s.recommended}:{}},r.push(l),e[u]={type:"string",title:s.otherFieldTitle??"If 'Other' selected above: type your answer",description:"Leave blank if you picked an option from the list."}}return{schema:{type:"object",properties:e,required:r},fieldKeys:n}}function Kl(t,e){let r=[],n;for(let{primary:i,other:o,question:s}of e){let a=String(t[i]??"").trim(),l;if(s.freetext)l=a||s.recommended||"";else{let u=o?String(t[o]??"").trim():"",h=a.toLowerCase(),d=h.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(h);u?l=u:d?l=s.recommended??(s.options?.[0]&&typeof s.options[0]=="object"?s.options[0].label:"")??a:l=a}let c=s.decisionKey??"";if(c==="urlChoice"){n=l;continue}r.push({question:s.question,decisionKey:c,answer:l})}return{answers:r,urlChoice:n}}function Ke(t,e,r){let n;switch(r.outcome){case"submitted":n=`submitted (${r.answers?.length??0} answers${r.urlChoice?`, urlChoice="${r.urlChoice}"`:""})`;break;case"error":n=`error (${r.errorMessage??"unknown"})`;break;case"unsupported":n=`unsupported (${e})`;break;default:n=r.outcome}console.error(`[mist_plan] elicitation/${t}: ${n}`)}async function cn(t,e,r,n="discovery"){if(Wl()){let u={outcome:"unsupported"};return Ke(n,"MISTFLOW_ELICITATION kill switch on",u),u}if(!Hl(t)){let u={outcome:"unsupported"};return Ke(n,"client did not declare elicitation capability",u),u}if(e.length===0){let u={outcome:"submitted",answers:[]};return Ke(n,"no questions to ask",u),u}let{schema:i,fieldKeys:o}=Vl(e),s;try{s=await t.elicitInput({message:r,requestedSchema:i,mode:"form"},{timeout:300*1e3})}catch(u){let h=u instanceof Error?u.message:String(u);if(h.toLowerCase().includes("not support")){let v={outcome:"unsupported"};return Ke(n,`SDK rejected form mode: ${h}`,v),v}let d={outcome:"error",errorMessage:h};return Ke(n,"",d),d}if(s.action==="decline"){let u={outcome:"declined"};return Ke(n,"",u),u}if(s.action==="cancel"){let u={outcome:"cancelled"};return Ke(n,"",u),u}if(s.action!=="accept"||!s.content){let u={outcome:"error",errorMessage:`Unexpected elicitation result: ${s.action}`};return Ke(n,"",u),u}let{answers:a,urlChoice:l}=Kl(s.content,o),c={outcome:"submitted",answers:a,urlChoice:l};return Ke(n,"",c),c}var Jl=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:t=>t.surfaceType==="internal-tool"||t.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:t=>t.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:t=>t.scheduling===!0,keywords:/\b(schedul|book|reserv|appointment|calendar|slot)\b/i},{name:"Payments / Billing",description:"Charge users, invoices, subscriptions (experimental \u2014 Stripe integration is early-stage)",condition:()=>!1,keywords:/\b(payment|billing|invoice|subscription|checkout|stripe)\b/i},{name:"Admin Panel",description:"Manage users, roles, and content",condition:t=>t.multiRole===!0||t.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:t=>t.primaryActor==="customers"||t.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:t=>t.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:t=>t.integrations?.includes("email")===!0,keywords:/\b(notification|alert|reminder|email.?notif|sms|welcome.?email)\b/i},{name:"Analytics / Reports",description:"Usage stats, trends, data exports",condition:()=>!1,keywords:/\b(analytics|report|chart|trend|insight|metric)\b/i},{name:"File Uploads",description:"Images, documents, attachments",condition:t=>t.integrations?.includes("file-uploads")===!0,keywords:/\b(upload|image|photo|attachment|document|gallery|file)\b/i},{name:"AI Features",description:"Chatbot, content generation, AI assistant",condition:t=>t.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:t=>t.integrations?.includes("maps")===!0,keywords:/\b(map|location|address|geo|places)\b/i},{name:"Voice / TTS",description:"Text-to-speech, voice notes, audio generation",condition:()=>!1,keywords:/\b(voice|tts|text.?to.?speech|audio|speak|narrat|podcast|elevenlabs)\b/i},{name:"SMS / Text Messages",description:"Send SMS notifications, OTP verification",condition:t=>t.integrations?.includes("sms")===!0,keywords:/\b(sms|text.?message|twilio|otp|verification.?code|phone.?verif)\b/i},{name:"Web Scraping",description:"Scrape URLs, crawl websites, extract structured data",condition:()=>!1,keywords:/\b(scrape|crawl|web.?scrap|extract.?from.?url|read.?url|ingest.?web|firecrawl)\b/i},{name:"Chat / Messaging",description:"Real-time messaging between users",condition:()=>!1,keywords:/\b(chat|messag|inbox|conversation|dm)\b/i},{name:"Events / Tournaments",description:"Create and manage events, registrations",condition:()=>!1,keywords:/\b(event|tournament|competition|league|registration)\b/i},{name:"High Scores",description:"Track and display top scores with a leaderboard",condition:t=>t.surfaceType==="game",keywords:/\b(high.?score|leaderboard|top.?score|ranking|scoreboard)\b/i},{name:"Save Progress",description:"Save and resume game state between sessions",condition:t=>t.surfaceType==="game",keywords:/\b(save|progress|resume|checkpoint|continue)\b/i},{name:"Guest Play",description:"Play immediately without signing up, optionally link account later",condition:t=>t.surfaceType==="game",keywords:/\b(guest|anonymous|no.?login|play.?now|instant.?play)\b/i},{name:"Levels / Stages",description:"Progressive difficulty with unlockable stages",condition:()=>!1,keywords:/\b(level|stage|unlock|difficult|progress|world)\b/i},{name:"Achievements",description:"Badges, trophies, and milestones for player accomplishments",condition:()=>!1,keywords:/\b(achieve|badge|trophy|milestone|reward|unlock)\b/i},{name:"Daily Challenge",description:"New puzzle or challenge every day to keep players coming back",condition:()=>!1,keywords:/\b(daily|challenge|streak|word.?of.?the.?day|puzzle.?of)\b/i}];function vo(t,e,r){let n=r?.suggestedName||Yl(t),i=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",o=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),s=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",a;if(r?.suggestedFeatures&&r.suggestedFeatures.length>0)a=r.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;a=[];for(let c of Jl){let u=c.keywords.test(l),h=c.condition(e);(u||h)&&a.push({name:c.name,description:c.description,checked:u,source:u?"explicit":"suggested"})}}return{name:n,audience:i,audienceType:o,surfaceType:s,primaryAction:e.primaryAction||"manage items",features:a,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:r?.language||"English"}}function ko(t){let e=t.features.filter(a=>a.checked),r=t.features.filter(a=>!a.checked),n={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},i={neon:"Postgres",turso:"SQLite (legacy)"},o={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},s=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${o[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${n[t.authModel]??t.authModel} | Database: ${i[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){s.push("**Included:**");for(let a of e)s.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(s.push(""),s.push(`**Integrations:** ${t.integrations.join(", ")}`)),r.length>0){s.push(""),s.push("**Available to add:**");for(let a of r)s.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return s.join(`
|
|
1935
1935
|
`)}function Yl(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return Hn(e[1]);let r=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),i=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(o=>o.length>2&&!r.has(o)).slice(0,3);return i.length===0?"my-app":i.join("-")}function Hn(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}function Xr(t,e,r){let n=dn(t||"your app"),i=e.map((s,a)=>{let l=Wn(s.id||`direction-${a}`),c=dn(s.name||`Direction ${a+1}`),u=dn(s.summary||"");return`<button class="tab${a===0?" active":""}" data-target="${l}" type="button"><span class="tab-name">${c}</span>${u?`<span class="tab-sub">${u}</span>`:""}</button>`}).join(`
|
|
1936
1936
|
`),o=e.map((s,a)=>{let l=Wn(s.id||`direction-${a}`),c=r[s.id??""]??"";return`<iframe class="render-frame${a===0?" active":""}" data-id="${l}" srcdoc="${Wn(c)}" sandbox="allow-same-origin allow-scripts" title="${Wn(s.name||`Direction ${a+1}`)}"></iframe>`}).join(`
|
|
@@ -2041,7 +2041,7 @@ ${o}
|
|
|
2041
2041
|
</body>
|
|
2042
2042
|
</html>
|
|
2043
2043
|
`}function dn(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Wn(t){return dn(t)}var Gn="__mistflow_url_choice__",rc=600*1e3;function Eo(){let t=fe(ct(),".mistflow","confirm-secret");if(Je(t))try{return Buffer.from(pn(t,"utf-8").trim(),"hex")}catch{}let e=tc(32);return xt(fe(ct(),".mistflow"),{recursive:!0}),lt(t,e.toString("hex"),{mode:384}),e}function No(t){return ec("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function sc(t,e){let r={cwd:t,d:No(e),exp:Date.now()+rc},n=Buffer.from(JSON.stringify(r)).toString("base64url"),i=Ro("sha256",Eo()).update(n).digest("base64url");return`${n}.${i}`}function oc(t,e,r){let n=t.split(".");if(n.length!==2)return!1;let[i,o]=n,s=Ro("sha256",Eo()).update(i).digest("base64url"),a=Buffer.from(o),l=Buffer.from(s);if(a.length!==l.length||!nc(a,l))return!1;try{let c=JSON.parse(Buffer.from(i,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==e||c.d!==No(r))}catch{return!1}}function ic(t){let e=t,r=ct(),n=!1;for(let i=0;i<64;i++){if(Je(fe(e,"mistflow.json")))return"mistflow";if(!n&&Je(fe(e,"package.json"))&&(n=!0),e===r)break;let o=Xl(e);if(o===e)break;e=o}return n?"foreign":"none"}function ac(t){let e=ct(),r=t.replace(/\/+$/,"");if(r===e||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let i of n)if(r===fe(e,i))return!0;return!1}function lc(t){let e=new Set(["build","create","make","scaffold","start","using","with","mist","mistflow","a","an","the","for","me","my","new","app","application","website","site","web","tool","dashboard","landing","page","platform","please","can","you","i","want","need"]);return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).map(n=>n.trim()).filter(n=>n.length>1&&!e.has(n)).slice(0,4).join("-").slice(0,48)||"new-app"}function To(t){if(!Je(t))return!0;try{return Ao(t).isDirectory()?Co(t).filter(n=>n!==".mistflow").length===0:!1}catch{return!1}}function cc(t,e){let r=lc(e),n=fe(t,r);if(To(n))return n;for(let i=2;i<=50;i++){let o=fe(t,`${r}-${i}`);if(To(o))return o}return fe(t,`${r}-${Date.now()}`)}function dc(t,e){if(e)return!0;let r=t.toLowerCase(),n=/\b(build|create|make|scaffold|start|generate)\b/.test(r),i=/\b(app|application|website|site|web\s+app|landing\s+page|dashboard|tool|marketplace|game|blog|portfolio|crm)\b/.test(r),o=/\b(add|change|fix|update|edit|refactor|debug|review)\b/.test(r)&&!n;return n&&i&&!o}function _o(t){try{xt(t,{recursive:!0});return}catch(e){return e instanceof Error?e.message:String(e)}}function Io(t){let{projectPath:e,description:r,confirmToken:n,suggestedPath:i,previousTokenInvalid:o}=t;return JSON.stringify({status:"confirm_new_project",requires_user_input:!0,projectPath:e,description:r,confirmToken:n,suggestedScaffoldPath:i,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:`Creates a fresh project at \`${i}\` without touching the existing code.`},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json).","MANDATORY: Ask the user the provided askUserQuestion before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token returned above.",`Mistflow will create and remember the new app directory at \`${i}\`. Do not change projectPath to the child directory on the retry; the token is intentionally bound to the original directory.`,"If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",o?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
2044
|
-
`)})}var pc=j.object({description:j.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:j.string().min(1).describe("REQUIRED. Absolute path to the user's current working directory \u2014 where the Mistflow app will be scaffolded. Pass the directory the user is actually working in (e.g. /Users/alice/projects). Do NOT pass '/', '~', $HOME, Desktop, Documents, Downloads, or /tmp \u2014 the tool will refuse to scaffold at those locations. If you are unsure of the user's working directory, ask them before calling this tool."),sessionId:j.string().uuid().optional().describe("Backend-owned session ID. When present, mist_plan polls GET /api/sessions/{id}/next and returns the next instruction (wait, ask_user, pick_design, call_mist_init, etc.). Pass it on every subsequent mist_* call to keep the same session."),conversationId:j.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:j.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("[")&&!e.startsWith("{"))return t;try{return JSON.parse(e)}catch{return t}},j.union([j.record(j.string()),j.array(j.object({question:j.string().optional(),decisionKey:j.string().optional(),answer:j.string()}))]).optional()).describe("User's answers to the clarifying questions. Pass an ARRAY of { question, decisionKey, answer } objects directly \u2014 do NOT stringify it as JSON. The schema also accepts a { '<question text>': '<answer label>' } object map for one-question-per-decisionKey rounds. Strings that look like JSON arrays/objects are auto-parsed for resilience."),existingPlan:j.record(j.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:j.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:j.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:j.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:j.boolean().optional().describe("DANGER \u2014 only set this to `true` when the user has EXPLICITLY asked to skip discovery questions (phrases like 'no questions', 'just build it', 'autonomous mode', 'don't ask'). Default is `false` and should stay that way in every other case. Do NOT set autonomous=true as a retry strategy after a plan-gen failure \u2014 it doesn't make things more reliable, it just removes the user's control over discovery answers (roles, integrations, auth model, etc.) and Sonnet ends up guessing. If a plan call fails, retry the SAME call with the same parameters, not a more aggressive one. Do NOT set autonomous=true to speed things up \u2014 the server already runs plan-gen in the background and polls, so there is no speed benefit. When set, skips the clarify round and generates the plan straight from the description. The user loses the chance to pick any option."),language:j.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:j.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:j.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:j.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers."),designConversationId:j.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:j.object({id:j.string().optional(),name:j.string().optional(),summary:j.string().optional(),heroHeadline:j.string().optional(),ctaText:j.string().optional(),bodySample:j.string().optional(),fontsHint:j.string().optional(),fonts:j.object({display:j.string(),body:j.string()}).partial().optional(),colorMood:j.string().optional(),colors:j.object({bg:j.string(),fg:j.string(),accent:j.string()}).partial().optional(),heroTreatment:j.string().optional(),shapeLang:j.string().optional(),texture:j.string().optional(),decorationHint:j.string().optional(),custom:j.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass ONLY the minimal shape: (a) `{ id: '<short-kebab-id-from-directionRefs>' }` when the user picked one of the proposed options \u2014 copy the id verbatim from `directionRefs[].id`, e.g. 'morning-paper' or 'quiet-utility'; or (b) `{ custom: '<the user\\'s exact words>' }` + `userConfirmedCustom: true` when the user typed their own description. Do NOT pass the full direction object (name, summary, fonts, colors, hero_headline, body_sample, etc.) \u2014 those fields are ignored and may exceed backend length limits, causing 422 rejections. ID values are short kebab-case strings (\u2264256 chars). Custom descriptions are user-typed prose (\u22644000 chars). Anything longer is wrong."),userConfirmedCustom:j.boolean().optional().describe("Set true ONLY when the user themselves typed a custom direction (via AskUserQuestion 'Other' or by explicitly describing the look in the chat). Required when submitting designDirection: { custom: ... } if the backend has real directions cached \u2014 the server rejects custom submissions otherwise to stop the AI from silently bypassing the picker. NEVER set this true unless the words in `custom` came directly from the user."),forceNew:j.boolean().optional().describe("Set to true ONLY after the user has explicitly chosen 'start fresh' from a previous mist_plan response with status 'resume_offer'. Suppresses the resume-offer check and lets a new session start even when this machine has unfinished work in flight. Do NOT set this preemptively on the first call \u2014 the resume-offer check needs to run so the user gets the chance to pick up where they left off.")});function uc(t){let e=[[/payment/i,"Payments"],[/database/i,"Database"],[/auth|sign.?up|login|access/i,"Access"],[/landing.?page/i,"Landing page"],[/who.*using|user|role/i,"Users"],[/design|theme|style/i,"Design"],[/deploy/i,"Deploy"],[/domain/i,"Domain"],[/notification/i,"Notify"],[/email/i,"Email"],[/mobile|responsive/i,"Mobile"],[/integrat/i,"Integration"],[/field|info|propert|detail|contain/i,"Item shape"],[/view|layout|board|grid|list|timeline/i,"View"],[/scope|how many|one.*or.*many|multi/i,"Scope"],[/share|read.?only|viewer|stakeholder/i,"Sharing"],[/workflow|status|state|move|stage|pipeline/i,"Workflow"],[/avoid|bloat|simple|complex|minimal/i,"Constraints"],[/time.*period|quarter|month|sprint/i,"Time periods"],[/swimlane|column|group|categor/i,"Structure"]];for(let[n,i]of e)if(n.test(t))return i;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(n=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(n.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function mc(t){let e=fe(ct(),".mistflow","plans",`${t}.json`);if(!Je(e))return null;try{return JSON.parse(pn(e,"utf-8")).plan??null}catch{return null}}async function hc(t){let e=Date.now(),r=5e4,n=2e3;for(;Date.now()-e<r;){try{let i=await Cn(t.design_conversation_id);if(i.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:i.directions,plan:i.plan,methodology:i.methodology};if(i.status==="failed")return{status:"ready",plan:i.plan,methodology:i.methodology}}catch(i){let o=i instanceof Error?i.message:String(i);if(o.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll failed: ${o}`)}await new Promise(i=>setTimeout(i,n))}return console.error("[plan] directions poll exhausted (50s) \u2014 preserving pending so host re-polls"),t}function gc(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function fc(t,e){for(let r of e){let n=gc(t[r]);if(n)return n}}function yc(t){return fc(t,["mockup_url","mockupUrl","preview_url","previewUrl","live_url","liveUrl","deploy_url","deployUrl","url"])}function Po(t,e){return`Next action: call ${t} with ${JSON.stringify(e)}. Do not omit sessionId.`}function bc(t){let e=yc(t),r=t.reason?`
|
|
2044
|
+
`)})}var pc=D.object({description:D.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:D.string().min(1).describe("REQUIRED. Absolute path to the user's current working directory \u2014 where the Mistflow app will be scaffolded. Pass the directory the user is actually working in (e.g. /Users/alice/projects). Do NOT pass '/', '~', $HOME, Desktop, Documents, Downloads, or /tmp \u2014 the tool will refuse to scaffold at those locations. If you are unsure of the user's working directory, ask them before calling this tool."),sessionId:D.string().uuid().optional().describe("Backend-owned session ID. When present, mist_plan polls GET /api/sessions/{id}/next and returns the next instruction (wait, ask_user, pick_design, call_mist_init, etc.). Pass it on every subsequent mist_* call to keep the same session."),conversationId:D.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:D.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("[")&&!e.startsWith("{"))return t;try{return JSON.parse(e)}catch{return t}},D.union([D.record(D.string()),D.array(D.object({question:D.string().optional(),decisionKey:D.string().optional(),answer:D.string()}))]).optional()).describe("User's answers to the clarifying questions. Pass an ARRAY of { question, decisionKey, answer } objects directly \u2014 do NOT stringify it as JSON. The schema also accepts a { '<question text>': '<answer label>' } object map for one-question-per-decisionKey rounds. Strings that look like JSON arrays/objects are auto-parsed for resilience."),existingPlan:D.record(D.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:D.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:D.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:D.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:D.boolean().optional().describe("DANGER \u2014 only set this to `true` when the user has EXPLICITLY asked to skip discovery questions (phrases like 'no questions', 'just build it', 'autonomous mode', 'don't ask'). Default is `false` and should stay that way in every other case. Do NOT set autonomous=true as a retry strategy after a plan-gen failure \u2014 it doesn't make things more reliable, it just removes the user's control over discovery answers (roles, integrations, auth model, etc.) and Sonnet ends up guessing. If a plan call fails, retry the SAME call with the same parameters, not a more aggressive one. Do NOT set autonomous=true to speed things up \u2014 the server already runs plan-gen in the background and polls, so there is no speed benefit. When set, skips the clarify round and generates the plan straight from the description. The user loses the chance to pick any option."),language:D.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:D.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:D.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:D.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers."),designConversationId:D.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass this ONLY on the SUBMIT call after the user has picked a direction \u2014 i.e. ALWAYS together with `designDirection`. Do NOT include it on polling calls (status: 'rendering_directions' / 'design_clarify_pending') \u2014 for polling, send only `{ projectPath, conversationId }`. Including `designConversationId` without `designDirection` makes the backend respond 'you passed designConversationId but no designDirection' and wastes a round-trip. Decision rule: if the user has not yet typed/clicked a pick, omit this field; if they have, include both this field AND designDirection together in the same call."),designDirection:D.object({id:D.string().optional(),name:D.string().optional(),summary:D.string().optional(),heroHeadline:D.string().optional(),ctaText:D.string().optional(),bodySample:D.string().optional(),fontsHint:D.string().optional(),fonts:D.object({display:D.string(),body:D.string()}).partial().optional(),colorMood:D.string().optional(),colors:D.object({bg:D.string(),fg:D.string(),accent:D.string()}).partial().optional(),heroTreatment:D.string().optional(),shapeLang:D.string().optional(),texture:D.string().optional(),decorationHint:D.string().optional(),custom:D.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass ONLY the minimal shape: (a) `{ id: '<short-kebab-id-from-directionRefs>' }` when the user picked one of the proposed options \u2014 copy the id verbatim from `directionRefs[].id`, e.g. 'morning-paper' or 'quiet-utility'; or (b) `{ custom: '<the user\\'s exact words>' }` + `userConfirmedCustom: true` when the user typed their own description. Do NOT pass the full direction object (name, summary, fonts, colors, hero_headline, body_sample, etc.) \u2014 those fields are ignored and may exceed backend length limits, causing 422 rejections. ID values are short kebab-case strings (\u2264256 chars). Custom descriptions are user-typed prose (\u22644000 chars). Anything longer is wrong."),userConfirmedCustom:D.boolean().optional().describe("Set true ONLY when the user themselves typed a custom direction (via AskUserQuestion 'Other' or by explicitly describing the look in the chat). Required when submitting designDirection: { custom: ... } if the backend has real directions cached \u2014 the server rejects custom submissions otherwise to stop the AI from silently bypassing the picker. NEVER set this true unless the words in `custom` came directly from the user."),forceNew:D.boolean().optional().describe("Set to true ONLY after the user has explicitly chosen 'start fresh' from a previous mist_plan response with status 'resume_offer'. Suppresses the resume-offer check and lets a new session start even when this machine has unfinished work in flight. Do NOT set this preemptively on the first call \u2014 the resume-offer check needs to run so the user gets the chance to pick up where they left off.")});function uc(t){let e=[[/payment/i,"Payments"],[/database/i,"Database"],[/auth|sign.?up|login|access/i,"Access"],[/landing.?page/i,"Landing page"],[/who.*using|user|role/i,"Users"],[/design|theme|style/i,"Design"],[/deploy/i,"Deploy"],[/domain/i,"Domain"],[/notification/i,"Notify"],[/email/i,"Email"],[/mobile|responsive/i,"Mobile"],[/integrat/i,"Integration"],[/field|info|propert|detail|contain/i,"Item shape"],[/view|layout|board|grid|list|timeline/i,"View"],[/scope|how many|one.*or.*many|multi/i,"Scope"],[/share|read.?only|viewer|stakeholder/i,"Sharing"],[/workflow|status|state|move|stage|pipeline/i,"Workflow"],[/avoid|bloat|simple|complex|minimal/i,"Constraints"],[/time.*period|quarter|month|sprint/i,"Time periods"],[/swimlane|column|group|categor/i,"Structure"]];for(let[n,i]of e)if(n.test(t))return i;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(n=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(n.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function mc(t){let e=fe(ct(),".mistflow","plans",`${t}.json`);if(!Je(e))return null;try{return JSON.parse(pn(e,"utf-8")).plan??null}catch{return null}}async function hc(t){let e=Date.now(),r=5e4,n=2e3;for(;Date.now()-e<r;){try{let i=await Cn(t.design_conversation_id);if(i.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:i.directions,plan:i.plan,methodology:i.methodology};if(i.status==="failed")return{status:"ready",plan:i.plan,methodology:i.methodology}}catch(i){let o=i instanceof Error?i.message:String(i);if(o.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll failed: ${o}`)}await new Promise(i=>setTimeout(i,n))}return console.error("[plan] directions poll exhausted (50s) \u2014 preserving pending so host re-polls"),t}function gc(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function fc(t,e){for(let r of e){let n=gc(t[r]);if(n)return n}}function yc(t){return fc(t,["mockup_url","mockupUrl","preview_url","previewUrl","live_url","liveUrl","deploy_url","deployUrl","url"])}function Po(t,e){return`Next action: call ${t} with ${JSON.stringify(e)}. Do not omit sessionId.`}function bc(t){let e=yc(t),r=t.reason?`
|
|
2045
2045
|
Reason: ${t.reason}`:"";switch(t.state){case"COMPLETE":return`Session complete.${e?` Live URL: ${e}`:""}${r}`;case"CANCELLED":return`Session was cancelled.${r}`;case"FAILED":return`Session ended in FAILED.${e?` Last known URL: ${e}`:""}${r}`;case"ABANDONED":return`Session was abandoned.${r}`;case"EXPIRED":return`Session expired.${r}`;default:return`Session finished with state ${t.state}.${e?` URL: ${e}`:""}${r}`}}async function wc(t,e){let{description:r,projectPath:n,sessionId:i,conversationId:o,answers:s,existingPlan:a,existingPlanId:l,templateToken:c,remixDescription:u,autonomous:h,language:d,brandMentioned:v,confirmToken:H,urlChoice:_,designConversationId:k,designDirection:y,userConfirmedCustom:C,forceNew:B}=t;if(i&&!o&&!k)try{let m=await Nt(i),g=[`Session ID: ${m.session_id}`,`Status: ${m.status??"active"}`,`Instruction: ${m.instruction}`];switch(m.reason&&g.push(`Reason: ${m.reason}`),m.instruction){case"wait":return p([...g,`Next action: ${m.reason??"The backend is still preparing the next step."} Tell the user briefly what's happening, then call mist_plan with { projectPath, sessionId: "${m.session_id}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`].join(`
|
|
2046
2046
|
`));case"resume_conversation":{let w=m.conversation_id;return p([...g,`In-flight conversation: ${w??"(missing \u2014 backend bug)"}`,`Next action: call mist_plan with { projectPath, conversationId: "${w??""}" } to continue the plan flow. The conversation poll renders questions / design directions in the same way it would have on the original mist_plan response.`].join(`
|
|
2047
2047
|
`))}case"continue":return p([...g,`Next action: ${m.reason??"Continue from where you left off \u2014 read mistflow.json to find the next pending step, then call mist_install / mist_implement / mist_build / mist_deploy as appropriate."}`].join(`
|
|
@@ -2056,10 +2056,10 @@ Reason: ${t.reason}`:"";switch(t.state){case"COMPLETE":return`Session complete.$
|
|
|
2056
2056
|
|
|
2057
2057
|
You're inside \`${n}\` which has a \`package.json\`. Mistflow will create a NEW app in a subdirectory \u2014 it won't modify the existing code.
|
|
2058
2058
|
|
|
2059
|
-
Default path: \`${w}\``,"scope");if($.outcome==="submitted"){let se=$.answers?.[0]?.answer??"",ae=se.toLowerCase(),oe=se.startsWith("/")?se:null;if(oe||ae.startsWith("create at:")||ae.startsWith("choose a different path")){let M=oe||(ae.startsWith("choose a different path")?null:w);if(!M)return p("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);F=M;let K=_o(F);if(K)return p(`Mistflow could not create the scaffold directory at ${F}: ${K}`,!0);Y=`Note: Mistflow will scaffold the new app at \`${F}\`. The existing project at \`${n}\` is not modified.`}else return ae.startsWith("cancel")?p("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(`User submitted an unrecognized scope choice: ${se}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return $.outcome==="declined"?p("User declined the scope confirmation. They wanted to edit the existing project, not create a new Mistflow app. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(Io({projectPath:n,description:z,confirmToken:N,suggestedPath:w,previousTokenInvalid:!!H}))}else return p(Io({projectPath:n,description:z,confirmToken:N,suggestedPath:w,previousTokenInvalid:!!H}))}}}if(c)try{if(!(await Mr(c)).plan)return p("This template has no plan to fork. Try a different template.",!0);let g=await Lr(c),w=g.plan,T="";if(u&&g.has_source)try{let K=await On(g.plan,u),be=K.plan??K,ne=K.diff,le=be?.steps??[],xe=new Set([...(ne?.added??[]).map(f=>f.number),...(ne?.modified??[]).map(f=>f.number)]),pe=le.map(f=>{let R=f.number;return xe.has(R)?{...f,status:"pending"}:{...f,status:"completed",source:"forked"}});be.steps=pe,w=be;let P=pe.filter(f=>f.status==="pending").length;T=` Remixed: ${pe.filter(f=>f.status==="completed").length} steps unchanged, ${P} steps need re-implementation.`}catch(K){console.error("[plan] Remix failed, using original plan:",K),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let N=So(),$=fe(ct(),".mistflow","plans");xt($,{recursive:!0}),lt(fe($,`${N}.json`),JSON.stringify({plan:w,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let se=w?.name??"forked-app",ae=g.has_source,oe=ae?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",M=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return p(JSON.stringify({planId:N,forkedFrom:g.forked_from,projectId:g.id,hasSource:ae,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${T}${M} ${oe} NEXT: Call mist_init, name='${se}', and planId='${N}' to create the project now.`}))}catch(m){let g=m instanceof Error?m.message:"Failed to fork template";return p(g,!0)}if(te){let m;if(n){let M=fe(n,"PLAN.md");if(Je(M))try{m=pn(M,"utf-8")}catch(K){console.error(`[mist_plan:modify] PLAN.md read failed (${M}): ${K instanceof Error?K.message:String(K)}`)}}let g;try{g=await On(te,z,{planMd:m})}catch(M){let K=M instanceof Error?M.message:"Failed to modify plan";return p(K,!0)}let w=g.plan,T=g.diff,N=typeof g.plan_md=="string"?g.plan_md:null,$,se;if(N&&n)try{let M=fe(n,"PLAN.md");lt(M,N,"utf-8"),$=M}catch(M){se=M instanceof Error?M.message:String(M)}let ae=[];if(T?.added?.length){let M=T.added.map(K=>K.title);ae.push(`Added ${M.length} step(s): ${M.join(", ")}`)}if(T?.removed?.length){let M=T.removed.map(K=>K.title);ae.push(`Removed ${M.length} step(s): ${M.join(", ")}`)}if(T?.modified?.length){let M=T.modified.map(K=>K.title);ae.push(`Modified ${M.length} step(s): ${M.join(", ")}`)}let oe=ae.length>0?ae.join(". "):"No changes detected.";return p(JSON.stringify({plan:w,diff:T,planMdPath:$,planMdError:se,message:`Plan modified. ${oe}. Update mistflow.json with the new plan${$?"; PLAN.md has been regenerated at "+$:""}, then continue with mist_implement.`}))}let I=_?.trim()||void 0,re=s;if(Array.isArray(s)){let m=s.findIndex(g=>g&&typeof g=="object"&&g.decisionKey==="urlChoice");if(m>=0){let g=s[m];!I&&g.answer&&(I=g.answer);let w=s.slice(0,m).concat(s.slice(m+1));re=w.length>0?w:void 0}}else if(s!=null){let m=s;if(!I&&Gn in m&&(I=m[Gn]),!I&&"urlChoice"in m&&(I=m.urlChoice),Gn in m||"urlChoice"in m){let{[Gn]:g,urlChoice:w,...T}=m;re=Object.keys(T).length>0?T:void 0}}if(I&&(I=I.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),I){let m=I.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(m)?I=m:(console.error(`[mist_plan] Discarding urlChoice '${I}' \u2014 does not look like a subdomain. Backend will auto-generate.`),I=void 0)}let q;if(y){q={...y},delete q.userConfirmedCustom,delete q.user_confirmed_custom;let m={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,w]of Object.entries(m))y[g]!==void 0&&q[w]===void 0&&(q[w]=y[g])}let b=q!==void 0&&typeof q.custom=="string"&&!q.id&&!q.name,U=C===!0||y!==void 0&&(y.userConfirmedCustom===!0||y.user_confirmed_custom===!0);if(b&&k)try{let m=await Cn(k);if(m.status==="pending")return p(`Refusing to submit a custom design direction: the backend's direction-generation BG task is still running (status: pending). The user has not yet had the chance to see the real directions. Stop asking the user about aesthetic / fonts / colors / mood right now \u2014 the backend will produce 3-4 concrete options shortly. Re-call mist_plan with { projectPath, conversationId, designConversationId: '${k}' } to keep polling. When directions are ready (status: 'design_clarify'), surface them to the user via AskUserQuestion. Custom is only legitimate AFTER the user has seen the real options and explicitly rejected them \u2014 never as a workaround for a slow generation run.`,!0);if(m.status==="ready"&&Array.isArray(m.directions)&&m.directions.length>0&&!U){let g=m.directions.map(w=>w.name).join(", ");return p(`Refusing to submit a custom design direction: the backend has ${m.directions.length} real directions ready (${g}). The picker is mandatory \u2014 you must surface those exact directions to the user via AskUserQuestion before submitting any pick. Re-call mist_plan with { conversationId, designConversationId: '${k}' } to get the picker payload (status: 'design_clarify'), render the directions HTML preview at .mistflow/design-directions.html for the user, then submit the user's choice. If the user opens the preview, sees the ${m.directions.length} directions, rejects all of them, and types their own description, ONLY THEN retry this call with userConfirmedCustom: true. Never set userConfirmedCustom: true without first showing the user the real directions.`,!0)}}catch(m){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${m instanceof Error?m.message:String(m)}`)}let G=s?"Generating plan with your answers (LLM call)":k?"Finalizing design direction":"Thinking through discovery questions",D=e?$e(e.server,e.progressToken,()=>G):{stop:()=>{}};if(e&&(e.cleanup=()=>D.stop()),!i&&!o&&!k&&!a&&!l&&!c&&!H&&z.trim().length>0&&!B)try{let m=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),g=336*60*60*1e3,w=Date.now()-g,N=(await nn(xo())).filter($=>!m.has($.state)).filter($=>{let se=Date.parse($.updated_at);return Number.isFinite(se)&&se>=w}).sort(($,se)=>Date.parse(se.updated_at)-Date.parse($.updated_at)).slice(0,5);if(N.length>0)return D.stop(),p(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:N.map($=>({sessionId:$.id,state:$.state,description:$.description,currentStep:$.current_step,awaitingInput:$.awaiting_input,updatedAt:$.updated_at})),instruction:"This machine has unfinished Mistflow build(s) in flight. Before starting a new project, ask the user whether they want to resume one of these or start fresh. Show the description, state, and updatedAt for each candidate so they can pick.",nextAction:"Step 1: Show the candidates to the user via your host's question UI (AskUserQuestion in Claude Code, request_user_input in Codex Plan mode, quick pick in Cursor). Step 2a (resume): if they pick a candidate, call mist_session({ action: 'resume', sessionId: '<picked>', projectPath }) and follow the next instruction it returns. Step 2b (start fresh): if they want a new build, call mist_plan again with the SAME description and projectPath, plus forceNew: true. The forceNew flag suppresses this check so the new session can be minted."}))}catch(m){console.error("resume-offer check failed (falling through to bootstrap):",m instanceof Error?m.message:m)}let ee=i,A;try{Z&&!re&&!k&&!te&&!l?A=await En(Z):A=await Nn(z,{conversationId:Z,answers:re,autonomous:h,language:d,designConversationId:k,designDirection:q})}catch(m){D.stop();let g=m instanceof Error?m.message:"Failed to generate plan";return p(g,!0)}let he=A.session_id;if(!ee&&he){ee=he;try{await tn(he,{machine_id:xo(),local_path:n})}catch(m){console.error("workspace bind failed (resume offers will miss this session):",m instanceof Error?m.message:m)}}if(A.status==="clarify_pending"){D.stop();let m=A;return p(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:ee,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${m.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.${ee?` Carry sessionId="${ee}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(A.status==="plan_pending"){D.stop();let m=A;return p(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:ee,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(A.status==="design_clarify_pending"&&(G="Generating creative design directions",A=await hc(A)),A.status==="design_clarify_pending")return D.stop(),p(JSON.stringify({status:"running",conversationId:o,designConversationId:A.design_conversation_id,sessionId:ee,phase:"generating_design_directions",nextAction:`Creative design directions are still generating (45-60s typical, can stretch on slow runs). Call mist_plan with { projectPath, conversationId: "${o??""}" } IMMEDIATELY to keep polling \u2014 do NOT run bash sleep, do NOT submit a designDirection of your own, do NOT mark the plan as ready, and DO NOT ASK THE USER about aesthetic / fonts / colors / mood / vibe / style while you wait. The backend is generating 3-4 concrete direction options the user will pick from \u2014 asking the user to invent one defeats the entire feature, and the server will reject any { custom } submission while directions are still pending. Just poll. The picker is mandatory; keep polling until status becomes 'design_clarify' with the directions array, then surface those exact directions to the user via AskUserQuestion.`}));if(D.stop(),A.status==="clarify"){let m=A.reflection||"",g=A.suggestedName||"",w=A.suggestedFeatures??[],T=A.questions??[],N=T.some(ne=>Array.isArray(ne.options)&&typeof ne.options[0]=="object"&&ne.options[0]?.label),$={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"},se=T.map(ne=>{let le=ne.decisionKey&&$[ne.decisionKey]||uc(ne.question),xe;return N&&Array.isArray(ne.options)?xe=ne.options.map(pe=>({label:pe.label,description:pe.description??""})):Array.isArray(ne.options)?xe=ne.options.map((pe,P)=>({label:P===0?`${pe} (Recommended)`:String(pe),description:ne.why??""})):xe=[{label:"Yes (Recommended)",description:ne.why??""},{label:"No",description:""}],{question:ne.question,header:le,options:xe,multiSelect:!1}}),oe=A.decisions?.audienceType??null,M=w.length>0?vo(z,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:oe,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:w,language:d}):null,K=M?ko(M):"",be=Hn(g||"my-app").slice(0,32);try{let ne=await Pn(be);!ne.available&&ne.suggestion&&(be=ne.suggestion)}catch{}if(K&&(K+=`
|
|
2059
|
+
Default path: \`${w}\``,"scope");if($.outcome==="submitted"){let se=$.answers?.[0]?.answer??"",ae=se.toLowerCase(),oe=se.startsWith("/")?se:null;if(oe||ae.startsWith("create at:")||ae.startsWith("choose a different path")){let M=oe||(ae.startsWith("choose a different path")?null:w);if(!M)return p("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);F=M;let K=_o(F);if(K)return p(`Mistflow could not create the scaffold directory at ${F}: ${K}`,!0);Y=`Note: Mistflow will scaffold the new app at \`${F}\`. The existing project at \`${n}\` is not modified.`}else return ae.startsWith("cancel")?p("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(`User submitted an unrecognized scope choice: ${se}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return $.outcome==="declined"?p("User declined the scope confirmation. They wanted to edit the existing project, not create a new Mistflow app. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):p(Io({projectPath:n,description:z,confirmToken:N,suggestedPath:w,previousTokenInvalid:!!H}))}else return p(Io({projectPath:n,description:z,confirmToken:N,suggestedPath:w,previousTokenInvalid:!!H}))}}}if(c)try{if(!(await Mr(c)).plan)return p("This template has no plan to fork. Try a different template.",!0);let g=await Lr(c),w=g.plan,T="";if(u&&g.has_source)try{let K=await On(g.plan,u),be=K.plan??K,ne=K.diff,le=be?.steps??[],xe=new Set([...(ne?.added??[]).map(f=>f.number),...(ne?.modified??[]).map(f=>f.number)]),pe=le.map(f=>{let R=f.number;return xe.has(R)?{...f,status:"pending"}:{...f,status:"completed",source:"forked"}});be.steps=pe,w=be;let P=pe.filter(f=>f.status==="pending").length;T=` Remixed: ${pe.filter(f=>f.status==="completed").length} steps unchanged, ${P} steps need re-implementation.`}catch(K){console.error("[plan] Remix failed, using original plan:",K),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let N=So(),$=fe(ct(),".mistflow","plans");xt($,{recursive:!0}),lt(fe($,`${N}.json`),JSON.stringify({plan:w,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let se=w?.name??"forked-app",ae=g.has_source,oe=ae?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",M=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return p(JSON.stringify({planId:N,forkedFrom:g.forked_from,projectId:g.id,hasSource:ae,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${T}${M} ${oe} NEXT: Call mist_init, name='${se}', and planId='${N}' to create the project now.`}))}catch(m){let g=m instanceof Error?m.message:"Failed to fork template";return p(g,!0)}if(te){let m;if(n){let M=fe(n,"PLAN.md");if(Je(M))try{m=pn(M,"utf-8")}catch(K){console.error(`[mist_plan:modify] PLAN.md read failed (${M}): ${K instanceof Error?K.message:String(K)}`)}}let g;try{g=await On(te,z,{planMd:m})}catch(M){let K=M instanceof Error?M.message:"Failed to modify plan";return p(K,!0)}let w=g.plan,T=g.diff,N=typeof g.plan_md=="string"?g.plan_md:null,$,se;if(N&&n)try{let M=fe(n,"PLAN.md");lt(M,N,"utf-8"),$=M}catch(M){se=M instanceof Error?M.message:String(M)}let ae=[];if(T?.added?.length){let M=T.added.map(K=>K.title);ae.push(`Added ${M.length} step(s): ${M.join(", ")}`)}if(T?.removed?.length){let M=T.removed.map(K=>K.title);ae.push(`Removed ${M.length} step(s): ${M.join(", ")}`)}if(T?.modified?.length){let M=T.modified.map(K=>K.title);ae.push(`Modified ${M.length} step(s): ${M.join(", ")}`)}let oe=ae.length>0?ae.join(". "):"No changes detected.";return p(JSON.stringify({plan:w,diff:T,planMdPath:$,planMdError:se,message:`Plan modified. ${oe}. Update mistflow.json with the new plan${$?"; PLAN.md has been regenerated at "+$:""}, then continue with mist_implement.`}))}let I=_?.trim()||void 0,re=s;if(Array.isArray(s)){let m=s.findIndex(g=>g&&typeof g=="object"&&g.decisionKey==="urlChoice");if(m>=0){let g=s[m];!I&&g.answer&&(I=g.answer);let w=s.slice(0,m).concat(s.slice(m+1));re=w.length>0?w:void 0}}else if(s!=null){let m=s;if(!I&&Gn in m&&(I=m[Gn]),!I&&"urlChoice"in m&&(I=m.urlChoice),Gn in m||"urlChoice"in m){let{[Gn]:g,urlChoice:w,...T}=m;re=Object.keys(T).length>0?T:void 0}}if(I&&(I=I.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),I){let m=I.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(m)?I=m:(console.error(`[mist_plan] Discarding urlChoice '${I}' \u2014 does not look like a subdomain. Backend will auto-generate.`),I=void 0)}let q;if(y){q={...y},delete q.userConfirmedCustom,delete q.user_confirmed_custom;let m={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,w]of Object.entries(m))y[g]!==void 0&&q[w]===void 0&&(q[w]=y[g])}let b=q!==void 0&&typeof q.custom=="string"&&!q.id&&!q.name,U=C===!0||y!==void 0&&(y.userConfirmedCustom===!0||y.user_confirmed_custom===!0);if(b&&k)try{let m=await Cn(k);if(m.status==="pending")return p(`Refusing to submit a custom design direction: the backend's direction-generation BG task is still running (status: pending). The user has not yet had the chance to see the real directions. Stop asking the user about aesthetic / fonts / colors / mood right now \u2014 the backend will produce 3-4 concrete options shortly. Re-call mist_plan with { projectPath, conversationId, designConversationId: '${k}' } to keep polling. When directions are ready (status: 'design_clarify'), surface them to the user via AskUserQuestion. Custom is only legitimate AFTER the user has seen the real options and explicitly rejected them \u2014 never as a workaround for a slow generation run.`,!0);if(m.status==="ready"&&Array.isArray(m.directions)&&m.directions.length>0&&!U){let g=m.directions.map(w=>w.name).join(", ");return p(`Refusing to submit a custom design direction: the backend has ${m.directions.length} real directions ready (${g}). The picker is mandatory \u2014 you must surface those exact directions to the user via AskUserQuestion before submitting any pick. Re-call mist_plan with { conversationId, designConversationId: '${k}' } to get the picker payload (status: 'design_clarify'), render the directions HTML preview at .mistflow/design-directions.html for the user, then submit the user's choice. If the user opens the preview, sees the ${m.directions.length} directions, rejects all of them, and types their own description, ONLY THEN retry this call with userConfirmedCustom: true. Never set userConfirmedCustom: true without first showing the user the real directions.`,!0)}}catch(m){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${m instanceof Error?m.message:String(m)}`)}let G=s?"Generating plan with your answers (LLM call)":k?"Finalizing design direction":"Thinking through discovery questions",j=e?$e(e.server,e.progressToken,()=>G):{stop:()=>{}};if(e&&(e.cleanup=()=>j.stop()),!i&&!o&&!k&&!a&&!l&&!c&&!H&&z.trim().length>0&&!B)try{let m=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),g=336*60*60*1e3,w=Date.now()-g,N=(await nn(xo())).filter($=>!m.has($.state)).filter($=>{let se=Date.parse($.updated_at);return Number.isFinite(se)&&se>=w}).sort(($,se)=>Date.parse(se.updated_at)-Date.parse($.updated_at)).slice(0,5);if(N.length>0)return j.stop(),p(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:N.map($=>({sessionId:$.id,state:$.state,description:$.description,currentStep:$.current_step,awaitingInput:$.awaiting_input,updatedAt:$.updated_at})),instruction:"This machine has unfinished Mistflow build(s) in flight. Before starting a new project, ask the user whether they want to resume one of these or start fresh. Show the description, state, and updatedAt for each candidate so they can pick.",nextAction:"Step 1: Show the candidates to the user via your host's question UI (AskUserQuestion in Claude Code, request_user_input in Codex Plan mode, quick pick in Cursor). Step 2a (resume): if they pick a candidate, call mist_session({ action: 'resume', sessionId: '<picked>', projectPath }) and follow the next instruction it returns. Step 2b (start fresh): if they want a new build, call mist_plan again with the SAME description and projectPath, plus forceNew: true. The forceNew flag suppresses this check so the new session can be minted."}))}catch(m){console.error("resume-offer check failed (falling through to bootstrap):",m instanceof Error?m.message:m)}let ee=i,A;try{Z&&!re&&!k&&!te&&!l?A=await En(Z):A=await Nn(z,{conversationId:Z,answers:re,autonomous:h,language:d,designConversationId:k,designDirection:q})}catch(m){j.stop();let g=m instanceof Error?m.message:"Failed to generate plan";return p(g,!0)}let he=A.session_id;if(!ee&&he){ee=he;try{await tn(he,{machine_id:xo(),local_path:n})}catch(m){console.error("workspace bind failed (resume offers will miss this session):",m instanceof Error?m.message:m)}}if(A.status==="clarify_pending"){j.stop();let m=A;return p(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:ee,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${m.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.${ee?` Carry sessionId="${ee}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(A.status==="plan_pending"){j.stop();let m=A;return p(JSON.stringify({status:"running",conversationId:m.conversation_id,sessionId:ee,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(A.status==="design_clarify_pending"&&(G="Generating creative design directions",A=await hc(A)),A.status==="design_clarify_pending")return j.stop(),p(JSON.stringify({status:"running",conversationId:o,designConversationId:A.design_conversation_id,sessionId:ee,phase:"generating_design_directions",nextAction:`Creative design directions are still generating (45-60s typical, can stretch on slow runs). Call mist_plan with { projectPath, conversationId: "${o??""}" } IMMEDIATELY to keep polling \u2014 do NOT run bash sleep, do NOT submit a designDirection of your own, do NOT mark the plan as ready, and DO NOT ASK THE USER about aesthetic / fonts / colors / mood / vibe / style while you wait. The backend is generating 3-4 concrete direction options the user will pick from \u2014 asking the user to invent one defeats the entire feature, and the server will reject any { custom } submission while directions are still pending. Just poll. The picker is mandatory; keep polling until status becomes 'design_clarify' with the directions array, then surface those exact directions to the user via AskUserQuestion.`}));if(j.stop(),A.status==="clarify"){let m=A.reflection||"",g=A.suggestedName||"",w=A.suggestedFeatures??[],T=A.questions??[],N=T.some(ne=>Array.isArray(ne.options)&&typeof ne.options[0]=="object"&&ne.options[0]?.label),$={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"},se=T.map(ne=>{let le=ne.decisionKey&&$[ne.decisionKey]||uc(ne.question),xe;return N&&Array.isArray(ne.options)?xe=ne.options.map(pe=>({label:pe.label,description:pe.description??""})):Array.isArray(ne.options)?xe=ne.options.map((pe,P)=>({label:P===0?`${pe} (Recommended)`:String(pe),description:ne.why??""})):xe=[{label:"Yes (Recommended)",description:ne.why??""},{label:"No",description:""}],{question:ne.question,header:le,options:xe,multiSelect:!1}}),oe=A.decisions?.audienceType??null,M=w.length>0?vo(z,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:oe,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:w,language:d}):null,K=M?ko(M):"",be=Hn(g||"my-app").slice(0,32);try{let ne=await Pn(be);!ne.available&&ne.suggestion&&(be=ne.suggestion)}catch{}if(K&&(K+=`
|
|
2060
2060
|
|
|
2061
2061
|
**Your app URL (you can change this before scaffolding):** https://${be}.mistflow.app`),e?.server){let ne=[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(`
|
|
2062
|
-
`),le=await cn(e.server,T,ne,"clarify");if(le.outcome==="submitted"){
|
|
2062
|
+
`),le=await cn(e.server,T,ne,"clarify");if(le.outcome==="submitted"){j.stop();let xe={};for(let P of le.answers??[])P.decisionKey?xe[P.decisionKey]=P.answer:xe[P.question]=P.answer;let pe=le.urlChoice?.trim();pe&&(pe=pe.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let P=await Nn(z,{conversationId:A.conversation_id,answers:xe,autonomous:h,language:d});if(P.status==="plan_pending"){let ve=P;return p(JSON.stringify({status:"running",conversationId:ve.conversation_id,phase:"generating_plan",...pe?{urlChoice:pe}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${ve.conversation_id}"${pe?`, urlChoice: "${pe}"`:""} } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll up to ~10s and returns when the plan lands. Pass urlChoice on every poll so it threads through to the saved plan.`}))}A=P}catch(P){let ve=P instanceof Error?P.message:String(P);return p(`Submitting your answers failed: ${ve}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(le.outcome==="declined")return j.stop(),p("User declined the planning flow via the form. They likely want a different approach \u2014 ask them what they'd prefer instead of re-running mist_plan.",!0);if(le.outcome==="cancelled")return j.stop(),p("User cancelled the planning form without picking. The conversation is still alive \u2014 re-run mist_plan with the same conversationId if they want to retry, or start a fresh plan if they want to change the description.",!0);le.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${le.errorMessage}) \u2014 falling back to prose flow.`)}}return p(JSON.stringify({status:"clarify",requires_user_input:!0,nextAction:"STOP \u2014 DO NOT submit answers yourself. Render every entry in `askUserQuestions` via your host's native question tool (AskUserQuestion in Claude Code, request_user_input in OpenAI Codex Plan mode, quick pick in Cursor) and WAIT for the user to actually answer. If your host has no native question tool, stop your turn, print the questions verbatim as a numbered list with all options visible, and wait for the user's next message. Calling mist_plan with answers in the same turn you received the questions is ALWAYS wrong, regardless of how obvious `recommended` looks.",conversation_id:A.conversation_id,questions:T,questionCount:T.length,suggestedFeatures:w,suggestedName:g,suggestedSubdomain:be,reflection:m,briefText:K,askUserQuestions:se,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: "${A.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${be}".`,'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.',...m||K?["","\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",...m?[m]:[],...K?["",K]:[]]:[],...Y?["",Y]:[]].join(`
|
|
2063
2063
|
`)}))}if(A.status==="design_clarify"){let m=A.directions??[],g=A.plan.name??"your app",w=A.design_conversation_id,T=m.map(S=>({id:S.id,name:S.name,summary:S.summary,hero_headline:S.hero_headline,cta_text:S.cta_text,body_sample:S.body_sample,fonts:S.fonts,colors:S.colors,hero_treatment:S.hero_treatment,shape_lang:S.shape_lang,texture:S.texture,decoration_hint:S.decoration_hint})),N={},$=!1;try{if(w){let ue=Date.now();for(;Date.now()-ue<5e4;){let X=await Rn(w),J=0;for(let x of T){let O=X[x.id];O&&((O.status==="done"||O.status==="ready")&&typeof O.html=="string"&&O.html.length>0?(N[x.id]=O.html,J+=1):O.status==="failed"&&(J+=1))}if(J===T.length){$=!0;break}await new Promise(x=>setTimeout(x,5e3))}}}catch(S){console.error(`[mist_plan:design_clarify] render poll failed: ${S instanceof Error?S.message:String(S)}`)}if(!$)return p(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:A.conversation_id??o,design_conversation_id:w,renderedSoFar:Object.keys(N).length,totalDirections:T.length,nextAction:`${Object.keys(N).length}/${T.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${A.conversation_id??o??""}" } again IMMEDIATELY \u2014 do NOT bash sleep. Do NOT ask the user about design yet.`}));let se=T.filter(S=>N[S.id]),ae,oe,M=fe(n,".mistflow"),K=fe(M,"design-directions.html"),be=fe(M,"picker-state.json"),ne=()=>{try{if(Je(be))return JSON.parse(pn(be,"utf-8"))}catch{}return{}},le=S=>{try{xt(M,{recursive:!0}),lt(be,JSON.stringify(S,null,2),"utf-8")}catch(ce){console.error(`[mist_plan:design_clarify] sidecar write failed: ${ce instanceof Error?ce.message:String(ce)}`)}},xe=ne(),pe=w&&xe.opened_for_design_cid===w;try{if(xt(M,{recursive:!0}),pe)ae=K;else{let S=Xr(g,se,N);lt(K,S,"utf-8"),ae=K;let ce=Qr(`file://${K}`);ce.opened||(oe=ce.reason),w&&le({opened_for_design_cid:w,elicit_state:"pending",elicit_design_cid:w,opened_at:new Date().toISOString()})}}catch(S){console.error(`[mist_plan:design_clarify] picker write/open failed: ${S instanceof Error?S.message:String(S)}`)}let P=ne(),ve=se.map(S=>({id:S.id,name:S.name})),f=ve.map(S=>S.name).filter(Boolean);if(e?.server&&w&&P.elicit_design_cid===w&&P.elicit_state==="pending"){let S=ae?[`## ${g} \u2014 pick a creative direction`,"",`${se.length} directions, each with its own fonts, colors, and mood.`,"",`Visual preview (auto-opened in your browser): file://${ae}`,"Each card shows what you'd be picking \u2014 fonts, colors, hero layout."].join(`
|
|
2064
2064
|
`):`## ${g} \u2014 pick a creative direction
|
|
2065
2065
|
|
|
@@ -2069,8 +2069,8 @@ ${se.length} directions, each with its own fonts, colors, and mood. Pick one or
|
|
|
2069
2069
|
|
|
2070
2070
|
`)}))}if(A.status!=="ready")return p(`Unexpected plan status after build: ${A.status}. Please retry by calling mist_plan with the same conversationId.`,!0);let V=A.plan,ie=V.name??"Untitled App",Ee=A.methodology,we=V.steps;if(!Array.isArray(we)||we.length===0)return p("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let ye=V.suggestedSubdomain??Hn(ie).slice(0,32)??"my-app";if(!I&&e?.server){try{let g=await Pn(ye);!g.available&&g.suggestion&&(ye=g.suggestion)}catch{}let m=await cn(e.server,[{question:"Your app URL \u2014 last decision before scaffolding",decisionKey:"urlChoice",recommended:`Keep ${ye}.mistflow.app`,why:"Subdomains lock in at scaffold time and are baked into auth callbacks, share links, and analytics. Pick the default to ship now, or type a custom subdomain in the textbox below.",options:[{label:`Keep ${ye}.mistflow.app`,description:"Use the suggested subdomain"},{label:"Type a different subdomain",description:"Custom subdomain \u2014 fill the textbox below"}],noOtherSentinel:!0,otherFieldTitle:"Custom subdomain (e.g. 'sales-comm') \u2014 lowercase, alphanumeric + hyphens, 3-32 chars"}],`## ${ie} \u2014 pick the URL
|
|
2071
2071
|
|
|
2072
|
-
The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(m.outcome==="submitted"){let g=m.urlChoice?.trim()||m.answers?.[0]?.answer.trim()||"";g=g.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(g)||!g)&&(g=ye);let w=g.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(w)?I=w:(console.error(`[mist_plan] URL elicitation returned '${g}' \u2014 does not look like a subdomain. Using default '${ye}'.`),I=ye)}else m.outcome==="declined"||m.outcome,I=ye}else I||(I=ye);let De=V.publicPages;if(!De||Array.isArray(De)&&De.length===0){let m=V.pages,g=we.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),w=Array.isArray(m)&&m.some(T=>T.path==="/"||T.route==="/");g||w?De=["/","/pricing"]:De=["/"]}let It=V.primaryAction;if(!It){let m=V.features;if(Array.isArray(m)&&m.length>0){let w=m.find(N=>typeof N.priority=="string"&&N.priority.toLowerCase()==="must-have")??m[0];It={entity:w.name??w.title??"item",action:"create",fromPage:"/dashboard"}}}let We=V.nonNegotiables;(!We||Array.isArray(We)&&We.length===0)&&(We=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Be=So(),Ze=fe(ct(),".mistflow","plans");xt(Ze,{recursive:!0});try{let g=Date.now();for(let w of[Ze,fe(ct(),".mistflow","mockup-state")])if(Je(w))for(let T of Co(w))try{let N=fe(w,T),$=Ao(N).mtimeMs;g-$>6048e5&&Ql(N)}catch{}}catch{}let Ie=V,Q={name:V.name,summary:V.summary,dataModel:V.dataModel,pages:V.pages,features:V.features,steps:we.map(m=>({...m,name:m.name??m.title})),design:V.design,dbProvider:V.dbProvider??"neon",authModel:V.authModel,audienceType:V.audienceType??"b2c",roles:V.roles,defaultRole:V.defaultRole,publicPages:De,navStyle:V.navStyle,multiTenant:V.multiTenant,primaryAction:It,nonNegotiables:We,requestedSubdomain:I,...d&&d.toLowerCase()!=="english"?{language:d}:{},...Ie.pickedDirection?{pickedDirection:Ie.pickedDirection}:{},...Ie.imageryBrief?{imageryBrief:Ie.imageryBrief}:{},...Ie.designConversationId?{designConversationId:Ie.designConversationId}:{}};lt(fe(Ze,`${Be}.json`),JSON.stringify({plan:Q,methodology:Ee,...F?{scaffoldTargetPath:F}:{}}));let ge=we.map(m=>`${m.number}. ${m.name??m.title}`),Ne,et="";if(!!!Ie.pickedDirection){let g=(V.audienceType??"b2c")==="b2c";Ne={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:g?"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:g?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},et=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call."}let tt="",ze=[];for(let m of we){let g=m.name??m.title,w=m.integrationId;if(w){let T=jt(w);if(T){let N=Dt(T.id);ze.push({step:g,presetId:T.id,presetName:T.name,envVars:N?.envVars??[]})}}}if(ze.length>0){let m=ze.flatMap(T=>T.envVars),g=[...new Set(m.map(T=>T.key))];tt=` This plan uses integrations (${ze.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 p(JSON.stringify({planId:Be,name:V.name,summary:V.summary,stepCount:we.length,steps:ge,design:V.design,...Ne?{heroPhotoQuestion:Ne}:{},...ze.length>0?{integrations:ze.map(m=>({step:m.step,preset:m.presetId,name:m.presetName,envVars:m.envVars}))}:{},message:`Plan generated for "${ie}" (${we.length} steps).${tt}${et}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,we.length*3)}\u2013${we.length*5} minutes total across ${we.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: '${Be}' }). If the user says skip or "just build it", call mist_init({ planId: '${Be}'${F?"":", path: '<absolute path>'"} }) immediately.`,...F?{scaffoldTargetPath:F}:{},...Y?{warning:Y}:{}}))}var Oo={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist'). Clear new-app requests inside an existing non-Mistflow repo are scaffolded into a remembered child directory; Mistflow does not edit the surrounding codebase.","",`DESIGN REFERENCES (screenshots, Figma, brand names): if the user drags a screenshot, pastes a Figma URL, or names a brand to match ("make it feel like Linear"), use your native vision/knowledge to extract design tokens and submit them via designDirection: { custom: '<your description>', ...extracted_tokens } with userConfirmedCustom: true. The flag is required because the user supplied the reference; without it the server rejects the submission to stop AIs from inventing custom directions. Full flow at docs/design-references.md.`,"","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). For clear new-app requests it automatically creates and remembers a child scaffold directory. For ambiguous requests, it returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token from the response. Do not change projectPath to the suggested child path; Mistflow stores that target for mist_init.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_init with the returned planId. If the response includes scaffoldTargetPath you do not need to pass path; mist_init loads it from the cached plan. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","SESSIONID FLOW (dumb-ai-proof, when the response includes sessionId): keep the sessionId and pass it on every subsequent mist_* call. Calling mist_plan with just { sessionId, projectPath } polls GET /api/sessions/{id}/next and returns the next instruction (wait | ask_user | pick_design | review_mockup | call_mist_init | call_mist_install | call_mist_implement | call_mist_build | call_mist_deploy | call_mist_qa | done). Do exactly what the instruction says \u2014 don't branch on raw state. The backend owns routing; the host relays.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. The aesthetic (fonts, colors, motion) is decided by the design-direction picker step \u2014 the host AI doesn't pick a catalog ID."].join(`
|
|
2073
|
-
`),inputSchema:pc,handler:wc};import{z as Ft}from"zod";import{existsSync as Re,mkdirSync as qt,rmSync as Nc,writeFileSync as Ye,readFileSync as Bt,readdirSync as qo,copyFileSync as Oc}from"fs";import{join as me,resolve as Bo,dirname as un,isAbsolute as
|
|
2072
|
+
The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(m.outcome==="submitted"){let g=m.urlChoice?.trim()||m.answers?.[0]?.answer.trim()||"";g=g.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(g)||!g)&&(g=ye);let w=g.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(w)?I=w:(console.error(`[mist_plan] URL elicitation returned '${g}' \u2014 does not look like a subdomain. Using default '${ye}'.`),I=ye)}else m.outcome==="declined"||m.outcome,I=ye}else I||(I=ye);let je=V.publicPages;if(!je||Array.isArray(je)&&je.length===0){let m=V.pages,g=we.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),w=Array.isArray(m)&&m.some(T=>T.path==="/"||T.route==="/");g||w?je=["/","/pricing"]:je=["/"]}let It=V.primaryAction;if(!It){let m=V.features;if(Array.isArray(m)&&m.length>0){let w=m.find(N=>typeof N.priority=="string"&&N.priority.toLowerCase()==="must-have")??m[0];It={entity:w.name??w.title??"item",action:"create",fromPage:"/dashboard"}}}let We=V.nonNegotiables;(!We||Array.isArray(We)&&We.length===0)&&(We=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Be=So(),Ze=fe(ct(),".mistflow","plans");xt(Ze,{recursive:!0});try{let g=Date.now();for(let w of[Ze,fe(ct(),".mistflow","mockup-state")])if(Je(w))for(let T of Co(w))try{let N=fe(w,T),$=Ao(N).mtimeMs;g-$>6048e5&&Ql(N)}catch{}}catch{}let Ie=V,Q={name:V.name,summary:V.summary,dataModel:V.dataModel,pages:V.pages,features:V.features,steps:we.map(m=>({...m,name:m.name??m.title})),design:V.design,dbProvider:V.dbProvider??"neon",authModel:V.authModel,audienceType:V.audienceType??"b2c",roles:V.roles,defaultRole:V.defaultRole,publicPages:je,navStyle:V.navStyle,multiTenant:V.multiTenant,primaryAction:It,nonNegotiables:We,requestedSubdomain:I,...d&&d.toLowerCase()!=="english"?{language:d}:{},...Ie.pickedDirection?{pickedDirection:Ie.pickedDirection}:{},...Ie.imageryBrief?{imageryBrief:Ie.imageryBrief}:{},...Ie.designConversationId?{designConversationId:Ie.designConversationId}:{}};lt(fe(Ze,`${Be}.json`),JSON.stringify({plan:Q,methodology:Ee,...F?{scaffoldTargetPath:F}:{}}));let ge=we.map(m=>`${m.number}. ${m.name??m.title}`),Ne,et="";if(!!!Ie.pickedDirection){let g=(V.audienceType??"b2c")==="b2c";Ne={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:g?"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:g?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},et=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call."}let tt="",ze=[];for(let m of we){let g=m.name??m.title,w=m.integrationId;if(w){let T=Dt(w);if(T){let N=jt(T.id);ze.push({step:g,presetId:T.id,presetName:T.name,envVars:N?.envVars??[]})}}}if(ze.length>0){let m=ze.flatMap(T=>T.envVars),g=[...new Set(m.map(T=>T.key))];tt=` This plan uses integrations (${ze.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 p(JSON.stringify({planId:Be,name:V.name,summary:V.summary,stepCount:we.length,steps:ge,design:V.design,...Ne?{heroPhotoQuestion:Ne}:{},...ze.length>0?{integrations:ze.map(m=>({step:m.step,preset:m.presetId,name:m.presetName,envVars:m.envVars}))}:{},message:`Plan generated for "${ie}" (${we.length} steps).${tt}${et}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,we.length*3)}\u2013${we.length*5} minutes total across ${we.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: '${Be}' }). If the user says skip or "just build it", call mist_init({ planId: '${Be}'${F?"":", path: '<absolute path>'"} }) immediately.`,...F?{scaffoldTargetPath:F}:{},...Y?{warning:Y}:{}}))}var Oo={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist'). Clear new-app requests inside an existing non-Mistflow repo are scaffolded into a remembered child directory; Mistflow does not edit the surrounding codebase.","",`DESIGN REFERENCES (screenshots, Figma, brand names): if the user drags a screenshot, pastes a Figma URL, or names a brand to match ("make it feel like Linear"), use your native vision/knowledge to extract design tokens and submit them via designDirection: { custom: '<your description>', ...extracted_tokens } with userConfirmedCustom: true. The flag is required because the user supplied the reference; without it the server rejects the submission to stop AIs from inventing custom directions. Full flow at docs/design-references.md.`,"","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). For clear new-app requests it automatically creates and remembers a child scaffold directory. For ambiguous requests, it returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description, SAME projectPath, and confirmToken set to the token from the response. Do not change projectPath to the suggested child path; Mistflow stores that target for mist_init.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_init with the returned planId. If the response includes scaffoldTargetPath you do not need to pass path; mist_init loads it from the cached plan. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","SESSIONID FLOW (dumb-ai-proof, when the response includes sessionId): keep the sessionId and pass it on every subsequent mist_* call. Calling mist_plan with just { sessionId, projectPath } polls GET /api/sessions/{id}/next and returns the next instruction (wait | ask_user | pick_design | review_mockup | call_mist_init | call_mist_install | call_mist_implement | call_mist_build | call_mist_deploy | call_mist_qa | done). Do exactly what the instruction says \u2014 don't branch on raw state. The backend owns routing; the host relays.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. The aesthetic (fonts, colors, motion) is decided by the design-direction picker step \u2014 the host AI doesn't pick a catalog ID."].join(`
|
|
2073
|
+
`),inputSchema:pc,handler:wc};import{z as Ft}from"zod";import{existsSync as Re,mkdirSync as qt,rmSync as Nc,writeFileSync as Ye,readFileSync as Bt,readdirSync as qo,copyFileSync as Oc}from"fs";import{join as me,resolve as Bo,dirname as un,isAbsolute as Dc}from"path";import{homedir as jc}from"os";import{spawn as Ah}from"child_process";import{randomBytes as Mc}from"crypto";import{simpleGit as Uc}from"simple-git";function vc(t){let e=t.match(/^v?(\d+)\.(\d+)\.(\d+)/);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null}function Ut(t=process.version){let e=vc(t);return!e||e.major>=23?!0:e.major===22?e.minor>=12:e.major===20?e.minor>=19:!1}function kc(t=process.execPath){return t.includes("Library/pnpm/")||t.includes("AppData\\pnpm\\")||t.includes("/.pnpm/")?"pnpm":t.includes("/.fnm/")||process.env.FNM_DIR?"fnm":process.env.NVM_DIR||t.includes("/.nvm/")?"nvm":process.env.VOLTA_HOME||t.includes("/.volta/")?"volta":t.startsWith("/opt/homebrew/")||t.startsWith("/usr/local/")?"brew":t==="/usr/bin/node"?"system":"unknown"}function St(t=process.version,e=kc()){let r={pnpm:"Run: pnpm env use --global 22.12.0",fnm:"Run: fnm install 22.12 && fnm use 22.12",nvm:"Run: nvm install 22.12 && nvm use 22.12",volta:"Run: volta install node@22.12",brew:"Run: brew install node@22 && brew link node@22 --force --overwrite",system:"Install Node 22.12+ from https://nodejs.org/download",unknown:"Install Node 22.12+ from https://nodejs.org/download"};return[`OpenNext/Cloudflare builds require Node 20.19+, 22.12+, or 23+. The current MCP process is running ${t}.`,r[e],"Then quit and reopen your IDE so the MCP picks up the new Node."].join(`
|
|
2074
2074
|
`)}var Vn="\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 Kn=`# Landing Page Rules
|
|
2075
2075
|
|
|
2076
2076
|
These rules apply to every landing page. They are non-negotiable.
|
|
@@ -2485,14 +2485,14 @@ app/
|
|
|
2485
2485
|
\`\`\`
|
|
2486
2486
|
|
|
2487
2487
|
Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
|
|
2488
|
-
`;Se();vt();import{existsSync as Tc,readFileSync as _c,writeFileSync as Ic}from"fs";import{join as
|
|
2488
|
+
`;Se();vt();import{existsSync as Tc,readFileSync as _c,writeFileSync as Ic}from"fs";import{join as Do}from"path";var Pc={completed:"\u2705",done:"\u2705",in_progress:"\u{1F7E1}",pending:"\u23ED\uFE0F",skipped:"\u23ED\uFE0F"};function Zr(t){return t?Pc[t]??"\u23ED\uFE0F":"\u23ED\uFE0F"}function es(t){return t.name??t.title??`Step ${t.number}`}function jo(t){return t.entity??t.name??"Unknown"}function Cc(t){let e=t.fields??[];return e.length===0?"":typeof e[0]=="string"?e.join(", "):e.map(r=>r.name).filter(Boolean).join(", ")}function Ac(t){let e=[],r=t.plan,n=(t.name??r?.name??"App").split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ");e.push(`# ${n}`),e.push(""),e.push("Per-app orientation doc for host AIs editing this Mistflow-scaffolded codebase. Pairs with AGENTS.md (stack methodology) and DESIGN.md (aesthetic). Auto-regenerated by mist_init, mist_implement, and mist_deploy."),e.push("");let i=r?.summary??r?.description;if(i){if(e.push("## What this is"),e.push(""),e.push(i),r?.audienceType&&(e.push(""),e.push(`Audience: **${r.audienceType}**.`)),r?.design?.archetype){let c=r.design.tone?` (${r.design.tone} tone)`:"";e.push(`Aesthetic: **${r.design.archetype}**${c} \u2014 see DESIGN.md.`)}e.push("")}let o=r?.steps??[];if(o.length>0){e.push("## Build progress"),e.push("");let c=o.filter(d=>d.status==="completed"||d.status==="done"),u=o.filter(d=>d.status==="in_progress"),h=o.filter(d=>d.status!=="completed"&&d.status!=="done"&&d.status!=="in_progress");if(c.length>0){e.push(`**Done (${c.length}/${o.length}):**`);for(let d of c)e.push(`- ${Zr(d.status)} ${es(d)}`);e.push("")}if(u.length>0){e.push("**In progress:**");for(let d of u)e.push(`- ${Zr(d.status)} ${es(d)}`);e.push("")}if(h.length>0){e.push("**Planned next:**");for(let d of h)e.push(`- ${Zr(d.status)} ${es(d)}`);e.push("")}}let s=r?.dataModel??[];if(s.length>0){e.push("## Data model"),e.push("");for(let c of s){let u=Cc(c);u?e.push(`- **${jo(c)}**(${u})`):e.push(`- **${jo(c)}**`)}e.push("")}let a=r?.integrations??[];if(a.length>0){e.push("## Active integrations"),e.push("");for(let c of a){let u=c.name??c.id??"integration";e.push(`- **${u}**`)}e.push(""),e.push('Per-integration patterns: load the matching skill via `mist_docs({ topic: "<id>-integration" })` or read `.claude/skills/<id>-integration/SKILL.md`.'),e.push("")}let l=t.deploy;return l?.url&&(e.push("## Deploy"),e.push(""),e.push(`- URL: ${l.url}`),l.completedAt&&e.push(`- Last deploy: ${l.completedAt}`),l.deploymentId&&e.push(`- Last deployment id: \`${l.deploymentId}\``),e.push("")),e.push("## For fresh state"),e.push(""),e.push("This file is a **snapshot** written at scaffold/implement/deploy time \u2014 it can lag the live state of the app by minutes. For authoritative state (current step statuses, env vars actually set, deployment history, runtime errors), call:"),e.push(""),e.push("```"),e.push('mist_project({ action: "get", projectPath })'),e.push("```"),e.push(""),e.join(`
|
|
2489
2489
|
`).trimEnd()+`
|
|
2490
|
-
`}function $t(t){try{let e=
|
|
2490
|
+
`}function $t(t){try{let e=Do(t,"mistflow.json");if(!Tc(e))return;let r=_c(e,"utf-8"),n=JSON.parse(r),i=Ac(n);Ic(Do(t,"PROJECT.md"),i,"utf-8")}catch{}}function Mo(t){if(!t)return"Item";let e=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return e.length===0?"Item":e.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}function Rc(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function Ec(t){let e=Mo(t);return e.charAt(0).toLowerCase()+e.slice(1)}function ns(){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(`
|
|
2491
2491
|
`)}function Lo(){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(`
|
|
2492
2492
|
`)}var ts="<!-- mist:contracts:start -->",Uo="<!-- mist:contracts:end -->";function rs(t){let e=Lo();if(t.includes(ts)){let n=t.indexOf(ts),i=Uo,o=t.indexOf(i,n);if(o===-1)return t.slice(0,n)+e;let s=t.slice(o+i.length);return t.slice(0,n)+e+s.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
|
|
2493
2493
|
|
|
2494
2494
|
`+e}function ss(t,e){let r=Mo(t),n=e??Ec(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${n} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${r}Schema = createSelectSchema(${n});`,`export type ${r} = z.infer<typeof ${r}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${r}Input = createInsertSchema(${n}).omit({`," id: true,"," createdAt: true,","});",`export type Create${r}Input = z.infer<typeof Create${r}Input>;`,""].join(`
|
|
2495
|
-
`)}function os(t){return`contracts/${Rc(t)}.ts`}function Lc(t){let e=me(
|
|
2495
|
+
`)}function os(t){return`contracts/${Rc(t)}.ts`}function Lc(t){let e=me(jc(),".mistflow","plans",`${t}.json`);if(!Re(e))return null;try{let r=JSON.parse(Bt(e,"utf-8"));return r.plan?{plan:r.plan,...typeof r.scaffoldTargetPath=="string"?{scaffoldTargetPath:r.scaffoldTargetPath}:{}}:null}catch{return null}}var $c=`## Project plan (PLAN.md)
|
|
2496
2496
|
|
|
2497
2497
|
This project ships with a \`PLAN.md\` at the root \u2014 a PRD-style
|
|
2498
2498
|
projection of the plan with the data model, pages, steps, and per-step
|
|
@@ -2712,7 +2712,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2712
2712
|
`)}function hd(t){if(!t.multiTenant)return null;let e=[];return e.push('import { db } from "./db";'),e.push('import { organization, orgMember } from "@/db/schema/organization";'),e.push('import { eq } from "drizzle-orm";'),e.push(""),e.push("export async function getCurrentOrg(userId: string) {"),e.push(" const membership = await db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.userId, userId))"),e.push(" .limit(1);"),e.push(" if (membership.length === 0) return null;"),e.push(" const org = await db"),e.push(" .select()"),e.push(" .from(organization)"),e.push(" .where(eq(organization.id, membership[0].orgId))"),e.push(" .limit(1);"),e.push(" return org[0] ?? null;"),e.push("}"),e.push(""),e.push("export async function getOrgMembers(orgId: string) {"),e.push(" return db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.orgId, orgId));"),e.push("}"),e.push(""),e.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),e.push(" const id = crypto.randomUUID();"),e.push(" await db.insert(orgMember).values({"),e.push(" id,"),e.push(" orgId,"),e.push(" userId: email,"),e.push(" role,"),e.push(" });"),e.push(" return { id, orgId, email, role };"),e.push("}"),e.push(""),e.join(`
|
|
2713
2713
|
`)}function gd(t){if(!t.multiTenant)return null;let e=[];return e.push('"use client";'),e.push(""),e.push("import {"),e.push(" DropdownMenu,"),e.push(" DropdownMenuContent,"),e.push(" DropdownMenuItem,"),e.push(" DropdownMenuTrigger,"),e.push('} from "@/components/ui/dropdown-menu";'),e.push('import { Button } from "@/components/ui/button";'),e.push('import { ChevronsUpDown } from "lucide-react";'),e.push(""),e.push("interface OrgSwitcherProps {"),e.push(" orgs: Array<{ id: string; name: string }>;"),e.push(" currentOrgId: string;"),e.push("}"),e.push(""),e.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),e.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),e.push(""),e.push(" return ("),e.push(" <DropdownMenu>"),e.push(" <DropdownMenuTrigger asChild>"),e.push(' <Button variant="outline" className="w-full justify-between">'),e.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),e.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),e.push(" </Button>"),e.push(" </DropdownMenuTrigger>"),e.push(' <DropdownMenuContent className="w-56">'),e.push(" {orgs.map((org) => ("),e.push(" <DropdownMenuItem key={org.id}>"),e.push(" {org.name}"),e.push(" </DropdownMenuItem>"),e.push(" ))}"),e.push(" </DropdownMenuContent>"),e.push(" </DropdownMenu>"),e.push(" );"),e.push("}"),e.push(""),e.join(`
|
|
2714
2714
|
`)}function fd(t,e,r){let n=[],i=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");n.push(`# ${i}`),n.push(""),e?.summary&&(n.push(e.summary),n.push(""));let o=e?.features??[];if(o.length>0){n.push("## Features"),n.push("");for(let l of o){let c=l.description?` \u2014 ${l.description}`:"";n.push(`- **${l.name}**${c}`)}n.push("")}n.push("## Tech Stack"),n.push(""),n.push("| Layer | Technology |"),n.push("|-------|------------|"),n.push("| Framework | Next.js 15 (App Router) |"),n.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),n.push("| Auth | Better Auth (email/password, social login) |"),n.push("| Styling | Tailwind CSS + shadcn/ui |"),n.push("| Deployment | Mistflow Cloud |"),r.hasStripe&&n.push("| Payments | Stripe |"),r.hasResend&&n.push("| Email | Resend + React Email |"),r.hasStorage&&n.push("| File Storage | Mistflow Cloud (managed blob storage) |"),r.hasAdmin&&n.push("| Admin | Better Auth admin plugin |"),r.hasAI&&n.push("| AI | Vercel AI SDK + OpenAI |"),n.push("");let s=e?.pages??[];if(s.length>0){n.push("## Pages"),n.push(""),n.push("| Route | Description |"),n.push("|-------|-------------|");for(let l of s){let c=l.path??l.route??l.name??"",u=l.description??"";n.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${u} |`)}n.push("")}let a=e?.dataModel??[];if(a.length>0){n.push("## Data Model"),n.push("");for(let l of a){let c=l.entity??l.name??"Unknown";if(n.push(`### ${c}`),n.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")n.push(`Fields: ${l.fields.join(", ")}`);else{n.push("| Field | Type |"),n.push("|-------|------|");for(let u of l.fields)n.push(`| ${u.name} | ${u.type} |`)}n.push("")}}}return n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),r.isNeon?n.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(n.push("| `TURSO_URL` | Database connection URL | Yes |"),n.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),n.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),r.hasStripe&&(n.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),n.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),n.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),r.hasResend&&(n.push("| `RESEND_API_KEY` | Resend API key | Yes |"),n.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),(r.hasAI||r.hasStorage)&&n.push("| `MISTFLOW_RUNTIME_KEY` | Mistflow Cloud runtime key \u2014 authenticates AI gateway, file storage, and other managed features | Auto-provisioned at `mist_init` |"),r.hasAI&&n.push("| `OPENROUTER_API_KEY` | OpenRouter key for your-key fallback (only used when `MISTFLOW_RUNTIME_KEY` is unset) | Optional |"),n.push(""),n.push("### Local database"),n.push(""),r.isNeon?(n.push("For local development, start a local Postgres server:"),n.push(""),n.push("```bash"),n.push("# Using Docker:"),n.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),n.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),n.push("```")):(n.push("For local development, start a local Turso server:"),n.push(""),n.push("```bash"),n.push("npx turso dev"),n.push("```")),n.push(""),n.push("Then set up the database:"),n.push(""),n.push("```bash"),n.push("npm run db:push"),n.push("```"),n.push(""),n.push("### Run"),n.push(""),n.push("```bash"),n.push("npm run dev"),n.push("```"),n.push(""),n.push("Open [http://localhost:3000](http://localhost:3000)."),n.push(""),n.push("## Project Structure"),n.push(""),n.push("```"),n.push("app/"),n.push(" (auth)/ Login and registration pages"),n.push(" (dashboard)/ Authenticated app pages"),r.hasAdmin&&n.push(" admin/ Admin panel pages (at /admin/...)"),n.push(" home/ Public landing page (served via / \u2192 /home redirect)"),n.push(" api/ API routes (auth, health, webhooks)"),n.push(" layout.tsx Root layout with fonts and providers"),n.push(" globals.css Design tokens and Tailwind config"),n.push("components/ Reusable UI components"),n.push("db/"),n.push(" schema/ Database table definitions"),n.push(" index.ts Schema exports"),n.push("lib/"),n.push(" auth.ts Better Auth server config"),n.push(" auth-client.ts Better Auth client config"),n.push(` db.ts ${r.isNeon?"Postgres":"SQLite"} database connection`),r.hasStripe&&n.push(" stripe.ts Stripe client"),r.hasResend&&(n.push(" resend.ts Resend client"),n.push(" email.ts Email send helpers")),r.hasStorage&&n.push(" storage.ts File upload/download helpers"),r.hasAI&&(n.push(" ai.ts Back-compat export for server AI helpers"),n.push(" server/ai.ts Server-only AI Gateway and provider helpers")),r.hasResend&&n.push("emails/ React Email templates"),n.push("```"),n.push(""),n.push("## Deploy"),n.push(""),n.push("Deploy to production with Mistflow:"),n.push(""),n.push("```"),n.push("# In your AI editor (Claude Code, Cursor, etc.):"),n.push("mist_deploy action='deploy'"),n.push("```"),n.push(""),n.push("Your app will be live at `https://<app-name>.mistflow.app`."),n.push(""),e?.design&&(n.push("## Design"),n.push(""),e.design.tone&&n.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(n.push(`- **Heading font**: ${e.design.fonts.heading}`),n.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&n.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&n.push(`- **Border radius**: ${e.design.borderRadius}`),n.push("")),n.push("---"),n.push(""),n.push("Built with [Mistflow](https://mistflow.ai)"),n.push(""),n.join(`
|
|
2715
|
-
`)}async function yd(t,e){if(!ke())return Ae("scaffold a new project");if(!Ut())return p(JSON.stringify({status:"node_version_unsupported",code:"node_version_unsupported",message:St(),nextAction:"Tell the user their Node version is too old, paste the upgrade command from `message`, and stop. Do NOT proceed with mist_init \u2014 the scaffolded app would build-fail at deploy time."}),!0);let{name:r,plan:n,path:i,planId:o,sessionId:s}=t,a,l,c=null,u=n;if(typeof u=="string")try{let b=JSON.parse(u);b&&typeof b=="object"&&!Array.isArray(b)&&"plan"in b?u=b.plan:u=b}catch{return p("mist_init received `plan` as a string, but it is not valid JSON. Pass the plan object directly or pass planId from mist_plan.",!0)}if(!u&&o){if(c=Lc(o),!c)return p(`No plan found for planId '${o}'. Call mist_plan first, or pass the plan object inline.`,!0);u=c.plan}if(!u||typeof u!="object"||Array.isArray(u))return p("mist_init requires a plan object or a valid planId from mist_plan. Refusing to scaffold without a structured plan because mist_implement would not know what to build.",!0);let h=i??c?.scaffoldTargetPath;if(!h)return p("mist_init requires an explicit 'path' unless the planId cache includes a scaffoldTargetPath. Call mist_init with the planId returned by mist_plan, pass the absolute scaffold directory, or pass { sessionId, path } in session mode.",!0);if(!
|
|
2715
|
+
`)}async function yd(t,e){if(!ke())return Ae("scaffold a new project");if(!Ut())return p(JSON.stringify({status:"node_version_unsupported",code:"node_version_unsupported",message:St(),nextAction:"Tell the user their Node version is too old, paste the upgrade command from `message`, and stop. Do NOT proceed with mist_init \u2014 the scaffolded app would build-fail at deploy time."}),!0);let{name:r,plan:n,path:i,planId:o,sessionId:s}=t,a,l,c=null,u=n;if(typeof u=="string")try{let b=JSON.parse(u);b&&typeof b=="object"&&!Array.isArray(b)&&"plan"in b?u=b.plan:u=b}catch{return p("mist_init received `plan` as a string, but it is not valid JSON. Pass the plan object directly or pass planId from mist_plan.",!0)}if(!u&&o){if(c=Lc(o),!c)return p(`No plan found for planId '${o}'. Call mist_plan first, or pass the plan object inline.`,!0);u=c.plan}if(!u||typeof u!="object"||Array.isArray(u))return p("mist_init requires a plan object or a valid planId from mist_plan. Refusing to scaffold without a structured plan because mist_implement would not know what to build.",!0);let h=i??c?.scaffoldTargetPath;if(!h)return p("mist_init requires an explicit 'path' unless the planId cache includes a scaffoldTargetPath. Call mist_init with the planId returned by mist_plan, pass the absolute scaffold directory, or pass { sessionId, path } in session mode.",!0);if(!Dc(h))return p(`mist_init 'path' must be an absolute path \u2014 received '${h}'. Pass the full absolute path to the target directory.`,!0);let d=Bo(h),v=r??(typeof u.name=="string"?u.name:void 0);if(!v)return p("mist_init requires a human-readable app name. Pass `name`, or call it with a planId whose cached plan includes a name.",!0);let H=u?.design,_=typeof u.authModel=="string"?u.authModel:void 0,k=_==="none",y=sd(u),C=od(u,_),B=u?mn(u,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,z=u?mn(u,"admin panel","admin dashboard","admin management"):!1,te=u?mn(u,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,Z=u,Y=typeof u.dbProvider=="string"?u.dbProvider:"neon",F=Array.isArray(u.dataModel)&&u.dataModel.length>0,I=Y==="none"||k&&!F&&!B,re=I?"none":Y,q=re==="neon";if(!Kc(d))return p(Jc(d,u?.name),!0);qt(d,{recursive:!0});try{try{let f=me(d,".mistflow","rules");qt(f,{recursive:!0}),Ye(me(f,"design-quality.md"),Vn),Ye(me(f,"landing.md"),Kn)}catch(f){console.error("Could not write design rule files:",f instanceof Error?f.message:f)}try{let f=me(un(d),".mistflow","mockups");if(Re(f)){let R=qo(f).filter(S=>S.endsWith(".html"));if(R.length>0){let S=me(d,".mistflow","mockups");qt(S,{recursive:!0});for(let ce of R)Oc(me(f,ce),me(S,ce));console.error(`Copied ${R.length} mockup file(s) into project`)}}}catch(f){console.error("Could not copy mockup files:",f instanceof Error?f.message:f)}let b=null;try{b=await Er("nextjs")}catch(f){console.error("Could not fetch scaffold from API, using minimal scaffold:",f instanceof Error?f.message:f)}if(b){let f=v.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let x of b.files){if(x.path==="package.json"||x.path==="middleware.ts"||x.path==="components/sidebar.tsx"||x.path==="components/topnav.tsx"||x.path==="app/(dashboard)/layout.tsx"||x.path==="app/(dashboard)/page.tsx"||x.path==="app/(dashboard)/dashboard/page.tsx"||I&&(x.path==="lib/db.ts"||x.path==="drizzle.config.ts"||x.path==="db/index.ts"||x.path.startsWith("db/schema/"))||k&&(x.path.includes("(auth)")||x.path.includes("(admin)")||x.path.startsWith("app/admin/")||x.path.includes("components/auth/")||x.path.includes("admin-sidebar")||x.path.includes("app/api/auth/")||x.path.includes("app/api/admin/seed")||x.path==="lib/auth.ts"||x.path==="lib/auth-client.ts"||x.path==="db/schema/auth.ts"||x.path==="db/schema/index.ts"||x.path==="db/index.ts")||!y&&(x.path.includes("stripe")||x.path.includes("webhook/stripe"))||!C&&(x.path.includes("resend")||x.path.includes("emails/"))||!z&&(x.path.includes("(admin)")||x.path.startsWith("app/admin/")||x.path.includes("admin-sidebar"))||q&&(x.path==="lib/db.ts"||x.path==="lib/auth.ts"||x.path==="drizzle.config.ts"||x.path==="db/schema/auth.ts"))continue;let O=x.content.replace(/\{\{APP_NAME\}\}/g,v).replace(/\{\{WORKER_NAME\}\}/g,f);if(q&&x.path==="next.config.ts"&&(O=O.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),x.path==="next.config.ts"){let _e=Fc(d);_e&&(console.error(`[init] Project is inside monorepo at ${_e} \u2014 adding outputFileTracingRoot`),O.includes("outputFileTracingRoot")||(O=O.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
2716
2716
|
import { dirname } from "path";
|
|
2717
2717
|
import { fileURLToPath } from "url";
|
|
2718
2718
|
|
|
@@ -2731,7 +2731,7 @@ import { sql } from "drizzle-orm";`).replace(/pgTable/g,"sqliteTable").replace(/
|
|
|
2731
2731
|
`)),E(d,"db/schema/index.ts",['export * from "./auth";',""].join(`
|
|
2732
2732
|
`)),E(d,"db/index.ts",['export * from "./schema/auth";',""].join(`
|
|
2733
2733
|
`));let x=u.defaultRole??"user";E(d,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { genericOAuth } from "better-auth/plugins/generic-oauth";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"","async function sendEmail({ to, subject, html, fallbackUrl }: { to: string; subject: string; html: string; fallbackUrl?: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {"," if (fallbackUrl) {"," console.error(`\\n[auth] No RESEND_API_KEY set. Email to ${to} was not sent.`);"," console.error(`[auth] Dev fallback \u2014 use this link directly:\\n ${fallbackUrl}\\n`);"," } else {"," console.error(`[auth] RESEND_API_KEY not set \u2014 skipping email send to ${to}`);"," }"," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' const body = await res.text().catch(() => "unknown");'," console.error(`[auth] Email send failed (${res.status}): ${body}`);"," throw new Error(`Email send failed: ${res.status}`);"," }","}","","function createAuth() {",' const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',' const isLocal = baseURL.includes("localhost") || baseURL.includes("127.0.0.1");'," const canSendEmail = Boolean(process.env.RESEND_API_KEY);"," const mistflowAppId = process.env.MISTFLOW_APP_ID;"," const mistflowOAuthProxyURL = process.env.MISTFLOW_OAUTH_PROXY_URL;"," // 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,"," // Include the Mistflow OAuth proxy in trustedOrigins so Better Auth"," // accepts the OAuth callback round-trip without 'invalid origin' errors."," trustedOrigins: [baseURL, mistflowOAuthProxyURL].filter((u): u is string => Boolean(u)),",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,"," requireEmailVerification: !isLocal && 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: "${x}" }),`," ...(mistflowAppId && mistflowOAuthProxyURL ? ["," genericOAuth({"," config: [{",' providerId: "google",'," clientId: mistflowAppId,",' clientSecret: "pkce",'," discoveryUrl: `${mistflowOAuthProxyURL}/.well-known/openid-configuration`,",' scopes: ["openid", "email", "profile"],'," pkce: true,"," redirectURI: `${baseURL}/api/auth/oauth2/callback/google`,"," }],"," }),"," ] : []),"," 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.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(`
|
|
2734
|
-
`))}}else E(d,"package.json",JSON.stringify({name:v,version:"0.1.0",private:!0},null,2));let U=a??u?.designMd;E(d,"app/globals.css",ed(H,U)),E(d,"app/layout.tsx",rd(v,H,Z?.language)),E(d,"README.md",fd(v,u,{hasStripe:y,hasResend:C,hasStorage:B,hasAdmin:z,hasAI:te,isNeon:q})),E(d,"contracts/README.md",ns());let G=u?.dataModel??[],
|
|
2734
|
+
`))}}else E(d,"package.json",JSON.stringify({name:v,version:"0.1.0",private:!0},null,2));let U=a??u?.designMd;E(d,"app/globals.css",ed(H,U)),E(d,"app/layout.tsx",rd(v,H,Z?.language)),E(d,"README.md",fd(v,u,{hasStripe:y,hasResend:C,hasStorage:B,hasAdmin:z,hasAI:te,isNeon:q})),E(d,"contracts/README.md",ns());let G=u?.dataModel??[],j=new Set,de=0;for(let f of G){let R=f.entity??f.name;if(!R||typeof R!="string")continue;let S=os(R);j.has(S)||(j.add(S),E(d,S,ss(R)),de++)}de===0&&E(d,"contracts/.gitkeep","");let ee=[],A=u?.publicPages;if(Array.isArray(A))ee=A;else if(typeof A=="string"){try{ee=JSON.parse(A)}catch{ee=[]}Array.isArray(ee)||(ee=[])}if(!ee.includes("/")){let f=u?.steps?.some(S=>{let ce=((S.name??"")+" "+(S.description??"")).toLowerCase();return ce.includes("landing")||ce.includes("marketing")||ce.includes("homepage")}),R=u?.pages?.some(S=>S.path==="/");(f||R)&&(ee=["/",...ee])}let he={name:v,summary:u?.summary,authModel:_,roles:u?.roles,defaultRole:u?.defaultRole,publicPages:ee,navStyle:u?.navStyle,multiTenant:u?.multiTenant,pages:u?.pages,dataModel:u?.dataModel,design:u?.design},V=ad(he);V&&E(d,"middleware.ts",V);let ie=ld(he);ie&&E(d,ie.path,ie.content);let Ee=cd(he);if(Ee&&E(d,"lib/roles.ts",Ee),E(d,"app/page.tsx",dd(he)),E(d,"app/(dashboard)/layout.tsx",pd(he,z)),E(d,"app/(dashboard)/dashboard/page.tsx",ud(he)),he.multiTenant){let f=md(he,q);f&&E(d,"db/schema/organization.ts",f);let R=hd(he);R&&E(d,"lib/org.ts",R);let S=gd(he);S&&E(d,"components/org-switcher.tsx",S)}E(d,"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)),y&&E(d,"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(`
|
|
2735
2735
|
`)),C&&(E(d,"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(`
|
|
2736
2736
|
`)),E(d,"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(`
|
|
2737
2737
|
`)),E(d,"lib/server/email.ts",['import "server-only";','import { render } from "@react-email/render";','import type { ReactElement } from "react";',"",'export class EmailConfigError extends Error { readonly code = "email_config"; }','export class EmailRateLimitError extends Error { readonly code = "email_rate_limit"; }','export class EmailCreditExhaustedError extends Error { readonly code = "email_credits_exhausted"; }','export class EmailUpstreamError extends Error { readonly code = "email_upstream_error"; }','export class EmailValidationError extends Error { readonly code = "email_validation"; }',"","function runtimeKey(): string | undefined {"," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","","export type EmailSendOptions = {"," to: string | string[];"," subject: string;"," html?: string;"," text?: string;"," react?: ReactElement;"," cc?: string[];"," bcc?: string[];"," replyTo?: string;"," idempotencyKey?: string;"," tags?: Record<string, string>;","};","","export const email = {"," /** Send an email. Sandbox decision is server-enforced via the runtime key's"," * environment field \u2014 your app cannot accidentally email real users from"," * dev or preview deploys. Real sends only fire when the key is",' * environment="production".'," *"," * React components are rendered to HTML locally before the gateway call"," * (React doesn't serialize over HTTP). */"," async send(opts: EmailSendOptions): Promise<{ id: string; sandbox?: boolean }> {"," if (!opts.to || (Array.isArray(opts.to) && opts.to.length === 0)) {",' throw new EmailValidationError("Recipient (to) is required");'," }"," if (!opts.subject) {",' throw new EmailValidationError("Subject is required");'," }"," let html = opts.html;"," if (opts.react && !html) {"," html = await render(opts.react);"," }",""," const key = runtimeKey();"," if (key) {"," // Managed mode \u2014 gateway handles sandbox enforcement, idempotency, billing."," const body = {"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, replyTo: opts.replyTo,"," idempotencyKey: opts.idempotencyKey, tags: opts.tags,"," };",' const r = await fetch(apiUrl() + "/api/email/send", {',' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": key },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new EmailConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (r.status === 402) throw new EmailCreditExhaustedError("Email/AI credits exhausted.");',' if (r.status === 429) throw new EmailRateLimitError("Rate limited.");'," if (r.status === 422) throw new EmailValidationError(await r.text());",' if (!r.ok) throw new EmailUpstreamError("Email gateway error " + r.status);'," return (await r.json()) as { id: string; sandbox?: boolean };"," }",""," if (process.env.RESEND_API_KEY) {"," // BYOK direct \u2014 no sandbox enforcement, user is responsible.",' const { Resend } = await import("resend");'," const client = new Resend(process.env.RESEND_API_KEY);",' const fromAddr = process.env.EMAIL_FROM ?? "onboarding@resend.dev";'," const result = await client.emails.send({"," from: fromAddr,"," to: opts.to, subject: opts.subject, html, text: opts.text,"," cc: opts.cc, bcc: opts.bcc, reply_to: opts.replyTo,",' ...(opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}),'," });"," if (result.error) throw new EmailUpstreamError(result.error.message);",' return { id: result.data?.id ?? "unknown", sandbox: false };'," }",""," throw new EmailConfigError(",` "Email is not configured. Run 'mist_setup' for managed mode (sandbox-safe in dev) or set RESEND_API_KEY."`," );"," },","};",""].join(`
|
|
@@ -2741,7 +2741,7 @@ import { sql } from "drizzle-orm";`).replace(/pgTable/g,"sqliteTable").replace(/
|
|
|
2741
2741
|
`))),te&&(E(d,"lib/server/ai.ts",['import "server-only";',"",'import { createOpenAI } from "@ai-sdk/openai";','import { streamText, type CoreMessage } from "ai";','import type { z } from "zod";','import { zodToJsonSchema } from "zod-to-json-schema";',"","export const MISTFLOW_AI_HELPER_VERSION = 2;","","// \u2500\u2500 Typed error hierarchy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Catch the specific class to give the user actionable copy.",'export class AIConfigError extends Error { readonly code = "ai_config"; }','export class AIRateLimitError extends Error { readonly code = "ai_rate_limit"; }','export class AICreditExhaustedError extends Error { readonly code = "ai_credits_exhausted"; }','export class AIModelError extends Error { readonly code = "ai_model_error"; }',"export class AISchemaError extends Error {",' readonly code = "ai_schema_error";'," /** Raw model output that failed validation. Redacted by default; set"," * MISTFLOW_DEBUG=1 in dev to see full output. */"," readonly rawOutput?: string;"," constructor(message: string, rawOutput?: string) {"," super(message);"," this.rawOutput = rawOutput;"," }","}","","function redact(s: string | undefined): string | undefined {"," if (!s) return s;",' if (process.env.MISTFLOW_DEBUG === "1") return s;',' if (s.length <= 80) return "<redacted>";',' return s.slice(0, 40) + " ...<redacted>... " + s.slice(-20);',"}","","// \u2500\u2500 Env + dispatch helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",'const DEFAULT_MISTFLOW_AI_API_URL = "https://api.mistflow.ai";',"","function runtimeKey(): string | undefined {"," // Canonical name first; legacy alias for one release of compat."," return process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","}","","function mistflowAiApiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? DEFAULT_MISTFLOW_AI_API_URL).replace(/\\/$/, "");',"}","","function gatewayHeaders(): HeadersInit {"," const key = runtimeKey();"," if (!key) {",` throw new AIConfigError("MISTFLOW_RUNTIME_KEY not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY for BYOK.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": key,'," };","}","","function isManagedAvailable(): boolean { return !!runtimeKey(); }","function isBYOKAvailable(): boolean { return !!process.env.OPENROUTER_API_KEY; }","","function noConfigError(): AIConfigError {"," return new AIConfigError(",` "AI is not configured. Run 'mist_setup' for managed mode (free credits) or set OPENROUTER_API_KEY in .env.local."`," );","}","","async function callManaged(path: string, body: unknown): Promise<Response> {"," const response = await fetch(mistflowAiApiUrl() + path, {",' method: "POST",'," headers: gatewayHeaders(),"," body: JSON.stringify(body),"," });",' if (response.status === 401) throw new AIConfigError("Runtime key rejected by gateway. Re-run mist_setup.");',' if (response.status === 402) throw new AICreditExhaustedError("AI credits exhausted. Top up at https://app.mistflow.ai/ai-gateway");',' if (response.status === 429) throw new AIRateLimitError("Rate limited by gateway. Retry with backoff.");'," if (!response.ok) {",' const text = await response.text().catch(() => "");',' throw new AIModelError("AI gateway error " + response.status + ": " + redact(text));'," }"," return response;","}","","// BYOK direct OpenRouter \u2014 used when MISTFLOW_RUNTIME_KEY is not set.","export const openrouter = createOpenAI({"," apiKey: process.env.OPENROUTER_API_KEY,",' baseURL: "https://openrouter.ai/api/v1",'," headers: {",' "HTTP-Referer": process.env.NEXT_PUBLIC_APP_URL ?? "https://mistflow.app",',' "X-Title": "Mistflow App",'," },","});","","// \u2500\u2500 Public surface: the `ai` object \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Always import this. The wrapper handles all dispatch (managed-first,","// BYOK fallback). Never write process.env.OPENROUTER_API_KEY in feature code.","","export type TextOptions = {"," messages: CoreMessage[];"," model?: string;"," useCase?: string;"," idempotencyKey?: string;","};","","export type ImageOptions = { prompt: string; size?: string; model?: string; idempotencyKey?: string };","export type EmbedOptions = { model?: string };","export type TTSOptions = { text: string; voice?: string; model?: string };","export type STTOptions = { audio: Blob | ArrayBuffer; model?: string };","export type RealtimeOptions = { instructions?: string; useCase?: string };","","export const ai = {"," async text(opts: TextOptions): Promise<string> {"," if (isManagedAvailable()) {",' const r = await callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: false, messages: opts.messages,"," });"," const json = (await r.json()) as { text?: string };",' return json.text ?? "";'," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return await result.text;"," }"," throw noConfigError();"," },",""," async streamText(opts: TextOptions): Promise<Response> {"," if (isManagedAvailable()) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: "llm", use_case: opts.useCase ?? "chat",'," model: opts.model, idempotency_key: opts.idempotencyKey,"," stream: true, messages: opts.messages,"," });"," }"," if (isBYOKAvailable()) {",' const result = await streamText({ model: openrouter(opts.model ?? "openai/gpt-5-mini"), messages: opts.messages });'," return result.toDataStreamResponse();"," }"," throw noConfigError();"," },",""," async extractJSON<T>(opts: { prompt: string; schema: z.ZodType<T>; model?: string; useCase?: string }): Promise<T> {"," // Per Codex review: no dedicated /runtime/extract-json endpoint."," // Wrapper uses /runtime/text + JSON-schema-mode + local Zod validation.",' const jsonSchema = zodToJsonSchema(opts.schema, { target: "openApi3" });'," const messages: CoreMessage[] = [",' { role: "system", content: "Respond ONLY with valid JSON matching this schema: " + JSON.stringify(jsonSchema) },',' { role: "user", content: opts.prompt },'," ];",' const text = await this.text({ messages, model: opts.model, useCase: opts.useCase ?? "extract" });'," let parsed: unknown;"," try { parsed = JSON.parse(text); }",' catch { throw new AISchemaError("Model returned non-JSON output", redact(text)); }'," const result = opts.schema.safeParse(parsed);"," if (!result.success) {",' throw new AISchemaError("Model output failed schema validation: " + result.error.message, redact(text));'," }"," return result.data;"," },",""," async embed(input: string | string[], opts: EmbedOptions = {}): Promise<number[][]> {"," if (!isManagedAvailable()) {"," // BYOK embed via OpenRouter is not in v1; require managed mode for embeddings."," throw noConfigError();"," }",' const r = await callManaged("/api/ai-gateway/runtime/embed", { input, model: opts.model });'," const json = (await r.json()) as { vectors: number[][] };"," return json.vectors;"," },",""," async generateImage(opts: ImageOptions): Promise<{ url: string }[]> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt: opts.prompt, model: opts.model, size: opts.size,"," idempotency_key: opts.idempotencyKey,"," });"," const json = (await r.json()) as { url?: string; image?: string };",' return [{ url: json.url ?? json.image ?? "" }];'," },",""," async speak(opts: TTSOptions): Promise<Blob> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/tts", {'," text: opts.text, voice: opts.voice, model: opts.model,"," });"," return await r.blob();"," },",""," async transcribe(opts: STTOptions): Promise<{ text: string }> {"," if (!isManagedAvailable()) throw noConfigError();"," const blob = opts.audio instanceof Blob ? opts.audio : new Blob([opts.audio]);"," const form = new FormData();",' form.append("audio", blob);',' if (opts.model) form.append("model", opts.model);'," const key = runtimeKey();"," if (!key) throw noConfigError();",' const response = await fetch(mistflowAiApiUrl() + "/api/ai-gateway/runtime/stt", {',' method: "POST", body: form, headers: { "X-Mistflow-AI-Key": key },'," });",' if (!response.ok) throw new AIModelError("STT failed: " + response.status);'," return (await response.json()) as { text: string };"," },",""," async createRealtimeSession(opts: RealtimeOptions = {}): Promise<Record<string, unknown>> {"," if (!isManagedAvailable()) throw noConfigError();",' const r = await callManaged("/api/ai-gateway/runtime/realtime-session", {',' use_case: opts.useCase ?? "agent", instructions: opts.instructions,'," });"," return (await r.json()) as Record<string, unknown>;"," },","};","","// \u2500\u2500 Legacy named exports (back-compat for older scaffolds + chat route) \u2500\u2500","// These wrap the new `ai` object so existing call sites keep working.",'export type AiCapability = "llm" | "voice_realtime" | "tts" | "stt" | "image";',"type ManagedTextOptions = { capability?: AiCapability; useCase?: string; model?: string; idempotencyKey?: string; stream?: boolean };","",'export function openrouterModel(model = "openai/gpt-5-mini") { return openrouter(model); }',"",'export async function streamOpenRouterText(messages: CoreMessage[], model = "openai/gpt-5-mini") {'," return streamText({ model: openrouter(model), messages });","}","","export async function mistflowManagedText(messages: CoreMessage[], options: ManagedTextOptions = {}) {",' return callManaged("/api/ai-gateway/runtime/text", {',' capability: options.capability ?? "llm", use_case: options.useCase ?? "chat",'," model: options.model, idempotency_key: options.idempotencyKey,"," stream: options.stream ?? false, messages,"," });","}","","export async function mistflowManagedImage(prompt: string, options: { model?: string; size?: string; idempotencyKey?: string } = {}) {",' const r = await callManaged("/api/ai-gateway/runtime/image", {',' capability: "image", use_case: "generation",'," prompt, model: options.model, idempotency_key: options.idempotencyKey, size: options.size,"," });"," return await r.json();","}","","export async function mistflowManagedRealtimeSession(instructions?: string) {"," return ai.createRealtimeSession({ instructions });","}","","export async function reportDirectAIUsage(report: Record<string, unknown>): Promise<void> {"," if (!isManagedAvailable()) return;",' try { await callManaged("/api/ai-gateway/runtime/report-usage", report); } catch { /* never break user request path */ }',"}",""].join(`
|
|
2742
2742
|
`)),E(d,"lib/ai.ts",['import "server-only";',"",'export * from "./server/ai";',""].join(`
|
|
2743
2743
|
`)),E(d,"app/api/chat/route.ts",['import { ai, AIConfigError, AICreditExhaustedError } from "@/lib/server/ai";','import type { CoreMessage } from "ai";',"","export async function POST(req: Request) {"," const { messages } = (await req.json()) as { messages?: CoreMessage[] };"," if (!messages) {",' return Response.json({ error: "messages is required" }, { status: 400 });'," }"," try {"," return await ai.streamText({ messages });"," } catch (e) {"," if (e instanceof AIConfigError) return Response.json({ error: e.message }, { status: 503 });"," if (e instanceof AICreditExhaustedError) return Response.json({ error: e.message }, { status: 402 });",' return Response.json({ error: "AI request failed" }, { status: 500 });'," }","}",""].join(`
|
|
2744
|
-
`)));let we=Array.isArray(u?.integrations)?u.integrations.map(f=>({name:f.name,preset:f.preset,envVars:f.envVars??[]})):[],ye={};for(let f of we)for(let R of f.envVars??[])ye[R.key]||(ye[R.key]={description:R.description,setupUrl:R.setupUrl,...f.name?{integration:f.name}:{}});let
|
|
2744
|
+
`)));let we=Array.isArray(u?.integrations)?u.integrations.map(f=>({name:f.name,preset:f.preset,envVars:f.envVars??[]})):[],ye={};for(let f of we)for(let R of f.envVars??[])ye[R.key]||(ye[R.key]={description:R.description,setupUrl:R.setupUrl,...f.name?{integration:f.name}:{}});let je=Z?.requestedSubdomain||void 0,It={name:v,methodologyVersion:b?.version??"1.0",createdAt:new Date().toISOString(),...o?{planId:o}:{},...je?{requestedSubdomain:je}:{},plan:Array.isArray(u?.steps)?{...u,steps:u.steps.map(f=>({number:f.number,name:f.name??f.title,description:f.description,entities:f.entities,pages:f.pages,features:f.features,status:"pending"}))}:u,dbProvider:re,env:{managed:{...!I&&q?{DATABASE_URL:{description:"Postgres connection URL",scope:"production"}}:I?{}:{TURSO_URL:{description:"Turso database URL",scope:"production"},TURSO_AUTH_TOKEN:{description:"Turso database auth token",scope:"production"}},...k?{}:{AUTH_SECRET:{description:"Auth encryption secret",scope:"production"}},...y?{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"}}:{},...C?{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"}}:{}},...Object.keys(ye).length>0?{required:ye}:{}},authModel:_??"email",roles:u?.roles??null,navStyle:u?.navStyle??"sidebar",multiTenant:u?.multiTenant??!1,hasAdmin:z,hasResend:C,hasStorage:B,hasAI:te,deploy:null};E(d,"mistflow.json",JSON.stringify(It,null,2)),$t(d);let We=Mc(32).toString("hex"),Be=y?`
|
|
2745
2745
|
# Stripe
|
|
2746
2746
|
STRIPE_SECRET_KEY=
|
|
2747
2747
|
STRIPE_WEBHOOK_SECRET=
|
|
@@ -2771,7 +2771,7 @@ ${k?"":`
|
|
|
2771
2771
|
# Mistflow-hosted Google sign-in (zero Google Cloud setup)
|
|
2772
2772
|
MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
|
|
2773
2773
|
`}${Be}${Ze}${Ie}${ge}`),E(d,".env.example",`${tt}${et}
|
|
2774
|
-
${Be}${Ze}${Ie}${ge}`);let m=[],g=(f,R)=>{m.push({phase:f,message:R})},w=(f,R)=>{let S=m.find(ce=>ce.phase===f&&!ce.durationMs);S&&(S.durationMs=R)};if(e){let f=$e(e.server,e.progressToken,()=>m[m.length-1]?.message??"Setting up project...");e.cleanup=()=>f.stop()}let T=
|
|
2774
|
+
${Be}${Ze}${Ie}${ge}`);let m=[],g=(f,R)=>{m.push({phase:f,message:R})},w=(f,R)=>{let S=m.find(ce=>ce.phase===f&&!ce.durationMs);S&&(S.durationMs=R)};if(e){let f=$e(e.server,e.progressToken,()=>m[m.length-1]?.message??"Setting up project...");e.cleanup=()=>f.stop()}let T=je,N=Z?.pickedDirection??Z?.designDirection??void 0,$=Z?.imageryBrief??N?.imagery??void 0,se=Z?.designConversationId??void 0,ae=Z?{name:Z.name,summary:Z.summary,audienceType:Z.audienceType,authModel:Z.authModel,dbProvider:re,dataModel:Z.dataModel,design:Z.design,publicLanding:Z.publicLanding}:void 0,oe,M;g("register","Registering project on Mistflow...");let K=Date.now();try{let f=await wt(v,{template:void 0,dbProvider:re,requestedSubdomain:T,pickedDirection:N,imageryBrief:$,planContext:ae,designConversationId:se,sessionId:s});if(oe=f.id,f.design_md&&(a=f.design_md),f.plan_md&&(l=f.plan_md),f.layout_spec&&u&&typeof u=="object"&&(u.layoutSpec=f.layout_spec),f.picker_render_html&&typeof f.picker_render_html=="string")try{let X=me(d,".mistflow");qt(X,{recursive:!0}),Ye(me(X,"picker-render.html"),f.picker_render_html),console.error(`[mist_init] picker render written to .mistflow/picker-render.html (${f.picker_render_html.length} chars)`)}catch(X){let J=X instanceof Error?X.message:String(X);console.error(`[mist_init] picker render write failed: ${J}`)}if($)try{let X=await br(oe),J=me(d,"public","images");qt(J,{recursive:!0});let x=0,O=0;for(let[_e,Pe]of Object.entries(X.slots))if(Pe.status==="done"&&Pe.signed_url)try{let Ce=await wr(Pe.signed_url);Ye(me(J,`${_e}.png`),Ce),x++}catch(Ce){let da=Ce instanceof Error?Ce.message:String(Ce);console.error(`[mist_init] imagery: ${_e} download failed: ${da}`)}else(Pe.status==="queued"||Pe.status==="running")&&O++;(x>0||O>0)&&console.error(`[mist_init] imagery: ${x} ready, ${O} still rendering`)}catch(X){let J=X instanceof Error?X.message:String(X);console.error(`[mist_init] imagery manifest fetch failed: ${J}`)}let R=me(d,"mistflow.json"),S=JSON.parse(Bt(R,"utf-8"));if(S.projectId=oe,f.layout_spec&&S.plan&&typeof S.plan=="object"&&(S.plan.layoutSpec=f.layout_spec),Ye(R,JSON.stringify(S,null,2)),rn(d,sn(oe,v)),f.managed_env&&Object.keys(f.managed_env).length>0){let X=me(d,".env.local"),J=Re(X)?Bt(X,"utf-8"):"";for(let[x,O]of Object.entries(f.managed_env)){let _e=new RegExp(`^${x}=.*$`,"m");_e.test(J)?J=J.replace(_e,`${x}=${O}`):J+=`
|
|
2775
2775
|
${x}=${O}`}Ye(X,J)}let ue=f.runtimeKey;if(ue?.rawKey){let X=me(d,".env.local"),J=Re(X)?Bt(X,"utf-8"):"",x=(O,_e)=>{let Pe=new RegExp(`^${O}=\\s*$`,"m"),Ce=new RegExp(`^${O}=`,"m");Pe.test(J)?J=J.replace(Pe,`${O}=${_e}`):Ce.test(J)||(J+=`
|
|
2776
2776
|
${O}=${_e}`)};x("MISTFLOW_RUNTIME_KEY",ue.rawKey),x("MISTFLOW_AI_RUNTIME_KEY",ue.rawKey),Ye(X,J)}if(!k&&f.mistflow_app_id){let X=me(d,".env.local"),J=Re(X)?Bt(X,"utf-8"):"";/^MISTFLOW_OAUTH_PROXY_URL=/m.test(J)||(J+=`
|
|
2777
2777
|
# Mistflow-hosted Google sign-in (zero Google Cloud setup)
|
|
@@ -4766,7 +4766,7 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
|
|
|
4766
4766
|
- **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
|
|
4767
4767
|
- **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
|
|
4768
4768
|
- **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.
|
|
4769
|
-
`;var ei={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Ho},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:Wo},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Go},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Vo},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Ko},"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:Jo},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Yo},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:Qo},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:Xo},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:Zo}};var cg=Object.keys(ei);function ti(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return ei[e]}import{createServer as Bd}from"net";import{existsSync as Xn,readFileSync as mi,writeFileSync as hi,mkdirSync as gi}from"fs";import{join as Zn}from"path";import{spawn as zd}from"child_process";import{spawn as Cd,execFileSync as Ad}from"child_process";import{existsSync as Yn,mkdirSync as si,openSync as ls,closeSync as cs,readSync as Rd,readFileSync as oi,writeFileSync as ii,renameSync as ai,unlinkSync as Ed,readdirSync as mg,statSync as Nd}from"fs";import{homedir as li}from"os";import{join as
|
|
4769
|
+
`;var ei={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Ho},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:Wo},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Go},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Vo},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Ko},"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:Jo},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Yo},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:Qo},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:Xo},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:Zo}};var cg=Object.keys(ei);function ti(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return ei[e]}import{createServer as Bd}from"net";import{existsSync as Xn,readFileSync as mi,writeFileSync as hi,mkdirSync as gi}from"fs";import{join as Zn}from"path";import{spawn as zd}from"child_process";import{spawn as Cd,execFileSync as Ad}from"child_process";import{existsSync as Yn,mkdirSync as si,openSync as ls,closeSync as cs,readSync as Rd,readFileSync as oi,writeFileSync as ii,renameSync as ai,unlinkSync as Ed,readdirSync as mg,statSync as Nd}from"fs";import{homedir as li}from"os";import{join as De,dirname as ci}from"path";import{randomBytes as di,randomUUID as Od}from"crypto";var pi=1,Dd=`// Generated by @mistflow-ai/mcp local-jobs (v${pi}). Do not edit.
|
|
4770
4770
|
const { spawn } = require('node:child_process');
|
|
4771
4771
|
const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
|
|
4772
4772
|
const { join, dirname } = require('node:path');
|
|
@@ -4830,11 +4830,11 @@ child.on('error', (err) => {
|
|
|
4830
4830
|
});
|
|
4831
4831
|
process.exit(1);
|
|
4832
4832
|
});
|
|
4833
|
-
`;function Qn(){return
|
|
4834
|
-
`),ai(n,r)}catch(i){try{Ed(n)}catch{}throw i}}function Ld(t){let e=ui(t);if(!Yn(e))return null;try{return JSON.parse(oi(e,"utf-8"))}catch{return null}}async function dt(t){let e=`job_${Od().replace(/-/g,"").slice(0,12)}`,r=zt(e);si(r,{recursive:!0}),cs(ls(
|
|
4833
|
+
`;function Qn(){return De(li(),".mistflow","jobs")}function jd(){return De(li(),".mistflow","job-wrapper.cjs")}function Md(){let t=jd(),e=ci(t);Yn(e)||si(e,{recursive:!0});let r=`v${pi}`;if(Yn(t))try{if(oi(t,"utf-8").includes(r))return t}catch{}let n=De(e,`.job-wrapper.tmp.${di(6).toString("hex")}`);return ii(n,Dd),ai(n,t),t}function zt(t){return De(Qn(),t)}function ui(t){return De(zt(t),"status.json")}function ni(t,e){let r=ui(t),n=De(ci(r),`.status.tmp.${di(6).toString("hex")}`);try{ii(n,JSON.stringify(e,null,2)+`
|
|
4834
|
+
`),ai(n,r)}catch(i){try{Ed(n)}catch{}throw i}}function Ld(t){let e=ui(t);if(!Yn(e))return null;try{return JSON.parse(oi(e,"utf-8"))}catch{return null}}async function dt(t){let e=`job_${Od().replace(/-/g,"").slice(0,12)}`,r=zt(e);si(r,{recursive:!0}),cs(ls(De(r,"stdout.log"),"a")),cs(ls(De(r,"stderr.log"),"a"));let n=new Date().toISOString(),i={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:n,cmd:t.cmd,args:t.args,cwd:t.cwd};ni(e,i);let o=Md(),s={...process.env,...t.env??{}},a=Cd("node",[o,r,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:s});a.unref();let l={...i,wrapperPid:a.pid??0};return ni(e,l),l}function Ud(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function $d(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=Ad("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=Ud(r),i=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(i)&&Math.abs(n-i)>2e3)return!1}catch{}return!0}function Fd(t,e){let r=Date.parse(t),n=e?Date.parse(e):Date.now();if(!Number.isFinite(r)||!Number.isFinite(n))return"0s";let i=Math.max(0,n-r),o=Math.floor(i/1e3);if(o<60)return`${o}s`;let s=Math.floor(o/60),a=o%60;return s<60?`${s}m ${a}s`:`${Math.floor(s/60)}h ${s%60}m`}function ri(t,e){if(!Yn(t))return"";let r=Nd(t);if(r.size===0)return"";let n=r.size>e?r.size-e:0,i=r.size-n,o=ls(t,"r");try{let s=Buffer.alloc(i);return Rd(o,s,0,i,n),s.toString("utf-8")}finally{cs(o)}}function qd(t,e=200){let r=ri(De(zt(t),"stdout.log"),65536),n=ri(De(zt(t),"stderr.log"),64*1024),i=[];return r.trim()&&i.push(...r.split(`
|
|
4835
4835
|
`).slice(-e).map(o=>`[out] ${o}`)),n.trim()&&i.push(...n.split(`
|
|
4836
4836
|
`).slice(-e).map(o=>`[err] ${o}`)),i.filter(o=>o.trim().length>0).join(`
|
|
4837
|
-
`)}function Tt(t){return{stdout:
|
|
4837
|
+
`)}function Tt(t){return{stdout:De(zt(t),"stdout.log"),stderr:De(zt(t),"stderr.log")}}async function pt(t){let e=Ld(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!$d(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:Fd(r.startedAt,r.endedAt),logTail:qd(t)}}async function Ht(t,e){let r=Math.max(100,e.pollIntervalMs??500),n=Date.now()+Math.max(0,e.timeoutMs),i=["complete","failed","unknown_exit"];for(;;){let o=await pt(t);if(!o)return null;try{e.onPoll?.(o)}catch{}if(i.includes(o.status))return o;let s=n-Date.now();if(s<=0)return o;await new Promise(a=>setTimeout(a,Math.min(r,s)))}}function fi(){let t=(process.env.MISTFLOW_VISUAL_CONTEXT??"full").toLowerCase();return t==="off"||t==="preview"||t==="full"?t:"full"}function yi(t){return Zn(t,".mistflow","visual-context.json")}function bi(t){let e=yi(t);if(!Xn(e))return{screenshotsTaken:0,lastScreenshotStep:0};try{return JSON.parse(mi(e,"utf-8"))}catch{return{screenshotsTaken:0,lastScreenshotStep:0}}}function Hd(t,e){let r=Zn(t,".mistflow");Xn(r)||gi(r,{recursive:!0}),hi(yi(t),JSON.stringify(e,null,2)+`
|
|
4838
4838
|
`)}var Wd=5;function wi(t,e,r){if(fi()!=="full")return!1;let n=bi(t);return n.screenshotsTaken>=Wd?!1:n.screenshotsTaken===0||r>0&&e>=r||e>0&&e!==n.lastScreenshotStep&&e%3===0}function vi(t,e){let r=bi(t);Hd(t,{screenshotsTaken:r.screenshotsTaken+1,lastScreenshotStep:e})}async function Gd(){return new Promise((t,e)=>{let r=Bd();r.unref(),r.on("error",e),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(n&&typeof n=="object"){let i=n.port;r.close(()=>t(i))}else r.close(()=>e(new Error("could not read assigned port")))})})}async function ki(t,e=15e3,r=500){let n=Date.now()+e;for(;Date.now()<n;){try{let i=new AbortController,o=setTimeout(()=>i.abort(),Math.min(r*2,2e3)),s=await fetch(t,{method:"HEAD",signal:i.signal});if(clearTimeout(o),s)return!0}catch{}await new Promise(i=>setTimeout(i,r))}return!1}function xi(t){return Zn(t,".mistflow","preview.json")}function Si(t){let e=xi(t);if(!Xn(e))return null;try{return JSON.parse(mi(e,"utf-8"))}catch{return null}}function Ti(t){return Si(t)}function Vd(t,e){let r=Zn(t,".mistflow");Xn(r)||gi(r,{recursive:!0}),hi(xi(t),JSON.stringify(e,null,2)+`
|
|
4839
4839
|
`)}async function _i(t){if(fi()==="off")return null;let e=Si(t);if(e){let n=await pt(e.jobId);if(n&&(n.status==="running"||n.status==="starting"))return{state:e,freshlyStarted:!1}}let r;try{r=await Gd()}catch{return null}try{let n=await dt({type:"preview",cmd:"sh",args:["-c",`npm run dev -- --port ${r}`],cwd:t});await new Promise(a=>setTimeout(a,600));let i=await pt(n.id);if(i&&(i.status==="failed"||i.status==="unknown_exit"))return null;let o=`http://localhost:${r}`,s={port:r,url:o,jobId:n.id,startedAt:n.startedAt};return Vd(t,s),{state:s,freshlyStarted:!0}}catch{return null}}function Ii(t){try{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];zd(e,r,{detached:!0,stdio:"ignore"}).unref()}catch{}}var Pi=`# Design Doctrine
|
|
4840
4840
|
|
|
@@ -5300,16 +5300,16 @@ If there's a pricing page:
|
|
|
5300
5300
|
|
|
5301
5301
|
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."
|
|
5302
5302
|
`;import{existsSync as tp,readFileSync as np,writeFileSync as rp}from"fs";import{join as sp}from"path";import{z as gn}from"zod";var er=gn.object({key:gn.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:gn.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:gn.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:gn.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),op=/^[A-Z][A-Z0-9_]*$/;function tr(t,e){if(e.length===0)return{added:[],skipped:[]};let r=sp(t,"mistflow.json");if(!tp(r))throw new Error(`mistflow.json not found at ${t}`);let n=np(r,"utf-8"),i=JSON.parse(n);i.env=i.env??{},i.env.required=i.env.required??{};let o=i.env.required,s=[],a=[];for(let l of e)if(!(!l?.key||typeof l.key!="string"||!op.test(l.key))){if(o[l.key]){a.push(l.key);continue}o[l.key]={description:typeof l.description=="string"?l.description:"",...typeof l.setupUrl=="string"&&l.setupUrl?{setupUrl:l.setupUrl}:{},...typeof l.integration=="string"&&l.integration?{integration:l.integration}:{}},s.push(l.key)}return s.length>0&&rp(r,JSON.stringify(i,null,2)+`
|
|
5303
|
-
`),{added:s,skipped:a}}function dp(t){return new Promise(e=>{let r=cp({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}var pp=fn.object({projectPath:fn.string().optional().describe("Path to the project directory (default: cwd)"),step:fn.number().optional().describe("Specific step number to implement (default: next incomplete step)"),sessionId:fn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),envVarsRequired:fn.array(er).optional().describe("Declare any env vars the code you just wrote uses (process.env.X) that aren't already in mistflow.json env.required. Server merges these into the manifest so missing values surface as warnings on deploy. Skip keys already covered by integration presets (Stripe, Resend, etc. \u2014 those are pre-declared). Only declare ad-hoc keys you introduced. First declaration wins; re-declaring is a no-op.")});function up(t){let e=Qe(t,"mistflow.json");if(!ut(e))return null;try{return JSON.parse(ps(e,"utf-8"))}catch{return null}}function
|
|
5304
|
-
`),$t(t)}function nr(t){return t.entity??t.name??"Unknown"}function mp(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Di(t){return t.path??t.route??t.name??""}function hp(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 Mi(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let i=nr(n).toLowerCase();return r.some(o=>i.includes(o)||o.includes(i))})}function gp(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let i=(n.name??"").toLowerCase(),o=Di(n).toLowerCase();return r.some(s=>i.includes(s)||s.includes(i)||o.includes(s))})}var fp=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function yp(t){let e=t.stepType;if(e&&fp.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name??t.title??""} ${t.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function bp(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 wp(t){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&e.push(`- **App tone**: ${t.tone}`),t.fonts&&(e.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let r={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${t.borderRadius} (${r[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let r={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${r[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let r={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${t.cardStyle} \u2014 ${r[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&e.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let r=t.visualStrategy,n=t.heroPhoto!==!1,i=n&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),i&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let s=r.heroImages[0];e.push(`- URL: ${s.url}`),e.push(`- Alt text for img tag: "${s.alt||"Hero image"} \u2014 Photo by ${s.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!r.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/home/page.tsx.'"):n||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(r.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let s of r.sectionImages)e.push(`- ${s.url} \u2014 alt: "${s.alt||"section image"} \u2014 Photo by ${s.photographer} on Unsplash"`)}(i||r.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let o=ti(t);o?(e.push(""),e.push(`### Page composition \u2014 ${o.name} archetype`),e.push(`This plan was classified as **${o.id}** \u2014 ${o.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),e.push(""),e.push(o.content)):(e.push(""),e.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),i?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows. Must be DOMAIN-SPECIFIC."),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return e.join(`
|
|
5303
|
+
`),{added:s,skipped:a}}function dp(t){return new Promise(e=>{let r=cp({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}var pp=fn.object({projectPath:fn.string().optional().describe("Path to the project directory (default: cwd)"),step:fn.number().optional().describe("Specific step number to implement (default: next incomplete step)"),sessionId:fn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),envVarsRequired:fn.array(er).optional().describe("Declare any env vars the code you just wrote uses (process.env.X) that aren't already in mistflow.json env.required. Server merges these into the manifest so missing values surface as warnings on deploy. Skip keys already covered by integration presets (Stripe, Resend, etc. \u2014 those are pre-declared). Only declare ad-hoc keys you introduced. First declaration wins; re-declaring is a no-op.")});function up(t){let e=Qe(t,"mistflow.json");if(!ut(e))return null;try{return JSON.parse(ps(e,"utf-8"))}catch{return null}}function Di(t,e){let r=Qe(t,"mistflow.json");ds(r,JSON.stringify(e,null,2)+`
|
|
5304
|
+
`),$t(t)}function nr(t){return t.entity??t.name??"Unknown"}function mp(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function ji(t){return t.path??t.route??t.name??""}function hp(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 Mi(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let i=nr(n).toLowerCase();return r.some(o=>i.includes(o)||o.includes(i))})}function gp(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let i=(n.name??"").toLowerCase(),o=ji(n).toLowerCase();return r.some(s=>i.includes(s)||s.includes(i)||o.includes(s))})}var fp=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function yp(t){let e=t.stepType;if(e&&fp.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name??t.title??""} ${t.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function bp(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 wp(t){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&e.push(`- **App tone**: ${t.tone}`),t.fonts&&(e.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let r={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${t.borderRadius} (${r[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let r={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${r[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let r={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${t.cardStyle} \u2014 ${r[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&e.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let r=t.visualStrategy,n=t.heroPhoto!==!1,i=n&&!!r.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),i&&r.heroImages&&r.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let s=r.heroImages[0];e.push(`- URL: ${s.url}`),e.push(`- Alt text for img tag: "${s.alt||"Hero image"} \u2014 Photo by ${s.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!r.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/home/page.tsx.'"):n||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(r.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let s of r.sectionImages)e.push(`- ${s.url} \u2014 alt: "${s.alt||"section image"} \u2014 Photo by ${s.photographer} on Unsplash"`)}(i||r.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page.");let o=ti(t);o?(e.push(""),e.push(`### Page composition \u2014 ${o.name} archetype`),e.push(`This plan was classified as **${o.id}** \u2014 ${o.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),e.push(""),e.push(o.content)):(e.push(""),e.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),i?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows. Must be DOMAIN-SPECIFIC."),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return e.join(`
|
|
5305
5305
|
`)}function vp(t){let e=[];return e.push("### Landing layout (Plan G IR \u2014 STRUCTURAL AUTHORITY for this page):"),e.push(""),e.push("Build the landing page with EXACTLY these sections, in this order. Each section's `type` names a primitive \u2014 render it using the picked direction's fonts + colors + shape language. The `intent` explains WHY the section exists; the `props` are the content."),e.push(""),e.push(`- **Page intent**: ${t.page_intent}`),e.push(`- **Narrative arc**: ${t.narrative_arc}`),e.push(`- **Audience**: ${t.audience_persona}`),t.primary_cta&&e.push(`- **Primary CTA**: \`${t.primary_cta.label}\` \u2014 ${t.primary_cta.intent}`),e.push(""),e.push("**Sections (build in order):**"),e.push(""),t.sections.forEach((r,n)=>{let i=n+1;e.push(`${i}. \`${r.type}\` (id: \`${r.id}\`, role: \`${r.narrative_role}\`)`),e.push(` - **Intent**: ${r.intent}`),r.answers_section_id&&e.push(` - **Answers**: section \`${r.answers_section_id}\` (use visual cues \u2014 paired typography, matching accent, sequential numbering \u2014 to make the relationship readable)`),e.push(" - **Props** (JSON):"),e.push(" ```json");let o=JSON.stringify(r.props,null,2).split(`
|
|
5306
5306
|
`).map(s=>` ${s}`);e.push(...o),e.push(" ```"),e.push("")}),e.push("**Rules:**"),e.push("- Render sections in the order above. Do not add, remove, or reorder."),e.push("- Each section's `type` is a known primitive \u2014 implement it as a real component with the props as content. Field names in `props` are descriptive of the role (e.g. `hero_magazine.pullquote` is an italicized 15-40 word quote with a left-rule mark)."),e.push("- Use the picked direction's `fonts.display` / `fonts.body` / `colors.bg/fg/accent` / `shape_lang` (border radius scale) / `texture` (background overlay) \u2014 those are in the design choices block above."),e.push("- The IR is the structural authority for THIS page; landing-rules.md still applies for anti-slop / motion choreography / general quality. If they conflict on structure, the IR wins."),e.push("- Don't invent placeholder content \u2014 every `props` value here is what the section should display."),e.join(`
|
|
5307
5307
|
`)}async function kp(t){try{let e=await Nr("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
|
|
5308
5308
|
- Follow existing patterns in the codebase
|
|
5309
|
-
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function xp(t,e,r,n,i,o){let s=[];s.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),s.push(""),s.push("### What to build:"),s.push(t.description),s.push(""),e.primaryAction&&(s.push("### Primary user action (non-negotiable):"),s.push(`- **Core action**: ${e.primaryAction.action}`),s.push(`- **User flow**: ${e.primaryAction.flow}`),s.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),s.push(""),s.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."),s.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l){s.push(wp(e.design)),s.push("");let _=o?Qe(o,".mistflow","rules","design-quality.md"):null;_&&ut(_)?(s.push("### Design quality rules (non-negotiable):"),s.push("**Read `.mistflow/rules/design-quality.md` BEFORE writing any code for this step.** That file contains the full rule set (shadcn usage, routes, typography, color, layout, motion, responsive, UX writing, cognitive load, production hardening, anti-patterns). It's been written to disk to keep this prompt under the per-tool-result token cap \u2014 read it once, then write your code."),s.push("")):(s.push(Vn),s.push(""))}else e.design&&!l&&(s.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&s.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),s.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),s.push(""));if(o){let _=bo(o);if(_.length>0){s.push("### Approved wireframe (MUST READ before writing any files):"),s.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let k of _){let y=k.replace(o,"").replace(/^\//,"");s.push(`- \`${y}\``)}s.push(""),s.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."),s.push(""),s.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),s.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),s.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),s.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),s.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),s.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"),s.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(s.push("### Role system (from plan):"),s.push(`- Roles: ${e.roles.join(", ")}`),s.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),s.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),s.push("")),e.multiTenant&&(s.push("### Multi-tenant (from plan):"),s.push("- Organization tables are in `db/schema/organization.ts`"),s.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),s.push("- All data queries MUST be scoped to the current org (filter by orgId)"),s.push("- Org switcher component is at `components/org-switcher.tsx`"),s.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."),s.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."),s.push("")),e.language&&(s.push(`### Language: ${e.language}`),s.push(`ALL user-facing text must be written in ${e.language}:`),s.push("- Page titles, headings, labels, button text, placeholder text"),s.push("- Navigation items, menu labels, footer text"),s.push("- Error messages, success messages, empty states"),s.push("- Landing page copy, marketing text, CTAs"),s.push("- Form labels and validation messages"),s.push("Code (variable names, comments, file names) stays in English."),s.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),s.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(i)&&(e.audienceType==="b2c"?(s.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),s.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),s.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),s.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),s.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),s.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),s.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),s.push("")):e.audienceType==="b2b"?(s.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),s.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),s.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),s.push("- Testimonials: from business owners who use the platform"),s.push("- Features: business benefits ('Track dietary preferences across all orders')"),s.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),s.push("")):e.audienceType==="internal"&&(s.push("### Audience: internal staff tool. No marketing copy needed."),s.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),s.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),s.push(""))),r.length>0&&(s.push("### Already completed:"),r.forEach(_=>s.push(`- ${_}`)),s.push(""));let u=e.dataModel?Mi(t,e.dataModel):[];u.length>0&&(s.push("### Data model (from plan):"),u.forEach(_=>{let k=nr(_),y=mp(_.fields);s.push(`- **${k}**: ${y}`),s.push(` Schema file: \`db/schema/${k.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let h=e.pages?gp(t,e.pages):[];if(h.length>0&&(s.push("### Pages to create/update:"),h.forEach(_=>{let k=_.description?` \u2014 ${_.description}`:"";s.push(`- \`${Di(_)}\`${k}`)}),s.push("")),i==="crud"&&u.length>0&&u.forEach(_=>{let k=nr(_),y=k.toLowerCase().replace(/\s+/g,"-"),C=y.endsWith("s")?y:`${y}s`;s.push(`### Files for ${k} CRUD:`),s.push(`- List page: \`app/(dashboard)/${C}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${C}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${C}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${C}/actions.ts\``),s.push(`- DataTable columns: \`components/${y}-table-columns.tsx\``),s.push(`- Form: \`components/${y}-form.tsx\``),s.push("")}),l){s.push("## Design Doctrine (the standard for every UI step)"),s.push(""),s.push(Pi),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(Ci),s.push(""),s.push("### Color"),s.push(Ai),s.push(""),s.push("### Motion"),s.push(Ri),s.push(""),s.push("### Spatial Composition"),s.push(Ei),s.push(""),s.push("### Interaction"),s.push(Ni),s.push(""),s.push("### UX Writing"),s.push(Oi),s.push("");let _=o?Qe(o,"DESIGN.md"):void 0,k=_&&ut(_)?(()=>{try{return ps(_,"utf-8")}catch{return null}})():null;k&&(s.push("### Design system (source of truth: DESIGN.md):"),s.push(""),s.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."),s.push(""),s.push(k),s.push(""));let y=o?Qe(o,".mistflow","picker-render.html"):void 0;(i==="landing"||i==="design")&&y&&ut(y)&&(s.push("### Picked landing page render \u2014 ground-truth design contract"),s.push(""),s.push("The user picked their direction from a **fully-rendered HTML preview** of this landing page. That render is at `.mistflow/picker-render.html` (relative to the project root). **Read it** \u2014 it is the design contract the user agreed to."),s.push(""),s.push("Your job for this step is **mechanical translation**: convert that standalone HTML to Next.js Server Components + Client Components in `app/home/page.tsx` (and `components/landing/*.tsx` for any sections you split out). You are NOT redesigning. The user already picked the design \u2014 colors, fonts, composition, copy, and section order are LOCKED."),s.push(""),s.push("How to translate:\n1. **Preserve every voice sample exactly.** The H1 in the rendered HTML is the headline the user picked. The CTA button text is the CTA the user picked. Do NOT paraphrase, shorten, or 'improve' them. The picker is a contract.\n2. **Preserve the section order.** Each `<section data-section-id=\"X\">` in the rendered HTML maps to a TSX section in the SAME order. You may split each section into its own component file (`components/landing/{section-id}.tsx`) for readability \u2014 that's the only structural transformation allowed.\n3. **Migrate inline `<style>` to globals.css**. The render uses one inline `<style>` block; move those rules to `app/globals.css` so the rest of the app shares the design tokens. CSS custom properties (`--color-bg` / `--color-fg` / `--color-accent`) become the canonical design tokens.\n4. **Tailwind utility classes are FORBIDDEN in this step**, the same way they were forbidden in the render. The render already emits raw CSS; keep it that way in the TSX (use `className` to attach classes defined in globals.css, not Tailwind utilities).\n5. **Image slots:** each `<img data-image-slot=\"hero|feature-1|feature-2|feature-3|og|favicon\">` in the render points at picsum placeholder URLs. Replace each `src` with `/images/{slot}.png` \u2014 those files arrive in `public/images/` from the imagery pipeline (see Plan F A.6.1; check `mist_project action='imagery'` for status during the build). For the favicon slot, also wire `app/icon.png` to the same asset.\n6. **Do not add or remove sections.** If the render has 6 sections, the deployed page has 6 sections in the same order. Adding a CTA the user didn't pick is a bug; dropping a feature card the user did pick is also a bug.\n"),s.push("Bar: a designer comparing the picker iframe and the deployed /home page side by side should not be able to tell them apart at first glance. The HTML\u2192TSX translation is mechanical. Anything creative belongs in a separate refinement step the user explicitly asks for."),s.push(""))}if(i==="landing"||i==="design"){s.push("### File location for the landing page (non-negotiable):"),s.push('Write the landing page to **`app/home/page.tsx`** \u2014 NOT `app/page.tsx`. The scaffold\'s `middleware.ts` 308-redirects `/` to `/home` as a workaround for an OpenNext Cloudflare bug. Visitors land at `/` and end up on `/home` transparently. Internal links like `<Link href="/">` still work because the middleware does the redirect on every request.'),s.push("");let _=o?Qe(o,".mistflow","rules","landing.md"):null;_&&ut(_)?(s.push("### Landing page rules:"),s.push("**Read `.mistflow/rules/landing.md` BEFORE writing the landing page.** That file contains the full conversion structure, section catalog, motion menu, and anti-slop audit. Written to disk to keep this prompt under the per-tool-result token cap \u2014 read once, then write your code."),s.push("")):(s.push(Kn),s.push(""))}i==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(s.push(vp(e.layoutSpec)),s.push(""));let d=t.integrationId?jt(t.integrationId):void 0;if(d){let _=Dt(d.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${d.name}** (${d.category})`),_?.docsUrl&&s.push(`Official docs: ${_.docsUrl}`),_?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let k of _.envVars)s.push(`- \`${k.key}\`: ${k.description} \u2014 Get it at ${k.setupUrl}`);s.push(""),s.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.")}_?.packages?.length&&(s.push(""),s.push(`**Packages to install:** \`npm install ${_.packages.join(" ")}\``)),s.push(""),s.push("---"),s.push(d.prompt),s.push("---"),s.push(""),s.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."),s.push("")}let{reminders:v,skill:H}=await kp(i);return s.push(v),s.push(""),H&&(s.push(`### ${i} reference:`),s.push(H),s.push("")),l&&(s.push("## Self-Audit \u2014 run before submitting this file"),s.push(""),s.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.`),s.push(""),s.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.'),s.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."),s.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),s.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),s.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."),s.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),s.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),s.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.'),s.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).'),s.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)."),s.push(""),s.push(`If every answer is "no, I'm good" \u2014 then submit.`),s.push("")),s.join(`
|
|
5310
|
-
`)}async function Sp(t){let{projectPath:e,step:r,envVarsRequired:n,sessionId:i}=t,o=ap(e??process.cwd());if(n&&n.length>0)try{let b=tr(o,n);b.added.length>0&&console.error(`[implement] declared env.required: ${b.added.join(", ")}`)}catch(b){console.error("[implement] env var merge skipped:",b instanceof Error?b.message:String(b))}let s=up(o);if(!s)return Ve(o);if(!ut(Qe(o,"node_modules")))return p(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:b,ensureShadcnComponents:U}=await Promise.resolve().then(()=>(Wr(),Hr)),G=await b(o);G&&!s.projectId&&(s.projectId=G);let
|
|
5309
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function xp(t,e,r,n,i,o){let s=[];s.push(`## Step ${t.number}: ${t.name??t.title??"(untitled)"}`),s.push(""),s.push("### What to build:"),s.push(t.description),s.push(""),e.primaryAction&&(s.push("### Primary user action (non-negotiable):"),s.push(`- **Core action**: ${e.primaryAction.action}`),s.push(`- **User flow**: ${e.primaryAction.flow}`),s.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),s.push(""),s.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."),s.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l){s.push(wp(e.design)),s.push("");let _=o?Qe(o,".mistflow","rules","design-quality.md"):null;_&&ut(_)?(s.push("### Design quality rules (non-negotiable):"),s.push("**Read `.mistflow/rules/design-quality.md` BEFORE writing any code for this step.** That file contains the full rule set (shadcn usage, routes, typography, color, layout, motion, responsive, UX writing, cognitive load, production hardening, anti-patterns). It's been written to disk to keep this prompt under the per-tool-result token cap \u2014 read it once, then write your code."),s.push("")):(s.push(Vn),s.push(""))}else e.design&&!l&&(s.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&s.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),s.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),s.push(""));if(o){let _=bo(o);if(_.length>0){s.push("### Approved wireframe (MUST READ before writing any files):"),s.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let k of _){let y=k.replace(o,"").replace(/^\//,"");s.push(`- \`${y}\``)}s.push(""),s.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."),s.push(""),s.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),s.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),s.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),s.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),s.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),s.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"),s.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(s.push("### Role system (from plan):"),s.push(`- Roles: ${e.roles.join(", ")}`),s.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),s.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),s.push("")),e.multiTenant&&(s.push("### Multi-tenant (from plan):"),s.push("- Organization tables are in `db/schema/organization.ts`"),s.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),s.push("- All data queries MUST be scoped to the current org (filter by orgId)"),s.push("- Org switcher component is at `components/org-switcher.tsx`"),s.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."),s.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."),s.push("")),e.language&&(s.push(`### Language: ${e.language}`),s.push(`ALL user-facing text must be written in ${e.language}:`),s.push("- Page titles, headings, labels, button text, placeholder text"),s.push("- Navigation items, menu labels, footer text"),s.push("- Error messages, success messages, empty states"),s.push("- Landing page copy, marketing text, CTAs"),s.push("- Form labels and validation messages"),s.push("Code (variable names, comments, file names) stays in English."),s.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),s.push(""));let c=["landing","design","auth","general","crud","dashboard"];e.audienceType&&c.includes(i)&&(e.audienceType==="b2c"?(s.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),s.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),s.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),s.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),s.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),s.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),s.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),s.push("")):e.audienceType==="b2b"?(s.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),s.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),s.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),s.push("- Testimonials: from business owners who use the platform"),s.push("- Features: business benefits ('Track dietary preferences across all orders')"),s.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),s.push("")):e.audienceType==="internal"&&(s.push("### Audience: internal staff tool. No marketing copy needed."),s.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),s.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),s.push(""))),r.length>0&&(s.push("### Already completed:"),r.forEach(_=>s.push(`- ${_}`)),s.push(""));let u=e.dataModel?Mi(t,e.dataModel):[];u.length>0&&(s.push("### Data model (from plan):"),u.forEach(_=>{let k=nr(_),y=mp(_.fields);s.push(`- **${k}**: ${y}`),s.push(` Schema file: \`db/schema/${k.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let h=e.pages?gp(t,e.pages):[];if(h.length>0&&(s.push("### Pages to create/update:"),h.forEach(_=>{let k=_.description?` \u2014 ${_.description}`:"";s.push(`- \`${ji(_)}\`${k}`)}),s.push("")),i==="crud"&&u.length>0&&u.forEach(_=>{let k=nr(_),y=k.toLowerCase().replace(/\s+/g,"-"),C=y.endsWith("s")?y:`${y}s`;s.push(`### Files for ${k} CRUD:`),s.push(`- List page: \`app/(dashboard)/${C}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${C}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${C}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${C}/actions.ts\``),s.push(`- DataTable columns: \`components/${y}-table-columns.tsx\``),s.push(`- Form: \`components/${y}-form.tsx\``),s.push("")}),l){s.push("## Design Doctrine (the standard for every UI step)"),s.push(""),s.push(Pi),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(Ci),s.push(""),s.push("### Color"),s.push(Ai),s.push(""),s.push("### Motion"),s.push(Ri),s.push(""),s.push("### Spatial Composition"),s.push(Ei),s.push(""),s.push("### Interaction"),s.push(Ni),s.push(""),s.push("### UX Writing"),s.push(Oi),s.push("");let _=o?Qe(o,"DESIGN.md"):void 0,k=_&&ut(_)?(()=>{try{return ps(_,"utf-8")}catch{return null}})():null;k&&(s.push("### Design system (source of truth: DESIGN.md):"),s.push(""),s.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."),s.push(""),s.push(k),s.push(""));let y=o?Qe(o,".mistflow","picker-render.html"):void 0;(i==="landing"||i==="design")&&y&&ut(y)&&(s.push("### Picked landing page render \u2014 ground-truth design contract"),s.push(""),s.push("The user picked their direction from a **fully-rendered HTML preview** of this landing page. That render is at `.mistflow/picker-render.html` (relative to the project root). **Read it** \u2014 it is the design contract the user agreed to."),s.push(""),s.push("Your job for this step is **mechanical translation**: convert that standalone HTML to Next.js Server Components + Client Components in `app/home/page.tsx` (and `components/landing/*.tsx` for any sections you split out). You are NOT redesigning. The user already picked the design \u2014 colors, fonts, composition, copy, and section order are LOCKED."),s.push(""),s.push("How to translate:\n1. **Preserve every voice sample exactly.** The H1 in the rendered HTML is the headline the user picked. The CTA button text is the CTA the user picked. Do NOT paraphrase, shorten, or 'improve' them. The picker is a contract.\n2. **Preserve the section order.** Each `<section data-section-id=\"X\">` in the rendered HTML maps to a TSX section in the SAME order. You may split each section into its own component file (`components/landing/{section-id}.tsx`) for readability \u2014 that's the only structural transformation allowed.\n3. **Migrate inline `<style>` to globals.css**. The render uses one inline `<style>` block; move those rules to `app/globals.css` so the rest of the app shares the design tokens. CSS custom properties (`--color-bg` / `--color-fg` / `--color-accent`) become the canonical design tokens.\n4. **Tailwind utility classes are FORBIDDEN in this step**, the same way they were forbidden in the render. The render already emits raw CSS; keep it that way in the TSX (use `className` to attach classes defined in globals.css, not Tailwind utilities).\n5. **Image slots:** each `<img data-image-slot=\"hero|feature-1|feature-2|feature-3|og|favicon\">` in the render points at picsum placeholder URLs. Replace each `src` with `/images/{slot}.png` \u2014 those files arrive in `public/images/` from the imagery pipeline (see Plan F A.6.1; check `mist_project action='imagery'` for status during the build). For the favicon slot, also wire `app/icon.png` to the same asset.\n6. **Do not add or remove sections.** If the render has 6 sections, the deployed page has 6 sections in the same order. Adding a CTA the user didn't pick is a bug; dropping a feature card the user did pick is also a bug.\n"),s.push("Bar: a designer comparing the picker iframe and the deployed /home page side by side should not be able to tell them apart at first glance. The HTML\u2192TSX translation is mechanical. Anything creative belongs in a separate refinement step the user explicitly asks for."),s.push(""))}if(i==="landing"||i==="design"){s.push("### File location for the landing page (non-negotiable):"),s.push('Write the landing page to **`app/home/page.tsx`** \u2014 NOT `app/page.tsx`. The scaffold\'s `middleware.ts` 308-redirects `/` to `/home` as a workaround for an OpenNext Cloudflare bug. Visitors land at `/` and end up on `/home` transparently. Internal links like `<Link href="/">` still work because the middleware does the redirect on every request.'),s.push("");let _=o?Qe(o,".mistflow","rules","landing.md"):null;_&&ut(_)?(s.push("### Landing page rules:"),s.push("**Read `.mistflow/rules/landing.md` BEFORE writing the landing page.** That file contains the full conversion structure, section catalog, motion menu, and anti-slop audit. Written to disk to keep this prompt under the per-tool-result token cap \u2014 read once, then write your code."),s.push("")):(s.push(Kn),s.push(""))}i==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(s.push(vp(e.layoutSpec)),s.push(""));let d=t.integrationId?Dt(t.integrationId):void 0;if(d){let _=jt(d.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${d.name}** (${d.category})`),_?.docsUrl&&s.push(`Official docs: ${_.docsUrl}`),_?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let k of _.envVars)s.push(`- \`${k.key}\`: ${k.description} \u2014 Get it at ${k.setupUrl}`);s.push(""),s.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.")}_?.packages?.length&&(s.push(""),s.push(`**Packages to install:** \`npm install ${_.packages.join(" ")}\``)),s.push(""),s.push("---"),s.push(d.prompt),s.push("---"),s.push(""),s.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."),s.push("")}let{reminders:v,skill:H}=await kp(i);return s.push(v),s.push(""),H&&(s.push(`### ${i} reference:`),s.push(H),s.push("")),l&&(s.push("## Self-Audit \u2014 run before submitting this file"),s.push(""),s.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.`),s.push(""),s.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.'),s.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."),s.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),s.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),s.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."),s.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),s.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),s.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.'),s.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).'),s.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)."),s.push(""),s.push(`If every answer is "no, I'm good" \u2014 then submit.`),s.push("")),s.join(`
|
|
5310
|
+
`)}async function Sp(t){let{projectPath:e,step:r,envVarsRequired:n,sessionId:i}=t,o=ap(e??process.cwd());if(n&&n.length>0)try{let b=tr(o,n);b.added.length>0&&console.error(`[implement] declared env.required: ${b.added.join(", ")}`)}catch(b){console.error("[implement] env var merge skipped:",b instanceof Error?b.message:String(b))}let s=up(o);if(!s)return Ve(o);if(!ut(Qe(o,"node_modules")))return p(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:b,ensureShadcnComponents:U}=await Promise.resolve().then(()=>(Wr(),Hr)),G=await b(o);G&&!s.projectId&&(s.projectId=G);let j=await U(o);j.failed?console.error(`[implement] ${j.failed}`):j.installed.length>0&&console.error(`[implement] installed ${j.installed.length} shadcn components`)}catch(b){console.error("[implement] self-heal skipped:",b instanceof Error?b.message:String(b))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return p("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let l,c=a.steps.find(b=>b.status==="in_progress");if(c){let b=a.steps.findIndex(U=>U.number===c.number);b!==-1&&(a.steps[b].status="completed",l=`Auto-completed step ${c.number} (${c.name})`,Di(o,s))}let u;if(r!==void 0){if(u=a.steps.find(b=>b.number===r),!u)return p(`Step ${r} not found. The plan has ${a.steps.length} steps (numbered ${a.steps[0].number} to ${a.steps[a.steps.length-1].number}).`,!0)}else if(u=a.steps.find(b=>b.status!=="completed"),!u)return p(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(b=>b.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let h=a.steps.filter(b=>b.status==="completed").map(b=>`Step ${b.number}: ${b.name}`),{readLocalState:d}=await Promise.resolve().then(()=>(vt(),on)),v=d(o),H=yp(u),_=[];if((H==="crud"||H==="schema")&&a.dataModel&&u.entities&&u.entities.length>0){let b=Mi(u,a.dataModel);for(let U of b){let G=nr(U);try{let j=(U.fields||[]).map(ie=>typeof ie=="string"?{name:ie,type:"text"}:{name:ie.name,type:hp(ie.type),required:ie.required!==!1});if(j.length===0)continue;let de=s.dbProvider==="neon"?"nextjs-neon":"nextjs",ee=await jr(de,G,j),A=0,he=0;for(let ie of ee.files){let Ee=Qe(o,ie.path);if(ut(Ee)){he++;continue}ip(lp(Ee),{recursive:!0}),ds(Ee,ie.content),A++}let V=Qe(o,"db","index.ts");if(ut(V)){let ie=ps(V,"utf-8");ie.includes(ee.dbExport)||ds(V,ie.trimEnd()+`
|
|
5311
5311
|
`+ee.dbExport+`
|
|
5312
|
-
`)}A>0?_.push(`${ee.entityPascal} CRUD (${A} new files${he>0?`, ${he} existing skipped`:""})`):he>0&&_.push(`${ee.entityPascal} CRUD (all ${he} files already exist \u2014 skipped)`)}catch(
|
|
5312
|
+
`)}A>0?_.push(`${ee.entityPascal} CRUD (${A} new files${he>0?`, ${he} existing skipped`:""})`):he>0&&_.push(`${ee.entityPascal} CRUD (all ${he} files already exist \u2014 skipped)`)}catch(j){console.error(`Module generation failed for ${G} (non-fatal):`,j instanceof Error?j.message:j)}}}let k=await xp(u,a,h,null,H,o),y=a.steps.findIndex(b=>b.number===u.number);if(y!==-1&&(s.plan.steps[y].status="in_progress",Di(o,s)),v&&s.projectId){let{syncRemoteState:b}=await Promise.resolve().then(()=>(vt(),on));b(s.projectId,v).catch(()=>{})}let C=a.steps.every(b=>b.status==="completed"||b.number===u.number),B;C?B=`THIS IS THE LAST STEP. Rules for speed:
|
|
5313
5313
|
|
|
5314
5314
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
5315
5315
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -5327,17 +5327,17 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
5327
5327
|
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.
|
|
5328
5328
|
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).
|
|
5329
5329
|
5. After writing ALL files, call mist_implement to move to the next step. If you used any process.env.X that isn't already in mistflow.json env.required, pass it via envVarsRequired on this call so the dashboard can prompt the user for it (skip keys covered by integration presets \u2014 those are pre-declared). Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let z=bp(H),te={stepNumber:u.number,totalSteps:a.steps.length,estimatedMinutes:z,announcement:`Starting step ${u.number} of ${a.steps.length}: ${u.name}. This step usually takes ${z.min}\u2013${z.max} minutes.`},Y=JSON.stringify({instruction:k,step:{number:u.number,name:u.name,description:u.description,status:"in_progress"},stepTiming:te,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.",...l?{autoCompleted:l}:{},..._.length>0?{generatedModules:_,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${h.length}/${a.steps.length} steps done`,nextAction:B}),F=Ti(o),I=F?.url??"http://localhost:3000",re=F?.port??3e3;return await dp(re)&&wi(o,u.number,a.steps.length)?(vi(o,u.number),Es(I,Y)):p(Y)}var Li={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:pp,handler:Sp};import{z as Fe}from"zod";import{z as mt}from"zod";import{resolve as Tp}from"path";Se();yt();var cf=mt.object({projectPath:mt.string().optional().describe("Path to the project directory (default: cwd)"),action:mt.enum(["set","list","delete"]).describe("Action to perform"),key:mt.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:mt.string().optional().describe("Environment variable value (required for 'set')"),category:mt.string().optional().describe("Category for the env var (default: 'custom')"),description:mt.string().optional().describe("Description of what this env var is for"),setupUrl:mt.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function Ui(t){let{projectPath:e,action:r,key:n,value:i,category:o,description:s,setupUrl:a}=t,l=Tp(e??process.cwd());if(!ke())return Ae("manage env vars");let u=rt(l)?.projectId;if(!u)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"set":return n?i?(await _r(u,n,i,{category:o,description:s,setupUrl:a}),p(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):p("Value is required. Provide the env var value.",!0):p("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let h=await Tr(u);return h.length===0?p(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):p(JSON.stringify({envVars:h.map(d=>({key:d.key,category:d.category,description:d.description,hasValue:d.has_value})),message:`${h.length} environment variable(s) configured.`}))}case"delete":return n?(await Ir(u,n),p(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):p("Key is required. Provide the env var name to delete.",!0);default:return p(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(h){if(h instanceof W)return p(h.message,!0);let d=h instanceof Error?h.message:"An unexpected error occurred";return p(d,!0)}}import{z as yn}from"zod";import{resolve as _p,join as Ip}from"path";import{existsSync as Pp,readFileSync as Cp,writeFileSync as Ap}from"fs";Se();yt();var yf=yn.object({projectPath:yn.string().optional().describe("Path to the project directory (default: cwd)"),action:yn.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:yn.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:yn.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function us(t,e){let r=Ip(t,"mistflow.json");if(!Pp(r))return;let n;try{n=JSON.parse(Cp(r,"utf-8"))}catch{return}n.domains=e,Ap(r,JSON.stringify(n,null,2)+`
|
|
5330
|
-
`)}async function $i(t){let{projectPath:e,action:r,domain:n,domainId:i}=t,o=_p(e??process.cwd());if(!ke())return Ae("manage custom domains");let a=rt(o)?.projectId;if(!a)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!n)return p("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await kr(a,n),c=await ot(a);return us(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await ot(a);return l.length===0?p(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):p(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!i){if(n){let h=(await ot(a)).find(d=>d.domain===n);if(h){let d=await
|
|
5330
|
+
`)}async function $i(t){let{projectPath:e,action:r,domain:n,domainId:i}=t,o=_p(e??process.cwd());if(!ke())return Ae("manage custom domains");let a=rt(o)?.projectId;if(!a)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!n)return p("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await kr(a,n),c=await ot(a);return us(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await ot(a);return l.length===0?p(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):p(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!i){if(n){let h=(await ot(a)).find(d=>d.domain===n);if(h){let d=await Dn(a,h.id);return p(JSON.stringify({domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message,message:d.status==="active"?`Domain '${d.domain}' is active and serving traffic.`:`Domain '${d.domain}' is ${d.status}. Make sure DNS records are configured correctly.`}))}return p(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return p("Provide either domainId or domain name to verify.",!0)}let l=await Dn(a,i),c=await ot(a);return us(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!i&&!n)return p("Provide either domainId or domain name to remove.",!0);let l=i;if(!l&&n){let h=(await ot(a)).find(d=>d.domain===n);if(!h)return p(`Domain '${n}' not found.`,!0);l=h.id}await xr(a,l);let c=await ot(a);return us(o,c.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return p(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof W)return p(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return p(c,!0)}}var Rp=Fe.object({resource:Fe.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Fe.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Fe.string().optional().describe("Path to the project directory (default: cwd)"),key:Fe.string().optional().describe("(env) Variable name"),value:Fe.string().optional().describe("(env set) Variable value"),category:Fe.string().optional().describe("(env set) Category"),description:Fe.string().optional().describe("(env set) Description"),setupUrl:Fe.string().optional().describe("(env set) URL to obtain the value"),domain:Fe.string().optional().describe("(domain) Domain name"),domainId:Fe.string().optional().describe("(domain) Domain ID")}),Fi={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:Rp,handler:async t=>{let e=t;switch(e.resource){case"env":return Ui({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return $i({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return p(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}};import{z as bn}from"zod";import{resolve as Ep}from"path";import{existsSync as Np}from"fs";import{join as Op}from"path";function Dp(t,e=15){let r=t.split(`
|
|
5331
5331
|
`).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
|
|
5332
|
-
`)}var
|
|
5332
|
+
`)}var jp=bn.object({projectPath:bn.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:bn.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:bn.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical install fits in 2 round-trips instead of 5-6. Default 20. Set 0 to disable."),sessionId:bn.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),qi={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:jp,handler:async(t,e)=>{let r=t;if(r.jobId){let l=await pt(r.jobId);if(!l)return p(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No install job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let c=r.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let h=l.elapsed,d=e?$e(e.server,e.progressToken,()=>`Install running (${h}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let v=await Ht(r.jobId,{timeoutMs:c*1e3,onPoll:H=>{h=H.elapsed}});v&&(l=v)}finally{d.stop()}}if(l.status==="running"||l.status==="starting")return p(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:Dp(l.logTail),nextAction:"Install still running after long-poll window. Call mist_install again with the same jobId to continue waiting."}));if(l.status==="complete"){let h=await _i(l.cwd),d=!1;h&&h.freshlyStarted?(d=await ki(h.state.url,15e3),d&&Ii(h.state.url)):h&&(d=!0);let v=h?d?` PREVIEW: Live dev server at ${h.state.url} (browser opened). TELL THE USER: "Your app is rendering at ${h.state.url} \u2014 it'll refresh live as it's built."`:` PREVIEW: Dev server starting at ${h.state.url} (still compiling). TELL THE USER: "Open ${h.state.url} in your browser in ~30s \u2014 your app will appear there and refresh live as it's built."`:"";return p(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,...h?{previewUrl:h.state.url,previewReady:d}:{},nextAction:`Dependencies installed.${v} Run mist_implement next to start executing plan steps.`}))}let u=Tt(l.id);return p(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:u,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${u.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let n=Ep(r.projectPath);if(!Np(Op(n,"package.json")))return p(`No package.json at ${n}. Confirm the path and that mist_init has scaffolded the project.`,!0);let s=`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 dt({type:"install",cmd:"sh",args:["-c",s],cwd:n,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return p(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:n,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+a.id+"' } immediately \u2014 each poll long-polls for up to 20s server-side so there's no need to sleep between calls. Typical duration: 30-90s."}))}};import{z as Wt}from"zod";import{resolve as Mp,join as qe}from"path";import{existsSync as He,readFileSync as Bi,statSync as Lp,readdirSync as Up}from"fs";var zi=100*1024;function $p(t){let e=0,r=0,n=[t];for(;n.length>0&&r<1e4;){let i=n.pop();r++;let o;try{o=Up(i)}catch{continue}for(let s of o){let a=qe(i,s),l;try{l=Lp(a)}catch{continue}l.isDirectory()?n.push(a):l.isFile()&&(e+=l.size)}}return e}function Fp(t){if(!(He(qe(t,"open-next.config.ts"))||He(qe(t,"open-next.config.js"))))return null;let r=qe(t,".open-next","worker.js");if(!He(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker entrypoint. Common causes: (1) open-next.config.ts is misconfigured, (2) a client component imports a Node-only API (fs, path, crypto node:* imports in 'use client' files), (3) the adapter crashed silently mid-build. Check the logTail above for "error"/"failed" messages, fix the offending file, and re-run mist_build.`;let n=qe(t,".open-next","server-functions","default");if(!He(n))return'Build exited 0 and .open-next/worker.js exists, but .open-next/server-functions/default/ is missing. The OpenNext adapter produced an orchestrator with no server bundle to import. Check the logTail above for "error"/"failed" messages near "Building server function: default..." and re-run mist_build.';let i=$p(n);return i<zi?`Build exited 0 but the server-functions bundle is only ${i} bytes (expected at least ${zi}). A healthy Next.js + OpenNext bundle is 5-50MB. This size suggests the adapter failed to bundle most of the app. Check the logTail for bundling errors and re-run mist_build.`:null}var qp=Wt.object({projectPath:Wt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Wt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Wt.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:Wt.number().min(0).max(50).optional().describe("On poll calls: long-poll for up to N seconds before returning, so a typical build fits in 2 round-trips instead of 6-8. Default 20. Set 0 to disable."),sessionId:Wt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});function Bp(t){let e=qe(Qn(),t,"stdout.log"),r=qe(Qn(),t,"stderr.log"),n="";try{He(e)&&(n+=Bi(e,"utf-8"))}catch{}try{He(r)&&(n+=`
|
|
5333
5333
|
`+Bi(r,"utf-8"))}catch{}return n}function zp(t,e=15){let r=t.split(`
|
|
5334
5334
|
`).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
|
|
5335
|
-
`)}function Hp(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let n of t.matchAll(e)){let i=n[1];if(i.startsWith(".")||i.startsWith("@/")||i.startsWith("~/"))continue;let o=i.startsWith("@")?i.split("/").slice(0,2).join("/"):i.split("/")[0];o&&r.add(o)}return[...r]}function Wp(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${St()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var Hi={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:qp,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await pt(r.jobId);if(!c)return p(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let u=r.waitSeconds??20;if(u>0&&(c.status==="running"||c.status==="starting")){let C=c.elapsed,B=e?$e(e.server,e.progressToken,()=>`Build running (${C}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let z=await Ht(r.jobId,{timeoutMs:u*1e3,onPoll:te=>{C=te.elapsed}});z&&(c=z)}finally{B.stop()}}if(c.status==="running"||c.status==="starting")return p(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:zp(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 C=Fp(c.cwd);if(C){let B=Tt(c.id);return p(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:B,error:C,nextAction:C+` Full build log: ${B.stdout} and ${B.stderr}.`}),!0)}return p(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let h=Bp(c.id),d=zn(h),v=Hp(h),H=Wp(h),_=Tt(c.id),k=` Full log: ${_.stdout} and ${_.stderr}.`,y=v.length>0?`Build failed with missing modules: ${v.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.${k}`:H?`${H}${k}`:d.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${k}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${k}`;return p(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:d,missingModules:v,logTail:c.logTail,logPaths:_,nextAction:y}),!0)}let n=Mp(r.projectPath);if(!He(qe(n,"package.json")))return p(`No package.json at ${n}. Run mist_init first.`,!0);if(!He(qe(n,"node_modules")))return p(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let i,o,s,a=He(qe(n,"open-next.config.ts"))||He(qe(n,"open-next.config.js"));if(r.script)i="npm",o=["run",r.script],s=r.script;else if(a){if(!Ut())return p(St(),!0);i="npx",o=["-y","@opennextjs/cloudflare","build"],s="@opennextjs/cloudflare build"}else i="npm",o=["run","build"],s="build";let l=await dt({type:"build",cmd:i,args:o,cwd:n});return p(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:s,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 Yp,readFileSync as Qp}from"fs";import{join as Xp}from"path";import{z as Gt}from"zod";Se();Se();import{existsSync as Gp,readdirSync as Vp}from"fs";import{join as Wi}from"path";import{pathToFileURL as Kp}from"url";async function Jp(t){let e=Wi(t,".mistflow","acceptance"),r=new Map;if(!Gp(e))return r;let n=Vp(e).filter(i=>i.endsWith(".spec.ts")||i.endsWith(".spec.js")||i.endsWith(".spec.mjs"));for(let i of n){let o=i.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!o)continue;let s=Wi(e,i);try{let a=await import(Kp(s).href),l=a.default??a.run;typeof l=="function"?r.set(o,l):console.error(`Probe ${i} doesn't export a default function (or named 'run'). Skipping.`)}catch(a){console.error(`Failed to load probe ${i}:`,a instanceof Error?a.message:a)}}return r}async function Gi(t,e){let{sessionId:r,projectPath:n,deployUrl:i,seedCredentials:o}=e,a=(await en(r)).criteria,l=await Jp(n),c=[];for(let u of a){let h=l.get(u.id);if(!h){c.push({criterion_id:u.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${u.id}.spec.ts`}});continue}try{await t.goto(i,{waitUntil:"domcontentloaded"});let d=await h(t,{url:i,criterion:u,seedCredentials:o});c.push({criterion_id:u.id,status:d.pass?"pass":"fail",evidence:{...d.detail?{detail:d.detail}:{},...d.screenshot?{screenshot:d.screenshot}:{}}})}catch(d){c.push({criterion_id:u.id,status:"fail",evidence:{error:d instanceof Error?d.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var Zp=Gt.object({projectPath:Gt.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:Gt.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:Gt.string().optional().describe("Deployment ID to associate QA results with. When set, results are uploaded to the backend and surfaced on the dashboard deployment card."),sessionId:Gt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),action:Gt.enum(["full","acceptance"]).default("full").describe("'full' (default) runs the standard post-deploy QA suite: HTTP pre-flight, landing render, login, sidebar pages, design audits. 'acceptance' runs only the per-criterion Playwright probes from .mistflow/acceptance/<criterion-id>.spec.ts against the deploy URL and uploads pass/fail results to the backend. Requires sessionId.")}),Ji={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:Zp,handler:async t=>{let e=t;if(e.action==="acceptance"){let n=await tu(e);return n.isError,n}let r=await nu(e);return r.isError,r}};function Yi(t){let e=Xp(t,"mistflow.json");if(!Yp(e))return null;try{return JSON.parse(Qp(e,"utf-8"))}catch{return null}}async function Vi(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await e.text();return{status:e.status,body:r}}catch(e){return{status:0,body:String(e)}}}async function eu(t,e,r){try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),i=await n.text(),o;try{o=JSON.parse(i)}catch{}return{status:n.status,json:o}}catch{return{status:0}}}async function Ki(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function ht(t,e,r){let n=[],i=o=>{o.type()==="error"&&n.push(o.text())};t.on("console",i);try{let o=await r(),s=await Ki(t);return{name:e,status:o.pass?"pass":"fail",detail:o.detail,fix:o.fix,screenshot:s,consoleErrors:n.length>0?n:void 0}}catch(o){let s=await Ki(t);return{name:e,status:"fail",detail:`Unexpected error: ${o instanceof Error?o.message:String(o)}`,screenshot:s,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",i)}}async function tu(t){if(!t.sessionId)return p("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=Yi(e),n=t.url;if(!n&&t.deploymentId)try{let a=await st(t.deploymentId);a.url&&(n=a.url)}catch(a){console.error(`[acceptance] Could not resolve URL from deploymentId ${t.deploymentId}:`,a instanceof Error?a.message:String(a))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa action='acceptance'.",!0);let i;if(t.deploymentId)try{let l=await Dn(t.deploymentId);l?.adminEmail&&l?.adminPassword&&(i={email:l.adminEmail,password:l.adminPassword})}catch(a){console.error("[acceptance] getSeedInfo failed (continuing without):",a instanceof Error?a.message:String(a))}let o,s;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(Ct(),Xt)),l=await a();o=l.context,s=l.page}catch(a){return p(`Playwright not available locally \u2014 install it with \`npx playwright install chromium\`. Detail: ${a instanceof Error?a.message:String(a)}`,!0)}try{let{criteria:a,results:l}=await Gi(s,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:i});try{await qr(t.sessionId,l)}catch(d){console.error("[acceptance] submitAcceptanceResults failed:",d instanceof Error?d.message:String(d))}let c=l.filter(d=>d.status==="pass").length,u=l.filter(d=>d.status==="fail").length,h=l.filter(d=>d.status==="skipped").length;return p(JSON.stringify({status:u===0?"pass":"fail",url:n,totals:{passed:c,failed:u,skipped:h,total:a.length},results:l.map(d=>({criterion_id:d.criterion_id,status:d.status,detail:d.evidence&&typeof d.evidence=="object"&&"detail"in d.evidence?d.evidence.detail:d.evidence&&typeof d.evidence=="object"&&"reason"in d.evidence?d.evidence.reason:void 0})),nextAction:u===0?"All required acceptance criteria passed. The app is shippable.":"Some criteria failed. Read the per-criterion detail, fix the underlying code, then re-run mist_qa action='acceptance'."}),u>0)}finally{if(o)try{await o.close()}catch{}}}async function nu(t){let e=t.projectPath??process.cwd(),r=Yi(e),n=t.url;if(!n&&t.deploymentId)try{let C=await st(t.deploymentId);C.url&&(n=C.url)}catch(C){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,C instanceof Error?C.message:String(C))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);n.startsWith("http")||(n=`https://${n}`);let i=r?.projectId,o=[],s=await Vi(`${n}/api/health`);if(s.status!==200)return o.push({name:"Health endpoint",status:"fail",detail:`Returns ${s.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),rr(n,o);o.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Vi(`${n}/api/auth/ok`);if(a.status!==200)return o.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."}),rr(n,o);o.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",u="QaTemp1!",h="single",d="user",v=[];async function H(C,B,z,te){let Z=await eu(`${n}/api/admin/seed`,{token:te,email:B,password:u,role:z});if(Z.status!==200||!Z.json)return console.error(`[qa] Seed (${C}) returned ${Z.status}`),null;let Y=Z.json.sessionToken;if(!Y)return null;let F=Z.json.seeded===!0;return{role:C,email:B,sessionToken:Y,password:F?u:void 0}}if(i){let C=await Dn(i);if(C){if(h=C.authMode??"single",d=C.defaultRole??"user",console.error(`[qa] auth_mode=${h}, default_role=${d}`),h!=="none"){let z=await H("actor",l,h==="multi"?"admin":d,C.seedToken);if(z&&v.push(z),h==="multi"){let te=await H("user",c,d,C.seedToken);te?v.push(te):o.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${d}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),h="none"}if(h!=="none"&&v.length===0)return o.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy injects ADMIN_SEED_TOKEN and stores it on the backend; the scaffold's /api/admin/seed route accepts { token, email, password, role } and creates synthetic QA users with the requested role."}),rr(n,o);let _,k,y;try{let{getIsolatedContext:C}=await Promise.resolve().then(()=>(Ct(),Xt)),B=await C();_=B.context,y=B.page}catch(C){let B=C instanceof Error?C.message:String(C);return p(JSON.stringify({status:"cannot_verify",url:n,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:B,httpChecks:o.map(({screenshot:z,...te})=>te),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${n}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${n}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_qa again for full verification."].join(`
|
|
5336
|
-
`)}),!1)}try{let C=await ht(y,"Landing page",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await y.waitForLoadState("networkidle").catch(()=>{});let Y=await y.evaluate(()=>{let I=document.body;if(!I)return"";let re=document.createTreeWalker(I,NodeFilter.SHOW_TEXT),q="",b;for(;b=re.nextNode();){let U=b.parentElement;if(U){let G=window.getComputedStyle(U);G.display!=="none"&&G.visibility!=="hidden"&&parseFloat(G.opacity)>0&&(q+=b.textContent?.trim()+" ")}}return q.trim()});if(Y.length<50)return{pass:!1,detail:`Landing page appears blank (${Y.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let F=y.url();return F.includes("/login")||F.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${Y.length} chars)`}});o.push(C),h==="none"&&o.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let B=v[0],z=(Y,F)=>v.length>1&&Y?`${F} (${Y.role})`:F,te=!1;if(B?.password){let Y=await ht(y,z(B,"Login"),async()=>{await y.goto(`${n}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let F=y.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),I=y.locator('input[type="password"], input[name="password"]');try{await F.first().waitFor({state:"visible",timeout:1e4})}catch{return{pass:!1,detail:"Login page has no visible email input field",fix:"Check app/(auth)/login/page.tsx renders a login form with email and password inputs."}}await F.first().fill(B.email),await I.first().fill(B.password),await y.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await y.waitForURL(q=>!q.pathname.includes("/login"),{timeout:1e4})}catch{let q=await y.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:q?`Login failed: ${q}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified QA accounts."}}return te=!0,{pass:!0,detail:`Logged in, redirected to ${y.url()}`}});o.push(Y)}else B&&o.push({name:z(B,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!te&&B){let Y=new URL(n).hostname,F=n.startsWith("https");await _.addCookies([{name:F?"__Secure-better-auth.session_token":"better-auth.session_token",value:B.sessionToken,domain:Y,path:"/",httpOnly:!0,secure:F,sameSite:"Lax"}]),console.error(`[qa] Injected ${B.role} cookie for primary walk`)}if(B){let Y=await ht(y,z(B,"Dashboard"),async()=>{y.url().includes("/dashboard")||(await y.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}),new URL(y.url()).pathname==="/"&&(await y.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{})));let re=await y.content();return re.length<1e3?{pass:!1,detail:`Dashboard page is very small (${re.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await y.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 (${re.length} bytes)`}});o.push(Y);let F=await y.evaluate(()=>{let re=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(b=>{let U=b.getAttribute("href");U&&U.startsWith("/")&&!U.startsWith("/api")&&!U.includes("[")&&U!=="/dashboard"&&U!=="/"&&!U.includes("/login")&&!U.includes("/sign")&&re.push(U)}),[...new Set(re)]});if(F.length>0){let re=0,q=[];for(let b of F.slice(0,8)){let U=await ht(y,z(B,`Page: ${b}`),async()=>{await y.goto(`${n}${b}`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let G=await y.title(),
|
|
5335
|
+
`)}function Hp(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let n of t.matchAll(e)){let i=n[1];if(i.startsWith(".")||i.startsWith("@/")||i.startsWith("~/"))continue;let o=i.startsWith("@")?i.split("/").slice(0,2).join("/"):i.split("/")[0];o&&r.add(o)}return[...r]}function Wp(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${St()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var Hi={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:qp,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await pt(r.jobId);if(!c)return p(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let u=r.waitSeconds??20;if(u>0&&(c.status==="running"||c.status==="starting")){let C=c.elapsed,B=e?$e(e.server,e.progressToken,()=>`Build running (${C}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let z=await Ht(r.jobId,{timeoutMs:u*1e3,onPoll:te=>{C=te.elapsed}});z&&(c=z)}finally{B.stop()}}if(c.status==="running"||c.status==="starting")return p(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:zp(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 C=Fp(c.cwd);if(C){let B=Tt(c.id);return p(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:B,error:C,nextAction:C+` Full build log: ${B.stdout} and ${B.stderr}.`}),!0)}return p(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let h=Bp(c.id),d=zn(h),v=Hp(h),H=Wp(h),_=Tt(c.id),k=` Full log: ${_.stdout} and ${_.stderr}.`,y=v.length>0?`Build failed with missing modules: ${v.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.${k}`:H?`${H}${k}`:d.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${k}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${k}`;return p(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:d,missingModules:v,logTail:c.logTail,logPaths:_,nextAction:y}),!0)}let n=Mp(r.projectPath);if(!He(qe(n,"package.json")))return p(`No package.json at ${n}. Run mist_init first.`,!0);if(!He(qe(n,"node_modules")))return p(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let i,o,s,a=He(qe(n,"open-next.config.ts"))||He(qe(n,"open-next.config.js"));if(r.script)i="npm",o=["run",r.script],s=r.script;else if(a){if(!Ut())return p(St(),!0);i="npx",o=["-y","@opennextjs/cloudflare","build"],s="@opennextjs/cloudflare build"}else i="npm",o=["run","build"],s="build";let l=await dt({type:"build",cmd:i,args:o,cwd:n});return p(JSON.stringify({status:"running",jobId:l.id,startedAt:l.startedAt,cwd:n,script:s,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 Yp,readFileSync as Qp}from"fs";import{join as Xp}from"path";import{z as Gt}from"zod";Se();Se();import{existsSync as Gp,readdirSync as Vp}from"fs";import{join as Wi}from"path";import{pathToFileURL as Kp}from"url";async function Jp(t){let e=Wi(t,".mistflow","acceptance"),r=new Map;if(!Gp(e))return r;let n=Vp(e).filter(i=>i.endsWith(".spec.ts")||i.endsWith(".spec.js")||i.endsWith(".spec.mjs"));for(let i of n){let o=i.replace(/\.spec\.(ts|js|mjs)$/,"").trim();if(!o)continue;let s=Wi(e,i);try{let a=await import(Kp(s).href),l=a.default??a.run;typeof l=="function"?r.set(o,l):console.error(`Probe ${i} doesn't export a default function (or named 'run'). Skipping.`)}catch(a){console.error(`Failed to load probe ${i}:`,a instanceof Error?a.message:a)}}return r}async function Gi(t,e){let{sessionId:r,projectPath:n,deployUrl:i,seedCredentials:o}=e,a=(await en(r)).criteria,l=await Jp(n),c=[];for(let u of a){let h=l.get(u.id);if(!h){c.push({criterion_id:u.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${u.id}.spec.ts`}});continue}try{await t.goto(i,{waitUntil:"domcontentloaded"});let d=await h(t,{url:i,criterion:u,seedCredentials:o});c.push({criterion_id:u.id,status:d.pass?"pass":"fail",evidence:{...d.detail?{detail:d.detail}:{},...d.screenshot?{screenshot:d.screenshot}:{}}})}catch(d){c.push({criterion_id:u.id,status:"fail",evidence:{error:d instanceof Error?d.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var Zp=Gt.object({projectPath:Gt.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:Gt.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:Gt.string().optional().describe("Deployment ID to associate QA results with. When set, results are uploaded to the backend and surfaced on the dashboard deployment card."),sessionId:Gt.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs."),action:Gt.enum(["full","acceptance"]).default("full").describe("'full' (default) runs the standard post-deploy QA suite: HTTP pre-flight, landing render, login, sidebar pages, design audits. 'acceptance' runs only the per-criterion Playwright probes from .mistflow/acceptance/<criterion-id>.spec.ts against the deploy URL and uploads pass/fail results to the backend. Requires sessionId.")}),Ji={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:Zp,handler:async t=>{let e=t;if(e.action==="acceptance"){let n=await tu(e);return n.isError,n}let r=await nu(e);return r.isError,r}};function Yi(t){let e=Xp(t,"mistflow.json");if(!Yp(e))return null;try{return JSON.parse(Qp(e,"utf-8"))}catch{return null}}async function Vi(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await e.text();return{status:e.status,body:r}}catch(e){return{status:0,body:String(e)}}}async function eu(t,e,r){try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),i=await n.text(),o;try{o=JSON.parse(i)}catch{}return{status:n.status,json:o}}catch{return{status:0}}}async function Ki(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function ht(t,e,r){let n=[],i=o=>{o.type()==="error"&&n.push(o.text())};t.on("console",i);try{let o=await r(),s=await Ki(t);return{name:e,status:o.pass?"pass":"fail",detail:o.detail,fix:o.fix,screenshot:s,consoleErrors:n.length>0?n:void 0}}catch(o){let s=await Ki(t);return{name:e,status:"fail",detail:`Unexpected error: ${o instanceof Error?o.message:String(o)}`,screenshot:s,consoleErrors:n.length>0?n:void 0}}finally{t.removeListener("console",i)}}async function tu(t){if(!t.sessionId)return p("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=Yi(e),n=t.url;if(!n&&t.deploymentId)try{let a=await st(t.deploymentId);a.url&&(n=a.url)}catch(a){console.error(`[acceptance] Could not resolve URL from deploymentId ${t.deploymentId}:`,a instanceof Error?a.message:String(a))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa action='acceptance'.",!0);let i;if(t.deploymentId)try{let l=await jn(t.deploymentId);l?.adminEmail&&l?.adminPassword&&(i={email:l.adminEmail,password:l.adminPassword})}catch(a){console.error("[acceptance] getSeedInfo failed (continuing without):",a instanceof Error?a.message:String(a))}let o,s;try{let{getIsolatedContext:a}=await Promise.resolve().then(()=>(Ct(),Xt)),l=await a();o=l.context,s=l.page}catch(a){return p(`Playwright not available locally \u2014 install it with \`npx playwright install chromium\`. Detail: ${a instanceof Error?a.message:String(a)}`,!0)}try{let{criteria:a,results:l}=await Gi(s,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:i});try{await qr(t.sessionId,l)}catch(d){console.error("[acceptance] submitAcceptanceResults failed:",d instanceof Error?d.message:String(d))}let c=l.filter(d=>d.status==="pass").length,u=l.filter(d=>d.status==="fail").length,h=l.filter(d=>d.status==="skipped").length;return p(JSON.stringify({status:u===0?"pass":"fail",url:n,totals:{passed:c,failed:u,skipped:h,total:a.length},results:l.map(d=>({criterion_id:d.criterion_id,status:d.status,detail:d.evidence&&typeof d.evidence=="object"&&"detail"in d.evidence?d.evidence.detail:d.evidence&&typeof d.evidence=="object"&&"reason"in d.evidence?d.evidence.reason:void 0})),nextAction:u===0?"All required acceptance criteria passed. The app is shippable.":"Some criteria failed. Read the per-criterion detail, fix the underlying code, then re-run mist_qa action='acceptance'."}),u>0)}finally{if(o)try{await o.close()}catch{}}}async function nu(t){let e=t.projectPath??process.cwd(),r=Yi(e),n=t.url;if(!n&&t.deploymentId)try{let C=await st(t.deploymentId);C.url&&(n=C.url)}catch(C){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,C instanceof Error?C.message:String(C))}if(n||(n=r?.deploy?.url),!n)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);n.startsWith("http")||(n=`https://${n}`);let i=r?.projectId,o=[],s=await Vi(`${n}/api/health`);if(s.status!==200)return o.push({name:"Health endpoint",status:"fail",detail:`Returns ${s.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),rr(n,o);o.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Vi(`${n}/api/auth/ok`);if(a.status!==200)return o.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."}),rr(n,o);o.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l="qa-actor@qa.mistflow.local",c="qa-user@qa.mistflow.local",u="QaTemp1!",h="single",d="user",v=[];async function H(C,B,z,te){let Z=await eu(`${n}/api/admin/seed`,{token:te,email:B,password:u,role:z});if(Z.status!==200||!Z.json)return console.error(`[qa] Seed (${C}) returned ${Z.status}`),null;let Y=Z.json.sessionToken;if(!Y)return null;let F=Z.json.seeded===!0;return{role:C,email:B,sessionToken:Y,password:F?u:void 0}}if(i){let C=await jn(i);if(C){if(h=C.authMode??"single",d=C.defaultRole??"user",console.error(`[qa] auth_mode=${h}, default_role=${d}`),h!=="none"){let z=await H("actor",l,h==="multi"?"admin":d,C.seedToken);if(z&&v.push(z),h==="multi"){let te=await H("user",c,d,C.seedToken);te?v.push(te):o.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${d}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),h="none"}if(h!=="none"&&v.length===0)return o.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy injects ADMIN_SEED_TOKEN and stores it on the backend; the scaffold's /api/admin/seed route accepts { token, email, password, role } and creates synthetic QA users with the requested role."}),rr(n,o);let _,k,y;try{let{getIsolatedContext:C}=await Promise.resolve().then(()=>(Ct(),Xt)),B=await C();_=B.context,y=B.page}catch(C){let B=C instanceof Error?C.message:String(C);return p(JSON.stringify({status:"cannot_verify",url:n,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:B,httpChecks:o.map(({screenshot:z,...te})=>te),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${n}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${n}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_qa again for full verification."].join(`
|
|
5336
|
+
`)}),!1)}try{let C=await ht(y,"Landing page",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await y.waitForLoadState("networkidle").catch(()=>{});let Y=await y.evaluate(()=>{let I=document.body;if(!I)return"";let re=document.createTreeWalker(I,NodeFilter.SHOW_TEXT),q="",b;for(;b=re.nextNode();){let U=b.parentElement;if(U){let G=window.getComputedStyle(U);G.display!=="none"&&G.visibility!=="hidden"&&parseFloat(G.opacity)>0&&(q+=b.textContent?.trim()+" ")}}return q.trim()});if(Y.length<50)return{pass:!1,detail:`Landing page appears blank (${Y.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let F=y.url();return F.includes("/login")||F.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${Y.length} chars)`}});o.push(C),h==="none"&&o.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let B=v[0],z=(Y,F)=>v.length>1&&Y?`${F} (${Y.role})`:F,te=!1;if(B?.password){let Y=await ht(y,z(B,"Login"),async()=>{await y.goto(`${n}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let F=y.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),I=y.locator('input[type="password"], input[name="password"]');try{await F.first().waitFor({state:"visible",timeout:1e4})}catch{return{pass:!1,detail:"Login page has no visible email input field",fix:"Check app/(auth)/login/page.tsx renders a login form with email and password inputs."}}await F.first().fill(B.email),await I.first().fill(B.password),await y.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await y.waitForURL(q=>!q.pathname.includes("/login"),{timeout:1e4})}catch{let q=await y.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:q?`Login failed: ${q}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified QA accounts."}}return te=!0,{pass:!0,detail:`Logged in, redirected to ${y.url()}`}});o.push(Y)}else B&&o.push({name:z(B,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!te&&B){let Y=new URL(n).hostname,F=n.startsWith("https");await _.addCookies([{name:F?"__Secure-better-auth.session_token":"better-auth.session_token",value:B.sessionToken,domain:Y,path:"/",httpOnly:!0,secure:F,sameSite:"Lax"}]),console.error(`[qa] Injected ${B.role} cookie for primary walk`)}if(B){let Y=await ht(y,z(B,"Dashboard"),async()=>{y.url().includes("/dashboard")||(await y.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}),new URL(y.url()).pathname==="/"&&(await y.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{})));let re=await y.content();return re.length<1e3?{pass:!1,detail:`Dashboard page is very small (${re.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await y.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 (${re.length} bytes)`}});o.push(Y);let F=await y.evaluate(()=>{let re=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(b=>{let U=b.getAttribute("href");U&&U.startsWith("/")&&!U.startsWith("/api")&&!U.includes("[")&&U!=="/dashboard"&&U!=="/"&&!U.includes("/login")&&!U.includes("/sign")&&re.push(U)}),[...new Set(re)]});if(F.length>0){let re=0,q=[];for(let b of F.slice(0,8)){let U=await ht(y,z(B,`Page: ${b}`),async()=>{await y.goto(`${n}${b}`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let G=await y.title(),j=await y.content();return G.toLowerCase().includes("500")||G.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."}:G.toLowerCase().includes("404")||G.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${b} not found. Create the page or remove the nav link.`}:await y.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."}:j.length<500?{pass:!1,detail:`Page is very small (${j.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});U.status==="fail"&&(re++,q.push(b)),o.push(U)}}let I=await ht(y,"Design quality",async()=>{let re=y.url().includes("/dashboard")?y.url():`${n}/dashboard`;y.url().includes("/dashboard")||(await y.goto(re,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}));let q=await y.evaluate(()=>{let b=[],U=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),G=new Set;U.forEach(Q=>{G.add(window.getComputedStyle(Q).fontSize)}),U.length>=3&&G.size<2&&b.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 j=Array.from(U).map(Q=>parseInt(Q.tagName.charAt(1),10));for(let Q=1;Q<j.length;Q++)if(j[Q]-j[Q-1]>1){b.push(`TYPOGRAPHY: Heading level skipped (h${j[Q-1]} -> h${j[Q]}). Use sequential heading levels for accessibility.`);break}let de=document.querySelectorAll("*"),ee=!1,A=!1;de.forEach(Q=>{let ge=window.getComputedStyle(Q);ge.backgroundColor==="rgb(0, 0, 0)"&&Q.clientHeight>100&&Q.clientWidth>200&&(ee=!0);let Ne=ge.backgroundColor,et=ge.color;if(Ne&&!Ne.includes("0, 0, 0")&&!Ne.includes("255, 255, 255")&&Ne!=="rgba(0, 0, 0, 0)"&&Ne!=="transparent"&&et.match(/rgb\((\d+), (\d+), (\d+)\)/)){let gt=et.match(/rgb\((\d+), (\d+), (\d+)\)/);if(gt){let[tt,ze,m]=[parseInt(gt[1]),parseInt(gt[2]),parseInt(gt[3])],g=Math.abs(tt-ze)<10&&Math.abs(ze-m)<10&&tt>80&&tt<180,w=Ne.match(/rgb\((\d+), (\d+), (\d+)\)/);if(g&&w){let[T,N,$]=[parseInt(w[1]),parseInt(w[2]),parseInt(w[3])];!(Math.abs(T-N)<15&&Math.abs(N-$)<15)&&Q.textContent&&Q.textContent.trim().length>0&&(A=!0)}}}}),ee&&b.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)."),A&&b.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 he=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),V=!1;he.forEach(Q=>{Q.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(V=!0)}),V&&b.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let ie=document.querySelectorAll("p, li, span, div"),Ee=0,we=0;ie.forEach(Q=>{Q.textContent&&Q.textContent.trim().length>20&&Q.clientHeight>0&&(we++,window.getComputedStyle(Q).textAlign==="center"&&Ee++)}),we>5&&Ee/we>.7&&b.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let ye=new Set;de.forEach(Q=>{let ge=window.getComputedStyle(Q);ge.gap&&ge.gap!=="normal"&&ge.gap!=="0px"&&ye.add(ge.gap)}),ye.size===1&&de.length>20&&b.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let je=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(Q=>{Q.querySelectorAll("tbody tr").length===0&&(Q.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||b.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 We=document.querySelectorAll("style"),Be=!1;We.forEach(Q=>{let ge=Q.textContent||"";(ge.includes("bounce")||ge.includes("elastic")||ge.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Be=!0)}),Be&&b.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']"),Ie=0;return Ze.forEach(Q=>{let ge=Q.getBoundingClientRect();ge.width>0&&ge.height>0&&(ge.width<32||ge.height<32)&&Ie++}),Ie>3&&b.push(`ACCESSIBILITY: ${Ie} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),b});return q.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${q.length} design quality issue(s) found:
|
|
5337
5337
|
${q.map((b,U)=>`${U+1}. ${b}`).join(`
|
|
5338
|
-
`)}`,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."}});o.push(I)}if(o.find(Y=>Y.name==="Landing page"&&Y.status==="pass")){let Y=await ht(y,"Landing design quality",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let F=await y.evaluate(()=>{let I=[];document.querySelectorAll("*").forEach(U=>{let G=window.getComputedStyle(U);(G.getPropertyValue("-webkit-background-clip")||G.getPropertyValue("background-clip"))==="text"&&U.textContent&&U.textContent.trim().length>0&&I.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let q=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(q){let U=(q.textContent||"").toLowerCase(),G=["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
|
|
5338
|
+
`)}`,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."}});o.push(I)}if(o.find(Y=>Y.name==="Landing page"&&Y.status==="pass")){let Y=await ht(y,"Landing design quality",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let F=await y.evaluate(()=>{let I=[];document.querySelectorAll("*").forEach(U=>{let G=window.getComputedStyle(U);(G.getPropertyValue("-webkit-background-clip")||G.getPropertyValue("background-clip"))==="text"&&U.textContent&&U.textContent.trim().length>0&&I.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let q=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(q){let U=(q.textContent||"").toLowerCase(),G=["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 j of G)if(U.match(new RegExp(j))){I.push(`COPY: Generic hero text detected ('${j}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(U=>{let j=window.getComputedStyle(U).gridTemplateColumns;if(j){let de=j.split(" ").filter(A=>A!=="").length,ee=U.children;if(de===3&&ee.length===3){let A=Array.from(ee).map(ie=>ie.offsetHeight),he=A.every(ie=>Math.abs(ie-A[0])<5),V=Array.from(ee).every(ie=>{let Ee=ie.querySelectorAll("svg"),we=ie.querySelectorAll("h2, h3, h4"),ye=ie.querySelectorAll("p");return Ee.length>=1&&we.length>=1&&ye.length>=1});he&&V&&I.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.")}}}),I});return F.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${F.length} landing design issue(s):
|
|
5339
5339
|
${F.map((I,re)=>`${re+1}. ${I}`).join(`
|
|
5340
|
-
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});o.push(Y)}let Z=v[1];if(Z){let{getIsolatedContext:Y}=await Promise.resolve().then(()=>(Ct(),Xt)),F=await Y();k=F.context;let I=F.page,re=new URL(n).hostname,q=n.startsWith("https");await k.addCookies([{name:q?"__Secure-better-auth.session_token":"better-auth.session_token",value:Z.sessionToken,domain:re,path:"/",httpOnly:!0,secure:q,sameSite:"Lax"}]),console.error(`[qa] Injected ${Z.role} cookie for secondary walk`);let b=await ht(I,z(Z,"Dashboard"),async()=>{await I.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await I.waitForLoadState("networkidle").catch(()=>{}),new URL(I.url()).pathname==="/"&&(await I.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await I.waitForLoadState("networkidle").catch(()=>{}));let G=await I.content();return G.length<1e3?{pass:!1,detail:`Dashboard is very small (${G.length} bytes) for the default-role user`,fix:"The default-role user dashboard crashed or rendered empty. Check that role-gated server components handle non-admin roles without throwing."}:await I.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary for the default-role user",fix:"A server component crashed under the non-admin role. Likely a role check that throws instead of redirecting."}:{pass:!0,detail:`Loads (${G.length} bytes)`}});o.push(b);let U=await I.evaluate(()=>{let G=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(
|
|
5340
|
+
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});o.push(Y)}let Z=v[1];if(Z){let{getIsolatedContext:Y}=await Promise.resolve().then(()=>(Ct(),Xt)),F=await Y();k=F.context;let I=F.page,re=new URL(n).hostname,q=n.startsWith("https");await k.addCookies([{name:q?"__Secure-better-auth.session_token":"better-auth.session_token",value:Z.sessionToken,domain:re,path:"/",httpOnly:!0,secure:q,sameSite:"Lax"}]),console.error(`[qa] Injected ${Z.role} cookie for secondary walk`);let b=await ht(I,z(Z,"Dashboard"),async()=>{await I.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await I.waitForLoadState("networkidle").catch(()=>{}),new URL(I.url()).pathname==="/"&&(await I.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await I.waitForLoadState("networkidle").catch(()=>{}));let G=await I.content();return G.length<1e3?{pass:!1,detail:`Dashboard is very small (${G.length} bytes) for the default-role user`,fix:"The default-role user dashboard crashed or rendered empty. Check that role-gated server components handle non-admin roles without throwing."}:await I.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary for the default-role user",fix:"A server component crashed under the non-admin role. Likely a role check that throws instead of redirecting."}:{pass:!0,detail:`Loads (${G.length} bytes)`}});o.push(b);let U=await I.evaluate(()=>{let G=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(j=>{let de=j.getAttribute("href");de&&de.startsWith("/")&&!de.startsWith("/api")&&!de.includes("[")&&de!=="/dashboard"&&de!=="/"&&!de.includes("/login")&&!de.includes("/sign")&&G.push(de)}),[...new Set(G)]});for(let G of U.slice(0,8)){let j=await ht(I,z(Z,`Page: ${G}`),async()=>{await I.goto(`${n}${G}`,{waitUntil:"domcontentloaded",timeout:15e3}),await I.waitForLoadState("networkidle").catch(()=>{});let de=await I.title(),ee=await I.content();return de.toLowerCase().includes("500")||de.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 for the default-role user",fix:"Server component crashed under the non-admin role. Check role gates use redirect() not throw."}:de.toLowerCase().includes("404")||de.toLowerCase().includes("not found")?{pass:!0,detail:"404 (likely admin-only \u2014 acceptable)"}:await I.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Error boundary on page for default-role user",fix:"Role-gated content crashed. Use a graceful fallback."}:ee.length<500?{pass:!1,detail:`Page very small (${ee.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});o.push(j)}}}finally{_&&await _.close().catch(()=>{}),k&&await k.close().catch(()=>{})}if(t.deploymentId){let C=o.filter(te=>te.status==="fail"),B=o.filter(te=>te.status==="pass"),z=Date.now();await Sr(t.deploymentId,{checks:o.map(({screenshot:te,...Z})=>Z),overall:C.length===0?"pass":"fail",passed:B.length,failed:C.length,duration_ms:Date.now()-z}).catch(()=>{})}return rr(n,o)}function rr(t,e){let r=e.filter(o=>o.status==="fail"),n=e.filter(o=>o.status==="pass"),i=[];if(r.length===0)i.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${e.length} checks OK. The app is working correctly.`,url:t,checks:e.map(({screenshot:o,...s})=>s)})});else{let o=r.map((s,a)=>`${a+1}. **${s.name}**: ${s.detail}
|
|
5341
5341
|
Fix: ${s.fix}`).join(`
|
|
5342
5342
|
|
|
5343
5343
|
`);i.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${r.length} issue(s) on the live app. Fix them and redeploy.`,url:t,passed:n.length,failed:r.length,checks:e.map(({screenshot:s,...a})=>a),fixInstructions:`The deployed app at ${t} has ${r.length} issue(s):
|
|
@@ -5347,7 +5347,7 @@ ${o}
|
|
|
5347
5347
|
Fix these issues in the source code, then call mist_deploy with action='deploy'${t.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let o of e)o.screenshot&&i.push({type:"image",data:o.screenshot,mimeType:"image/png"});return{content:i}}import{z as Xe}from"zod";import{resolve as iu,join as or}from"path";import{existsSync as ir}from"fs";Se();yt();yt();import{existsSync as sr,readdirSync as ru,statSync as Qi,unlinkSync as Xi}from"fs";import{join as _t}from"path";import{execFile as su}from"child_process";function ou(t,e){let r=0;for(let n of e){let i=_t(t,n);if(sr(i))try{let o=Qi(i);if(o.isFile())r++;else if(o.isDirectory()){let s=[i];for(;s.length;){let a=s.pop(),l=ru(a,{withFileTypes:!0});for(let c of l){let u=_t(a,c.name);c.isDirectory()?s.push(u):r++}}}}catch{}}return r}function Zi(t,e,r){return new Promise(n=>{su("tar",t,{cwd:e,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(i,o,s)=>{n({success:!i,stderr:s?.toString()??""})})})}async function ea(t){let e=_t(t,".open-next-build.tar.gz"),r=[".open-next"];sr(_t(t,"db"))&&r.push("db"),sr(_t(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),sr(_t(t,"package.json"))&&r.push("package.json");let n=ou(t,r),i=await Zi(["-czf",e,"-C",t,...r],t,12e4);if(!i.success){try{Xi(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(i.stderr?`
|
|
5348
5348
|
${i.stderr.slice(-500)}`:""))}let o=0;try{o=Qi(e).size}catch{}return{path:e,sizeBytes:o,fileCount:n}}async function ta(t){let e=_t(t,".mistflow-source.tar.gz");return(await Zi(["-czf",e,"-C",t,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],t,12e4)).success?e:null}function ms(t){if(t)try{Xi(t)}catch{}}function na(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function ra(t){switch(t){case"pending":return"Provisioning...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";case"live":return"Live!";case"failed":return"Failed";default:return`Status: ${t}`}}var au=Xe.object({action:Xe.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:Xe.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:Xe.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:Xe.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:Xe.string().optional().describe("Optional override for the owner email. Defaults to the email of whoever ran mist_setup (read from ~/.mistflow/credentials.json). Multi-role apps auto-promote this email to admin on first signup; single-role apps just attach it to the project for the dashboard's Owner Access card. Pass explicitly only when the deploying user is not the intended owner."),waitSeconds:Xe.number().min(0).max(20).optional().describe("On action='status' calls: long-poll the backend for up to N seconds (0-20) before returning, so a typical deploy fits in 1-2 round-trips instead of 6-12. Default 20. Ignored for non-status actions."),envVarsRequired:Xe.array(er).optional().describe("Last chance to declare env vars introduced since the last implement call. Merged into mistflow.json env.required before the build is tarred, so the backend's deploy-time check picks them up. Skip keys covered by integration presets (Stripe, Resend, etc.). Only used for action='deploy'."),sessionId:Xe.string().uuid().optional().describe("Backend session ID. Pass through from mist_plan response so state guards apply and session state advances as the tool runs.")});function sa(t){return ir(or(t,".open-next"))}function lu(t){return rt(t)?.deploy?.strategy==="staging"?"preview":null}async function cu(t,e){if(!(ir(or(t,"open-next.config.ts"))||ir(or(t,"open-next.config.js"))))return{kind:"failed",result:p(`No .open-next/ build output at ${t}, and no open-next.config.* either. This project is not configured for the Cloudflare adapter \u2014 mist_deploy ships the .open-next/ artifact, not raw source. If this is a Mistflow project, re-run mist_init to restore the OpenNext config.`,!0)};if(!ir(or(t,"node_modules")))return{kind:"failed",result:p(`node_modules is missing at ${t}. Call mist_install { projectPath } first, then mist_deploy.`,!0)};if(!Ut())return{kind:"failed",result:p(St(),!0)};let n=await dt({type:"build",cmd:"npx",args:["-y","@opennextjs/cloudflare","build"],cwd:t}),i=e?$e(e.server,e.progressToken,()=>`Auto-building before deploy \u2014 OpenNext adapter (${n.id})`):{stop:()=>{}},o;try{o=await Ht(n.id,{timeoutMs:45e3})}finally{i.stop()}if(!o)return{kind:"failed",result:p(`Auto-build job ${n.id} disappeared. Run mist_build { projectPath } manually, then mist_deploy.`,!0)};if(o.status==="running"||o.status==="starting")return{kind:"running",result:p(JSON.stringify({status:"building",buildJobId:n.id,phase:"auto-build",nextAction:`Build is still running after the 45s inline window. Call mist_build { jobId: '${n.id}' } to keep waiting (long-polls server-side), then call mist_deploy { action: 'deploy', projectPath } again. Do NOT ask the user \u2014 the build is in flight, just keep going.`}))};if(o.status==="complete"&&sa(t))return{kind:"ok"};let s=Tt(n.id),a=(o.logTail??"").split(`
|
|
5349
5349
|
`).slice(-30).join(`
|
|
5350
|
-
`);return{kind:"failed",result:p(JSON.stringify({status:"build_failed",buildJobId:n.id,exitCode:o.exitCode,logTail:a,logPaths:s,nextAction:`Auto-build before deploy failed (exit ${o.exitCode??"?"}). Read the logTail or run mist_debug { projectPath, jobId: '${n.id}' } to extract structured errors. Fix the code, then call mist_deploy { action: 'deploy', projectPath } again.`}),!0)}}async function du(t){let e=iu(t.projectPath);if(!ke())return Ae("deploy");let r=rt(e),n=r?.projectId;if(!n){if(!r?.name)return p(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);try{n=(await wt(r.name,{dbProvider:r.dbProvider,requestedSubdomain:r.requestedSubdomain})).id,fr(e,{projectId:n}),console.error(`[deploy] auto-registered project ${n.slice(0,8)} (${r.name})`+(r.requestedSubdomain?` at ${r.requestedSubdomain}.mistflow.app`:""))}catch(l){let c=l instanceof W||l instanceof Error?l.message:String(l);return p(`Auto-register before deploy failed: ${c}. mistflow.json has no projectId \u2014 mist_init couldn't register the project earlier (likely offline or backend timeout). Try again in a moment, or check Mistflow status.`,!0)}}if(!sa(e)){let l=await cu(e,t.ctx);if(l.kind==="running"||l.kind==="failed")return l.result}let i=t.environment??lu(e)??"production",o=t.adminEmail??
|
|
5350
|
+
`);return{kind:"failed",result:p(JSON.stringify({status:"build_failed",buildJobId:n.id,exitCode:o.exitCode,logTail:a,logPaths:s,nextAction:`Auto-build before deploy failed (exit ${o.exitCode??"?"}). Read the logTail or run mist_debug { projectPath, jobId: '${n.id}' } to extract structured errors. Fix the code, then call mist_deploy { action: 'deploy', projectPath } again.`}),!0)}}async function du(t){let e=iu(t.projectPath);if(!ke())return Ae("deploy");let r=rt(e),n=r?.projectId;if(!n){if(!r?.name)return p(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);try{n=(await wt(r.name,{dbProvider:r.dbProvider,requestedSubdomain:r.requestedSubdomain})).id,fr(e,{projectId:n}),console.error(`[deploy] auto-registered project ${n.slice(0,8)} (${r.name})`+(r.requestedSubdomain?` at ${r.requestedSubdomain}.mistflow.app`:""))}catch(l){let c=l instanceof W||l instanceof Error?l.message:String(l);return p(`Auto-register before deploy failed: ${c}. mistflow.json has no projectId \u2014 mist_init couldn't register the project earlier (likely offline or backend timeout). Try again in a moment, or check Mistflow status.`,!0)}}if(!sa(e)){let l=await cu(e,t.ctx);if(l.kind==="running"||l.kind==="failed")return l.result}let i=t.environment??lu(e)??"production",o=t.adminEmail??js()?.email,s=null,a=null;try{s=await ea(e),a=await ta(e);let l=await vr(n,s.path,i,o,void 0,a??void 0,void 0);return p(JSON.stringify({status:"running",jobId:l.deployment_id,deploymentId:l.deployment_id,environment:l.environment??i,buildSize:na(s.sizeBytes),buildFileCount:s.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${l.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side, so there's no need to sleep between calls. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(l){let c=l instanceof W||l instanceof Error?l.message:String(l);return p(`Deploy upload failed: ${c}`,!0)}finally{ms(s?.path),ms(a)}}async function pu(t,e){let r=e.ctx?$e(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let n=await st(t,{waitSeconds:e.waitSeconds}),i=ra(n.status),o=n.id??t;return n.status==="live"?(e.projectPath&&n.url&&(fr(e.projectPath,{deploy:{url:n.url,deploymentId:o,completedAt:n.completedAt}}),$t(e.projectPath)),p(JSON.stringify({status:"complete",jobId:o,deploymentId:o,url:n.url,completedAt:n.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${n.url??""}', deploymentId: '${o}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`}))):n.status==="failed"?p(JSON.stringify({status:"failed",jobId:o,deploymentId:o,error:n.error,phase:i,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):p(JSON.stringify({status:"running",jobId:o,deploymentId:o,phase:i,phaseCode:n.status,nextAction:`Still ${n.status} after the ${e.waitSeconds}s backend long-poll window. Call mist_deploy { action: 'status', deploymentId: '${o}' } again immediately to continue waiting \u2014 no sleep needed.`}))}catch(n){let i=n instanceof W||n instanceof Error?n.message:String(n);return p(`Could not fetch deploy status: ${i}`,!0)}finally{r.stop()}}async function uu(t,e){if(!ke())return Ae("promote a preview deployment");let n=rt(t)?.projectId;if(!n)return p(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let i=e;if(!i)try{let s=(await Rt(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!s)return p("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);i=s.id}catch(o){let s=o instanceof W?o.message:String(o);return p(`Could not list deployments: ${s}`,!0)}try{let o=await Ar(n,i);return p(JSON.stringify({status:"running",jobId:o.deployment_id,deploymentId:o.deployment_id,promotedFrom:i,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${o.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(o){let s=o instanceof W||o instanceof Error?o.message:String(o);return p(`Promote failed: ${s}`,!0)}}async function mu(t){if(!ke())return Ae("roll back a deployment");try{let e=await Rr(t);return p(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let r=e instanceof W||e instanceof Error?e.message:String(e);return p(`Rollback failed: ${r}`,!0)}}var oa={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:au,handler:async(t,e)=>{let r=t;switch(r.action??"deploy"){case"deploy":{if(!r.projectPath)return p("projectPath is required for action='deploy'.",!0);if(r.envVarsRequired&&r.envVarsRequired.length>0)try{let i=tr(r.projectPath,r.envVarsRequired);i.added.length>0&&console.error(`[deploy] declared env.required: ${i.added.join(", ")}`)}catch(i){console.error("[deploy] env var merge skipped:",i instanceof Error?i.message:String(i))}return du({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail,ctx:e})}case"status":return r.deploymentId?pu(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e,projectPath:r.projectPath,sessionId:r.sessionId}):p("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?uu(r.projectPath,r.deploymentId):p("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?mu(r.deploymentId):p("deploymentId is required for action='rollback'.",!0)}}};import{z as Vt}from"zod";Se();import{hostname as hu}from"os";var aa=Vt.object({action:Vt.enum(["status","cancel","resume","list"]).describe("status = read current state + acceptance criteria; cancel = terminal CANCELLED transition; resume = bind this machine + path to a session; list = sessions this machine has bound (no sessionId needed)."),sessionId:Vt.string().uuid().optional().describe("Required for status / cancel / resume. Omit for list."),reason:Vt.string().max(500).optional().describe("Optional cancellation reason (used with action=cancel)."),projectPath:Vt.string().min(1).optional().describe("Absolute path to the project directory on this machine. Required for action=resume."),includeIdle:Vt.boolean().optional().describe("For action=list. Default false: only active sessions touched in the last 24h are returned. Set true to see every session ever bound on this machine, including cancelled / completed / stale ones.")});function ia(){return hu()}function hs(t){let e=[`Session: ${t.id}`,`Status: ${t.status}`,`Deploy strategy: ${t.deploy_strategy}`];return t.paused_after_plan&&e.push("Paused: yes (awaiting PLAN.md review \u2014 call mist_session({resume}) when done)"),t.description&&e.push(`Description: ${t.description}`),t.cancelled_at&&e.push(`Cancelled at: ${t.cancelled_at}`),t.completed_at&&e.push(`Completed at: ${t.completed_at}`),e.join(`
|
|
5351
5351
|
`)}async function gu(t){let e=aa.safeParse(t);if(!e.success){let s=e.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return p(`Invalid input: ${s}`,!0)}let r=e.data;if((r.action==="status"||r.action==="cancel"||r.action==="resume")&&!r.sessionId)return p(`Invalid input: action="${r.action}" requires sessionId.`,!0);if(r.action==="resume"&&!r.projectPath)return p('Invalid input: action="resume" requires projectPath.',!0);if(r.action==="status"){let s=r.sessionId,[a,l,c]=await Promise.all([Mn(s),Nt(s).catch(()=>null),en(s).catch(()=>null)]),u=[hs(a),"",l?`Next instruction: ${l.instruction}${l.reason?` (${l.reason})`:""}`:"Next instruction: (unavailable)"];if(c&&c.criteria.length>0){u.push("",`Acceptance criteria (${c.criteria.length}):`);for(let h of c.criteria)u.push(` - [${h.priority}] ${h.id}: ${h.description}`)}return p(u.join(`
|
|
5352
5352
|
`))}if(r.action==="cancel"){let s=r.sessionId,a=await $r(s,r.reason);return p(`Session cancelled.
|
|
5353
5353
|
${hs(a)}
|