@mistflow-ai/mcp 1.5.3 → 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +106 -106
  2. package/dist/index.js +98 -98
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var ma=Object.defineProperty;var Ct=(t,e)=>()=>(t&&(e=t(t=0)),e);var vn=(t,e)=>{for(var r in e)ma(t,r,{get:e[r],enumerable:!0})};import{existsSync as ur,readFileSync as Ps,writeFileSync as Sa,mkdirSync as Ta}from"fs";import{join as dr,dirname as pr}from"path";import{homedir as _a}from"os";import{fileURLToPath as Ia}from"url";function qe(){if(kn)return kn;try{let t=Ia(import.meta.url),e=pr(t);for(let r=0;r<6;r++){let n=dr(e,"package.json");if(ur(n)){let o=JSON.parse(Ps(n,"utf-8"));if(o.name==="@mistflow-ai/mcp"&&typeof o.version=="string")return kn=o.version,o.version}let i=pr(e);if(i===e)break;e=i}}catch{}return kn="0.0.0","0.0.0"}function xn(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function Ts(t,e){let r=xn(t),n=xn(e);if(!r||!n)return 0;for(let i=0;i<3;i++){if(r[i]<n[i])return-1;if(r[i]>n[i])return 1}return 0}function Cs(t,e,r){if(r&&Ts(t,r)<0)return"unsupported";if(!e||Ts(t,e)>=0)return"none";let i=xn(t),o=xn(e);return!i||!o?"none":i[0]<o[0]?"major":i[1]<o[1]?"minor":"patch"}function Jt(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||(Fe={latest:e,minSupported:r,changelogUrl:n})}function As(){let t=process.env.MISTFLOW_STATE_DIR||dr(_a(),".mistflow");return dr(t,"upgrade-state.json")}function Pa(){try{let t=As();return ur(t)?JSON.parse(Ps(t,"utf-8")):{}}catch{return{}}}function Ca(t){try{let e=As(),r=pr(e);ur(r)||Ta(r,{recursive:!0}),Sa(e,JSON.stringify(t,null,2)+`
1
+ var ma=Object.defineProperty;var Ct=(t,e)=>()=>(t&&(e=t(t=0)),e);var xn=(t,e)=>{for(var r in e)ma(t,r,{get:e[r],enumerable:!0})};import{existsSync as ur,readFileSync as Ps,writeFileSync as Sa,mkdirSync as Ta}from"fs";import{join as dr,dirname as pr}from"path";import{homedir as _a}from"os";import{fileURLToPath as Ia}from"url";function qe(){if(Sn)return Sn;try{let t=Ia(import.meta.url),e=pr(t);for(let r=0;r<6;r++){let n=dr(e,"package.json");if(ur(n)){let o=JSON.parse(Ps(n,"utf-8"));if(o.name==="@mistflow-ai/mcp"&&typeof o.version=="string")return Sn=o.version,o.version}let i=pr(e);if(i===e)break;e=i}}catch{}return Sn="0.0.0","0.0.0"}function Tn(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function Ts(t,e){let r=Tn(t),n=Tn(e);if(!r||!n)return 0;for(let i=0;i<3;i++){if(r[i]<n[i])return-1;if(r[i]>n[i])return 1}return 0}function Cs(t,e,r){if(r&&Ts(t,r)<0)return"unsupported";if(!e||Ts(t,e)>=0)return"none";let i=Tn(t),o=Tn(e);return!i||!o?"none":i[0]<o[0]?"major":i[1]<o[1]?"minor":"patch"}function Jt(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||(Fe={latest:e,minSupported:r,changelogUrl:n})}function As(){let t=process.env.MISTFLOW_STATE_DIR||dr(_a(),".mistflow");return dr(t,"upgrade-state.json")}function Pa(){try{let t=As();return ur(t)?JSON.parse(Ps(t,"utf-8")):{}}catch{return{}}}function Ca(t){try{let e=As(),r=pr(e);ur(r)||Ta(r,{recursive:!0}),Sa(e,JSON.stringify(t,null,2)+`
2
2
  `,{mode:384})}catch{}}function Aa(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Rs(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!Fe)return null;let t=qe();if(t==="0.0.0")return null;let e=Cs(t,Fe.latest,Fe.minSupported);if(e==="none")return null;if(e==="unsupported")return Is(e,t,Fe);if(_s)return null;let r=Pa(),n=Date.now(),i=Aa(e);return r.dismissedForVersion===Fe.latest&&e!=="major"||r.lastLatestSeen===Fe.latest&&r.lastShownMs&&n-r.lastShownMs<i?null:(_s=!0,Ca({...r,lastShownMs:n,lastLatestSeen:Fe.latest}),Is(e,t,Fe))}function Is(t,e,r){let n="npx -y mistflow-ai install",i=r.changelogUrl?`
3
3
  What's new: ${r.changelogUrl}`:"";return t==="unsupported"?`
4
4
 
@@ -19,10 +19,10 @@ 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 mr(){let t=qe(),e=Fe??{latest:"",minSupported:"",changelogUrl:""},r=Cs(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:Fe!==null}}var kn,Fe,_s,Yt=Ct(()=>{"use strict";kn=null;Fe=null;_s=!1});var Zt={};vn(Zt,{closeBrowser:()=>gr,getIsolatedContext:()=>Ea,getPage:()=>hr,getSnapshot:()=>Qt,takeScreenshot:()=>Xt});async function Es(){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 Ra(){let t=await Es();return(!Be||!Be.isConnected())&&(Be=await t.chromium.launch({headless:!0})),ot&&(await ot.close().catch(()=>{}),ot=null),ot=await Be.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Qe=await ot.newPage(),Qe}async function hr(){return Qe&&!Qe.isClosed()?Qe:(Sn||(Sn=Ra().finally(()=>{Sn=null})),Sn)}async function gr(){Qe&&!Qe.isClosed()&&await Qe.close().catch(()=>{}),ot&&await ot.close().catch(()=>{}),Be?.isConnected()&&await Be.close().catch(()=>{}),Qe=null,ot=null,Be=null}async function Ea(){let t=await Es();(!Be||!Be.isConnected())&&(Be=await t.chromium.launch({headless:!0}));let e=await Be.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function Qt(t){return await t.locator("body").ariaSnapshot()}async function Xt(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var Be,ot,Qe,Sn,At=Ct(()=>{"use strict";Be=null,ot=null,Qe=null,Sn=null;process.once("SIGTERM",()=>{gr().finally(()=>process.exit(0))});process.once("SIGINT",()=>{gr().finally(()=>process.exit(0))})});import{readFileSync as fr,existsSync as Tn,writeFileSync as Os,mkdirSync as Da,renameSync as ja,unlinkSync as Ma}from"fs";import{join as _n,dirname as La}from"path";import{homedir as $a}from"os";import{randomBytes as Ua}from"crypto";function Ds(){return _n($a(),".mistflow","credentials.json")}function In(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function js(){let t=Ds();if(!Tn(t))return null;try{let e=JSON.parse(fr(t,"utf-8"));return typeof e.apiKey=="string"?{[Fa]:e}:e}catch{return null}}function bt(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=js();if(!e)return{ok:!1,reason:"missing"};let r=In(),n=e[r];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function yr(t){let e=Ds(),r=La(e);Tn(r)||Da(r,{recursive:!0});let n=js()??{},i=In();n[i]=t;let o=_n(r,`.credentials.tmp.${Ua(8).toString("hex")}`);try{Os(o,JSON.stringify(n,null,2)+`
23
- `,{mode:384}),ja(o,e)}catch(s){try{Ma(o)}catch{}throw s}}function Ms(){let t=bt();return t.ok?t.creds:null}function xe(){return bt().ok}function it(t){let e=_n(t,"mistflow.json");if(!Tn(e))return null;try{return JSON.parse(fr(e,"utf-8"))}catch{return null}}function br(t,e){let r=_n(t,"mistflow.json");if(Tn(r))try{let i={...JSON.parse(fr(r,"utf-8")),...e};Os(r,JSON.stringify(i,null,2)+`
24
- `,"utf-8")}catch{}}var Fa,wt=Ct(()=>{"use strict";Fa="https://api.mistflow.ai"});var zs={};vn(zs,{MistflowApiError:()=>J,addDomain:()=>Sr,bindWorkspace:()=>nn,cancelSession:()=>qr,checkAuth:()=>Wa,checkAuthDetailed:()=>Fs,checkSubdomain:()=>Cn,checkToolGuard:()=>Br,createDeployment:()=>Va,createProject:()=>kt,deleteEnvVar:()=>Cr,discoverDecisions:()=>Ja,downloadImageryAsset:()=>kr,downloadSource:()=>Xa,downloadSourceWithToken:()=>qs,fetchAcceptanceCriteria:()=>tn,fetchActiveSessionPlan:()=>nl,fetchDesignDirections:()=>An,fetchDesignPick:()=>Ka,fetchDesignRenders:()=>En,fetchDoc:()=>Mr,fetchDocsList:()=>jr,fetchModule:()=>Lr,fetchPlanConversation:()=>Nn,fetchProjectImagery:()=>vr,fetchScaffold:()=>Or,fetchSessionNext:()=>Ot,fetchSessionPlanRevisions:()=>Bs,fetchStepContext:()=>Dr,forkTemplate:()=>Ur,generatePlan:()=>On,getAuthHeaders:()=>vt,getBaseUrl:()=>Ie,getDashboardUrl:()=>Ba,getDbCredentials:()=>Ya,getDeployLogs:()=>Ar,getDeploymentStatus:()=>at,getProject:()=>Ga,getProjectErrors:()=>Rr,getSeedInfo:()=>Mn,getSession:()=>Ln,getSiteUrl:()=>qa,getTemplate:()=>$r,hasCredentialsOnDisk:()=>xe,hasLocalCredentials:()=>Us,listDeployments:()=>Et,listDomains:()=>lt,listEnvVars:()=>Ir,listSessionsForMachine:()=>rn,markLocalSetupDone:()=>Za,modifyPlan:()=>Dn,pingBackend:()=>wr,promotePreview:()=>Er,redeployProject:()=>Qa,removeDomain:()=>Tr,rollbackDeployment:()=>Nr,shareProject:()=>Fr,startSession:()=>el,submitAcceptanceResults:()=>zr,submitDesignPick:()=>Rn,submitSessionAnswers:()=>tl,uploadAndDeploy:()=>xr,uploadQAResults:()=>_r,upsertEnvVar:()=>Pr,verifyDomain:()=>jn});function Ie(){return In()}function qa(){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 Ba(){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 vt(){let t=bt();if(!t.ok)throw new J("auth_missing","No Mistflow credentials found.",401);return za(t.creds)}function za(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()}}function Rt(t){try{Jt(t.headers)}catch{}}async function wr(){try{let t=await fetch(`${Ie()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Rt(t)}catch{}}async function $s(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 en(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 J(r,n,t.status,e?.details);let i=t.status;return i===401?new J("auth_invalid",n,i):i===403?new J("permission_denied",n,i):i===404?new J("not_found",n,i):i===409?new J("conflict",n,i):i===422?new J("validation_error",n,i):i===429?new J("rate_limited",n,i):i>=500?new J("server_error",t.statusText||"Internal server error",i):new J("client_error",n,i)}async function q(t,e={}){let r=vt(),{timeoutMs:n,idempotent:i,...o}=e,s=n??3e4,a=(o.method??"GET").toUpperCase(),l=i??(a==="GET"||a==="HEAD"),c;try{c=await $s(`${Ie()}${t}`,{...o,headers:{...r,...o.headers}},s,l)}catch(m){throw m instanceof Error&&m.name==="TimeoutError"?new J("network_error","Request timed out. Try again in a moment."):new J("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(c),!c.ok)throw await en(c);return c.json()}function Us(){return bt().ok}async function Wa(){return(await Fs()).ok}async function Fs(){if(Pn!==null&&Date.now()<Ls)return Pn?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Us())return{ok:!1,reason:"no_credentials"};try{return await q("/api/org"),Pn=!0,Ls=Date.now()+Ha,{ok:!0}}catch(t){if(Pn=null,!(t instanceof J))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 Ga(t){return q(`/api/projects/${encodeURIComponent(t)}`)}async function Cn(t){return q(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function kt(t,e={}){return q("/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 vr(t){return q(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function kr(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 Va(t,e){return q("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function xr(t,e,r="production",n,i,o,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=bt();if(!c.ok)throw new J("auth_missing","No Mistflow credentials found.",401);let m=c.creds,p=a(e),u=new Blob([p],{type:"application/gzip"}),g=new FormData;if(g.append("project_id",t),g.append("build",u,l(e)),r!=="production"&&g.append("environment",r),n&&g.append("admin_email",n),i&&g.append("schema_pushed","true"),o){let{existsSync:x}=await import("fs");if(x(o)){let y=a(o),P=new Blob([y],{type:"application/gzip"});g.append("source",P,"source.tar.gz")}}s&&g.append("git_commit_sha",s);let D;try{D=await fetch(`${Ie()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":qe()},body:g,signal:AbortSignal.timeout(3e5)})}catch{throw new J("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(D),!D.ok)throw await en(D);let _=await D.json();return{..._,id:_.deployment_id}}async function at(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return q(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:i}:void 0)}async function An(t){return q(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Ka(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return q(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:i})}async function Rn(t,e){return q(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),timeoutMs:6e4})}async function En(t){try{return await q(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function Nn(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return q(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:i})}async function On(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,m=(()=>{if(l&&l.length>0)return l.length<=s?l:l.slice(0,s)+" (truncated)";if(!c){let g=JSON.stringify(i);return g.length<=s?g:g.slice(0,s)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${o}; falling back to custom`);let p=c?{direction_id:c}:{custom:m};e.conversationId&&(p.conversation_id=e.conversationId);let u=await Rn(e.designConversationId,p);return{status:"ready",plan:u.plan??{},methodology:u.methodology??"",...u.designMd?{designMd:u.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return q("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function Dn(t,e,r={}){return q("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function Ja(t){return q("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Sr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function lt(t){return q(`/api/projects/${encodeURIComponent(t)}/domains`)}async function jn(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Tr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ya(t){return q(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Mn(t){try{return await q(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof J&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function _r(t,e){try{return await q(`/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 Ir(t){return q(`/api/projects/${encodeURIComponent(t)}/env`)}async function Pr(t,e,r,n){return q(`/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 Cr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ar(t){return q(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Rr(t,e="7d"){return q(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Et(t){return q(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function Qa(t){return q(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Er(t,e){let r=new URLSearchParams({preview_deployment_id:e});return q(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Nr(t){return q(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function Xa(t,e){let r=bt();if(!r.ok)throw new J("auth_missing","Not authenticated.",401);let n=r.creds,i=await fetch(`${Ie()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":qe()},signal:AbortSignal.timeout(12e4)});if(Rt(i),!i.ok)throw await en(i);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await i.arrayBuffer());o(e,s)}async function Nt(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 $s(`${Ie()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()},...i},o,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new J("network_error","Request timed out. Try again in a moment."):new J("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(l),!l.ok)throw await en(l);return l.json()}async function Or(t="nextjs"){return Nt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Dr(t,e){return Nt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function jr(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return Nt(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function Mr(t,e){return Nt(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function Lr(t,e,r,n){return Nt(`/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 $r(t){return Nt(`/api/templates/${encodeURIComponent(t)}`)}async function Ur(t){return q(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function qs(t,e,r){let n;try{n=await fetch(`${Ie()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":qe()},signal:AbortSignal.timeout(12e4)})}catch{throw new J("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(n),!n.ok)throw n.status===401?new J("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await en(n);let{writeFileSync:i}=await import("fs"),o=Buffer.from(await n.arrayBuffer());i(r,o)}async function Za(t){await q(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Fr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function el(t){return q("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function Ln(t){return q(`/api/sessions/${t}`)}async function qr(t,e){return q(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Ot(t){return q(`/api/sessions/${t}/next`)}async function tl(t,e){return q(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Br(t,e){return q(`/api/sessions/${t}/can/${e}`)}async function tn(t){return q(`/api/sessions/${t}/acceptance`)}async function Bs(t){return q(`/api/sessions/${t}/revisions`)}async function nl(t){let e=await Bs(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 nn(t,e){return q(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function rn(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return q(`/api/sessions/me/workspaces?${n}`)}async function zr(t,e,r){return q(`/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 J,Pn,Ls,Ha,_e=Ct(()=>{"use strict";wt();Yt();J=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"}};Pn=null,Ls=0,Ha=300*1e3});var an={};vn(an,{emptyState:()=>on,fetchRemoteState:()=>gl,fuzzyMatch:()=>yl,getLocalStatePath:()=>Wr,readLocalState:()=>hl,syncRemoteState:()=>fl,writeLocalState:()=>sn});import{existsSync as Js,readFileSync as pl,writeFileSync as ul,mkdirSync as ml}from"fs";import{join as Ys}from"path";function Wr(t){return Ys(t,".mistflow","state.json")}function hl(t){let e=Wr(t);if(!Js(e))return null;try{return JSON.parse(pl(e,"utf-8"))}catch{return null}}function sn(t,e){let r=Ys(t,".mistflow");Js(r)||ml(r,{recursive:!0}),ul(Wr(t),JSON.stringify(e,null,2)+`
25
- `)}function on(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function gl(t){let e;try{e=vt()}catch{return null}try{let r=await fetch(`${Ie()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()}});try{Jt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function fl(t,e){let r;try{r=vt()}catch{return!1}try{let n=await fetch(`${Ie()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()},body:JSON.stringify(e)});try{Jt(n.headers)}catch{}return n.ok}catch{return!1}}function yl(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 xt=Ct(()=>{"use strict";_e();Yt()});var Gr={};vn(Gr,{ensureBackendRegistered:()=>Tl,ensureShadcnComponents:()=>_l});import{existsSync as Xs,readFileSync as bl,writeFileSync as wl}from"fs";import{join as $n}from"path";import{spawn as vl}from"child_process";function kl(t,e,r,n,i){return new Promise(o=>{let s=vl(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 xl(t){let e=$n(t,"mistflow.json");if(!Xs(e))return null;try{return JSON.parse(bl(e,"utf-8"))}catch{return null}}function Sl(t,e){wl($n(t,"mistflow.json"),JSON.stringify(e,null,2))}async function Qs(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(`${Ie()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...vt(),"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 Tl(t,e={}){let r=xl(t);if(r){if(!xe())return r.projectId;if(!r.projectId)try{let i=r.plan?.requestedSubdomain,o=await kt(r.name,{dbProvider:r.dbProvider??"neon",requestedSubdomain:i});return r.projectId=o.id,Sl(t,r),sn(t,on(o.id,r.name)),r.plan&&await Qs(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 Qs(r.projectId,r.plan),r.projectId}}async function _l(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=$n(t,"components","ui"),o=[],s=[];for(let c of n)Xs($n(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 kl("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 Vr=Ct(()=>{"use strict";_e();xt()});import{Server as yu}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as bu}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as wu,ListToolsRequestSchema as vu}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as ku}from"zod-to-json-schema";var ha="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.",ga='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"`.',fa="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.",ya="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.",ba='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.',wa="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.",va="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.",ka='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.',xa="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.",fs="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).",ys="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.",bs="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.",ws="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.",vs="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.",ks="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).",xs="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 Ss(){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(ka),t.push(""),t.push(ha),t.push(""),t.push(ga),t.push(""),t.push(fa),t.push(""),t.push(ya),t.push(""),t.push(xa),t.push(""),t.push(wa),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(ba),t.push(""),t.push(va),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(`
22
+ (Mistflow ${r.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function mr(){let t=qe(),e=Fe??{latest:"",minSupported:"",changelogUrl:""},r=Cs(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:Fe!==null}}var Sn,Fe,_s,Yt=Ct(()=>{"use strict";Sn=null;Fe=null;_s=!1});var Zt={};xn(Zt,{closeBrowser:()=>gr,getIsolatedContext:()=>Ea,getPage:()=>hr,getSnapshot:()=>Qt,takeScreenshot:()=>Xt});async function Es(){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 Ra(){let t=await Es();return(!Be||!Be.isConnected())&&(Be=await t.chromium.launch({headless:!0})),ot&&(await ot.close().catch(()=>{}),ot=null),ot=await Be.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Qe=await ot.newPage(),Qe}async function hr(){return Qe&&!Qe.isClosed()?Qe:(_n||(_n=Ra().finally(()=>{_n=null})),_n)}async function gr(){Qe&&!Qe.isClosed()&&await Qe.close().catch(()=>{}),ot&&await ot.close().catch(()=>{}),Be?.isConnected()&&await Be.close().catch(()=>{}),Qe=null,ot=null,Be=null}async function Ea(){let t=await Es();(!Be||!Be.isConnected())&&(Be=await t.chromium.launch({headless:!0}));let e=await Be.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function Qt(t){return await t.locator("body").ariaSnapshot()}async function Xt(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var Be,ot,Qe,_n,At=Ct(()=>{"use strict";Be=null,ot=null,Qe=null,_n=null;process.once("SIGTERM",()=>{gr().finally(()=>process.exit(0))});process.once("SIGINT",()=>{gr().finally(()=>process.exit(0))})});import{readFileSync as fr,existsSync as In,writeFileSync as Os,mkdirSync as Da,renameSync as ja,unlinkSync as Ma}from"fs";import{join as Pn,dirname as La}from"path";import{homedir as $a}from"os";import{randomBytes as Ua}from"crypto";function Ds(){return Pn($a(),".mistflow","credentials.json")}function Cn(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function js(){let t=Ds();if(!In(t))return null;try{let e=JSON.parse(fr(t,"utf-8"));return typeof e.apiKey=="string"?{[Fa]:e}:e}catch{return null}}function bt(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=js();if(!e)return{ok:!1,reason:"missing"};let r=Cn(),n=e[r];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function yr(t){let e=Ds(),r=La(e);In(r)||Da(r,{recursive:!0});let n=js()??{},i=Cn();n[i]=t;let o=Pn(r,`.credentials.tmp.${Ua(8).toString("hex")}`);try{Os(o,JSON.stringify(n,null,2)+`
23
+ `,{mode:384}),ja(o,e)}catch(s){try{Ma(o)}catch{}throw s}}function Ms(){let t=bt();return t.ok?t.creds:null}function xe(){return bt().ok}function it(t){let e=Pn(t,"mistflow.json");if(!In(e))return null;try{return JSON.parse(fr(e,"utf-8"))}catch{return null}}function br(t,e){let r=Pn(t,"mistflow.json");if(In(r))try{let i={...JSON.parse(fr(r,"utf-8")),...e};Os(r,JSON.stringify(i,null,2)+`
24
+ `,"utf-8")}catch{}}var Fa,wt=Ct(()=>{"use strict";Fa="https://api.mistflow.ai"});var zs={};xn(zs,{MistflowApiError:()=>J,addDomain:()=>Sr,bindWorkspace:()=>nn,cancelSession:()=>qr,checkAuth:()=>Wa,checkAuthDetailed:()=>Fs,checkSubdomain:()=>Rn,checkToolGuard:()=>Br,createDeployment:()=>Va,createProject:()=>kt,deleteEnvVar:()=>Cr,discoverDecisions:()=>Ja,downloadImageryAsset:()=>kr,downloadSource:()=>Xa,downloadSourceWithToken:()=>qs,fetchAcceptanceCriteria:()=>tn,fetchActiveSessionPlan:()=>nl,fetchDesignDirections:()=>En,fetchDesignPick:()=>Ka,fetchDesignRenders:()=>On,fetchDoc:()=>Mr,fetchDocsList:()=>jr,fetchModule:()=>Lr,fetchPlanConversation:()=>Dn,fetchProjectImagery:()=>vr,fetchScaffold:()=>Or,fetchSessionNext:()=>Ot,fetchSessionPlanRevisions:()=>Bs,fetchStepContext:()=>Dr,forkTemplate:()=>Ur,generatePlan:()=>jn,getAuthHeaders:()=>vt,getBaseUrl:()=>Ie,getDashboardUrl:()=>Ba,getDbCredentials:()=>Ya,getDeployLogs:()=>Ar,getDeploymentStatus:()=>at,getProject:()=>Ga,getProjectErrors:()=>Rr,getSeedInfo:()=>$n,getSession:()=>Un,getSiteUrl:()=>qa,getTemplate:()=>$r,hasCredentialsOnDisk:()=>xe,hasLocalCredentials:()=>Us,listDeployments:()=>Et,listDomains:()=>lt,listEnvVars:()=>Ir,listSessionsForMachine:()=>rn,markLocalSetupDone:()=>Za,modifyPlan:()=>Mn,pingBackend:()=>wr,promotePreview:()=>Er,redeployProject:()=>Qa,removeDomain:()=>Tr,rollbackDeployment:()=>Nr,shareProject:()=>Fr,startSession:()=>el,submitAcceptanceResults:()=>zr,submitDesignPick:()=>Nn,submitSessionAnswers:()=>tl,uploadAndDeploy:()=>xr,uploadQAResults:()=>_r,upsertEnvVar:()=>Pr,verifyDomain:()=>Ln});function Ie(){return Cn()}function qa(){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 Ba(){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 vt(){let t=bt();if(!t.ok)throw new J("auth_missing","No Mistflow credentials found.",401);return za(t.creds)}function za(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()}}function Rt(t){try{Jt(t.headers)}catch{}}async function wr(){try{let t=await fetch(`${Ie()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Rt(t)}catch{}}async function $s(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 en(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 J(r,n,t.status,e?.details);let i=t.status;return i===401?new J("auth_invalid",n,i):i===403?new J("permission_denied",n,i):i===404?new J("not_found",n,i):i===409?new J("conflict",n,i):i===422?new J("validation_error",n,i):i===429?new J("rate_limited",n,i):i>=500?new J("server_error",t.statusText||"Internal server error",i):new J("client_error",n,i)}async function q(t,e={}){let r=vt(),{timeoutMs:n,idempotent:i,...o}=e,s=n??3e4,a=(o.method??"GET").toUpperCase(),l=i??(a==="GET"||a==="HEAD"),c;try{c=await $s(`${Ie()}${t}`,{...o,headers:{...r,...o.headers}},s,l)}catch(m){throw m instanceof Error&&m.name==="TimeoutError"?new J("network_error","Request timed out. Try again in a moment."):new J("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(c),!c.ok)throw await en(c);return c.json()}function Us(){return bt().ok}async function Wa(){return(await Fs()).ok}async function Fs(){if(An!==null&&Date.now()<Ls)return An?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Us())return{ok:!1,reason:"no_credentials"};try{return await q("/api/org"),An=!0,Ls=Date.now()+Ha,{ok:!0}}catch(t){if(An=null,!(t instanceof J))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 Ga(t){return q(`/api/projects/${encodeURIComponent(t)}`)}async function Rn(t){return q(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function kt(t,e={}){return q("/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 vr(t){return q(`/api/projects/${encodeURIComponent(t)}/imagery`)}async function kr(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 Va(t,e){return q("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function xr(t,e,r="production",n,i,o,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),c=bt();if(!c.ok)throw new J("auth_missing","No Mistflow credentials found.",401);let m=c.creds,p=a(e),u=new Blob([p],{type:"application/gzip"}),h=new FormData;if(h.append("project_id",t),h.append("build",u,l(e)),r!=="production"&&h.append("environment",r),n&&h.append("admin_email",n),i&&h.append("schema_pushed","true"),o){let{existsSync:x}=await import("fs");if(x(o)){let y=a(o),P=new Blob([y],{type:"application/gzip"});h.append("source",P,"source.tar.gz")}}s&&h.append("git_commit_sha",s);let N;try{N=await fetch(`${Ie()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":qe()},body:h,signal:AbortSignal.timeout(3e5)})}catch{throw new J("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(N),!N.ok)throw await en(N);let _=await N.json();return{..._,id:_.deployment_id}}async function at(t,e){let r=e?.waitSeconds??0,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return q(`/api/deploy/${encodeURIComponent(t)}/status${n}`,r>0?{timeoutMs:i}:void 0)}async function En(t){return q(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Ka(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return q(`/api/plan/design-directions/${encodeURIComponent(t)}/pick${n}`,{timeoutMs:i})}async function Nn(t,e){return q(`/api/plan/design-directions/${encodeURIComponent(t)}/pick`,{method:"POST",body:JSON.stringify(e),timeoutMs:6e4})}async function On(t){try{return await q(`/api/plan/design-directions/${encodeURIComponent(t)}/renders`,{timeoutMs:1e4})}catch{return{}}}async function Dn(t,e){let r=e?.waitSeconds??45,n=r>0?`?wait=${r}`:"",i=Math.min(6e4,(r+5)*1e3);return q(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:i})}async function jn(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,m=(()=>{if(l&&l.length>0)return l.length<=s?l:l.slice(0,s)+" (truncated)";if(!c){let h=JSON.stringify(i);return h.length<=s?h:h.slice(0,s)+" (truncated)"}})();a&&!c&&console.error(`[mistflow] direction_id ${a.length} chars exceeds ${o}; falling back to custom`);let p=c?{direction_id:c}:{custom:m};e.conversationId&&(p.conversation_id=e.conversationId);let u=await Nn(e.designConversationId,p);return{status:"ready",plan:u.plan??{},methodology:u.methodology??"",...u.designMd?{designMd:u.designMd}:{}}}let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return q("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:n,idempotent:!1})}async function Mn(t,e,r={}){return q("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e,plan_md:r.planMd})})}async function Ja(t){return q("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Sr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function lt(t){return q(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Ln(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Tr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ya(t){return q(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function $n(t){try{return await q(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof J&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function _r(t,e){try{return await q(`/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 Ir(t){return q(`/api/projects/${encodeURIComponent(t)}/env`)}async function Pr(t,e,r,n){return q(`/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 Cr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ar(t){return q(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Rr(t,e="7d"){return q(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Et(t){return q(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function Qa(t){return q(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Er(t,e){let r=new URLSearchParams({preview_deployment_id:e});return q(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function Nr(t){return q(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function Xa(t,e){let r=bt();if(!r.ok)throw new J("auth_missing","Not authenticated.",401);let n=r.creds,i=await fetch(`${Ie()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":qe()},signal:AbortSignal.timeout(12e4)});if(Rt(i),!i.ok)throw await en(i);let{writeFileSync:o}=await import("fs"),s=Buffer.from(await i.arrayBuffer());o(e,s)}async function Nt(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 $s(`${Ie()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()},...i},o,a)}catch(c){throw c instanceof Error&&c.name==="TimeoutError"?new J("network_error","Request timed out. Try again in a moment."):new J("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(l),!l.ok)throw await en(l);return l.json()}async function Or(t="nextjs"){return Nt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Dr(t,e){return Nt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function jr(t="nextjs",e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return Nt(`/api/scaffold/${encodeURIComponent(t)}/docs${r}`)}async function Mr(t,e){return Nt(`/api/scaffold/${encodeURIComponent(t)}/docs/${encodeURIComponent(e)}`)}async function Lr(t,e,r,n){return Nt(`/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 $r(t){return Nt(`/api/templates/${encodeURIComponent(t)}`)}async function Ur(t){return q(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function qs(t,e,r){let n;try{n=await fetch(`${Ie()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":qe()},signal:AbortSignal.timeout(12e4)})}catch{throw new J("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(n),!n.ok)throw n.status===401?new J("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await en(n);let{writeFileSync:i}=await import("fs"),o=Buffer.from(await n.arrayBuffer());i(r,o)}async function Za(t){await q(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Fr(t,e){return q(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}async function el(t){return q("/api/sessions/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),idempotent:!1})}async function Un(t){return q(`/api/sessions/${t}`)}async function qr(t,e){return q(`/api/sessions/${t}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e??null}),idempotent:!0})}async function Ot(t){return q(`/api/sessions/${t}/next`)}async function tl(t,e){return q(`/api/sessions/${t}/answers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:e}),idempotent:!0})}async function Br(t,e){return q(`/api/sessions/${t}/can/${e}`)}async function tn(t){return q(`/api/sessions/${t}/acceptance`)}async function Bs(t){return q(`/api/sessions/${t}/revisions`)}async function nl(t){let e=await Bs(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 nn(t,e){return q(`/api/sessions/${t}/workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),idempotent:!0})}async function rn(t,e={}){let r={machine_id:t};e.includeIdle&&(r.include_idle="true");let n=new URLSearchParams(r).toString();return q(`/api/sessions/me/workspaces?${n}`)}async function zr(t,e,r){return q(`/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 J,An,Ls,Ha,_e=Ct(()=>{"use strict";wt();Yt();J=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"}};An=null,Ls=0,Ha=300*1e3});var an={};xn(an,{emptyState:()=>on,fetchRemoteState:()=>gl,fuzzyMatch:()=>yl,getLocalStatePath:()=>Wr,readLocalState:()=>hl,syncRemoteState:()=>fl,writeLocalState:()=>sn});import{existsSync as Js,readFileSync as pl,writeFileSync as ul,mkdirSync as ml}from"fs";import{join as Ys}from"path";function Wr(t){return Ys(t,".mistflow","state.json")}function hl(t){let e=Wr(t);if(!Js(e))return null;try{return JSON.parse(pl(e,"utf-8"))}catch{return null}}function sn(t,e){let r=Ys(t,".mistflow");Js(r)||ml(r,{recursive:!0}),ul(Wr(t),JSON.stringify(e,null,2)+`
25
+ `)}function on(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function gl(t){let e;try{e=vt()}catch{return null}try{let r=await fetch(`${Ie()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()}});try{Jt(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function fl(t,e){let r;try{r=vt()}catch{return!1}try{let n=await fetch(`${Ie()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":qe()},body:JSON.stringify(e)});try{Jt(n.headers)}catch{}return n.ok}catch{return!1}}function yl(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 xt=Ct(()=>{"use strict";_e();Yt()});var Gr={};xn(Gr,{ensureBackendRegistered:()=>Tl,ensureShadcnComponents:()=>_l});import{existsSync as Xs,readFileSync as bl,writeFileSync as wl}from"fs";import{join as Fn}from"path";import{spawn as vl}from"child_process";function kl(t,e,r,n,i){return new Promise(o=>{let s=vl(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 xl(t){let e=Fn(t,"mistflow.json");if(!Xs(e))return null;try{return JSON.parse(bl(e,"utf-8"))}catch{return null}}function Sl(t,e){wl(Fn(t,"mistflow.json"),JSON.stringify(e,null,2))}async function Qs(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(`${Ie()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...vt(),"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 Tl(t,e={}){let r=xl(t);if(r){if(!xe())return r.projectId;if(!r.projectId)try{let i=r.plan?.requestedSubdomain,o=await kt(r.name,{dbProvider:r.dbProvider??"neon",requestedSubdomain:i});return r.projectId=o.id,Sl(t,r),sn(t,on(o.id,r.name)),r.plan&&await Qs(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 Qs(r.projectId,r.plan),r.projectId}}async function _l(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=Fn(t,"components","ui"),o=[],s=[];for(let c of n)Xs(Fn(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 kl("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 Vr=Ct(()=>{"use strict";_e();xt()});import{Server as wu}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as vu}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as ku,ListToolsRequestSchema as xu}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as Su}from"zod-to-json-schema";var ha="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.",ga='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"`.',fa="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.",ya="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.",ba='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.',wa="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.",va="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.",ka='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.',xa="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.",fs="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).",ys="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.",bs="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.",ws="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.",vs="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.",ks="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).",xs="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 Ss(){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(ka),t.push(""),t.push(ha),t.push(""),t.push(ga),t.push(""),t.push(fa),t.push(""),t.push(ya),t.push(""),t.push(xa),t.push(""),t.push(wa),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(ba),t.push(""),t.push(va),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
  `)}Yt();function d(t,e=!1){let r=t;try{let n=Rs();n&&(r=t+n)}catch{}return{content:[{type:"text",text:r}],isError:e}}function Ne(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 d(JSON.stringify(e),!0)}function Xe(t){return d(`This is not a Mistflow project (no mistflow.json found at ${t}).
27
27
 
28
28
  Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
@@ -35,9 +35,9 @@ To get started:
35
35
  If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}var Na={width:1024,height:576},Oa={width:1280,height:720};async function Ns(t,e){try{let{getPage:r,takeScreenshot:n}=await Promise.resolve().then(()=>(At(),Zt)),i=await r();await i.setViewportSize(Na);try{await i.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await i.waitForLoadState("networkidle").catch(()=>{});let o=await n(i,!1);return{content:[{type:"text",text:e},{type:"image",data:o.toString("base64"),mimeType:"image/png"}]}}finally{await i.setViewportSize(Oa).catch(()=>{})}}catch{return d(e)}}import{z as Hr}from"zod";import{platform as rl}from"os";import{execFile as Hs}from"child_process";_e();wt();var sl=Hr.object({apiKey:Hr.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:Hr.string().optional().describe("Resume polling for a pending device code. Returned by a previous mist_setup call with status 'pending'. Call mist_setup again with this value after ~15 seconds to check if the user approved.")});function ol(t){return"error"in t}function Gs(t){return new Promise(e=>setTimeout(e,t))}function il(t){return new Promise(e=>{let r=rl();r==="win32"?Hs("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):Hs(r==="darwin"?"open":"xdg-open",[t],i=>{i&&console.error("Could not open browser:",i.message),e(!i)}),setTimeout(()=>e(!1),5e3)})}var al={fetch:globalThis.fetch,openBrowser:il,sleep:Gs};async function Ws(t,e,r,n){let i=r,o=n.sleep??Gs;for(let s=0;s<e;s++){await o(i);let a;try{let c=await n.fetch(`${Ie()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!c.ok)continue;a=await c.json()}catch{continue}if(ol(a))switch(a.error){case"authorization_pending":continue;case"slow_down":i+=5e3;continue;case"expired_token":return d("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return d("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return d("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=a.email||a.org_name||a.org_slug;return yr({apiKey:a.api_key,apiKeyId:a.api_key_id,apiKeyName:a.api_key_name,orgId:a.org_id,orgSlug:a.org_slug,email:a.email}),d(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function ll(t,e=al){let r=t;if(r?.apiKey)try{let s=await e.fetch(`${Ie()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!s.ok)return d("Invalid API key. Check the key and try again.",!0);let a=await s.json();return yr({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),d(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let s=await Ws(r.deviceCode,6,5e3,e);return s||d(JSON.stringify({status:"pending",deviceCode:r.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let s=await e.fetch(`${Ie()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!s.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await s.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let i=`${n.verification_uri}?code=${n.user_code}`;console.error(`
36
36
  Sign in at: ${i}
37
37
  Your code: ${n.user_code}
38
- `);try{await e.openBrowser(i)}catch{}let o=await Ws(n.device_code,6,5e3,e);return o||d(JSON.stringify({status:"pending",deviceCode:n.device_code,signInUrl:i,userCode:n.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+n.device_code+"' to check if they approved."}))}var Vs={name:"mist_setup",description:fs,inputSchema:sl,handler:t=>ll(t)};import{z as De}from"zod";import{resolve as Un}from"path";import{existsSync as Fn,readFileSync as qn}from"fs";import{join as Bn}from"path";import{z as ct}from"zod";import{resolve as Il,join as Zs}from"path";import{existsSync as Pl,readFileSync as eo,writeFileSync as Cl}from"fs";import{existsSync as cl,readFileSync as dl}from"fs";function Ks(t){let e=new Set;if(!cl(t))return e;let r=dl(t,"utf-8");for(let n of r.split(`
39
- `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o>0){let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();a&&a!=='""'&&a!=="''"&&e.add(s)}}return e}var Al=ct.object({action:ct.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:ct.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:ct.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:ct.object({key:ct.string(),description:ct.string().optional(),setupUrl:ct.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),to={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Called internally by mist_project; host AIs should use mist_project directly.",inputSchema:Al,handler:async t=>{let e=t,r=Il(e.projectPath??process.cwd()),n=Zs(r,"mistflow.json");if(!Pl(n))return Xe(r);let i;try{i=JSON.parse(eo(n,"utf-8"))}catch{return d("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!i.projectId)try{let{ensureBackendRegistered:x}=await Promise.resolve().then(()=>(Vr(),Gr));await x(r)&&(i=JSON.parse(eo(n,"utf-8")))}catch{}let a=i.plan,l=a?.steps?.filter(x=>x.status==="completed").length??0,c=a?.steps?.length??0,m=Ks(Zs(r,".env.local")),p=i.env?.required?Object.entries(i.env.required).map(([x,y])=>({name:x,description:y?.description,configured:m.has(x)})):[];i.projectId&&Promise.resolve().then(()=>(xt(),an)).then(({fetchRemoteState:x})=>x(i.projectId)).catch(()=>{});let u=[`Project: ${i.name}`];if(a){u.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let x of a.steps){let y=x.status==="completed"?"\u2713":x.status==="in_progress"?"\u2192":" ";u.push(` [${y}] ${x.number}. ${x.name}`)}}let g=p.filter(x=>!x.configured);g.length>0&&u.push(`Missing env vars: ${g.map(x=>x.name).join(", ")}`),i.deploy?.url?u.push(`Deployed: ${i.deploy.url} (${i.deploy.count??0} deploys)`):u.push("Not deployed yet");let D=[],_=a?.steps?.find(x=>x.status!=="completed");return _?D.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${_.number} (${_.name}).`):a&&l===c&&(i.deploy?.url||D.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),g.length>0&&D.push(`Missing env vars in .env.local: ${g.map(x=>x.name).join(", ")}`),d(JSON.stringify({name:i.name,projectId:i.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:c,completedSteps:l,steps:a.steps}:null,envStatus:p,deploy:i.deploy??null,contextMessage:u.join(`
40
- `),nextSteps:D}))}let o=[];if(e.completedStep!==void 0){let a=i.plan;if(a?.steps){let l=a.steps.findIndex(c=>c.number===e.completedStep);if(l===-1)return d(`Step ${e.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",o.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(i.env||(i.env={required:{}}),i.env.required||(i.env.required={}),i.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},o.push(`Added required env var: ${e.addEnvVar.key}`)),Cl(n,JSON.stringify(i,null,2)+`
38
+ `);try{await e.openBrowser(i)}catch{}let o=await Ws(n.device_code,6,5e3,e);return o||d(JSON.stringify({status:"pending",deviceCode:n.device_code,signInUrl:i,userCode:n.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+n.device_code+"' to check if they approved."}))}var Vs={name:"mist_setup",description:fs,inputSchema:sl,handler:t=>ll(t)};import{z as De}from"zod";import{resolve as qn}from"path";import{existsSync as Bn,readFileSync as zn}from"fs";import{join as Hn}from"path";import{z as ct}from"zod";import{resolve as Il,join as Zs}from"path";import{existsSync as Pl,readFileSync as eo,writeFileSync as Cl}from"fs";import{existsSync as cl,readFileSync as dl}from"fs";function Ks(t){let e=new Set;if(!cl(t))return e;let r=dl(t,"utf-8");for(let n of r.split(`
39
+ `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o>0){let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();a&&a!=='""'&&a!=="''"&&e.add(s)}}return e}var Al=ct.object({action:ct.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:ct.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:ct.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:ct.object({key:ct.string(),description:ct.string().optional(),setupUrl:ct.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),to={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Called internally by mist_project; host AIs should use mist_project directly.",inputSchema:Al,handler:async t=>{let e=t,r=Il(e.projectPath??process.cwd()),n=Zs(r,"mistflow.json");if(!Pl(n))return Xe(r);let i;try{i=JSON.parse(eo(n,"utf-8"))}catch{return d("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!i.projectId)try{let{ensureBackendRegistered:x}=await Promise.resolve().then(()=>(Vr(),Gr));await x(r)&&(i=JSON.parse(eo(n,"utf-8")))}catch{}let a=i.plan,l=a?.steps?.filter(x=>x.status==="completed").length??0,c=a?.steps?.length??0,m=Ks(Zs(r,".env.local")),p=i.env?.required?Object.entries(i.env.required).map(([x,y])=>({name:x,description:y?.description,configured:m.has(x)})):[];i.projectId&&Promise.resolve().then(()=>(xt(),an)).then(({fetchRemoteState:x})=>x(i.projectId)).catch(()=>{});let u=[`Project: ${i.name}`];if(a){u.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let x of a.steps){let y=x.status==="completed"?"\u2713":x.status==="in_progress"?"\u2192":" ";u.push(` [${y}] ${x.number}. ${x.name}`)}}let h=p.filter(x=>!x.configured);h.length>0&&u.push(`Missing env vars: ${h.map(x=>x.name).join(", ")}`),i.deploy?.url?u.push(`Deployed: ${i.deploy.url} (${i.deploy.count??0} deploys)`):u.push("Not deployed yet");let N=[],_=a?.steps?.find(x=>x.status!=="completed");return _?N.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${_.number} (${_.name}).`):a&&l===c&&(i.deploy?.url||N.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),h.length>0&&N.push(`Missing env vars in .env.local: ${h.map(x=>x.name).join(", ")}`),d(JSON.stringify({name:i.name,projectId:i.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:c,completedSteps:l,steps:a.steps}:null,envStatus:p,deploy:i.deploy??null,contextMessage:u.join(`
40
+ `),nextSteps:N}))}let o=[];if(e.completedStep!==void 0){let a=i.plan;if(a?.steps){let l=a.steps.findIndex(c=>c.number===e.completedStep);if(l===-1)return d(`Step ${e.completedStep} not found in the plan.`,!0);a.steps[l].status="completed",o.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(i.env||(i.env={required:{}}),i.env.required||(i.env.required={}),i.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},o.push(`Added required env var: ${e.addEnvVar.key}`)),Cl(n,JSON.stringify(i,null,2)+`
41
41
  `),i.projectId&&Promise.resolve().then(()=>(xt(),an)).then(async({readLocalState:a,syncRemoteState:l})=>{let c=a(r);c&&await l(i.projectId,c)}).catch(()=>{});let s=[];if(e.completedStep!==void 0){let l=i.plan?.steps?.find(c=>c.status!=="completed");l?s.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):s.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }) to deploy the app. Do NOT suggest localhost.")}return e.addEnvVar&&(s.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&s.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),d(JSON.stringify({updated:!0,changes:o,message:o.length>0?`Project state saved. ${o.join(". ")}.`:"No changes made.",nextSteps:s.length>0?s:void 0}))}};_e();Yt();var Kr={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"neon-smart-search":{description:"Semantic and hybrid search using Neon Postgres, pgvector, Postgres full-text search, and embeddings.",tags:["search","semantic","vector","embedding","hybrid","rag","knowledge-base","documents"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for generating embeddings",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://neon.com/docs/extensions/pgvector",packages:["openai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},Dt=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
42
42
 
43
43
  ### File Structure
@@ -1591,12 +1591,12 @@ export async function searchDocumentsHybrid(query: string, limit = 10) {
1591
1591
  ${o.map(s=>` - ${s}`).join(`
1592
1592
  `)}`);return n.join(`
1593
1593
 
1594
- `)}function ro(t){return(t?Jr(t):Dt).map(r=>{let n=Kr[r.id];return{id:r.id,slug:Rl(r.name),name:r.name,category:r.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var El=De.object({action:De.enum(["get","update","share","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:De.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:De.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:De.object({key:De.string(),description:De.string().optional(),setupUrl:De.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:De.string().optional().describe("(share) Short description of what this template builds"),category:De.string().optional().describe("(integrations) Filter integrations by category"),integrationId:De.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:De.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:De.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),so={name:"mist_project",description:ys,inputSchema:El,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!xe())return Ne(`${e.action} project state`);switch(e.action){case"get":case"update":return to.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let n=Un(e.projectPath??process.cwd()),i=Bn(n,"mistflow.json");if(!Fn(i))return Xe(n);let o;try{o=JSON.parse(qn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first to register it.",!0);try{let a=await Fr(s,{isTemplate:!0,description:e.templateDescription});return d(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
1594
+ `)}function ro(t){return(t?Jr(t):Dt).map(r=>{let n=Kr[r.id];return{id:r.id,slug:Rl(r.name),name:r.name,category:r.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var El=De.object({action:De.enum(["get","update","share","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:De.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:De.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:De.object({key:De.string(),description:De.string().optional(),setupUrl:De.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:De.string().optional().describe("(share) Short description of what this template builds"),category:De.string().optional().describe("(integrations) Filter integrations by category"),integrationId:De.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:De.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:De.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),so={name:"mist_project",description:ys,inputSchema:El,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!xe())return Ne(`${e.action} project state`);switch(e.action){case"get":case"update":return to.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let n=qn(e.projectPath??process.cwd()),i=Hn(n,"mistflow.json");if(!Bn(i))return Xe(n);let o;try{o=JSON.parse(zn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first to register it.",!0);try{let a=await Fr(s,{isTemplate:!0,description:e.templateDescription});return d(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
1595
1595
 
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 d(l,!0)}}case"integrations":{if(e.integrationId){let s=jt(e.integrationId);if(!s)return d(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=Mt(s.id);return d(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=ro(e.category??void 0),i=Jr(e.category??void 0),o=no(i);return d(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=Bn(n,"mistflow.json");if(!Fn(i))return Xe(n);let o;try{o=JSON.parse(qn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first.",!0);try{let a=await Rr(s,e.period??"7d");return a.total===0?d(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):d(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return d(l,!0)}}case"logs":{let n=Un(e.projectPath??process.cwd()),i=Bn(n,"mistflow.json");if(!Fn(i))return Xe(n);let o;try{o=JSON.parse(qn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await Et(s);if(l.length===0)return d("No deployments found for this project.",!0);a=l[0].id}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return d(c,!0)}try{let[l,c]=await Promise.all([Ar(a),at(a)]),m=l.filter(u=>u.level==="error"),p=l.filter(u=>u.level==="warn");return d(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:m.length,warnCount:p.length,logs:l.map(u=>({time:u.timestamp,level:u.level,phase:u.phase,message:u.message})),message:c.status==="failed"?`Deployment failed. ${m.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${m.length} errors, ${p.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return d(c,!0)}}case"deployments":{let n=Un(e.projectPath??process.cwd()),i=Bn(n,"mistflow.json");if(!Fn(i))return Xe(n);let o;try{o=JSON.parse(qn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first.",!0);try{let a=await Et(s);return d(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return d(l,!0)}}case"version":{mr().backendSignalReceived||await wr();let n=mr(),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 d(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 d(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as St}from"zod";At();var Nl=St.object({action:St.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:St.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:St.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:St.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:St.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:St.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),oo={name:"mist_browser",description:bs,inputSchema:Nl,handler:async t=>{let e=t,r=await hr();if(e.action==="navigate"){if(!e.url)return d("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 Qt(r),m=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:o,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let p=await Xt(r);m.push({type:"image",data:p.toString("base64"),mimeType:"image/png"})}return{content:m}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return d("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return d("Selector is required for 'type'.",!0);if(!e.value)return d("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return d("Selector is required for 'fill'.",!0);if(!e.value)return d("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return d("Selector is required for 'select_option'.",!0);if(!e.value)return d("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return d("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let o;if(e.selector){let s=await r.$(e.selector);if(!s)return d(`Element not found: ${e.selector}`,!0);o=await s.screenshot({type:"png"})}else o=await Xt(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 Qt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}]}}let n=await Qt(r),i=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:n})}];if(e.includeScreenshot){let o=await Xt(r);i.push({type:"image",data:o.toString("base64"),mimeType:"image/png"})}return{content:i}}};import{z as io}from"zod";var ao=`# Mistflow MCP tool reference
1599
+ "build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return d(l,!0)}}case"integrations":{if(e.integrationId){let s=jt(e.integrationId);if(!s)return d(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=Mt(s.id);return d(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=ro(e.category??void 0),i=Jr(e.category??void 0),o=no(i);return d(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=qn(e.projectPath??process.cwd()),i=Hn(n,"mistflow.json");if(!Bn(i))return Xe(n);let o;try{o=JSON.parse(zn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first.",!0);try{let a=await Rr(s,e.period??"7d");return a.total===0?d(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):d(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return d(l,!0)}}case"logs":{let n=qn(e.projectPath??process.cwd()),i=Hn(n,"mistflow.json");if(!Bn(i))return Xe(n);let o;try{o=JSON.parse(zn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await Et(s);if(l.length===0)return d("No deployments found for this project.",!0);a=l[0].id}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return d(c,!0)}try{let[l,c]=await Promise.all([Ar(a),at(a)]),m=l.filter(u=>u.level==="error"),p=l.filter(u=>u.level==="warn");return d(JSON.stringify({deploymentId:a,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:m.length,warnCount:p.length,logs:l.map(u=>({time:u.timestamp,level:u.level,phase:u.phase,message:u.message})),message:c.status==="failed"?`Deployment failed. ${m.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${m.length} errors, ${p.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return d(c,!0)}}case"deployments":{let n=qn(e.projectPath??process.cwd()),i=Hn(n,"mistflow.json");if(!Bn(i))return Xe(n);let o;try{o=JSON.parse(zn(i,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let s=o.projectId;if(!s)return d("No project ID found. Deploy the project first.",!0);try{let a=await Et(s);return d(JSON.stringify({total:a.length,deployments:a.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return d(l,!0)}}case"version":{mr().backendSignalReceived||await wr();let n=mr(),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 d(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 d(`Unknown action: ${e.action}. Use get, update, share, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as St}from"zod";At();var Nl=St.object({action:St.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:St.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:St.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:St.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:St.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:St.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),oo={name:"mist_browser",description:bs,inputSchema:Nl,handler:async t=>{let e=t,r=await hr();if(e.action==="navigate"){if(!e.url)return d("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 Qt(r),m=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:c,consoleErrors:o,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let p=await Xt(r);m.push({type:"image",data:p.toString("base64"),mimeType:"image/png"})}return{content:m}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return d("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return d("Selector is required for 'type'.",!0);if(!e.value)return d("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return d("Selector is required for 'fill'.",!0);if(!e.value)return d("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return d("Selector is required for 'select_option'.",!0);if(!e.value)return d("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return d("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let o;if(e.selector){let s=await r.$(e.selector);if(!s)return d(`Element not found: ${e.selector}`,!0);o=await s.screenshot({type:"png"})}else o=await Xt(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 Qt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}]}}let n=await Qt(r),i=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:n})}];if(e.includeScreenshot){let o=await Xt(r);i.push({type:"image",data:o.toString("base64"),mimeType:"image/png"})}return{content:i}}};import{z as io}from"zod";var ao=`# 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
@@ -1917,7 +1917,7 @@ is cheaper than building the wrong thing and iterating.
1917
1917
  `),i=new RegExp(`^### \`${r}`),o=-1,s=n.length;for(let a=0;a<n.length;a++)if(i.test(n[a]))o=a;else if(o>=0&&n[a].startsWith("### ")){s=a;break}else if(o>=0&&n[a].startsWith("## ")&&a>o){s=a;break}return o<0?d(`No tool named '${r}' found. Call mist_help with no args to see the full catalog.`,!0):d(n.slice(o,s).join(`
1918
1918
  `).trim())}};import{z as ln}from"zod";_e();var co=ln.object({action:ln.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:ln.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:ln.enum(["stack","skill","integration"]).optional().describe("Optional filter for action='list'. 'stack' = framework methodology, 'skill' = design + structural patterns, 'integration' = third-party services."),stack:ln.string().optional().default("nextjs").describe("Stack slug. Defaults to 'nextjs' (currently the only supported stack).")}),po={name:"mist_docs",description:vs,inputSchema:co,handler:async t=>{let{action:e,topic:r,kind:n,stack:i}=co.parse(t);try{if(e==="list"){let a=await jr(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
- `);let c={};for(let p of a.topics)(c[p.kind]??=[]).push(p);let m=["stack","skill","integration"];for(let p of m){let u=c[p];if(!(!u||u.length===0)){l.push(`## ${p}`);for(let g of u)l.push(`- **${g.id}** \u2014 ${g.title}: ${g.description}`);l.push("")}}return d(l.join(`
1920
+ `);let c={};for(let p of a.topics)(c[p.kind]??=[]).push(p);let m=["stack","skill","integration"];for(let p of m){let u=c[p];if(!(!u||u.length===0)){l.push(`## ${p}`);for(let h of u)l.push(`- **${h.id}** \u2014 ${h.title}: ${h.description}`);l.push("")}}return d(l.join(`
1921
1921
  `).trim())}if(!r)return d("Missing `topic`. Pass action='get' with a topic id, or action='list' to see available topics.",!0);let o=await Mr(i,r),s=`<!-- mist_docs: topic=${o.topic} kind=${o.kind} stack=${o.stack} -->
1922
1922
  # ${o.title}
1923
1923
 
@@ -1927,13 +1927,13 @@ ${o.description}
1927
1927
 
1928
1928
  `;return d(s+o.content)}catch(o){if(o instanceof J&&o.statusCode===404)return d(o.message,!0);let s=o instanceof Error?o.message:String(o);return d(`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 zn,mkdirSync as ho,readFileSync as go,readdirSync as fo,writeFileSync as Ol}from"fs";import{join as dt,resolve as Dl}from"path";import{homedir as Qr}from"os";import{z as cn}from"zod";function Lt(t){return t.entity??t.name??"Unknown"}function $t(t){return typeof t=="string"?t:t.name}function Yr(t){return typeof t=="string"?"text":t.type}function uo(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[$t(s)]=jl($t(s),Yr(s),Lt(t),i);n.push(o)}return n}function jl(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 Ml(t){let e=t.dataModel??[],r=t.pages??[],n=t.design??{},i=r.map(p=>({label:p.name??p.path??"Page",route:p.path??p.route??"/"})),o=[],s=e.slice(0,3).map(p=>({name:Lt(p),fields:(p.fields||[]).map(u=>({name:$t(u),type:Yr(u)})),sampleData:uo(p)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(p=>Lt(p)).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(p=>Lt(p)).join(", ")} with key metrics.`,informationHierarchy:a,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:s});let l=e[0];if(l){let p=Lt(l),u=p.toLowerCase().endsWith("s")?p:`${p}s`;o.push({name:`${p} List`,type:"detail",route:`/${u.toLowerCase()}`,purpose:`Browse, search, and manage ${u.toLowerCase()}. Create new ${p.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${u}" title + "Add ${p}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(g=>$t(g)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${u.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${u.toLowerCase()} matching..." with clear filter`],entities:[{name:p,fields:(l.fields||[]).map(g=>({name:$t(g),type:Yr(g)})),sampleData:uo(l)}]})}t.steps.some(p=>{let u=`${p.name??p.title??""} ${p.description??""}`.toLowerCase();return u.includes("landing")||u.includes("hero")||u.includes("marketing")||u.includes("homepage")})&&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 m=[];for(let p of e.slice(0,3)){let u=Lt(p);(p.fields||[]).find(D=>{let _=$t(D).toLowerCase();return _==="name"||_==="title"})&&m.push(`What if a ${u.toLowerCase()}'s name is 47 characters? Does the layout break?`),m.push(`What if there are 0 ${u.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&m.push("What does a brand-new user see? (no data, no setup)"),m.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens: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:m}}function Ll(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(`
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 Wn,mkdirSync as ho,readFileSync as go,readdirSync as fo,writeFileSync as Ol}from"fs";import{join as dt,resolve as Dl}from"path";import{homedir as Qr}from"os";import{z as cn}from"zod";function Lt(t){return t.entity??t.name??"Unknown"}function $t(t){return typeof t=="string"?t:t.name}function Yr(t){return typeof t=="string"?"text":t.type}function uo(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[$t(s)]=jl($t(s),Yr(s),Lt(t),i);n.push(o)}return n}function jl(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 Ml(t){let e=t.dataModel??[],r=t.pages??[],n=t.design??{},i=r.map(p=>({label:p.name??p.path??"Page",route:p.path??p.route??"/"})),o=[],s=e.slice(0,3).map(p=>({name:Lt(p),fields:(p.fields||[]).map(u=>({name:$t(u),type:Yr(u)})),sampleData:uo(p)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(p=>Lt(p)).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(p=>Lt(p)).join(", ")} with key metrics.`,informationHierarchy:a,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:s});let l=e[0];if(l){let p=Lt(l),u=p.toLowerCase().endsWith("s")?p:`${p}s`;o.push({name:`${p} List`,type:"detail",route:`/${u.toLowerCase()}`,purpose:`Browse, search, and manage ${u.toLowerCase()}. Create new ${p.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${u}" title + "Add ${p}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(h=>$t(h)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${u.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${u.toLowerCase()} matching..." with clear filter`],entities:[{name:p,fields:(l.fields||[]).map(h=>({name:$t(h),type:Yr(h)})),sampleData:uo(l)}]})}t.steps.some(p=>{let u=`${p.name??p.title??""} ${p.description??""}`.toLowerCase();return u.includes("landing")||u.includes("hero")||u.includes("marketing")||u.includes("homepage")})&&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 m=[];for(let p of e.slice(0,3)){let u=Lt(p);(p.fields||[]).find(N=>{let _=$t(N).toLowerCase();return _==="name"||_==="title"})&&m.push(`What if a ${u.toLowerCase()}'s name is 47 characters? Does the layout break?`),m.push(`What if there are 0 ${u.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&m.push("What does a brand-new user see? (no data, no setup)"),m.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens: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:m}}function Ll(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 yo(t){return dt(Qr(),".mistflow","mockup-state",`${t}.json`)}function $l(t){let e=yo(t);if(!zn(e))return null;try{return JSON.parse(go(e,"utf-8"))}catch{return null}}function mo(t,e){let r=dt(Qr(),".mistflow","mockup-state");ho(r,{recursive:!0}),Ol(yo(t),JSON.stringify(e,null,2))}var Ul=cn.object({planId:cn.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:cn.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:cn.string().optional().describe("User feedback to apply to the next iteration."),approved:cn.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."}),bo={name:"mist_mockup",description:xs,inputSchema:Ul,handler:async t=>{let e=t,{planId:r,feedback:n,approved:i}=e,o=Dl(e.projectPath??process.cwd()),s=dt(Qr(),".mistflow","plans",`${r}.json`);if(!zn(s))return d(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(go(s,"utf-8"))}catch{return d("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return d("Plan data is empty. Call mist_plan again.",!0);let c=$l(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let m=dt(o,".mistflow","mockups");ho(m,{recursive:!0});let p=`mockup-${r}.html`,u=dt(m,p);if(i){c.approved=!0,mo(r,c);let y=zn(m)?fo(m).filter(P=>P.endsWith(".html")).map(P=>dt(".mistflow","mockups",P)):[];return d(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 g=Ml(l);c.screens=g.screens.map(y=>y.name),mo(r,c);let D=Ll(g,n??void 0,u),_=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,x=n?`Apply the user's feedback to ${u}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${u}, then open it in the browser. Ask the user if the layout feels right.`;return d(JSON.stringify({status:"wireframe",requires_user_input:!0,iterationCount:c.iterationCount,screens:g.screens.map(y=>({name:y.name,type:y.type,route:y.route})),wireframePrompt:D,designDirection:g.designDirection,..._?{nudge:_}:{},mockupFile:p,mockupPath:u,nextAction:x}))}};function wo(t){let e=dt(t,".mistflow","mockups");return zn(e)?fo(e).filter(r=>r.endsWith(".html")).map(r=>dt(e,r)):[]}import{z as Xr}from"zod";import{resolve as Fl}from"path";import{spawn as ql}from"child_process";function Hn(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,c,m,p,u]=a;e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:`${p}: ${u}`,humanMessage:`There is a type error in ${l} on line ${c}: ${u}`,suggestion:`Check line ${c} in ${l}. ${p==="TS2345"?"The types of the arguments do not match.":`Fix the ${p} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(n)){let[,l,c,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(c,10))||e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:p,humanMessage:`There is an error in ${l} on line ${c}: ${p.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let 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,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(m,10))||e.push({file:l,line:parseInt(m,10),column:parseInt(p,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${m}.`,suggestion:`Check line ${m} in ${l} for a missing closing bracket or unexpected token.`})}return e}var Bl=Xr.object({projectPath:Xr.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:Xr.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});function zl(t){return new Promise(e=>{let r=ql("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 vo={name:"mist_debug",description:ks,inputSchema:Bl,handler:async t=>{let e=t,r=Fl(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let s=await zl(r);if(s.exitCode===0)return d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=s.combined}let i=Hn(n),o=n.slice(0,2e3);return i.length===0?d(JSON.stringify({errors:i,rawOutput:o,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):d(JSON.stringify({errors:i,rawOutput:o,message:`Found ${i.length} error${i.length===1?"":"s"} in the build output.`}))}};import{z as j}from"zod";import{existsSync as et,mkdirSync as Tt,readFileSync as un,readdirSync as Ao,statSync as Ro,unlinkSync as Zl,writeFileSync as pt}from"fs";import{dirname as ec,isAbsolute as tc,join as he}from"path";import{homedir as ut,hostname as So}from"os";import{createHash as nc,createHmac as Eo,randomBytes as rc,randomUUID as To,timingSafeEqual as sc}from"crypto";_e();import{spawn as Hl}from"child_process";function Zr(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(Wl())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=Hl(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 Wl(){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 ze(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 Gl(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function Vl(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function Kl(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function Jl(t){let e={},r=[],n=[],i=new Set;for(let o=0;o<t.length;o++){let s=t[o],a=s.decisionKey?Kl(s.decisionKey):`q_${o+1}`,l=a,c=2;for(;i.has(l);)l=`${a}_${c}`,c++;i.add(l);let m=s.freetext?"":`${l}_other`;if(m&&i.add(m),n.push({primary:l,other:m,question:s}),s.freetext){e[l]={type:"string",title:s.question,description:s.why,...s.recommended?{default:s.recommended}:{}},r.push(l);continue}let p=(s.options??[]).map(g=>typeof g=="string"?g:g.label),u=s.noOtherSentinel?[...p]:[...p,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:s.question,description:s.why?`${s.why}${s.recommended?`
1934
- Recommended: ${s.recommended}`:""}`:s.recommended?`Recommended: ${s.recommended}`:void 0,enum:u,enumNames:u,...s.recommended&&p.includes(s.recommended)?{default:s.recommended}:{}},r.push(l),e[m]={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 Yl(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 m=o?String(t[o]??"").trim():"",p=a.toLowerCase(),u=p.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(p);m?l=m:u?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 Ze(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 dn(t,e,r,n="discovery"){if(Vl()){let m={outcome:"unsupported"};return Ze(n,"MISTFLOW_ELICITATION kill switch on",m),m}if(!Gl(t)){let m={outcome:"unsupported"};return Ze(n,"client did not declare elicitation capability",m),m}if(e.length===0){let m={outcome:"submitted",answers:[]};return Ze(n,"no questions to ask",m),m}let{schema:i,fieldKeys:o}=Jl(e),s;try{s=await t.elicitInput({message:r,requestedSchema:i,mode:"form"},{timeout:300*1e3})}catch(m){let p=m instanceof Error?m.message:String(m);if(p.toLowerCase().includes("not support")){let g={outcome:"unsupported"};return Ze(n,`SDK rejected form mode: ${p}`,g),g}let u={outcome:"error",errorMessage:p};return Ze(n,"",u),u}if(s.action==="decline"){let m={outcome:"declined"};return Ze(n,"",m),m}if(s.action==="cancel"){let m={outcome:"cancelled"};return Ze(n,"",m),m}if(s.action!=="accept"||!s.content){let m={outcome:"error",errorMessage:`Unexpected elicitation result: ${s.action}`};return Ze(n,"",m),m}let{answers:a,urlChoice:l}=Yl(s.content,o),c={outcome:"submitted",answers:a,urlChoice:l};return Ze(n,"",c),c}var Ql=[{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 ko(t,e,r){let n=r?.suggestedName||Xl(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 Ql){let m=c.keywords.test(l),p=c.condition(e);(m||p)&&a.push({name:c.name,description:c.description,checked:m,source:m?"explicit":"suggested"})}}return{name: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 xo(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
- `)}function Xl(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return Wn(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 Wn(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}function es(t,e,r){let n=pn(t||"your app"),i=e.map((s,a)=>{let l=Gn(s.id||`direction-${a}`),c=pn(s.name||`Direction ${a+1}`),m=pn(s.summary||"");return`<button class="tab${a===0?" active":""}" data-target="${l}" type="button"><span class="tab-name">${c}</span>${m?`<span class="tab-sub">${m}</span>`:""}</button>`}).join(`
1936
- `),o=e.map((s,a)=>{let l=Gn(s.id||`direction-${a}`),c=r[s.id??""]??"";return`<iframe class="render-frame${a===0?" active":""}" data-id="${l}" srcdoc="${Gn(c)}" sandbox="allow-same-origin allow-scripts" title="${Gn(s.name||`Direction ${a+1}`)}"></iframe>`}).join(`
1932
+ `)}function yo(t){return dt(Qr(),".mistflow","mockup-state",`${t}.json`)}function $l(t){let e=yo(t);if(!Wn(e))return null;try{return JSON.parse(go(e,"utf-8"))}catch{return null}}function mo(t,e){let r=dt(Qr(),".mistflow","mockup-state");ho(r,{recursive:!0}),Ol(yo(t),JSON.stringify(e,null,2))}var Ul=cn.object({planId:cn.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:cn.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:cn.string().optional().describe("User feedback to apply to the next iteration."),approved:cn.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."}),bo={name:"mist_mockup",description:xs,inputSchema:Ul,handler:async t=>{let e=t,{planId:r,feedback:n,approved:i}=e,o=Dl(e.projectPath??process.cwd()),s=dt(Qr(),".mistflow","plans",`${r}.json`);if(!Wn(s))return d(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(go(s,"utf-8"))}catch{return d("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return d("Plan data is empty. Call mist_plan again.",!0);let c=$l(r);c||(c={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let m=dt(o,".mistflow","mockups");ho(m,{recursive:!0});let p=`mockup-${r}.html`,u=dt(m,p);if(i){c.approved=!0,mo(r,c);let y=Wn(m)?fo(m).filter(P=>P.endsWith(".html")).map(P=>dt(".mistflow","mockups",P)):[];return d(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 h=Ml(l);c.screens=h.screens.map(y=>y.name),mo(r,c);let N=Ll(h,n??void 0,u),_=c.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,x=n?`Apply the user's feedback to ${u}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${u}, then open it in the browser. Ask the user if the layout feels right.`;return d(JSON.stringify({status:"wireframe",requires_user_input:!0,iterationCount:c.iterationCount,screens:h.screens.map(y=>({name:y.name,type:y.type,route:y.route})),wireframePrompt:N,designDirection:h.designDirection,..._?{nudge:_}:{},mockupFile:p,mockupPath:u,nextAction:x}))}};function wo(t){let e=dt(t,".mistflow","mockups");return Wn(e)?fo(e).filter(r=>r.endsWith(".html")).map(r=>dt(e,r)):[]}import{z as Xr}from"zod";import{resolve as Fl}from"path";import{spawn as ql}from"child_process";function Gn(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,c,m,p,u]=a;e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:`${p}: ${u}`,humanMessage:`There is a type error in ${l} on line ${c}: ${u}`,suggestion:`Check line ${c} in ${l}. ${p==="TS2345"?"The types of the arguments do not match.":`Fix the ${p} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(n)){let[,l,c,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(c,10))||e.push({file:l,line:parseInt(c,10),column:parseInt(m,10),message:p,humanMessage:`There is an error in ${l} on line ${c}: ${p.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let 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,m,p]=a;e.some(u=>u.file===l&&u.line===parseInt(m,10))||e.push({file:l,line:parseInt(m,10),column:parseInt(p,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${m}.`,suggestion:`Check line ${m} in ${l} for a missing closing bracket or unexpected token.`})}return e}var Bl=Xr.object({projectPath:Xr.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:Xr.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});function zl(t){return new Promise(e=>{let r=ql("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 vo={name:"mist_debug",description:ks,inputSchema:Bl,handler:async t=>{let e=t,r=Fl(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let s=await zl(r);if(s.exitCode===0)return d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=s.combined}let i=Gn(n),o=n.slice(0,2e3);return i.length===0?d(JSON.stringify({errors:i,rawOutput:o,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):d(JSON.stringify({errors:i,rawOutput:o,message:`Found ${i.length} error${i.length===1?"":"s"} in the build output.`}))}};import{z as j}from"zod";import{existsSync as et,mkdirSync as Tt,readFileSync as un,readdirSync as Ao,statSync as Ro,unlinkSync as Zl,writeFileSync as pt}from"fs";import{dirname as ec,isAbsolute as tc,join as he}from"path";import{homedir as ut,hostname as So}from"os";import{createHash as nc,createHmac as Eo,randomBytes as rc,randomUUID as To,timingSafeEqual as sc}from"crypto";_e();import{spawn as Hl}from"child_process";function Zr(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(Wl())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=Hl(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 Wl(){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 ze(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 Gl(t){try{return!!t.getClientCapabilities()?.elicitation}catch{return!1}}function Vl(){let t=(process.env.MISTFLOW_ELICITATION??"").toLowerCase().trim();return t==="off"||t==="false"||t==="0"||t==="disabled"}function Kl(t){let e=t.replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(e)?e:`_${e}`}function Jl(t){let e={},r=[],n=[],i=new Set;for(let o=0;o<t.length;o++){let s=t[o],a=s.decisionKey?Kl(s.decisionKey):`q_${o+1}`,l=a,c=2;for(;i.has(l);)l=`${a}_${c}`,c++;i.add(l);let m=s.freetext?"":`${l}_other`;if(m&&i.add(m),n.push({primary:l,other:m,question:s}),s.freetext){e[l]={type:"string",title:s.question,description:s.why,...s.recommended?{default:s.recommended}:{}},r.push(l);continue}let p=(s.options??[]).map(h=>typeof h=="string"?h:h.label),u=s.noOtherSentinel?[...p]:[...p,"Other (specify in the 'Other' field below)"];e[l]={type:"string",title:s.question,description:s.why?`${s.why}${s.recommended?`
1934
+ Recommended: ${s.recommended}`:""}`:s.recommended?`Recommended: ${s.recommended}`:void 0,enum:u,enumNames:u,...s.recommended&&p.includes(s.recommended)?{default:s.recommended}:{}},r.push(l),e[m]={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 Yl(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 m=o?String(t[o]??"").trim():"",p=a.toLowerCase(),u=p.startsWith("other")||/\btype\b|\bcustom\b|\bdifferent\b/.test(p);m?l=m:u?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 Ze(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 dn(t,e,r,n="discovery"){if(Vl()){let m={outcome:"unsupported"};return Ze(n,"MISTFLOW_ELICITATION kill switch on",m),m}if(!Gl(t)){let m={outcome:"unsupported"};return Ze(n,"client did not declare elicitation capability",m),m}if(e.length===0){let m={outcome:"submitted",answers:[]};return Ze(n,"no questions to ask",m),m}let{schema:i,fieldKeys:o}=Jl(e),s;try{s=await t.elicitInput({message:r,requestedSchema:i,mode:"form"},{timeout:300*1e3})}catch(m){let p=m instanceof Error?m.message:String(m);if(p.toLowerCase().includes("not support")){let h={outcome:"unsupported"};return Ze(n,`SDK rejected form mode: ${p}`,h),h}let u={outcome:"error",errorMessage:p};return Ze(n,"",u),u}if(s.action==="decline"){let m={outcome:"declined"};return Ze(n,"",m),m}if(s.action==="cancel"){let m={outcome:"cancelled"};return Ze(n,"",m),m}if(s.action!=="accept"||!s.content){let m={outcome:"error",errorMessage:`Unexpected elicitation result: ${s.action}`};return Ze(n,"",m),m}let{answers:a,urlChoice:l}=Yl(s.content,o),c={outcome:"submitted",answers:a,urlChoice:l};return Ze(n,"",c),c}var Ql=[{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 ko(t,e,r){let n=r?.suggestedName||Xl(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 Ql){let m=c.keywords.test(l),p=c.condition(e);(m||p)&&a.push({name:c.name,description:c.description,checked:m,source:m?"explicit":"suggested"})}}return{name: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 xo(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
+ `)}function Xl(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return Vn(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 Vn(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}function es(t,e,r){let n=pn(t||"your app"),i=e.map((s,a)=>{let l=Kn(s.id||`direction-${a}`),c=pn(s.name||`Direction ${a+1}`),m=pn(s.summary||"");return`<button class="tab${a===0?" active":""}" data-target="${l}" type="button"><span class="tab-name">${c}</span>${m?`<span class="tab-sub">${m}</span>`:""}</button>`}).join(`
1936
+ `),o=e.map((s,a)=>{let l=Kn(s.id||`direction-${a}`),c=r[s.id??""]??"";return`<iframe class="render-frame${a===0?" active":""}" data-id="${l}" srcdoc="${Kn(c)}" sandbox="allow-same-origin allow-scripts" title="${Kn(s.name||`Direction ${a+1}`)}"></iframe>`}).join(`
1937
1937
  `);return`<!doctype html>
1938
1938
  <html lang="en">
1939
1939
  <head>
@@ -2040,38 +2040,38 @@ ${o}
2040
2040
  </script>
2041
2041
  </body>
2042
2042
  </html>
2043
- `}function pn(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Gn(t){return pn(t)}var Vn="__mistflow_url_choice__",oc=600*1e3;function No(){let t=he(ut(),".mistflow","confirm-secret");if(et(t))try{return Buffer.from(un(t,"utf-8").trim(),"hex")}catch{}let e=rc(32);return Tt(he(ut(),".mistflow"),{recursive:!0}),pt(t,e.toString("hex"),{mode:384}),e}function Oo(t){return nc("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function ic(t,e){let r={cwd:t,d:Oo(e),exp:Date.now()+oc},n=Buffer.from(JSON.stringify(r)).toString("base64url"),i=Eo("sha256",No()).update(n).digest("base64url");return`${n}.${i}`}function ac(t,e,r){let n=t.split(".");if(n.length!==2)return!1;let[i,o]=n,s=Eo("sha256",No()).update(i).digest("base64url"),a=Buffer.from(o),l=Buffer.from(s);if(a.length!==l.length||!sc(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!==Oo(r))}catch{return!1}}function lc(t){let e=t,r=ut(),n=!1;for(let i=0;i<64;i++){if(et(he(e,"mistflow.json")))return"mistflow";if(!n&&et(he(e,"package.json"))&&(n=!0),e===r)break;let o=ec(e);if(o===e)break;e=o}return n?"foreign":"none"}function cc(t){let e=ut(),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===he(e,i))return!0;return!1}function dc(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 _o(t){if(!et(t))return!0;try{return Ro(t).isDirectory()?Ao(t).filter(n=>n!==".mistflow").length===0:!1}catch{return!1}}function pc(t,e){let r=dc(e),n=he(t,r);if(_o(n))return n;for(let i=2;i<=50;i++){let o=he(t,`${r}-${i}`);if(_o(o))return o}return he(t,`${r}-${Date.now()}`)}function uc(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 Io(t){try{Tt(t,{recursive:!0});return}catch(e){return e instanceof Error?e.message:String(e)}}function Po(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 mc=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 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: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 hc(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 gc(t){let e=he(ut(),".mistflow","plans",`${t}.json`);if(!et(e))return null;try{return JSON.parse(un(e,"utf-8")).plan??null}catch{return null}}async function fc(t){let e=Date.now(),r=5e4,n=2e3;for(;Date.now()-e<r;){try{let i=await An(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 yc(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function bc(t,e){for(let r of e){let n=yc(t[r]);if(n)return n}}function wc(t){return bc(t,["mockup_url","mockupUrl","preview_url","previewUrl","live_url","liveUrl","deploy_url","deployUrl","url"])}function Co(t,e){return`Next action: call ${t} with ${JSON.stringify(e)}. Do not omit sessionId.`}function vc(t){let e=wc(t),r=t.reason?`
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 kc(t,e){let{description:r,projectPath:n,sessionId:i,conversationId:o,answers:s,existingPlan:a,existingPlanId:l,templateToken:c,remixDescription:m,autonomous:p,language:u,brandMentioned:g,confirmToken:D,urlChoice:_,designConversationId:x,designDirection:y,userConfirmedCustom:P,forceNew:z}=t;if(i&&!o&&!x)try{let h=await Ot(i),f=[`Session ID: ${h.session_id}`,`Status: ${h.status??"active"}`,`Instruction: ${h.instruction}`];switch(h.reason&&f.push(`Reason: ${h.reason}`),h.instruction){case"wait":return d([...f,`Next action: ${h.reason??"The backend is still preparing the next step."} Tell the user briefly what's happening, then call mist_plan with { projectPath, sessionId: "${h.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
- `));case"resume_conversation":{let k=h.conversation_id;return d([...f,`In-flight conversation: ${k??"(missing \u2014 backend bug)"}`,`Next action: call mist_plan with { projectPath, conversationId: "${k??""}" } 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
- `))}case"continue":return d([...f,`Next action: ${h.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(`
2048
- `));case"call_mist_init":return d([...f,Co("mist_init",{sessionId:h.session_id,path:n})].join(`
2049
- `));case"call_mist_deploy":return d([...f,Co("mist_deploy",{sessionId:h.session_id,projectPath:n})].join(`
2050
- `));case"review_plan":return d([...f,`Next action: ${h.reason??"User asked to review PLAN.md before scaffolding. Open <projectPath>/PLAN.md, let the user read / edit, then call mist_session({ resume }) and re-run mist_init."}`].join(`
2051
- `));case"done":return d([...f,vc(h)].join(`
2052
- `))}}catch(h){let f=h instanceof Error?h.message:String(h);return d(`Could not poll session '${i}': ${f}`,!0)}if(o&&!r&&!s&&!x&&!y&&!a&&!l&&!c)try{let h=await Nn(o);if(h.status==="clarify_pending"||h.status==="plan_pending"){let f=typeof h.phase_hint=="string"?h.phase_hint:null,k=typeof h.elapsed_seconds=="number"?h.elapsed_seconds:null,T=typeof h.progress=="number"?h.progress:null,E=h.status==="plan_pending",B=E?"generating_plan":"generating_questions",se=f?`${f}${k!==null?` (${k}s elapsed)`:""}`:E?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return d(JSON.stringify({status:"running",conversationId:o,phase:B,...f?{phaseHint:f}:{},...k!==null?{elapsedSeconds:k}:{},...T!==null?{progress:T}:{},nextAction:`${se}. Tell the user briefly what's happening (e.g. "${f??(E?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}if(h.status==="design_clarify"&&Array.isArray(h.directions)){let k=h.directions.map((I,Te)=>({id:I.id??String(Te),name:I.name??`Direction ${Te+1}`,summary:I.summary,hero_headline:I.hero_headline,cta_text:I.cta_text,body_sample:I.body_sample,fonts:I.fonts,colors:I.colors,hero_treatment:I.hero_treatment,shape_lang:I.shape_lang,texture:I.texture,decoration_hint:I.decoration_hint})),T=h.plan?.name??"your app",E=h.design_conversation_id,B={},se=!1;try{if(E){let be=Date.now();for(;Date.now()-be<5e4;){let b=await En(E),w=0;for(let F of k){let ne=b[F.id];ne&&((ne.status==="done"||ne.status==="ready")&&typeof ne.html=="string"&&ne.html.length>0?(B[F.id]=ne.html,w+=1):ne.status==="failed"&&(w+=1))}if(w===k.length){se=!0;break}await new Promise(F=>setTimeout(F,5e3))}}}catch(I){console.error(`[mist_plan:design_clarify] render poll failed: ${I instanceof Error?I.message:String(I)}`)}if(!se)return d(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:o,design_conversation_id:E,renderedSoFar:Object.keys(B).length,totalDirections:k.length,nextAction:`${Object.keys(B).length}/${k.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${o}" } again IMMEDIATELY \u2014 do NOT bash sleep. The render-poll holds the connection up to ~50s; each call returns as soon as state changes. Do NOT ask the user about design yet; the picker isn't ready.`}));let ie=k.filter(I=>B[I.id]),me,O,G=he(n,".mistflow"),we=he(G,"design-directions.html"),oe=he(G,"picker-state.json"),fe=!1;if(E)try{et(oe)&&JSON.parse(un(oe,"utf-8")).opened_for_design_cid===E&&(fe=!0)}catch{}try{if(Tt(G,{recursive:!0}),fe)me=we;else{let I=es(T,ie,B);pt(we,I,"utf-8"),me=we;let Te=Zr(`file://${we}`);Te.opened||(O=Te.reason),E&&pt(oe,JSON.stringify({opened_for_design_cid:E,opened_at:new Date().toISOString()},null,2),"utf-8")}}catch(I){console.error(`[mist_plan:design_clarify] picker write/open failed: ${I instanceof Error?I.message:String(I)}`)}let de=ie.map(I=>({id:I.id,name:I.name})),ue=de.map(I=>I.name).filter(Boolean);return d(JSON.stringify({status:"design_clarify",previewPath:me,previewOpenError:O,directionRefs:de,directionNames:ue,design_conversation_id:E,conversation_id:o,nextAction:[`The visual picker has been opened in the user's browser at file://${me??"(path missing)"} \u2014 every direction is a real, rendered landing page. The user is looking at it now.`,O?`(auto-open suppressed: ${O} \u2014 tell the user to open file://${me} manually)`:"",`Now use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names as options: ${ue.map(I=>`"${I}"`).join(", ")}. Do NOT invent extra options. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${o}", designConversationId: "${E}", designDirection: { id: "<map name \u2192 id from directionRefs>" } }. If the user types a custom description, pass designDirection: { custom: "<their exact words>" } and userConfirmedCustom: true.`].filter(Boolean).join(`
2053
-
2054
- `)}))}return d(JSON.stringify(h))}catch(h){let f=h instanceof Error?h.message:String(h);return d(`Could not poll plan conversation '${o}': ${f}`,!0)}let V=r??"";if(!V.trim()&&!o&&!x&&!a&&!l&&!c)return d("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(x&&!y&&!V.trim()&&!s)return d(`You passed designConversationId='${x}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${x}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let Z=a;if(!Z&&l&&(Z=gc(l)??void 0,!Z))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let ae=o;if(!xe())return Ne("plan a new app");let L,H;if(!ae&&!Z&&!c&&!x){if(!tc(n))return d(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let h=lc(n);if(h!=="mistflow"&&cc(n))return d(JSON.stringify({status:"unsafe_cwd",projectPath:n,instruction:[`The projectPath you passed (${n}) is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Create the subfolder at ${n}/<subfolder-name>.`," 3. Call mist_plan again with the SAME description and projectPath set to the new subfolder.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description."].join(`
2055
- `)}),!0);if(h==="foreign"){let f=D?ac(D,n,V):!1,k=pc(n,V),T=uc(V,g);if(T||f){H=k;let E=Io(H);if(E)return d(`Mistflow could not create the scaffold directory at ${H}: ${E}`,!0);L=`Note: Mistflow will scaffold the new app at \`${H}\`. The existing project at \`${n}\` is not modified.`}if(!f&&!T){let E=ic(n,V);if(e?.server){let B=await dn(e.server,[{question:"You're inside an existing project. Where should Mistflow scaffold the new app?",decisionKey:"scopeChoice",recommended:`Create at: ${k}`,why:"Mistflow creates a NEW app and never modifies the surrounding codebase. The default puts it in a subdirectory of the current path, named after your description. You can pick a custom path or cancel if you actually want to edit the existing project instead.",options:[{label:`Create at: ${k}`,description:"Default \u2014 uses your description as the folder name."},{label:"Choose a different path",description:"Type a custom absolute path in the textbox below."},{label:"Cancel \u2014 I wanted to edit the existing project",description:"Stop Mistflow. Handle the request by editing files in the current project instead."}]}],`## Existing project detected
2043
+ `}function pn(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Kn(t){return pn(t)}var Jn="__mistflow_url_choice__",oc=600*1e3;function No(){let t=he(ut(),".mistflow","confirm-secret");if(et(t))try{return Buffer.from(un(t,"utf-8").trim(),"hex")}catch{}let e=rc(32);return Tt(he(ut(),".mistflow"),{recursive:!0}),pt(t,e.toString("hex"),{mode:384}),e}function Oo(t){return nc("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function ic(t,e){let r={cwd:t,d:Oo(e),exp:Date.now()+oc},n=Buffer.from(JSON.stringify(r)).toString("base64url"),i=Eo("sha256",No()).update(n).digest("base64url");return`${n}.${i}`}function ac(t,e,r){let n=t.split(".");if(n.length!==2)return!1;let[i,o]=n,s=Eo("sha256",No()).update(i).digest("base64url"),a=Buffer.from(o),l=Buffer.from(s);if(a.length!==l.length||!sc(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!==Oo(r))}catch{return!1}}function lc(t){let e=t,r=ut(),n=!1;for(let i=0;i<64;i++){if(et(he(e,"mistflow.json")))return"mistflow";if(!n&&et(he(e,"package.json"))&&(n=!0),e===r)break;let o=ec(e);if(o===e)break;e=o}return n?"foreign":"none"}function cc(t){let e=ut(),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===he(e,i))return!0;return!1}function dc(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 _o(t){if(!et(t))return!0;try{return Ro(t).isDirectory()?Ao(t).filter(n=>n!==".mistflow").length===0:!1}catch{return!1}}function pc(t,e){let r=dc(e),n=he(t,r);if(_o(n))return n;for(let i=2;i<=50;i++){let o=he(t,`${r}-${i}`);if(_o(o))return o}return he(t,`${r}-${Date.now()}`)}function uc(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 Io(t){try{Tt(t,{recursive:!0});return}catch(e){return e instanceof Error?e.message:String(e)}}function Po(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 mc=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 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: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 hc(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 gc(t){let e=he(ut(),".mistflow","plans",`${t}.json`);if(!et(e))return null;try{return JSON.parse(un(e,"utf-8")).plan??null}catch{return null}}async function fc(t){let e=Date.now(),r=5e4,n=2e3;for(;Date.now()-e<r;){try{let i=await En(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 yc(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function bc(t,e){for(let r of e){let n=yc(t[r]);if(n)return n}}function wc(t){return bc(t,["mockup_url","mockupUrl","preview_url","previewUrl","live_url","liveUrl","deploy_url","deployUrl","url"])}function Co(t,e){return`Next action: call ${t} with ${JSON.stringify(e)}. Do not omit sessionId.`}function vc(t){let e=wc(t),r=t.reason?`
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 kc(t,e){let{description:r,projectPath:n,sessionId:i,conversationId:o,answers:s,existingPlan:a,existingPlanId:l,templateToken:c,remixDescription:m,autonomous:p,language:u,brandMentioned:h,confirmToken:N,urlChoice:_,designConversationId:x,designDirection:y,userConfirmedCustom:P,forceNew:z}=t;if(i&&!o&&!x)try{let g=await Ot(i),f=[`Session ID: ${g.session_id}`,`Status: ${g.status??"active"}`,`Instruction: ${g.instruction}`];switch(g.reason&&f.push(`Reason: ${g.reason}`),g.instruction){case"wait":return d([...f,`Next action: ${g.reason??"The backend is still preparing the next step."} Tell the user briefly what's happening, then call mist_plan with { projectPath, sessionId: "${g.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
+ `));case"resume_conversation":{let k=g.conversation_id;return d([...f,`In-flight conversation: ${k??"(missing \u2014 backend bug)"}`,`Next action: call mist_plan with { projectPath, conversationId: "${k??""}" } 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
+ `))}case"continue":return d([...f,`Next action: ${g.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(`
2048
+ `));case"call_mist_init":return d([...f,Co("mist_init",{sessionId:g.session_id,path:n})].join(`
2049
+ `));case"call_mist_deploy":return d([...f,Co("mist_deploy",{sessionId:g.session_id,projectPath:n})].join(`
2050
+ `));case"review_plan":return d([...f,`Next action: ${g.reason??"User asked to review PLAN.md before scaffolding. Open <projectPath>/PLAN.md, let the user read / edit, then call mist_session({ resume }) and re-run mist_init."}`].join(`
2051
+ `));case"done":return d([...f,vc(g)].join(`
2052
+ `))}}catch(g){let f=g instanceof Error?g.message:String(g);return d(`Could not poll session '${i}': ${f}`,!0)}if(o&&!r&&!s&&!x&&!y&&!a&&!l&&!c)try{let g=await Dn(o);if(g.status==="clarify_pending"||g.status==="plan_pending"){let f=typeof g.phase_hint=="string"?g.phase_hint:null,k=typeof g.elapsed_seconds=="number"?g.elapsed_seconds:null,T=typeof g.progress=="number"?g.progress:null,E=g.status==="plan_pending",B=E?"generating_plan":"generating_questions",se=f?`${f}${k!==null?` (${k}s elapsed)`:""}`:E?"Plan is being generated (build_plan + image enrichment, 30-60s typical)":"Discovery questions are being analyzed";return d(JSON.stringify({status:"running",conversationId:o,phase:B,...f?{phaseHint:f}:{},...k!==null?{elapsedSeconds:k}:{},...T!==null?{progress:T}:{},nextAction:`${se}. Tell the user briefly what's happening (e.g. "${f??(E?"Generating the plan":"Analyzing your description")}"), then call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the next phase lands.`}))}if(g.status==="design_clarify"&&Array.isArray(g.directions)){let k=g.directions.map((I,Te)=>({id:I.id??String(Te),name:I.name??`Direction ${Te+1}`,summary:I.summary,hero_headline:I.hero_headline,cta_text:I.cta_text,body_sample:I.body_sample,fonts:I.fonts,colors:I.colors,hero_treatment:I.hero_treatment,shape_lang:I.shape_lang,texture:I.texture,decoration_hint:I.decoration_hint})),T=g.plan?.name??"your app",E=g.design_conversation_id,B={},se=!1;try{if(E){let be=Date.now();for(;Date.now()-be<5e4;){let b=await On(E),w=0;for(let F of k){let ne=b[F.id];ne&&((ne.status==="done"||ne.status==="ready")&&typeof ne.html=="string"&&ne.html.length>0?(B[F.id]=ne.html,w+=1):ne.status==="failed"&&(w+=1))}if(w===k.length){se=!0;break}await new Promise(F=>setTimeout(F,5e3))}}}catch(I){console.error(`[mist_plan:design_clarify] render poll failed: ${I instanceof Error?I.message:String(I)}`)}if(!se)return d(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:o,design_conversation_id:E,renderedSoFar:Object.keys(B).length,totalDirections:k.length,nextAction:`${Object.keys(B).length}/${k.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${o}" } again IMMEDIATELY \u2014 do NOT bash sleep. The render-poll holds the connection up to ~50s; each call returns as soon as state changes. Do NOT ask the user about design yet; the picker isn't ready.`}));let ie=k.filter(I=>B[I.id]),me,D,G=he(n,".mistflow"),we=he(G,"design-directions.html"),oe=he(G,"picker-state.json"),fe=!1;if(E)try{et(oe)&&JSON.parse(un(oe,"utf-8")).opened_for_design_cid===E&&(fe=!0)}catch{}try{if(Tt(G,{recursive:!0}),fe)me=we;else{let I=es(T,ie,B);pt(we,I,"utf-8"),me=we;let Te=Zr(`file://${we}`);Te.opened||(D=Te.reason),E&&pt(oe,JSON.stringify({opened_for_design_cid:E,opened_at:new Date().toISOString()},null,2),"utf-8")}}catch(I){console.error(`[mist_plan:design_clarify] picker write/open failed: ${I instanceof Error?I.message:String(I)}`)}let de=ie.map(I=>({id:I.id,name:I.name})),ue=de.map(I=>I.name).filter(Boolean);return d(JSON.stringify({status:"design_clarify",previewPath:me,previewOpenError:D,directionRefs:de,directionNames:ue,design_conversation_id:E,conversation_id:o,nextAction:[`The visual picker has been opened in the user's browser at file://${me??"(path missing)"} \u2014 every direction is a real, rendered landing page. The user is looking at it now.`,D?`(auto-open suppressed: ${D} \u2014 tell the user to open file://${me} manually)`:"",`Now use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names as options: ${ue.map(I=>`"${I}"`).join(", ")}. Do NOT invent extra options. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${o}", designConversationId: "${E}", designDirection: { id: "<map name \u2192 id from directionRefs>" } }. If the user types a custom description, pass designDirection: { custom: "<their exact words>" } and userConfirmedCustom: true.`].filter(Boolean).join(`
2053
+
2054
+ `)}))}return d(JSON.stringify(g))}catch(g){let f=g instanceof Error?g.message:String(g);return d(`Could not poll plan conversation '${o}': ${f}`,!0)}let V=r??"";if(!V.trim()&&!o&&!x&&!a&&!l&&!c)return d("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(x&&!y&&!V.trim()&&!s)return d(`You passed designConversationId='${x}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${x}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let Z=a;if(!Z&&l&&(Z=gc(l)??void 0,!Z))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let ae=o;if(!xe())return Ne("plan a new app");let L,H;if(!ae&&!Z&&!c&&!x){if(!tc(n))return d(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let g=lc(n);if(g!=="mistflow"&&cc(n))return d(JSON.stringify({status:"unsafe_cwd",projectPath:n,instruction:[`The projectPath you passed (${n}) is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Create the subfolder at ${n}/<subfolder-name>.`," 3. Call mist_plan again with the SAME description and projectPath set to the new subfolder.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description."].join(`
2055
+ `)}),!0);if(g==="foreign"){let f=N?ac(N,n,V):!1,k=pc(n,V),T=uc(V,h);if(T||f){H=k;let E=Io(H);if(E)return d(`Mistflow could not create the scaffold directory at ${H}: ${E}`,!0);L=`Note: Mistflow will scaffold the new app at \`${H}\`. The existing project at \`${n}\` is not modified.`}if(!f&&!T){let E=ic(n,V);if(e?.server){let B=await dn(e.server,[{question:"You're inside an existing project. Where should Mistflow scaffold the new app?",decisionKey:"scopeChoice",recommended:`Create at: ${k}`,why:"Mistflow creates a NEW app and never modifies the surrounding codebase. The default puts it in a subdirectory of the current path, named after your description. You can pick a custom path or cancel if you actually want to edit the existing project instead.",options:[{label:`Create at: ${k}`,description:"Default \u2014 uses your description as the folder name."},{label:"Choose a different path",description:"Type a custom absolute path in the textbox below."},{label:"Cancel \u2014 I wanted to edit the existing project",description:"Stop Mistflow. Handle the request by editing files in the current project instead."}]}],`## Existing project detected
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: \`${k}\``,"scope");if(B.outcome==="submitted"){let se=B.answers?.[0]?.answer??"",ie=se.toLowerCase(),me=se.startsWith("/")?se:null;if(me||ie.startsWith("create at:")||ie.startsWith("choose a different path")){let O=me||(ie.startsWith("choose a different path")?null:k);if(!O)return d("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);H=O;let G=Io(H);if(G)return d(`Mistflow could not create the scaffold directory at ${H}: ${G}`,!0);L=`Note: Mistflow will scaffold the new app at \`${H}\`. The existing project at \`${n}\` is not modified.`}else return ie.startsWith("cancel")?d("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):d(`User submitted an unrecognized scope choice: ${se}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return B.outcome==="declined"?d("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):d(Po({projectPath:n,description:V,confirmToken:E,suggestedPath:k,previousTokenInvalid:!!D}))}else return d(Po({projectPath:n,description:V,confirmToken:E,suggestedPath:k,previousTokenInvalid:!!D}))}}}if(c)try{if(!(await $r(c)).plan)return d("This template has no plan to fork. Try a different template.",!0);let f=await Ur(c),k=f.plan,T="";if(m&&f.has_source)try{let G=await Dn(f.plan,m),we=G.plan??G,oe=G.diff,fe=we?.steps??[],de=new Set([...(oe?.added??[]).map(be=>be.number),...(oe?.modified??[]).map(be=>be.number)]),ue=fe.map(be=>{let b=be.number;return de.has(b)?{...be,status:"pending"}:{...be,status:"completed",source:"forked"}});we.steps=ue,k=we;let I=ue.filter(be=>be.status==="pending").length;T=` Remixed: ${ue.filter(be=>be.status==="completed").length} steps unchanged, ${I} steps need re-implementation.`}catch(G){console.error("[plan] Remix failed, using original plan:",G),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let E=To(),B=he(ut(),".mistflow","plans");Tt(B,{recursive:!0}),pt(he(B,`${E}.json`),JSON.stringify({plan:k,projectId:f.id,sourceDeploymentId:f.source_deployment_id,forkToken:f.fork_token,requiredEnvVars:f.required_env_vars,dbProvider:f.db_provider}));let se=k?.name??"forked-app",ie=f.has_source,me=ie?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",O=f.deploy_url?` Instant deploy started \u2014 your app will be live at ${f.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:E,forkedFrom:f.forked_from,projectId:f.id,hasSource:ie,deployUrl:f.deploy_url,message:`Forked "${f.forked_from}" into your workspace.${T}${O} ${me} NEXT: Call mist_init, name='${se}', and planId='${E}' to create the project now.`}))}catch(h){let f=h instanceof Error?h.message:"Failed to fork template";return d(f,!0)}if(Z){let h;if(n){let O=he(n,"PLAN.md");if(et(O))try{h=un(O,"utf-8")}catch(G){console.error(`[mist_plan:modify] PLAN.md read failed (${O}): ${G instanceof Error?G.message:String(G)}`)}}let f;try{f=await Dn(Z,V,{planMd:h})}catch(O){let G=O instanceof Error?O.message:"Failed to modify plan";return d(G,!0)}let k=f.plan,T=f.diff,E=typeof f.plan_md=="string"?f.plan_md:null,B,se;if(E&&n)try{let O=he(n,"PLAN.md");pt(O,E,"utf-8"),B=O}catch(O){se=O instanceof Error?O.message:String(O)}let ie=[];if(T?.added?.length){let O=T.added.map(G=>G.title);ie.push(`Added ${O.length} step(s): ${O.join(", ")}`)}if(T?.removed?.length){let O=T.removed.map(G=>G.title);ie.push(`Removed ${O.length} step(s): ${O.join(", ")}`)}if(T?.modified?.length){let O=T.modified.map(G=>G.title);ie.push(`Modified ${O.length} step(s): ${O.join(", ")}`)}let me=ie.length>0?ie.join(". "):"No changes detected.";return d(JSON.stringify({plan:k,diff:T,planMdPath:B,planMdError:se,message:`Plan modified. ${me}. Update mistflow.json with the new plan${B?"; PLAN.md has been regenerated at "+B:""}, then continue with mist_implement.`}))}let A=_?.trim()||void 0,X=s;if(Array.isArray(s)){let h=s.findIndex(f=>f&&typeof f=="object"&&f.decisionKey==="urlChoice");if(h>=0){let f=s[h];!A&&f.answer&&(A=f.answer);let k=s.slice(0,h).concat(s.slice(h+1));X=k.length>0?k:void 0}}else if(s!=null){let h=s;if(!A&&Vn in h&&(A=h[Vn]),!A&&"urlChoice"in h&&(A=h.urlChoice),Vn in h||"urlChoice"in h){let{[Vn]:f,urlChoice:k,...T}=h;X=Object.keys(T).length>0?T:void 0}}if(A&&(A=A.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),A){let h=A.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(h)?A=h:(console.error(`[mist_plan] Discarding urlChoice '${A}' \u2014 does not look like a subdomain. Backend will auto-generate.`),A=void 0)}let K;if(y){K={...y},delete K.userConfirmedCustom,delete K.user_confirmed_custom;let h={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[f,k]of Object.entries(h))y[f]!==void 0&&K[k]===void 0&&(K[k]=y[f])}let W=K!==void 0&&typeof K.custom=="string"&&!K.id&&!K.name,R=P===!0||y!==void 0&&(y.userConfirmedCustom===!0||y.user_confirmed_custom===!0);if(W&&x)try{let h=await An(x);if(h.status==="pending")return d(`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: '${x}' } 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(h.status==="ready"&&Array.isArray(h.directions)&&h.directions.length>0&&!R){let f=h.directions.map(k=>k.name).join(", ");return d(`Refusing to submit a custom design direction: the backend has ${h.directions.length} real directions ready (${f}). 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: '${x}' } 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 ${h.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(h){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${h instanceof Error?h.message:String(h)}`)}let S=s?"Generating plan with your answers (LLM call)":x?"Finalizing design direction":"Thinking through discovery questions",M=e?ze(e.server,e.progressToken,()=>S):{stop:()=>{}};if(e&&(e.cleanup=()=>M.stop()),!i&&!o&&!x&&!a&&!l&&!c&&!D&&V.trim().length>0&&!z)try{let h=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),f=336*60*60*1e3,k=Date.now()-f,E=(await rn(So())).filter(B=>!h.has(B.state)).filter(B=>{let se=Date.parse(B.updated_at);return Number.isFinite(se)&&se>=k}).sort((B,se)=>Date.parse(se.updated_at)-Date.parse(B.updated_at)).slice(0,5);if(E.length>0)return M.stop(),d(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:E.map(B=>({sessionId:B.id,state:B.state,description:B.description,currentStep:B.current_step,awaitingInput:B.awaiting_input,updatedAt:B.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(h){console.error("resume-offer check failed (falling through to bootstrap):",h instanceof Error?h.message:h)}let te=i,C;try{ae&&!X&&!x&&!Z&&!l?C=await Nn(ae):C=await On(V,{conversationId:ae,answers:X,autonomous:p,language:u,designConversationId:x,designDirection:K})}catch(h){M.stop();let f=h instanceof Error?h.message:"Failed to generate plan";return d(f,!0)}let ve=C.session_id;if(!te&&ve){te=ve;try{await nn(ve,{machine_id:So(),local_path:n})}catch(h){console.error("workspace bind failed (resume offers will miss this session):",h instanceof Error?h.message:h)}}if(C.status==="clarify_pending"){M.stop();let h=C;return d(JSON.stringify({status:"running",conversationId:h.conversation_id,sessionId:te,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${h.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.${te?` Carry sessionId="${te}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(C.status==="plan_pending"){M.stop();let h=C;return d(JSON.stringify({status:"running",conversationId:h.conversation_id,sessionId:te,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${h.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(C.status==="design_clarify_pending"&&(S="Generating creative design directions",C=await fc(C)),C.status==="design_clarify_pending")return M.stop(),d(JSON.stringify({status:"running",conversationId:o,designConversationId:C.design_conversation_id,sessionId:te,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(M.stop(),C.status==="clarify"){let h=C.reflection||"",f=C.suggestedName||"",k=C.suggestedFeatures??[],T=C.questions??[],E=T.some(oe=>Array.isArray(oe.options)&&typeof oe.options[0]=="object"&&oe.options[0]?.label),B={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(oe=>{let fe=oe.decisionKey&&B[oe.decisionKey]||hc(oe.question),de;return E&&Array.isArray(oe.options)?de=oe.options.map(ue=>({label:ue.label,description:ue.description??""})):Array.isArray(oe.options)?de=oe.options.map((ue,I)=>({label:I===0?`${ue} (Recommended)`:String(ue),description:oe.why??""})):de=[{label:"Yes (Recommended)",description:oe.why??""},{label:"No",description:""}],{question:oe.question,header:fe,options:de,multiSelect:!1}}),me=C.decisions?.audienceType??null,O=k.length>0?ko(V,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:me,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:f,suggestedFeatures:k,language:u}):null,G=O?xo(O):"",we=Wn(f||"my-app").slice(0,32);try{let oe=await Cn(we);!oe.available&&oe.suggestion&&(we=oe.suggestion)}catch{}if(G&&(G+=`
2059
+ Default path: \`${k}\``,"scope");if(B.outcome==="submitted"){let se=B.answers?.[0]?.answer??"",ie=se.toLowerCase(),me=se.startsWith("/")?se:null;if(me||ie.startsWith("create at:")||ie.startsWith("choose a different path")){let D=me||(ie.startsWith("choose a different path")?null:k);if(!D)return d("User picked 'Choose a different path' but didn't type one in the textbox. Ask them what path they want, then re-run mist_plan with projectPath set to that path.",!0);H=D;let G=Io(H);if(G)return d(`Mistflow could not create the scaffold directory at ${H}: ${G}`,!0);L=`Note: Mistflow will scaffold the new app at \`${H}\`. The existing project at \`${n}\` is not modified.`}else return ie.startsWith("cancel")?d("User chose to cancel \u2014 they wanted to edit the existing project, not create a new one. Do NOT call mist_plan again. Handle the request by editing files in the current project.",!0):d(`User submitted an unrecognized scope choice: ${se}. Ask them whether to scaffold a new Mistflow app or edit the existing codebase before retrying.`,!0)}else return B.outcome==="declined"?d("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):d(Po({projectPath:n,description:V,confirmToken:E,suggestedPath:k,previousTokenInvalid:!!N}))}else return d(Po({projectPath:n,description:V,confirmToken:E,suggestedPath:k,previousTokenInvalid:!!N}))}}}if(c)try{if(!(await $r(c)).plan)return d("This template has no plan to fork. Try a different template.",!0);let f=await Ur(c),k=f.plan,T="";if(m&&f.has_source)try{let G=await Mn(f.plan,m),we=G.plan??G,oe=G.diff,fe=we?.steps??[],de=new Set([...(oe?.added??[]).map(be=>be.number),...(oe?.modified??[]).map(be=>be.number)]),ue=fe.map(be=>{let b=be.number;return de.has(b)?{...be,status:"pending"}:{...be,status:"completed",source:"forked"}});we.steps=ue,k=we;let I=ue.filter(be=>be.status==="pending").length;T=` Remixed: ${ue.filter(be=>be.status==="completed").length} steps unchanged, ${I} steps need re-implementation.`}catch(G){console.error("[plan] Remix failed, using original plan:",G),T=" (Remix failed \u2014 using original plan. You can modify it later.)"}let E=To(),B=he(ut(),".mistflow","plans");Tt(B,{recursive:!0}),pt(he(B,`${E}.json`),JSON.stringify({plan:k,projectId:f.id,sourceDeploymentId:f.source_deployment_id,forkToken:f.fork_token,requiredEnvVars:f.required_env_vars,dbProvider:f.db_provider}));let se=k?.name??"forked-app",ie=f.has_source,me=ie?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",D=f.deploy_url?` Instant deploy started \u2014 your app will be live at ${f.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:E,forkedFrom:f.forked_from,projectId:f.id,hasSource:ie,deployUrl:f.deploy_url,message:`Forked "${f.forked_from}" into your workspace.${T}${D} ${me} NEXT: Call mist_init, name='${se}', and planId='${E}' to create the project now.`}))}catch(g){let f=g instanceof Error?g.message:"Failed to fork template";return d(f,!0)}if(Z){let g;if(n){let D=he(n,"PLAN.md");if(et(D))try{g=un(D,"utf-8")}catch(G){console.error(`[mist_plan:modify] PLAN.md read failed (${D}): ${G instanceof Error?G.message:String(G)}`)}}let f;try{f=await Mn(Z,V,{planMd:g})}catch(D){let G=D instanceof Error?D.message:"Failed to modify plan";return d(G,!0)}let k=f.plan,T=f.diff,E=typeof f.plan_md=="string"?f.plan_md:null,B,se;if(E&&n)try{let D=he(n,"PLAN.md");pt(D,E,"utf-8"),B=D}catch(D){se=D instanceof Error?D.message:String(D)}let ie=[];if(T?.added?.length){let D=T.added.map(G=>G.title);ie.push(`Added ${D.length} step(s): ${D.join(", ")}`)}if(T?.removed?.length){let D=T.removed.map(G=>G.title);ie.push(`Removed ${D.length} step(s): ${D.join(", ")}`)}if(T?.modified?.length){let D=T.modified.map(G=>G.title);ie.push(`Modified ${D.length} step(s): ${D.join(", ")}`)}let me=ie.length>0?ie.join(". "):"No changes detected.";return d(JSON.stringify({plan:k,diff:T,planMdPath:B,planMdError:se,message:`Plan modified. ${me}. Update mistflow.json with the new plan${B?"; PLAN.md has been regenerated at "+B:""}, then continue with mist_implement.`}))}let A=_?.trim()||void 0,X=s;if(Array.isArray(s)){let g=s.findIndex(f=>f&&typeof f=="object"&&f.decisionKey==="urlChoice");if(g>=0){let f=s[g];!A&&f.answer&&(A=f.answer);let k=s.slice(0,g).concat(s.slice(g+1));X=k.length>0?k:void 0}}else if(s!=null){let g=s;if(!A&&Jn in g&&(A=g[Jn]),!A&&"urlChoice"in g&&(A=g.urlChoice),Jn in g||"urlChoice"in g){let{[Jn]:f,urlChoice:k,...T}=g;X=Object.keys(T).length>0?T:void 0}}if(A&&(A=A.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),A){let g=A.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(g)?A=g:(console.error(`[mist_plan] Discarding urlChoice '${A}' \u2014 does not look like a subdomain. Backend will auto-generate.`),A=void 0)}let K;if(y){K={...y},delete K.userConfirmedCustom,delete K.user_confirmed_custom;let g={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[f,k]of Object.entries(g))y[f]!==void 0&&K[k]===void 0&&(K[k]=y[f])}let W=K!==void 0&&typeof K.custom=="string"&&!K.id&&!K.name,R=P===!0||y!==void 0&&(y.userConfirmedCustom===!0||y.user_confirmed_custom===!0);if(W&&x)try{let g=await En(x);if(g.status==="pending")return d(`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: '${x}' } 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(g.status==="ready"&&Array.isArray(g.directions)&&g.directions.length>0&&!R){let f=g.directions.map(k=>k.name).join(", ");return d(`Refusing to submit a custom design direction: the backend has ${g.directions.length} real directions ready (${f}). 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: '${x}' } 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 ${g.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(g){console.error(`[plan] custom-direction guard fetchDesignDirections failed (allowing submit): ${g instanceof Error?g.message:String(g)}`)}let S=s?"Generating plan with your answers (LLM call)":x?"Finalizing design direction":"Thinking through discovery questions",M=e?ze(e.server,e.progressToken,()=>S):{stop:()=>{}};if(e&&(e.cleanup=()=>M.stop()),!i&&!o&&!x&&!a&&!l&&!c&&!N&&V.trim().length>0&&!z)try{let g=new Set(["COMPLETED","CANCELLED","FAILED","DONE"]),f=336*60*60*1e3,k=Date.now()-f,E=(await rn(So())).filter(B=>!g.has(B.state)).filter(B=>{let se=Date.parse(B.updated_at);return Number.isFinite(se)&&se>=k}).sort((B,se)=>Date.parse(se.updated_at)-Date.parse(B.updated_at)).slice(0,5);if(E.length>0)return M.stop(),d(JSON.stringify({status:"resume_offer",requires_user_input:!0,candidates:E.map(B=>({sessionId:B.id,state:B.state,description:B.description,currentStep:B.current_step,awaitingInput:B.awaiting_input,updatedAt:B.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(g){console.error("resume-offer check failed (falling through to bootstrap):",g instanceof Error?g.message:g)}let te=i,C;try{ae&&!X&&!x&&!Z&&!l?C=await Dn(ae):C=await jn(V,{conversationId:ae,answers:X,autonomous:p,language:u,designConversationId:x,designDirection:K})}catch(g){M.stop();let f=g instanceof Error?g.message:"Failed to generate plan";return d(f,!0)}let ve=C.session_id;if(!te&&ve){te=ve;try{await nn(ve,{machine_id:So(),local_path:n})}catch(g){console.error("workspace bind failed (resume offers will miss this session):",g instanceof Error?g.message:g)}}if(C.status==="clarify_pending"){M.stop();let g=C;return d(JSON.stringify({status:"running",conversationId:g.conversation_id,sessionId:te,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${g.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.${te?` Carry sessionId="${te}" forward on every subsequent mist_* call so backend state guards apply.`:""}`}))}if(C.status==="plan_pending"){M.stop();let g=C;return d(JSON.stringify({status:"running",conversationId:g.conversation_id,sessionId:te,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${g.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(C.status==="design_clarify_pending"&&(S="Generating creative design directions",C=await fc(C)),C.status==="design_clarify_pending")return M.stop(),d(JSON.stringify({status:"running",conversationId:o,designConversationId:C.design_conversation_id,sessionId:te,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(M.stop(),C.status==="clarify"){let g=C.reflection||"",f=C.suggestedName||"",k=C.suggestedFeatures??[],T=C.questions??[],E=T.some(oe=>Array.isArray(oe.options)&&typeof oe.options[0]=="object"&&oe.options[0]?.label),B={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(oe=>{let fe=oe.decisionKey&&B[oe.decisionKey]||hc(oe.question),de;return E&&Array.isArray(oe.options)?de=oe.options.map(ue=>({label:ue.label,description:ue.description??""})):Array.isArray(oe.options)?de=oe.options.map((ue,I)=>({label:I===0?`${ue} (Recommended)`:String(ue),description:oe.why??""})):de=[{label:"Yes (Recommended)",description:oe.why??""},{label:"No",description:""}],{question:oe.question,header:fe,options:de,multiSelect:!1}}),me=C.decisions?.audienceType??null,D=k.length>0?ko(V,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:me,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:f,suggestedFeatures:k,language:u}):null,G=D?xo(D):"",we=Vn(f||"my-app").slice(0,32);try{let oe=await Rn(we);!oe.available&&oe.suggestion&&(we=oe.suggestion)}catch{}if(G&&(G+=`
2060
2060
 
2061
2061
  **Your app URL (you can change this before scaffolding):** https://${we}.mistflow.app`),e?.server){let oe=[f?`## ${f}`:"## 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
- `),fe=await dn(e.server,T,oe,"clarify");if(fe.outcome==="submitted"){M.stop();let de={};for(let I of fe.answers??[])I.decisionKey?de[I.decisionKey]=I.answer:de[I.question]=I.answer;let ue=fe.urlChoice?.trim();ue&&(ue=ue.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let I=await On(V,{conversationId:C.conversation_id,answers:de,autonomous:p,language:u});if(I.status==="plan_pending"){let Te=I;return d(JSON.stringify({status:"running",conversationId:Te.conversation_id,phase:"generating_plan",...ue?{urlChoice:ue}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${Te.conversation_id}"${ue?`, urlChoice: "${ue}"`:""} } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll up to ~10s and returns when the plan lands. Pass urlChoice on every poll so it threads through to the saved plan.`}))}C=I}catch(I){let Te=I instanceof Error?I.message:String(I);return d(`Submitting your answers failed: ${Te}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(fe.outcome==="declined")return M.stop(),d("User declined the planning flow via the form. They likely want a different approach \u2014 ask them what they'd prefer instead of re-running mist_plan.",!0);if(fe.outcome==="cancelled")return M.stop(),d("User cancelled the planning form without picking. The conversation is still alive \u2014 re-run mist_plan with the same conversationId if they want to retry, or start a fresh plan if they want to change the description.",!0);fe.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${fe.errorMessage}) \u2014 falling back to prose flow.`)}}return d(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:C.conversation_id,questions:T,questionCount:T.length,suggestedFeatures:k,suggestedName:f,suggestedSubdomain:we,reflection:h,briefText:G,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: "${C.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${we}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.',...h||G?["","\u2500\u2500\u2500 BACKGROUND (not for you to summarize and proceed \u2014 it's what the user will see when you show them the questions) \u2500\u2500\u2500",...h?[h]:[],...G?["",G]:[]]:[],...L?["",L]:[]].join(`
2063
- `)}))}if(C.status==="design_clarify"){let h=C.directions??[],f=C.plan.name??"your app",k=C.design_conversation_id,T=h.map(w=>({id:w.id,name:w.name,summary:w.summary,hero_headline:w.hero_headline,cta_text:w.cta_text,body_sample:w.body_sample,fonts:w.fonts,colors:w.colors,hero_treatment:w.hero_treatment,shape_lang:w.shape_lang,texture:w.texture,decoration_hint:w.decoration_hint})),E={},B=!1;try{if(k){let ne=Date.now();for(;Date.now()-ne<5e4;){let Le=await En(k),Y=0;for(let Q of T){let v=Le[Q.id];v&&((v.status==="done"||v.status==="ready")&&typeof v.html=="string"&&v.html.length>0?(E[Q.id]=v.html,Y+=1):v.status==="failed"&&(Y+=1))}if(Y===T.length){B=!0;break}await new Promise(Q=>setTimeout(Q,5e3))}}}catch(w){console.error(`[mist_plan:design_clarify] render poll failed: ${w instanceof Error?w.message:String(w)}`)}if(!B)return d(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:C.conversation_id??o,design_conversation_id:k,renderedSoFar:Object.keys(E).length,totalDirections:T.length,nextAction:`${Object.keys(E).length}/${T.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${C.conversation_id??o??""}" } again IMMEDIATELY \u2014 do NOT bash sleep. Do NOT ask the user about design yet.`}));let se=T.filter(w=>E[w.id]),ie,me,O=he(n,".mistflow"),G=he(O,"design-directions.html"),we=he(O,"picker-state.json"),oe=()=>{try{if(et(we))return JSON.parse(un(we,"utf-8"))}catch{}return{}},fe=w=>{try{Tt(O,{recursive:!0}),pt(we,JSON.stringify(w,null,2),"utf-8")}catch(F){console.error(`[mist_plan:design_clarify] sidecar write failed: ${F instanceof Error?F.message:String(F)}`)}},de=oe(),ue=k&&de.opened_for_design_cid===k;try{if(Tt(O,{recursive:!0}),ue)ie=G;else{let w=es(f,se,E);pt(G,w,"utf-8"),ie=G;let F=Zr(`file://${G}`);F.opened||(me=F.reason),k&&fe({opened_for_design_cid:k,elicit_state:"pending",elicit_design_cid:k,opened_at:new Date().toISOString()})}}catch(w){console.error(`[mist_plan:design_clarify] picker write/open failed: ${w instanceof Error?w.message:String(w)}`)}let I=oe(),Te=se.map(w=>({id:w.id,name:w.name})),be=Te.map(w=>w.name).filter(Boolean);if(e?.server&&k&&I.elicit_design_cid===k&&I.elicit_state==="pending"){let w=ie?[`## ${f} \u2014 pick a creative direction`,"",`${se.length} directions, each with its own fonts, colors, and mood.`,"",`Visual preview (auto-opened in your browser): file://${ie}`,"Each card shows what you'd be picking \u2014 fonts, colors, hero layout."].join(`
2062
+ `),fe=await dn(e.server,T,oe,"clarify");if(fe.outcome==="submitted"){M.stop();let de={};for(let I of fe.answers??[])I.decisionKey?de[I.decisionKey]=I.answer:de[I.question]=I.answer;let ue=fe.urlChoice?.trim();ue&&(ue=ue.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0);try{let I=await jn(V,{conversationId:C.conversation_id,answers:de,autonomous:p,language:u});if(I.status==="plan_pending"){let Te=I;return d(JSON.stringify({status:"running",conversationId:Te.conversation_id,phase:"generating_plan",...ue?{urlChoice:ue}:{},nextAction:`User answered via the native form. Plan is generating now (30-60s typical). Call mist_plan with { projectPath, conversationId: "${Te.conversation_id}"${ue?`, urlChoice: "${ue}"`:""} } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll up to ~10s and returns when the plan lands. Pass urlChoice on every poll so it threads through to the saved plan.`}))}C=I}catch(I){let Te=I instanceof Error?I.message:String(I);return d(`Submitting your answers failed: ${Te}. Please retry by calling mist_plan with the same conversationId and answers.`,!0)}}else{if(fe.outcome==="declined")return M.stop(),d("User declined the planning flow via the form. They likely want a different approach \u2014 ask them what they'd prefer instead of re-running mist_plan.",!0);if(fe.outcome==="cancelled")return M.stop(),d("User cancelled the planning form without picking. The conversation is still alive \u2014 re-run mist_plan with the same conversationId if they want to retry, or start a fresh plan if they want to change the description.",!0);fe.outcome==="error"&&console.error(`[mist_plan] Elicitation failed (${fe.errorMessage}) \u2014 falling back to prose flow.`)}}return d(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:C.conversation_id,questions:T,questionCount:T.length,suggestedFeatures:k,suggestedName:f,suggestedSubdomain:we,reflection:g,briefText:G,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: "${C.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${we}".`,'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.',...g||G?["","\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",...g?[g]:[],...G?["",G]:[]]:[],...L?["",L]:[]].join(`
2063
+ `)}))}if(C.status==="design_clarify"){let g=C.directions??[],f=C.plan.name??"your app",k=C.design_conversation_id,T=g.map(w=>({id:w.id,name:w.name,summary:w.summary,hero_headline:w.hero_headline,cta_text:w.cta_text,body_sample:w.body_sample,fonts:w.fonts,colors:w.colors,hero_treatment:w.hero_treatment,shape_lang:w.shape_lang,texture:w.texture,decoration_hint:w.decoration_hint})),E={},B=!1;try{if(k){let ne=Date.now();for(;Date.now()-ne<5e4;){let Le=await On(k),Y=0;for(let Q of T){let v=Le[Q.id];v&&((v.status==="done"||v.status==="ready")&&typeof v.html=="string"&&v.html.length>0?(E[Q.id]=v.html,Y+=1):v.status==="failed"&&(Y+=1))}if(Y===T.length){B=!0;break}await new Promise(Q=>setTimeout(Q,5e3))}}}catch(w){console.error(`[mist_plan:design_clarify] render poll failed: ${w instanceof Error?w.message:String(w)}`)}if(!B)return d(JSON.stringify({status:"running",phase:"rendering_directions",conversation_id:C.conversation_id??o,design_conversation_id:k,renderedSoFar:Object.keys(E).length,totalDirections:T.length,nextAction:`${Object.keys(E).length}/${T.length} direction renders ready. Tell the user "still generating design previews" briefly, then call mist_plan with { projectPath, conversationId: "${C.conversation_id??o??""}" } again IMMEDIATELY \u2014 do NOT bash sleep. Do NOT ask the user about design yet.`}));let se=T.filter(w=>E[w.id]),ie,me,D=he(n,".mistflow"),G=he(D,"design-directions.html"),we=he(D,"picker-state.json"),oe=()=>{try{if(et(we))return JSON.parse(un(we,"utf-8"))}catch{}return{}},fe=w=>{try{Tt(D,{recursive:!0}),pt(we,JSON.stringify(w,null,2),"utf-8")}catch(F){console.error(`[mist_plan:design_clarify] sidecar write failed: ${F instanceof Error?F.message:String(F)}`)}},de=oe(),ue=k&&de.opened_for_design_cid===k;try{if(Tt(D,{recursive:!0}),ue)ie=G;else{let w=es(f,se,E);pt(G,w,"utf-8"),ie=G;let F=Zr(`file://${G}`);F.opened||(me=F.reason),k&&fe({opened_for_design_cid:k,elicit_state:"pending",elicit_design_cid:k,opened_at:new Date().toISOString()})}}catch(w){console.error(`[mist_plan:design_clarify] picker write/open failed: ${w instanceof Error?w.message:String(w)}`)}let I=oe(),Te=se.map(w=>({id:w.id,name:w.name})),be=Te.map(w=>w.name).filter(Boolean);if(e?.server&&k&&I.elicit_design_cid===k&&I.elicit_state==="pending"){let w=ie?[`## ${f} \u2014 pick a creative direction`,"",`${se.length} directions, each with its own fonts, colors, and mood.`,"",`Visual preview (auto-opened in your browser): file://${ie}`,"Each card shows what you'd be picking \u2014 fonts, colors, hero layout."].join(`
2064
2064
  `):`## ${f} \u2014 pick a creative direction
2065
2065
 
2066
- ${se.length} directions, each with its own fonts, colors, and mood. Pick one or describe your own.`,F=se.map(ne=>({label:ne.name,description:ne.summary??""}));F.push({label:"Describe your own direction",description:"Skip the proposed options and type a short description of how the app should feel."});try{let ne=await dn(e.server,[{question:`${f} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,decisionKey:"designDirection",options:F,noOtherSentinel:!0,otherFieldTitle:"If 'Describe your own direction' was picked: type how the app should feel (fonts, colors, mood \u2014 your words)."}],w,"design");if(ne.outcome==="submitted"&&ne.answers?.[0]){let Le=ne.answers[0].answer.trim(),Y=se.find(v=>v.name===Le),Q=Y?{direction_id:Y.id}:{custom:Le};(C.conversation_id??o)&&(Q.conversation_id=C.conversation_id??o);try{let v=await Rn(k,Q);fe({...I,elicit_state:"completed",elicit_design_cid:k}),C={status:"ready",plan:v.plan??{},methodology:v.methodology??"",...v.designMd?{designMd:v.designMd}:{}}}catch(v){return console.error(`[mist_plan:design_clarify] submitDesignPick failed: ${v instanceof Error?v.message:String(v)}`),fe({...I,elicit_state:"skipped"}),d(`Design submission failed: ${v instanceof Error?v.message:String(v)}. Ask the user to retry by re-running mist_plan with their pick.`,!0)}}else return fe({...I,elicit_state:"skipped"}),d(JSON.stringify({status:"design_clarify",previewPath:ie,previewOpenError:me,directionRefs:Te,directionNames:be,design_conversation_id:k,conversation_id:C.conversation_id??o,nextAction:[`The user closed the elicit picker without picking. The visual picker is still open at file://${ie??"(path missing)"}.`,`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask which direction they pick. List EXACTLY these names: ${be.map(Le=>`"${Le}"`).join(", ")}.`,`When they pick, call mist_plan with { projectPath, conversationId: "${C.conversation_id??o??""}", designConversationId: "${k??""}", designDirection: { id: "<id from directionRefs>" } }.`].join(`
2066
+ ${se.length} directions, each with its own fonts, colors, and mood. Pick one or describe your own.`,F=se.map(ne=>({label:ne.name,description:ne.summary??""}));F.push({label:"Describe your own direction",description:"Skip the proposed options and type a short description of how the app should feel."});try{let ne=await dn(e.server,[{question:`${f} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,decisionKey:"designDirection",options:F,noOtherSentinel:!0,otherFieldTitle:"If 'Describe your own direction' was picked: type how the app should feel (fonts, colors, mood \u2014 your words)."}],w,"design");if(ne.outcome==="submitted"&&ne.answers?.[0]){let Le=ne.answers[0].answer.trim(),Y=se.find(v=>v.name===Le),Q=Y?{direction_id:Y.id}:{custom:Le};(C.conversation_id??o)&&(Q.conversation_id=C.conversation_id??o);try{let v=await Nn(k,Q);fe({...I,elicit_state:"completed",elicit_design_cid:k}),C={status:"ready",plan:v.plan??{},methodology:v.methodology??"",...v.designMd?{designMd:v.designMd}:{}}}catch(v){return console.error(`[mist_plan:design_clarify] submitDesignPick failed: ${v instanceof Error?v.message:String(v)}`),fe({...I,elicit_state:"skipped"}),d(`Design submission failed: ${v instanceof Error?v.message:String(v)}. Ask the user to retry by re-running mist_plan with their pick.`,!0)}}else return fe({...I,elicit_state:"skipped"}),d(JSON.stringify({status:"design_clarify",previewPath:ie,previewOpenError:me,directionRefs:Te,directionNames:be,design_conversation_id:k,conversation_id:C.conversation_id??o,nextAction:[`The user closed the elicit picker without picking. The visual picker is still open at file://${ie??"(path missing)"}.`,`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask which direction they pick. List EXACTLY these names: ${be.map(Le=>`"${Le}"`).join(", ")}.`,`When they pick, call mist_plan with { projectPath, conversationId: "${C.conversation_id??o??""}", designConversationId: "${k??""}", designDirection: { id: "<id from directionRefs>" } }.`].join(`
2067
2067
 
2068
2068
  `)}))}catch(ne){console.error(`[mist_plan:design_clarify] elicit failed: ${ne instanceof Error?ne.message:String(ne)}`),fe({...I,elicit_state:"skipped"})}}if(C.status==="design_clarify")return d(JSON.stringify({status:"design_clarify",previewPath:ie,previewOpenError:me,directionRefs:Te,directionNames:be,design_conversation_id:k,conversation_id:C.conversation_id??o,nextAction:[`The visual picker is open in the user's browser at file://${ie??"(path missing)"} \u2014 every direction is a real, rendered landing page.`,me?`(auto-open suppressed: ${me} \u2014 tell the user to open file://${ie} manually)`:"",`Use your host's structured-question UI (AskUserQuestion in Claude Code) to ask the user which direction they pick. List EXACTLY these names: ${be.map(w=>`"${w}"`).join(", ")}. Add a "Type something" option for custom descriptions.`,`When the user picks a name, call mist_plan with { projectPath, conversationId: "${C.conversation_id??o??""}", designConversationId: "${k??""}", designDirection: { id: "<map name \u2192 id from directionRefs>" } }. If they describe their own, pass designDirection: { custom: "<their exact words>" } and userConfirmedCustom: true.`].filter(Boolean).join(`
2069
2069
 
2070
- `)}))}if(C.status!=="ready")return d(`Unexpected plan status after build: ${C.status}. Please retry by calling mist_plan with the same conversationId.`,!0);let $=C.plan,ge=$.name??"Untitled App",Ce=C.methodology,re=$.steps;if(!Array.isArray(re)||re.length===0)return d("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let ye=$.suggestedSubdomain??Wn(ge).slice(0,32)??"my-app";if(!A&&e?.server){try{let f=await Cn(ye);!f.available&&f.suggestion&&(ye=f.suggestion)}catch{}let h=await dn(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"}],`## ${ge} \u2014 pick the URL
2070
+ `)}))}if(C.status!=="ready")return d(`Unexpected plan status after build: ${C.status}. Please retry by calling mist_plan with the same conversationId.`,!0);let $=C.plan,ge=$.name??"Untitled App",Ce=C.methodology,re=$.steps;if(!Array.isArray(re)||re.length===0)return d("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let ye=$.suggestedSubdomain??Vn(ge).slice(0,32)??"my-app";if(!A&&e?.server){try{let f=await Rn(ye);!f.available&&f.suggestion&&(ye=f.suggestion)}catch{}let g=await dn(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"}],`## ${ge} \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(h.outcome==="submitted"){let f=h.urlChoice?.trim()||h.answers?.[0]?.answer.trim()||"";f=f.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(f)||!f)&&(f=ye);let k=f.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(k)?A=k:(console.error(`[mist_plan] URL elicitation returned '${f}' \u2014 does not look like a subdomain. Using default '${ye}'.`),A=ye)}else h.outcome==="declined"||h.outcome,A=ye}else A||(A=ye);let je=$.publicPages;if(!je||Array.isArray(je)&&je.length===0){let h=$.pages,f=re.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),k=Array.isArray(h)&&h.some(T=>T.path==="/"||T.route==="/");f||k?je=["/","/pricing"]:je=["/"]}let rt=$.primaryAction;if(!rt){let h=$.features;if(Array.isArray(h)&&h.length>0){let k=h.find(E=>typeof E.priority=="string"&&E.priority.toLowerCase()==="must-have")??h[0];rt={entity:k.name??k.title??"item",action:"create",fromPage:"/dashboard"}}}let Ke=$.nonNegotiables;(!Ke||Array.isArray(Ke)&&Ke.length===0)&&(Ke=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Je=To(),st=he(ut(),".mistflow","plans");Tt(st,{recursive:!0});try{let f=Date.now();for(let k of[st,he(ut(),".mistflow","mockup-state")])if(et(k))for(let T of Ao(k))try{let E=he(k,T),B=Ro(E).mtimeMs;f-B>6048e5&&Zl(E)}catch{}}catch{}let Se=$,U={name:$.name,summary:$.summary,dataModel:$.dataModel,pages:$.pages,features:$.features,steps:re.map(h=>({...h,name:h.name??h.title})),design:$.design,dbProvider:$.dbProvider??"neon",authModel:$.authModel,audienceType:$.audienceType??"b2c",roles:$.roles,defaultRole:$.defaultRole,publicPages:je,navStyle:$.navStyle,multiTenant:$.multiTenant,primaryAction:rt,nonNegotiables:Ke,requestedSubdomain:A,...u&&u.toLowerCase()!=="english"?{language:u}:{},...Se.pickedDirection?{pickedDirection:Se.pickedDirection}:{},...Se.imageryBrief?{imageryBrief:Se.imageryBrief}:{},...Se.designConversationId?{designConversationId:Se.designConversationId}:{}};pt(he(st,`${Je}.json`),JSON.stringify({plan:U,methodology:Ce,...H?{scaffoldTargetPath:H}:{}}));let ce=re.map(h=>`${h.number}. ${h.name??h.title}`),ke,Me="";if(!!!Se.pickedDirection){let f=($.audienceType??"b2c")==="b2c";ke={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:f?"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:f?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},Me=" 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 Ue="",Ae=[];for(let h of re){let f=h.name??h.title,k=h.integrationId;if(k){let T=jt(k);if(T){let E=Mt(T.id);Ae.push({step:f,presetId:T.id,presetName:T.name,envVars:E?.envVars??[]})}}}if(Ae.length>0){let h=Ae.flatMap(T=>T.envVars),f=[...new Set(h.map(T=>T.key))];Ue=` This plan uses integrations (${Ae.map(T=>T.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${f.length>0?` The user will need these API keys: ${f.join(", ")}.`:""}`}return d(JSON.stringify({planId:Je,name:$.name,summary:$.summary,stepCount:re.length,steps:ce,design:$.design,...ke?{heroPhotoQuestion:ke}:{},...Ae.length>0?{integrations:Ae.map(h=>({step:h.step,preset:h.presetId,name:h.presetName,envVars:h.envVars}))}:{},message:`Plan generated for "${ge}" (${re.length} steps).${Ue}${Me}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,re.length*3)}\u2013${re.length*5} minutes total across ${re.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: '${Je}' }). If the user says skip or "just build it", call mist_init({ planId: '${Je}'${H?"":", path: '<absolute path>'"} }) immediately.`,...H?{scaffoldTargetPath:H}:{},...L?{warning:L}:{}}))}var Do={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:mc,handler:kc};import{z as qt}from"zod";import{existsSync as Oe,mkdirSync as Bt,rmSync as Dc,writeFileSync as tt,readFileSync as zt,readdirSync as Bo,copyFileSync as jc}from"fs";import{join as pe,resolve as zo,dirname as mn,isAbsolute as Mc}from"path";import{homedir as Lc}from"os";import{spawn as Rh}from"child_process";import{randomBytes as $c}from"crypto";import{simpleGit as Fc}from"simple-git";function xc(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=xc(t);return!e||e.major>=23?!0:e.major===22?e.minor>=12:e.major===20?e.minor>=19:!1}function Sc(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 _t(t=process.version,e=Sc()){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
- `)}var Kn="\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 Jn=`# Landing Page Rules
2072
+ The plan is ready. One last decision before I scaffold: what's the app's URL?`,"url");if(g.outcome==="submitted"){let f=g.urlChoice?.trim()||g.answers?.[0]?.answer.trim()||"";f=f.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim(),(/^type\b|\bdifferent\b/i.test(f)||!f)&&(f=ye);let k=f.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(k)?A=k:(console.error(`[mist_plan] URL elicitation returned '${f}' \u2014 does not look like a subdomain. Using default '${ye}'.`),A=ye)}else g.outcome==="declined"||g.outcome,A=ye}else A||(A=ye);let je=$.publicPages;if(!je||Array.isArray(je)&&je.length===0){let g=$.pages,f=re.some(T=>typeof T.name=="string"&&T.name.toLowerCase().includes("landing")||typeof T.title=="string"&&T.title.toLowerCase().includes("landing")),k=Array.isArray(g)&&g.some(T=>T.path==="/"||T.route==="/");f||k?je=["/","/pricing"]:je=["/"]}let rt=$.primaryAction;if(!rt){let g=$.features;if(Array.isArray(g)&&g.length>0){let k=g.find(E=>typeof E.priority=="string"&&E.priority.toLowerCase()==="must-have")??g[0];rt={entity:k.name??k.title??"item",action:"create",fromPage:"/dashboard"}}}let Ke=$.nonNegotiables;(!Ke||Array.isArray(Ke)&&Ke.length===0)&&(Ke=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Je=To(),st=he(ut(),".mistflow","plans");Tt(st,{recursive:!0});try{let f=Date.now();for(let k of[st,he(ut(),".mistflow","mockup-state")])if(et(k))for(let T of Ao(k))try{let E=he(k,T),B=Ro(E).mtimeMs;f-B>6048e5&&Zl(E)}catch{}}catch{}let Se=$,U={name:$.name,summary:$.summary,dataModel:$.dataModel,pages:$.pages,features:$.features,steps:re.map(g=>({...g,name:g.name??g.title})),design:$.design,dbProvider:$.dbProvider??"neon",authModel:$.authModel,audienceType:$.audienceType??"b2c",roles:$.roles,defaultRole:$.defaultRole,publicPages:je,navStyle:$.navStyle,multiTenant:$.multiTenant,primaryAction:rt,nonNegotiables:Ke,requestedSubdomain:A,...u&&u.toLowerCase()!=="english"?{language:u}:{},...Se.pickedDirection?{pickedDirection:Se.pickedDirection}:{},...Se.imageryBrief?{imageryBrief:Se.imageryBrief}:{},...Se.designConversationId?{designConversationId:Se.designConversationId}:{}};pt(he(st,`${Je}.json`),JSON.stringify({plan:U,methodology:Ce,...H?{scaffoldTargetPath:H}:{}}));let ce=re.map(g=>`${g.number}. ${g.name??g.title}`),ke,Me="";if(!!!Se.pickedDirection){let f=($.audienceType??"b2c")==="b2c";ke={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:f?"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:f?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},Me=" 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 Ue="",Ae=[];for(let g of re){let f=g.name??g.title,k=g.integrationId;if(k){let T=jt(k);if(T){let E=Mt(T.id);Ae.push({step:f,presetId:T.id,presetName:T.name,envVars:E?.envVars??[]})}}}if(Ae.length>0){let g=Ae.flatMap(T=>T.envVars),f=[...new Set(g.map(T=>T.key))];Ue=` This plan uses integrations (${Ae.map(T=>T.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${f.length>0?` The user will need these API keys: ${f.join(", ")}.`:""}`}return d(JSON.stringify({planId:Je,name:$.name,summary:$.summary,stepCount:re.length,steps:ce,design:$.design,...ke?{heroPhotoQuestion:ke}:{},...Ae.length>0?{integrations:Ae.map(g=>({step:g.step,preset:g.presetId,name:g.presetName,envVars:g.envVars}))}:{},message:`Plan generated for "${ge}" (${re.length} steps).${Ue}${Me}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,re.length*3)}\u2013${re.length*5} minutes total across ${re.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: '${Je}' }). If the user says skip or "just build it", call mist_init({ planId: '${Je}'${H?"":", path: '<absolute path>'"} }) immediately.`,...H?{scaffoldTargetPath:H}:{},...L?{warning:L}:{}}))}var Do={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:mc,handler:kc};import{z as qt}from"zod";import{existsSync as Oe,mkdirSync as Bt,rmSync as Dc,writeFileSync as tt,readFileSync as zt,readdirSync as Bo,copyFileSync as jc}from"fs";import{join as pe,resolve as zo,dirname as mn,isAbsolute as Mc}from"path";import{homedir as Lc}from"os";import{spawn as Nh}from"child_process";import{randomBytes as $c}from"crypto";import{simpleGit as Fc}from"simple-git";function xc(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=xc(t);return!e||e.major>=23?!0:e.major===22?e.minor>=12:e.major===20?e.minor>=19:!1}function Sc(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 _t(t=process.version,e=Sc()){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
+ `)}var Yn="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n";var Qn=`# Landing Page Rules
2075
2075
 
2076
2076
  These rules apply to every landing page. They are non-negotiable.
2077
2077
 
@@ -2513,17 +2513,17 @@ control plane.
2513
2513
  To change the plan (new feature, missed requirement, scope shift),
2514
2514
  call \`mist_plan\` with \`modify: true\` and a description. The backend
2515
2515
  generates a new plan revision and regenerates PLAN.md.
2516
- `;function Bc(t){let e=mn(zo(t)),r=10,n=0;for(;n<r&&e!==mn(e);){if(Oe(pe(e,"pnpm-workspace.yaml"))||Oe(pe(e,"lerna.json"))||Oe(pe(e,"pnpm-lock.yaml"))||Oe(pe(e,"package-lock.json"))||Oe(pe(e,"yarn.lock"))||Oe(pe(e,"bun.lockb"))||Oe(pe(e,"bun.lock")))return e;let i=pe(e,"package.json");if(Oe(i))try{if(JSON.parse(zt(i,"utf-8")).workspaces)return e}catch{}e=mn(e),n++}return null}var zc=qt.object({name:qt.string().min(1).optional().describe("Human-readable app name (e.g. 'Task Flow'). Optional when planId is provided \u2014 the cached plan's name is used."),plan:qt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:qt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:qt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted."),sessionId:qt.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 N(t,e,r){let n=pe(t,e);Bt(mn(n),{recursive:!0}),tt(n,r)}var Yn="# Mistflow project\n\nThis is a Mistflow-generated app. The full conventions, stack guide, and\nintegration contracts are in `AGENTS.md` (universal) and `CLAUDE.md`\n(identical copy for Claude Code).\n\nThe current build plan is in `PLAN.md` \u2014 read it for the data model,\npages, steps, and acceptance criteria. The plan is render-only; do\nnot hand-edit step status or check boxes. Step status lives in\n`mistflow.json` and is updated by `mist_implement` automatically.\n\nTo change the plan, call `mist_plan` with `modify: true` \u2014 never edit\nPLAN.md's structure manually.\n",Hc=`---
2516
+ `;function Bc(t){let e=mn(zo(t)),r=10,n=0;for(;n<r&&e!==mn(e);){if(Oe(pe(e,"pnpm-workspace.yaml"))||Oe(pe(e,"lerna.json"))||Oe(pe(e,"pnpm-lock.yaml"))||Oe(pe(e,"package-lock.json"))||Oe(pe(e,"yarn.lock"))||Oe(pe(e,"bun.lockb"))||Oe(pe(e,"bun.lock")))return e;let i=pe(e,"package.json");if(Oe(i))try{if(JSON.parse(zt(i,"utf-8")).workspaces)return e}catch{}e=mn(e),n++}return null}var zc=qt.object({name:qt.string().min(1).optional().describe("Human-readable app name (e.g. 'Task Flow'). Optional when planId is provided \u2014 the cached plan's name is used."),plan:qt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:qt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:qt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted."),sessionId:qt.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 O(t,e,r){let n=pe(t,e);Bt(mn(n),{recursive:!0}),tt(n,r)}var Xn="# Mistflow project\n\nThis is a Mistflow-generated app. The full conventions, stack guide, and\nintegration contracts are in `AGENTS.md` (universal) and `CLAUDE.md`\n(identical copy for Claude Code).\n\nThe current build plan is in `PLAN.md` \u2014 read it for the data model,\npages, steps, and acceptance criteria. The plan is render-only; do\nnot hand-edit step status or check boxes. Step status lives in\n`mistflow.json` and is updated by `mist_implement` automatically.\n\nTo change the plan, call `mist_plan` with `modify: true` \u2014 never edit\nPLAN.md's structure manually.\n",Hc=`---
2517
2517
  description: Mistflow project conventions \u2014 read AGENTS.md + PLAN.md first
2518
2518
  alwaysApply: false
2519
2519
  ---
2520
2520
 
2521
- ${Yn}`,Wc=`# VS Code Copilot instructions
2521
+ ${Xn}`,Wc=`# VS Code Copilot instructions
2522
2522
 
2523
2523
  This is the project's primary instruction file for VS Code Copilot.
2524
2524
 
2525
- ${Yn}`,Gc=`read: ["CONVENTIONS.md", "AGENTS.md", "PLAN.md"]
2526
- `;function Vc(t,e){N(t,".cursor/rules/mistflow.mdc",Hc),N(t,".github/copilot-instructions.md",Wc),N(t,".continue/rules/mistflow.md",Yn),N(t,"CONVENTIONS.md",Yn),N(t,".aider.conf.yml",Gc)}function Kc(t){if(!t.startsWith(`---
2525
+ ${Xn}`,Gc=`read: ["CONVENTIONS.md", "AGENTS.md", "PLAN.md"]
2526
+ `;function Vc(t,e){O(t,".cursor/rules/mistflow.mdc",Hc),O(t,".github/copilot-instructions.md",Wc),O(t,".continue/rules/mistflow.md",Xn),O(t,"CONVENTIONS.md",Xn),O(t,".aider.conf.yml",Gc)}function Kc(t){if(!t.startsWith(`---
2527
2527
  `))return{frontmatter:null,body:t};let e=t.indexOf(`
2528
2528
  ---
2529
2529
  `,4);if(e<0)return{frontmatter:null,body:t};let r=t.slice(4,e),n={};for(let i of r.split(`
@@ -2532,13 +2532,13 @@ name: ${s}
2532
2532
  description: ${a}
2533
2533
  ---
2534
2534
 
2535
- `;N(t,`.claude/skills/${r}/SKILL.md`,l+o);let c=`---
2535
+ `;O(t,`.claude/skills/${r}/SKILL.md`,l+o);let c=`---
2536
2536
  description: ${a}
2537
2537
  alwaysApply: false
2538
2538
  ---
2539
2539
 
2540
- `;N(t,`.cursor/rules/${r}.mdc`,c+o)}}function Yc(t){if(!Oe(t))return!0;let e;try{e=Bo(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}function Qc(t,e){let r=(e??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"new-app",n=pe(t,r);return`${t} isn't empty, so we can't scaffold the project here without clobbering existing files. Retry mist_init with path: "${n}" (a subdirectory) \u2014 the user almost certainly meant "create a new app inside this folder," not "overwrite this folder." Confirm with the user once if you're not sure, but the suggested sub-path is usually right. (A leftover .mistflow/ from planning is fine \u2014 init preserves it.)`}var Xc={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Zc=[["--color-background","#ffffff"],["--color-foreground","#0a0a0a"],["--color-card","#ffffff"],["--color-card-foreground","#0a0a0a"],["--color-popover","#ffffff"],["--color-popover-foreground","#0a0a0a"],["--color-muted","#f5f5f5"],["--color-muted-foreground","#525252"],["--color-border","#e5e5e5"],["--color-input","#e5e5e5"],["--color-primary","#0a0a0a"],["--color-primary-foreground","#ffffff"],["--color-ring","#0a0a0a"],["--color-secondary","#f5f5f5"],["--color-secondary-foreground","#0a0a0a"],["--color-accent","#f5f5f5"],["--color-accent-foreground","#0a0a0a"],["--color-destructive","#b91c1c"],["--color-destructive-foreground","#ffffff"],["--color-success","#15803d"],["--color-success-foreground","#ffffff"],["--color-warning","#a16207"],["--color-warning-foreground","#ffffff"],["--color-info","#0369a1"],["--color-info-foreground","#ffffff"]];function ed(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let r=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},i=r.split(`
2541
- `),o=null,s=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of i){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let u=a(c.slice(6).trim());(u==="dark"||u==="light")&&(n.theme=u);continue}let m=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(m){o=m[1],s=null;continue}if(c.length>0&&!c.startsWith(" ")&&!c.startsWith(" ")&&c.match(/^[a-zA-Z0-9_-]+:(\s|$)/)){o=null,s=null;continue}if(o==="typography"){let u=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(u){s=u[1].replace(/-/g,"_"),n.typography[s]={};continue}let g=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(g&&s){n.typography[s][g[1]]=a(g[2]);continue}}let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(p&&o){let u=p[1].replace(/-/g,"_"),g=a(p[2]);o==="colors"?n.colors[u]=g:o==="rounded"?n.rounded[u]=g:o==="spacing"&&(n.spacing[u]=g)}}return n}function td(t,e){let r=t.colors,i=[["--color-background",r.background],["--color-foreground",r.on_background??r.on_surface],["--color-card",r.surface??r.background],["--color-card-foreground",r.on_surface??r.on_background],["--color-popover",r.surface??r.background],["--color-popover-foreground",r.on_surface??r.on_background],["--color-muted",r.surface_variant??r.outline_variant??r.outline],["--color-muted-foreground",r.on_surface_variant??r.outline],["--color-border",r.outline_variant??r.outline],["--color-input",r.outline_variant??r.outline],["--color-primary",r.primary],["--color-primary-foreground",r.on_primary],["--color-ring",r.primary],["--color-secondary",r.secondary],["--color-secondary-foreground",r.on_secondary],["--color-accent",r.secondary],["--color-accent-foreground",r.on_secondary],["--color-destructive",r.error],["--color-destructive-foreground",r.on_error],["--color-success",r.success],["--color-success-foreground",r.on_success],["--color-warning",r.warning],["--color-warning-foreground",r.on_warning],["--color-info",r.info??r.primary],["--color-info-foreground",r.on_info??r.on_primary]].filter(a=>typeof a[1]=="string").map(([a,l])=>` ${a}: ${l};`).join(`
2540
+ `;O(t,`.cursor/rules/${r}.mdc`,c+o)}}function Yc(t){if(!Oe(t))return!0;let e;try{e=Bo(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}function Qc(t,e){let r=(e??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"new-app",n=pe(t,r);return`${t} isn't empty, so we can't scaffold the project here without clobbering existing files. Retry mist_init with path: "${n}" (a subdirectory) \u2014 the user almost certainly meant "create a new app inside this folder," not "overwrite this folder." Confirm with the user once if you're not sure, but the suggested sub-path is usually right. (A leftover .mistflow/ from planning is fine \u2014 init preserves it.)`}var Xc={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Zc=[["--color-background","#ffffff"],["--color-foreground","#0a0a0a"],["--color-card","#ffffff"],["--color-card-foreground","#0a0a0a"],["--color-popover","#ffffff"],["--color-popover-foreground","#0a0a0a"],["--color-muted","#f5f5f5"],["--color-muted-foreground","#525252"],["--color-border","#e5e5e5"],["--color-input","#e5e5e5"],["--color-primary","#0a0a0a"],["--color-primary-foreground","#ffffff"],["--color-ring","#0a0a0a"],["--color-secondary","#f5f5f5"],["--color-secondary-foreground","#0a0a0a"],["--color-accent","#f5f5f5"],["--color-accent-foreground","#0a0a0a"],["--color-destructive","#b91c1c"],["--color-destructive-foreground","#ffffff"],["--color-success","#15803d"],["--color-success-foreground","#ffffff"],["--color-warning","#a16207"],["--color-warning-foreground","#ffffff"],["--color-info","#0369a1"],["--color-info-foreground","#ffffff"]];function ed(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let r=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},i=r.split(`
2541
+ `),o=null,s=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of i){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let u=a(c.slice(6).trim());(u==="dark"||u==="light")&&(n.theme=u);continue}let m=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(m){o=m[1],s=null;continue}if(c.length>0&&!c.startsWith(" ")&&!c.startsWith(" ")&&c.match(/^[a-zA-Z0-9_-]+:(\s|$)/)){o=null,s=null;continue}if(o==="typography"){let u=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(u){s=u[1].replace(/-/g,"_"),n.typography[s]={};continue}let h=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(h&&s){n.typography[s][h[1]]=a(h[2]);continue}}let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(p&&o){let u=p[1].replace(/-/g,"_"),h=a(p[2]);o==="colors"?n.colors[u]=h:o==="rounded"?n.rounded[u]=h:o==="spacing"&&(n.spacing[u]=h)}}return n}function td(t,e){let r=t.colors,i=[["--color-background",r.background],["--color-foreground",r.on_background??r.on_surface],["--color-card",r.surface??r.background],["--color-card-foreground",r.on_surface??r.on_background],["--color-popover",r.surface??r.background],["--color-popover-foreground",r.on_surface??r.on_background],["--color-muted",r.surface_variant??r.outline_variant??r.outline],["--color-muted-foreground",r.on_surface_variant??r.outline],["--color-border",r.outline_variant??r.outline],["--color-input",r.outline_variant??r.outline],["--color-primary",r.primary],["--color-primary-foreground",r.on_primary],["--color-ring",r.primary],["--color-secondary",r.secondary],["--color-secondary-foreground",r.on_secondary],["--color-accent",r.secondary],["--color-accent-foreground",r.on_secondary],["--color-destructive",r.error],["--color-destructive-foreground",r.on_error],["--color-success",r.success],["--color-success-foreground",r.on_success],["--color-warning",r.warning],["--color-warning-foreground",r.on_warning],["--color-info",r.info??r.primary],["--color-info-foreground",r.on_info??r.on_primary]].filter(a=>typeof a[1]=="string").map(([a,l])=>` ${a}: ${l};`).join(`
2542
2542
  `),o=[` --radius-sm: ${t.rounded.sm??"0.25rem"};`,` --radius-md: ${t.rounded.md??e};`,` --radius-lg: ${t.rounded.lg??"0.5rem"};`,` --radius-xl: ${t.rounded.xl??"0.75rem"};`].join(`
2543
2543
  `);return`@import "tailwindcss";
2544
2544
  @import "tw-animate-css";
@@ -2712,36 +2712,36 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2712
2712
  `)}function fd(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 yd(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 bd(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??"",m=l.description??"";n.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${m} |`)}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 m of l.fields)n.push(`| ${m.name} | ${m.type} |`)}n.push("")}}}return n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),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 wd(t,e){if(!xe())return Ne("scaffold a new project");if(!Ut())return d(JSON.stringify({status:"node_version_unsupported",code:"node_version_unsupported",message:_t(),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,m=null,p=n;if(typeof p=="string")try{let R=JSON.parse(p);R&&typeof R=="object"&&!Array.isArray(R)&&"plan"in R?p=R.plan:p=R}catch{return d("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(!p&&o){if(m=Uc(o),!m)return d(`No plan found for planId '${o}'. Call mist_plan first, or pass the plan object inline.`,!0);p=m.plan}if(!p||typeof p!="object"||Array.isArray(p))return d("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 u=i??m?.scaffoldTargetPath;if(!u)return d("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(!Mc(u))return d(`mist_init 'path' must be an absolute path \u2014 received '${u}'. Pass the full absolute path to the target directory.`,!0);let g=zo(u),D=r??(typeof p.name=="string"?p.name:void 0);if(!D)return d("mist_init requires a human-readable app name. Pass `name`, or call it with a planId whose cached plan includes a name.",!0);let _=p?.design,x=typeof p.authModel=="string"?p.authModel:void 0,y=x==="none",P=id(p),z=ad(p,x),V=p?hn(p,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,Z=p?hn(p,"admin panel","admin dashboard","admin management"):!1,ae=p?hn(p,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,L=p,H=typeof p.dbProvider=="string"?p.dbProvider:"neon",A=Array.isArray(p.dataModel)&&p.dataModel.length>0,X=H==="none"||y&&!A&&!V,K=X?"none":H,W=K==="neon";if(!Yc(g))return d(Qc(g,p?.name),!0);Bt(g,{recursive:!0});try{try{let b=pe(g,".mistflow","rules");Bt(b,{recursive:!0}),tt(pe(b,"design-quality.md"),Kn),tt(pe(b,"landing.md"),Jn)}catch(b){console.error("Could not write design rule files:",b instanceof Error?b.message:b)}try{let b=pe(mn(g),".mistflow","mockups");if(Oe(b)){let w=Bo(b).filter(F=>F.endsWith(".html"));if(w.length>0){let F=pe(g,".mistflow","mockups");Bt(F,{recursive:!0});for(let ne of w)jc(pe(b,ne),pe(F,ne));console.error(`Copied ${w.length} mockup file(s) into project`)}}}catch(b){console.error("Could not copy mockup files:",b instanceof Error?b.message:b)}let R=null;try{R=await Or("nextjs")}catch(b){console.error("Could not fetch scaffold from API, using minimal scaffold:",b instanceof Error?b.message:b)}if(R){let b=D.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let v of R.files){if(v.path==="package.json"||v.path==="middleware.ts"||v.path==="components/sidebar.tsx"||v.path==="components/topnav.tsx"||v.path==="app/(dashboard)/layout.tsx"||v.path==="app/(dashboard)/page.tsx"||v.path==="app/(dashboard)/dashboard/page.tsx"||X&&(v.path==="lib/db.ts"||v.path==="drizzle.config.ts"||v.path==="db/index.ts"||v.path.startsWith("db/schema/"))||y&&(v.path.includes("(auth)")||v.path.includes("(admin)")||v.path.startsWith("app/admin/")||v.path.includes("components/auth/")||v.path.includes("admin-sidebar")||v.path.includes("app/api/auth/")||v.path.includes("app/api/admin/seed")||v.path==="lib/auth.ts"||v.path==="lib/auth-client.ts"||v.path==="db/schema/auth.ts"||v.path==="db/schema/index.ts"||v.path==="db/index.ts")||!P&&(v.path.includes("stripe")||v.path.includes("webhook/stripe"))||!z&&(v.path.includes("resend")||v.path.includes("emails/"))||!Z&&(v.path.includes("(admin)")||v.path.startsWith("app/admin/")||v.path.includes("admin-sidebar"))||W&&(v.path==="lib/db.ts"||v.path==="lib/auth.ts"||v.path==="drizzle.config.ts"||v.path==="db/schema/auth.ts"))continue;let le=v.content.replace(/\{\{APP_NAME\}\}/g,D).replace(/\{\{WORKER_NAME\}\}/g,b);if(W&&v.path==="next.config.ts"&&(le=le.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),v.path==="next.config.ts"){let Pe=Bc(g);Pe&&(console.error(`[init] Project is inside monorepo at ${Pe} \u2014 adding outputFileTracingRoot`),le.includes("outputFileTracingRoot")||(le=le.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
2715
+ `)}async function wd(t,e){if(!xe())return Ne("scaffold a new project");if(!Ut())return d(JSON.stringify({status:"node_version_unsupported",code:"node_version_unsupported",message:_t(),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,m=null,p=n;if(typeof p=="string")try{let R=JSON.parse(p);R&&typeof R=="object"&&!Array.isArray(R)&&"plan"in R?p=R.plan:p=R}catch{return d("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(!p&&o){if(m=Uc(o),!m)return d(`No plan found for planId '${o}'. Call mist_plan first, or pass the plan object inline.`,!0);p=m.plan}if(!p||typeof p!="object"||Array.isArray(p))return d("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 u=i??m?.scaffoldTargetPath;if(!u)return d("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(!Mc(u))return d(`mist_init 'path' must be an absolute path \u2014 received '${u}'. Pass the full absolute path to the target directory.`,!0);let h=zo(u),N=r??(typeof p.name=="string"?p.name:void 0);if(!N)return d("mist_init requires a human-readable app name. Pass `name`, or call it with a planId whose cached plan includes a name.",!0);let _=p?.design,x=typeof p.authModel=="string"?p.authModel:void 0,y=x==="none",P=id(p),z=ad(p,x),V=p?hn(p,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,Z=p?hn(p,"admin panel","admin dashboard","admin management"):!1,ae=p?hn(p,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,L=p,H=typeof p.dbProvider=="string"?p.dbProvider:"neon",A=Array.isArray(p.dataModel)&&p.dataModel.length>0,X=H==="none"||y&&!A&&!V,K=X?"none":H,W=K==="neon";if(!Yc(h))return d(Qc(h,p?.name),!0);Bt(h,{recursive:!0});try{try{let b=pe(h,".mistflow","rules");Bt(b,{recursive:!0}),tt(pe(b,"design-quality.md"),Yn),tt(pe(b,"landing.md"),Qn)}catch(b){console.error("Could not write design rule files:",b instanceof Error?b.message:b)}try{let b=pe(mn(h),".mistflow","mockups");if(Oe(b)){let w=Bo(b).filter(F=>F.endsWith(".html"));if(w.length>0){let F=pe(h,".mistflow","mockups");Bt(F,{recursive:!0});for(let ne of w)jc(pe(b,ne),pe(F,ne));console.error(`Copied ${w.length} mockup file(s) into project`)}}}catch(b){console.error("Could not copy mockup files:",b instanceof Error?b.message:b)}let R=null;try{R=await Or("nextjs")}catch(b){console.error("Could not fetch scaffold from API, using minimal scaffold:",b instanceof Error?b.message:b)}if(R){let b=N.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let v of R.files){if(v.path==="package.json"||v.path==="middleware.ts"||v.path==="components/sidebar.tsx"||v.path==="components/topnav.tsx"||v.path==="app/(dashboard)/layout.tsx"||v.path==="app/(dashboard)/page.tsx"||v.path==="app/(dashboard)/dashboard/page.tsx"||X&&(v.path==="lib/db.ts"||v.path==="drizzle.config.ts"||v.path==="db/index.ts"||v.path.startsWith("db/schema/"))||y&&(v.path.includes("(auth)")||v.path.includes("(admin)")||v.path.startsWith("app/admin/")||v.path.includes("components/auth/")||v.path.includes("admin-sidebar")||v.path.includes("app/api/auth/")||v.path.includes("app/api/admin/seed")||v.path==="lib/auth.ts"||v.path==="lib/auth-client.ts"||v.path==="db/schema/auth.ts"||v.path==="db/schema/index.ts"||v.path==="db/index.ts")||!P&&(v.path.includes("stripe")||v.path.includes("webhook/stripe"))||!z&&(v.path.includes("resend")||v.path.includes("emails/"))||!Z&&(v.path.includes("(admin)")||v.path.startsWith("app/admin/")||v.path.includes("admin-sidebar"))||W&&(v.path==="lib/db.ts"||v.path==="lib/auth.ts"||v.path==="drizzle.config.ts"||v.path==="db/schema/auth.ts"))continue;let le=v.content.replace(/\{\{APP_NAME\}\}/g,N).replace(/\{\{WORKER_NAME\}\}/g,b);if(W&&v.path==="next.config.ts"&&(le=le.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),v.path==="next.config.ts"){let Pe=Bc(h);Pe&&(console.error(`[init] Project is inside monorepo at ${Pe} \u2014 adding outputFileTracingRoot`),le.includes("outputFileTracingRoot")||(le=le.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
 
2719
2719
  const __dirname = dirname(fileURLToPath(import.meta.url));`),le=le.replace("images: {",`outputFileTracingRoot: __dirname,
2720
- images: {`)))}!Z&&v.path.includes("sidebar")&&(le=le.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),le=le.replace(/, Shield/g,"")),N(g,v.path,le)}let w={...R.dependencies},F={...R.devDependencies};w["drizzle-zod"]||(w["drizzle-zod"]="^0.5.1"),y&&delete w["better-auth"],X&&(delete w["drizzle-orm"],delete w["@libsql/client"],delete w["@neondatabase/serverless"],delete F["drizzle-kit"],delete F["@electric-sql/pglite"]),W&&(delete w["@libsql/client"],w["@neondatabase/serverless"]="^0.10.0",F["@electric-sql/pglite"]="^0.2.0"),P&&(w.stripe="^17.0.0"),z&&(w.resend="^4.0.0",w["@react-email/components"]="^0.0.31"),ae&&(w.ai="^4.0.0",w["@ai-sdk/openai"]="^1.0.0",w.openai="^4.0.0",w["server-only"]="^0.0.1",w["zod-to-json-schema"]="3.24.6");let ne={"@noble/ciphers":"^1.3.0"},Le={react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"},Y={dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint",...X?{}:{"db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"}};if(N(g,"package.json",JSON.stringify({name:D,version:"0.1.0",private:!0,scripts:Y,dependencies:w,devDependencies:F,optionalDependencies:ne,overrides:Le},null,2)),R.methodology){let v=R.methodology;W||(v=v.replace(/import \{ pgTable, text, timestamp(?:, boolean)? \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
2720
+ images: {`)))}!Z&&v.path.includes("sidebar")&&(le=le.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),le=le.replace(/, Shield/g,"")),O(h,v.path,le)}let w={...R.dependencies},F={...R.devDependencies};w["drizzle-zod"]||(w["drizzle-zod"]="^0.5.1"),y&&delete w["better-auth"],X&&(delete w["drizzle-orm"],delete w["@libsql/client"],delete w["@neondatabase/serverless"],delete F["drizzle-kit"],delete F["@electric-sql/pglite"]),W&&(delete w["@libsql/client"],w["@neondatabase/serverless"]="^0.10.0",F["@electric-sql/pglite"]="^0.2.0"),P&&(w.stripe="^17.0.0"),z&&(w.resend="^4.0.0",w["@react-email/components"]="^0.0.31"),ae&&(w.ai="^4.0.0",w["@ai-sdk/openai"]="^1.0.0",w.openai="^4.0.0",w["server-only"]="^0.0.1",w["zod-to-json-schema"]="3.24.6");let ne={"@noble/ciphers":"^1.3.0"},Le={react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"},Y={dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint",...X?{}:{"db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"}};if(O(h,"package.json",JSON.stringify({name:N,version:"0.1.0",private:!0,scripts:Y,dependencies:w,devDependencies:F,optionalDependencies:ne,overrides:Le},null,2)),R.methodology){let v=R.methodology;W||(v=v.replace(/import \{ pgTable, text, timestamp(?:, boolean)? \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
2721
2721
  import { sql } from "drizzle-orm";`).replace(/import \{ pgTable, text \} from "drizzle-orm\/pg-core";/g,`import { sqliteTable, text } from "drizzle-orm/sqlite-core";
2722
2722
  import { sql } from "drizzle-orm";`).replace(/pgTable/g,"sqliteTable").replace(/drizzle-orm\/pg-core/g,"drizzle-orm/sqlite-core").replace(/timestamp\("created_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("created_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("updated_at"\)\.notNull\(\)\.defaultNow\(\)/g,'text("updated_at").notNull().default(sql`(CURRENT_TIMESTAMP)`)').replace(/timestamp\("([a-z_]+)"\)/g,'text("$1")').replace(/boolean\("([a-z_]+)"\)\.default\(false\)/g,'integer("$1", { mode: "boolean" }).default(false)')),v=os(v),v=v+`
2723
2723
 
2724
2724
  `+qc+`
2725
- `,N(g,"AGENTS.md",v),N(g,"CLAUDE.md",v),Vc(g,v)}R.skills&&Object.keys(R.skills).length>0&&Jc(g,R.skills);let Q=a??p?.designMd;if(Q&&N(g,"DESIGN.md",Q),c&&N(g,"PLAN.md",c),W)if(N(g,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);",' } else if (process.env.NODE_ENV !== "production") {'," // Local dev \u2014 PGlite (zero-install embedded Postgres). Gating on"," // NODE_ENV !== 'production' lets webpack/esbuild dead-code-eliminate"," // this entire branch in `next build` and the Cloudflare Worker"," // bundle, so pglite + its 30MB WASM never reach prod. In `next dev`"," // the branch is live, the static require resolves ./db-local, and"," // pglite (declared in next.config.ts's serverExternalPackages) is"," // left as an external runtime import. No bundler-evasion tricks."," // eslint-disable-next-line @typescript-eslint/no-require-imports",' const { createLocalDb } = require("./db-local");'," _db = createLocalDb();"," } else {"," throw new Error(",` "DATABASE_URL is not set in production. The Mistflow deploy pipeline injects it automatically \u2014 check the project's env vars in the dashboard."`," );"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
2726
- `)),N(g,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its 30MB","// WASM binary. db.ts only requires this file when NODE_ENV !==","// 'production', so esbuild dead-code-eliminates the import in prod and","// never reaches this file. In dev, pglite is declared as a server","// external package in next.config.ts so webpack leaves it alone too.","",'import { PGlite } from "@electric-sql/pglite";','import { drizzle } from "drizzle-orm/pglite";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
2727
- `)),N(g,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
2728
- `)),y)N(g,"db/schema/index.ts",["// Re-export schema tables here as they are added.",""].join(`
2729
- `)),N(g,"db/index.ts",["// Re-export schema tables here as they are added.",'export * from "./schema";',""].join(`
2730
- `));else{N(g,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
2731
- `)),N(g,"db/schema/index.ts",['export * from "./auth";',""].join(`
2732
- `)),N(g,"db/index.ts",['export * from "./schema/auth";',""].join(`
2733
- `));let v=p.defaultRole??"user";N(g,"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: "${v}" }),`," ...(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 N(g,"package.json",JSON.stringify({name:D,version:"0.1.0",private:!0},null,2));let S=a??p?.designMd;N(g,"app/globals.css",nd(_,S)),N(g,"app/layout.tsx",od(D,_,L?.language)),N(g,"README.md",bd(D,p,{hasStripe:P,hasResend:z,hasStorage:V,hasAdmin:Z,hasAI:ae,isNeon:W})),N(g,"contracts/README.md",ss());let M=p?.dataModel??[],ee=new Set,te=0;for(let b of M){let w=b.entity??b.name;if(!w||typeof w!="string")continue;let F=as(w);ee.has(F)||(ee.add(F),N(g,F,is(w)),te++)}te===0&&N(g,"contracts/.gitkeep","");let C=[],ve=p?.publicPages;if(Array.isArray(ve))C=ve;else if(typeof ve=="string"){try{C=JSON.parse(ve)}catch{C=[]}Array.isArray(C)||(C=[])}if(!C.includes("/")){let b=p?.steps?.some(F=>{let ne=((F.name??"")+" "+(F.description??"")).toLowerCase();return ne.includes("landing")||ne.includes("marketing")||ne.includes("homepage")}),w=p?.pages?.some(F=>F.path==="/");(b||w)&&(C=["/",...C])}let $={name:D,summary:p?.summary,authModel:x,roles:p?.roles,defaultRole:p?.defaultRole,publicPages:C,navStyle:p?.navStyle,multiTenant:p?.multiTenant,pages:p?.pages,dataModel:p?.dataModel,design:p?.design},ge=cd($);ge&&N(g,"middleware.ts",ge);let Ce=dd($);Ce&&N(g,Ce.path,Ce.content);let re=pd($);if(re&&N(g,"lib/roles.ts",re),N(g,"app/page.tsx",ud($)),N(g,"app/(dashboard)/layout.tsx",md($,Z)),N(g,"app/(dashboard)/dashboard/page.tsx",hd($)),$.multiTenant){let b=gd($,W);b&&N(g,"db/schema/organization.ts",b);let w=fd($);w&&N(g,"lib/org.ts",w);let F=yd($);F&&N(g,"components/org-switcher.tsx",F)}N(g,"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)),P&&N(g,"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
- `)),z&&(N(g,"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
- `)),N(g,"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
- `)),N(g,"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(`
2738
- `))),V&&(N(g,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai";',"const RUNTIME_KEY = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","",'export type UploadMode = "rename" | "overwrite" | "fail";',"","export interface UploadIntent {"," /** Pre-signed PUT URL \u2014 client uploads bytes here directly. Short-lived (15 min). */"," uploadUrl: string;"," /** The fully-qualified storage key the file ends up at. Use this when persisting attachment refs. */"," finalKey: string;"," /** ISO8601 timestamp when the signed URL expires. */"," expiresAt: string;"," /** Hard upload size cap, in bytes (storage-edge enforced). */"," maxSize: number;","}","","function authHeaders(): Record<string, string> {"," if (!RUNTIME_KEY) {",` throw new Error("Storage requires MISTFLOW_RUNTIME_KEY. Run 'mist_setup' or check your .env.local.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": RUNTIME_KEY,'," };","}","","// 100MB hard cap matches the backend's storage_gateway.MAX_UPLOAD_SIZE_BYTES.","const MAX_UPLOAD_SIZE = 100 * 1024 * 1024;","","/**"," * Ask Mistflow for a pre-signed PUT URL."," *"," * The runtime key scopes the upload to this project's storage prefix on R2 \u2014"," * other projects can't read/write each other's files. The signed URL is good"," * for 15 minutes; the client PUTs the bytes directly to R2 (no proxy through"," * Mistflow). Persist `finalKey` (not `file.name`) when storing the attachment"," * reference, since the backend may have prefixed it for project isolation."," */","export async function getUploadIntent("," key: string,",' contentType: string = "application/octet-stream",'," contentLength: number,","): Promise<UploadIntent> {"," if (contentLength > MAX_UPLOAD_SIZE) {"," throw new Error(`File is over the 100MB upload limit (${contentLength} bytes)`);"," }"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-upload`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key, contentType, contentLength }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return { ...data, maxSize: MAX_UPLOAD_SIZE };","}","","/** Get a short-lived signed download URL for a previously-uploaded key. */","export async function getDownloadUrl(finalKey: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-download`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.downloadUrl as string;","}","","export async function deleteFile(finalKey: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/object`, {",' method: "DELETE",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });","}","","/**"," * Upload a file directly from the client to R2 using the pre-signed PUT URL."," * Returns { finalKey } \u2014 persist this when storing the attachment reference;"," * pair it with `getDownloadUrl(finalKey)` to render the file later."," */","export async function uploadFile(file: File): Promise<{ finalKey: string }> {"," const intent = await getUploadIntent(file.name, file.type, file.size);"," const res = await fetch(intent.uploadUrl, {",' method: "PUT",',' headers: { "Content-Type": file.type || "application/octet-stream" },'," body: file,"," });"," if (!res.ok) throw new Error(`Upload failed (${res.status})`);"," return { finalKey: intent.finalKey };","}",""].join(`
2739
- `)),N(g,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadIntent } from "@/lib/storage";',"","// Server-side intent broker. The route receives the client's filename +","// content type, asks Mistflow for a signed PUT URL using the project's","// runtime key, and hands the URL back to the client. The client then PUTs","// the bytes directly to R2 \u2014 bytes never proxy through this server.","export async function POST(req: NextRequest) {"," const { key, filename, contentType, contentLength } = await req.json();"," // Backwards-compat: older client code sent { filename } without { key }."," const finalKeyHint = key ?? filename;"," if (!finalKeyHint) {",' return NextResponse.json({ error: "key (or filename) is required" }, { status: 400 });'," }",' if (typeof contentLength !== "number" || contentLength < 1) {',' return NextResponse.json({ error: "contentLength is required (file size in bytes)" }, { status: 400 });'," }"," try {"," const intent = await getUploadIntent("," finalKeyHint,",' contentType ?? "application/octet-stream",'," contentLength,"," );"," return NextResponse.json(intent);"," } catch (err) {",' const msg = err instanceof Error ? err.message : "Failed to prepare upload";'," return NextResponse.json({ error: msg }, { status: 500 });"," }","}",""].join(`
2740
- `)),N(g,"lib/server/storage.ts",['import "server-only";',"",'export class StorageConfigError extends Error { readonly code = "storage_config"; }','export class StorageUpstreamError extends Error { readonly code = "storage_upstream_error"; }','export class StorageQuotaError extends Error { readonly code = "storage_quota"; }',"","function runtimeKey(): string {"," const k = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;",` if (!k) throw new StorageConfigError("Storage requires managed mode. Run 'mist_setup' to enable.");`," return k;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","async function callGateway<T>(path: string, body: unknown): Promise<T> {"," const r = await fetch(apiUrl() + path, {",' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new StorageConfigError("Runtime key rejected. Re-run mist_setup.");',' if (r.status === 402) throw new StorageQuotaError("Storage quota exhausted.");',' if (r.status === 413) throw new StorageQuotaError("File exceeds the 100MB upload limit.");',' if (!r.ok) throw new StorageUpstreamError("Storage gateway error " + r.status);'," return (await r.json()) as T;","}","","export const storage = {"," /** Upload a Blob/File. Backend mints a signed URL; client PUTs directly to R2. */"," async put(opts: { key: string; blob: Blob; contentType: string; expiresIn?: number }): Promise<{ finalKey: string }> {"," const signed = await callGateway<{ uploadUrl: string; finalKey: string; expiresAt: string }>(",' "/api/storage/sign-upload",'," {"," key: opts.key,"," contentType: opts.contentType,"," contentLength: opts.blob.size,"," expiresIn: opts.expiresIn,"," },"," );"," const res = await fetch(signed.uploadUrl, {",' method: "PUT",'," body: opts.blob,",' headers: { "Content-Type": opts.contentType },'," });"," if (!res.ok) {",' throw new StorageUpstreamError("Direct R2 upload failed: " + res.status);'," }"," return { finalKey: signed.finalKey };"," },",""," /** Get a short-lived signed download URL for a stored object. */"," async get(opts: { key: string; expiresIn?: number }): Promise<{ url: string; expiresAt: string }> {"," const signed = await callGateway<{ downloadUrl: string; expiresAt: string }>(",' "/api/storage/sign-download",'," { key: opts.key, expiresIn: opts.expiresIn },"," );"," return { url: signed.downloadUrl, expiresAt: signed.expiresAt };"," },",""," /** Delete an object. Server-side delete via R2 SDK. */"," async delete(opts: { key: string }): Promise<void> {",' const r = await fetch(apiUrl() + "/api/storage/object", {',' method: "DELETE",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify({ key: opts.key }),"," });"," if (!r.ok && r.status !== 204) {",' throw new StorageUpstreamError("Delete failed: " + r.status);'," }"," },",""," /** List objects under an optional prefix. Always scoped to your project. */"," async list(opts: { prefix?: string; limit?: number; cursor?: string } = {}): Promise<{ keys: { key: string; size: number }[]; cursor?: string }> {",' return callGateway("/api/storage/list", opts);'," },","};",""].join(`
2741
- `))),ae&&(N(g,"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
- `)),N(g,"lib/ai.ts",['import "server-only";',"",'export * from "./server/ai";',""].join(`
2743
- `)),N(g,"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 ye=Array.isArray(p?.integrations)?p.integrations.map(b=>({name:b.name,preset:b.preset,envVars:b.envVars??[]})):[],je={};for(let b of ye)for(let w of b.envVars??[])je[w.key]||(je[w.key]={description:w.description,setupUrl:w.setupUrl,...b.name?{integration:b.name}:{}});let rt=L?.requestedSubdomain||void 0,Ke={name:D,methodologyVersion:R?.version??"1.0",createdAt:new Date().toISOString(),...o?{planId:o}:{},...rt?{requestedSubdomain:rt}:{},plan:Array.isArray(p?.steps)?{...p,steps:p.steps.map(b=>({number:b.number,name:b.name??b.title,description:b.description,entities:b.entities,pages:b.pages,features:b.features,status:"pending"}))}:p,dbProvider:K,env:{managed:{...!X&&W?{DATABASE_URL:{description:"Postgres connection URL",scope:"production"}}:X?{}:{TURSO_URL:{description:"Turso database URL",scope:"production"},TURSO_AUTH_TOKEN:{description:"Turso database auth token",scope:"production"}},...y?{}:{AUTH_SECRET:{description:"Auth encryption secret",scope:"production"}},...P?{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"}}:{},...z?{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(je).length>0?{required:je}:{}},authModel:x??"email",roles:p?.roles??null,navStyle:p?.navStyle??"sidebar",multiTenant:p?.multiTenant??!1,hasAdmin:Z,hasResend:z,hasStorage:V,hasAI:ae,deploy:null};N(g,"mistflow.json",JSON.stringify(Ke,null,2)),Ft(g);let Je=$c(32).toString("hex"),st=P?`
2725
+ `,O(h,"AGENTS.md",v),O(h,"CLAUDE.md",v),Vc(h,v)}R.skills&&Object.keys(R.skills).length>0&&Jc(h,R.skills);let Q=a??p?.designMd;if(Q&&O(h,"DESIGN.md",Q),c&&O(h,"PLAN.md",c),W)if(O(h,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);",' } else if (process.env.NODE_ENV !== "production") {'," // Local dev \u2014 PGlite (zero-install embedded Postgres). Gating on"," // NODE_ENV !== 'production' lets webpack/esbuild dead-code-eliminate"," // this entire branch in `next build` and the Cloudflare Worker"," // bundle, so pglite + its 30MB WASM never reach prod. In `next dev`"," // the branch is live, the static require resolves ./db-local, and"," // pglite (declared in next.config.ts's serverExternalPackages) is"," // left as an external runtime import. No bundler-evasion tricks."," // eslint-disable-next-line @typescript-eslint/no-require-imports",' const { createLocalDb } = require("./db-local");'," _db = createLocalDb();"," } else {"," throw new Error(",` "DATABASE_URL is not set in production. The Mistflow deploy pipeline injects it automatically \u2014 check the project's env vars in the dashboard."`," );"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
2726
+ `)),O(h,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its 30MB","// WASM binary. db.ts only requires this file when NODE_ENV !==","// 'production', so esbuild dead-code-eliminates the import in prod and","// never reaches this file. In dev, pglite is declared as a server","// external package in next.config.ts so webpack leaves it alone too.","",'import { PGlite } from "@electric-sql/pglite";','import { drizzle } from "drizzle-orm/pglite";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
2727
+ `)),O(h,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
2728
+ `)),y)O(h,"db/schema/index.ts",["// Re-export schema tables here as they are added.",""].join(`
2729
+ `)),O(h,"db/index.ts",["// Re-export schema tables here as they are added.",'export * from "./schema";',""].join(`
2730
+ `));else{O(h,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
2731
+ `)),O(h,"db/schema/index.ts",['export * from "./auth";',""].join(`
2732
+ `)),O(h,"db/index.ts",['export * from "./schema/auth";',""].join(`
2733
+ `));let v=p.defaultRole??"user";O(h,"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: "${v}" }),`," ...(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 O(h,"package.json",JSON.stringify({name:N,version:"0.1.0",private:!0},null,2));let S=a??p?.designMd;O(h,"app/globals.css",nd(_,S)),O(h,"app/layout.tsx",od(N,_,L?.language)),O(h,"README.md",bd(N,p,{hasStripe:P,hasResend:z,hasStorage:V,hasAdmin:Z,hasAI:ae,isNeon:W})),O(h,"contracts/README.md",ss());let M=p?.dataModel??[],ee=new Set,te=0;for(let b of M){let w=b.entity??b.name;if(!w||typeof w!="string")continue;let F=as(w);ee.has(F)||(ee.add(F),O(h,F,is(w)),te++)}te===0&&O(h,"contracts/.gitkeep","");let C=[],ve=p?.publicPages;if(Array.isArray(ve))C=ve;else if(typeof ve=="string"){try{C=JSON.parse(ve)}catch{C=[]}Array.isArray(C)||(C=[])}if(!C.includes("/")){let b=p?.steps?.some(F=>{let ne=((F.name??"")+" "+(F.description??"")).toLowerCase();return ne.includes("landing")||ne.includes("marketing")||ne.includes("homepage")}),w=p?.pages?.some(F=>F.path==="/");(b||w)&&(C=["/",...C])}let $={name:N,summary:p?.summary,authModel:x,roles:p?.roles,defaultRole:p?.defaultRole,publicPages:C,navStyle:p?.navStyle,multiTenant:p?.multiTenant,pages:p?.pages,dataModel:p?.dataModel,design:p?.design},ge=cd($);ge&&O(h,"middleware.ts",ge);let Ce=dd($);Ce&&O(h,Ce.path,Ce.content);let re=pd($);if(re&&O(h,"lib/roles.ts",re),O(h,"app/page.tsx",ud($)),O(h,"app/(dashboard)/layout.tsx",md($,Z)),O(h,"app/(dashboard)/dashboard/page.tsx",hd($)),$.multiTenant){let b=gd($,W);b&&O(h,"db/schema/organization.ts",b);let w=fd($);w&&O(h,"lib/org.ts",w);let F=yd($);F&&O(h,"components/org-switcher.tsx",F)}O(h,"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)),P&&O(h,"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
+ `)),z&&(O(h,"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
+ `)),O(h,"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
+ `)),O(h,"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(`
2738
+ `))),V&&(O(h,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai";',"const RUNTIME_KEY = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;","",'export type UploadMode = "rename" | "overwrite" | "fail";',"","export interface UploadIntent {"," /** Pre-signed PUT URL \u2014 client uploads bytes here directly. Short-lived (15 min). */"," uploadUrl: string;"," /** The fully-qualified storage key the file ends up at. Use this when persisting attachment refs. */"," finalKey: string;"," /** ISO8601 timestamp when the signed URL expires. */"," expiresAt: string;"," /** Hard upload size cap, in bytes (storage-edge enforced). */"," maxSize: number;","}","","function authHeaders(): Record<string, string> {"," if (!RUNTIME_KEY) {",` throw new Error("Storage requires MISTFLOW_RUNTIME_KEY. Run 'mist_setup' or check your .env.local.");`," }"," return {",' "Content-Type": "application/json",',' "X-Mistflow-AI-Key": RUNTIME_KEY,'," };","}","","// 100MB hard cap matches the backend's storage_gateway.MAX_UPLOAD_SIZE_BYTES.","const MAX_UPLOAD_SIZE = 100 * 1024 * 1024;","","/**"," * Ask Mistflow for a pre-signed PUT URL."," *"," * The runtime key scopes the upload to this project's storage prefix on R2 \u2014"," * other projects can't read/write each other's files. The signed URL is good"," * for 15 minutes; the client PUTs the bytes directly to R2 (no proxy through"," * Mistflow). Persist `finalKey` (not `file.name`) when storing the attachment"," * reference, since the backend may have prefixed it for project isolation."," */","export async function getUploadIntent("," key: string,",' contentType: string = "application/octet-stream",'," contentLength: number,","): Promise<UploadIntent> {"," if (contentLength > MAX_UPLOAD_SIZE) {"," throw new Error(`File is over the 100MB upload limit (${contentLength} bytes)`);"," }"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-upload`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key, contentType, contentLength }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return { ...data, maxSize: MAX_UPLOAD_SIZE };","}","","/** Get a short-lived signed download URL for a previously-uploaded key. */","export async function getDownloadUrl(finalKey: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/sign-download`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.downloadUrl as string;","}","","export async function deleteFile(finalKey: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/object`, {",' method: "DELETE",'," headers: authHeaders(),"," body: JSON.stringify({ key: finalKey }),"," });","}","","/**"," * Upload a file directly from the client to R2 using the pre-signed PUT URL."," * Returns { finalKey } \u2014 persist this when storing the attachment reference;"," * pair it with `getDownloadUrl(finalKey)` to render the file later."," */","export async function uploadFile(file: File): Promise<{ finalKey: string }> {"," const intent = await getUploadIntent(file.name, file.type, file.size);"," const res = await fetch(intent.uploadUrl, {",' method: "PUT",',' headers: { "Content-Type": file.type || "application/octet-stream" },'," body: file,"," });"," if (!res.ok) throw new Error(`Upload failed (${res.status})`);"," return { finalKey: intent.finalKey };","}",""].join(`
2739
+ `)),O(h,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadIntent } from "@/lib/storage";',"","// Server-side intent broker. The route receives the client's filename +","// content type, asks Mistflow for a signed PUT URL using the project's","// runtime key, and hands the URL back to the client. The client then PUTs","// the bytes directly to R2 \u2014 bytes never proxy through this server.","export async function POST(req: NextRequest) {"," const { key, filename, contentType, contentLength } = await req.json();"," // Backwards-compat: older client code sent { filename } without { key }."," const finalKeyHint = key ?? filename;"," if (!finalKeyHint) {",' return NextResponse.json({ error: "key (or filename) is required" }, { status: 400 });'," }",' if (typeof contentLength !== "number" || contentLength < 1) {',' return NextResponse.json({ error: "contentLength is required (file size in bytes)" }, { status: 400 });'," }"," try {"," const intent = await getUploadIntent("," finalKeyHint,",' contentType ?? "application/octet-stream",'," contentLength,"," );"," return NextResponse.json(intent);"," } catch (err) {",' const msg = err instanceof Error ? err.message : "Failed to prepare upload";'," return NextResponse.json({ error: msg }, { status: 500 });"," }","}",""].join(`
2740
+ `)),O(h,"lib/server/storage.ts",['import "server-only";',"",'export class StorageConfigError extends Error { readonly code = "storage_config"; }','export class StorageUpstreamError extends Error { readonly code = "storage_upstream_error"; }','export class StorageQuotaError extends Error { readonly code = "storage_quota"; }',"","function runtimeKey(): string {"," const k = process.env.MISTFLOW_RUNTIME_KEY ?? process.env.MISTFLOW_AI_RUNTIME_KEY;",` if (!k) throw new StorageConfigError("Storage requires managed mode. Run 'mist_setup' to enable.");`," return k;","}","function apiUrl(): string {",' return (process.env.MISTFLOW_API_URL ?? process.env.MISTFLOW_AI_API_URL ?? "https://api.mistflow.ai").replace(/\\/$/, "");',"}","async function callGateway<T>(path: string, body: unknown): Promise<T> {"," const r = await fetch(apiUrl() + path, {",' method: "POST",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify(body),"," });",' if (r.status === 401) throw new StorageConfigError("Runtime key rejected. Re-run mist_setup.");',' if (r.status === 402) throw new StorageQuotaError("Storage quota exhausted.");',' if (r.status === 413) throw new StorageQuotaError("File exceeds the 100MB upload limit.");',' if (!r.ok) throw new StorageUpstreamError("Storage gateway error " + r.status);'," return (await r.json()) as T;","}","","export const storage = {"," /** Upload a Blob/File. Backend mints a signed URL; client PUTs directly to R2. */"," async put(opts: { key: string; blob: Blob; contentType: string; expiresIn?: number }): Promise<{ finalKey: string }> {"," const signed = await callGateway<{ uploadUrl: string; finalKey: string; expiresAt: string }>(",' "/api/storage/sign-upload",'," {"," key: opts.key,"," contentType: opts.contentType,"," contentLength: opts.blob.size,"," expiresIn: opts.expiresIn,"," },"," );"," const res = await fetch(signed.uploadUrl, {",' method: "PUT",'," body: opts.blob,",' headers: { "Content-Type": opts.contentType },'," });"," if (!res.ok) {",' throw new StorageUpstreamError("Direct R2 upload failed: " + res.status);'," }"," return { finalKey: signed.finalKey };"," },",""," /** Get a short-lived signed download URL for a stored object. */"," async get(opts: { key: string; expiresIn?: number }): Promise<{ url: string; expiresAt: string }> {"," const signed = await callGateway<{ downloadUrl: string; expiresAt: string }>(",' "/api/storage/sign-download",'," { key: opts.key, expiresIn: opts.expiresIn },"," );"," return { url: signed.downloadUrl, expiresAt: signed.expiresAt };"," },",""," /** Delete an object. Server-side delete via R2 SDK. */"," async delete(opts: { key: string }): Promise<void> {",' const r = await fetch(apiUrl() + "/api/storage/object", {',' method: "DELETE",',' headers: { "Content-Type": "application/json", "X-Mistflow-AI-Key": runtimeKey() },'," body: JSON.stringify({ key: opts.key }),"," });"," if (!r.ok && r.status !== 204) {",' throw new StorageUpstreamError("Delete failed: " + r.status);'," }"," },",""," /** List objects under an optional prefix. Always scoped to your project. */"," async list(opts: { prefix?: string; limit?: number; cursor?: string } = {}): Promise<{ keys: { key: string; size: number }[]; cursor?: string }> {",' return callGateway("/api/storage/list", opts);'," },","};",""].join(`
2741
+ `))),ae&&(O(h,"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
+ `)),O(h,"lib/ai.ts",['import "server-only";',"",'export * from "./server/ai";',""].join(`
2743
+ `)),O(h,"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 ye=Array.isArray(p?.integrations)?p.integrations.map(b=>({name:b.name,preset:b.preset,envVars:b.envVars??[]})):[],je={};for(let b of ye)for(let w of b.envVars??[])je[w.key]||(je[w.key]={description:w.description,setupUrl:w.setupUrl,...b.name?{integration:b.name}:{}});let rt=L?.requestedSubdomain||void 0,Ke={name:N,methodologyVersion:R?.version??"1.0",createdAt:new Date().toISOString(),...o?{planId:o}:{},...rt?{requestedSubdomain:rt}:{},plan:Array.isArray(p?.steps)?{...p,steps:p.steps.map(b=>({number:b.number,name:b.name??b.title,description:b.description,entities:b.entities,pages:b.pages,features:b.features,status:"pending"}))}:p,dbProvider:K,env:{managed:{...!X&&W?{DATABASE_URL:{description:"Postgres connection URL",scope:"production"}}:X?{}:{TURSO_URL:{description:"Turso database URL",scope:"production"},TURSO_AUTH_TOKEN:{description:"Turso database auth token",scope:"production"}},...y?{}:{AUTH_SECRET:{description:"Auth encryption secret",scope:"production"}},...P?{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"}}:{},...z?{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(je).length>0?{required:je}:{}},authModel:x??"email",roles:p?.roles??null,navStyle:p?.navStyle??"sidebar",multiTenant:p?.multiTenant??!1,hasAdmin:Z,hasResend:z,hasStorage:V,hasAI:ae,deploy:null};O(h,"mistflow.json",JSON.stringify(Ke,null,2)),Ft(h);let Je=$c(32).toString("hex"),st=P?`
2745
2745
  # Stripe
2746
2746
  STRIPE_SECRET_KEY=
2747
2747
  STRIPE_WEBHOOK_SECRET=
@@ -2766,20 +2766,20 @@ AUTH_SECRET=your-secret-here`,Ue=X?"# No database required for this public app":
2766
2766
  # Set DATABASE_URL only for production or to use a remote Postgres
2767
2767
  # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Ae=X?"# No database required for this public app":`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
2768
2768
  # Set DATABASE_URL only for production or to use a remote Postgres
2769
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;N(g,".env.local",`${Ue}${Me}
2769
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;O(h,".env.local",`${Ue}${Me}
2770
2770
  ${y?"":`
2771
2771
  # Mistflow-hosted Google sign-in (zero Google Cloud setup)
2772
2772
  MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
2773
- `}${st}${Se}${U}${ke}`),N(g,".env.example",`${Ae}${Ye}
2774
- ${st}${Se}${U}${ke}`);let f=[],k=(b,w)=>{f.push({phase:b,message:w})},T=(b,w)=>{let F=f.find(ne=>ne.phase===b&&!ne.durationMs);F&&(F.durationMs=w)};if(e){let b=ze(e.server,e.progressToken,()=>f[f.length-1]?.message??"Setting up project...");e.cleanup=()=>b.stop()}let E=rt,B=L?.pickedDirection??L?.designDirection??void 0,se=L?.imageryBrief??B?.imagery??void 0,ie=L?.designConversationId??void 0,me=L?{name:L.name,summary:L.summary,audienceType:L.audienceType,authModel:L.authModel,dbProvider:K,dataModel:L.dataModel,design:L.design,publicLanding:L.publicLanding}:void 0,O,G;k("register","Registering project on Mistflow...");let we=Date.now();try{let b=await kt(D,{template:void 0,dbProvider:K,requestedSubdomain:E,pickedDirection:B,imageryBrief:se,planContext:me,designConversationId:ie,sessionId:s});if(O=b.id,b.design_md&&(a=b.design_md),b.plan_md&&(c=b.plan_md),Array.isArray(b.design_warnings)&&b.design_warnings.length>0){l=b.design_warnings;for(let Y of b.design_warnings)console.error(`[mist_init] design warning [${Y.code}]: ${Y.detail}`)}if(b.layout_spec&&p&&typeof p=="object"&&(p.layoutSpec=b.layout_spec),b.picker_render_html&&typeof b.picker_render_html=="string")try{let Y=pe(g,".mistflow");Bt(Y,{recursive:!0}),tt(pe(Y,"picker-render.html"),b.picker_render_html),console.error(`[mist_init] picker render written to .mistflow/picker-render.html (${b.picker_render_html.length} chars)`)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);console.error(`[mist_init] picker render write failed: ${Q}`)}if(se)try{let Y=await vr(O),Q=pe(g,"public","images");Bt(Q,{recursive:!0});let v=0,le=0;for(let[Pe,Re]of Object.entries(Y.slots))if(Re.status==="done"&&Re.signed_url)try{let Ee=await kr(Re.signed_url);tt(pe(Q,`${Pe}.png`),Ee),v++}catch(Ee){let ua=Ee instanceof Error?Ee.message:String(Ee);console.error(`[mist_init] imagery: ${Pe} download failed: ${ua}`)}else(Re.status==="queued"||Re.status==="running")&&le++;(v>0||le>0)&&console.error(`[mist_init] imagery: ${v} ready, ${le} still rendering`)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);console.error(`[mist_init] imagery manifest fetch failed: ${Q}`)}let w=pe(g,"mistflow.json"),F=JSON.parse(zt(w,"utf-8"));if(F.projectId=O,b.layout_spec&&F.plan&&typeof F.plan=="object"&&(F.plan.layoutSpec=b.layout_spec),tt(w,JSON.stringify(F,null,2)),sn(g,on(O,D)),b.managed_env&&Object.keys(b.managed_env).length>0){let Y=pe(g,".env.local"),Q=Oe(Y)?zt(Y,"utf-8"):"";for(let[v,le]of Object.entries(b.managed_env)){let Pe=new RegExp(`^${v}=.*$`,"m");Pe.test(Q)?Q=Q.replace(Pe,`${v}=${le}`):Q+=`
2775
- ${v}=${le}`}tt(Y,Q)}let Le=b.runtimeKey;if(Le?.rawKey){let Y=pe(g,".env.local"),Q=Oe(Y)?zt(Y,"utf-8"):"",v=(le,Pe)=>{let Re=new RegExp(`^${le}=\\s*$`,"m"),Ee=new RegExp(`^${le}=`,"m");Re.test(Q)?Q=Q.replace(Re,`${le}=${Pe}`):Ee.test(Q)||(Q+=`
2776
- ${le}=${Pe}`)};v("MISTFLOW_RUNTIME_KEY",Le.rawKey),v("MISTFLOW_AI_RUNTIME_KEY",Le.rawKey),tt(Y,Q)}if(!y&&b.mistflow_app_id){let Y=pe(g,".env.local"),Q=Oe(Y)?zt(Y,"utf-8"):"";/^MISTFLOW_OAUTH_PROXY_URL=/m.test(Q)||(Q+=`
2773
+ `}${st}${Se}${U}${ke}`),O(h,".env.example",`${Ae}${Ye}
2774
+ ${st}${Se}${U}${ke}`);let f=[],k=(b,w)=>{f.push({phase:b,message:w})},T=(b,w)=>{let F=f.find(ne=>ne.phase===b&&!ne.durationMs);F&&(F.durationMs=w)};if(e){let b=ze(e.server,e.progressToken,()=>f[f.length-1]?.message??"Setting up project...");e.cleanup=()=>b.stop()}let E=rt,B=L?.pickedDirection??L?.designDirection??void 0,se=L?.imageryBrief??B?.imagery??void 0,ie=L?.designConversationId??void 0,me=L?{name:L.name,summary:L.summary,audienceType:L.audienceType,authModel:L.authModel,dbProvider:K,dataModel:L.dataModel,design:L.design,publicLanding:L.publicLanding}:void 0,D,G;k("register","Registering project on Mistflow...");let we=Date.now();try{let b=await kt(N,{template:void 0,dbProvider:K,requestedSubdomain:E,pickedDirection:B,imageryBrief:se,planContext:me,designConversationId:ie,sessionId:s});if(D=b.id,b.design_md&&(a=b.design_md),b.plan_md&&(c=b.plan_md),Array.isArray(b.design_warnings)&&b.design_warnings.length>0){l=b.design_warnings;for(let Y of b.design_warnings)console.error(`[mist_init] design warning [${Y.code}]: ${Y.detail}`)}if(b.layout_spec&&p&&typeof p=="object"&&(p.layoutSpec=b.layout_spec),b.picker_render_html&&typeof b.picker_render_html=="string")try{let Y=pe(h,".mistflow");Bt(Y,{recursive:!0}),tt(pe(Y,"picker-render.html"),b.picker_render_html),console.error(`[mist_init] picker render written to .mistflow/picker-render.html (${b.picker_render_html.length} chars)`)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);console.error(`[mist_init] picker render write failed: ${Q}`)}if(se)try{let Y=await vr(D),Q=pe(h,"public","images");Bt(Q,{recursive:!0});let v=0,le=0;for(let[Pe,Re]of Object.entries(Y.slots))if(Re.status==="done"&&Re.signed_url)try{let Ee=await kr(Re.signed_url);tt(pe(Q,`${Pe}.png`),Ee),v++}catch(Ee){let ua=Ee instanceof Error?Ee.message:String(Ee);console.error(`[mist_init] imagery: ${Pe} download failed: ${ua}`)}else(Re.status==="queued"||Re.status==="running")&&le++;(v>0||le>0)&&console.error(`[mist_init] imagery: ${v} ready, ${le} still rendering`)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);console.error(`[mist_init] imagery manifest fetch failed: ${Q}`)}let w=pe(h,"mistflow.json"),F=JSON.parse(zt(w,"utf-8"));if(F.projectId=D,b.layout_spec&&F.plan&&typeof F.plan=="object"&&(F.plan.layoutSpec=b.layout_spec),tt(w,JSON.stringify(F,null,2)),sn(h,on(D,N)),b.managed_env&&Object.keys(b.managed_env).length>0){let Y=pe(h,".env.local"),Q=Oe(Y)?zt(Y,"utf-8"):"";for(let[v,le]of Object.entries(b.managed_env)){let Pe=new RegExp(`^${v}=.*$`,"m");Pe.test(Q)?Q=Q.replace(Pe,`${v}=${le}`):Q+=`
2775
+ ${v}=${le}`}tt(Y,Q)}let Le=b.runtimeKey;if(Le?.rawKey){let Y=pe(h,".env.local"),Q=Oe(Y)?zt(Y,"utf-8"):"",v=(le,Pe)=>{let Re=new RegExp(`^${le}=\\s*$`,"m"),Ee=new RegExp(`^${le}=`,"m");Re.test(Q)?Q=Q.replace(Re,`${le}=${Pe}`):Ee.test(Q)||(Q+=`
2776
+ ${le}=${Pe}`)};v("MISTFLOW_RUNTIME_KEY",Le.rawKey),v("MISTFLOW_AI_RUNTIME_KEY",Le.rawKey),tt(Y,Q)}if(!y&&b.mistflow_app_id){let Y=pe(h,".env.local"),Q=Oe(Y)?zt(Y,"utf-8"):"";/^MISTFLOW_OAUTH_PROXY_URL=/m.test(Q)||(Q+=`
2777
2777
  # Mistflow-hosted Google sign-in (zero Google Cloud setup)
2778
2778
  MISTFLOW_OAUTH_PROXY_URL=http://localhost:9100
2779
2779
  `),/^MISTFLOW_APP_ID=/m.test(Q)||(Q+=`
2780
2780
  # Mistflow-hosted Google sign-in (zero GCP setup)
2781
2781
  MISTFLOW_APP_ID=${b.mistflow_app_id}
2782
- `),tt(Y,Q)}try{let{getBaseUrl:Y,getAuthHeaders:Q}=await Promise.resolve().then(()=>(_e(),zs)),v=Q(),le=p?.features,Pe=p?.steps,Re={};Array.isArray(le)&&le.length>0&&(Re.features=le.map(Ee=>Ee.name)),p&&(Re.plan=p),Array.isArray(Pe)&&Pe.length>0&&(Re.provenance=Pe.map(Ee=>({feature:Ee.name??Ee.title??`Step ${Ee.number??"?"}`,user_intent:(Ee.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(Re).length>0&&await fetch(`${Y()}/api/projects/${encodeURIComponent(O)}/state`,{method:"PUT",headers:{...v,"Content-Type":"application/json"},body:JSON.stringify(Re)})}catch{}f[f.length-1].message=`Registered as ${O.slice(0,8)}`}catch(b){let w=b instanceof Error?b.message:String(b);console.error("Could not register project on backend:",w),G=`Project created locally but NOT registered on Mistflow servers (${w}). Deploy will auto-register it.`,f[f.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}T("register",Date.now()-we),k("git","Initializing git repository...");let oe=Date.now();try{let b=Fc(g);await b.init(),await b.add("."),await b.commit("Initial Mistflow project setup"),f[f.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),f[f.length-1].message="Git init skipped"}T("git",Date.now()-oe);let fe=f.reduce((b,w)=>b+(w.durationMs??0),0),de={projectPath:g,projectId:O,status:"awaiting_install"};E&&(de.requestedSubdomain=E,de.productionUrl=`https://${E}.mistflow.app`);let ue=f.map(b=>{let w=b.durationMs?` (${(b.durationMs/1e3).toFixed(1)}s)`:"";return`${b.message}${w}`});de.progress=ue,de.totalSetupTime=`${(fe/1e3).toFixed(1)}s`;let I=[];O||I.push("Project was not registered with Mistflow (backend error during create). mist_deploy will retry registration automatically on the first deploy."),G&&(de.registrationWarning=G),I.length>0&&(de.warnings=I),l.length>0&&(de.designPipelineWarnings=l,de.designPipelineWarningsHostAction=`Tell the user explicitly: "The design generation pipeline had a partial failure \u2014 your scaffolded landing may not match the picker preview exactly. The build will continue with fallback design tokens. If the deployed landing looks wrong, run mist_plan({ description: '<original description>' }) again to get a fresh picker." Then continue with the install step. Do not silently proceed.`);let be=`${E?`TELL THE USER: "Your app's URL is reserved: https://${E}.mistflow.app \u2014 it goes live when you deploy. While it's being built, you'll get a local preview to watch your app come together in real time." `:""}NEXT: Call mist_install({ projectPath: "${g}" }). This is fire-and-poll \u2014 the first call returns a jobId and status: "running"; re-call with the same jobId every ~15-30s until status is "complete". Typical duration 30-90s. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. After install completes, call mist_implement({ projectPath: "${g}" }) to build the first plan step.`;return de.nextAction=O?be:`${be} NOTE: The project could not be registered with the backend during init (${G??"see registrationWarning"}). mist_deploy will retry the registration automatically on the first deploy \u2014 no manual recovery needed.`,d(JSON.stringify(de))}catch(R){try{Dc(g,{recursive:!0,force:!0})}catch{}throw R}}var Ho={name:"mist_init",description:"Initialize a new Next.js project using the Mistflow stack. Downloads templates from the Mistflow registry, installs dependencies, sets up auth, and initializes git. Use this after mist_plan to create the project.",inputSchema:zc,handler:wd};import{z as yn}from"zod";import{existsSync as gt,readFileSync as us,writeFileSync as rr,mkdirSync as ji}from"fs";import{join as He,resolve as lp,dirname as cp}from"path";_e();import{createConnection as dp}from"net";var Wo=`# Consumer Warm Archetype
2782
+ `),tt(Y,Q)}try{let{getBaseUrl:Y,getAuthHeaders:Q}=await Promise.resolve().then(()=>(_e(),zs)),v=Q(),le=p?.features,Pe=p?.steps,Re={};Array.isArray(le)&&le.length>0&&(Re.features=le.map(Ee=>Ee.name)),p&&(Re.plan=p),Array.isArray(Pe)&&Pe.length>0&&(Re.provenance=Pe.map(Ee=>({feature:Ee.name??Ee.title??`Step ${Ee.number??"?"}`,user_intent:(Ee.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(Re).length>0&&await fetch(`${Y()}/api/projects/${encodeURIComponent(D)}/state`,{method:"PUT",headers:{...v,"Content-Type":"application/json"},body:JSON.stringify(Re)})}catch{}f[f.length-1].message=`Registered as ${D.slice(0,8)}`}catch(b){let w=b instanceof Error?b.message:String(b);console.error("Could not register project on backend:",w),G=`Project created locally but NOT registered on Mistflow servers (${w}). Deploy will auto-register it.`,f[f.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}T("register",Date.now()-we),k("git","Initializing git repository...");let oe=Date.now();try{let b=Fc(h);await b.init(),await b.add("."),await b.commit("Initial Mistflow project setup"),f[f.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),f[f.length-1].message="Git init skipped"}T("git",Date.now()-oe);let fe=f.reduce((b,w)=>b+(w.durationMs??0),0),de={projectPath:h,projectId:D,status:"awaiting_install"};E&&(de.requestedSubdomain=E,de.productionUrl=`https://${E}.mistflow.app`);let ue=f.map(b=>{let w=b.durationMs?` (${(b.durationMs/1e3).toFixed(1)}s)`:"";return`${b.message}${w}`});de.progress=ue,de.totalSetupTime=`${(fe/1e3).toFixed(1)}s`;let I=[];D||I.push("Project was not registered with Mistflow (backend error during create). mist_deploy will retry registration automatically on the first deploy."),G&&(de.registrationWarning=G),I.length>0&&(de.warnings=I),l.length>0&&(de.designPipelineWarnings=l,de.designPipelineWarningsHostAction=`Tell the user explicitly: "The design generation pipeline had a partial failure \u2014 your scaffolded landing may not match the picker preview exactly. The build will continue with fallback design tokens. If the deployed landing looks wrong, run mist_plan({ description: '<original description>' }) again to get a fresh picker." Then continue with the install step. Do not silently proceed.`);let be=`${E?`TELL THE USER: "Your app's URL is reserved: https://${E}.mistflow.app \u2014 it goes live when you deploy. While it's being built, you'll get a local preview to watch your app come together in real time." `:""}NEXT: Call mist_install({ projectPath: "${h}" }). This is fire-and-poll \u2014 the first call returns a jobId and status: "running"; re-call with the same jobId every ~15-30s until status is "complete". Typical duration 30-90s. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. After install completes, call mist_implement({ projectPath: "${h}" }) to build the first plan step.`;return de.nextAction=D?be:`${be} NOTE: The project could not be registered with the backend during init (${G??"see registrationWarning"}). mist_deploy will retry the registration automatically on the first deploy \u2014 no manual recovery needed.`,d(JSON.stringify(de))}catch(R){try{Dc(h,{recursive:!0,force:!0})}catch{}throw R}}var Ho={name:"mist_init",description:"Initialize a new Next.js project using the Mistflow stack. Downloads templates from the Mistflow registry, installs dependencies, sets up auth, and initializes git. Use this after mist_plan to create the project.",inputSchema:zc,handler:wd};import{z as yn}from"zod";import{existsSync as gt,readFileSync as us,writeFileSync as or,mkdirSync as ji}from"fs";import{join as He,resolve as lp,dirname as cp}from"path";_e();import{createConnection as dp}from"net";var Wo=`# Consumer Warm Archetype
2783
2783
 
2784
2784
  Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
2785
2785
 
@@ -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 ti={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Wo},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:Go},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Vo},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Ko},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Jo},"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:Yo},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Qo},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:Xo},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:Zo},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:ei}};var dg=Object.keys(ti);function ni(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return ti[e]}import{createServer as Hd}from"net";import{existsSync as Zn,readFileSync as hi,writeFileSync as gi,mkdirSync as fi}from"fs";import{join as er}from"path";import{spawn as Wd}from"child_process";import{spawn as Rd,execFileSync as Ed}from"child_process";import{existsSync as Qn,mkdirSync as oi,openSync as ds,closeSync as ps,readSync as Nd,readFileSync as ii,writeFileSync as ai,renameSync as li,unlinkSync as Od,readdirSync as hg,statSync as Dd}from"fs";import{homedir as ci}from"os";import{join as $e,dirname as di}from"path";import{randomBytes as pi,randomUUID as jd}from"crypto";var ui=1,Md=`// Generated by @mistflow-ai/mcp local-jobs (v${ui}). Do not edit.
4769
+ `;var ti={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Wo},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:Go},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Vo},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Ko},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Jo},"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:Yo},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:Qo},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:Xo},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:Zo},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:ei}};var ug=Object.keys(ti);function ni(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return ti[e]}import{createServer as Hd}from"net";import{existsSync as tr,readFileSync as hi,writeFileSync as gi,mkdirSync as fi}from"fs";import{join as nr}from"path";import{spawn as Wd}from"child_process";import{spawn as Rd,execFileSync as Ed}from"child_process";import{existsSync as Zn,mkdirSync as oi,openSync as ds,closeSync as ps,readSync as Nd,readFileSync as ii,writeFileSync as ai,renameSync as li,unlinkSync as Od,readdirSync as fg,statSync as Dd}from"fs";import{homedir as ci}from"os";import{join as $e,dirname as di}from"path";import{randomBytes as pi,randomUUID as jd}from"crypto";var ui=1,Md=`// Generated by @mistflow-ai/mcp local-jobs (v${ui}). 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,12 +4830,12 @@ child.on('error', (err) => {
4830
4830
  });
4831
4831
  process.exit(1);
4832
4832
  });
4833
- `;function Xn(){return $e(ci(),".mistflow","jobs")}function Ld(){return $e(ci(),".mistflow","job-wrapper.cjs")}function $d(){let t=Ld(),e=di(t);Qn(e)||oi(e,{recursive:!0});let r=`v${ui}`;if(Qn(t))try{if(ii(t,"utf-8").includes(r))return t}catch{}let n=$e(e,`.job-wrapper.tmp.${pi(6).toString("hex")}`);return ai(n,Md),li(n,t),t}function Ht(t){return $e(Xn(),t)}function mi(t){return $e(Ht(t),"status.json")}function ri(t,e){let r=mi(t),n=$e(di(r),`.status.tmp.${pi(6).toString("hex")}`);try{ai(n,JSON.stringify(e,null,2)+`
4834
- `),li(n,r)}catch(i){try{Od(n)}catch{}throw i}}function Ud(t){let e=mi(t);if(!Qn(e))return null;try{return JSON.parse(ii(e,"utf-8"))}catch{return null}}async function mt(t){let e=`job_${jd().replace(/-/g,"").slice(0,12)}`,r=Ht(e);oi(r,{recursive:!0}),ps(ds($e(r,"stdout.log"),"a")),ps(ds($e(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};ri(e,i);let o=$d(),s={...process.env,...t.env??{}},a=Rd("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 ri(e,l),l}function Fd(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function qd(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=Ed("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=Fd(r),i=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(i)&&Math.abs(n-i)>2e3)return!1}catch{}return!0}function Bd(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 si(t,e){if(!Qn(t))return"";let r=Dd(t);if(r.size===0)return"";let n=r.size>e?r.size-e:0,i=r.size-n,o=ds(t,"r");try{let s=Buffer.alloc(i);return Nd(o,s,0,i,n),s.toString("utf-8")}finally{ps(o)}}function zd(t,e=200){let r=si($e(Ht(t),"stdout.log"),65536),n=si($e(Ht(t),"stderr.log"),64*1024),i=[];return r.trim()&&i.push(...r.split(`
4833
+ `;function er(){return $e(ci(),".mistflow","jobs")}function Ld(){return $e(ci(),".mistflow","job-wrapper.cjs")}function $d(){let t=Ld(),e=di(t);Zn(e)||oi(e,{recursive:!0});let r=`v${ui}`;if(Zn(t))try{if(ii(t,"utf-8").includes(r))return t}catch{}let n=$e(e,`.job-wrapper.tmp.${pi(6).toString("hex")}`);return ai(n,Md),li(n,t),t}function Ht(t){return $e(er(),t)}function mi(t){return $e(Ht(t),"status.json")}function ri(t,e){let r=mi(t),n=$e(di(r),`.status.tmp.${pi(6).toString("hex")}`);try{ai(n,JSON.stringify(e,null,2)+`
4834
+ `),li(n,r)}catch(i){try{Od(n)}catch{}throw i}}function Ud(t){let e=mi(t);if(!Zn(e))return null;try{return JSON.parse(ii(e,"utf-8"))}catch{return null}}async function mt(t){let e=`job_${jd().replace(/-/g,"").slice(0,12)}`,r=Ht(e);oi(r,{recursive:!0}),ps(ds($e(r,"stdout.log"),"a")),ps(ds($e(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};ri(e,i);let o=$d(),s={...process.env,...t.env??{}},a=Rd("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 ri(e,l),l}function Fd(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function qd(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=Ed("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=Fd(r),i=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(i)&&Math.abs(n-i)>2e3)return!1}catch{}return!0}function Bd(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 si(t,e){if(!Zn(t))return"";let r=Dd(t);if(r.size===0)return"";let n=r.size>e?r.size-e:0,i=r.size-n,o=ds(t,"r");try{let s=Buffer.alloc(i);return Nd(o,s,0,i,n),s.toString("utf-8")}finally{ps(o)}}function zd(t,e=200){let r=si($e(Ht(t),"stdout.log"),65536),n=si($e(Ht(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 It(t){return{stdout:$e(Ht(t),"stdout.log"),stderr:$e(Ht(t),"stderr.log")}}async function ht(t){let e=Ud(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!qd(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:Bd(r.startedAt,r.endedAt),logTail:zd(t)}}async function Wt(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 ht(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 yi(){let t=(process.env.MISTFLOW_VISUAL_CONTEXT??"full").toLowerCase();return t==="off"||t==="preview"||t==="full"?t:"full"}function bi(t){return er(t,".mistflow","visual-context.json")}function wi(t){let e=bi(t);if(!Zn(e))return{screenshotsTaken:0,lastScreenshotStep:0};try{return JSON.parse(hi(e,"utf-8"))}catch{return{screenshotsTaken:0,lastScreenshotStep:0}}}function Gd(t,e){let r=er(t,".mistflow");Zn(r)||fi(r,{recursive:!0}),gi(bi(t),JSON.stringify(e,null,2)+`
4838
- `)}var Vd=5;function vi(t,e,r){if(yi()!=="full")return!1;let n=wi(t);return n.screenshotsTaken>=Vd?!1:n.screenshotsTaken===0||r>0&&e>=r||e>0&&e!==n.lastScreenshotStep&&e%3===0}function ki(t,e){let r=wi(t);Gd(t,{screenshotsTaken:r.screenshotsTaken+1,lastScreenshotStep:e})}async function Kd(){return new Promise((t,e)=>{let r=Hd();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 xi(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 Si(t){return er(t,".mistflow","preview.json")}function Ti(t){let e=Si(t);if(!Zn(e))return null;try{return JSON.parse(hi(e,"utf-8"))}catch{return null}}function _i(t){return Ti(t)}function Jd(t,e){let r=er(t,".mistflow");Zn(r)||fi(r,{recursive:!0}),gi(Si(t),JSON.stringify(e,null,2)+`
4837
+ `)}function It(t){return{stdout:$e(Ht(t),"stdout.log"),stderr:$e(Ht(t),"stderr.log")}}async function ht(t){let e=Ud(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!qd(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:Bd(r.startedAt,r.endedAt),logTail:zd(t)}}async function Wt(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 ht(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 yi(){let t=(process.env.MISTFLOW_VISUAL_CONTEXT??"full").toLowerCase();return t==="off"||t==="preview"||t==="full"?t:"full"}function bi(t){return nr(t,".mistflow","visual-context.json")}function wi(t){let e=bi(t);if(!tr(e))return{screenshotsTaken:0,lastScreenshotStep:0};try{return JSON.parse(hi(e,"utf-8"))}catch{return{screenshotsTaken:0,lastScreenshotStep:0}}}function Gd(t,e){let r=nr(t,".mistflow");tr(r)||fi(r,{recursive:!0}),gi(bi(t),JSON.stringify(e,null,2)+`
4838
+ `)}var Vd=5;function vi(t,e,r){if(yi()!=="full")return!1;let n=wi(t);return n.screenshotsTaken>=Vd?!1:n.screenshotsTaken===0||r>0&&e>=r||e>0&&e!==n.lastScreenshotStep&&e%3===0}function ki(t,e){let r=wi(t);Gd(t,{screenshotsTaken:r.screenshotsTaken+1,lastScreenshotStep:e})}async function Kd(){return new Promise((t,e)=>{let r=Hd();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 xi(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 Si(t){return nr(t,".mistflow","preview.json")}function Ti(t){let e=Si(t);if(!tr(e))return null;try{return JSON.parse(hi(e,"utf-8"))}catch{return null}}function _i(t){return Ti(t)}function Jd(t,e){let r=nr(t,".mistflow");tr(r)||fi(r,{recursive:!0}),gi(Si(t),JSON.stringify(e,null,2)+`
4839
4839
  `)}async function Ii(t){if(yi()==="off")return null;let e=Ti(t);if(e){let n=await ht(e.jobId);if(n&&(n.status==="running"||n.status==="starting"))return{state:e,freshlyStarted:!1}}let r;try{r=await Kd()}catch{return null}try{let n=await mt({type:"preview",cmd:"sh",args:["-c",`npm run dev -- --port ${r}`],cwd:t});await new Promise(a=>setTimeout(a,600));let i=await ht(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 Jd(t,s),{state:s,freshlyStarted:!0}}catch{return null}}function Pi(t){try{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];Wd(e,r,{detached:!0,stdio:"ignore"}).unref()}catch{}}var Ci=`# Design Doctrine
4840
4840
 
4841
4841
  This is the standard for every UI you generate. It is not aspirational. It is the floor.
@@ -5299,18 +5299,18 @@ If there's a pricing page:
5299
5299
  ## The Footer
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
- `;import{existsSync as rp,readFileSync as sp,writeFileSync as op}from"fs";import{join as ip}from"path";import{z as fn}from"zod";var tr=fn.object({key:fn.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:fn.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:fn.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:fn.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),ap=/^[A-Z][A-Z0-9_]*$/;function nr(t,e){if(e.length===0)return{added:[],skipped:[]};let r=ip(t,"mistflow.json");if(!rp(r))throw new Error(`mistflow.json not found at ${t}`);let n=sp(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"||!ap.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&&op(r,JSON.stringify(i,null,2)+`
5303
- `),{added:s,skipped:a}}function pp(t){return new Promise(e=>{let r=dp({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}var up=yn.object({projectPath:yn.string().optional().describe("Path to the project directory (default: cwd)"),step:yn.number().optional().describe("Specific step number to implement (default: next incomplete step)"),sessionId:yn.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:yn.array(tr).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 mp(t){let e=He(t,"mistflow.json");if(!gt(e))return null;try{return JSON.parse(us(e,"utf-8"))}catch{return null}}function Mi(t,e){let r=He(t,"mistflow.json");rr(r,JSON.stringify(e,null,2)+`
5304
- `),Ft(t)}function sr(t){return t.entity??t.name??"Unknown"}function hp(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Li(t){return t.path??t.route??t.name??""}function gp(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 $i(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=sr(n).toLowerCase();return r.some(o=>i.includes(o)||o.includes(i))})}function fp(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=Li(n).toLowerCase();return r.some(s=>i.includes(s)||s.includes(i)||o.includes(s))})}var yp=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function bp(t){let e=t.stepType;if(e&&yp.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 wp(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 vp(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=ni(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(`
5302
+ `;import{existsSync as rp,readFileSync as sp,writeFileSync as op}from"fs";import{join as ip}from"path";import{z as fn}from"zod";var rr=fn.object({key:fn.string().describe("SHOUTING_SNAKE_CASE env var name, e.g. OPENAI_API_KEY"),description:fn.string().describe("Plain-English description, e.g. 'OpenAI API key for AI features'"),setupUrl:fn.string().optional().describe("URL where the user can obtain this key, e.g. https://platform.openai.com/api-keys"),integration:fn.string().optional().describe("Optional integration name this key belongs to, e.g. 'OpenAI'")}),ap=/^[A-Z][A-Z0-9_]*$/;function sr(t,e){if(e.length===0)return{added:[],skipped:[]};let r=ip(t,"mistflow.json");if(!rp(r))throw new Error(`mistflow.json not found at ${t}`);let n=sp(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"||!ap.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&&op(r,JSON.stringify(i,null,2)+`
5303
+ `),{added:s,skipped:a}}function pp(t){return new Promise(e=>{let r=dp({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}var up=yn.object({projectPath:yn.string().optional().describe("Path to the project directory (default: cwd)"),step:yn.number().optional().describe("Specific step number to implement (default: next incomplete step)"),sessionId:yn.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:yn.array(rr).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 mp(t){let e=He(t,"mistflow.json");if(!gt(e))return null;try{return JSON.parse(us(e,"utf-8"))}catch{return null}}function Mi(t,e){let r=He(t,"mistflow.json");or(r,JSON.stringify(e,null,2)+`
5304
+ `),Ft(t)}function ir(t){return t.entity??t.name??"Unknown"}function hp(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Li(t){return t.path??t.route??t.name??""}function gp(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 $i(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=ir(n).toLowerCase();return r.some(o=>i.includes(o)||o.includes(i))})}function fp(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=Li(n).toLowerCase();return r.some(s=>i.includes(s)||s.includes(i)||o.includes(s))})}var yp=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function bp(t){let e=t.stepType;if(e&&yp.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 wp(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 vp(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=ni(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 kp(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 xp(t){try{let e=await Dr("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 Sp(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(vp(e.design)),s.push("");let _=o?He(o,".mistflow","rules","design-quality.md"):null;_&&gt(_)?(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(Kn),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 _=wo(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 x of _){let y=x.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 m=e.dataModel?$i(t,e.dataModel):[];m.length>0&&(s.push("### Data model (from plan):"),m.forEach(_=>{let x=sr(_),y=hp(_.fields);s.push(`- **${x}**: ${y}`),s.push(` Schema file: \`db/schema/${x.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let p=e.pages?fp(t,e.pages):[];if(p.length>0&&(s.push("### Pages to create/update:"),p.forEach(_=>{let x=_.description?` \u2014 ${_.description}`:"";s.push(`- \`${Li(_)}\`${x}`)}),s.push("")),i==="crud"&&m.length>0&&m.forEach(_=>{let x=sr(_),y=x.toLowerCase().replace(/\s+/g,"-"),P=y.endsWith("s")?y:`${y}s`;s.push(`### Files for ${x} CRUD:`),s.push(`- List page: \`app/(dashboard)/${P}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${P}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${P}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${P}/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(Ci),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(Ai),s.push(""),s.push("### Color"),s.push(Ri),s.push(""),s.push("### Motion"),s.push(Ei),s.push(""),s.push("### Spatial Composition"),s.push(Ni),s.push(""),s.push("### Interaction"),s.push(Oi),s.push(""),s.push("### UX Writing"),s.push(Di),s.push("");let _=o?He(o,"DESIGN.md"):void 0,x=_&&gt(_)?(()=>{try{return us(_,"utf-8")}catch{return null}})():null;x&&(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(x),s.push(""));let y=o?He(o,".mistflow","picker-render.html"):void 0;(i==="landing"||i==="design")&&y&&gt(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?He(o,".mistflow","rules","landing.md"):null;_&&gt(_)?(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(Jn),s.push(""))}i==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(s.push(kp(e.layoutSpec)),s.push(""));let u=t.integrationId?jt(t.integrationId):void 0;if(u){let _=Mt(u.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${u.name}** (${u.category})`),_?.docsUrl&&s.push(`Official docs: ${_.docsUrl}`),_?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let x of _.envVars)s.push(`- \`${x.key}\`: ${x.description} \u2014 Get it at ${x.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(u.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:g,skill:D}=await xp(i);return s.push(g),s.push(""),D&&(s.push(`### ${i} reference:`),s.push(D),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 Tp(t){let{projectPath:e,step:r,envVarsRequired:n,sessionId:i}=t,o=lp(e??process.cwd());if(n&&n.length>0)try{let S=nr(o,n);S.added.length>0&&console.error(`[implement] declared env.required: ${S.added.join(", ")}`)}catch(S){console.error("[implement] env var merge skipped:",S instanceof Error?S.message:String(S))}let s=mp(o);if(!s)return Xe(o);if(!gt(He(o,"node_modules")))return d(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:S,ensureShadcnComponents:M}=await Promise.resolve().then(()=>(Vr(),Gr)),ee=await S(o);ee&&!s.projectId&&(s.projectId=ee);let te=await M(o);te.failed?console.error(`[implement] ${te.failed}`):te.installed.length>0&&console.error(`[implement] installed ${te.installed.length} shadcn components`)}catch(S){console.error("[implement] self-heal skipped:",S instanceof Error?S.message:String(S))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return d("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let l,c=a.steps.find(S=>S.status==="in_progress");if(c){let S=a.steps.findIndex(M=>M.number===c.number);S!==-1&&(a.steps[S].status="completed",l=`Auto-completed step ${c.number} (${c.name})`,Mi(o,s))}let m;if(r!==void 0){if(m=a.steps.find(S=>S.number===r),!m)return d(`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(m=a.steps.find(S=>S.status!=="completed"),!m)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(S=>S.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let p=a.steps.filter(S=>S.status==="completed").map(S=>`Step ${S.number}: ${S.name}`),{readLocalState:u}=await Promise.resolve().then(()=>(xt(),an)),g=u(o),D=bp(m),_=[];if((D==="crud"||D==="schema")&&a.dataModel&&m.entities&&m.entities.length>0){let S=$i(m,a.dataModel);for(let M of S){let ee=sr(M);try{let te=(M.fields||[]).map(re=>typeof re=="string"?{name:re,type:"text"}:{name:re.name,type:gp(re.type),required:re.required!==!1});if(te.length===0)continue;let C=s.dbProvider==="neon"?"nextjs-neon":"nextjs",ve=await Lr(C,ee,te),$=0,ge=0;for(let re of ve.files){let ye=He(o,re.path);if(gt(ye)){ge++;continue}ji(cp(ye),{recursive:!0}),rr(ye,re.content),$++}let Ce=He(o,"db","index.ts");if(gt(Ce)){let re=us(Ce,"utf-8");re.includes(ve.dbExport)||rr(Ce,re.trimEnd()+`
5309
+ - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Sp(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(vp(e.design)),s.push("");let _=o?He(o,".mistflow","rules","design-quality.md"):null;_&&gt(_)?(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(Yn),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 _=wo(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 x of _){let y=x.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 m=e.dataModel?$i(t,e.dataModel):[];m.length>0&&(s.push("### Data model (from plan):"),m.forEach(_=>{let x=ir(_),y=hp(_.fields);s.push(`- **${x}**: ${y}`),s.push(` Schema file: \`db/schema/${x.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let p=e.pages?fp(t,e.pages):[];if(p.length>0&&(s.push("### Pages to create/update:"),p.forEach(_=>{let x=_.description?` \u2014 ${_.description}`:"";s.push(`- \`${Li(_)}\`${x}`)}),s.push("")),i==="crud"&&m.length>0&&m.forEach(_=>{let x=ir(_),y=x.toLowerCase().replace(/\s+/g,"-"),P=y.endsWith("s")?y:`${y}s`;s.push(`### Files for ${x} CRUD:`),s.push(`- List page: \`app/(dashboard)/${P}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${P}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${P}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${P}/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(Ci),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(Ai),s.push(""),s.push("### Color"),s.push(Ri),s.push(""),s.push("### Motion"),s.push(Ei),s.push(""),s.push("### Spatial Composition"),s.push(Ni),s.push(""),s.push("### Interaction"),s.push(Oi),s.push(""),s.push("### UX Writing"),s.push(Di),s.push("");let _=o?He(o,"DESIGN.md"):void 0,x=_&&gt(_)?(()=>{try{return us(_,"utf-8")}catch{return null}})():null;x&&(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(x),s.push(""));let y=o?He(o,".mistflow","picker-render.html"):void 0;(i==="landing"||i==="design")&&y&&gt(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?He(o,".mistflow","rules","landing.md"):null;_&&gt(_)?(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(Qn),s.push(""))}i==="landing"&&e.layoutSpec&&Array.isArray(e.layoutSpec.sections)&&(s.push(kp(e.layoutSpec)),s.push(""));let u=t.integrationId?jt(t.integrationId):void 0;if(u){let _=Mt(u.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${u.name}** (${u.category})`),_?.docsUrl&&s.push(`Official docs: ${_.docsUrl}`),_?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let x of _.envVars)s.push(`- \`${x.key}\`: ${x.description} \u2014 Get it at ${x.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(u.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:h,skill:N}=await xp(i);return s.push(h),s.push(""),N&&(s.push(`### ${i} reference:`),s.push(N),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 Tp(t){let{projectPath:e,step:r,envVarsRequired:n,sessionId:i}=t,o=lp(e??process.cwd());if(n&&n.length>0)try{let S=sr(o,n);S.added.length>0&&console.error(`[implement] declared env.required: ${S.added.join(", ")}`)}catch(S){console.error("[implement] env var merge skipped:",S instanceof Error?S.message:String(S))}let s=mp(o);if(!s)return Xe(o);if(!gt(He(o,"node_modules")))return d(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:S,ensureShadcnComponents:M}=await Promise.resolve().then(()=>(Vr(),Gr)),ee=await S(o);ee&&!s.projectId&&(s.projectId=ee);let te=await M(o);te.failed?console.error(`[implement] ${te.failed}`):te.installed.length>0&&console.error(`[implement] installed ${te.installed.length} shadcn components`)}catch(S){console.error("[implement] self-heal skipped:",S instanceof Error?S.message:String(S))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return d("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let l,c=a.steps.find(S=>S.status==="in_progress");if(c){let S=a.steps.findIndex(M=>M.number===c.number);S!==-1&&(a.steps[S].status="completed",l=`Auto-completed step ${c.number} (${c.name})`,Mi(o,s))}let m;if(r!==void 0){if(m=a.steps.find(S=>S.number===r),!m)return d(`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(m=a.steps.find(S=>S.status!=="completed"),!m)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(S=>S.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let p=a.steps.filter(S=>S.status==="completed").map(S=>`Step ${S.number}: ${S.name}`),{readLocalState:u}=await Promise.resolve().then(()=>(xt(),an)),h=u(o),N=bp(m),_=[];if((N==="crud"||N==="schema")&&a.dataModel&&m.entities&&m.entities.length>0){let S=$i(m,a.dataModel);for(let M of S){let ee=ir(M);try{let te=(M.fields||[]).map(re=>typeof re=="string"?{name:re,type:"text"}:{name:re.name,type:gp(re.type),required:re.required!==!1});if(te.length===0)continue;let C=s.dbProvider==="neon"?"nextjs-neon":"nextjs",ve=await Lr(C,ee,te),$=0,ge=0;for(let re of ve.files){let ye=He(o,re.path);if(gt(ye)){ge++;continue}ji(cp(ye),{recursive:!0}),or(ye,re.content),$++}let Ce=He(o,"db","index.ts");if(gt(Ce)){let re=us(Ce,"utf-8");re.includes(ve.dbExport)||or(Ce,re.trimEnd()+`
5311
5311
  `+ve.dbExport+`
5312
- `)}$>0?_.push(`${ve.entityPascal} CRUD (${$} new files${ge>0?`, ${ge} existing skipped`:""})`):ge>0&&_.push(`${ve.entityPascal} CRUD (all ${ge} files already exist \u2014 skipped)`)}catch(te){console.error(`Module generation failed for ${ee} (non-fatal):`,te instanceof Error?te.message:te)}}}let x=await Sp(m,a,p,null,D,o),y=3e4,P=null;if(x.length>y){let S=He(o,".mistflow","instructions");try{ji(S,{recursive:!0});let M=`step-${m.number}.md`,ee=He(S,M);rr(ee,x,"utf-8"),P=`.mistflow/instructions/${M}`,x=[x.slice(0,5e3),"","---",`**Instruction continues in ${P}** (${x.length.toLocaleString()} chars total).`,"",`Read the full file before writing code: \`Read(${P})\`. The truncated portion above contains step framing; the file contains the detailed prescriptive guidance, layout specs, design tokens, and per-section instructions.`].join(`
5313
- `)}catch(M){console.error("implement-step: failed to write overflow instruction file:",M instanceof Error?M.message:M),x=x.slice(0,y-500)+"\n\n---\n**Instruction was truncated** to fit the tool-result size cap. Detailed guidance for this step (design tokens, layout spec, anti-slop rules) lives in `.mistflow/rules/` and `methodologies/` \u2014 read those for the full context."}}let z=a.steps.findIndex(S=>S.number===m.number);if(z!==-1&&(s.plan.steps[z].status="in_progress",Mi(o,s)),g&&s.projectId){let{syncRemoteState:S}=await Promise.resolve().then(()=>(xt(),an));S(s.projectId,g).catch(()=>{})}let V=a.steps.every(S=>S.status==="completed"||S.number===m.number),Z;V?Z=`THIS IS THE LAST STEP. Rules for speed:
5312
+ `)}$>0?_.push(`${ve.entityPascal} CRUD (${$} new files${ge>0?`, ${ge} existing skipped`:""})`):ge>0&&_.push(`${ve.entityPascal} CRUD (all ${ge} files already exist \u2014 skipped)`)}catch(te){console.error(`Module generation failed for ${ee} (non-fatal):`,te instanceof Error?te.message:te)}}}let x=await Sp(m,a,p,null,N,o),y=3e4,P=null;if(x.length>y){let S=He(o,".mistflow","instructions");try{ji(S,{recursive:!0});let M=`step-${m.number}.md`,ee=He(S,M);or(ee,x,"utf-8"),P=`.mistflow/instructions/${M}`,x=[x.slice(0,5e3),"","---",`**Instruction continues in ${P}** (${x.length.toLocaleString()} chars total).`,"",`Read the full file before writing code: \`Read(${P})\`. The truncated portion above contains step framing; the file contains the detailed prescriptive guidance, layout specs, design tokens, and per-section instructions.`].join(`
5313
+ `)}catch(M){console.error("implement-step: failed to write overflow instruction file:",M instanceof Error?M.message:M),x=x.slice(0,y-500)+"\n\n---\n**Instruction was truncated** to fit the tool-result size cap. Detailed guidance for this step (design tokens, layout spec, anti-slop rules) lives in `.mistflow/rules/` and `methodologies/` \u2014 read those for the full context."}}let z=a.steps.findIndex(S=>S.number===m.number);if(z!==-1&&(s.plan.steps[z].status="in_progress",Mi(o,s)),h&&s.projectId){let{syncRemoteState:S}=await Promise.resolve().then(()=>(xt(),an));S(s.projectId,h).catch(()=>{})}let V=a.steps.every(S=>S.status==="completed"||S.number===m.number),Z;V?Z=`THIS IS THE LAST STEP. Rules for speed:
5314
5314
 
5315
5315
  1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
5316
5316
  2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
@@ -5327,14 +5327,14 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
5327
5327
  2. Write ALL files for this step using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message. Do NOT write one file at a time.
5328
5328
  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.
5329
5329
  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).
5330
- 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 ae=wp(D),L={stepNumber:m.number,totalSteps:a.steps.length,estimatedMinutes:ae,announcement:`Starting step ${m.number} of ${a.steps.length}: ${m.name}. This step usually takes ${ae.min}\u2013${ae.max} minutes.`},A=JSON.stringify({instruction:x,...P?{instructionFilePath:P}:{},step:{number:m.number,name:m.name,description:m.description,status:"in_progress"},stepTiming:L,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:`${p.length}/${a.steps.length} steps done`,nextAction:Z}),X=_i(o),K=X?.url??"http://localhost:3000",W=X?.port??3e3;return await pp(W)&&vi(o,m.number,a.steps.length)?(ki(o,m.number),Ns(K,A)):d(A)}var Ui={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:up,handler:Tp};import{z as We}from"zod";import{z as ft}from"zod";import{resolve as _p}from"path";_e();wt();var df=ft.object({projectPath:ft.string().optional().describe("Path to the project directory (default: cwd)"),action:ft.enum(["set","list","delete"]).describe("Action to perform"),key:ft.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:ft.string().optional().describe("Environment variable value (required for 'set')"),category:ft.string().optional().describe("Category for the env var (default: 'custom')"),description:ft.string().optional().describe("Description of what this env var is for"),setupUrl:ft.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function Fi(t){let{projectPath:e,action:r,key:n,value:i,category:o,description:s,setupUrl:a}=t,l=_p(e??process.cwd());if(!xe())return Ne("manage env vars");let m=it(l)?.projectId;if(!m)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"set":return n?i?(await Pr(m,n,i,{category:o,description:s,setupUrl:a}),d(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):d("Value is required. Provide the env var value.",!0):d("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let p=await Ir(m);return p.length===0?d(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):d(JSON.stringify({envVars:p.map(u=>({key:u.key,category:u.category,description:u.description,hasValue:u.has_value})),message:`${p.length} environment variable(s) configured.`}))}case"delete":return n?(await Cr(m,n),d(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):d("Key is required. Provide the env var name to delete.",!0);default:return d(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(p){if(p instanceof J)return d(p.message,!0);let u=p instanceof Error?p.message:"An unexpected error occurred";return d(u,!0)}}import{z as bn}from"zod";import{resolve as Ip,join as Pp}from"path";import{existsSync as Cp,readFileSync as Ap,writeFileSync as Rp}from"fs";_e();wt();var bf=bn.object({projectPath:bn.string().optional().describe("Path to the project directory (default: cwd)"),action:bn.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:bn.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:bn.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function ms(t,e){let r=Pp(t,"mistflow.json");if(!Cp(r))return;let n;try{n=JSON.parse(Ap(r,"utf-8"))}catch{return}n.domains=e,Rp(r,JSON.stringify(n,null,2)+`
5331
- `)}async function qi(t){let{projectPath:e,action:r,domain:n,domainId:i}=t,o=Ip(e??process.cwd());if(!xe())return Ne("manage custom domains");let a=it(o)?.projectId;if(!a)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!n)return d("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Sr(a,n),c=await lt(a);return ms(o,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await lt(a);return l.length===0?d(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):d(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!i){if(n){let p=(await lt(a)).find(u=>u.domain===n);if(p){let u=await jn(a,p.id);return d(JSON.stringify({domain:u.domain,status:u.status,ssl:u.ssl_status,error:u.error_message,message:u.status==="active"?`Domain '${u.domain}' is active and serving traffic.`:`Domain '${u.domain}' is ${u.status}. Make sure DNS records are configured correctly.`}))}return d(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return d("Provide either domainId or domain name to verify.",!0)}let l=await jn(a,i),c=await lt(a);return ms(o,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!i&&!n)return d("Provide either domainId or domain name to remove.",!0);let l=i;if(!l&&n){let p=(await lt(a)).find(u=>u.domain===n);if(!p)return d(`Domain '${n}' not found.`,!0);l=p.id}await Tr(a,l);let c=await lt(a);return ms(o,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return d(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof J)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var Ep=We.object({resource:We.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:We.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:We.string().optional().describe("Path to the project directory (default: cwd)"),key:We.string().optional().describe("(env) Variable name"),value:We.string().optional().describe("(env set) Variable value"),category:We.string().optional().describe("(env set) Category"),description:We.string().optional().describe("(env set) Description"),setupUrl:We.string().optional().describe("(env set) URL to obtain the value"),domain:We.string().optional().describe("(domain) Domain name"),domainId:We.string().optional().describe("(domain) Domain ID")}),Bi={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:Ep,handler:async t=>{let e=t;switch(e.resource){case"env":return Fi({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return qi({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return d(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}};import{z as wn}from"zod";import{resolve as Np}from"path";import{existsSync as Op}from"fs";import{join as Dp}from"path";function jp(t,e=15){let r=t.split(`
5330
+ 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 ae=wp(N),L={stepNumber:m.number,totalSteps:a.steps.length,estimatedMinutes:ae,announcement:`Starting step ${m.number} of ${a.steps.length}: ${m.name}. This step usually takes ${ae.min}\u2013${ae.max} minutes.`},A=JSON.stringify({instruction:x,...P?{instructionFilePath:P}:{},step:{number:m.number,name:m.name,description:m.description,status:"in_progress"},stepTiming:L,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:`${p.length}/${a.steps.length} steps done`,nextAction:Z}),X=_i(o),K=X?.url??"http://localhost:3000",W=X?.port??3e3;return await pp(W)&&vi(o,m.number,a.steps.length)?(ki(o,m.number),Ns(K,A)):d(A)}var Ui={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:up,handler:Tp};import{z as We}from"zod";import{z as ft}from"zod";import{resolve as _p}from"path";_e();wt();var uf=ft.object({projectPath:ft.string().optional().describe("Path to the project directory (default: cwd)"),action:ft.enum(["set","list","delete"]).describe("Action to perform"),key:ft.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:ft.string().optional().describe("Environment variable value (required for 'set')"),category:ft.string().optional().describe("Category for the env var (default: 'custom')"),description:ft.string().optional().describe("Description of what this env var is for"),setupUrl:ft.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function Fi(t){let{projectPath:e,action:r,key:n,value:i,category:o,description:s,setupUrl:a}=t,l=_p(e??process.cwd());if(!xe())return Ne("manage env vars");let m=it(l)?.projectId;if(!m)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"set":return n?i?(await Pr(m,n,i,{category:o,description:s,setupUrl:a}),d(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):d("Value is required. Provide the env var value.",!0):d("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let p=await Ir(m);return p.length===0?d(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):d(JSON.stringify({envVars:p.map(u=>({key:u.key,category:u.category,description:u.description,hasValue:u.has_value})),message:`${p.length} environment variable(s) configured.`}))}case"delete":return n?(await Cr(m,n),d(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):d("Key is required. Provide the env var name to delete.",!0);default:return d(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(p){if(p instanceof J)return d(p.message,!0);let u=p instanceof Error?p.message:"An unexpected error occurred";return d(u,!0)}}import{z as bn}from"zod";import{resolve as Ip,join as Pp}from"path";import{existsSync as Cp,readFileSync as Ap,writeFileSync as Rp}from"fs";_e();wt();var vf=bn.object({projectPath:bn.string().optional().describe("Path to the project directory (default: cwd)"),action:bn.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:bn.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:bn.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function ms(t,e){let r=Pp(t,"mistflow.json");if(!Cp(r))return;let n;try{n=JSON.parse(Ap(r,"utf-8"))}catch{return}n.domains=e,Rp(r,JSON.stringify(n,null,2)+`
5331
+ `)}async function qi(t){let{projectPath:e,action:r,domain:n,domainId:i}=t,o=Ip(e??process.cwd());if(!xe())return Ne("manage custom domains");let a=it(o)?.projectId;if(!a)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!n)return d("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Sr(a,n),c=await lt(a);return ms(o,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await lt(a);return l.length===0?d(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):d(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!i){if(n){let p=(await lt(a)).find(u=>u.domain===n);if(p){let u=await Ln(a,p.id);return d(JSON.stringify({domain:u.domain,status:u.status,ssl:u.ssl_status,error:u.error_message,message:u.status==="active"?`Domain '${u.domain}' is active and serving traffic.`:`Domain '${u.domain}' is ${u.status}. Make sure DNS records are configured correctly.`}))}return d(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return d("Provide either domainId or domain name to verify.",!0)}let l=await Ln(a,i),c=await lt(a);return ms(o,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!i&&!n)return d("Provide either domainId or domain name to remove.",!0);let l=i;if(!l&&n){let p=(await lt(a)).find(u=>u.domain===n);if(!p)return d(`Domain '${n}' not found.`,!0);l=p.id}await Tr(a,l);let c=await lt(a);return ms(o,c.map(m=>({domain:m.domain,status:m.status}))),d(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return d(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof J)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var Ep=We.object({resource:We.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:We.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:We.string().optional().describe("Path to the project directory (default: cwd)"),key:We.string().optional().describe("(env) Variable name"),value:We.string().optional().describe("(env set) Variable value"),category:We.string().optional().describe("(env set) Category"),description:We.string().optional().describe("(env set) Description"),setupUrl:We.string().optional().describe("(env set) URL to obtain the value"),domain:We.string().optional().describe("(domain) Domain name"),domainId:We.string().optional().describe("(domain) Domain ID")}),Bi={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:Ep,handler:async t=>{let e=t;switch(e.resource){case"env":return Fi({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return qi({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return d(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}};import{z as wn}from"zod";import{resolve as Np}from"path";import{existsSync as Op}from"fs";import{join as Dp}from"path";function jp(t,e=15){let r=t.split(`
5332
5332
  `).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
5333
- `)}var Mp=wn.object({projectPath:wn.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:wn.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:wn.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:wn.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."}),zi={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:Mp,handler:async(t,e)=>{let r=t;if(r.jobId){let l=await ht(r.jobId);if(!l)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No install job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let c=r.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let p=l.elapsed,u=e?ze(e.server,e.progressToken,()=>`Install running (${p}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let g=await Wt(r.jobId,{timeoutMs:c*1e3,onPoll:D=>{p=D.elapsed}});g&&(l=g)}finally{u.stop()}}if(l.status==="running"||l.status==="starting")return d(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:jp(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 p=await Ii(l.cwd),u=!1;p&&p.freshlyStarted?(u=await xi(p.state.url,15e3),u&&Pi(p.state.url)):p&&(u=!0);let g=p?u?` PREVIEW: Live dev server at ${p.state.url} (browser opened). TELL THE USER: "Your app is rendering at ${p.state.url} \u2014 it'll refresh live as it's built."`:` PREVIEW: Dev server starting at ${p.state.url} (still compiling). TELL THE USER: "Open ${p.state.url} in your browser in ~30s \u2014 your app will appear there and refresh live as it's built."`:"";return d(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,...p?{previewUrl:p.state.url,previewReady:u}:{},nextAction:`Dependencies installed.${g} Run mist_implement next to start executing plan steps.`}))}let m=It(l.id);return d(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:m,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${m.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let n=Np(r.projectPath);if(!Op(Dp(n,"package.json")))return d(`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 mt({type:"install",cmd:"sh",args:["-c",s],cwd:n,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return d(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 Gt}from"zod";import{resolve as Lp,join as Ge}from"path";import{existsSync as Ve,readFileSync as Hi,statSync as $p,readdirSync as Up}from"fs";var Wi=100*1024;function Fp(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=Ge(i,s),l;try{l=$p(a)}catch{continue}l.isDirectory()?n.push(a):l.isFile()&&(e+=l.size)}}return e}function qp(t){if(!(Ve(Ge(t,"open-next.config.ts"))||Ve(Ge(t,"open-next.config.js"))))return null;let r=Ge(t,".open-next","worker.js");if(!Ve(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=Ge(t,".open-next","server-functions","default");if(!Ve(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=Fp(n);return i<Wi?`Build exited 0 but the server-functions bundle is only ${i} bytes (expected at least ${Wi}). 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 Bp=Gt.object({projectPath:Gt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Gt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Gt.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:Gt.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: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.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});function zp(t){let e=Ge(Xn(),t,"stdout.log"),r=Ge(Xn(),t,"stderr.log"),n="";try{Ve(e)&&(n+=Hi(e,"utf-8"))}catch{}try{Ve(r)&&(n+=`
5333
+ `)}var Mp=wn.object({projectPath:wn.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:wn.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start."),waitSeconds:wn.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:wn.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."}),zi={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:Mp,handler:async(t,e)=>{let r=t;if(r.jobId){let l=await ht(r.jobId);if(!l)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No install job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let c=r.waitSeconds??20;if(c>0&&(l.status==="running"||l.status==="starting")){let p=l.elapsed,u=e?ze(e.server,e.progressToken,()=>`Install running (${p}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let h=await Wt(r.jobId,{timeoutMs:c*1e3,onPoll:N=>{p=N.elapsed}});h&&(l=h)}finally{u.stop()}}if(l.status==="running"||l.status==="starting")return d(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:jp(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 p=await Ii(l.cwd),u=!1;p&&p.freshlyStarted?(u=await xi(p.state.url,15e3),u&&Pi(p.state.url)):p&&(u=!0);let h=p?u?` PREVIEW: Live dev server at ${p.state.url} (browser opened). TELL THE USER: "Your app is rendering at ${p.state.url} \u2014 it'll refresh live as it's built."`:` PREVIEW: Dev server starting at ${p.state.url} (still compiling). TELL THE USER: "Open ${p.state.url} in your browser in ~30s \u2014 your app will appear there and refresh live as it's built."`:"";return d(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,...p?{previewUrl:p.state.url,previewReady:u}:{},nextAction:`Dependencies installed.${h} Run mist_implement next to start executing plan steps.`}))}let m=It(l.id);return d(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:m,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${m.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let n=Np(r.projectPath);if(!Op(Dp(n,"package.json")))return d(`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 mt({type:"install",cmd:"sh",args:["-c",s],cwd:n,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return d(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 Gt}from"zod";import{resolve as Lp,join as Ge}from"path";import{existsSync as Ve,readFileSync as Hi,statSync as $p,readdirSync as Up}from"fs";var Wi=100*1024;function Fp(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=Ge(i,s),l;try{l=$p(a)}catch{continue}l.isDirectory()?n.push(a):l.isFile()&&(e+=l.size)}}return e}function qp(t){if(!(Ve(Ge(t,"open-next.config.ts"))||Ve(Ge(t,"open-next.config.js"))))return null;let r=Ge(t,".open-next","worker.js");if(!Ve(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=Ge(t,".open-next","server-functions","default");if(!Ve(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=Fp(n);return i<Wi?`Build exited 0 but the server-functions bundle is only ${i} bytes (expected at least ${Wi}). 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 Bp=Gt.object({projectPath:Gt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Gt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:Gt.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:Gt.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: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.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});function zp(t){let e=Ge(er(),t,"stdout.log"),r=Ge(er(),t,"stderr.log"),n="";try{Ve(e)&&(n+=Hi(e,"utf-8"))}catch{}try{Ve(r)&&(n+=`
5334
5334
  `+Hi(r,"utf-8"))}catch{}return n}function Hp(t,e=15){let r=t.split(`
5335
5335
  `).filter(n=>n.length>0);return r.length<=e?t:r.slice(-e).join(`
5336
- `)}function Wp(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 Gp(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${_t()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var Gi={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:Bp,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await ht(r.jobId);if(!c)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let m=r.waitSeconds??20;if(m>0&&(c.status==="running"||c.status==="starting")){let P=c.elapsed,z=e?ze(e.server,e.progressToken,()=>`Build running (${P}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let V=await Wt(r.jobId,{timeoutMs:m*1e3,onPoll:Z=>{P=Z.elapsed}});V&&(c=V)}finally{z.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Hp(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 P=qp(c.cwd);if(P){let z=It(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:z,error:P,nextAction:P+` Full build log: ${z.stdout} and ${z.stderr}.`}),!0)}return d(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let p=zp(c.id),u=Hn(p),g=Wp(p),D=Gp(p),_=It(c.id),x=` Full log: ${_.stdout} and ${_.stderr}.`,y=g.length>0?`Build failed with missing modules: ${g.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${x}`:D?`${D}${x}`:u.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${x}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${x}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:u,missingModules:g,logTail:c.logTail,logPaths:_,nextAction:y}),!0)}let n=Lp(r.projectPath);if(!Ve(Ge(n,"package.json")))return d(`No package.json at ${n}. Run mist_init first.`,!0);if(!Ve(Ge(n,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let i,o,s,a=Ve(Ge(n,"open-next.config.ts"))||Ve(Ge(n,"open-next.config.js"));if(r.script)i="npm",o=["run",r.script],s=r.script;else if(a){if(!Ut())return d(_t(),!0);i="npx",o=["-y","@opennextjs/cloudflare","build"],s="@opennextjs/cloudflare build"}else i="npm",o=["run","build"],s="build";let l=await mt({type:"build",cmd:i,args:o,cwd:n});return d(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 Qp,readFileSync as Xp}from"fs";import{join as Zp}from"path";import{z as Vt}from"zod";_e();_e();import{existsSync as Vp,readdirSync as Kp}from"fs";import{join as Vi}from"path";import{pathToFileURL as Jp}from"url";async function Yp(t){let e=Vi(t,".mistflow","acceptance"),r=new Map;if(!Vp(e))return r;let n=Kp(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=Vi(e,i);try{let a=await import(Jp(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 Ki(t,e){let{sessionId:r,projectPath:n,deployUrl:i,seedCredentials:o}=e,a=(await tn(r)).criteria,l=await Yp(n),c=[];for(let m of a){let p=l.get(m.id);if(!p){c.push({criterion_id:m.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${m.id}.spec.ts`}});continue}try{await t.goto(i,{waitUntil:"domcontentloaded"});let u=await p(t,{url:i,criterion:m,seedCredentials:o});c.push({criterion_id:m.id,status:u.pass?"pass":"fail",evidence:{...u.detail?{detail:u.detail}:{},...u.screenshot?{screenshot:u.screenshot}:{}}})}catch(u){c.push({criterion_id:m.id,status:"fail",evidence:{error:u instanceof Error?u.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var eu=Vt.object({projectPath:Vt.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:Vt.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:Vt.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:Vt.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:Vt.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.")}),Qi={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:eu,handler:async t=>{let e=t;if(e.action==="acceptance"){let n=await nu(e);return n.isError,n}let r=await ru(e);return r.isError,r}};function Xi(t){let e=Zp(t,"mistflow.json");if(!Qp(e))return null;try{return JSON.parse(Xp(e,"utf-8"))}catch{return null}}async function Ji(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 tu(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 Yi(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function yt(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 Yi(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 Yi(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 nu(t){if(!t.sessionId)return d("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=Xi(e),n=t.url;if(!n&&t.deploymentId)try{let a=await at(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 d("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 Mn(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(()=>(At(),Zt)),l=await a();o=l.context,s=l.page}catch(a){return d(`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 Ki(s,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:i});try{await zr(t.sessionId,l)}catch(u){console.error("[acceptance] submitAcceptanceResults failed:",u instanceof Error?u.message:String(u))}let c=l.filter(u=>u.status==="pass").length,m=l.filter(u=>u.status==="fail").length,p=l.filter(u=>u.status==="skipped").length;return d(JSON.stringify({status:m===0?"pass":"fail",url:n,totals:{passed:c,failed:m,skipped:p,total:a.length},results:l.map(u=>({criterion_id:u.criterion_id,status:u.status,detail:u.evidence&&typeof u.evidence=="object"&&"detail"in u.evidence?u.evidence.detail:u.evidence&&typeof u.evidence=="object"&&"reason"in u.evidence?u.evidence.reason:void 0})),nextAction:m===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'."}),m>0)}finally{if(o)try{await o.close()}catch{}}}async function ru(t){let e=t.projectPath??process.cwd(),r=Xi(e),n=t.url;if(!n&&t.deploymentId)try{let P=await at(t.deploymentId);P.url&&(n=P.url)}catch(P){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,P instanceof Error?P.message:String(P))}if(n||(n=r?.deploy?.url),!n)return d("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 Ji(`${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."}),or(n,o);o.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Ji(`${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."}),or(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",m="QaTemp1!",p="single",u="user",g=[];async function D(P,z,V,Z){let ae=await tu(`${n}/api/admin/seed`,{token:Z,email:z,password:m,role:V});if(ae.status!==200||!ae.json)return console.error(`[qa] Seed (${P}) returned ${ae.status}`),null;let L=ae.json.sessionToken;if(!L)return null;let H=ae.json.seeded===!0;return{role:P,email:z,sessionToken:L,password:H?m:void 0}}if(i){let P=await Mn(i);if(P){if(p=P.authMode??"single",u=P.defaultRole??"user",console.error(`[qa] auth_mode=${p}, default_role=${u}`),p!=="none"){let V=await D("actor",l,p==="multi"?"admin":u,P.seedToken);if(V&&g.push(V),p==="multi"){let Z=await D("user",c,u,P.seedToken);Z?g.push(Z):o.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${u}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),p="none"}if(p!=="none"&&g.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."}),or(n,o);let _,x,y;try{let{getIsolatedContext:P}=await Promise.resolve().then(()=>(At(),Zt)),z=await P();_=z.context,y=z.page}catch(P){let z=P instanceof Error?P.message:String(P);return d(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:z,httpChecks:o.map(({screenshot:V,...Z})=>Z),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(`
5337
- `)}),!1)}try{let P=await yt(y,"Landing page",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await y.waitForLoadState("networkidle").catch(()=>{});let L=await y.evaluate(()=>{let A=document.body;if(!A)return"";let X=document.createTreeWalker(A,NodeFilter.SHOW_TEXT),K="",W;for(;W=X.nextNode();){let R=W.parentElement;if(R){let S=window.getComputedStyle(R);S.display!=="none"&&S.visibility!=="hidden"&&parseFloat(S.opacity)>0&&(K+=W.textContent?.trim()+" ")}}return K.trim()});if(L.length<50)return{pass:!1,detail:`Landing page appears blank (${L.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 H=y.url();return H.includes("/login")||H.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 (${L.length} chars)`}});o.push(P),p==="none"&&o.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let z=g[0],V=(L,H)=>g.length>1&&L?`${H} (${L.role})`:H,Z=!1;if(z?.password){let L=await yt(y,V(z,"Login"),async()=>{await y.goto(`${n}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let H=y.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),A=y.locator('input[type="password"], input[name="password"]');try{await H.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 H.first().fill(z.email),await A.first().fill(z.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(K=>!K.pathname.includes("/login"),{timeout:1e4})}catch{let K=await y.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:K?`Login failed: ${K}`:"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 Z=!0,{pass:!0,detail:`Logged in, redirected to ${y.url()}`}});o.push(L)}else z&&o.push({name:V(z,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!Z&&z){let L=new URL(n).hostname,H=n.startsWith("https");await _.addCookies([{name:H?"__Secure-better-auth.session_token":"better-auth.session_token",value:z.sessionToken,domain:L,path:"/",httpOnly:!0,secure:H,sameSite:"Lax"}]),console.error(`[qa] Injected ${z.role} cookie for primary walk`)}if(z){let L=await yt(y,V(z,"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 X=await y.content();return X.length<1e3?{pass:!1,detail:`Dashboard page is very small (${X.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 (${X.length} bytes)`}});o.push(L);let H=await y.evaluate(()=>{let X=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(W=>{let R=W.getAttribute("href");R&&R.startsWith("/")&&!R.startsWith("/api")&&!R.includes("[")&&R!=="/dashboard"&&R!=="/"&&!R.includes("/login")&&!R.includes("/sign")&&X.push(R)}),[...new Set(X)]});if(H.length>0){let X=0,K=[];for(let W of H.slice(0,8)){let R=await yt(y,V(z,`Page: ${W}`),async()=>{await y.goto(`${n}${W}`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let S=await y.title(),M=await y.content();return S.toLowerCase().includes("500")||S.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."}:S.toLowerCase().includes("404")||S.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${W} 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."}:M.length<500?{pass:!1,detail:`Page is very small (${M.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});R.status==="fail"&&(X++,K.push(W)),o.push(R)}}let A=await yt(y,"Design quality",async()=>{let X=y.url().includes("/dashboard")?y.url():`${n}/dashboard`;y.url().includes("/dashboard")||(await y.goto(X,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}));let K=await y.evaluate(()=>{let W=[],R=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),S=new Set;R.forEach(U=>{S.add(window.getComputedStyle(U).fontSize)}),R.length>=3&&S.size<2&&W.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 M=Array.from(R).map(U=>parseInt(U.tagName.charAt(1),10));for(let U=1;U<M.length;U++)if(M[U]-M[U-1]>1){W.push(`TYPOGRAPHY: Heading level skipped (h${M[U-1]} -> h${M[U]}). Use sequential heading levels for accessibility.`);break}let ee=document.querySelectorAll("*"),te=!1,C=!1;ee.forEach(U=>{let ce=window.getComputedStyle(U);ce.backgroundColor==="rgb(0, 0, 0)"&&U.clientHeight>100&&U.clientWidth>200&&(te=!0);let ke=ce.backgroundColor,Me=ce.color;if(ke&&!ke.includes("0, 0, 0")&&!ke.includes("255, 255, 255")&&ke!=="rgba(0, 0, 0, 0)"&&ke!=="transparent"&&Me.match(/rgb\((\d+), (\d+), (\d+)\)/)){let Ye=Me.match(/rgb\((\d+), (\d+), (\d+)\)/);if(Ye){let[Ue,Ae,h]=[parseInt(Ye[1]),parseInt(Ye[2]),parseInt(Ye[3])],f=Math.abs(Ue-Ae)<10&&Math.abs(Ae-h)<10&&Ue>80&&Ue<180,k=ke.match(/rgb\((\d+), (\d+), (\d+)\)/);if(f&&k){let[T,E,B]=[parseInt(k[1]),parseInt(k[2]),parseInt(k[3])];!(Math.abs(T-E)<15&&Math.abs(E-B)<15)&&U.textContent&&U.textContent.trim().length>0&&(C=!0)}}}}),te&&W.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)."),C&&W.push("COLOR: Gray text on a colored background detected. Gray looks washed out on color. Use a darker shade of the background color or white instead.");let ve=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),$=!1;ve.forEach(U=>{U.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&($=!0)}),$&&W.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let ge=document.querySelectorAll("p, li, span, div"),Ce=0,re=0;ge.forEach(U=>{U.textContent&&U.textContent.trim().length>20&&U.clientHeight>0&&(re++,window.getComputedStyle(U).textAlign==="center"&&Ce++)}),re>5&&Ce/re>.7&&W.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;ee.forEach(U=>{let ce=window.getComputedStyle(U);ce.gap&&ce.gap!=="normal"&&ce.gap!=="0px"&&ye.add(ce.gap)}),ye.size===1&&ee.length>20&&W.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(U=>{U.querySelectorAll("tbody tr").length===0&&(U.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||W.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 Ke=document.querySelectorAll("style"),Je=!1;Ke.forEach(U=>{let ce=U.textContent||"";(ce.includes("bounce")||ce.includes("elastic")||ce.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Je=!0)}),Je&&W.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let st=document.querySelectorAll("button, a, input, select, [role='button']"),Se=[];if(st.forEach(U=>{let ce=U.getBoundingClientRect();if(ce.width>0&&ce.height>0&&(ce.width<32||ce.height<32)){let ke=U.tagName.toLowerCase(),Me=U.id?`#${U.id}`:"",Ye=U.className&&typeof U.className=="string"?`.${U.className.split(/\s+/).filter(Boolean).slice(0,2).join(".")}`:"",Ue=(U.textContent||"").trim().slice(0,40),Ae=`${ke}${Me}${Ye}`,h=`${Math.round(ce.width)}x${Math.round(ce.height)}px`;Se.push(Ue?`${Ae} ("${Ue}", ${h})`:`${Ae} (${h})`)}}),Se.length>3){let U=Se.slice(0,8).map((ke,Me)=>` ${Me+1}. ${ke}`).join(`
5336
+ `)}function Wp(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 Gp(t){return t.includes(".next/diagnostics/build-diagnostics.json")?`The build log shows Next/OpenNext failed while reading .next/diagnostics/build-diagnostics.json. ${_t()} This has shown up when the adapter runs under an unsupported Node 22 patch release.`:null}var Gi={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:Bp,handler:async(t,e)=>{let r=t;if(r.jobId){let c=await ht(r.jobId);if(!c)return d(JSON.stringify({status:"not_found",jobId:r.jobId,message:`No build job found for jobId '${r.jobId}'. Start a new one with { projectPath }.`}),!0);let m=r.waitSeconds??20;if(m>0&&(c.status==="running"||c.status==="starting")){let P=c.elapsed,z=e?ze(e.server,e.progressToken,()=>`Build running (${P}) \u2014 waiting for terminal state`):{stop:()=>{}};try{let V=await Wt(r.jobId,{timeoutMs:m*1e3,onPoll:Z=>{P=Z.elapsed}});V&&(c=V)}finally{z.stop()}}if(c.status==="running"||c.status==="starting")return d(JSON.stringify({status:"running",jobId:c.id,elapsed:c.elapsed,logTail:Hp(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 P=qp(c.cwd);if(P){let z=It(c.id);return d(JSON.stringify({status:"failed",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,logTail:c.logTail,logPaths:z,error:P,nextAction:P+` Full build log: ${z.stdout} and ${z.stderr}.`}),!0)}return d(JSON.stringify({status:"complete",jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let p=zp(c.id),u=Gn(p),h=Wp(p),N=Gp(p),_=It(c.id),x=` Full log: ${_.stdout} and ${_.stderr}.`,y=h.length>0?`Build failed with missing modules: ${h.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${x}`:N?`${N}${x}`:u.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${x}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${x}`;return d(JSON.stringify({status:c.status,jobId:c.id,elapsed:c.elapsed,exitCode:c.exitCode,errors:u,missingModules:h,logTail:c.logTail,logPaths:_,nextAction:y}),!0)}let n=Lp(r.projectPath);if(!Ve(Ge(n,"package.json")))return d(`No package.json at ${n}. Run mist_init first.`,!0);if(!Ve(Ge(n,"node_modules")))return d(`node_modules not installed. Run mist_install { projectPath: '${n}' } first.`,!0);let i,o,s,a=Ve(Ge(n,"open-next.config.ts"))||Ve(Ge(n,"open-next.config.js"));if(r.script)i="npm",o=["run",r.script],s=r.script;else if(a){if(!Ut())return d(_t(),!0);i="npx",o=["-y","@opennextjs/cloudflare","build"],s="@opennextjs/cloudflare build"}else i="npm",o=["run","build"],s="build";let l=await mt({type:"build",cmd:i,args:o,cwd:n});return d(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 Qp,readFileSync as Xp}from"fs";import{join as Zp}from"path";import{z as Vt}from"zod";_e();_e();import{existsSync as Vp,readdirSync as Kp}from"fs";import{join as Vi}from"path";import{pathToFileURL as Jp}from"url";async function Yp(t){let e=Vi(t,".mistflow","acceptance"),r=new Map;if(!Vp(e))return r;let n=Kp(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=Vi(e,i);try{let a=await import(Jp(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 Ki(t,e){let{sessionId:r,projectPath:n,deployUrl:i,seedCredentials:o}=e,a=(await tn(r)).criteria,l=await Yp(n),c=[];for(let m of a){let p=l.get(m.id);if(!p){c.push({criterion_id:m.id,status:"skipped",evidence:{reason:`no probe at .mistflow/acceptance/${m.id}.spec.ts`}});continue}try{await t.goto(i,{waitUntil:"domcontentloaded"});let u=await p(t,{url:i,criterion:m,seedCredentials:o});c.push({criterion_id:m.id,status:u.pass?"pass":"fail",evidence:{...u.detail?{detail:u.detail}:{},...u.screenshot?{screenshot:u.screenshot}:{}}})}catch(u){c.push({criterion_id:m.id,status:"fail",evidence:{error:u instanceof Error?u.message:"probe threw an unknown error"}})}}return{criteria:a,results:c}}var eu=Vt.object({projectPath:Vt.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:Vt.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:Vt.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:Vt.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:Vt.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.")}),Qi={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:eu,handler:async t=>{let e=t;if(e.action==="acceptance"){let n=await nu(e);return n.isError,n}let r=await ru(e);return r.isError,r}};function Xi(t){let e=Zp(t,"mistflow.json");if(!Qp(e))return null;try{return JSON.parse(Xp(e,"utf-8"))}catch{return null}}async function Ji(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 tu(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 Yi(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function yt(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 Yi(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 Yi(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 nu(t){if(!t.sessionId)return d("mist_qa action='acceptance' requires sessionId. Pass the session ID from your mist_plan response.",!0);let e=t.projectPath??process.cwd(),r=Xi(e),n=t.url;if(!n&&t.deploymentId)try{let a=await at(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 d("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 $n(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(()=>(At(),Zt)),l=await a();o=l.context,s=l.page}catch(a){return d(`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 Ki(s,{sessionId:t.sessionId,projectPath:e,deployUrl:n,seedCredentials:i});try{await zr(t.sessionId,l)}catch(u){console.error("[acceptance] submitAcceptanceResults failed:",u instanceof Error?u.message:String(u))}let c=l.filter(u=>u.status==="pass").length,m=l.filter(u=>u.status==="fail").length,p=l.filter(u=>u.status==="skipped").length;return d(JSON.stringify({status:m===0?"pass":"fail",url:n,totals:{passed:c,failed:m,skipped:p,total:a.length},results:l.map(u=>({criterion_id:u.criterion_id,status:u.status,detail:u.evidence&&typeof u.evidence=="object"&&"detail"in u.evidence?u.evidence.detail:u.evidence&&typeof u.evidence=="object"&&"reason"in u.evidence?u.evidence.reason:void 0})),nextAction:m===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'."}),m>0)}finally{if(o)try{await o.close()}catch{}}}async function ru(t){let e=t.projectPath??process.cwd(),r=Xi(e),n=t.url;if(!n&&t.deploymentId)try{let P=await at(t.deploymentId);P.url&&(n=P.url)}catch(P){console.error(`[qa] Could not resolve URL from deploymentId ${t.deploymentId}:`,P instanceof Error?P.message:String(P))}if(n||(n=r?.deploy?.url),!n)return d("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 Ji(`${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."}),ar(n,o);o.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Ji(`${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."}),ar(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",m="QaTemp1!",p="single",u="user",h=[];async function N(P,z,V,Z){let ae=await tu(`${n}/api/admin/seed`,{token:Z,email:z,password:m,role:V});if(ae.status!==200||!ae.json)return console.error(`[qa] Seed (${P}) returned ${ae.status}`),null;let L=ae.json.sessionToken;if(!L)return null;let H=ae.json.seeded===!0;return{role:P,email:z,sessionToken:L,password:H?m:void 0}}if(i){let P=await $n(i);if(P){if(p=P.authMode??"single",u=P.defaultRole??"user",console.error(`[qa] auth_mode=${p}, default_role=${u}`),p!=="none"){let V=await N("actor",l,p==="multi"?"admin":u,P.seedToken);if(V&&h.push(V),p==="multi"){let Z=await N("user",c,u,P.seedToken);Z?h.push(Z):o.push({name:"Auth session (user)",status:"fail",detail:`Seed endpoint did not create the default-role user (${u}). Multi-role walk degraded to admin-only.`,fix:"Check that /api/admin/seed accepts a `role` parameter and creates users with non-admin roles. The scaffold ships this support; if customised, ensure the role argument is honored."})}}}else console.error("[qa] No seed info from backend \u2014 assuming auth-disabled or pre-deploy state"),p="none"}if(p!=="none"&&h.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."}),ar(n,o);let _,x,y;try{let{getIsolatedContext:P}=await Promise.resolve().then(()=>(At(),Zt)),z=await P();_=z.context,y=z.page}catch(P){let z=P instanceof Error?P.message:String(P);return d(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:z,httpChecks:o.map(({screenshot:V,...Z})=>Z),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(`
5337
+ `)}),!1)}try{let P=await yt(y,"Landing page",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await y.waitForLoadState("networkidle").catch(()=>{});let L=await y.evaluate(()=>{let A=document.body;if(!A)return"";let X=document.createTreeWalker(A,NodeFilter.SHOW_TEXT),K="",W;for(;W=X.nextNode();){let R=W.parentElement;if(R){let S=window.getComputedStyle(R);S.display!=="none"&&S.visibility!=="hidden"&&parseFloat(S.opacity)>0&&(K+=W.textContent?.trim()+" ")}}return K.trim()});if(L.length<50)return{pass:!1,detail:`Landing page appears blank (${L.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 H=y.url();return H.includes("/login")||H.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 (${L.length} chars)`}});o.push(P),p==="none"&&o.push({name:"Auth walk",status:"pass",detail:"Skipped \u2014 app has no authentication (authModel=none)."});let z=h[0],V=(L,H)=>h.length>1&&L?`${H} (${L.role})`:H,Z=!1;if(z?.password){let L=await yt(y,V(z,"Login"),async()=>{await y.goto(`${n}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let H=y.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),A=y.locator('input[type="password"], input[name="password"]');try{await H.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 H.first().fill(z.email),await A.first().fill(z.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(K=>!K.pathname.includes("/login"),{timeout:1e4})}catch{let K=await y.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:K?`Login failed: ${K}`:"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 Z=!0,{pass:!0,detail:`Logged in, redirected to ${y.url()}`}});o.push(L)}else z&&o.push({name:V(z,"Login"),status:"pass",detail:"Skipped form login (QA user already exists from previous deploy). Using session injection."});if(!Z&&z){let L=new URL(n).hostname,H=n.startsWith("https");await _.addCookies([{name:H?"__Secure-better-auth.session_token":"better-auth.session_token",value:z.sessionToken,domain:L,path:"/",httpOnly:!0,secure:H,sameSite:"Lax"}]),console.error(`[qa] Injected ${z.role} cookie for primary walk`)}if(z){let L=await yt(y,V(z,"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 X=await y.content();return X.length<1e3?{pass:!1,detail:`Dashboard page is very small (${X.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 (${X.length} bytes)`}});o.push(L);let H=await y.evaluate(()=>{let X=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(W=>{let R=W.getAttribute("href");R&&R.startsWith("/")&&!R.startsWith("/api")&&!R.includes("[")&&R!=="/dashboard"&&R!=="/"&&!R.includes("/login")&&!R.includes("/sign")&&X.push(R)}),[...new Set(X)]});if(H.length>0){let X=0,K=[];for(let W of H.slice(0,8)){let R=await yt(y,V(z,`Page: ${W}`),async()=>{await y.goto(`${n}${W}`,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let S=await y.title(),M=await y.content();return S.toLowerCase().includes("500")||S.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."}:S.toLowerCase().includes("404")||S.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${W} 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."}:M.length<500?{pass:!1,detail:`Page is very small (${M.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});R.status==="fail"&&(X++,K.push(W)),o.push(R)}}let A=await yt(y,"Design quality",async()=>{let X=y.url().includes("/dashboard")?y.url():`${n}/dashboard`;y.url().includes("/dashboard")||(await y.goto(X,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{}));let K=await y.evaluate(()=>{let W=[],R=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),S=new Set;R.forEach(U=>{S.add(window.getComputedStyle(U).fontSize)}),R.length>=3&&S.size<2&&W.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 M=Array.from(R).map(U=>parseInt(U.tagName.charAt(1),10));for(let U=1;U<M.length;U++)if(M[U]-M[U-1]>1){W.push(`TYPOGRAPHY: Heading level skipped (h${M[U-1]} -> h${M[U]}). Use sequential heading levels for accessibility.`);break}let ee=document.querySelectorAll("*"),te=!1,C=!1;ee.forEach(U=>{let ce=window.getComputedStyle(U);ce.backgroundColor==="rgb(0, 0, 0)"&&U.clientHeight>100&&U.clientWidth>200&&(te=!0);let ke=ce.backgroundColor,Me=ce.color;if(ke&&!ke.includes("0, 0, 0")&&!ke.includes("255, 255, 255")&&ke!=="rgba(0, 0, 0, 0)"&&ke!=="transparent"&&Me.match(/rgb\((\d+), (\d+), (\d+)\)/)){let Ye=Me.match(/rgb\((\d+), (\d+), (\d+)\)/);if(Ye){let[Ue,Ae,g]=[parseInt(Ye[1]),parseInt(Ye[2]),parseInt(Ye[3])],f=Math.abs(Ue-Ae)<10&&Math.abs(Ae-g)<10&&Ue>80&&Ue<180,k=ke.match(/rgb\((\d+), (\d+), (\d+)\)/);if(f&&k){let[T,E,B]=[parseInt(k[1]),parseInt(k[2]),parseInt(k[3])];!(Math.abs(T-E)<15&&Math.abs(E-B)<15)&&U.textContent&&U.textContent.trim().length>0&&(C=!0)}}}}),te&&W.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)."),C&&W.push("COLOR: Gray text on a colored background detected. Gray looks washed out on color. Use a darker shade of the background color or white instead.");let ve=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),$=!1;ve.forEach(U=>{U.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&($=!0)}),$&&W.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let ge=document.querySelectorAll("p, li, span, div"),Ce=0,re=0;ge.forEach(U=>{U.textContent&&U.textContent.trim().length>20&&U.clientHeight>0&&(re++,window.getComputedStyle(U).textAlign==="center"&&Ce++)}),re>5&&Ce/re>.7&&W.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;ee.forEach(U=>{let ce=window.getComputedStyle(U);ce.gap&&ce.gap!=="normal"&&ce.gap!=="0px"&&ye.add(ce.gap)}),ye.size===1&&ee.length>20&&W.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(U=>{U.querySelectorAll("tbody tr").length===0&&(U.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||W.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 Ke=document.querySelectorAll("style"),Je=!1;Ke.forEach(U=>{let ce=U.textContent||"";(ce.includes("bounce")||ce.includes("elastic")||ce.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Je=!0)}),Je&&W.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let st=document.querySelectorAll("button, a, input, select, [role='button']"),Se=[];if(st.forEach(U=>{let ce=U.getBoundingClientRect();if(ce.width>0&&ce.height>0&&(ce.width<32||ce.height<32)){let ke=U.tagName.toLowerCase(),Me=U.id?`#${U.id}`:"",Ye=U.className&&typeof U.className=="string"?`.${U.className.split(/\s+/).filter(Boolean).slice(0,2).join(".")}`:"",Ue=(U.textContent||"").trim().slice(0,40),Ae=`${ke}${Me}${Ye}`,g=`${Math.round(ce.width)}x${Math.round(ce.height)}px`;Se.push(Ue?`${Ae} ("${Ue}", ${g})`:`${Ae} (${g})`)}}),Se.length>3){let U=Se.slice(0,8).map((ke,Me)=>` ${Me+1}. ${ke}`).join(`
5338
5338
  `),ce=Se.length>8?`
5339
5339
  \u2026and ${Se.length-8} more.`:"";W.push(`ACCESSIBILITY: ${Se.length} interactive elements are smaller than 32x32px (minimum recommended touch target is 44x44px). Add padding so each element's bounding box reaches 44x44.
5340
5340
  Offenders:
@@ -5342,22 +5342,22 @@ ${U}${ce}`)}return W});return K.length===0?{pass:!0,detail:"No design quality is
5342
5342
  ${K.map((W,R)=>`${R+1}. ${W}`).join(`
5343
5343
  `)}`,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(A)}if(o.find(L=>L.name==="Landing page"&&L.status==="pass")){let L=await yt(y,"Landing design quality",async()=>{await y.goto(n,{waitUntil:"domcontentloaded",timeout:15e3}),await y.waitForLoadState("networkidle").catch(()=>{});let H=await y.evaluate(()=>{let A=[];document.querySelectorAll("*").forEach(R=>{let S=window.getComputedStyle(R);(S.getPropertyValue("-webkit-background-clip")||S.getPropertyValue("background-clip"))==="text"&&R.textContent&&R.textContent.trim().length>0&&A.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let K=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(K){let R=(K.textContent||"").toLowerCase(),S=["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 M of S)if(R.match(new RegExp(M))){A.push(`COPY: Generic hero text detected ('${M}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(R=>{let M=window.getComputedStyle(R).gridTemplateColumns;if(M){let ee=M.split(" ").filter(C=>C!=="").length,te=R.children;if(ee===3&&te.length===3){let C=Array.from(te).map(ge=>ge.offsetHeight),ve=C.every(ge=>Math.abs(ge-C[0])<5),$=Array.from(te).every(ge=>{let Ce=ge.querySelectorAll("svg"),re=ge.querySelectorAll("h2, h3, h4"),ye=ge.querySelectorAll("p");return Ce.length>=1&&re.length>=1&&ye.length>=1});ve&&$&&A.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.")}}}),A});return H.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${H.length} landing design issue(s):
5344
5344
  ${H.map((A,X)=>`${X+1}. ${A}`).join(`
5345
- `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});o.push(L)}let ae=g[1];if(ae){let{getIsolatedContext:L}=await Promise.resolve().then(()=>(At(),Zt)),H=await L();x=H.context;let A=H.page,X=new URL(n).hostname,K=n.startsWith("https");await x.addCookies([{name:K?"__Secure-better-auth.session_token":"better-auth.session_token",value:ae.sessionToken,domain:X,path:"/",httpOnly:!0,secure:K,sameSite:"Lax"}]),console.error(`[qa] Injected ${ae.role} cookie for secondary walk`);let W=await yt(A,V(ae,"Dashboard"),async()=>{await A.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await A.waitForLoadState("networkidle").catch(()=>{}),new URL(A.url()).pathname==="/"&&(await A.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await A.waitForLoadState("networkidle").catch(()=>{}));let S=await A.content();return S.length<1e3?{pass:!1,detail:`Dashboard is very small (${S.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 A.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 (${S.length} bytes)`}});o.push(W);let R=await A.evaluate(()=>{let S=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(M=>{let ee=M.getAttribute("href");ee&&ee.startsWith("/")&&!ee.startsWith("/api")&&!ee.includes("[")&&ee!=="/dashboard"&&ee!=="/"&&!ee.includes("/login")&&!ee.includes("/sign")&&S.push(ee)}),[...new Set(S)]});for(let S of R.slice(0,8)){let M=await yt(A,V(ae,`Page: ${S}`),async()=>{await A.goto(`${n}${S}`,{waitUntil:"domcontentloaded",timeout:15e3}),await A.waitForLoadState("networkidle").catch(()=>{});let ee=await A.title(),te=await A.content();return ee.toLowerCase().includes("500")||ee.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."}:ee.toLowerCase().includes("404")||ee.toLowerCase().includes("not found")?{pass:!0,detail:"404 (likely admin-only \u2014 acceptable)"}:await A.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."}:te.length<500?{pass:!1,detail:`Page very small (${te.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});o.push(M)}}}finally{_&&await _.close().catch(()=>{}),x&&await x.close().catch(()=>{})}if(t.deploymentId){let P=o.filter(Z=>Z.status==="fail"),z=o.filter(Z=>Z.status==="pass"),V=Date.now();await _r(t.deploymentId,{checks:o.map(({screenshot:Z,...ae})=>ae),overall:P.length===0?"pass":"fail",passed:z.length,failed:P.length,duration_ms:Date.now()-V}).catch(()=>{})}return or(n,o)}function or(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}
5345
+ `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});o.push(L)}let ae=h[1];if(ae){let{getIsolatedContext:L}=await Promise.resolve().then(()=>(At(),Zt)),H=await L();x=H.context;let A=H.page,X=new URL(n).hostname,K=n.startsWith("https");await x.addCookies([{name:K?"__Secure-better-auth.session_token":"better-auth.session_token",value:ae.sessionToken,domain:X,path:"/",httpOnly:!0,secure:K,sameSite:"Lax"}]),console.error(`[qa] Injected ${ae.role} cookie for secondary walk`);let W=await yt(A,V(ae,"Dashboard"),async()=>{await A.goto(`${n}/`,{waitUntil:"domcontentloaded",timeout:15e3}),await A.waitForLoadState("networkidle").catch(()=>{}),new URL(A.url()).pathname==="/"&&(await A.goto(`${n}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await A.waitForLoadState("networkidle").catch(()=>{}));let S=await A.content();return S.length<1e3?{pass:!1,detail:`Dashboard is very small (${S.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 A.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 (${S.length} bytes)`}});o.push(W);let R=await A.evaluate(()=>{let S=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(M=>{let ee=M.getAttribute("href");ee&&ee.startsWith("/")&&!ee.startsWith("/api")&&!ee.includes("[")&&ee!=="/dashboard"&&ee!=="/"&&!ee.includes("/login")&&!ee.includes("/sign")&&S.push(ee)}),[...new Set(S)]});for(let S of R.slice(0,8)){let M=await yt(A,V(ae,`Page: ${S}`),async()=>{await A.goto(`${n}${S}`,{waitUntil:"domcontentloaded",timeout:15e3}),await A.waitForLoadState("networkidle").catch(()=>{});let ee=await A.title(),te=await A.content();return ee.toLowerCase().includes("500")||ee.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."}:ee.toLowerCase().includes("404")||ee.toLowerCase().includes("not found")?{pass:!0,detail:"404 (likely admin-only \u2014 acceptable)"}:await A.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."}:te.length<500?{pass:!1,detail:`Page very small (${te.length} bytes) for default-role user`,fix:"Page rendered empty under non-admin role."}:{pass:!0,detail:"Loads without errors"}});o.push(M)}}}finally{_&&await _.close().catch(()=>{}),x&&await x.close().catch(()=>{})}if(t.deploymentId){let P=o.filter(Z=>Z.status==="fail"),z=o.filter(Z=>Z.status==="pass"),V=Date.now();await _r(t.deploymentId,{checks:o.map(({screenshot:Z,...ae})=>ae),overall:P.length===0?"pass":"fail",passed:z.length,failed:P.length,duration_ms:Date.now()-V}).catch(()=>{})}return ar(n,o)}function ar(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}
5346
5346
  Fix: ${s.fix}`).join(`
5347
5347
 
5348
5348
  `);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):
5349
5349
 
5350
5350
  ${o}
5351
5351
 
5352
- 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 nt}from"zod";import{resolve as au,join as ar}from"path";import{existsSync as lr}from"fs";_e();wt();wt();import{existsSync as ir,readdirSync as su,statSync as Zi,unlinkSync as ea}from"fs";import{join as Pt}from"path";import{execFile as ou}from"child_process";function iu(t,e){let r=0;for(let n of e){let i=Pt(t,n);if(ir(i))try{let o=Zi(i);if(o.isFile())r++;else if(o.isDirectory()){let s=[i];for(;s.length;){let a=s.pop(),l=su(a,{withFileTypes:!0});for(let c of l){let m=Pt(a,c.name);c.isDirectory()?s.push(m):r++}}}}catch{}}return r}function ta(t,e,r){return new Promise(n=>{ou("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 na(t){let e=Pt(t,".open-next-build.tar.gz"),r=[".open-next"];ir(Pt(t,"db"))&&r.push("db"),ir(Pt(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),ir(Pt(t,"package.json"))&&r.push("package.json");let n=iu(t,r),i=await ta(["-czf",e,"-C",t,...r],t,12e4);if(!i.success){try{ea(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(i.stderr?`
5353
- ${i.stderr.slice(-500)}`:""))}let o=0;try{o=Zi(e).size}catch{}return{path:e,sizeBytes:o,fileCount:n}}async function ra(t){let e=Pt(t,".mistflow-source.tar.gz");return(await ta(["-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 hs(t){if(t)try{ea(t)}catch{}}function sa(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function oa(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 lu=nt.object({action:nt.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:nt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:nt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:nt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:nt.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:nt.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:nt.array(tr).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:nt.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 ia(t){return lr(ar(t,".open-next"))}function cu(t){return it(t)?.deploy?.strategy==="staging"?"preview":null}async function du(t,e){if(!(lr(ar(t,"open-next.config.ts"))||lr(ar(t,"open-next.config.js"))))return{kind:"failed",result:d(`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(!lr(ar(t,"node_modules")))return{kind:"failed",result:d(`node_modules is missing at ${t}. Call mist_install { projectPath } first, then mist_deploy.`,!0)};if(!Ut())return{kind:"failed",result:d(_t(),!0)};let n=await mt({type:"build",cmd:"npx",args:["-y","@opennextjs/cloudflare","build"],cwd:t}),i=e?ze(e.server,e.progressToken,()=>`Auto-building before deploy \u2014 OpenNext adapter (${n.id})`):{stop:()=>{}},o;try{o=await Wt(n.id,{timeoutMs:45e3})}finally{i.stop()}if(!o)return{kind:"failed",result:d(`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:d(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"&&ia(t))return{kind:"ok"};let s=It(n.id),a=(o.logTail??"").split(`
5352
+ 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 nt}from"zod";import{resolve as au,join as vn}from"path";import{existsSync as kn,readFileSync as lu}from"fs";import{homedir as cu}from"os";_e();wt();wt();import{existsSync as lr,readdirSync as su,statSync as Zi,unlinkSync as ea}from"fs";import{join as Pt}from"path";import{execFile as ou}from"child_process";function iu(t,e){let r=0;for(let n of e){let i=Pt(t,n);if(lr(i))try{let o=Zi(i);if(o.isFile())r++;else if(o.isDirectory()){let s=[i];for(;s.length;){let a=s.pop(),l=su(a,{withFileTypes:!0});for(let c of l){let m=Pt(a,c.name);c.isDirectory()?s.push(m):r++}}}}catch{}}return r}function ta(t,e,r){return new Promise(n=>{ou("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 na(t){let e=Pt(t,".open-next-build.tar.gz"),r=[".open-next"];lr(Pt(t,"db"))&&r.push("db"),lr(Pt(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),lr(Pt(t,"package.json"))&&r.push("package.json");let n=iu(t,r),i=await ta(["-czf",e,"-C",t,...r],t,12e4);if(!i.success){try{ea(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(i.stderr?`
5353
+ ${i.stderr.slice(-500)}`:""))}let o=0;try{o=Zi(e).size}catch{}return{path:e,sizeBytes:o,fileCount:n}}async function ra(t){let e=Pt(t,".mistflow-source.tar.gz");return(await ta(["-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 hs(t){if(t)try{ea(t)}catch{}}function sa(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function oa(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 du=nt.object({action:nt.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:nt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:nt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:nt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:nt.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:nt.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:nt.array(rr).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:nt.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 ia(t){return kn(vn(t,".open-next"))}function pu(t){return it(t)?.deploy?.strategy==="staging"?"preview":null}async function uu(t,e){if(!(kn(vn(t,"open-next.config.ts"))||kn(vn(t,"open-next.config.js"))))return{kind:"failed",result:d(`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(!kn(vn(t,"node_modules")))return{kind:"failed",result:d(`node_modules is missing at ${t}. Call mist_install { projectPath } first, then mist_deploy.`,!0)};if(!Ut())return{kind:"failed",result:d(_t(),!0)};let n=await mt({type:"build",cmd:"npx",args:["-y","@opennextjs/cloudflare","build"],cwd:t}),i=e?ze(e.server,e.progressToken,()=>`Auto-building before deploy \u2014 OpenNext adapter (${n.id})`):{stop:()=>{}},o;try{o=await Wt(n.id,{timeoutMs:45e3})}finally{i.stop()}if(!o)return{kind:"failed",result:d(`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:d(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"&&ia(t))return{kind:"ok"};let s=It(n.id),a=(o.logTail??"").split(`
5354
5354
  `).slice(-30).join(`
5355
- `);return{kind:"failed",result:d(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 pu(t){let e=au(t.projectPath);if(!xe())return Ne("deploy");let r=it(e),n=r?.projectId;if(!n){if(!r?.name)return d(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);try{n=(await kt(r.name,{dbProvider:r.dbProvider,requestedSubdomain:r.requestedSubdomain})).id,br(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 J||l instanceof Error?l.message:String(l);return d(`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(!ia(e)){let l=await du(e,t.ctx);if(l.kind==="running"||l.kind==="failed")return l.result}let i=t.environment??cu(e)??"production",o=t.adminEmail??Ms()?.email,s=null,a=null;try{s=await na(e),a=await ra(e);let l=await xr(n,s.path,i,o,void 0,a??void 0,void 0);return d(JSON.stringify({status:"running",jobId:l.deployment_id,deploymentId:l.deployment_id,environment:l.environment??i,buildSize:sa(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 J||l instanceof Error?l.message:String(l);return d(`Deploy upload failed: ${c}`,!0)}finally{hs(s?.path),hs(a)}}async function uu(t,e){let r=e.ctx?ze(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let n=await at(t,{waitSeconds:e.waitSeconds}),i=oa(n.status),o=n.id??t;return n.status==="live"?(e.projectPath&&n.url&&(br(e.projectPath,{deploy:{url:n.url,deploymentId:o,completedAt:n.completedAt}}),Ft(e.projectPath)),d(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"?d(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):d(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 J||n instanceof Error?n.message:String(n);return d(`Could not fetch deploy status: ${i}`,!0)}finally{r.stop()}}async function mu(t,e){if(!xe())return Ne("promote a preview deployment");let n=it(t)?.projectId;if(!n)return d(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let i=e;if(!i)try{let s=(await Et(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!s)return d("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 J?o.message:String(o);return d(`Could not list deployments: ${s}`,!0)}try{let o=await Er(n,i);return d(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 J||o instanceof Error?o.message:String(o);return d(`Promote failed: ${s}`,!0)}}async function hu(t){if(!xe())return Ne("roll back a deployment");try{let e=await Nr(t);return d(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let r=e instanceof J||e instanceof Error?e.message:String(e);return d(`Rollback failed: ${r}`,!0)}}var aa={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:lu,handler:async(t,e)=>{let r=t;switch(r.action??"deploy"){case"deploy":{if(!r.projectPath)return d("projectPath is required for action='deploy'.",!0);if(r.envVarsRequired&&r.envVarsRequired.length>0)try{let i=nr(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 pu({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail,ctx:e})}case"status":return r.deploymentId?uu(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e,projectPath:r.projectPath,sessionId:r.sessionId}):d("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?mu(r.projectPath,r.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?hu(r.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}};import{z as Kt}from"zod";_e();import{hostname as gu}from"os";var ca=Kt.object({action:Kt.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:Kt.string().uuid().optional().describe("Required for status / cancel / resume. Omit for list."),reason:Kt.string().max(500).optional().describe("Optional cancellation reason (used with action=cancel)."),projectPath:Kt.string().min(1).optional().describe("Absolute path to the project directory on this machine. Required for action=resume."),includeIdle:Kt.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 la(){return gu()}function gs(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(`
5356
- `)}async function fu(t){let e=ca.safeParse(t);if(!e.success){let s=e.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return d(`Invalid input: ${s}`,!0)}let r=e.data;if((r.action==="status"||r.action==="cancel"||r.action==="resume")&&!r.sessionId)return d(`Invalid input: action="${r.action}" requires sessionId.`,!0);if(r.action==="resume"&&!r.projectPath)return d('Invalid input: action="resume" requires projectPath.',!0);if(r.action==="status"){let s=r.sessionId,[a,l,c]=await Promise.all([Ln(s),Ot(s).catch(()=>null),tn(s).catch(()=>null)]),m=[gs(a),"",l?`Next instruction: ${l.instruction}${l.reason?` (${l.reason})`:""}`:"Next instruction: (unavailable)"];if(c&&c.criteria.length>0){m.push("",`Acceptance criteria (${c.criteria.length}):`);for(let p of c.criteria)m.push(` - [${p.priority}] ${p.id}: ${p.description}`)}return d(m.join(`
5355
+ `);return{kind:"failed",result:d(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 mu(t){let e=au(t.projectPath);if(!xe())return Ne("deploy");let r=it(e),n=r?.projectId;if(!n){if(!r?.name)return d(`No projectId or name in mistflow.json at ${e}. Run mist_init first.`,!0);let l=typeof r.plan=="object"&&r.plan!==null?r.plan:void 0;if(!l&&r.planId)try{let h=vn(cu(),".mistflow","plans",`${r.planId}.json`);if(kn(h)){let N=JSON.parse(lu(h,"utf-8"));l=N?.plan??N}}catch{}let c=l?.pickedDirection??void 0,m=l?.imageryBrief??c?.imagery??void 0,p=l?.designConversationId??void 0,u=l?{name:l.name,summary:l.summary,audienceType:l.audienceType,authModel:l.authModel,dbProvider:r.dbProvider,dataModel:l.dataModel,design:l.design,publicLanding:l.publicLanding,...p?{designConversationId:p}:{},...l.features?{features:l.features}:{},...l.integrations?{integrations:l.integrations}:{},...l.hasAI===!0?{hasAI:!0}:{},...l.hasEmail===!0?{hasEmail:!0}:{},...l.hasStorage===!0?{hasStorage:!0}:{}}:void 0;try{n=(await kt(r.name,{dbProvider:r.dbProvider,requestedSubdomain:r.requestedSubdomain,pickedDirection:c,imageryBrief:m,planContext:u,designConversationId:p})).id,br(e,{projectId:n}),console.error(`[deploy] auto-registered project ${n.slice(0,8)} (${r.name})`+(r.requestedSubdomain?` at ${r.requestedSubdomain}.mistflow.app`:"")+(u?" with plan context":" WITHOUT plan context (no plan blob in mistflow.json \u2014 AI/storage may not provision)"))}catch(h){let N=h instanceof J||h instanceof Error?h.message:String(h);return d(`Auto-register before deploy failed: ${N}. 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(!ia(e)){let l=await uu(e,t.ctx);if(l.kind==="running"||l.kind==="failed")return l.result}let i=t.environment??pu(e)??"production",o=t.adminEmail??Ms()?.email,s=null,a=null;try{s=await na(e),a=await ra(e);let l=await xr(n,s.path,i,o,void 0,a??void 0,void 0);return d(JSON.stringify({status:"running",jobId:l.deployment_id,deploymentId:l.deployment_id,environment:l.environment??i,buildSize:sa(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 J||l instanceof Error?l.message:String(l);return d(`Deploy upload failed: ${c}`,!0)}finally{hs(s?.path),hs(a)}}async function hu(t,e){let r=e.ctx?ze(e.ctx.server,e.ctx.progressToken,()=>`Deploy ${t} \u2014 waiting for terminal state`):{stop:()=>{}};try{let n=await at(t,{waitSeconds:e.waitSeconds}),i=oa(n.status),o=n.id??t;return n.status==="live"?(e.projectPath&&n.url&&(br(e.projectPath,{deploy:{url:n.url,deploymentId:o,completedAt:n.completedAt}}),Ft(e.projectPath)),d(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"?d(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):d(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 J||n instanceof Error?n.message:String(n);return d(`Could not fetch deploy status: ${i}`,!0)}finally{r.stop()}}async function gu(t,e){if(!xe())return Ne("promote a preview deployment");let n=it(t)?.projectId;if(!n)return d(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let i=e;if(!i)try{let s=(await Et(n)).find(a=>a.environment==="preview"&&a.status==="live");if(!s)return d("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 J?o.message:String(o);return d(`Could not list deployments: ${s}`,!0)}try{let o=await Er(n,i);return d(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 J||o instanceof Error?o.message:String(o);return d(`Promote failed: ${s}`,!0)}}async function fu(t){if(!xe())return Ne("roll back a deployment");try{let e=await Nr(t);return d(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } immediately \u2014 each status call long-polls for up to 20s server-side.`}))}catch(e){let r=e instanceof J||e instanceof Error?e.message:String(e);return d(`Rollback failed: ${r}`,!0)}}var aa={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:du,handler:async(t,e)=>{let r=t;switch(r.action??"deploy"){case"deploy":{if(!r.projectPath)return d("projectPath is required for action='deploy'.",!0);if(r.envVarsRequired&&r.envVarsRequired.length>0)try{let i=sr(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 mu({projectPath:r.projectPath,environment:r.environment,adminEmail:r.adminEmail,ctx:e})}case"status":return r.deploymentId?hu(r.deploymentId,{waitSeconds:r.waitSeconds??20,ctx:e,projectPath:r.projectPath,sessionId:r.sessionId}):d("deploymentId is required for action='status'.",!0);case"promote":return r.projectPath?gu(r.projectPath,r.deploymentId):d("projectPath is required for action='promote'.",!0);case"rollback":return r.deploymentId?fu(r.deploymentId):d("deploymentId is required for action='rollback'.",!0)}}};import{z as Kt}from"zod";_e();import{hostname as yu}from"os";var ca=Kt.object({action:Kt.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:Kt.string().uuid().optional().describe("Required for status / cancel / resume. Omit for list."),reason:Kt.string().max(500).optional().describe("Optional cancellation reason (used with action=cancel)."),projectPath:Kt.string().min(1).optional().describe("Absolute path to the project directory on this machine. Required for action=resume."),includeIdle:Kt.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 la(){return yu()}function gs(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(`
5356
+ `)}async function bu(t){let e=ca.safeParse(t);if(!e.success){let s=e.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return d(`Invalid input: ${s}`,!0)}let r=e.data;if((r.action==="status"||r.action==="cancel"||r.action==="resume")&&!r.sessionId)return d(`Invalid input: action="${r.action}" requires sessionId.`,!0);if(r.action==="resume"&&!r.projectPath)return d('Invalid input: action="resume" requires projectPath.',!0);if(r.action==="status"){let s=r.sessionId,[a,l,c]=await Promise.all([Un(s),Ot(s).catch(()=>null),tn(s).catch(()=>null)]),m=[gs(a),"",l?`Next instruction: ${l.instruction}${l.reason?` (${l.reason})`:""}`:"Next instruction: (unavailable)"];if(c&&c.criteria.length>0){m.push("",`Acceptance criteria (${c.criteria.length}):`);for(let p of c.criteria)m.push(` - [${p.priority}] ${p.id}: ${p.description}`)}return d(m.join(`
5357
5357
  `))}if(r.action==="cancel"){let s=r.sessionId,a=await qr(s,r.reason);return d(`Session cancelled.
5358
5358
  ${gs(a)}
5359
5359
 
5360
- Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(r.action==="resume"){let s=r.sessionId,a=r.projectPath,l=la(),c=await nn(s,{machine_id:l,local_path:a}),m=await Ln(s),p=await Ot(s).catch(()=>null);return d(`Resumed session on this machine.
5360
+ Note: cancellation is terminal. Start a new session with mist_plan to begin again.`)}if(r.action==="resume"){let s=r.sessionId,a=r.projectPath,l=la(),c=await nn(s,{machine_id:l,local_path:a}),m=await Un(s),p=await Ot(s).catch(()=>null);return d(`Resumed session on this machine.
5361
5361
  Machine: ${l}
5362
5362
  Local path: ${c.local_path}
5363
5363
  Last seen: ${c.last_seen_at}
@@ -5366,8 +5366,8 @@ Last seen: ${c.last_seen_at}
5366
5366
 
5367
5367
  Next instruction: ${p.instruction}${p.reason?` (${p.reason})`:""}`:""))}let n=la(),i=await rn(n,{includeIdle:r.includeIdle===!0});if(i.length===0){let s=r.includeIdle?"this machine has no sessions bound at all":"no active sessions touched in the last 24h on this machine";return d(`${s} (${n}).
5368
5368
  `+(r.includeIdle?"Run mist_plan to start a new one.":'Run mist_plan to start a new one, mist_session action="resume" with a sessionId, or mist_session action="list" includeIdle=true to see older sessions.'))}let o=[`Sessions bound on this machine (${n}):`,"",...i.map(s=>` - ${s.id} status=${s.status}${s.paused_after_plan?" (paused)":""} ${s.description?`"${s.description.slice(0,60)}"`:"(no description)"}`)];return d(o.join(`
5369
- `))}var da={name:"mist_session",description:"Read or correct a Mistflow session. Actions: status (current state + criteria), cancel (terminal), resume (bind this machine to a session for multi-machine work), list (sessions this machine has worked on). All state changes go through the backend so the host AI never directly mutates session state.",inputSchema:ca,handler:fu};_e();var cr=new yu({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Ss()}),pa=[Vs,so,oo,lo,po,Do,Ho,bo,Ui,vo,Bi,zi,Gi,Qi,aa,da];cr.setRequestHandler(vu,async()=>({tools:pa.map(t=>({name:t.name,description:t.description,inputSchema:ku(t.inputSchema)}))}));cr.setRequestHandler(wu,async t=>{let e=pa.find(r=>r.name===t.params.name);if(!e)return d(`Unknown tool: ${t.params.name}`,!0);try{let r=e.inputSchema.safeParse(t.params.arguments);if(!r.success){let s=r.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return d(`Invalid input: ${s}`,!0)}let n=typeof r.data=="object"&&r.data!==null&&"sessionId"in r.data&&typeof r.data.sessionId=="string"?r.data.sessionId:void 0;if(n&&e.name!=="mist_session")try{let s=await Br(n,e.name);if(!s.allowed)return d(`Tool ${e.name} not allowed for this session.
5369
+ `))}var da={name:"mist_session",description:"Read or correct a Mistflow session. Actions: status (current state + criteria), cancel (terminal), resume (bind this machine to a session for multi-machine work), list (sessions this machine has worked on). All state changes go through the backend so the host AI never directly mutates session state.",inputSchema:ca,handler:bu};_e();var cr=new wu({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Ss()}),pa=[Vs,so,oo,lo,po,Do,Ho,bo,Ui,vo,Bi,zi,Gi,Qi,aa,da];cr.setRequestHandler(xu,async()=>({tools:pa.map(t=>({name:t.name,description:t.description,inputSchema:Su(t.inputSchema)}))}));cr.setRequestHandler(ku,async t=>{let e=pa.find(r=>r.name===t.params.name);if(!e)return d(`Unknown tool: ${t.params.name}`,!0);try{let r=e.inputSchema.safeParse(t.params.arguments);if(!r.success){let s=r.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return d(`Invalid input: ${s}`,!0)}let n=typeof r.data=="object"&&r.data!==null&&"sessionId"in r.data&&typeof r.data.sessionId=="string"?r.data.sessionId:void 0;if(n&&e.name!=="mist_session")try{let s=await Br(n,e.name);if(!s.allowed)return d(`Tool ${e.name} not allowed for this session.
5370
5370
  Reason: ${s.reason}
5371
5371
  Status: ${s.status}
5372
5372
 
5373
- Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(s){if(s instanceof J&&s.code==="not_found")console.error(`Guard check 404 for tool ${e.name}: ${s.message}`);else throw s}let i=t.params._meta?.progressToken,o={server:cr,progressToken:i};try{return await e.handler(r.data,o)}finally{o.cleanup?.()}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),d(n,!0)}});async function xu(){let t=process.argv.indexOf("--api-url");t!==-1&&process.argv[t+1]&&(process.env.MISTFLOW_API_URL=process.argv[t+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let e=new bu;await cr.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}xu().catch(t=>{console.error("Fatal error:",t),process.exit(1)});
5373
+ Call mist_plan with this sessionId to find out what the host AI should do next.`,!0)}catch(s){if(s instanceof J&&s.code==="not_found")console.error(`Guard check 404 for tool ${e.name}: ${s.message}`);else throw s}let i=t.params._meta?.progressToken,o={server:cr,progressToken:i};try{return await e.handler(r.data,o)}finally{o.cleanup?.()}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),d(n,!0)}});async function Tu(){let t=process.argv.indexOf("--api-url");t!==-1&&process.argv[t+1]&&(process.env.MISTFLOW_API_URL=process.argv[t+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let e=new vu;await cr.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}Tu().catch(t=>{console.error("Fatal error:",t),process.exit(1)});