klaudius 0.32.1 → 0.32.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
- import{b as ke,c as Ye,d as J,e as T,f as sn,g as on,h as We,i as ze,j as de,k as rn,l as an,o as ln,q as Ae,r as qe,s as N}from"./chunk-4OWKYGZF.js";import{Command as Dr}from"commander";import{spawn as un}from"child_process";import{existsSync as qs}from"fs";import{homedir as Qs}from"os";import O from"picocolors";import{win32 as Ns}from"path";var Ms=["&","^","%","!"];function Ds(e){return Ms.filter(t=>e.includes(t))}function Ee(e){let t=[];for(let{label:n,path:s}of e){let o=Ds(s);o.length>0&&t.push({label:n,path:s,chars:o})}return t}function Fs(e){let t=(e??"").trim().replace(/^["']|["']$/g,"");if(!t||t==="undefined"||t==="null")return null;let n=t.toLowerCase().split(/[\\/]/);if(n.length<2||n.includes("system32"))return null;let s=Ns.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(s)?t:null}function Pe(e,t){let n=Fs(e);return n===null?!1:t?t(n):!0}function Se(e,t){let n=e[0],s=[...new Set(e.flatMap(f=>f.chars))],o=s.map(f=>`"${f}"`).join(", "),r=s.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${o} in it ${r?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${r?"will":"may"} fail here with a misleading demand to install Visual Studio \u2014 Visual Studio is NOT needed and installing it will not fix this. Instead point npm's build steps at a shell that parses these paths correctly: PowerShell 7 (pwsh) or Git Bash, whichever is installed \u2014 npm config set script-shell "<full path to pwsh.exe or bash.exe>" (applies to all npm projects on this machine) \u2014 ${t==="preflight"?'then re-run this preflight \u2014 the "Install path safe for npm builds" check passes once script-shell is set.':t==="doctor"?"then re-run doctor \u2014 this check passes once script-shell is set.":'then re-run `npx klaudius@latest install`; `npx klaudius@latest doctor` confirms the fix (its "Install path safe for npm builds" check passes once script-shell is set).'} Windows PowerShell 5.1 ("powershell") will NOT work: it can't run the "||" in packages' install scripts. If neither shell is installed, PowerShell 7 is a small download: winget install Microsoft.PowerShell. If only the PROJECT folder is affected (not the user folder), moving the project to a plain path like C:\\klaudius also fixes it, or scope the npm setting to just this project by adding --location=project (run inside the project folder).`}}function ue(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10),r=`${n}.${s}.${o}`;return n<22||n===22&&s<15?{ok:!1,version:r,major:n,minor:s,message:`Your installed Node.js is ${r}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:r,major:n,minor:s}}import{spawn as Hs}from"child_process";import{existsSync as Us}from"fs";import{homedir as js}from"os";import{delimiter as Ks,join as Qe}from"path";var Gs=new Set(["Restricted","AllSigned"]);function Bs(e,t=Us){for(let n of e.split(Ks)){let s=n.replace(/"/g,"");if(!s)continue;let o=Qe(s,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let a=Qe(s,r);if(t(a))return{path:a,isPs1:!1}}}return null}async function dn(){let e=Bs(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Vs();if(!t)return{blocked:!1,shimPath:e.path};let n=Qe(js(),".local","node")+"\\";return{blocked:Gs.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Vs(){let e=Qe(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await cn(e)??await cn("powershell.exe")}function cn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let s=Hs(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",r=setTimeout(()=>{s.kill(),n(null)},8e3);s.stdout.on("data",a=>{o+=a.toString()}),s.stderr?.resume(),s.on("close",a=>{clearTimeout(r),n(a===0&&o.trim()?o.trim():null)}),s.on("error",()=>{clearTimeout(r),n(null)})})}import{spawn as Ys}from"child_process";var De=3,Je=10,Ws=[["python3"],["python"],["py","-3"]];async function K(){for(let e of Ws){let t=await Xe(e[0],[...e.slice(1),"--version"]),n=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(n)||t.code!==0)continue;let s=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!s)continue;let o=parseInt(s[1],10),r=parseInt(s[2],10),a=s[3]?`${o}.${r}.${s[3]}`:`${o}.${r}`;return{command:[...e],version:a,major:o,minor:r}}return null}async function be(){let e=zs(),t=await K();if(!t){let a=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${De}.${Je}+ is not installed (or not on PATH). Install it from ${e}.`+a}}let{command:n,version:s,major:o,minor:r}=t;return o<De||o===De&&r<Je?{ok:!1,version:s,major:o,minor:r,command:n,message:`Your installed Python is ${s}. Klaudius needs Python ${De}.${Je} or newer (the pipeline depends on packages that only ship wheels for ${De}.${Je}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:s,major:o,minor:r,command:n}}function zs(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Xe(e,t){return new Promise(n=>{let s=Ys(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",a=>{o+=a.toString()}),s.stderr?.on("data",a=>{r+=a.toString()}),s.on("close",a=>n({code:a??1,stdout:o,stderr:r})),s.on("error",()=>n({code:1,stdout:o,stderr:r}))})}var pn=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function fn(e={}){console.log(O.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
- `));let t=[];t.push(Js());let n=await be();if(t.push(Xs(n)),t.push(await Zs(n.command)),t.push(await ei()),process.platform==="win32"){let o=await ti();o&&t.push(o);let r=await ni();r&&t.push(r)}t.push(await si());for(let o of t){let r=o.status==="ok"?O.green("\u2713"):o.status==="warn"?O.yellow("!"):O.red("\u2717");console.log(` ${r} ${o.name}${o.detail?O.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${O.dim("\u2192")} ${O.cyan(o.nextAction)}`)}console.log();let s=t.filter(o=>o.status==="fail");if(s.length===0){let o=t.filter(r=>r.status==="warn").length;ii(o);return}console.log(O.red(O.bold(`${s.length} check${s.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(O.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(O.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Js(){let e=ue();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal window before re-running."}}function Xs(e){return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:e.message??"Install Python 3.10+ from https://www.python.org/downloads/"}}async function Zs(e){let t=e??["python3"],n=await Ze(t[0],[...t.slice(1),"-m","pip","--version"]);return n.code===0?{name:"pip available",status:"ok",detail:(n.stdout||n.stderr).trim().split(`
4
- `)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function ei(){let e=process.platform==="win32",t=await Ze("npm",["--version"],e);return t.code!==0?{name:"npm / npx available",status:"fail",detail:"npm not found",nextAction:"npm ships with Node.js \u2014 reinstall Node from https://nodejs.org/."}:(await Ze("npx",["--version"],e)).code!==0?{name:"npm / npx available",status:"fail",detail:`npm ${t.stdout.trim()} ok, npx missing`,nextAction:"npx ships with npm 5.2+ \u2014 reinstall Node from https://nodejs.org/."}:{name:"npm / npx available",status:"ok",detail:`npm ${t.stdout.trim()}`}}async function ti(){let e=await dn();if(e.npxMissing)return null;let t="npx runs in PowerShell";if(!e.blocked){let n="resolves to a policy-immune shim";return e.shimPath&&(n=e.policy?`ExecutionPolicy ${e.policy} allows the npx.ps1 shim`:"npx.ps1 shim present but ExecutionPolicy unreadable \u2014 assuming it runs"),{name:t,status:"ok",detail:n}}return{name:t,status:"fail",detail:`ExecutionPolicy ${e.policy} blocks ${e.shimPath}, which PowerShell prefers over npx.cmd`,nextAction:e.ownInstall?`In PowerShell run: Remove-Item "$env:USERPROFILE\\.local\\node\\np*.ps1" \u2014 it deletes only the PowerShell shims from Klaudius's own Node install (npx falls back to npx.cmd). It prints nothing back; that means it worked. Then re-run this preflight.`:"In Windows PowerShell (the classic blue one, not PowerShell 7) run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned \u2014 printing nothing back means it worked; confirm with Get-ExecutionPolicy (should say RemoteSigned), then re-run this preflight. If it prints an error instead, your organisation manages this setting \u2014 ask IT."}}async function ni(){let e=Ee([{label:"your Windows user folder",path:Qs()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await Ze("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(Pe(s,qs))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(l=>`"${l}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=Se(e,"preflight"),a=e.some(l=>l.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function si(){try{return await fetch(pn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:pn}}catch(e){return{name:"klaudius.dev reachable",status:"fail",detail:e.name==="TimeoutError"?"timed out":"could not connect",nextAction:"Check your internet connection, VPN, or firewall \u2014 init needs klaudius.dev to validate your license and download the template."}}}function ii(e=0){e>0?console.log(O.green(O.bold("Your machine is ready."))+O.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(O.green(O.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(O.bold("NEXT STEP \u2014 this one is for you to run, not the AI assistant:")),console.log(" It's an interactive wizard (it asks for your license key and passwords),"),console.log(" so the assistant can't fill it in. Open a NEW terminal WINDOW and run:"),console.log(),console.log(` ${O.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(O.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(O.dim(" run it in a new terminal window.")),console.log()}function Ze(e,t,n=!1){return new Promise(s=>{let o=n?un([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):un(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:a})),o.on("error",()=>s({code:1,stdout:r,stderr:a}))})}import{mkdir as Gt,readdir as ds,readFile as Bt,stat as Vt,writeFile as Kt}from"fs/promises";import{spawnSync as Yt}from"child_process";import{homedir as To}from"os";import{resolve as Co,isAbsolute as Ro,join as X,normalize as xo}from"path";import*as S from"@clack/prompts";import h from"picocolors";var oi={GB:"44",US:"1",CA:"1",AU:"61",NZ:"64",IE:"353",DE:"49",FR:"33",ES:"34",IT:"39",NL:"31",BE:"32",CH:"41",AT:"43",PT:"351",SE:"46",NO:"47",DK:"45",FI:"358",PL:"48",ZA:"27"},ri={US:{pre:"$"},CA:{pre:"$"},AU:{pre:"$"},NZ:{pre:"$"},GB:{pre:"\xA3"},IE:{pre:"\u20AC"},DE:{pre:"\u20AC"},FR:{pre:"\u20AC"},ES:{pre:"\u20AC"},IT:{pre:"\u20AC"},NL:{pre:"\u20AC"},BE:{pre:"\u20AC"},AT:{pre:"\u20AC"},PT:{pre:"\u20AC"},FI:{pre:"\u20AC"},CH:{pre:"CHF "},SE:{post:" kr"},NO:{post:" kr"},DK:{post:" kr"},PL:{post:" z\u0142"},ZA:{pre:"R"}};function hn(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9.,  ]*$/.test(n))return n;let s=ri[(t??"").toUpperCase()];return s?`${s.pre??""}${n}${s.post??""}`:n}function $t(e,t){if(!e)return e;let n=e.replace(/[\s().-]/g,"");if(/^\+\d{8,15}$/.test(n))return n;if(/^00\d{8,15}$/.test(n))return`+${n.slice(2)}`;let s=t?oi[t.toUpperCase()]:void 0;return s==="1"&&/^1?\d{10}$/.test(n)?`+1${n.slice(-10)}`:s&&s!=="1"&&/^0\d{7,14}$/.test(n)?`+${s}${n.slice(1)}`:e}var Nt="claude-code",Mt="gpt-5.6-terra";function mn(e){if(e==="claude-code"||e==="codex")return e}var ai=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function et(e){let t=e?.trim().toLowerCase()??"";return ai.includes(t)?t:void 0}function tt(e){let t=e?.trim().toLowerCase();if(t==="on"||t==="true"||t==="yes"||t==="1")return"on";if(t==="off"||t==="false"||t==="no"||t==="0")return"off"}var Dt="vercel";function gn(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function yn(e){if(e==="telegram"||e==="email"||e==="sms")return e}function wn(e){if(e==="password"||e==="oauth-microsoft")return e}function li(e){if(e==="custom"||e!==void 0&&Object.hasOwn(J,e))return e}function nt(e){let t=li(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[s,o]of Object.entries(J))if(o.smtpHost===n)return s;return"custom"}}function kn(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let s of t.split(",")){let o=s.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(s=>{let o=/^[a-z0-9_]+$/.test(s)&&s!=="auto",r=l=>{let c=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`];return c?.trim()?c.trim():void 0},a=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(l=>!r(l)).map(l=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`);for(let l of["SMTP_PORT","IMAP_PORT"]){let c=r(l);c!==void 0&&!/^\d+$/.test(c)&&a.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`)}return{label:s,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:a,smtpHost:r("SMTP_HOST"),smtpPort:parseInt(r("SMTP_PORT")??"587",10),imapHost:r("IMAP_HOST"),imapPort:parseInt(r("IMAP_PORT")??"993",10),password:r("PASSWORD"),login:r("LOGIN")}})}function st(e){let t=[],n=l=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${l}`),t.push("# "+"=".repeat(60)),t.push("")},s=(l,c)=>{if(c==null||c===""){t.push(`# ${l}=`);return}let f=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(f)){let u=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${l}="${u}"`)}else t.push(`${l}=${f}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),s("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),s("AI_AGENT",e.aiAgent??Nt),s("AI_PLAN",e.aiPlan),s("QA_PHASE",e.qaPhase??Ae(e.aiPlan)),n("Operating country and language"),s("OPERATOR_COUNTRY",e.country),s("OPERATOR_COUNTRY_CODE",e.countryCode),s("OPERATOR_LANGUAGE",e.language),s("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let o=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];s("PIPELINE_MODES",[...new Set(o)].join(",")),n("Pricing"),s("PRICING",hn(e.pricing,e.countryCode)),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",hn(e.pricingMonthly,e.countryCode)),n("Automated outreach features"),s("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),s("OPERATOR_NAME",e.name),s("SIGNATURE",e.signature),s("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),s("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),s("EMAIL_PROVIDER",e.emailProvider),s("EMAIL_AUTH",e.emailAuth??"password"),s("EMAIL_ADDRESS",e.emailAddress),s("EMAIL_PASSWORD",e.emailPassword),s("EMAIL_FROM_NAME",e.emailFromName),s("EMAIL_SMTP_HOST",e.emailSmtpHost),s("EMAIL_SMTP_PORT",e.emailSmtpPort),s("EMAIL_IMAP_HOST",e.emailImapHost),s("EMAIL_IMAP_PORT",e.emailImapPort),s("EMAIL_SENT_FOLDER",e.emailSentFolder),s("EMAIL_INBOX_FOLDER",e.emailInboxFolder),s("EMAIL_DRAFTS_FOLDER",e.emailDraftsFolder),n("SMS outreach"),s("SMS_PROVIDER",e.smsProvider),s("TEST_PHONE",$t(e.testPhone,e.countryCode)),s("TWILIO_ACCOUNT_SID",e.twilioAccountSid),s("TWILIO_AUTH_TOKEN",e.twilioAuthToken),s("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),s("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Letter outreach"),s("LETTER_PROVIDER",e.letterProvider??"none"),s("PINGEN_CLIENT_ID",e.pingenClientId),s("PINGEN_CLIENT_SECRET",e.pingenClientSecret),s("PINGEN_ORG_ID",e.pingenOrgId),s("POSTGRID_API_KEY",e.postgridApiKey),n("Supabase (pipeline state)"),s("SUPABASE_URL",e.supabaseUrl),s("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),s("SUPABASE_ANON_KEY",e.supabaseAnonKey),s("SUPABASE_PAT",e.supabasePat),s("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),s("DEPLOY_PROVIDER",e.deployProvider??Dt),s("VERCEL_TOKEN",e.vercelToken),s("VERCEL_SCOPE",e.vercelScope??""),s("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),s("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),s("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),s("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),s("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),s("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),s("NOTIFY_CHANNEL",e.notifyChannel),s("NOTIFY_TO",e.notifyTo),s("TELEGRAM_BOT_TOKEN",e.telegramBotToken),s("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(l=>/^#?\s*([A-Z0-9_]+)=/.exec(l)?.[1]).filter(l=>!!l)),a=Object.entries(e.preservedEnv??{}).filter(([l])=>!r.has(l));if(a.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[l,c]of a)s(l,c)}return t.join(`
2
+ import{b as we,c as qe,d as X,e as x,f as on,g as rn,h as Qe,i as Je,j as de,k as an,l as ln,o as cn,q as Ae,r as Xe,s as N}from"./chunk-H4E3ZXDO.js";import{Command as Kr}from"commander";import{spawn as pn}from"child_process";import{existsSync as Ji}from"fs";import{homedir as Xi}from"os";import O from"picocolors";import{win32 as Di}from"path";var Fi=["&","^","%","!"];function Hi(e){return Fi.filter(t=>e.includes(t))}function Ee(e){let t=[];for(let{label:n,path:i}of e){let o=Hi(i);o.length>0&&t.push({label:n,path:i,chars:o})}return t}function Ui(e){let t=(e??"").trim().replace(/^["']|["']$/g,"");if(!t||t==="undefined"||t==="null")return null;let n=t.toLowerCase().split(/[\\/]/);if(n.length<2||n.includes("system32"))return null;let i=Di.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(i)?t:null}function Pe(e,t){let n=Ui(e);return n===null?!1:t?t(n):!0}function Se(e,t){let n=e[0],i=[...new Set(e.flatMap(f=>f.chars))],o=i.map(f=>`"${f}"`).join(", "),r=i.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${o} in it ${r?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${r?"will":"may"} fail here with a misleading demand to install Visual Studio \u2014 Visual Studio is NOT needed and installing it will not fix this. Instead point npm's build steps at a shell that parses these paths correctly: PowerShell 7 (pwsh) or Git Bash, whichever is installed \u2014 npm config set script-shell "<full path to pwsh.exe or bash.exe>" (applies to all npm projects on this machine) \u2014 ${t==="preflight"?'then re-run this preflight \u2014 the "Install path safe for npm builds" check passes once script-shell is set.':t==="doctor"?"then re-run doctor \u2014 this check passes once script-shell is set.":'then re-run `npx klaudius@latest install`; `npx klaudius@latest doctor` confirms the fix (its "Install path safe for npm builds" check passes once script-shell is set).'} Windows PowerShell 5.1 ("powershell") will NOT work: it can't run the "||" in packages' install scripts. If neither shell is installed, PowerShell 7 is a small download: winget install Microsoft.PowerShell. If only the PROJECT folder is affected (not the user folder), moving the project to a plain path like C:\\klaudius also fixes it, or scope the npm setting to just this project by adding --location=project (run inside the project folder).`}}function ue(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),i=parseInt(t[2],10),o=parseInt(t[3],10),r=`${n}.${i}.${o}`;return n<22||n===22&&i<15?{ok:!1,version:r,major:n,minor:i,message:`Your installed Node.js is ${r}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:r,major:n,minor:i}}import{spawn as ji}from"child_process";import{existsSync as Ki}from"fs";import{homedir as Gi}from"os";import{delimiter as Vi,join as Ze}from"path";var Bi=new Set(["Restricted","AllSigned"]);function Yi(e,t=Ki){for(let n of e.split(Vi)){let i=n.replace(/"/g,"");if(!i)continue;let o=Ze(i,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let a=Ze(i,r);if(t(a))return{path:a,isPs1:!1}}}return null}async function un(){let e=Yi(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Wi();if(!t)return{blocked:!1,shimPath:e.path};let n=Ze(Gi(),".local","node")+"\\";return{blocked:Bi.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Wi(){let e=Ze(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await dn(e)??await dn("powershell.exe")}function dn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let i=ji(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",r=setTimeout(()=>{i.kill(),n(null)},8e3);i.stdout.on("data",a=>{o+=a.toString()}),i.stderr?.resume(),i.on("close",a=>{clearTimeout(r),n(a===0&&o.trim()?o.trim():null)}),i.on("error",()=>{clearTimeout(r),n(null)})})}import{spawn as zi}from"child_process";var Ue=3,et=10,qi=[["python3"],["python"],["py","-3"]];async function K(){for(let e of qi){let t=await tt(e[0],[...e.slice(1),"--version"]),n=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(n)||t.code!==0)continue;let i=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!i)continue;let o=parseInt(i[1],10),r=parseInt(i[2],10),a=i[3]?`${o}.${r}.${i[3]}`:`${o}.${r}`;return{command:[...e],version:a,major:o,minor:r}}return null}async function be(){let e=Qi(),t=await K();if(!t){let a=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${Ue}.${et}+ is not installed (or not on PATH). Install it from ${e}.`+a}}let{command:n,version:i,major:o,minor:r}=t;return o<Ue||o===Ue&&r<et?{ok:!1,version:i,major:o,minor:r,command:n,message:`Your installed Python is ${i}. Klaudius needs Python ${Ue}.${et} or newer (the pipeline depends on packages that only ship wheels for ${Ue}.${et}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:i,major:o,minor:r,command:n}}function Qi(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function tt(e,t){return new Promise(n=>{let i=zi(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";i.stdout?.on("data",a=>{o+=a.toString()}),i.stderr?.on("data",a=>{r+=a.toString()}),i.on("close",a=>n({code:a??1,stdout:o,stderr:r})),i.on("error",()=>n({code:1,stdout:o,stderr:r}))})}var fn=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function hn(e={}){console.log(O.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
+ `));let t=[];t.push(Zi());let n=await be();if(t.push(es(n)),t.push(await ts(n.command)),t.push(await ns()),process.platform==="win32"){let o=await is();o&&t.push(o);let r=await ss();r&&t.push(r)}t.push(await os());for(let o of t){let r=o.status==="ok"?O.green("\u2713"):o.status==="warn"?O.yellow("!"):O.red("\u2717");console.log(` ${r} ${o.name}${o.detail?O.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${O.dim("\u2192")} ${O.cyan(o.nextAction)}`)}console.log();let i=t.filter(o=>o.status==="fail");if(i.length===0){let o=t.filter(r=>r.status==="warn").length;rs(o);return}console.log(O.red(O.bold(`${i.length} check${i.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(O.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(O.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Zi(){let e=ue();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal window before re-running."}}function es(e){return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:e.message??"Install Python 3.10+ from https://www.python.org/downloads/"}}async function ts(e){let t=e??["python3"],n=await nt(t[0],[...t.slice(1),"-m","pip","--version"]);return n.code===0?{name:"pip available",status:"ok",detail:(n.stdout||n.stderr).trim().split(`
4
+ `)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function ns(){let e=process.platform==="win32",t=await nt("npm",["--version"],e);return t.code!==0?{name:"npm / npx available",status:"fail",detail:"npm not found",nextAction:"npm ships with Node.js \u2014 reinstall Node from https://nodejs.org/."}:(await nt("npx",["--version"],e)).code!==0?{name:"npm / npx available",status:"fail",detail:`npm ${t.stdout.trim()} ok, npx missing`,nextAction:"npx ships with npm 5.2+ \u2014 reinstall Node from https://nodejs.org/."}:{name:"npm / npx available",status:"ok",detail:`npm ${t.stdout.trim()}`}}async function is(){let e=await un();if(e.npxMissing)return null;let t="npx runs in PowerShell";if(!e.blocked){let n="resolves to a policy-immune shim";return e.shimPath&&(n=e.policy?`ExecutionPolicy ${e.policy} allows the npx.ps1 shim`:"npx.ps1 shim present but ExecutionPolicy unreadable \u2014 assuming it runs"),{name:t,status:"ok",detail:n}}return{name:t,status:"fail",detail:`ExecutionPolicy ${e.policy} blocks ${e.shimPath}, which PowerShell prefers over npx.cmd`,nextAction:e.ownInstall?`In PowerShell run: Remove-Item "$env:USERPROFILE\\.local\\node\\np*.ps1" \u2014 it deletes only the PowerShell shims from Klaudius's own Node install (npx falls back to npx.cmd). It prints nothing back; that means it worked. Then re-run this preflight.`:"In Windows PowerShell (the classic blue one, not PowerShell 7) run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned \u2014 printing nothing back means it worked; confirm with Get-ExecutionPolicy (should say RemoteSigned), then re-run this preflight. If it prints an error instead, your organisation manages this setting \u2014 ask IT."}}async function ss(){let e=Ee([{label:"your Windows user folder",path:Xi()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await nt("npm",["config","get","script-shell"],!0),i=n.code===0?n.stdout.trim():void 0;if(Pe(i,Ji))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(l=>`"${l}"`).join(", ")}, but npm's script-shell (${i}) handles it`};let{detail:o,action:r}=Se(e,"preflight"),a=e.some(l=>l.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function os(){try{return await fetch(fn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:fn}}catch(e){return{name:"klaudius.dev reachable",status:"fail",detail:e.name==="TimeoutError"?"timed out":"could not connect",nextAction:"Check your internet connection, VPN, or firewall \u2014 init needs klaudius.dev to validate your license and download the template."}}}function rs(e=0){e>0?console.log(O.green(O.bold("Your machine is ready."))+O.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(O.green(O.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(O.bold("NEXT STEP \u2014 this one is for you to run, not the AI assistant:")),console.log(" It's an interactive wizard (it asks for your license key and passwords),"),console.log(" so the assistant can't fill it in. Open a NEW terminal WINDOW and run:"),console.log(),console.log(` ${O.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(O.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(O.dim(" run it in a new terminal window.")),console.log()}function nt(e,t,n=!1){return new Promise(i=>{let o=n?pn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):pn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>i({code:l??1,stdout:r,stderr:a})),o.on("error",()=>i({code:1,stdout:r,stderr:a}))})}import{mkdir as Gt,readdir as ui,readFile as Vt,stat as Bt,writeFile as Kt}from"fs/promises";import{spawnSync as Yt}from"child_process";import{homedir as vo}from"os";import{resolve as Oo,isAbsolute as Lo,join as Z,normalize as $o}from"path";import*as P from"@clack/prompts";import h from"picocolors";var as={GB:"44",US:"1",CA:"1",AU:"61",NZ:"64",IE:"353",DE:"49",FR:"33",ES:"34",IT:"39",NL:"31",BE:"32",CH:"41",AT:"43",PT:"351",SE:"46",NO:"47",DK:"45",FI:"358",PL:"48",ZA:"27"},ls={US:{pre:"$"},CA:{pre:"$"},AU:{pre:"$"},NZ:{pre:"$"},GB:{pre:"\xA3"},IE:{pre:"\u20AC"},DE:{pre:"\u20AC"},FR:{pre:"\u20AC"},ES:{pre:"\u20AC"},IT:{pre:"\u20AC"},NL:{pre:"\u20AC"},BE:{pre:"\u20AC"},AT:{pre:"\u20AC"},PT:{pre:"\u20AC"},FI:{pre:"\u20AC"},CH:{pre:"CHF "},SE:{post:" kr"},NO:{post:" kr"},DK:{post:" kr"},PL:{post:" z\u0142"},ZA:{pre:"R"}};function mn(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9.,  ]*$/.test(n))return n;let i=ls[(t??"").toUpperCase()];return i?`${i.pre??""}${n}${i.post??""}`:n}function $t(e,t){if(!e)return e;let n=e.replace(/[\s().-]/g,"");if(/^\+\d{8,15}$/.test(n))return n;if(/^00\d{8,15}$/.test(n))return`+${n.slice(2)}`;let i=t?as[t.toUpperCase()]:void 0;return i==="1"&&/^1?\d{10}$/.test(n)?`+1${n.slice(-10)}`:i&&i!=="1"&&/^0\d{7,14}$/.test(n)?`+${i}${n.slice(1)}`:e}var Nt="claude-code",Mt="gpt-5.6-terra";function gn(e){if(e==="claude-code"||e==="codex")return e}var cs=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function it(e){let t=e?.trim().toLowerCase()??"";return cs.includes(t)?t:void 0}function st(e){let t=e?.trim().toLowerCase();if(t==="on"||t==="true"||t==="yes"||t==="1")return"on";if(t==="off"||t==="false"||t==="no"||t==="0")return"off"}var Dt="vercel";function yn(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function kn(e){if(e==="telegram"||e==="email"||e==="sms")return e}function wn(e){if(e==="password"||e==="oauth-microsoft")return e}function ds(e){if(e==="custom"||e!==void 0&&Object.hasOwn(X,e))return e}function ot(e){let t=ds(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[i,o]of Object.entries(X))if(o.smtpHost===n)return i;return"custom"}}function An(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let i of t.split(",")){let o=i.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(i=>{let o=/^[a-z0-9_]+$/.test(i)&&i!=="auto",r=l=>{let c=e[`EMAIL_ACCOUNT_${i.toUpperCase()}_${l}`];return c?.trim()?c.trim():void 0},a=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(l=>!r(l)).map(l=>`EMAIL_ACCOUNT_${i.toUpperCase()}_${l}`);for(let l of["SMTP_PORT","IMAP_PORT"]){let c=r(l);c!==void 0&&!/^\d+$/.test(c)&&a.push(`EMAIL_ACCOUNT_${i.toUpperCase()}_${l}`)}return{label:i,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:a,smtpHost:r("SMTP_HOST"),smtpPort:parseInt(r("SMTP_PORT")??"587",10),imapHost:r("IMAP_HOST"),imapPort:parseInt(r("IMAP_PORT")??"993",10),password:r("PASSWORD"),login:r("LOGIN")}})}function rt(e){let t=[],n=l=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${l}`),t.push("# "+"=".repeat(60)),t.push("")},i=(l,c)=>{if(c==null||c===""){t.push(`# ${l}=`);return}let f=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(f)){let u=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${l}="${u}"`)}else t.push(`${l}=${f}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),i("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),i("AI_AGENT",e.aiAgent??Nt),i("AI_PLAN",e.aiPlan),i("QA_PHASE",e.qaPhase??Ae(e.aiPlan)),n("Operating country and language"),i("OPERATOR_COUNTRY",e.country),i("OPERATOR_COUNTRY_CODE",e.countryCode),i("OPERATOR_LANGUAGE",e.language),i("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let o=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];i("PIPELINE_MODES",[...new Set(o)].join(",")),n("Pricing"),i("PRICING",mn(e.pricing,e.countryCode)),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",mn(e.pricingMonthly,e.countryCode)),n("Automated outreach features"),i("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),i("OPERATOR_NAME",e.name),i("SIGNATURE",e.signature),i("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),i("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),i("EMAIL_PROVIDER",e.emailProvider),i("EMAIL_AUTH",e.emailAuth??"password"),i("EMAIL_ADDRESS",e.emailAddress),i("EMAIL_PASSWORD",e.emailPassword),i("EMAIL_FROM_NAME",e.emailFromName),i("EMAIL_SMTP_HOST",e.emailSmtpHost),i("EMAIL_SMTP_PORT",e.emailSmtpPort),i("EMAIL_IMAP_HOST",e.emailImapHost),i("EMAIL_IMAP_PORT",e.emailImapPort),i("EMAIL_SENT_FOLDER",e.emailSentFolder),i("EMAIL_INBOX_FOLDER",e.emailInboxFolder),i("EMAIL_DRAFTS_FOLDER",e.emailDraftsFolder),n("SMS outreach"),i("SMS_PROVIDER",e.smsProvider),i("TEST_PHONE",$t(e.testPhone,e.countryCode)),i("TWILIO_ACCOUNT_SID",e.twilioAccountSid),i("TWILIO_AUTH_TOKEN",e.twilioAuthToken),i("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),i("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Letter outreach"),i("LETTER_PROVIDER",e.letterProvider??"none"),i("PINGEN_CLIENT_ID",e.pingenClientId),i("PINGEN_CLIENT_SECRET",e.pingenClientSecret),i("PINGEN_ORG_ID",e.pingenOrgId),i("POSTGRID_API_KEY",e.postgridApiKey),n("Supabase (pipeline state)"),i("SUPABASE_URL",e.supabaseUrl),i("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),i("SUPABASE_ANON_KEY",e.supabaseAnonKey),i("SUPABASE_PAT",e.supabasePat),i("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),i("DEPLOY_PROVIDER",e.deployProvider??Dt),i("VERCEL_TOKEN",e.vercelToken),i("VERCEL_SCOPE",e.vercelScope??""),i("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),i("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),i("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),i("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),i("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),i("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),i("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),i("NOTIFY_CHANNEL",e.notifyChannel),i("NOTIFY_TO",e.notifyTo),i("TELEGRAM_BOT_TOKEN",e.telegramBotToken),i("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(l=>/^#?\s*([A-Z0-9_]+)=/.exec(l)?.[1]).filter(l=>!!l)),a=Object.entries(e.preservedEnv??{}).filter(([l])=>!r.has(l));if(a.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[l,c]of a)i(l,c)}return t.join(`
5
5
  `)+`
6
- `}function it(e){let t={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(t,null,2)+`
7
- `}function ot(e){let t=e.supabaseProjectRef,n=ci(e.supabasePat);return["# Codex MCP config \u2014 generated by `npx klaudius init` / `configure`.","# Edit freely. NEVER commit this file \u2014 .gitignore already excludes it.","# See `.codex/config.toml.example` for the documented format.","",...e.aiPlan==="codex-plus"?["# Set by the wizard for ChatGPT Plus. Change or delete to use Codex's default.",`model = "${Mt}"`,""]:[],"[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${t}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${n}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
8
- `)}function ci(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var An=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel', 'cloudflare', or 'netlify'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch host, run `npx klaudius@latest configure` (Cloudflare adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID; Netlify adds NETLIFY_AUTH_TOKEN)."},{key:"PIPELINE_MODES",value:"classic",comment:"Lead streams the pipeline targets \u2014 any combination of 'classic' (no website at all), 'rescue' (existing website verifiably dead or bad) and 'booking' (Google-listed website is a booking-platform page), at least one. Pre-modes installs targeted no-website businesses only \u2014 this records that explicitly. Edit the list (e.g. 'classic,rescue,booking') or re-run `npx klaudius@latest configure`."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'},{key:"NOTIFY_CHANNEL",value:"telegram",comment:"How scripts/notify.sh routes pipeline alerts: 'telegram' (default), 'email' (to your own inbox), or 'sms' (to your own phone). Pre-NOTIFY_CHANNEL installs alerted via Telegram, so this records that explicitly. NOTIFY_TO optionally overrides the email/sms destination."},{key:"QA_PHASE",value:"on",comment:"'on' runs the independent QA pass after each build (the behaviour this install already had); 'off' goes straight from build to deploy for more sites per usage window. Flip it here any time, or run `npx klaudius@latest configure` and pick your plan to get the matching default."}];function di(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function En(e,t,n){let s=n.filter(a=>!(a.key in t));if(s.length===0)return null;let o=e.endsWith(`
6
+ `}function at(e){let t={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(t,null,2)+`
7
+ `}function lt(e){let t=e.supabaseProjectRef,n=us(e.supabasePat);return["# Codex MCP config \u2014 generated by `npx klaudius init` / `configure`.","# Edit freely. NEVER commit this file \u2014 .gitignore already excludes it.","# See `.codex/config.toml.example` for the documented format.","",...e.aiPlan==="codex-plus"?["# Set by the wizard for ChatGPT Plus. Change or delete to use Codex's default.",`model = "${Mt}"`,""]:[],"[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${t}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${n}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
8
+ `)}function us(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var En=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel', 'cloudflare', or 'netlify'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch host, run `npx klaudius@latest configure` (Cloudflare adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID; Netlify adds NETLIFY_AUTH_TOKEN)."},{key:"PIPELINE_MODES",value:"classic",comment:"Lead streams the pipeline targets \u2014 any combination of 'classic' (no website at all), 'rescue' (existing website verifiably dead or bad) and 'booking' (Google-listed website is a booking-platform page), at least one. Pre-modes installs targeted no-website businesses only \u2014 this records that explicitly. Edit the list (e.g. 'classic,rescue,booking') or re-run `npx klaudius@latest configure`."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'},{key:"NOTIFY_CHANNEL",value:"telegram",comment:"How scripts/notify.sh routes pipeline alerts: 'telegram' (default), 'email' (to your own inbox), or 'sms' (to your own phone). Pre-NOTIFY_CHANNEL installs alerted via Telegram, so this records that explicitly. NOTIFY_TO optionally overrides the email/sms destination."},{key:"QA_PHASE",value:"on",comment:"'on' runs the independent QA pass after each build (the behaviour this install already had); 'off' goes straight from build to deploy for more sites per usage window. Flip it here any time, or run `npx klaudius@latest configure` and pick your plan to get the matching default."}];function ps(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function Pn(e,t,n){let i=n.filter(a=>!(a.key in t));if(i.length===0)return null;let o=e.endsWith(`
9
9
  `)?"":`
10
- `,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let a of s)r.push(""),a.comment&&r.push(`# ${a.comment}`),r.push(di(a.key,a.value));return e+o+r.join(`
10
+ `,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let a of i)r.push(""),a.comment&&r.push(`# ${a.comment}`),r.push(ps(a.key,a.value));return e+o+r.join(`
11
11
  `)+`
12
- `}function ui(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function G(e){let t={};for(let n of e.split(`
13
- `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),a=ui(s.slice(o+1).trim());t[r]=a}return t}function Pn(e){let t=l=>{let c=e[l];if(!c)return;let f=parseInt(c,10);return isNaN(f)?void 0:f},n=e.SMS_PROVIDER,s=l=>l==="email"||l==="sms"||l==="whatsapp"||l==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(l=>l.trim()).filter(s),r=e.OUTREACH_PRIORITY?.split(",").map(l=>l.trim()).filter(s),a=e.WHATSAPP_ACCOUNTS?.split(",").map(l=>l.trim()).filter(l=>l.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:mn(e.AI_AGENT)??Nt,aiPlan:et(e.AI_PLAN),qaPhase:tt(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:r&&r.length>0?r:void 0,whatsappAccounts:a&&a.length>0?a:void 0,emailProvider:nt(e),emailAuth:wn(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:n==="imessage"||n==="twilio"?n:void 0,testPhone:$t(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:gn(e.DEPLOY_PROVIDER)??Dt,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN||void 0,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID||void 0,netlifyAuthToken:e.NETLIFY_AUTH_TOKEN||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:e.SELFHOST_DEPLOY_TARGET||void 0,selfhostUrlTemplate:e.SELFHOST_URL_TEMPLATE||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,emailPassword:e.EMAIL_PASSWORD,notifyChannel:yn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function rt(e){let t=_=>{let ce=e[_];if(!ce)return;let j=parseInt(ce,10);return isNaN(j)?void 0:j},n=e.SUPABASE_URL,s=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),r=e.SUPABASE_PROJECT_REF,a=e.PRICING,l=e.PRICING_TERMS||"one-off, no monthly fees",c=gn(e.DEPLOY_PROVIDER)??Dt,f=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,k=e.CLOUDFLARE_ACCOUNT_ID,d=e.NETLIFY_AUTH_TOKEN,P=e.SELFHOST_DEPLOY_TARGET,y=e.SELFHOST_URL_TEMPLATE;if(!a||!n||!s||!o||!r||!(c==="cloudflare"?!!u&&!!k:c==="netlify"?!!d:c==="selfhost"?!!P&&!!y:!!f))return null;let b=e.SMS_PROVIDER,C=_=>_==="email"||_==="sms"||_==="whatsapp"||_==="letter",V=e.OUTREACH_CHANNELS?.split(",").map(_=>_.trim()).filter(C),le=e.OUTREACH_PRIORITY?.split(",").map(_=>_.trim()).filter(C),R=e.WHATSAPP_ACCOUNTS?.split(",").map(_=>_.trim()).filter(_=>_.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:mn(e.AI_AGENT)??Nt,aiPlan:et(e.AI_PLAN),qaPhase:tt(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(_=>_.trim().toLowerCase()).filter(Boolean):void 0,pricing:a,pricingTerms:l,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:V&&V.length>0?V:void 0,outreachPriority:le&&le.length>0?le:void 0,whatsappAccounts:R&&R.length>0?R:void 0,emailProvider:nt(e),emailAuth:wn(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:b==="imessage"||b==="twilio"?b:void 0,testPhone:$t(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,deployProvider:c,vercelToken:f,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:k||void 0,netlifyAuthToken:d||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:P||void 0,selfhostUrlTemplate:y||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:yn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as ha,mkdir as ma,readdir as ki,stat as ga}from"fs/promises";import{dirname as wa,join as Rn,relative as Ai,sep as Ei}from"path";import{fileURLToPath as Aa}from"url";import{createHash as Sn}from"crypto";import{readFile as pi}from"fs/promises";async function _e(e){let t=await pi(e);return Sn("sha256").update(t).digest("hex")}function Ft(e){return Sn("sha256").update(e).digest("hex")}import{mkdir as fi,readFile as hi,writeFile as mi,access as gi}from"fs/promises";import{dirname as yi,join as bn}from"path";var wi=".klaudius",_n=`${wi}/manifest.json`,at=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json"]),In=new Set(["clients/README.md"]),lt=new Set(["package-lock.json"]);async function Tn(e){let t=bn(e,_n);try{await gi(t)}catch{return null}let n=await hi(t,"utf-8"),s=JSON.parse(n),o={};for(let[r,a]of Object.entries(s.files??{}))o[r.split("\\").join("/")]=a;return s.files=o,Array.isArray(s.ignored)?s.ignored=s.ignored.filter(r=>typeof r=="string").map(r=>r.split("\\").join("/")):delete s.ignored,s}async function Fe(e,t){let n=bn(e,_n);await fi(yi(n),{recursive:!0}),await mi(n,JSON.stringify(t,null,2)+`
14
- `,"utf-8")}function Cn(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function ge(e,t=e){let n=await ki(e,{withFileTypes:!0}),s=[];for(let o of n){let r=Rn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await ge(r,t)):o.isFile()&&s.push(Ai(t,r).split(Ei).join("/")))}return s}async function xn(e){let t=await ge(e),n={};for(let s of t)at.has(s)||(n[s]=await _e(Rn(e,s)));return n}import{copyFile as Pi,mkdir as On,mkdtemp as Si,readdir as vn,rm as Ln}from"fs/promises";import{tmpdir as bi}from"os";import{dirname as _i,join as ct}from"path";import{Readable as Ii}from"stream";import*as $n from"tar";var Ti="https://klaudius.dev/api/template";function Ci(e){return Ii.fromWeb(e)}async function dt(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Ti,n="0.32.1",s;try{s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(l){throw new Error(`Could not reach klaudius.dev to download the template: ${T(l)}`)}if(!s.ok){let l="";try{let c=await s.json();l=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${l}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),r=await Si(ct(bi(),"klaudius-template-")),a=0;try{try{await new Promise((f,u)=>{let k=$n.extract({cwd:r,strict:!0});k.on("finish",f),k.on("error",u),Ci(s.body).on("error",u).pipe(k)})}catch(f){throw new Error(`Failed to extract template archive: ${f.message}`)}await On(e.destDir,{recursive:!0});let l=new Set(await vn(e.destDir)),c=await ge(r);try{for(let f of c){let u=ct(e.destDir,f);await On(_i(u),{recursive:!0}),await Pi(ct(r,f),u),a++}}catch(f){let u=await vn(e.destDir).catch(()=>[]);for(let k of u)l.has(k)||await Ln(ct(e.destDir,k),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${f.message}`)}}finally{await Ln(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:a,tier:o}}import{copyFile as Ri,mkdir as xi,readFile as Nn,rm as Oi}from"fs/promises";import{dirname as vi,join as ye}from"path";import{structuredPatch as Li}from"diff";var Mn=ye(".klaudius","base"),ut=ye(".klaudius","conflict-base");async function pt(e,t,n){let s=ye(e,Mn);await Oi(s,{recursive:!0,force:!0});for(let o of n){let r=ye(s,o);await xi(vi(r),{recursive:!0}),await Ri(ye(t,o),r)}}async function Dn(e,t){try{return await Nn(ye(e,Mn,t),"utf-8")}catch{return null}}async function Fn(e,t){try{return await Nn(ye(e,ut,t),"utf-8")}catch{return null}}function Hn(e,t,n,s){return Ie(n)?null:e!==null&&!Ie(e)&&(!s||Ft(e)===s)?e:t!==null&&!Ie(t)&&s&&Ft(t)===s?t:null}function Ie(e){return e.includes("\0")||e.includes("\uFFFD")}function Un(e,t,n=60){let s=Li("base","new",e,t,"","",{context:2});if(s.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=s.hunks.map(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),r=[`Upstream changed ${s.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],a=0,l=!1;for(let c of s.hunks){if(a>=n){l=!0;break}r.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),a+=1;let f=Math.max(n-a,0),u=c.lines.slice(0,f);if(r.push(...u),a+=u.length,u.length<c.lines.length){l=!0;break}}return r.push("```"),l&&r.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),r}import pe from"picocolors";var i={info:e=>console.log(pe.cyan("\u2139"),e),success:e=>console.log(pe.green("\u2713"),e),warn:e=>console.log(pe.yellow("\u26A0"),e),error:e=>console.error(pe.red("\u2717"),e),step:e=>console.log(pe.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
15
- `+pe.bold(pe.cyan(e))),detail:e=>console.log(pe.dim(" "+e))};var $i="https://registry.npmjs.org/klaudius/latest";async function Ni(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch($i,{signal:t.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let o=await s.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function Mi(e,t){let n=r=>r.split("-")[0].split(".").map(a=>Number.parseInt(a,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(s[r])||Number.isNaN(o[r]))return!1;if(s[r]>o[r])return!0;if(s[r]<o[r])return!1}return!1}async function ft(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Ni();!n||!Mi(n,t)||(i.blank(),i.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(i.detail("Your project content is fetched fresh either way, so you're not missing any"),i.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),i.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),i.blank())}import{createHash as Di}from"crypto";import{hostname as jn,userInfo as Fi,platform as Kn,arch as Gn}from"os";var Hi="https://klaudius.dev",Ui="/api/licenses/validate",ji="0.32.1";async function Bn(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),s=(process.env.KLAUDIUS_API_URL??Hi).replace(/\/$/,"")+Ui,o=He(),r;try{r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:jn(),os:`${Kn()}-${Gn()}`,cli_version:ji})})}catch(l){return{ok:!1,reason:`Could not reach the Klaudius license server (${T(l)}). Check your internet connection or try again later.`}}let a;try{a=await r.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${r.status}).`}}return a.ok?{ok:!0,tier:a.tier??"core"}:{ok:!1,reason:a.reason??`License rejected (HTTP ${r.status}).`}}function He(){let e=[jn(),Fi().username,Kn(),Gn()].join("|");return Di("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Ki}from"fs/promises";import{join as Gi}from"path";async function Te(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${T(n)}`}}}async function Vn(e){let t;try{t=await Ki(Gi(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(s){return{ok:!1,message:`Could not read scripts/schema.sql: ${s.message}`}}let n=e.pat.replace(/\s+/g,"");try{let s=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(s.ok)return{ok:!0};let o=await s.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(i.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${s.status}): ${o.slice(0,300)}`}}catch(s){return{ok:!1,message:`Schema apply failed: ${s.message}`}}}async function ht(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${T(t)}`}}}var Yn="https://api.cloudflare.com/client/v4";function Wn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function mt(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${Yn}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let r=await o.json(),a=r.result?.status;if(r.success===!1||a&&a!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${a?` (status: ${a})`:""}. ${Wn(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${T(o)}`}}try{let o=await fetch(`${Yn}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let r=await o.json();return r.success===!1?{ok:!1,message:Wn(r)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(r.result)?r.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${T(o)}`}}}var zn="https://api.netlify.com/api/v1";async function gt(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${zn}/user`,{headers:n});if(s.status===401||s.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} verifying the token. Try again or check netlifystatus.com.`}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${T(s)}`}}try{let s=await fetch(`${zn}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),r=Array.isArray(o)?o:[];if(r.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let a=typeof r[0]?.slug=="string"?r[0].slug:void 0;return{ok:!0,accountCount:r.length,accountSlug:a}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${T(s)}`}}}function Bi(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,s=/caller does not have permission|billing/i.test(t)?"This usually means the key's Google Cloud project has no active billing account \u2014 Places needs billing set up even though Google's free monthly credit covers normal use. Check https://console.cloud.google.com/billing for the project this key belongs to. (Less often: the key's restrictions block the Places API \u2014 check Credentials.)":"Common causes: the key is wrong or deleted, billing is not enabled on its Cloud project, or the key's restrictions block the Places API. Check https://console.cloud.google.com/billing and the key's entry under Credentials.";return`${n} ${s}`}async function Ce(e){let t=rn(e);if(t)return{ok:!1,message:t};let n=de(e),s=n.value,o=r=>{let a=[r],l=an(e);return l&&a.push(l),n.repairs.length>0&&a.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),a.join(`
16
- `)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let a={};try{a=await r.json()}catch{}let l=a.error?.message??"",c=a.error?.status??"";return r.status===400&&(c==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(l))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library/places.googleapis.com and press Enable for the project this key belongs to, then try again. (That page is 'Places API (New)' \u2014 the older 'Places API' is a different API and won't work.)"}:r.status===401||r.status===403?{ok:!1,message:o(Bi(r.status,l))}:{ok:!1,message:o(`Google API returned HTTP ${r.status}${l?`: ${l}`:""}.`)}}catch(r){return{ok:!1,message:`Could not reach Google: ${T(r)}`}}}import Vi from"nodemailer";import{ImapFlow as Yi}from"imapflow";function Wi(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function qn(e,t,n){let s=t.toLowerCase(),o=e.filter(Wi);if(o.some(l=>l.path.toLowerCase()===s))return;let r=s.startsWith("inbox")?void 0:[`inbox.${s}`,`inbox/${s}`],a=o.find(l=>l.specialUse===n)?.path??(r&&o.find(l=>r.includes(l.path.toLowerCase()))?.path);return{configured:t,detected:a||void 0}}function Qn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let s=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return s.includes("invalid credentials")||s.includes("authentication failed")||s.includes("auth failed")||s.includes("login failed")||s.includes("invalid login")?"auth":s.includes("etimedout")||s.includes("timeout")||s.includes("enotfound")||s.includes("getaddrinfo")||s.includes("econnrefused")||s.includes("econnreset")?"network":"other"}async function oe(e){let t=Vi.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(a){return{ok:!1,failedAt:"smtp",message:Jn(a,"SMTP",e.usesAccountPassword),failureKind:Qn(a)}}finally{t.close()}let n=new Yi({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),s,o,r;try{if(await n.connect(),e.sentFolder||e.draftsFolder)try{let a=await n.list();e.sentFolder&&(s=qn(a,e.sentFolder,"\\Sent")),e.draftsFolder&&(o=qn(a,e.draftsFolder,"\\Drafts"))}catch{r=!0}await n.logout()}catch(a){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Jn(a,"IMAP",e.usesAccountPassword),failureKind:Qn(a)}}return{ok:!0,sentFolderIssue:s,draftsFolderIssue:o,foldersUnverified:r}}function Jn(e,t,n){let s=e instanceof Error?e.message:String(e),o=s.toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
12
+ `}function fs(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function G(e){let t={};for(let n of e.split(`
13
+ `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o===-1)continue;let r=i.slice(0,o).trim(),a=fs(i.slice(o+1).trim());t[r]=a}return t}function Sn(e){let t=l=>{let c=e[l];if(!c)return;let f=parseInt(c,10);return isNaN(f)?void 0:f},n=e.SMS_PROVIDER,i=l=>l==="email"||l==="sms"||l==="whatsapp"||l==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(l=>l.trim()).filter(i),r=e.OUTREACH_PRIORITY?.split(",").map(l=>l.trim()).filter(i),a=e.WHATSAPP_ACCOUNTS?.split(",").map(l=>l.trim()).filter(l=>l.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:gn(e.AI_AGENT)??Nt,aiPlan:it(e.AI_PLAN),qaPhase:st(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:r&&r.length>0?r:void 0,whatsappAccounts:a&&a.length>0?a:void 0,emailProvider:ot(e),emailAuth:wn(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:n==="imessage"||n==="twilio"?n:void 0,testPhone:$t(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:yn(e.DEPLOY_PROVIDER)??Dt,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN||void 0,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID||void 0,netlifyAuthToken:e.NETLIFY_AUTH_TOKEN||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:e.SELFHOST_DEPLOY_TARGET||void 0,selfhostUrlTemplate:e.SELFHOST_URL_TEMPLATE||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,emailPassword:e.EMAIL_PASSWORD,notifyChannel:kn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function ct(e){let t=_=>{let ce=e[_];if(!ce)return;let j=parseInt(ce,10);return isNaN(j)?void 0:j},n=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),r=e.SUPABASE_PROJECT_REF,a=e.PRICING,l=e.PRICING_TERMS||"one-off, no monthly fees",c=yn(e.DEPLOY_PROVIDER)??Dt,f=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,A=e.CLOUDFLARE_ACCOUNT_ID,d=e.NETLIFY_AUTH_TOKEN,b=e.SELFHOST_DEPLOY_TARGET,g=e.SELFHOST_URL_TEMPLATE;if(!a||!n||!i||!o||!r||!(c==="cloudflare"?!!u&&!!A:c==="netlify"?!!d:c==="selfhost"?!!b&&!!g:!!f))return null;let S=e.SMS_PROVIDER,C=_=>_==="email"||_==="sms"||_==="whatsapp"||_==="letter",B=e.OUTREACH_CHANNELS?.split(",").map(_=>_.trim()).filter(C),le=e.OUTREACH_PRIORITY?.split(",").map(_=>_.trim()).filter(C),R=e.WHATSAPP_ACCOUNTS?.split(",").map(_=>_.trim()).filter(_=>_.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:gn(e.AI_AGENT)??Nt,aiPlan:it(e.AI_PLAN),qaPhase:st(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(_=>_.trim().toLowerCase()).filter(Boolean):void 0,pricing:a,pricingTerms:l,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:B&&B.length>0?B:void 0,outreachPriority:le&&le.length>0?le:void 0,whatsappAccounts:R&&R.length>0?R:void 0,emailProvider:ot(e),emailAuth:wn(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:S==="imessage"||S==="twilio"?S:void 0,testPhone:$t(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,deployProvider:c,vercelToken:f,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:A||void 0,netlifyAuthToken:d||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:b||void 0,selfhostUrlTemplate:g||void 0,supabaseUrl:n,supabaseServiceKey:i,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:kn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as wa,mkdir as Aa,readdir as Es,stat as Ea}from"fs/promises";import{dirname as Sa,join as Rn,relative as Ps,sep as Ss}from"path";import{fileURLToPath as _a}from"url";import{createHash as bn}from"crypto";import{readFile as hs}from"fs/promises";async function _e(e){let t=await hs(e);return bn("sha256").update(t).digest("hex")}function Ft(e){return bn("sha256").update(e).digest("hex")}import{mkdir as ms,readFile as gs,writeFile as ys,access as ks}from"fs/promises";import{dirname as ws,join as _n}from"path";var As=".klaudius",Tn=`${As}/manifest.json`,dt=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json"]),In=new Set(["clients/README.md"]),ut=new Set(["package-lock.json"]);async function Cn(e){let t=_n(e,Tn);try{await ks(t)}catch{return null}let n=await gs(t,"utf-8"),i=JSON.parse(n),o={};for(let[r,a]of Object.entries(i.files??{}))o[r.split("\\").join("/")]=a;return i.files=o,Array.isArray(i.ignored)?i.ignored=i.ignored.filter(r=>typeof r=="string").map(r=>r.split("\\").join("/")):delete i.ignored,i}async function je(e,t){let n=_n(e,Tn);await ms(ws(n),{recursive:!0}),await ys(n,JSON.stringify(t,null,2)+`
14
+ `,"utf-8")}function xn(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function ge(e,t=e){let n=await Es(e,{withFileTypes:!0}),i=[];for(let o of n){let r=Rn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?i.push(...await ge(r,t)):o.isFile()&&i.push(Ps(t,r).split(Ss).join("/")))}return i}async function vn(e){let t=await ge(e),n={};for(let i of t)dt.has(i)||(n[i]=await _e(Rn(e,i)));return n}import{copyFile as bs,mkdir as On,mkdtemp as _s,readdir as Ln,rm as $n}from"fs/promises";import{tmpdir as Ts}from"os";import{dirname as Is,join as pt}from"path";import{Readable as Cs}from"stream";import*as Nn from"tar";var xs="https://klaudius.dev/api/template";function Rs(e){return Cs.fromWeb(e)}async function ft(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??xs,n="0.32.3",i;try{i=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(l){throw new Error(`Could not reach klaudius.dev to download the template: ${x(l)}`)}if(!i.ok){let l="";try{let c=await i.json();l=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${i.status}${l}`)}if(!i.body)throw new Error("Template download succeeded but response had no body");let o=i.headers.get("x-klaudius-tier"),r=await _s(pt(Ts(),"klaudius-template-")),a=0;try{try{await new Promise((f,u)=>{let A=Nn.extract({cwd:r,strict:!0});A.on("finish",f),A.on("error",u),Rs(i.body).on("error",u).pipe(A)})}catch(f){throw new Error(`Failed to extract template archive: ${f.message}`)}await On(e.destDir,{recursive:!0});let l=new Set(await Ln(e.destDir)),c=await ge(r);try{for(let f of c){let u=pt(e.destDir,f);await On(Is(u),{recursive:!0}),await bs(pt(r,f),u),a++}}catch(f){let u=await Ln(e.destDir).catch(()=>[]);for(let A of u)l.has(A)||await $n(pt(e.destDir,A),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${f.message}`)}}finally{await $n(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:a,tier:o}}import{copyFile as vs,mkdir as Os,readFile as Mn,rm as Ls}from"fs/promises";import{dirname as $s,join as ye}from"path";import{structuredPatch as Ns}from"diff";var Dn=ye(".klaudius","base"),ht=ye(".klaudius","conflict-base");async function mt(e,t,n){let i=ye(e,Dn);await Ls(i,{recursive:!0,force:!0});for(let o of n){let r=ye(i,o);await Os($s(r),{recursive:!0}),await vs(ye(t,o),r)}}async function Fn(e,t){try{return await Mn(ye(e,Dn,t),"utf-8")}catch{return null}}async function Hn(e,t){try{return await Mn(ye(e,ht,t),"utf-8")}catch{return null}}function Un(e,t,n,i){return Te(n)?null:e!==null&&!Te(e)&&(!i||Ft(e)===i)?e:t!==null&&!Te(t)&&i&&Ft(t)===i?t:null}function Te(e){return e.includes("\0")||e.includes("\uFFFD")}function jn(e,t,n=60){let i=Ns("base","new",e,t,"","",{context:2});if(i.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=i.hunks.map(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),r=[`Upstream changed ${i.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],a=0,l=!1;for(let c of i.hunks){if(a>=n){l=!0;break}r.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),a+=1;let f=Math.max(n-a,0),u=c.lines.slice(0,f);if(r.push(...u),a+=u.length,u.length<c.lines.length){l=!0;break}}return r.push("```"),l&&r.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),r}import pe from"picocolors";var s={info:e=>console.log(pe.cyan("\u2139"),e),success:e=>console.log(pe.green("\u2713"),e),warn:e=>console.log(pe.yellow("\u26A0"),e),error:e=>console.error(pe.red("\u2717"),e),step:e=>console.log(pe.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
15
+ `+pe.bold(pe.cyan(e))),detail:e=>console.log(pe.dim(" "+e))};var Ms="https://registry.npmjs.org/klaudius/latest";async function Ds(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Ms,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let o=await i.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function Fs(e,t){let n=r=>r.split("-")[0].split(".").map(a=>Number.parseInt(a,10)),i=n(e),o=n(t);if(i.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(i[r])||Number.isNaN(o[r]))return!1;if(i[r]>o[r])return!0;if(i[r]<o[r])return!1}return!1}async function gt(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Ds();!n||!Fs(n,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(s.detail("Your project content is fetched fresh either way, so you're not missing any"),s.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),s.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),s.blank())}import{createHash as Hs}from"crypto";import{hostname as Kn,userInfo as Us,platform as Gn,arch as Vn}from"os";var js="https://klaudius.dev",Ks="/api/licenses/validate",Gs="0.32.3";async function Bn(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),i=(process.env.KLAUDIUS_API_URL??js).replace(/\/$/,"")+Ks,o=Ke(),r;try{r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Kn(),os:`${Gn()}-${Vn()}`,cli_version:Gs})})}catch(l){return{ok:!1,reason:`Could not reach the Klaudius license server (${x(l)}). Check your internet connection or try again later.`}}let a;try{a=await r.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${r.status}).`}}return a.ok?{ok:!0,tier:a.tier??"core"}:{ok:!1,reason:a.reason??`License rejected (HTTP ${r.status}).`}}function Ke(){let e=[Kn(),Us().username,Gn(),Vn()].join("|");return Hs("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Vs}from"fs/promises";import{join as Bs}from"path";async function Ie(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${x(n)}`}}}async function Yn(e){let t;try{t=await Vs(Bs(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(i){return{ok:!1,message:`Could not read scripts/schema.sql: ${i.message}`}}let n=e.pat.replace(/\s+/g,"");try{let i=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(i.ok)return{ok:!0};let o=await i.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(s.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${i.status}): ${o.slice(0,300)}`}}catch(i){return{ok:!1,message:`Schema apply failed: ${i.message}`}}}function Ys(e){try{let t=JSON.parse(e);return t.error?.code==="not_found"?!0:/user not found/i.test(t.error?.message??"")}catch{return!1}}function Ws(e,t){return e===401||e===403?{kind:"rejected",message:`Vercel rejected the token (HTTP ${e}). It may be invalid, expired or revoked.`}:e===404&&Ys(t)?{kind:"scope",message:"Vercel rejected the token (HTTP 404). Its Scope doesn't include your account, for example it was limited to a single project."}:{kind:"api",message:`Vercel API returned HTTP ${e}. Try again or check status.vercel.com.`}}async function Ce(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let i=await t.text().catch(()=>"");return{ok:!1,...Ws(t.status,i)}}let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,kind:"network",message:`Could not reach Vercel: ${x(t)}`}}}var Wn="https://api.cloudflare.com/client/v4";function zn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function xe(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${Wn}/user/tokens/verify`,{headers:i});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let r=await o.json(),a=r.result?.status;if(r.success===!1||a&&a!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${a?` (status: ${a})`:""}. ${zn(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${x(o)}`}}try{let o=await fetch(`${Wn}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:i});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let r=await o.json();return r.success===!1?{ok:!1,message:zn(r)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(r.result)?r.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${x(o)}`}}}var qn="https://api.netlify.com/api/v1";async function Re(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${qn}/user`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} verifying the token. Try again or check netlifystatus.com.`}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${x(i)}`}}try{let i=await fetch(`${qn}/accounts`,{headers:n});if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} listing your teams. Try again or check netlifystatus.com.`};let o=await i.json(),r=Array.isArray(o)?o:[];if(r.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let a=typeof r[0]?.slug=="string"?r[0].slug:void 0;return{ok:!0,accountCount:r.length,accountSlug:a}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${x(i)}`}}}function zs(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,i=/caller does not have permission|billing/i.test(t)?"This usually means the key's Google Cloud project has no active billing account \u2014 Places needs billing set up even though Google's free monthly credit covers normal use. Check https://console.cloud.google.com/billing for the project this key belongs to. (Less often: the key's restrictions block the Places API \u2014 check Credentials.)":"Common causes: the key is wrong or deleted, billing is not enabled on its Cloud project, or the key's restrictions block the Places API. Check https://console.cloud.google.com/billing and the key's entry under Credentials.";return`${n} ${i}`}async function ve(e){let t=an(e);if(t)return{ok:!1,message:t};let n=de(e),i=n.value,o=r=>{let a=[r],l=ln(e);return l&&a.push(l),n.repairs.length>0&&a.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),a.join(`
16
+ `)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":i,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let a={};try{a=await r.json()}catch{}let l=a.error?.message??"",c=a.error?.status??"";return r.status===400&&(c==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(l))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library/places.googleapis.com and press Enable for the project this key belongs to, then try again. (That page is 'Places API (New)' \u2014 the older 'Places API' is a different API and won't work.)"}:r.status===401||r.status===403?{ok:!1,message:o(zs(r.status,l))}:{ok:!1,message:o(`Google API returned HTTP ${r.status}${l?`: ${l}`:""}.`)}}catch(r){return{ok:!1,message:`Could not reach Google: ${x(r)}`}}}import qs from"nodemailer";import{ImapFlow as Qs}from"imapflow";function Js(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function Qn(e,t,n){let i=t.toLowerCase(),o=e.filter(Js);if(o.some(l=>l.path.toLowerCase()===i))return;let r=i.startsWith("inbox")?void 0:[`inbox.${i}`,`inbox/${i}`],a=o.find(l=>l.specialUse===n)?.path??(r&&o.find(l=>r.includes(l.path.toLowerCase()))?.path);return{configured:t,detected:a||void 0}}function Jn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let i=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return i.includes("invalid credentials")||i.includes("authentication failed")||i.includes("auth failed")||i.includes("login failed")||i.includes("invalid login")?"auth":i.includes("etimedout")||i.includes("timeout")||i.includes("enotfound")||i.includes("getaddrinfo")||i.includes("econnrefused")||i.includes("econnreset")?"network":"other"}async function oe(e){let t=qs.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(a){return{ok:!1,failedAt:"smtp",message:Xn(a,"SMTP",e.usesAccountPassword),failureKind:Jn(a)}}finally{t.close()}let n=new Qs({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),i,o,r;try{if(await n.connect(),e.sentFolder||e.draftsFolder)try{let a=await n.list();e.sentFolder&&(i=Qn(a,e.sentFolder,"\\Sent")),e.draftsFolder&&(o=Qn(a,e.draftsFolder,"\\Drafts"))}catch{r=!0}await n.logout()}catch(a){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Xn(a,"IMAP",e.usesAccountPassword),failureKind:Jn(a)}}return{ok:!0,sentFolderIssue:i,draftsFolderIssue:o,foldersUnverified:r}}function Xn(e,t,n){let i=e instanceof Error?e.message:String(e),o=i.toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
17
17
  \u2022 The mailbox password is wrong or mistyped.
18
18
  \u2022 The email address doesn't match this mailbox's login.
19
19
  \u2022 The provider is blocking third-party apps \u2014 check that third-party
@@ -23,106 +23,109 @@ import{b as ke,c as Ye,d as J,e as T,f as sn,g as on,h as We,i as ze,j as de,k a
23
23
  \u2022 The address is an alias (e.g. a Google Workspace alias domain) \u2014 the
24
24
  sign-in must use the account's primary address. Keep the alias as
25
25
  EMAIL_ADDRESS and set EMAIL_LOGIN in .env to the primary address.
26
- \u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}import*as yt from"@clack/prompts";var zi=[{key:"emailSentFolder",envKey:"EMAIL_SENT_FOLDER",label:"Sent",consequence:"Sent mail wouldn't be filed there, and follow-ups couldn't see what was sent to whom.",issue:e=>e.sentFolderIssue},{key:"emailDraftsFolder",envKey:"EMAIL_DRAFTS_FOLDER",label:"Drafts",consequence:"Saving drafts (manual-approval outreach, /send-invoice) would fail.",issue:e=>e.draftsFolderIssue}];async function wt(e,t,n){let s=!1;for(let o of zi){let r=o.issue(e);if(r){if(i.blank(),r.detected){if(n.nonInteractive){t[o.key]=r.detected,s=!0,i.warn(`Your mailbox has no "${r.configured}" folder \u2014 it calls its ${o.label} folder "${r.detected}". Using that.`);continue}i.warn(`Your mailbox has no "${r.configured}" folder.`),i.detail(`It calls its ${o.label} folder "${r.detected}".`);let a=await yt.confirm({message:`Use "${r.detected}" instead?`,initialValue:!0});if(yt.isCancel(a))return n.onCancel?.(),s;a?(t[o.key]=r.detected,s=!0,i.success(`${o.envKey} set to "${r.detected}"`)):i.warn(`Keeping "${r.configured}". ${o.consequence}`);continue}i.warn(`Your mailbox has no "${r.configured}" folder. ${o.consequence}`),i.detail(`After setup, ask your AI agent to list the mailbox's folders and set ${o.envKey} in .env to the real name.`)}}return s}async function Xn(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let s=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(s.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!s.ok)return{ok:!1,message:`Twilio API returned HTTP ${s.status}. Try again or check status.twilio.com.`};let o=await s.json();return o.status&&o.status!=="active"?{ok:!1,message:`Twilio account is in '${o.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:o.friendly_name}}catch(s){return{ok:!1,message:`Could not reach Twilio: ${T(s)}`}}}async function kt(e){return e.provider==="pingen"?qi(e):Qi(e)}async function qi(e){if(!e.pingenClientId||!e.pingenClientSecret||!e.pingenOrgId)return{ok:!1,message:"Missing Pingen Client ID, Client Secret, or organisation id."};let t=e.pingenStaging?"https://identity-staging.pingen.com":"https://identity.pingen.com",n=e.pingenStaging?"https://api-staging.pingen.com":"https://api.pingen.com";try{let s=await fetch(`${t}/auth/access-tokens`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:e.pingenClientId,client_secret:e.pingenClientSecret,scope:"letter"})});if(!s.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${s.status}). Check the Client ID and Secret under your organisation's 'API Access' page \u2014 note that staging and production credentials are separate.`};let o=(await s.json()).access_token;if(!o)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let r=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${o}`}});return r.status===403||r.status===404?{ok:!1,message:"Pingen accepted the credentials but not the organisation id. Copy it from the dashboard URL: app.pingen.com/organisations/<id>/\u2026"}:r.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${r.status}. Try again shortly.`}}catch(s){return{ok:!1,message:`Could not reach Pingen: ${T(s)}`}}}async function Qi(e){if(!e.postgridApiKey)return{ok:!1,message:"Missing PostGrid API key."};try{let t=await fetch("https://api.postgrid.com/print-mail/v1/letters?limit=1",{headers:{"x-api-key":e.postgridApiKey}});return t.status===401||t.status===403?{ok:!1,message:"PostGrid rejected the API key (HTTP "+t.status+"). Copy it from the PostGrid dashboard \u2014 the live key starts with 'live_sk_'."}:t.ok?{ok:!0,friendlyName:e.postgridApiKey.startsWith("test_")?"test mode \u2014 letters will NOT print":void 0}:{ok:!1,message:`PostGrid API returned HTTP ${t.status}. Try again shortly.`}}catch(t){return{ok:!1,message:`Could not reach PostGrid: ${T(t)}`}}}import{spawn as Ji}from"child_process";async function Zn(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,s=await Xi(n);if(s.code===0)return{ok:!0};let o=s.stderr.toLowerCase();return o.includes("can't get application")||o.includes("isn't running")||o.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:o.includes("(-1728)")||o.includes("not found")||o.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:o.includes("(-1719)")||o.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${s.stderr.trim()||`exit code ${s.code}`}`}}function Xi(e){return new Promise(t=>{let n=Ji("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),s="";n.stderr.on("data",o=>{s+=o.toString()}),n.on("close",o=>t({code:o??1,stderr:s})),n.on("error",o=>t({code:1,stderr:o.message}))})}import{spawn as At}from"child_process";import{existsSync as Zi}from"fs";import{homedir as eo}from"os";function to(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var Re=2,es=2e3,no=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function ts(e,t){let n=e+`
27
- `+t;return no.some(s=>s.test(n))}function ns(e){return new Promise(t=>setTimeout(t,e))}function so(e,t,n){return new Promise(s=>{let o=n.shell?At([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):At(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),r="",a="";o.stdout?.on("data",l=>{let c=l.toString();r+=c,process.stdout.write(c)}),o.stderr?.on("data",l=>{let c=l.toString();a+=c,process.stderr.write(c)}),o.on("close",l=>s({code:l??1,stdout:r,stderr:a})),o.on("error",l=>s({code:1,stdout:r,stderr:a+l.message}))})}async function Ht(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=Re;o++){if(s=await so(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!ts(s.stderr,s.stdout))return s;o<Re&&(i.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${Re+1})\u2026`),await ns(es))}return s}function io(e,t,n){return new Promise(s=>{let o=At(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:a})),o.on("error",l=>s({code:1,stdout:r,stderr:a+l.message}))})}var oo=[{pattern:/UNABLE_TO_VERIFY_LEAF_SIGNATURE|unable to verify the first certificate/i,hint:"TLS-handshake error \u2014 your machine appears to be intercepting HTTPS (antivirus, corporate proxy, or VPN re-signing traffic with its own root CA). We work around this with NODE_OPTIONS=--use-system-ca, which needs Node 22.15+. Run `node --version` to verify, upgrade if older, then re-run setup."},{pattern:/Microsoft Visual C\+\+ 14\.0 or greater is required/i,hint:"Python tried to compile a package from source and couldn't find the Microsoft C++ Build Tools. The latest Klaudius pins supabase<2.26 to skip the offending dependency entirely. Re-run with `npx klaudius@latest init` (pulls the latest) \u2014 that should bypass the source build."}];function ro(e){let t=`${e.stderr??""}
28
- ${e.stdout??""}`;return oo.find(s=>s.pattern.test(t))?.hint}async function ao(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await K())?.command??["python3"],r=async l=>{let c={code:0,stdout:"",stderr:""};for(let f=0;f<=Re;f++){if(c=await io(o[0],[...o.slice(1),...l],{cwd:e}),c.code===0||!ts(c.stderr,c.stdout))return c;f<Re&&(i.detail(`pip install hit a transient network error \u2014 retrying (${f+2}/${Re+1})\u2026`),await ns(es))}return c},a=await r([...n,"--break-system-packages",...t]);return a.code!==0&&/no such option:.*break-system-packages/i.test(a.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),a=await r([...n,...t])),a.code!==0&&(a.stderr.trim()&&process.stderr.write(a.stderr),a.stdout.trim()&&process.stdout.write(a.stdout)),a}async function Et(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=to(),s=process.platform==="win32",o;if(s){let u=Ee([{label:"your Windows user folder",path:eo()},{label:"the project folder",path:e}]);if(u.length>0){let k=await new Promise(P=>{let y=At("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),E="",b="";y.stdout?.on("data",C=>{E+=C.toString()}),y.stderr?.on("data",C=>{b+=C.toString()}),y.on("close",C=>P({code:C??1,stdout:E,stderr:b})),y.on("error",C=>P({code:1,stdout:E,stderr:C.message}))}),d=k.code===0?k.stdout.trim():void 0;if(!Pe(d,Zi)){let{detail:P,action:y}=Se(u,"install");o=`${P}. ${y}`}}}let r=(u,k)=>{let d=ro(k);if(d){(t.hints??={})[u]=d;return}o&&(u==="npm"||u==="playwright"||u==="patchright")&&!Object.values(t.hints??{}).includes(o)&&((t.hints??={})[u]=o)};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await Ht("npm",["install"],{cwd:e,label:"npm install",env:n,shell:s});t.npm=a.code===0?"ok":"failed",a.code!==0&&r("npm",a),i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await ao(e);t.pip=l.code===0?"ok":"failed",l.code!==0&&r("pip",l),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Ht("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:s});t.playwright=c.code===0?"ok":"failed",c.code!==0&&r("playwright",c),i.step("Installing Patchright browser (chromium ~200MB; one-time)...");let f=await Ht("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:s});return t.patchright=f.code===0?"ok":"failed",f.code!==0&&r("patchright",f),t}import{copyFile as lo,access as co}from"fs/promises";import{dirname as uo,join as po}from"path";async function ss(){let e=await Xe("python3",["--version"]),t=(e.stdout+e.stderr).trim();if(/Python was not found/i.test(t))return{state:"stub"};let n=/Python\s+(\d+\.\d+(?:\.\d+)?)/.exec(t);return e.code===0&&n?{state:"real",version:n[1]}:{state:"missing"}}async function Ut(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await ss();if(e.state==="real")return{status:"ok",version:e.version};let t=await K();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function fo(e){let[t,...n]=e.command,s=await Xe(t,[...n,"-c","import sys; print(sys.executable)"]),o=s.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(s.code!==0||!o)return{ok:!1,reason:"no-exe-path"};let r=po(uo(o),"python3.exe"),a=await co(r).then(()=>!0,()=>!1);if(!a){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await lo(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let l=await ss();return{ok:!0,target:r,created:!a,verified:l.state==="real",postState:l.state==="real"?void 0:l.state}}var ho="A real python3.exe now exists, but the Microsoft Store placeholder still shadows it. Turn OFF both `python.exe` and `python3.exe` under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases, then open a fresh terminal.";async function Pt(){let e=await Ut();if(e.status!=="broken")return;let t=await fo(e.fallback);if(t.ok&&t.verified){let n=t.created?e.literal==="stub"?"Fixed a Windows quirk: `python3` was a Store placeholder; it now runs your real Python.":"Fixed a Windows quirk: created the missing `python3` command from your real Python.":"The `python3` command now works \u2014 it runs your real Python.";i.success(n);return}if(t.ok&&t.postState==="stub"){i.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),i.detail(ho);return}if(t.ok){i.warn("A python3.exe is in place next to your Python, but that folder isn't on this machine's PATH, so commands can't find it."),i.detail('Re-installing Python from python.org with "Add python.exe to PATH" ticked resolves it \u2014 then open a fresh terminal.');return}if(t.reason==="store-python"){i.warn('This Python was installed from the Microsoft Store, which blocks creating the `python3` alias next to it. Installing Python from python.org (tick "Add python.exe to PATH") resolves it.');return}if(t.reason==="not-writable"){i.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),i.detail(t.manualCommand??"");return}i.warn("This machine's `python3` command isn't working, and the automatic fix could not complete. Re-installing Python from python.org (tick \"Add python.exe to PATH\") resolves it.")}import{spawn as mo,spawnSync as is}from"child_process";import{mkdtemp as go,rm as yo,rmdir as wo,writeFile as ko,stat as jt,unlink as Ao,mkdir as Eo}from"fs/promises";import{createServer as Po}from"net";import{tmpdir as So}from"os";import{join as xe}from"path";function bo(){return new Promise((e,t)=>{let n=Po();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let s=n.address(),o=typeof s=="object"&&s?s.port:0;n.close(()=>e(o))})})}function St(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?is(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):is("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function bt(e){try{return await _o(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function _o(e){let t=`klaudius-smoke-${process.pid}`,n=xe(".klaudius",`qa-smoke-${process.pid}.png`),s=xe(e,n),o,r,a=!1;try{o=await go(xe(So(),"klaudius-qa-smoke-")),await ko(xe(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let l=await bo();r=mo("python3",["-m","http.server",String(l),"--directory",o],{stdio:"ignore",shell:!1});let c=!1;r.on("error",()=>{c=!0}),r.on("exit",()=>{c=!0});let f=`http://127.0.0.1:${l}/`,u=!1;for(let b=0;b<24&&!c;b++)try{if((await fetch(f,{signal:AbortSignal.timeout(1e3)})).ok){u=!0;break}}catch{await new Promise(C=>setTimeout(C,500))}if(!u)return{ok:!1,stage:"python3-server",detail:"`python3 -m http.server` never came up on a free local port",remediation:process.platform==="win32"?"python3 on this machine isn't runnable (usually the Microsoft Store placeholder). Running `npx klaudius@latest update` fixes it automatically.":"Check `python3 --version` works in this terminal."};let k=xe(e,".klaudius"),d=await jt(k).then(()=>!0,()=>!1);await Eo(k,{recursive:!0}),a=!d;let P=St(e,[`-s=${t}`,"open",f]);if(P.status!==0)return{ok:!1,stage:"browser",detail:((P.stderr??"")+(P.stdout??"")).slice(-400).trim()||"playwright-cli could not open a browser",remediation:"Run `npx playwright install chromium` in this folder"+(process.platform==="linux"?", and under WSL also `npx playwright install-deps chromium` (missing system libraries are the usual cause there).":".")};let y=St(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await jt(s).catch(()=>null);if((!E||E.size===0)&&(y=St(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await jt(s).catch(()=>null)),!E||E.size===0){let b=((y.stderr??"")+(y.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${b?` (${b})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{St(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await Ao(s).catch(()=>{}),a&&await wo(xe(e,".klaudius")).catch(()=>{}),o&&await yo(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as os,readFile as Io,writeFile as rs}from"fs/promises";import{join as _t}from"path";var Oe="Bash(claude --bg --permission-mode auto *)";async function as(e){let t;try{t=await Io(e,"utf-8")}catch{return{}}try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return null}async function ve(e,t){let n=_t(e,".claude"),s=_t(n,"settings.local.json"),o=".claude/settings.local.json";try{await os(n,{recursive:!0});let r=await as(s);if(r===null)return i.warn(`${o} isn't valid JSON, so it was left as-is. Fix it and re-run to pre-approve the parallel-run dispatch.`),"skipped";let a=r.permissions&&typeof r.permissions=="object"&&!Array.isArray(r.permissions)?r.permissions:{},l=a.allow,c=Array.isArray(l)?l.filter(u=>typeof u=="string"):[];if(c.includes(t))return"present";c.push(t);let f={...r,permissions:{...a,allow:c}};return await rs(s,JSON.stringify(f,null,2)+`
29
- `,"utf-8"),"added"}catch(r){return i.warn(`Couldn't write ${o} (${r instanceof Error?r.message:String(r)}). The parallel-run dispatch may occasionally ask for approval.`),"skipped"}}async function It(e,t){let n=_t(e,".claude");await os(n,{recursive:!0});let s=_t(n,"settings.json"),o=await as(s)??{},r=o.enabledMcpjsonServers,a=Array.isArray(r)?r.filter(c=>typeof c=="string"):[];a.includes(t)||a.push(t);let l={...o,enabledMcpjsonServers:a};await rs(s,JSON.stringify(l,null,2)+`
30
- `,"utf-8")}var ls="0.32.1",v=5,F=!1;function H(e,t){i.blank(),console.error(`INIT-BLOCKED section=${e}`),console.error(t),console.error("Fix this section's values in the answers file and re-run the same init command. Progress so far is saved in .env."),process.exit(2)}async function Oo(e){let t;try{t=await Bt(e,"utf-8")}catch{H("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let s=JSON.parse(n),o={};for(let[r,a]of Object.entries(s))a!=null&&(o[r]=typeof a=="string"?a:String(a));return o}catch(s){H("answers",`Answers file is not valid JSON: ${s.message}`)}return G(t)}function re(e){return`npx klaudius@latest init ${Tt(Le(e))}`}function Le(e){if(process.platform==="win32")return e;let t=To();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function vo(e){let t=[];try{let s=(await ds(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let r=X(e,o.name);if(!await cs(X(r,".env")))continue;let a=await cs(X(r,".klaudius","manifest.json"));if(t.push({path:r,finished:a}),t.length>=3)break}}catch{}return t}async function cs(e){try{return await Vt(e),!0}catch{return!1}}function Tt(e){return/\s/.test(e)?`"${e}"`:e}function ee(e,t,n){i.blank(),i.error(`${t} validation failed ${v} times in a row. Pausing setup so you don't get stuck in a loop.`),i.detail(`Last error: ${n}`),i.blank(),i.detail("Your credentials are saved in `.env`. Two ways forward:"),i.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),i.blank(),console.log(` ${h.cyan(re(e))}`),i.blank(),i.detail(` (Your .env is at ${Le(X(e,".env"))} \u2014 open it in any text editor.)`),i.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),i.blank(),process.exit(1)}async function us(e){let t=e.target??".",n=Ro(t)?t:Co(process.cwd(),t),s=Mo(n);s&&(i.error("Klaudius can't be installed inside a protected system folder."),i.detail(`Path: ${n}`),i.detail(`Reason: ${s}`),i.blank(),i.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),i.blank(),process.platform==="win32"?(i.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${h.cyan("cd $HOME\\Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)):(i.detail("For example:"),console.log(` ${h.cyan("cd ~/Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)),i.blank(),process.exit(1)),process.platform==="win32"&&Do()&&(i.warn("You appear to be running in an elevated (Administrator) PowerShell."),i.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),i.blank()),await ft("init",ls);let o=await Lo(n);if(o.kind==="scaffolded"){i.blank(),i.warn(`Found an existing Klaudius project at ${h.bold(n)}.`),i.detail("(Your .env and project files are in place.)"),i.blank(),o.nodeModulesMissing?(i.detail("It looks like a previous setup didn't finish installing dependencies."),i.detail("To pick up where it left off, run:"),i.blank(),n!==process.cwd()&&console.log(` ${h.cyan(`cd ${Tt(t)}`)}`),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retries npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Everything is scaffolded and dependencies look installed."),i.detail("Pick the action you wanted:"),i.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${h.cyan("npx klaudius@latest configure")} ${h.dim("# change a credential / API key")}`),console.log(` ${h.cyan("npx klaudius@latest update")} ${h.dim("# pull the latest skills, scripts, lessons")}`),i.blank()),i.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),i.blank();return}if(o.kind==="occupied"){let p=t===".",g=await vo(n);if(g.length>0){i.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),i.detail(`You're in: ${Le(n)}`),i.blank();for(let m of g)i.detail(m.finished?`Found a finished project at ${Le(m.path)}. To work in it:`:`Found an unfinished setup at ${Le(m.path)}. To pick up where it left off:`),i.blank(),m.finished?(console.log(` ${h.cyan(`cd ${Le(m.path)}`)}`),console.log(` ${h.cyan("claude")} ${h.dim("# open Claude Code in the project")}`)):console.log(` ${h.cyan(re(m.path))} ${h.dim("# then pick Resume")}`),i.blank();process.exit(1)}i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),i.blank(),p?(i.detail("Two ways forward:"),i.blank(),i.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`),i.blank(),i.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${h.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(i.detail(`The folder '${t}' already exists and isn't empty.`),i.detail("Either pick a different name:"),console.log(` ${h.cyan(`npx klaudius@latest init ${t}-2`)}`),i.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=null;e.answers&&(F=!0,r=await Oo(e.answers),i.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let a=e.license??r?.KLAUDIUS_LICENSE_KEY;F&&(!a||a.trim().length===0)&&H("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let l=await No(a),c=S.spinner();c.start("Validating license");let f=await Bn(l);f.ok||(c.stop(`License invalid: ${f.reason??"unknown"}`,2),i.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),F&&H("license",`${f.reason??"The license could not be validated."} If you believe this is in error, email hello@klaudius.dev with your purchase details.`),process.exit(1)),c.stop(`License valid (${f.tier??"core"} tier)`);let u=await be();u.ok||(i.error(u.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${re(n)}`),process.exit(1)),await Pt();let k=ue();k.ok||(i.error(k.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${re(n)}`),process.exit(1));let d,P=!1;if(r){let p=rt(r);p||H("answers","The answers file is missing required fields. Required: PRICING, SUPABASE_URL, SUPABASE_SERVICE_KEY, SUPABASE_PAT, SUPABASE_PROJECT_REF, plus the credentials for your DEPLOY_PROVIDER (VERCEL_TOKEN, or CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, or NETLIFY_AUTH_TOKEN, or SELFHOST_DEPLOY_TARGET + SELFHOST_URL_TEMPLATE). Keys match a working .env."),d=p,i.success("Loaded setup answers (non-interactive mode)")}else if(o.kind==="partial")if(await $o(n)==="resume"){let g=await Bt(o.envPath,"utf-8"),m=rt(G(g));m?(i.success("Resuming with values from your existing .env"),i.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),d=m,P=!0,d.aiPlan||(d=await N(d,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
31
- runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),d=await N())}else{let g=await Bt(o.envPath,"utf-8"),m=rt(G(g));d=await N(m??{})}else d=await N();d.licenseKey=l,await M(n,d),P||(i.success("Saved .env"),i.success(d.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let p=1;;p++){let g=S.spinner();g.start("Validating Supabase credentials");let m=await Te({url:d.supabaseUrl,serviceKey:d.supabaseServiceKey});if(m.ok){g.stop("Supabase credentials accepted");break}g.stop(m.message??"Supabase check failed",2),p>=v&&ee(n,"Supabase",m.message??"Supabase check failed");let A=m.message??"Supabase check failed";i.blank(),F&&H("supabase",A),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${p+1} of ${v})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await N(d,{onlySection:"supabase",banner:`Supabase rejected your credentials:
32
- ${A}
26
+ \u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${i}`}import*as yt from"@clack/prompts";var Xs=[{key:"emailSentFolder",envKey:"EMAIL_SENT_FOLDER",label:"Sent",consequence:"Sent mail wouldn't be filed there, and follow-ups couldn't see what was sent to whom.",issue:e=>e.sentFolderIssue},{key:"emailDraftsFolder",envKey:"EMAIL_DRAFTS_FOLDER",label:"Drafts",consequence:"Saving drafts (manual-approval outreach, /send-invoice) would fail.",issue:e=>e.draftsFolderIssue}];async function kt(e,t,n){let i=!1;for(let o of Xs){let r=o.issue(e);if(r){if(s.blank(),r.detected){if(n.nonInteractive){t[o.key]=r.detected,i=!0,s.warn(`Your mailbox has no "${r.configured}" folder \u2014 it calls its ${o.label} folder "${r.detected}". Using that.`);continue}s.warn(`Your mailbox has no "${r.configured}" folder.`),s.detail(`It calls its ${o.label} folder "${r.detected}".`);let a=await yt.confirm({message:`Use "${r.detected}" instead?`,initialValue:!0});if(yt.isCancel(a))return n.onCancel?.(),i;a?(t[o.key]=r.detected,i=!0,s.success(`${o.envKey} set to "${r.detected}"`)):s.warn(`Keeping "${r.configured}". ${o.consequence}`);continue}s.warn(`Your mailbox has no "${r.configured}" folder. ${o.consequence}`),s.detail(`After setup, ask your AI agent to list the mailbox's folders and set ${o.envKey} in .env to the real name.`)}}return i}async function Zn(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let i=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(i.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!i.ok)return{ok:!1,message:`Twilio API returned HTTP ${i.status}. Try again or check status.twilio.com.`};let o=await i.json();return o.status&&o.status!=="active"?{ok:!1,message:`Twilio account is in '${o.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:o.friendly_name}}catch(i){return{ok:!1,message:`Could not reach Twilio: ${x(i)}`}}}async function wt(e){return e.provider==="pingen"?Zs(e):eo(e)}async function Zs(e){if(!e.pingenClientId||!e.pingenClientSecret||!e.pingenOrgId)return{ok:!1,message:"Missing Pingen Client ID, Client Secret, or organisation id."};let t=e.pingenStaging?"https://identity-staging.pingen.com":"https://identity.pingen.com",n=e.pingenStaging?"https://api-staging.pingen.com":"https://api.pingen.com";try{let i=await fetch(`${t}/auth/access-tokens`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:e.pingenClientId,client_secret:e.pingenClientSecret,scope:"letter"})});if(!i.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${i.status}). Check the Client ID and Secret under your organisation's 'API Access' page \u2014 note that staging and production credentials are separate.`};let o=(await i.json()).access_token;if(!o)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let r=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${o}`}});return r.status===403||r.status===404?{ok:!1,message:"Pingen accepted the credentials but not the organisation id. Copy it from the dashboard URL: app.pingen.com/organisations/<id>/\u2026"}:r.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${r.status}. Try again shortly.`}}catch(i){return{ok:!1,message:`Could not reach Pingen: ${x(i)}`}}}async function eo(e){if(!e.postgridApiKey)return{ok:!1,message:"Missing PostGrid API key."};try{let t=await fetch("https://api.postgrid.com/print-mail/v1/letters?limit=1",{headers:{"x-api-key":e.postgridApiKey}});return t.status===401||t.status===403?{ok:!1,message:"PostGrid rejected the API key (HTTP "+t.status+"). Copy it from the PostGrid dashboard \u2014 the live key starts with 'live_sk_'."}:t.ok?{ok:!0,friendlyName:e.postgridApiKey.startsWith("test_")?"test mode \u2014 letters will NOT print":void 0}:{ok:!1,message:`PostGrid API returned HTTP ${t.status}. Try again shortly.`}}catch(t){return{ok:!1,message:`Could not reach PostGrid: ${x(t)}`}}}import{spawn as to}from"child_process";async function ei(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,i=await no(n);if(i.code===0)return{ok:!0};let o=i.stderr.toLowerCase();return o.includes("can't get application")||o.includes("isn't running")||o.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:o.includes("(-1728)")||o.includes("not found")||o.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:o.includes("(-1719)")||o.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${i.stderr.trim()||`exit code ${i.code}`}`}}function no(e){return new Promise(t=>{let n=to("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),i="";n.stderr.on("data",o=>{i+=o.toString()}),n.on("close",o=>t({code:o??1,stderr:i})),n.on("error",o=>t({code:1,stderr:o.message}))})}import{spawn as At}from"child_process";import{existsSync as io}from"fs";import{homedir as so}from"os";function oo(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var Oe=2,ti=2e3,ro=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function ni(e,t){let n=e+`
27
+ `+t;return ro.some(i=>i.test(n))}function ii(e){return new Promise(t=>setTimeout(t,e))}function ao(e,t,n){return new Promise(i=>{let o=n.shell?At([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):At(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),r="",a="";o.stdout?.on("data",l=>{let c=l.toString();r+=c,process.stdout.write(c)}),o.stderr?.on("data",l=>{let c=l.toString();a+=c,process.stderr.write(c)}),o.on("close",l=>i({code:l??1,stdout:r,stderr:a})),o.on("error",l=>i({code:1,stdout:r,stderr:a+l.message}))})}async function Ht(e,t,n){let i={code:0,stdout:"",stderr:""};for(let o=0;o<=Oe;o++){if(i=await ao(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!ni(i.stderr,i.stdout))return i;o<Oe&&(s.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${Oe+1})\u2026`),await ii(ti))}return i}function lo(e,t,n){return new Promise(i=>{let o=At(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>i({code:l??1,stdout:r,stderr:a})),o.on("error",l=>i({code:1,stdout:r,stderr:a+l.message}))})}var co=[{pattern:/UNABLE_TO_VERIFY_LEAF_SIGNATURE|unable to verify the first certificate/i,hint:"TLS-handshake error \u2014 your machine appears to be intercepting HTTPS (antivirus, corporate proxy, or VPN re-signing traffic with its own root CA). We work around this with NODE_OPTIONS=--use-system-ca, which needs Node 22.15+. Run `node --version` to verify, upgrade if older, then re-run setup."},{pattern:/Microsoft Visual C\+\+ 14\.0 or greater is required/i,hint:"Python tried to compile a package from source and couldn't find the Microsoft C++ Build Tools. The latest Klaudius pins supabase<2.26 to skip the offending dependency entirely. Re-run with `npx klaudius@latest init` (pulls the latest) \u2014 that should bypass the source build."}];function uo(e){let t=`${e.stderr??""}
28
+ ${e.stdout??""}`;return co.find(i=>i.pattern.test(t))?.hint}async function po(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await K())?.command??["python3"],r=async l=>{let c={code:0,stdout:"",stderr:""};for(let f=0;f<=Oe;f++){if(c=await lo(o[0],[...o.slice(1),...l],{cwd:e}),c.code===0||!ni(c.stderr,c.stdout))return c;f<Oe&&(s.detail(`pip install hit a transient network error \u2014 retrying (${f+2}/${Oe+1})\u2026`),await ii(ti))}return c},a=await r([...n,"--break-system-packages",...t]);return a.code!==0&&/no such option:.*break-system-packages/i.test(a.stderr)&&(s.detail("Older pip detected; retrying without --break-system-packages"),a=await r([...n,...t])),a.code!==0&&(a.stderr.trim()&&process.stderr.write(a.stderr),a.stdout.trim()&&process.stdout.write(a.stdout)),a}async function Et(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=oo(),i=process.platform==="win32",o;if(i){let u=Ee([{label:"your Windows user folder",path:so()},{label:"the project folder",path:e}]);if(u.length>0){let A=await new Promise(b=>{let g=At("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),k="",S="";g.stdout?.on("data",C=>{k+=C.toString()}),g.stderr?.on("data",C=>{S+=C.toString()}),g.on("close",C=>b({code:C??1,stdout:k,stderr:S})),g.on("error",C=>b({code:1,stdout:k,stderr:C.message}))}),d=A.code===0?A.stdout.trim():void 0;if(!Pe(d,io)){let{detail:b,action:g}=Se(u,"install");o=`${b}. ${g}`}}}let r=(u,A)=>{let d=uo(A);if(d){(t.hints??={})[u]=d;return}o&&(u==="npm"||u==="playwright"||u==="patchright")&&!Object.values(t.hints??{}).includes(o)&&((t.hints??={})[u]=o)};s.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await Ht("npm",["install"],{cwd:e,label:"npm install",env:n,shell:i});t.npm=a.code===0?"ok":"failed",a.code!==0&&r("npm",a),s.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await po(e);t.pip=l.code===0?"ok":"failed",l.code!==0&&r("pip",l),s.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Ht("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:i});t.playwright=c.code===0?"ok":"failed",c.code!==0&&r("playwright",c),s.step("Installing Patchright browser (chromium ~200MB; one-time)...");let f=await Ht("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:i});return t.patchright=f.code===0?"ok":"failed",f.code!==0&&r("patchright",f),t}import{copyFile as fo,access as ho}from"fs/promises";import{dirname as mo,join as go}from"path";async function si(){let e=await tt("python3",["--version"]),t=(e.stdout+e.stderr).trim();if(/Python was not found/i.test(t))return{state:"stub"};let n=/Python\s+(\d+\.\d+(?:\.\d+)?)/.exec(t);return e.code===0&&n?{state:"real",version:n[1]}:{state:"missing"}}async function Ut(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await si();if(e.state==="real")return{status:"ok",version:e.version};let t=await K();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function yo(e){let[t,...n]=e.command,i=await tt(t,[...n,"-c","import sys; print(sys.executable)"]),o=i.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(i.code!==0||!o)return{ok:!1,reason:"no-exe-path"};let r=go(mo(o),"python3.exe"),a=await ho(r).then(()=>!0,()=>!1);if(!a){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await fo(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let l=await si();return{ok:!0,target:r,created:!a,verified:l.state==="real",postState:l.state==="real"?void 0:l.state}}var ko="A real python3.exe now exists, but the Microsoft Store placeholder still shadows it. Turn OFF both `python.exe` and `python3.exe` under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases, then open a fresh terminal.";async function Pt(){let e=await Ut();if(e.status!=="broken")return;let t=await yo(e.fallback);if(t.ok&&t.verified){let n=t.created?e.literal==="stub"?"Fixed a Windows quirk: `python3` was a Store placeholder; it now runs your real Python.":"Fixed a Windows quirk: created the missing `python3` command from your real Python.":"The `python3` command now works \u2014 it runs your real Python.";s.success(n);return}if(t.ok&&t.postState==="stub"){s.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),s.detail(ko);return}if(t.ok){s.warn("A python3.exe is in place next to your Python, but that folder isn't on this machine's PATH, so commands can't find it."),s.detail('Re-installing Python from python.org with "Add python.exe to PATH" ticked resolves it \u2014 then open a fresh terminal.');return}if(t.reason==="store-python"){s.warn('This Python was installed from the Microsoft Store, which blocks creating the `python3` alias next to it. Installing Python from python.org (tick "Add python.exe to PATH") resolves it.');return}if(t.reason==="not-writable"){s.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),s.detail(t.manualCommand??"");return}s.warn("This machine's `python3` command isn't working, and the automatic fix could not complete. Re-installing Python from python.org (tick \"Add python.exe to PATH\") resolves it.")}import{spawn as wo,spawnSync as oi}from"child_process";import{mkdtemp as Ao,rm as Eo,rmdir as Po,writeFile as So,stat as jt,unlink as bo,mkdir as _o}from"fs/promises";import{createServer as To}from"net";import{tmpdir as Io}from"os";import{join as Le}from"path";function Co(){return new Promise((e,t)=>{let n=To();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let i=n.address(),o=typeof i=="object"&&i?i.port:0;n.close(()=>e(o))})})}function St(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?oi(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):oi("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function bt(e){try{return await xo(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function xo(e){let t=`klaudius-smoke-${process.pid}`,n=Le(".klaudius",`qa-smoke-${process.pid}.png`),i=Le(e,n),o,r,a=!1;try{o=await Ao(Le(Io(),"klaudius-qa-smoke-")),await So(Le(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let l=await Co();r=wo("python3",["-m","http.server",String(l),"--directory",o],{stdio:"ignore",shell:!1});let c=!1;r.on("error",()=>{c=!0}),r.on("exit",()=>{c=!0});let f=`http://127.0.0.1:${l}/`,u=!1;for(let S=0;S<24&&!c;S++)try{if((await fetch(f,{signal:AbortSignal.timeout(1e3)})).ok){u=!0;break}}catch{await new Promise(C=>setTimeout(C,500))}if(!u)return{ok:!1,stage:"python3-server",detail:"`python3 -m http.server` never came up on a free local port",remediation:process.platform==="win32"?"python3 on this machine isn't runnable (usually the Microsoft Store placeholder). Running `npx klaudius@latest update` fixes it automatically.":"Check `python3 --version` works in this terminal."};let A=Le(e,".klaudius"),d=await jt(A).then(()=>!0,()=>!1);await _o(A,{recursive:!0}),a=!d;let b=St(e,[`-s=${t}`,"open",f]);if(b.status!==0)return{ok:!1,stage:"browser",detail:((b.stderr??"")+(b.stdout??"")).slice(-400).trim()||"playwright-cli could not open a browser",remediation:"Run `npx playwright install chromium` in this folder"+(process.platform==="linux"?", and under WSL also `npx playwright install-deps chromium` (missing system libraries are the usual cause there).":".")};let g=St(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await jt(i).catch(()=>null);if((!k||k.size===0)&&(g=St(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await jt(i).catch(()=>null)),!k||k.size===0){let S=((g.stderr??"")+(g.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${S?` (${S})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{St(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await bo(i).catch(()=>{}),a&&await Po(Le(e,".klaudius")).catch(()=>{}),o&&await Eo(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as ri,readFile as Ro,writeFile as ai}from"fs/promises";import{join as _t}from"path";var $e="Bash(claude --bg --permission-mode auto *)";async function li(e){let t;try{t=await Ro(e,"utf-8")}catch{return{}}try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return null}async function Ne(e,t){let n=_t(e,".claude"),i=_t(n,"settings.local.json"),o=".claude/settings.local.json";try{await ri(n,{recursive:!0});let r=await li(i);if(r===null)return s.warn(`${o} isn't valid JSON, so it was left as-is. Fix it and re-run to pre-approve the parallel-run dispatch.`),"skipped";let a=r.permissions&&typeof r.permissions=="object"&&!Array.isArray(r.permissions)?r.permissions:{},l=a.allow,c=Array.isArray(l)?l.filter(u=>typeof u=="string"):[];if(c.includes(t))return"present";c.push(t);let f={...r,permissions:{...a,allow:c}};return await ai(i,JSON.stringify(f,null,2)+`
29
+ `,"utf-8"),"added"}catch(r){return s.warn(`Couldn't write ${o} (${r instanceof Error?r.message:String(r)}). The parallel-run dispatch may occasionally ask for approval.`),"skipped"}}async function Tt(e,t){let n=_t(e,".claude");await ri(n,{recursive:!0});let i=_t(n,"settings.json"),o=await li(i)??{},r=o.enabledMcpjsonServers,a=Array.isArray(r)?r.filter(c=>typeof c=="string"):[];a.includes(t)||a.push(t);let l={...o,enabledMcpjsonServers:a};await ai(i,JSON.stringify(l,null,2)+`
30
+ `,"utf-8")}var ci="0.32.3",L=5,F=!1;function H(e,t){s.blank(),console.error(`INIT-BLOCKED section=${e}`),console.error(t),console.error("Fix this section's values in the answers file and re-run the same init command. Progress so far is saved in .env."),process.exit(2)}async function No(e){let t;try{t=await Vt(e,"utf-8")}catch{H("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let i=JSON.parse(n),o={};for(let[r,a]of Object.entries(i))a!=null&&(o[r]=typeof a=="string"?a:String(a));return o}catch(i){H("answers",`Answers file is not valid JSON: ${i.message}`)}return G(t)}function re(e){return`npx klaudius@latest init ${It(Me(e))}`}function Me(e){if(process.platform==="win32")return e;let t=vo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Mo(e){let t=[];try{let i=(await ui(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of i){let r=Z(e,o.name);if(!await di(Z(r,".env")))continue;let a=await di(Z(r,".klaudius","manifest.json"));if(t.push({path:r,finished:a}),t.length>=3)break}}catch{}return t}async function di(e){try{return await Bt(e),!0}catch{return!1}}function It(e){return/\s/.test(e)?`"${e}"`:e}function te(e,t,n){s.blank(),s.error(`${t} validation failed ${L} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${n}`),s.blank(),s.detail("Your credentials are saved in `.env`. Two ways forward:"),s.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),s.blank(),console.log(` ${h.cyan(re(e))}`),s.blank(),s.detail(` (Your .env is at ${Me(Z(e,".env"))} \u2014 open it in any text editor.)`),s.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),s.blank(),process.exit(1)}async function pi(e){let t=e.target??".",n=Lo(t)?t:Oo(process.cwd(),t),i=Uo(n);i&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${n}`),s.detail(`Reason: ${i}`),s.blank(),s.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),s.blank(),process.platform==="win32"?(s.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${h.cyan("cd $HOME\\Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)):(s.detail("For example:"),console.log(` ${h.cyan("cd ~/Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)),s.blank(),process.exit(1)),process.platform==="win32"&&jo()&&(s.warn("You appear to be running in an elevated (Administrator) PowerShell."),s.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),s.blank()),await gt("init",ci);let o=await Do(n);if(o.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${h.bold(n)}.`),s.detail("(Your .env and project files are in place.)"),s.blank(),o.nodeModulesMissing?(s.detail("It looks like a previous setup didn't finish installing dependencies."),s.detail("To pick up where it left off, run:"),s.blank(),n!==process.cwd()&&console.log(` ${h.cyan(`cd ${It(t)}`)}`),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retries npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Everything is scaffolded and dependencies look installed."),s.detail("Pick the action you wanted:"),s.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${h.cyan("npx klaudius@latest configure")} ${h.dim("# change a credential / API key")}`),console.log(` ${h.cyan("npx klaudius@latest update")} ${h.dim("# pull the latest skills, scripts, lessons")}`),s.blank()),s.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),s.blank();return}if(o.kind==="occupied"){let p=t===".",y=await Mo(n);if(y.length>0){s.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),s.detail(`You're in: ${Me(n)}`),s.blank();for(let m of y)s.detail(m.finished?`Found a finished project at ${Me(m.path)}. To work in it:`:`Found an unfinished setup at ${Me(m.path)}. To pick up where it left off:`),s.blank(),m.finished?(console.log(` ${h.cyan(`cd ${Me(m.path)}`)}`),console.log(` ${h.cyan("claude")} ${h.dim("# open Claude Code in the project")}`)):console.log(` ${h.cyan(re(m.path))} ${h.dim("# then pick Resume")}`),s.blank();process.exit(1)}s.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),s.detail(`Path: ${n}`),s.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),s.blank(),p?(s.detail("Two ways forward:"),s.blank(),s.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`),s.blank(),s.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${h.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(s.detail(`The folder '${t}' already exists and isn't empty.`),s.detail("Either pick a different name:"),console.log(` ${h.cyan(`npx klaudius@latest init ${t}-2`)}`),s.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=null;e.answers&&(F=!0,r=await No(e.answers),s.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let a=e.license??r?.KLAUDIUS_LICENSE_KEY;F&&(!a||a.trim().length===0)&&H("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let l=await Ho(a),c=P.spinner();c.start("Validating license");let f=await Bn(l);f.ok||(c.stop(`License invalid: ${f.reason??"unknown"}`,2),s.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),F&&H("license",`${f.reason??"The license could not be validated."} If you believe this is in error, email hello@klaudius.dev with your purchase details.`),process.exit(1)),c.stop(`License valid (${f.tier??"core"} tier)`);let u=await be();u.ok||(s.error(u.message??"Python version check failed."),s.blank(),s.detail(`Once you've installed Python 3.10+, re-run the same command: ${re(n)}`),process.exit(1)),await Pt();let A=ue();A.ok||(s.error(A.message??"Node.js version check failed."),s.blank(),s.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${re(n)}`),process.exit(1));let d,b=!1;if(r){let p=ct(r);p||H("answers","The answers file is missing required fields. Required: PRICING, SUPABASE_URL, SUPABASE_SERVICE_KEY, SUPABASE_PAT, SUPABASE_PROJECT_REF, plus the credentials for your DEPLOY_PROVIDER (VERCEL_TOKEN, or CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, or NETLIFY_AUTH_TOKEN, or SELFHOST_DEPLOY_TARGET + SELFHOST_URL_TEMPLATE). Keys match a working .env."),d=p,s.success("Loaded setup answers (non-interactive mode)")}else if(o.kind==="partial")if(await Fo(n)==="resume"){let y=await Vt(o.envPath,"utf-8"),m=ct(G(y));m?(s.success("Resuming with values from your existing .env"),s.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),d=m,b=!0,d.aiPlan||(d=await N(d,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
31
+ runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(s.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),d=await N())}else{let y=await Vt(o.envPath,"utf-8"),m=ct(G(y));d=await N(m??{})}else d=await N();d.licenseKey=l,await M(n,d),b||(s.success("Saved .env"),s.success(d.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),s.blank();for(let p=1;;p++){let y=P.spinner();y.start("Validating Supabase credentials");let m=await Ie({url:d.supabaseUrl,serviceKey:d.supabaseServiceKey});if(m.ok){y.stop("Supabase credentials accepted");break}y.stop(m.message??"Supabase check failed",2),p>=L&&te(n,"Supabase",m.message??"Supabase check failed");let E=m.message??"Supabase check failed";s.blank(),F&&H("supabase",E),s.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${p+1} of ${L})`),s.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"supabase",banner:`Supabase rejected your credentials:
32
+ ${E}
33
33
 
34
34
  Re-enter the URL, secret key, or PAT below. Press Enter on any
35
- field to keep what's already there.`}),await M(n,d)}if(i.blank(),d.deployProvider==="cloudflare")for(let p=1;;p++){let g=S.spinner();g.start("Validating Cloudflare token + account");let m=await mt({token:d.cloudflareApiToken??"",accountId:d.cloudflareAccountId??""});if(m.ok){g.stop(`Cloudflare credentials accepted (${m.projectCount??0} existing Pages project${m.projectCount===1?"":"s"})`);break}g.stop(m.message??"Cloudflare check failed",2),p>=v&&ee(n,"Cloudflare",m.message??"Cloudflare check failed");let A=m.message??"Cloudflare check failed";i.blank(),F&&H("cloudflare",A),i.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${p+1} of ${v})`),i.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await N(d,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
36
- ${A}
35
+ field to keep what's already there.`}),await M(n,d)}if(s.blank(),d.deployProvider==="cloudflare")for(let p=1;;p++){let y=P.spinner();y.start("Validating Cloudflare token + account");let m=await xe({token:d.cloudflareApiToken??"",accountId:d.cloudflareAccountId??""});if(m.ok){y.stop(`Cloudflare credentials accepted (${m.projectCount??0} existing Pages project${m.projectCount===1?"":"s"})`);break}y.stop(m.message??"Cloudflare check failed",2),p>=L&&te(n,"Cloudflare",m.message??"Cloudflare check failed");let E=m.message??"Cloudflare check failed";s.blank(),F&&H("cloudflare",E),s.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${p+1} of ${L})`),s.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
36
+ ${E}
37
37
 
38
38
  Re-enter the API token or Account ID below. The token needs the
39
39
  "Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
40
- the current value.`}),await M(n,d)}else if(d.deployProvider==="netlify")for(let p=1;;p++){let g=S.spinner();g.start("Validating Netlify token");let m=await gt({token:d.netlifyAuthToken??""});if(m.ok){g.stop(m.accountSlug?`Netlify token accepted (team: ${m.accountSlug})`:"Netlify token accepted");break}g.stop(m.message??"Netlify check failed",2),p>=v&&ee(n,"Netlify",m.message??"Netlify check failed");let A=m.message??"Netlify check failed";i.blank(),F&&H("netlify",A),i.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${p+1} of ${v})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await N(d,{onlySection:"netlify",banner:`Netlify rejected the token:
41
- ${A}
40
+ the current value.`}),await M(n,d)}else if(d.deployProvider==="netlify")for(let p=1;;p++){let y=P.spinner();y.start("Validating Netlify token");let m=await Re({token:d.netlifyAuthToken??""});if(m.ok){y.stop(m.accountSlug?`Netlify token accepted (team: ${m.accountSlug})`:"Netlify token accepted");break}y.stop(m.message??"Netlify check failed",2),p>=L&&te(n,"Netlify",m.message??"Netlify check failed");let E=m.message??"Netlify check failed";s.blank(),F&&H("netlify",E),s.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${p+1} of ${L})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"netlify",banner:`Netlify rejected the token:
41
+ ${E}
42
42
 
43
43
  Generate a new token at
44
44
  https://app.netlify.com/user/applications#personal-access-tokens
45
- and paste it below. Press Enter to keep the current value.`}),await M(n,d)}else if(d.deployProvider==="selfhost")for(let p=1;;p++){let g=We(d.selfhostDeployTarget??""),m=ze(d.selfhostUrlTemplate??"");if(!g&&!m){i.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let A=[g&&`SELFHOST_DEPLOY_TARGET: ${g}`,m&&`SELFHOST_URL_TEMPLATE: ${m}`].filter(Boolean).join(`
46
- `);p>=v&&ee(n,"Self-host",A),i.blank(),F&&H("selfhost",A),i.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${p+1} of ${v})`),i.blank(),d=await N(d,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
47
- ${A}
45
+ and paste it below. Press Enter to keep the current value.`}),await M(n,d)}else if(d.deployProvider==="selfhost")for(let p=1;;p++){let y=Qe(d.selfhostDeployTarget??""),m=Je(d.selfhostUrlTemplate??"");if(!y&&!m){s.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let E=[y&&`SELFHOST_DEPLOY_TARGET: ${y}`,m&&`SELFHOST_URL_TEMPLATE: ${m}`].filter(Boolean).join(`
46
+ `);p>=L&&te(n,"Self-host",E),s.blank(),F&&H("selfhost",E),s.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${p+1} of ${L})`),s.blank(),d=await N(d,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
47
+ ${E}
48
48
 
49
- Re-enter them below. Press Enter on a field to keep its current value.`}),await M(n,d)}else for(let p=1;;p++){let g=S.spinner();g.start("Validating Vercel token");let m=await ht(d.vercelToken??"");if(m.ok){g.stop(m.username?`Vercel token accepted (signed in as ${m.username})`:"Vercel token accepted");break}g.stop(m.message??"Vercel check failed",2),p>=v&&ee(n,"Vercel",m.message??"Vercel check failed");let A=m.message??"Vercel check failed";i.blank(),F&&H("vercel",A),i.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${p+1} of ${v})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await N(d,{onlySection:"vercel",banner:`Vercel rejected the token:
50
- ${A}
49
+ Re-enter them below. Press Enter on a field to keep its current value.`}),await M(n,d)}else for(let p=1;;p++){let y=P.spinner();y.start("Validating Vercel token");let m=await Ce(d.vercelToken??"");if(m.ok){y.stop(m.username?`Vercel token accepted (signed in as ${m.username})`:"Vercel token accepted");break}y.stop(m.message,2);let E=m.message,T=m.kind==="rejected"||m.kind==="scope",I=T?`${E} Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration).`:E;p>=L&&te(n,"Vercel",I),s.blank(),F&&H("vercel",I),s.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${p+1} of ${L})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"vercel",banner:T?`${E}
51
50
 
52
- Generate a new token at https://vercel.com/account/tokens and
53
- paste it below. Press Enter to keep the current value.`}),await M(n,d)}i.blank();for(let p=1;;p++){let g=de(d.googlePlacesApiKey??""),m=S.spinner();m.start("Validating Google Places API key");let A=await Ce(d.googlePlacesApiKey??"");if(A.ok){if(m.stop("Google Places API key accepted"),g.changed){if(g.repairs.length>0){i.blank(),i.warn("Corrected look-alike characters in your Google Places API key:");for(let $ of g.repairs)i.detail(` ${$}`);i.detail("These come from keys that were transcribed rather than copied."),i.detail("Google accepted the corrected key, and .env now holds it.")}d.googlePlacesApiKey=g.value,await M(n,d)}break}m.stop(A.message??"Google Places check failed",2),p>=v&&ee(n,"Google Places",A.message??"Google Places check failed");let I=A.message??"Google Places check failed";i.blank(),F&&H("google-places",I),i.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${p+1} of ${v})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await N(d,{onlySection:"google-places",banner:`Google rejected the key:
54
- ${I}
51
+ Create a new token at https://vercel.com/account/settings/tokens
52
+ (Scope: Full Account, Expiration: No Expiration) and paste it
53
+ below. Press Enter to keep the current value.`:`${E}
54
+
55
+ Press Enter to keep the current value and try again, or paste a
56
+ different token.`}),await M(n,d)}s.blank();for(let p=1;;p++){let y=de(d.googlePlacesApiKey??""),m=P.spinner();m.start("Validating Google Places API key");let E=await ve(d.googlePlacesApiKey??"");if(E.ok){if(m.stop("Google Places API key accepted"),y.changed){if(y.repairs.length>0){s.blank(),s.warn("Corrected look-alike characters in your Google Places API key:");for(let I of y.repairs)s.detail(` ${I}`);s.detail("These come from keys that were transcribed rather than copied."),s.detail("Google accepted the corrected key, and .env now holds it.")}d.googlePlacesApiKey=y.value,await M(n,d)}break}m.stop(E.message??"Google Places check failed",2),p>=L&&te(n,"Google Places",E.message??"Google Places check failed");let T=E.message??"Google Places check failed";s.blank(),F&&H("google-places",T),s.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${p+1} of ${L})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"google-places",banner:`Google rejected the key:
57
+ ${T}
55
58
 
56
59
  Generate (or fix) the key at https://console.cloud.google.com
57
- and paste it below. Press Enter to keep the current value.`}),await M(n,d)}let y=!1;if(d.outreachEnabled&&d.outreachChannels?.includes("email")&&d.emailAddress&&d.emailPassword&&d.emailSmtpHost&&d.emailSmtpPort&&d.emailImapHost&&d.emailImapPort){i.blank();let p=0,g=!1,m;for(;!g;){p++;let A=S.spinner();A.start("Validating email credentials (SMTP + IMAP)");let I=d.emailProvider&&d.emailProvider!=="custom"?d.emailProvider:ke(d.emailSmtpHost),$=I?J[I]:void 0,D=await oe({emailAddress:d.emailAddress,emailLogin:d.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:d.emailPassword,emailSmtpHost:d.emailSmtpHost,emailSmtpPort:d.emailSmtpPort,emailImapHost:d.emailImapHost,emailImapPort:d.emailImapPort,usesAccountPassword:$?.usesAccountPassword,sentFolder:(d.emailSentFolder??"").trim()||"Sent",draftsFolder:(d.emailDraftsFolder??"").trim()||"Drafts"});if(D.ok){A.stop("Email credentials accepted (SMTP + IMAP)"),await wt(D,d,{nonInteractive:F,onCancel:()=>{S.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
60
+ and paste it below. Press Enter to keep the current value.`}),await M(n,d)}let g=!1;if(d.outreachEnabled&&d.outreachChannels?.includes("email")&&d.emailAddress&&d.emailPassword&&d.emailSmtpHost&&d.emailSmtpPort&&d.emailImapHost&&d.emailImapPort){s.blank();let p=0,y=!1,m;for(;!y;){p++;let E=P.spinner();E.start("Validating email credentials (SMTP + IMAP)");let T=d.emailProvider&&d.emailProvider!=="custom"?d.emailProvider:we(d.emailSmtpHost),I=T?X[T]:void 0,D=await oe({emailAddress:d.emailAddress,emailLogin:d.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:d.emailPassword,emailSmtpHost:d.emailSmtpHost,emailSmtpPort:d.emailSmtpPort,emailImapHost:d.emailImapHost,emailImapPort:d.emailImapPort,usesAccountPassword:I?.usesAccountPassword,sentFolder:(d.emailSentFolder??"").trim()||"Sent",draftsFolder:(d.emailDraftsFolder??"").trim()||"Drafts"});if(D.ok){E.stop("Email credentials accepted (SMTP + IMAP)"),await kt(D,d,{nonInteractive:F,onCancel:()=>{P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
58
61
 
59
62
  ${re(n)}
60
- `),process.exit(0)}})&&await M(n,d);break}A.stop(D.message??"Email check failed",2);let Ve=`${I}\0${d.emailAddress}\0${d.emailPassword}`;if($&&D.failureKind!=="network"&&m!==Ve){m=Ve;let me=Ye(I,d.emailSmtpHost,d.emailImapHost),Z,nn=0;if(me.length>0){i.blank(),i.warn(`That server rejected the login. ${$.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let q of me){let vt=S.spinner();vt.start(`Trying ${q.label} (${q.smtpHost})`);let Lt=await oe({emailAddress:d.emailAddress,emailLogin:d.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:d.emailPassword,emailSmtpHost:q.smtpHost,emailSmtpPort:d.emailSmtpPort,emailImapHost:q.imapHost,emailImapPort:d.emailImapPort});if(Lt.ok){vt.stop(`${q.label}: your login works here (${q.smtpHost})`),Z=q;break}Lt.failureKind!=="network"&&nn++,vt.stop(Lt.failureKind==="network"?`${q.label}: unreachable`:`${q.label}: rejected too`,2)}}if(Z){if(i.blank(),i.success("Found it \u2014 your password was right all along; the server was the only problem."),F){i.detail(`Non-interactive: using the working ${Z.label} servers automatically.`),d.emailSmtpHost=Z.smtpHost,d.emailImapHost=Z.imapHost,await M(n,d);continue}let q=await S.confirm({message:`Use the ${Z.label} servers (${Z.smtpHost} / ${Z.imapHost})?`,initialValue:!0});if(S.isCancel(q)&&(S.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
63
+ `),process.exit(0)}})&&await M(n,d);break}E.stop(D.message??"Email check failed",2);let ze=`${T}\0${d.emailAddress}\0${d.emailPassword}`;if(I&&D.failureKind!=="network"&&m!==ze){m=ze;let me=qe(T,d.emailSmtpHost,d.emailImapHost),ee,sn=0;if(me.length>0){s.blank(),s.warn(`That server rejected the login. ${I.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let Q of me){let Ot=P.spinner();Ot.start(`Trying ${Q.label} (${Q.smtpHost})`);let Lt=await oe({emailAddress:d.emailAddress,emailLogin:d.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:d.emailPassword,emailSmtpHost:Q.smtpHost,emailSmtpPort:d.emailSmtpPort,emailImapHost:Q.imapHost,emailImapPort:d.emailImapPort});if(Lt.ok){Ot.stop(`${Q.label}: your login works here (${Q.smtpHost})`),ee=Q;break}Lt.failureKind!=="network"&&sn++,Ot.stop(Lt.failureKind==="network"?`${Q.label}: unreachable`:`${Q.label}: rejected too`,2)}}if(ee){if(s.blank(),s.success("Found it \u2014 your password was right all along; the server was the only problem."),F){s.detail(`Non-interactive: using the working ${ee.label} servers automatically.`),d.emailSmtpHost=ee.smtpHost,d.emailImapHost=ee.imapHost,await M(n,d);continue}let Q=await P.confirm({message:`Use the ${ee.label} servers (${ee.smtpHost} / ${ee.imapHost})?`,initialValue:!0});if(P.isCancel(Q)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
61
64
 
62
65
  ${re(n)}
63
- `),process.exit(0)),q){d.emailSmtpHost=Z.smtpHost,d.emailImapHost=Z.imapHost,await M(n,d);continue}}else me.length>0&&(i.blank(),nn===0?i.warn("Couldn't reach any of the alternate servers \u2014 this looks like a network problem, not a credential problem. Check your connection and retry."):$.noAltWorkedHint&&i.warn($.noAltWorkedHint))}let tn=D.message??"Email check failed";i.blank(),i.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),i.detail("You can skip it now and wire it up later from inside the project."),i.blank(),F&&H("email",tn);let Ot=await S.select({message:`What would you like to do? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:p>=3?"skip":p>=2?"edit":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my email details and retry"},{value:"skip",label:"Skip email for now (finish setup; wire email up later)"}]});if(S.isCancel(Ot)&&(S.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
66
+ `),process.exit(0)),Q){d.emailSmtpHost=ee.smtpHost,d.emailImapHost=ee.imapHost,await M(n,d);continue}}else me.length>0&&(s.blank(),sn===0?s.warn("Couldn't reach any of the alternate servers \u2014 this looks like a network problem, not a credential problem. Check your connection and retry."):I.noAltWorkedHint&&s.warn(I.noAltWorkedHint))}let nn=D.message??"Email check failed";s.blank(),s.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),s.detail("You can skip it now and wire it up later from inside the project."),s.blank(),F&&H("email",nn);let vt=await P.select({message:`What would you like to do? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:p>=3?"skip":p>=2?"edit":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my email details and retry"},{value:"skip",label:"Skip email for now (finish setup; wire email up later)"}]});if(P.isCancel(vt)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
64
67
 
65
68
  ${re(n)}
66
- `),process.exit(0)),Ot==="skip"){d.outreachChannels=(d.outreachChannels??[]).filter(me=>me!=="email"),d.outreachPriority=(d.outreachPriority??[]).filter(me=>me!=="email"),d.outreachChannels.length===0&&(d.outreachEnabled=!1),await M(n,d),y=!0,i.success("Skipped email for now. Setup will continue."),d.outreachEnabled?i.detail("Outreach will use your other channel(s); email stays off until it's fixed."):i.detail("Automated outreach is off until email is fixed \u2014 everything else works."),g=!0;break}Ot==="edit"&&(i.blank(),d=await N(d,{onlySection:"email",banner:`${D.failedAt==="imap"?"IMAP":"SMTP"} check failed:
67
- ${tn}
69
+ `),process.exit(0)),vt==="skip"){d.outreachChannels=(d.outreachChannels??[]).filter(me=>me!=="email"),d.outreachPriority=(d.outreachPriority??[]).filter(me=>me!=="email"),d.outreachChannels.length===0&&(d.outreachEnabled=!1),await M(n,d),g=!0,s.success("Skipped email for now. Setup will continue."),d.outreachEnabled?s.detail("Outreach will use your other channel(s); email stays off until it's fixed."):s.detail("Automated outreach is off until email is fixed \u2014 everything else works."),y=!0;break}vt==="edit"&&(s.blank(),d=await N(d,{onlySection:"email",banner:`${D.failedAt==="imap"?"IMAP":"SMTP"} check failed:
70
+ ${nn}
68
71
 
69
72
  Re-enter the email address, app password, or server details below.
70
73
  Press Enter on any field to keep its current value.
71
74
 
72
75
  Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
73
- at the "Server settings" question.`}),await M(n,d))}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="twilio"&&d.twilioAccountSid&&d.twilioAuthToken){i.blank();for(let p=1;;p++){let g=S.spinner();g.start("Validating Twilio credentials");let m=await Xn({accountSid:d.twilioAccountSid,authToken:d.twilioAuthToken});if(m.ok){g.stop(m.friendlyName?`Twilio credentials accepted (${m.friendlyName})`:"Twilio credentials accepted");break}g.stop(m.message??"Twilio check failed",2),p>=v&&ee(n,"Twilio",m.message??"Twilio check failed");let A=m.message??"Twilio check failed";i.blank(),F&&H("sms",A),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${p+1} of ${v})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await N(d,{onlySection:"sms",banner:`Twilio rejected the credentials:
74
- ${A}
76
+ at the "Server settings" question.`}),await M(n,d))}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="twilio"&&d.twilioAccountSid&&d.twilioAuthToken){s.blank();for(let p=1;;p++){let y=P.spinner();y.start("Validating Twilio credentials");let m=await Zn({accountSid:d.twilioAccountSid,authToken:d.twilioAuthToken});if(m.ok){y.stop(m.friendlyName?`Twilio credentials accepted (${m.friendlyName})`:"Twilio credentials accepted");break}y.stop(m.message??"Twilio check failed",2),p>=L&&te(n,"Twilio",m.message??"Twilio check failed");let E=m.message??"Twilio check failed";s.blank(),F&&H("sms",E),s.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${p+1} of ${L})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"sms",banner:`Twilio rejected the credentials:
77
+ ${E}
75
78
 
76
79
  Re-enter the Account SID or Auth Token below.
77
- Press Enter on any field to keep its current value.`}),await M(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("letter")&&d.letterProvider){i.blank();for(let p=1;;p++){let g=S.spinner();g.start("Validating letter provider credentials");let m=await kt({provider:d.letterProvider,pingenClientId:d.pingenClientId,pingenClientSecret:d.pingenClientSecret,pingenOrgId:d.pingenOrgId,postgridApiKey:d.postgridApiKey});if(m.ok){g.stop(m.friendlyName?`Letter provider credentials accepted (${m.friendlyName})`:"Letter provider credentials accepted");break}g.stop(m.message??"Letter provider check failed",2),p>=v&&ee(n,"Letter provider",m.message??"Letter provider check failed");let A=m.message??"Letter provider check failed";i.blank(),i.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${p+1} of ${v})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await N(d,{onlySection:"letter",banner:`The letter provider rejected the credentials:
78
- ${A}
80
+ Press Enter on any field to keep its current value.`}),await M(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("letter")&&d.letterProvider){s.blank();for(let p=1;;p++){let y=P.spinner();y.start("Validating letter provider credentials");let m=await wt({provider:d.letterProvider,pingenClientId:d.pingenClientId,pingenClientSecret:d.pingenClientSecret,pingenOrgId:d.pingenOrgId,postgridApiKey:d.postgridApiKey});if(m.ok){y.stop(m.friendlyName?`Letter provider credentials accepted (${m.friendlyName})`:"Letter provider credentials accepted");break}y.stop(m.message??"Letter provider check failed",2),p>=L&&te(n,"Letter provider",m.message??"Letter provider check failed");let E=m.message??"Letter provider check failed";s.blank(),s.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${p+1} of ${L})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"letter",banner:`The letter provider rejected the credentials:
81
+ ${E}
79
82
 
80
83
  Re-enter them below.
81
- Press Enter on any field to keep its current value.`}),await M(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="imessage"&&d.testPhone){i.blank();for(let p=1;;p++){let g=S.spinner();g.start("Validating iMessage setup (sending a test ping)");let m=await Zn({testPhone:d.testPhone});if(m.ok){if(g.stop("iMessage dispatched (check your phone for the test ping)"),F){console.error("NOTE: iMessage dispatch succeeded but DELIVERY is unverified in non-interactive mode. Check the test message arrived on your phone; if not, open Messages on this Mac, confirm it's signed in with your Apple ID, and enable Settings \u2192 Messages \u2192 Text Message Forwarding on your iPhone.");break}let I=await S.confirm({message:"Did the test message actually arrive on your phone?",initialValue:!0});if(S.isCancel(I)&&(S.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
84
+ Press Enter on any field to keep its current value.`}),await M(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="imessage"&&d.testPhone){s.blank();for(let p=1;;p++){let y=P.spinner();y.start("Validating iMessage setup (sending a test ping)");let m=await ei({testPhone:d.testPhone});if(m.ok){if(y.stop("iMessage dispatched (check your phone for the test ping)"),F){console.error("NOTE: iMessage dispatch succeeded but DELIVERY is unverified in non-interactive mode. Check the test message arrived on your phone; if not, open Messages on this Mac, confirm it's signed in with your Apple ID, and enable Settings \u2192 Messages \u2192 Text Message Forwarding on your iPhone.");break}let T=await P.confirm({message:"Did the test message actually arrive on your phone?",initialValue:!0});if(P.isCancel(T)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
82
85
 
83
86
  ${re(n)}
84
- `),process.exit(0)),I)break;g.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),p>=v&&ee(n,"iMessage","Test message dispatched but never delivered"),i.blank(),i.warn("Messages accepted the send but it didn't arrive. Usual fixes: make sure TEST_PHONE is in international format (+44\u2026 not 07\u2026); open Messages on this Mac and confirm it's signed in with your Apple ID; and on your iPhone enable Settings \u2192 Messages \u2192 Text Message Forwarding for this Mac. Fix, then retry."),i.blank(),d=await N(d,{onlySection:"sms",banner:`The test message was dispatched but never arrived on your phone.
87
+ `),process.exit(0)),T)break;y.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),p>=L&&te(n,"iMessage","Test message dispatched but never delivered"),s.blank(),s.warn("Messages accepted the send but it didn't arrive. Usual fixes: make sure TEST_PHONE is in international format (+44\u2026 not 07\u2026); open Messages on this Mac and confirm it's signed in with your Apple ID; and on your iPhone enable Settings \u2192 Messages \u2192 Text Message Forwarding for this Mac. Fix, then retry."),s.blank(),d=await N(d,{onlySection:"sms",banner:`The test message was dispatched but never arrived on your phone.
85
88
  Re-check the number below (international format with a leading +).
86
- Press Enter on any field to keep its current value.`}),await M(n,d);continue}g.stop(m.message??"iMessage check failed",2),p>=v&&ee(n,"iMessage",m.message??"iMessage check failed");let A=m.message??"iMessage check failed";i.blank(),F&&H("sms",A),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${p+1} of ${v})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await N(d,{onlySection:"sms",banner:`iMessage check failed:
87
- ${A}
89
+ Press Enter on any field to keep its current value.`}),await M(n,d);continue}y.stop(m.message??"iMessage check failed",2),p>=L&&te(n,"iMessage",m.message??"iMessage check failed");let E=m.message??"iMessage check failed";s.blank(),F&&H("sms",E),s.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${p+1} of ${L})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"sms",banner:`iMessage check failed:
90
+ ${E}
88
91
 
89
92
  Either fix the underlying issue (sign in to Messages.app, configure
90
93
  Text Message Forwarding) and press Enter through, or change SMS
91
- provider to Twilio.`}),await M(n,d)}}if((d.notifyChannel??"telegram")==="telegram"&&d.telegramBotToken&&d.telegramChatId){i.blank();let p=0,g=!1;for(;!g;){p++;let m=S.spinner();m.start("Validating Telegram bot + chat (sending a test ping)");let A=await on({botToken:d.telegramBotToken,chatId:d.telegramChatId});if(A.ok){m.stop(A.botHandle?`Telegram bot ${A.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),g=!0;break}m.stop(A.message??"Telegram check failed",2);let I=A.message??"Telegram check failed";i.blank(),i.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),i.blank(),F&&H("notifications",I);let $=await S.select({message:`What would you like to do? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:p>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(S.isCancel($)&&(S.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
94
+ provider to Twilio.`}),await M(n,d)}}if((d.notifyChannel??"telegram")==="telegram"&&d.telegramBotToken&&d.telegramChatId){s.blank();let p=0,y=!1;for(;!y;){p++;let m=P.spinner();m.start("Validating Telegram bot + chat (sending a test ping)");let E=await rn({botToken:d.telegramBotToken,chatId:d.telegramChatId});if(E.ok){m.stop(E.botHandle?`Telegram bot ${E.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),y=!0;break}m.stop(E.message??"Telegram check failed",2);let T=E.message??"Telegram check failed";s.blank(),s.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),s.blank(),F&&H("notifications",T);let I=await P.select({message:`What would you like to do? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:p>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(P.isCancel(I)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
92
95
 
93
96
  ${re(n)}
94
- `),process.exit(0)),$==="skip"){d.telegramBotToken=void 0,d.telegramChatId=void 0,await M(n,d),i.success("Skipped Telegram. Setup will continue."),i.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),g=!0;break}if($==="edit"&&(i.blank(),d=await N(d,{onlySection:"notifications",banner:`Telegram check failed:
95
- ${I}
97
+ `),process.exit(0)),I==="skip"){d.telegramBotToken=void 0,d.telegramChatId=void 0,await M(n,d),s.success("Skipped Telegram. Setup will continue."),s.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),y=!0;break}if(I==="edit"&&(s.blank(),d=await N(d,{onlySection:"notifications",banner:`Telegram check failed:
98
+ ${T}
96
99
 
97
100
  Re-enter the bot token or chat_id below.
98
- Press Enter on any field to keep its current value.`}),await M(n,d),(d.notifyChannel??"telegram")!=="telegram"||!d.telegramBotToken||!d.telegramChatId)){i.success("Skipped Telegram. Setup will continue."),g=!0;break}}}i.blank();let E=S.spinner();E.start("Downloading Klaudius template");let b;try{b=(await dt({licenseKey:l,machineId:He(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:d.aiAgent,destDir:n})).filesExtracted,E.stop(`Downloaded ${b} files into ${h.bold(n)}`)}catch(p){E.stop(p.message,2);let g=d.aiAgent==="codex"?".codex/config.toml":".mcp.json";i.detail(`Your .env / ${g} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await Gt(X(n,"clients"),{recursive:!0});let C=await xn(n);await Fe(n,Cn(ls,C)),i.success("Wrote .klaudius/manifest.json");try{await pt(n,n,Object.keys(C))}catch{}let V=!1,le="";if(e.skipSchema)i.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),i.detail(`Apply manually later via the SQL editor: ${d.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+d.supabaseProjectRef+"/sql/new").replace(d.supabaseProjectRef+".supabase.co","")}`);else{i.blank();let p=S.spinner();p.start("Applying schema to Supabase");let g=await Vn({projectRoot:n,pat:d.supabasePat,projectRef:d.supabaseProjectRef});g.ok?p.stop("Schema applied (or already present)"):(p.stop(g.message??"Schema apply failed",2),V=!0,le=`https://supabase.com/dashboard/project/${d.supabaseProjectRef}/sql/new`)}let R=[],_={};if(e.skipInstall)i.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{i.blank(),i.heading("Installing dependencies");let p=await Et(n);if(i.detail(`npm: ${p.npm}, pip: ${p.pip}, playwright: ${p.playwright}, patchright: ${p.patchright}`),p.npm==="failed"&&R.push("npm"),p.pip==="failed"&&R.push("pip"),p.playwright==="failed"&&R.push("playwright"),p.patchright==="failed"&&R.push("patchright"),_=p.hints??{},p.npm!=="failed"&&p.playwright!=="failed"){i.step("Checking the QA screenshot chain (serving a test page and screenshotting it)\u2026");let g=await bt(n);g.ok?i.success("QA screenshot chain verified (local page served and screenshotted)."):(i.warn(`QA screenshot chain check failed${g.stage?` (${g.stage})`:""}: ${g.detail??"unknown"}`),g.remediation&&i.detail(g.remediation))}}let ce=d.outreachEnabled&&d.outreachPriority?.includes("whatsapp")&&(d.whatsappAccounts?.length??0)>0,j=!e.skipInstall&&!R.includes("npm");if(ce&&j){i.blank(),i.heading("Linking WhatsApp accounts"),console.log(h.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
101
+ Press Enter on any field to keep its current value.`}),await M(n,d),(d.notifyChannel??"telegram")!=="telegram"||!d.telegramBotToken||!d.telegramChatId)){s.success("Skipped Telegram. Setup will continue."),y=!0;break}}}s.blank();let k=P.spinner();k.start("Downloading Klaudius template");let S;try{S=(await ft({licenseKey:l,machineId:Ke(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:d.aiAgent,destDir:n})).filesExtracted,k.stop(`Downloaded ${S} files into ${h.bold(n)}`)}catch(p){k.stop(p.message,2);let y=d.aiAgent==="codex"?".codex/config.toml":".mcp.json";s.detail(`Your .env / ${y} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await Gt(Z(n,"clients"),{recursive:!0});let C=await vn(n);await je(n,xn(ci,C)),s.success("Wrote .klaudius/manifest.json");try{await mt(n,n,Object.keys(C))}catch{}let B=!1,le="";if(e.skipSchema)s.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),s.detail(`Apply manually later via the SQL editor: ${d.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+d.supabaseProjectRef+"/sql/new").replace(d.supabaseProjectRef+".supabase.co","")}`);else{s.blank();let p=P.spinner();p.start("Applying schema to Supabase");let y=await Yn({projectRoot:n,pat:d.supabasePat,projectRef:d.supabaseProjectRef});y.ok?p.stop("Schema applied (or already present)"):(p.stop(y.message??"Schema apply failed",2),B=!0,le=`https://supabase.com/dashboard/project/${d.supabaseProjectRef}/sql/new`)}let R=[],_={};if(e.skipInstall)s.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{s.blank(),s.heading("Installing dependencies");let p=await Et(n);if(s.detail(`npm: ${p.npm}, pip: ${p.pip}, playwright: ${p.playwright}, patchright: ${p.patchright}`),p.npm==="failed"&&R.push("npm"),p.pip==="failed"&&R.push("pip"),p.playwright==="failed"&&R.push("playwright"),p.patchright==="failed"&&R.push("patchright"),_=p.hints??{},p.npm!=="failed"&&p.playwright!=="failed"){s.step("Checking the QA screenshot chain (serving a test page and screenshotting it)\u2026");let y=await bt(n);y.ok?s.success("QA screenshot chain verified (local page served and screenshotted)."):(s.warn(`QA screenshot chain check failed${y.stage?` (${y.stage})`:""}: ${y.detail??"unknown"}`),y.remediation&&s.detail(y.remediation))}}let ce=d.outreachEnabled&&d.outreachPriority?.includes("whatsapp")&&(d.whatsappAccounts?.length??0)>0,j=!e.skipInstall&&!R.includes("npm");if(ce&&j){s.blank(),s.heading("Linking WhatsApp accounts"),console.log(h.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
99
102
  phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
100
- Link a Device, and point it at the QR shown in this terminal.`)),i.blank();for(let p of d.whatsappAccounts){console.log(h.cyan(`Pairing WhatsApp account '${p}'...`)),console.log(h.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${p})`));let g=Yt(process.execPath,["scripts/whatsapp.mjs","pair","--account",p],{cwd:n,stdio:"inherit"});g.status===0?i.detail(`Paired '${p}'.`):(console.log(h.yellow(`'${p}' did not pair (exit ${g.status??"signalled"}). You can finish later via:`)),console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))),i.blank()}}else if(ce&&!j){i.blank(),console.log(h.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let p of d.whatsappAccounts)console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))}let we=d.emailAuth==="oauth-microsoft"&&d.outreachEnabled&&d.outreachChannels?.includes("email"),Me=!e.skipInstall&&!R.includes("pip"),w=p=>{console.log(h.dim("Connect it any time from the project folder with:")),console.log(h.cyan(` ${p?p.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(h.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(we&&Me){i.blank(),i.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(h.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
103
+ Link a Device, and point it at the QR shown in this terminal.`)),s.blank();for(let p of d.whatsappAccounts){console.log(h.cyan(`Pairing WhatsApp account '${p}'...`)),console.log(h.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${p})`));let y=Yt(process.execPath,["scripts/whatsapp.mjs","pair","--account",p],{cwd:n,stdio:"inherit"});y.status===0?s.detail(`Paired '${p}'.`):(console.log(h.yellow(`'${p}' did not pair (exit ${y.status??"signalled"}). You can finish later via:`)),console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))),s.blank()}}else if(ce&&!j){s.blank(),console.log(h.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let p of d.whatsappAccounts)console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))}let ke=d.emailAuth==="oauth-microsoft"&&d.outreachEnabled&&d.outreachChannels?.includes("email"),He=!e.skipInstall&&!R.includes("pip"),w=p=>{console.log(h.dim("Connect it any time from the project folder with:")),console.log(h.cyan(` ${p?p.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(h.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(ke&&He){s.blank(),s.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(h.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
101
104
  password. Your browser will open to Microsoft's sign-in page \u2014
102
105
  sign in as `+(d.emailAddress??"your outreach mailbox")+` and approve.
103
106
  (No browser on this machine? It falls back to a short code you can
104
- enter from any device.)`)),i.blank();let p=await K();if(p){let[g,...m]=p.command,A=Yt(g,[...m,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});A.status===0?i.success("Outlook mailbox connected."):(i.blank(),console.log(h.yellow(`The Microsoft sign-in didn't complete (exit ${A.status??"signalled"}). Setup continues without it.`)),w(p))}else console.log(h.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),w(null)}else we&&!Me&&(i.blank(),console.log(h.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(h.cyan(" python3 scripts/ms_oauth.py login")));i.blank();let x=[...R,...V?["schema"]:[]];if(x.length>0){S.outro(h.yellow(h.bold(`Setup paused \u2014 ${x.join(", ")} failed.`))),console.log(h.dim("Your credentials and project files are all saved.")),i.blank();for(let[D,Ve]of Object.entries(_))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${Ve}`)),i.blank();let p=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${Tt(e.target)}`)}
105
- `:"",g=d.aiAgent==="codex"?"codex":"claude",m=d.aiAgent==="codex"?"Codex":"Claude Code",A=d.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";R.length>0&&(console.log(h.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),i.blank(),p&&process.stdout.write(p),console.log(` ${h.cyan(g)} ${h.dim(`# open ${m} in this folder`)}`),console.log(h.dim(" Then paste:")),console.log(h.cyan(` "Finish my Klaudius install \u2014 ${R.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(h.dim(` (Don't have ${m} yet? Install with: \`${A}\`)`)),i.blank(),console.log(h.dim("Or do it yourself:")),i.blank(),p&&process.stdout.write(p),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retry the failing installers")}`),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify everything")}`),i.blank()),V&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(le)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),R.includes("pip")&&!_.pip&&(console.log(h.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(h.dim(`Python 3.10+. Install a newer one from ${Fo()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),i.blank());let $=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if($.length>0){let D=$.length===1?"keeps":"keep";console.log(h.dim(`If ${$.join(" / ")} ${D} failing with network errors (ECONNRESET,`)),console.log(h.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(h.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}y&&(console.log(h.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${m}`)),console.log(h.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(h.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Ho(d,n,e.target),y){let p=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(h.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(h.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(h.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(h.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(h.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(h.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(h.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(i.blank(),console.log(h.yellow(`Note: your other channel(s) \u2014 ${(d.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),i.blank()}}async function M(e,t){await Gt(e,{recursive:!0}),await Kt(X(e,".env"),st(t),"utf-8"),t.aiAgent==="codex"?(await Gt(X(e,".codex"),{recursive:!0}),await Kt(X(e,".codex","config.toml"),ot(t),"utf-8")):(await Kt(X(e,".mcp.json"),it(t),"utf-8"),await It(e,"supabase"),await ve(e,Oe))}async function Lo(e){try{(await Vt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ds(e),n=t.filter(l=>!l.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(l=>s.has(l)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:X(e,".env")};if(a&&r){let l=!0;try{l=!(await Vt(X(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function $o(e){i.blank(),i.warn(`Found a partial setup at ${h.bold(e)}.`),i.detail(`A previous init wrote ${h.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await S.select({message:`How would you like to proceed? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return S.isCancel(t)&&(S.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function No(e){if(e&&e.trim().length>0)return e;S.intro("Klaudius");let t=await S.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return S.isCancel(t)&&(S.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Mo(e){let t=xo(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let s of n)if(t.startsWith(s))return`Inside ${s.slice(0,-1)} (system-managed directory).`}}function Do(){if(process.platform!=="win32")return!1;try{return Yt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Fo(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Ho(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(S.outro(h.green(h.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${qe[e.aiPlan]}`),console.log(h.dim(r?` \u2192 QA pass off${e.aiPlan==="codex-plus"&&e.aiAgent==="codex"?", model pinned to Terra":""}, so each run fits your usage window.`:" \u2192 full pipeline, including the independent QA pass after every build.")),console.log(h.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),i.blank()}if(console.log(h.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let r=`cd ${Tt(n)}`;console.log(` ${h.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${h.dim("# go into your project folder")}`)}console.log(` ${h.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${h.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(h.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${h.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${h.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${h.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${h.cyan('"Run the pipeline for one client."')}`),console.log(h.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),i.blank(),e.aiAgent!=="codex"&&(console.log(h.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(h.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as Uo,readFile as jo}from"fs/promises";import{join as Wt,resolve as Ko}from"path";import Y from"picocolors";async function fs(e){let t=e.target?Ko(process.cwd(),e.target):process.cwd(),n=await ps(Wt(t,".env")),s=await ps(Wt(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{G(await jo(Wt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await Et(t);i.blank(),i.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let a=[];if(r.npm==="failed"&&a.push("npm"),r.pip==="failed"&&a.push("pip"),r.playwright==="failed"&&a.push("playwright"),r.patchright==="failed"&&a.push("patchright"),a.length===0){i.blank(),console.log(Y.green(Y.bold("All dependencies installed."))),console.log(Y.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(Y.yellow(Y.bold(`${a.join(", ")} still failing.`))),i.blank();for(let[u,k]of Object.entries(r.hints??{}))console.log(Y.yellow(`Likely cause of ${u} failure:`)),console.log(Y.dim(` ${k}`)),i.blank();let l=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",f=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(Y.dim("Options:")),console.log(Y.dim(` \u2022 Open ${c} in this folder (\`${l}\`) and paste:`)),console.log(Y.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(Y.dim(` (Don't have ${c} yet? Install with: \`${f}\`)`)),console.log(Y.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(Y.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function ps(e){try{return await Uo(e),!0}catch{return!1}}import{readFile as Go,writeFile as zt,access as Bo}from"fs/promises";import{join as $e}from"path";import*as te from"@clack/prompts";import ae from"picocolors";import{mkdir as Vo}from"fs/promises";import{spawnSync as hs}from"child_process";async function ms(e){let t=e.projectRoot??process.cwd(),n=$e(t,".env"),s=$e(t,".mcp.json"),o=$e(t,".codex","config.toml"),r=await qt($e(t,".klaudius","manifest.json")),a=await qt(n);!r&&!a&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let l=ue();l.ok||(i.error(l.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let c={};try{let P=await Go(n,"utf-8");c=G(P)}catch{i.warn("No .env found. Starting from an empty configuration.")}let f=Pn(c);Object.keys(c).length>0&&(f.pipelineModes??=["classic"]),te.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await N(f),k=f.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==k&&(i.error(`Switching AI coding agent (${k} \u2192 ${u.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest init <new-folder>")} ${ae.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let P=await Te({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});P.ok||(i.error(P.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let d=de(u.googlePlacesApiKey??"");if(d.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let P=await Ce(u.googlePlacesApiKey);if(P.ok){if(d.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let y of d.repairs)i.detail(` ${y}`);i.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=d.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(P.message??"Google rejected the Google Places API key"),i.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),i.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Yo(u,c)){let P=te.spinner();P.start("Validating email credentials (SMTP + IMAP)");let y=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:ke(u.emailSmtpHost),E=await oe({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:y?J[y].usesAccountPassword:void 0,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});E.ok?(P.stop("Email credentials accepted (SMTP + IMAP)"),await wt(E,u,{nonInteractive:!1,onCancel:()=>i.detail("Left the folder names as they are.")})):(P.stop(E.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(E.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await zt(n,st(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await Vo($e(t,".codex"),{recursive:!0}),await zt(o,ot(u),"utf-8"),i.success("Updated .codex/config.toml")):(await zt(s,it(u),"utf-8"),i.success("Updated .mcp.json"),await It(t,"supabase"),await ve(t,Oe)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let P=await K();if(!(P!==null&&hs(P.command[0],[...P.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!P)i.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),i.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let E=await te.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});te.isCancel(E)||!E?i.detail(`Skipped. Connect it any time with: ${P.command.join(" ")} scripts/ms_oauth.py login`):hs(P.command[0],[...P.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?i.success("Outlook mailbox connected."):(i.warn("The Microsoft sign-in didn't complete."),i.detail(`Connect it any time with: ${P.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),te.outro(ae.green("Configuration updated.")),await Wo(t,r)}function Yo(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];if(n.some(([o])=>o===void 0||o===""))return!1;let s=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([o,r])=>String(o)!==(t[r]??""))||s.some(([o,r])=>o!==void 0&&o!==(t[r]??""))}async function Wo(e,t){let n=await qt($e(e,"node_modules"));i.blank(),t?n||(i.detail("Your project files are in place but dependencies aren't installed yet."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest install")} ${ae.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest doctor")} ${ae.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest init")} ${ae.dim("# pick Resume when prompted")}`),i.blank())}async function qt(e){try{return await Bo(e),!0}catch{return!1}}import{copyFile as gs,mkdir as Qt,readFile as Ct,rm as fe,writeFile as Rt,access as ys}from"fs/promises";import{dirname as Jt,join as L}from"path";import{tmpdir as zo}from"os";import*as he from"@clack/prompts";import Ue from"picocolors";var je="0.32.1";async function ws(e){let t=e.projectRoot??process.cwd(),n=await Tn(t);n||(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let w of at)delete n.files[w];let s,o=L(t,".env"),r,a;try{r=await Ct(o,"utf-8"),a=G(r)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=a.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let l=e.check?null:En(r,a,An);l!==null&&(await Rt(o,l,"utf-8"),i.detail("Backfilled new env keys")),await ft("update",je),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${je}`),await Pt();let f=a.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&f==="claude-code"&&await ve(t,Oe)==="added"&&i.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=L(zo(),`klaudius-update-${process.pid}-${Date.now()}`),k;try{i.heading("Downloading the latest Klaudius template");let w=await dt({licenseKey:s,machineId:He(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:f,destDir:u});i.success(`Fetched ${w.filesExtracted} canonical files`),k=u}catch(w){i.error(w.message),i.detail("Update aborted. Your project is unchanged."),await fe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await qo(k,t,n);if(e.check){let w=d.filter(p=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(p.state)),x=d.filter(p=>["conflict","locally-deleted","removed-modified"].includes(p.state));i.blank(),w.length===0?he.outro(Ue.green("Already up to date.")):(i.detail(`${W(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(Ue.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${w.length===0?"current":"behind"} pending=${w.length} conflicts=${x.length}`),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}let P=!1,y=d.find(w=>w.path===".gitignore"&&w.state==="conflict");if(y){let w=L(t,".gitignore"),x=await Ct(w,"utf-8"),p=await Ct(L(k,".gitignore"),"utf-8"),{merged:g,added:m}=Qo(x,p);m.length>0&&await Rt(w,g,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",P=!0,i.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${W(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let E=d.filter(w=>w.state==="new"),b=d.filter(w=>w.state==="clean-update"),C=d.filter(w=>w.state==="user-only"),V=d.filter(w=>w.state==="conflict"),le=d.filter(w=>w.state==="no-change"),R=d.filter(w=>w.state==="locally-deleted"),_=d.filter(w=>w.state==="removed-clean"),ce=d.filter(w=>w.state==="removed-modified"),j=[...V,...R,...ce],we=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${W(le.length,"file")} unchanged`),i.detail(`${W(E.length,"new file")}`),i.detail(`${W(b.length,"file")} updated cleanly (no local edits)`),i.detail(`${W(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${W(_.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${W(V.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${W(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${W(ce.length,"file")} removed upstream but edited locally (need your decision)`),we>0&&(i.detail(`${W(we,"file")} kept deleted (previously resolved \u2014 skipped)`),we<=10))for(let w of n.ignored)i.detail(` kept deleted: ${w}`);let Me=async()=>{let w=!1,x=p=>fe(p,{recursive:!0,force:!0}).catch(()=>{w=!0});await x(L(t,".klaudius","incoming")),await x(L(t,ut)),await x(L(t,".klaudius","conflicts.md")),w&&i.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(E.length===0&&b.length===0&&_.length===0&&j.length===0&&!P){await Me(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=je,await Fe(t,n)),i.blank(),he.outro(Ue.green("Already up to date.")),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let w of[...E,...b]){let x=L(k,w.path),p=L(t,w.path);await Qt(Jt(p),{recursive:!0}),await gs(x,p),n.files[w.path]=w.canonicalHash}E.length+b.length>0&&i.success(`Wrote ${W(E.length+b.length,"file")}`),[...E,...b].some(w=>w.path==="package.json"||w.path==="package-lock.json")&&i.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let w of _){let x=L(t,w.path);await fe(x,{force:!0}),delete n.files[w.path]}if(_.length>0&&i.success(`Deleted ${W(_.length,"file")} removed upstream`),j.length>0){i.blank(),i.heading(`${j.length} conflict(s) need resolution`);let w=L(t,".klaudius","incoming");try{await fe(w,{recursive:!0,force:!0})}catch{}for(let m of[...V,...R]){let A=L(k,m.path),I=L(w,m.path);await Qt(Jt(I),{recursive:!0}),await gs(A,I)}let x=new Map,p=new Map;for(let m of V){let A=await Dn(t,m.path),I=await Fn(t,m.path),$=await Ct(L(k,m.path),"utf-8"),D=Hn(A,I,$,m.manifestHash);D!==null?(p.set(m.path,D),x.set(m.path,Un(D,$))):A!==null&&(Ie(A)||Ie($))?x.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):A===null?x.set(m.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):x.set(m.path,["_The base snapshot is newer than the version your edits diverged from (an earlier update's conflicts were left unresolved), so a precise upstream diff isn't available for this file \u2014 compare against `.klaudius/incoming/"+m.path+"` directly._"])}let g=L(t,ut);try{await fe(g,{recursive:!0,force:!0})}catch{}for(let[m,A]of p){let I=L(g,m);await Qt(Jt(I),{recursive:!0}),await Rt(I,A,"utf-8")}await Rt(L(t,".klaudius","conflicts.md"),Jo(j,n.templateVersion,je,x,p),"utf-8"),V.length+R.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),p.size>0&&i.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=je,j.length===0?(delete n.pendingConflicts,await Me()):n.pendingConflicts=j.length,await Fe(t,n);try{await pt(t,k,await ge(k))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),j.length===0)he.outro(Ue.green("Update complete."));else{let w=f==="codex"?"Codex":"Claude Code";he.outro(Ue.yellow(`${j.length} conflict(s) staged. Open ${w} in this project and ask:
106
- "Run /resolve-conflicts"`))}await fe(u,{recursive:!0,force:!0}).catch(()=>{})}async function qo(e,t,n){let s=await ge(e),o=new Set(s),r=new Set(n.ignored??[]),a=[];for(let l of s){if(r.has(l))continue;let c=await _e(L(e,l)),f=n.files[l],u=L(t,l),k;try{await ys(u),k=await _e(u)}catch{let P=f!==void 0&&!In.has(l)&&!lt.has(l)?"locally-deleted":"new";a.push({path:l,state:P,canonicalHash:c,manifestHash:f});continue}let d=lt.has(l);c===f?k===f||d?a.push({path:l,state:"no-change",canonicalHash:c,localHash:k,manifestHash:f}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:k,manifestHash:f}):k===f||d?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:k,manifestHash:f}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:k,manifestHash:f})}for(let l of Object.keys(n.files)){if(o.has(l))continue;let c=n.files[l],f=L(t,l),u;try{await ys(f),u=await _e(f)}catch{delete n.files[l];continue}u===c||lt.has(l)?a.push({path:l,state:"removed-clean",localHash:u,manifestHash:c}):a.push({path:l,state:"removed-modified",localHash:u,manifestHash:c})}return a}function W(e,t){return`${e} ${t}${e===1?"":"s"}`}function Qo(e,t){let n=e.includes(`\r
107
+ enter from any device.)`)),s.blank();let p=await K();if(p){let[y,...m]=p.command,E=Yt(y,[...m,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});E.status===0?s.success("Outlook mailbox connected."):(s.blank(),console.log(h.yellow(`The Microsoft sign-in didn't complete (exit ${E.status??"signalled"}). Setup continues without it.`)),w(p))}else console.log(h.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),w(null)}else ke&&!He&&(s.blank(),console.log(h.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(h.cyan(" python3 scripts/ms_oauth.py login")));s.blank();let v=[...R,...B?["schema"]:[]];if(v.length>0){P.outro(h.yellow(h.bold(`Setup paused \u2014 ${v.join(", ")} failed.`))),console.log(h.dim("Your credentials and project files are all saved.")),s.blank();for(let[D,ze]of Object.entries(_))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${ze}`)),s.blank();let p=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${It(e.target)}`)}
108
+ `:"",y=d.aiAgent==="codex"?"codex":"claude",m=d.aiAgent==="codex"?"Codex":"Claude Code",E=d.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";R.length>0&&(console.log(h.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),s.blank(),p&&process.stdout.write(p),console.log(` ${h.cyan(y)} ${h.dim(`# open ${m} in this folder`)}`),console.log(h.dim(" Then paste:")),console.log(h.cyan(` "Finish my Klaudius install \u2014 ${R.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(h.dim(` (Don't have ${m} yet? Install with: \`${E}\`)`)),s.blank(),console.log(h.dim("Or do it yourself:")),s.blank(),p&&process.stdout.write(p),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retry the failing installers")}`),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify everything")}`),s.blank()),B&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(le)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),R.includes("pip")&&!_.pip&&(console.log(h.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(h.dim(`Python 3.10+. Install a newer one from ${Ko()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),s.blank());let I=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if(I.length>0){let D=I.length===1?"keeps":"keep";console.log(h.dim(`If ${I.join(" / ")} ${D} failing with network errors (ECONNRESET,`)),console.log(h.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(h.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}g&&(console.log(h.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${m}`)),console.log(h.dim("to finish setting it up \u2014 your email details are saved in .env.")),s.blank()),console.log(h.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}if(Go(d,n,e.target),g){let p=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(h.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(h.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(h.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(h.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(h.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(h.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(h.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(s.blank(),console.log(h.yellow(`Note: your other channel(s) \u2014 ${(d.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),s.blank()}}async function M(e,t){await Gt(e,{recursive:!0}),await Kt(Z(e,".env"),rt(t),"utf-8"),t.aiAgent==="codex"?(await Gt(Z(e,".codex"),{recursive:!0}),await Kt(Z(e,".codex","config.toml"),lt(t),"utf-8")):(await Kt(Z(e,".mcp.json"),at(t),"utf-8"),await Tt(e,"supabase"),await Ne(e,$e))}async function Do(e){try{(await Bt(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ui(e),n=t.filter(l=>!l.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(l=>i.has(l)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:Z(e,".env")};if(a&&r){let l=!0;try{l=!(await Bt(Z(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Fo(e){s.blank(),s.warn(`Found a partial setup at ${h.bold(e)}.`),s.detail(`A previous init wrote ${h.bold(".env")} but didn't finish scaffolding.`),s.blank();let t=await P.select({message:`How would you like to proceed? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return P.isCancel(t)&&(P.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Ho(e){if(e&&e.trim().length>0)return e;P.intro("Klaudius");let t=await P.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return P.isCancel(t)&&(P.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Uo(e){let t=$o(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let i of n)if(t.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function jo(){if(process.platform!=="win32")return!1;try{return Yt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Ko(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Go(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(h.green(h.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${Xe[e.aiPlan]}`),console.log(h.dim(r?` \u2192 QA pass off${e.aiPlan==="codex-plus"&&e.aiAgent==="codex"?", model pinned to Terra":""}, so each run fits your usage window.`:" \u2192 full pipeline, including the independent QA pass after every build.")),console.log(h.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),s.blank()}if(console.log(h.bold("Next steps:")),s.blank(),t!==process.cwd()&&n){let r=`cd ${It(n)}`;console.log(` ${h.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${h.dim("# go into your project folder")}`)}console.log(` ${h.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${h.dim(`# opens ${o} in this project`)}`),s.blank(),console.log(h.bold(`Some starter prompts for ${o}:`)),s.blank(),console.log(` ${h.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${h.cyan(`I know I'm ready to start using Klaudius."`)}`),s.blank(),console.log(` ${h.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),s.blank(),console.log(` ${h.cyan('"Run the pipeline for one client."')}`),console.log(h.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),s.blank(),e.aiAgent!=="codex"&&(console.log(h.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(h.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),s.blank())}import{access as Vo,readFile as Bo}from"fs/promises";import{join as Wt,resolve as Yo}from"path";import Y from"picocolors";async function hi(e){let t=e.target?Yo(process.cwd(),e.target):process.cwd(),n=await fi(Wt(t,".env")),i=await fi(Wt(t,"package.json"));(!n||!i)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),n||s.detail("Missing: .env"),i||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{G(await Bo(Wt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}s.heading("Installing dependencies");let r=await Et(t);s.blank(),s.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let a=[];if(r.npm==="failed"&&a.push("npm"),r.pip==="failed"&&a.push("pip"),r.playwright==="failed"&&a.push("playwright"),r.patchright==="failed"&&a.push("patchright"),a.length===0){s.blank(),console.log(Y.green(Y.bold("All dependencies installed."))),console.log(Y.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(Y.yellow(Y.bold(`${a.join(", ")} still failing.`))),s.blank();for(let[u,A]of Object.entries(r.hints??{}))console.log(Y.yellow(`Likely cause of ${u} failure:`)),console.log(Y.dim(` ${A}`)),s.blank();let l=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",f=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(Y.dim("Options:")),console.log(Y.dim(` \u2022 Open ${c} in this folder (\`${l}\`) and paste:`)),console.log(Y.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(Y.dim(` (Don't have ${c} yet? Install with: \`${f}\`)`)),console.log(Y.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(Y.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function fi(e){try{return await Vo(e),!0}catch{return!1}}import{readFile as Wo,writeFile as zt,access as zo}from"fs/promises";import{join as De}from"path";import*as W from"@clack/prompts";import ae from"picocolors";import{mkdir as qo}from"fs/promises";import{spawnSync as mi}from"child_process";async function gi(e){let t=e.projectRoot??process.cwd(),n=De(t,".env"),i=De(t,".mcp.json"),o=De(t,".codex","config.toml"),r=await qt(De(t,".klaudius","manifest.json")),a=await qt(n);!r&&!a&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let l=ue();l.ok||(s.error(l.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let c={};try{let g=await Wo(n,"utf-8");c=G(g)}catch{s.warn("No .env found. Starting from an empty configuration.")}let f=Sn(c);Object.keys(c).length>0&&(f.pipelineModes??=["classic"]),W.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let u=await N(f),A=f.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==A&&(s.error(`Switching AI coding agent (${A} \u2192 ${u.aiAgent}) isn't supported via configure.`),s.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest init <new-folder>")} ${ae.dim("# pick the new agent in the wizard")}`),s.blank(),s.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let g=await Ie({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});g.ok||(s.error(g.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let d=Jo(u,c);if(d==="vercel"){let g=W.spinner();g.start("Validating Vercel token");let k=await Ce(u.vercelToken??"");k.ok?g.stop(k.username?`Vercel token accepted (signed in as ${k.username})`:"Vercel token accepted"):(g.stop(k.message,2),s.warn("Writing the token exactly as you entered it \u2014 not verified."),s.detail(k.kind==="rejected"||k.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then re-run `npx klaudius@latest configure`.":k.kind==="network"?"Couldn't reach Vercel \u2014 check your connection, then run `npx klaudius@latest doctor`.":"Vercel's API returned an error \u2014 try again shortly (status.vercel.com), then run `npx klaudius@latest doctor`."))}else if(d==="cloudflare"){let g=W.spinner();g.start("Validating Cloudflare token + account");let k=await xe({token:u.cloudflareApiToken??"",accountId:u.cloudflareAccountId??""});k.ok?g.stop("Cloudflare credentials accepted"):(g.stop(k.message??"Cloudflare check failed",2),s.warn("Writing the credentials exactly as you entered them \u2014 not verified."),s.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(d==="netlify"){let g=W.spinner();g.start("Validating Netlify token");let k=await Re({token:u.netlifyAuthToken??""});k.ok?g.stop(k.accountSlug?`Netlify token accepted (team: ${k.accountSlug})`:"Netlify token accepted"):(g.stop(k.message??"Netlify check failed",2),s.warn("Writing the token exactly as you entered it \u2014 not verified."),s.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let b=de(u.googlePlacesApiKey??"");if(b.changed&&u.googlePlacesApiKey){s.heading("Checking your Google Places API key");let g=await ve(u.googlePlacesApiKey);if(g.ok){if(b.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let k of b.repairs)s.detail(` ${k}`);s.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=b.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(g.message??"Google rejected the Google Places API key"),s.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),s.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Qo(u,c)){let g=W.spinner();g.start("Validating email credentials (SMTP + IMAP)");let k=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:we(u.emailSmtpHost),S=await oe({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:k?X[k].usesAccountPassword:void 0,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});S.ok?(g.stop("Email credentials accepted (SMTP + IMAP)"),await kt(S,u,{nonInteractive:!1,onCancel:()=>s.detail("Left the folder names as they are.")})):(g.stop(S.message??"Email check failed",2),s.warn("Writing the email settings exactly as you entered them \u2014 not verified."),s.detail(S.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await zt(n,rt(u),"utf-8"),s.success("Updated .env"),u.aiAgent==="codex"?(await qo(De(t,".codex"),{recursive:!0}),await zt(o,lt(u),"utf-8"),s.success("Updated .codex/config.toml")):(await zt(i,at(u),"utf-8"),s.success("Updated .mcp.json"),await Tt(t,"supabase"),await Ne(t,$e)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let g=await K();if(!(g!==null&&mi(g.command[0],[...g.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(s.blank(),!g)s.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),s.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let S=await W.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});W.isCancel(S)||!S?s.detail(`Skipped. Connect it any time with: ${g.command.join(" ")} scripts/ms_oauth.py login`):mi(g.command[0],[...g.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?s.success("Outlook mailbox connected."):(s.warn("The Microsoft sign-in didn't complete."),s.detail(`Connect it any time with: ${g.command.join(" ")} scripts/ms_oauth.py login`))}}s.blank(),W.outro(ae.green("Configuration updated.")),await Xo(t,r)}function Qo(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];if(n.some(([o])=>o===void 0||o===""))return!1;let i=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([o,r])=>String(o)!==(t[r]??""))||i.some(([o,r])=>o!==void 0&&o!==(t[r]??""))}function Jo(e,t){let n=(i,o)=>(i??"")!==(t[o]??"");switch(e.deployProvider??"vercel"){case"vercel":return e.vercelToken&&n(e.vercelToken,"VERCEL_TOKEN")?"vercel":null;case"cloudflare":return e.cloudflareApiToken&&e.cloudflareAccountId&&(n(e.cloudflareApiToken,"CLOUDFLARE_API_TOKEN")||n(e.cloudflareAccountId,"CLOUDFLARE_ACCOUNT_ID"))?"cloudflare":null;case"netlify":return e.netlifyAuthToken&&n(e.netlifyAuthToken,"NETLIFY_AUTH_TOKEN")?"netlify":null;default:return null}}async function Xo(e,t){let n=await qt(De(e,"node_modules"));s.blank(),t?n||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest install")} ${ae.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest doctor")} ${ae.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest init")} ${ae.dim("# pick Resume when prompted")}`),s.blank())}async function qt(e){try{return await zo(e),!0}catch{return!1}}import{copyFile as yi,mkdir as Qt,readFile as Ct,rm as fe,writeFile as xt,access as ki}from"fs/promises";import{dirname as Jt,join as $}from"path";import{tmpdir as Zo}from"os";import*as he from"@clack/prompts";import Ge from"picocolors";var Ve="0.32.3";async function wi(e){let t=e.projectRoot??process.cwd(),n=await Cn(t);n||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let w of dt)delete n.files[w];let i,o=$(t,".env"),r,a;try{r=await Ct(o,"utf-8"),a=G(r)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=a.KLAUDIUS_LICENSE_KEY??"",i||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius@latest init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let l=e.check?null:Pn(r,a,En);l!==null&&(await xt(o,l,"utf-8"),s.detail("Backfilled new env keys")),await gt("update",Ve),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Ve}`),await Pt();let f=a.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&f==="claude-code"&&await Ne(t,$e)==="added"&&s.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=$(Zo(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{s.heading("Downloading the latest Klaudius template");let w=await ft({licenseKey:i,machineId:Ke(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:f,destDir:u});s.success(`Fetched ${w.filesExtracted} canonical files`),A=u}catch(w){s.error(w.message),s.detail("Update aborted. Your project is unchanged."),await fe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await er(A,t,n);if(e.check){let w=d.filter(p=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(p.state)),v=d.filter(p=>["conflict","locally-deleted","removed-modified"].includes(p.state));s.blank(),w.length===0?he.outro(Ge.green("Already up to date.")):(s.detail(`${z(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(Ge.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${w.length===0?"current":"behind"} pending=${w.length} conflicts=${v.length}`),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}let b=!1,g=d.find(w=>w.path===".gitignore"&&w.state==="conflict");if(g){let w=$(t,".gitignore"),v=await Ct(w,"utf-8"),p=await Ct($(A,".gitignore"),"utf-8"),{merged:y,added:m}=tr(v,p);m.length>0&&await xt(w,y,"utf-8"),n.files[".gitignore"]=g.canonicalHash,g.state="gitignore-merged",b=!0,s.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${z(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let k=d.filter(w=>w.state==="new"),S=d.filter(w=>w.state==="clean-update"),C=d.filter(w=>w.state==="user-only"),B=d.filter(w=>w.state==="conflict"),le=d.filter(w=>w.state==="no-change"),R=d.filter(w=>w.state==="locally-deleted"),_=d.filter(w=>w.state==="removed-clean"),ce=d.filter(w=>w.state==="removed-modified"),j=[...B,...R,...ce],ke=n.ignored?.length??0;if(s.blank(),s.heading("Change summary"),s.detail(`${z(le.length,"file")} unchanged`),s.detail(`${z(k.length,"new file")}`),s.detail(`${z(S.length,"file")} updated cleanly (no local edits)`),s.detail(`${z(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${z(_.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${z(B.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${z(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),s.detail(`${z(ce.length,"file")} removed upstream but edited locally (need your decision)`),ke>0&&(s.detail(`${z(ke,"file")} kept deleted (previously resolved \u2014 skipped)`),ke<=10))for(let w of n.ignored)s.detail(` kept deleted: ${w}`);let He=async()=>{let w=!1,v=p=>fe(p,{recursive:!0,force:!0}).catch(()=>{w=!0});await v($(t,".klaudius","incoming")),await v($(t,ht)),await v($(t,".klaudius","conflicts.md")),w&&s.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(k.length===0&&S.length===0&&_.length===0&&j.length===0&&!b){await He(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ve,await je(t,n)),s.blank(),he.outro(Ge.green("Already up to date.")),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let w of[...k,...S]){let v=$(A,w.path),p=$(t,w.path);await Qt(Jt(p),{recursive:!0}),await yi(v,p),n.files[w.path]=w.canonicalHash}k.length+S.length>0&&s.success(`Wrote ${z(k.length+S.length,"file")}`),[...k,...S].some(w=>w.path==="package.json"||w.path==="package-lock.json")&&s.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let w of _){let v=$(t,w.path);await fe(v,{force:!0}),delete n.files[w.path]}if(_.length>0&&s.success(`Deleted ${z(_.length,"file")} removed upstream`),j.length>0){s.blank(),s.heading(`${j.length} conflict(s) need resolution`);let w=$(t,".klaudius","incoming");try{await fe(w,{recursive:!0,force:!0})}catch{}for(let m of[...B,...R]){let E=$(A,m.path),T=$(w,m.path);await Qt(Jt(T),{recursive:!0}),await yi(E,T)}let v=new Map,p=new Map;for(let m of B){let E=await Fn(t,m.path),T=await Hn(t,m.path),I=await Ct($(A,m.path),"utf-8"),D=Un(E,T,I,m.manifestHash);D!==null?(p.set(m.path,D),v.set(m.path,jn(D,I))):E!==null&&(Te(E)||Te(I))?v.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):E===null?v.set(m.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):v.set(m.path,["_The base snapshot is newer than the version your edits diverged from (an earlier update's conflicts were left unresolved), so a precise upstream diff isn't available for this file \u2014 compare against `.klaudius/incoming/"+m.path+"` directly._"])}let y=$(t,ht);try{await fe(y,{recursive:!0,force:!0})}catch{}for(let[m,E]of p){let T=$(y,m);await Qt(Jt(T),{recursive:!0}),await xt(T,E,"utf-8")}await xt($(t,".klaudius","conflicts.md"),nr(j,n.templateVersion,Ve,v,p),"utf-8"),B.length+R.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),p.size>0&&s.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Ve,j.length===0?(delete n.pendingConflicts,await He()):n.pendingConflicts=j.length,await je(t,n);try{await mt(t,A,await ge(A))}catch{s.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(s.blank(),j.length===0)he.outro(Ge.green("Update complete."));else{let w=f==="codex"?"Codex":"Claude Code";he.outro(Ge.yellow(`${j.length} conflict(s) staged. Open ${w} in this project and ask:
109
+ "Run /resolve-conflicts"`))}await fe(u,{recursive:!0,force:!0}).catch(()=>{})}async function er(e,t,n){let i=await ge(e),o=new Set(i),r=new Set(n.ignored??[]),a=[];for(let l of i){if(r.has(l))continue;let c=await _e($(e,l)),f=n.files[l],u=$(t,l),A;try{await ki(u),A=await _e(u)}catch{let b=f!==void 0&&!In.has(l)&&!ut.has(l)?"locally-deleted":"new";a.push({path:l,state:b,canonicalHash:c,manifestHash:f});continue}let d=ut.has(l);c===f?A===f||d?a.push({path:l,state:"no-change",canonicalHash:c,localHash:A,manifestHash:f}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:A,manifestHash:f}):A===f||d?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:A,manifestHash:f}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:A,manifestHash:f})}for(let l of Object.keys(n.files)){if(o.has(l))continue;let c=n.files[l],f=$(t,l),u;try{await ki(f),u=await _e(f)}catch{delete n.files[l];continue}u===c||ut.has(l)?a.push({path:l,state:"removed-clean",localHash:u,manifestHash:c}):a.push({path:l,state:"removed-modified",localHash:u,manifestHash:c})}return a}function z(e,t){return`${e} ${t}${e===1?"":"s"}`}function tr(e,t){let n=e.includes(`\r
107
110
  `)?`\r
108
111
  `:`
109
- `,s=e.split(/\r?\n/),o=new Set(s.map(c=>c.trim()).filter(c=>c!=="")),r=[];for(let c of t.split(/\r?\n/)){let f=c.trim();f===""||f.startsWith("#")||o.has(f)||(r.push(f),o.add(f))}if(r.length===0)return{merged:e,added:r};let a=[...s];for(;a.length>0&&a[a.length-1].trim()==="";)a.pop();a.push("","# Added by `klaudius update` (new canonical ignore patterns)",...r);let l=[...new Set(s.map(c=>c.trim()).filter(c=>c.startsWith("!")))].filter(c=>!r.includes(c));return a.push(...l,""),{merged:a.join(n),added:r}}function Jo(e,t,n,s=new Map,o=new Map){let r=e.filter(u=>u.state==="conflict").length,a=e.filter(u=>u.state==="locally-deleted").length,l=e.filter(u=>u.state==="removed-modified").length,c=[];c.push("# Update Conflicts"),c.push(""),c.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),c.push(`Updating from canonical version **${t}** to **${n}**.`),c.push("");let f=[];r>0&&f.push(`${r} file${r===1?"":"s"} ha${r===1?"s":"ve"} BOTH local edits AND upstream changes`),a>0&&f.push(`${a} file${a===1?"":"s"} you deleted locally ${a===1?"is":"are"} still shipped by the canonical template`),l>0&&f.push(`${l} file${l===1?"":"s"} ${l===1?"was":"were"} removed upstream but edited locally`),c.push(f.join(", and ")+"."),c.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),c.push(""),c.push("---"),c.push("");for(let u of e){if(c.push(`## ${u.path}`),c.push(""),u.state==="locally-deleted")c.push("**Type:** Deleted locally"),c.push(""),c.push("- You deleted this file after it was installed; the canonical template still ships it."),c.push(`- New canonical version staged at: \`.klaudius/incoming/${u.path}\``),c.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),c.push(`- New canonical hash: \`${(u.canonicalHash??"(none)").slice(0,16)}\``),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Restore \u2014 copy the canonical version back into place"),c.push("2. Keep deleted \u2014 never reinstall this file (recorded in the manifest's ignore list)");else if(u.state==="removed-modified")c.push("**Type:** Removed upstream"),c.push(""),c.push(`- Your local copy: \`${u.path}\``),c.push("- This file no longer exists in the canonical template."),c.push("- You've modified it locally since install."),c.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),c.push(`- Your local hash now: \`${(u.localHash??"(missing)").slice(0,16)}\``),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),c.push("2. Delete \u2014 remove the file from disk and from the manifest");else{c.push("**Type:** Edit conflict"),c.push(""),c.push(`- Your version (with your local edits): \`${u.path}\``),c.push(`- New canonical version: \`.klaudius/incoming/${u.path}\``),o.has(u.path)&&c.push(`- Pre-edit base (3-way merge ancestor): \`.klaudius/conflict-base/${u.path}\``),c.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),c.push(`- Your local hash now: \`${(u.localHash??"(missing)").slice(0,16)}\``),c.push(`- New canonical hash: \`${(u.canonicalHash??"(none)").slice(0,16)}\``);let k=s.get(u.path);k&&k.length>0&&(c.push(""),c.push("**What upstream changed since your base:**"),c.push(""),c.push(...k),c.push(""),c.push("_If your local edits don't touch the hunks above, merging is mechanical: take the canonical version and re-apply your edits (or apply the hunks to your copy). If they overlap, compare both versions properly before choosing._")),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Keep mine \u2014 discard the new canonical changes"),c.push("2. Take canonical \u2014 overwrite my edits with the new version"),c.push("3. Merge \u2014 review both side-by-side and produce a combined version")}c.push(""),c.push("---"),c.push("")}return c.join(`
110
- `)}import{existsSync as Xo}from"fs";import{access as Zo,readFile as Ke,stat as er}from"fs/promises";import{homedir as tr}from"os";import{join as z}from"path";import U from"picocolors";import{spawn as ks,spawnSync as nr}from"child_process";async function As(e){let t=e.projectRoot??process.cwd(),n=[];console.log(U.bold(`Klaudius doctor \u2014 checking your project\u2026
111
- `)),n.push(await sr());let s=await lr();s&&n.push(s),n.push(await ir());let o=z(t,".env"),r=z(t,".klaudius","manifest.json"),a=z(t,".mcp.json"),l=z(t,".codex","config.toml"),c=await ne(o),f=await ne(r),u="claude-code";if(c)try{G(await Ke(o,"utf-8")).AI_AGENT==="codex"&&(u="codex")}catch{}if(u==="claude-code"){let y=await ne(z(t,"AGENTS.md")),E=!await ne(z(t,".claude"));y&&E&&(u="codex")}n.push({name:".env present",status:c?"ok":"fail",detail:c?o:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."});let k=!1;if(c){let y={};try{y=G(await Ke(o,"utf-8"))}catch{}let E=et(y.AI_PLAN),b=tt(y.QA_PHASE)??Ae(E);k=b==="off";let C=E==="codex-plus"&&u==="codex"?` \xB7 model pin ${Mt}`:"";n.push({name:"Plan / QA pass",status:E?"ok":"warn",detail:E?`${qe[E]} \xB7 QA pass ${b}${C}`:`plan not set \xB7 QA pass ${b}`,nextAction:E?void 0:"Run `npx klaudius@latest configure` and pick your plan \u2014 on Claude Pro / ChatGPT Plus it turns the QA pass off so each run fits your usage window."})}{let y=0,E="";if(f)try{let b=JSON.parse(await Ke(r,"utf-8"));y=typeof b.pendingConflicts=="number"?b.pendingConflicts:0,E=typeof b.templateVersion=="string"?b.templateVersion:""}catch{}n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:f?y>0?"warn":"ok":"fail",detail:f?y>0?`${E||"version unknown"} \u2014 ${y} conflict${y===1?"":"s"} from the last update still unresolved`:E?`${r} (template ${E})`:r:"missing",nextAction:f?y>0?'Open your agent in this folder and say "resolve the conflicts" \u2014 until then some files are still on the previous version.':void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."})}if(u==="codex"){let y=await ne(l);n.push({name:".codex/config.toml present",status:y?"ok":"warn",detail:y?l:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let y=await ne(a);n.push({name:".mcp.json present",status:y?"ok":"warn",detail:y?a:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await kr(u)),process.platform==="win32"){let y=await or(t);y&&n.push(y)}if(n.push(await rr(t)),n.push(await ar(t)),n.push(await cr(t,k)),n.push(await ur()),n.push(await dr(t)),!c)n.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)n.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let y=await Ke(o,"utf-8"),E=G(y);await pr(E,n,t)}console.log();for(let y of n){let E=y.status==="ok"?U.green("\u2713"):y.status==="warn"?U.yellow("\u26A0"):y.status==="skip"?U.dim("\xB7"):U.red("\u2717");console.log(` ${E} ${y.name}${y.detail?U.dim(` \u2014 ${y.detail}`):""}`),y.nextAction&&console.log(` ${U.dim("\u2192")} ${U.cyan(y.nextAction)}`)}let d=n.filter(y=>y.status==="fail").length,P=n.filter(y=>y.status==="warn").length;console.log(),d===0&&P===0?console.log(U.green(U.bold("Everything checks out. You're good to go."))):d===0?console.log(U.yellow(U.bold(`${P} warning${P===1?"":"s"} \u2014 review above.`))):(console.log(U.red(U.bold(`${d} failed check${d===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function ne(e){try{return await Zo(e),!0}catch{return!1}}async function sr(){let e=await be();return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:"Install Python 3.10+ from https://www.python.org/downloads/"}}async function ir(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let n=parseInt(t[1],10),s=parseInt(t[2],10);return n<22||n===22&&s<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function or(e){let t=Ee([{label:"your Windows user folder",path:tr()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",s=await Xt("npm",["config","get","script-shell"],!0),o=s.code===0?s.stdout.trim():void 0;if(Pe(o,Xo))return{name:n,status:"ok",detail:`${t[0].label} contains ${t[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${o}) handles it`};let{detail:r,action:a}=Se(t,"doctor"),l=t.some(c=>c.chars.includes("&"));return{name:n,status:l?"fail":"warn",detail:r,nextAction:a}}async function rr(e){let t=z(e,"node_modules");if(!await ne(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await er(t)).isDirectory())return{name:"node_modules installed",status:"warn",detail:"exists but isn't a directory"}}catch{}return{name:"node_modules installed",status:"ok"}}async function ar(e){let t=process.platform==="darwin"?z(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?z(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):z(process.env.HOME??"",".cache","ms-playwright");return await ne(t)?{name:"Playwright browser installed",status:"ok",detail:t}:{name:"Playwright browser installed",status:"fail",detail:"no browser cache found",nextAction:"Run `npx playwright install chromium` in this folder."}}async function lr(){let e=await Ut();return e.status==="irrelevant"?null:e.status==="ok"?{name:"python3 runtime command",status:"ok",detail:`Python ${e.version}`}:e.status==="no-python"?{name:"python3 runtime command",status:"skip",detail:"no Python found \u2014 see the Python check above"}:{name:"python3 runtime command",status:"fail",detail:e.literal==="stub"?"`python3` is the Microsoft Store placeholder \u2014 every pipeline `python3` call dies":`\`python3\` is missing (your Python answers to \`${e.fallback.command.join(" ")}\`) \u2014 every pipeline \`python3\` call dies`,nextAction:"Fixed automatically by the updater \u2014 running `npx klaudius@latest update` creates the python3 alias from the real Python."}}async function cr(e,t){if(!await ne(z(e,"node_modules","@playwright","cli")))return{name:"QA screenshot chain",status:"skip",detail:"project dependencies not installed",nextAction:"Run `npx klaudius@latest install` first."};let s=await bt(e);if(s.ok)return{name:"QA screenshot chain",status:"ok",detail:"served a page with python3 and screenshotted it"};let o=s.stage!=="python3-server"&&t;return{name:"QA screenshot chain",status:o?"warn":"fail",detail:`${s.stage?`${s.stage}: `:""}${s.detail??"failed"}`+(o?" (QA pass is off \u2014 this matters when you enable it, and for browser-based gathering)":""),nextAction:s.remediation}}async function dr(e){let t=z(e,".klaudius","notify-failures.log");try{let n=(await Ke(t,"utf8")).trim();if(!n)return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"};let s=n.split(/\r?\n/);return{name:"Alert delivery",status:"warn",detail:`${s.length} failed send${s.length===1?"":"s"} recorded; latest: "${s[s.length-1]}"`,nextAction:"Check TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID in .env (rate limits also land here). Delete .klaudius/notify-failures.log once resolved."}}catch{return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"}}}async function ur(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
112
+ `,i=e.split(/\r?\n/),o=new Set(i.map(c=>c.trim()).filter(c=>c!=="")),r=[];for(let c of t.split(/\r?\n/)){let f=c.trim();f===""||f.startsWith("#")||o.has(f)||(r.push(f),o.add(f))}if(r.length===0)return{merged:e,added:r};let a=[...i];for(;a.length>0&&a[a.length-1].trim()==="";)a.pop();a.push("","# Added by `klaudius update` (new canonical ignore patterns)",...r);let l=[...new Set(i.map(c=>c.trim()).filter(c=>c.startsWith("!")))].filter(c=>!r.includes(c));return a.push(...l,""),{merged:a.join(n),added:r}}function nr(e,t,n,i=new Map,o=new Map){let r=e.filter(u=>u.state==="conflict").length,a=e.filter(u=>u.state==="locally-deleted").length,l=e.filter(u=>u.state==="removed-modified").length,c=[];c.push("# Update Conflicts"),c.push(""),c.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),c.push(`Updating from canonical version **${t}** to **${n}**.`),c.push("");let f=[];r>0&&f.push(`${r} file${r===1?"":"s"} ha${r===1?"s":"ve"} BOTH local edits AND upstream changes`),a>0&&f.push(`${a} file${a===1?"":"s"} you deleted locally ${a===1?"is":"are"} still shipped by the canonical template`),l>0&&f.push(`${l} file${l===1?"":"s"} ${l===1?"was":"were"} removed upstream but edited locally`),c.push(f.join(", and ")+"."),c.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),c.push(""),c.push("---"),c.push("");for(let u of e){if(c.push(`## ${u.path}`),c.push(""),u.state==="locally-deleted")c.push("**Type:** Deleted locally"),c.push(""),c.push("- You deleted this file after it was installed; the canonical template still ships it."),c.push(`- New canonical version staged at: \`.klaudius/incoming/${u.path}\``),c.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),c.push(`- New canonical hash: \`${(u.canonicalHash??"(none)").slice(0,16)}\``),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Restore \u2014 copy the canonical version back into place"),c.push("2. Keep deleted \u2014 never reinstall this file (recorded in the manifest's ignore list)");else if(u.state==="removed-modified")c.push("**Type:** Removed upstream"),c.push(""),c.push(`- Your local copy: \`${u.path}\``),c.push("- This file no longer exists in the canonical template."),c.push("- You've modified it locally since install."),c.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),c.push(`- Your local hash now: \`${(u.localHash??"(missing)").slice(0,16)}\``),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),c.push("2. Delete \u2014 remove the file from disk and from the manifest");else{c.push("**Type:** Edit conflict"),c.push(""),c.push(`- Your version (with your local edits): \`${u.path}\``),c.push(`- New canonical version: \`.klaudius/incoming/${u.path}\``),o.has(u.path)&&c.push(`- Pre-edit base (3-way merge ancestor): \`.klaudius/conflict-base/${u.path}\``),c.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),c.push(`- Your local hash now: \`${(u.localHash??"(missing)").slice(0,16)}\``),c.push(`- New canonical hash: \`${(u.canonicalHash??"(none)").slice(0,16)}\``);let A=i.get(u.path);A&&A.length>0&&(c.push(""),c.push("**What upstream changed since your base:**"),c.push(""),c.push(...A),c.push(""),c.push("_If your local edits don't touch the hunks above, merging is mechanical: take the canonical version and re-apply your edits (or apply the hunks to your copy). If they overlap, compare both versions properly before choosing._")),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Keep mine \u2014 discard the new canonical changes"),c.push("2. Take canonical \u2014 overwrite my edits with the new version"),c.push("3. Merge \u2014 review both side-by-side and produce a combined version")}c.push(""),c.push("---"),c.push("")}return c.join(`
113
+ `)}import{existsSync as ir}from"fs";import{access as sr,readFile as Be,stat as or}from"fs/promises";import{homedir as rr}from"os";import{join as q}from"path";import U from"picocolors";import{spawn as Ai,spawnSync as ar}from"child_process";async function Ei(e){let t=e.projectRoot??process.cwd(),n=[];console.log(U.bold(`Klaudius doctor \u2014 checking your project\u2026
114
+ `)),n.push(await lr());let i=await fr();i&&n.push(i),n.push(await cr());let o=q(t,".env"),r=q(t,".klaudius","manifest.json"),a=q(t,".mcp.json"),l=q(t,".codex","config.toml"),c=await ne(o),f=await ne(r),u="claude-code";if(c)try{G(await Be(o,"utf-8")).AI_AGENT==="codex"&&(u="codex")}catch{}if(u==="claude-code"){let g=await ne(q(t,"AGENTS.md")),k=!await ne(q(t,".claude"));g&&k&&(u="codex")}n.push({name:".env present",status:c?"ok":"fail",detail:c?o:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."});let A=!1;if(c){let g={};try{g=G(await Be(o,"utf-8"))}catch{}let k=it(g.AI_PLAN),S=st(g.QA_PHASE)??Ae(k);A=S==="off";let C=k==="codex-plus"&&u==="codex"?` \xB7 model pin ${Mt}`:"";n.push({name:"Plan / QA pass",status:k?"ok":"warn",detail:k?`${Xe[k]} \xB7 QA pass ${S}${C}`:`plan not set \xB7 QA pass ${S}`,nextAction:k?void 0:"Run `npx klaudius@latest configure` and pick your plan \u2014 on Claude Pro / ChatGPT Plus it turns the QA pass off so each run fits your usage window."})}{let g=0,k="";if(f)try{let S=JSON.parse(await Be(r,"utf-8"));g=typeof S.pendingConflicts=="number"?S.pendingConflicts:0,k=typeof S.templateVersion=="string"?S.templateVersion:""}catch{}n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:f?g>0?"warn":"ok":"fail",detail:f?g>0?`${k||"version unknown"} \u2014 ${g} conflict${g===1?"":"s"} from the last update still unresolved`:k?`${r} (template ${k})`:r:"missing",nextAction:f?g>0?'Open your agent in this folder and say "resolve the conflicts" \u2014 until then some files are still on the previous version.':void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."})}if(u==="codex"){let g=await ne(l);n.push({name:".codex/config.toml present",status:g?"ok":"warn",detail:g?l:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let g=await ne(a);n.push({name:".mcp.json present",status:g?"ok":"warn",detail:g?a:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await br(u)),process.platform==="win32"){let g=await dr(t);g&&n.push(g)}if(n.push(await ur(t)),n.push(await pr(t)),n.push(await hr(t,A)),n.push(await gr()),n.push(await mr(t)),!c)n.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)n.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let g=await Be(o,"utf-8"),k=G(g);await yr(k,n,t)}console.log();for(let g of n){let k=g.status==="ok"?U.green("\u2713"):g.status==="warn"?U.yellow("\u26A0"):g.status==="skip"?U.dim("\xB7"):U.red("\u2717");console.log(` ${k} ${g.name}${g.detail?U.dim(` \u2014 ${g.detail}`):""}`),g.nextAction&&console.log(` ${U.dim("\u2192")} ${U.cyan(g.nextAction)}`)}let d=n.filter(g=>g.status==="fail").length,b=n.filter(g=>g.status==="warn").length;console.log(),d===0&&b===0?console.log(U.green(U.bold("Everything checks out. You're good to go."))):d===0?console.log(U.yellow(U.bold(`${b} warning${b===1?"":"s"} \u2014 review above.`))):(console.log(U.red(U.bold(`${d} failed check${d===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function ne(e){try{return await sr(e),!0}catch{return!1}}async function lr(){let e=await be();return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:"Install Python 3.10+ from https://www.python.org/downloads/"}}async function cr(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let n=parseInt(t[1],10),i=parseInt(t[2],10);return n<22||n===22&&i<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function dr(e){let t=Ee([{label:"your Windows user folder",path:rr()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",i=await Xt("npm",["config","get","script-shell"],!0),o=i.code===0?i.stdout.trim():void 0;if(Pe(o,ir))return{name:n,status:"ok",detail:`${t[0].label} contains ${t[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${o}) handles it`};let{detail:r,action:a}=Se(t,"doctor"),l=t.some(c=>c.chars.includes("&"));return{name:n,status:l?"fail":"warn",detail:r,nextAction:a}}async function ur(e){let t=q(e,"node_modules");if(!await ne(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await or(t)).isDirectory())return{name:"node_modules installed",status:"warn",detail:"exists but isn't a directory"}}catch{}return{name:"node_modules installed",status:"ok"}}async function pr(e){let t=process.platform==="darwin"?q(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?q(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):q(process.env.HOME??"",".cache","ms-playwright");return await ne(t)?{name:"Playwright browser installed",status:"ok",detail:t}:{name:"Playwright browser installed",status:"fail",detail:"no browser cache found",nextAction:"Run `npx playwright install chromium` in this folder."}}async function fr(){let e=await Ut();return e.status==="irrelevant"?null:e.status==="ok"?{name:"python3 runtime command",status:"ok",detail:`Python ${e.version}`}:e.status==="no-python"?{name:"python3 runtime command",status:"skip",detail:"no Python found \u2014 see the Python check above"}:{name:"python3 runtime command",status:"fail",detail:e.literal==="stub"?"`python3` is the Microsoft Store placeholder \u2014 every pipeline `python3` call dies":`\`python3\` is missing (your Python answers to \`${e.fallback.command.join(" ")}\`) \u2014 every pipeline \`python3\` call dies`,nextAction:"Fixed automatically by the updater \u2014 running `npx klaudius@latest update` creates the python3 alias from the real Python."}}async function hr(e,t){if(!await ne(q(e,"node_modules","@playwright","cli")))return{name:"QA screenshot chain",status:"skip",detail:"project dependencies not installed",nextAction:"Run `npx klaudius@latest install` first."};let i=await bt(e);if(i.ok)return{name:"QA screenshot chain",status:"ok",detail:"served a page with python3 and screenshotted it"};let o=i.stage!=="python3-server"&&t;return{name:"QA screenshot chain",status:o?"warn":"fail",detail:`${i.stage?`${i.stage}: `:""}${i.detail??"failed"}`+(o?" (QA pass is off \u2014 this matters when you enable it, and for browser-based gathering)":""),nextAction:i.remediation}}async function mr(e){let t=q(e,".klaudius","notify-failures.log");try{let n=(await Be(t,"utf8")).trim();if(!n)return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"};let i=n.split(/\r?\n/);return{name:"Alert delivery",status:"warn",detail:`${i.length} failed send${i.length===1?"":"s"} recorded; latest: "${i[i.length-1]}"`,nextAction:"Check TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID in .env (rate limits also land here). Delete .klaudius/notify-failures.log once resolved."}}catch{return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"}}}async function gr(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
112
115
  try:
113
116
  ${e.map(r=>` import ${r}`).join(`
114
117
  `)}
115
118
  except Exception as e:
116
119
  print(str(e))
117
120
  sys.exit(1)
118
- `,n=await K();if(!n)return{name:"Python packages installed",status:"fail",detail:"no Python interpreter found (tried python3, python, py -3)",nextAction:"Fix the Python check above first \u2014 the packages live inside that interpreter."};let s=n.command,o=await Xt(s[0],[...s.slice(1),"-c",t]);return o.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(o.stdout||o.stderr).trim().split(`
119
- `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function pr(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let a=await Te({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:a.ok?"ok":"fail",detail:a.ok?"connected":a.message,nextAction:a.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});let s=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(s==="selfhost"){let a=e.SELFHOST_DEPLOY_TARGET??"",l=e.SELFHOST_URL_TEMPLATE??"",c=[],f=We(a);f&&c.push(`SELFHOST_DEPLOY_TARGET: ${f}`);let u=ze(l);u&&c.push(`SELFHOST_URL_TEMPLATE: ${u}`),t.push({name:"Self-host deploy config",status:c.length===0?"ok":"fail",detail:c.length===0?`target ${a} (SSH reachability tested at first deploy)`:c.join("; "),nextAction:c.length===0?void 0:"Run `npx klaudius@latest configure` and fix the self-host deployment answers."})}else if(s==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let a=await mt({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:a.ok?"ok":"fail",detail:a.ok?`valid (${a.projectCount??0} Pages project${a.projectCount===1?"":"s"})`:a.message,nextAction:a.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Cloudflare."});else if(s==="netlify")if(e.NETLIFY_AUTH_TOKEN){let a=await gt({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:a.ok?"ok":"fail",detail:a.ok?a.accountSlug?`valid (team: ${a.accountSlug})`:"valid":a.message,nextAction:a.ok?void 0:"Fix the token at https://app.netlify.com/user/applications#personal-access-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Netlify token",status:"fail",detail:"NETLIFY_AUTH_TOKEN missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Netlify."});else if(e.VERCEL_TOKEN){let a=await ht(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:a.ok?"ok":"fail",detail:a.ok?a.username??"valid":a.message,nextAction:a.ok?void 0:"Generate a new token at https://vercel.com/account/tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let a=await Ce(e.GOOGLE_PLACES_API_KEY),l=de(e.GOOGLE_PLACES_API_KEY);a.ok&&l.changed?t.push({name:"Google Places API key",status:"fail",detail:"The key works, but the copy stored in .env is not the key we had to send \u2014 "+(l.repairs.length>0?`it contains look-alike characters (${l.repairs.join("; ")}). `:"it contains invisible or stray characters. ")+"The pipeline's scripts read .env directly and will fail on it.",nextAction:"Run `npx klaudius@latest configure` and press Enter through the prompts \u2014 it rewrites .env with the corrected key."}):t.push({name:"Google Places API key",status:a.ok?"ok":"fail",detail:a.ok?"accepted":a.message,nextAction:a.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius@latest configure`."})}else t.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});t.push(await yr(e,n)),t.push(...await wr(e)),t.push(await mr(e)),t.push(await gr(e));let o=(e.NOTIFY_CHANNEL??"").toLowerCase(),r=o==="email"||o==="sms"||o==="none"||o==="off"?o:"telegram";if(r==="none"||r==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(r==="email"){let a=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:a&&e.EMAIL_ADDRESS?"ok":"fail",detail:a&&e.EMAIL_ADDRESS?`alerts go to ${a}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:a&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(r==="sms"){let a=e.NOTIFY_TO||e.TEST_PHONE,l=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:a&&l?"ok":"fail",detail:a&&l?`alerts go to ${a} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:a?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:a&&l?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let a=await sn({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:a.ok?"ok":"fail",detail:a.ok?`bot ${a.botHandle??"ok"} (chat_id not tested)`:a.message,nextAction:a.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?t.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):t.push({name:"Notifications",status:"skip",detail:"not configured (optional)"})}function fr(e){let t=r=>!!r&&/^\d+$/.test(r.trim()),n=Es(e)?!!e.EMAIL_ADDRESS:!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),s=(e.OUTREACH_CHANNELS??"").split(",").map(r=>r.trim()),o=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&s.includes("email");return o&&n?"active":o?"incomplete":n?"parked":"unconfigured"}function Es(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function hr(e){let t="Email account (Microsoft sign-in)",n=await K(),o=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[a,...l]=n.command,c=nr(a,[...l,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),f=`${c.stdout??""}${c.stderr??""}`.trim();if(c.status===0){let u=/signed in as (\S+)/.exec(f)?.[1];return{name:t,status:"ok",detail:u?`signed in as ${u} (token refresh works)`:"signed in (token refresh works)"}}return{name:t,status:"fail",detail:f.split(`
120
- `)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await ne(z(e,".ms-token.json"))?{name:t,status:"warn",detail:"token cache present, but no Python found to verify it"}:{name:t,status:"fail",detail:"no Microsoft sign-in found (.ms-token.json missing)",nextAction:o}}async function mr(e){let t="Database schema up to date",n=(e.SUPABASE_URL??"").trim().replace(/\/+$/,""),s=(e.SUPABASE_SERVICE_KEY??"").trim();if(!n||!s)return{name:t,status:"skip",detail:"Supabase credentials not set"};try{let o=await fetch(`${n}/rest/v1/clients?select=postal_address&limit=1`,{headers:{apikey:s,Authorization:`Bearer ${s}`}});if(o.ok)return{name:t,status:"ok",detail:"clients.postal_address present"};let r=await o.text();return o.status===400&&/postal_address/.test(r)?(e.OUTREACH_CHANNELS??"").split(",").some(l=>l.trim().toLowerCase()==="letter")?{name:t,status:"warn",detail:"clients.postal_address is missing \u2014 this database was provisioned before the letter channel. Captures still work (values are stored under extra), but the letter channel reads the real column.",nextAction:"Run once in the Supabase SQL editor: ALTER TABLE clients ADD COLUMN IF NOT EXISTS postal_address JSONB;"}:{name:t,status:"skip",detail:"clients.postal_address absent \u2014 only needed by the letter channel, which isn't enabled"}:{name:t,status:"skip",detail:`Could not verify (HTTP ${o.status}) \u2014 see the Supabase rows above.`}}catch{return{name:t,status:"skip",detail:"Supabase unreachable \u2014 skipped schema check"}}}async function gr(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(f=>f.trim().toLowerCase()),s=(e.LETTER_PROVIDER??"").trim().toLowerCase(),o=n.includes("letter");if(!o&&(!s||s==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(o&&s!=="pingen"&&s!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!o)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${s} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let r=await kt({provider:s,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!r.ok)return{name:t,status:"fail",detail:r.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let a=`${s} credentials accepted`+(r.friendlyName?` (${r.friendlyName})`:""),l=(e.SUPABASE_ANON_KEY??"").trim();if(!l)return{name:t,status:"warn",detail:a+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let c=ln(l);if(c&&c!=="anon")return{name:t,status:"fail",detail:a+`, but SUPABASE_ANON_KEY holds a '${c}' key \u2014 shipping it in a claim page would expose the whole database`,nextAction:"Replace SUPABASE_ANON_KEY with the key whose role is 'anon' (Supabase dashboard \u2192 Settings \u2192 API keys)."};if(e.SUPABASE_URL)try{let f=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:l,Authorization:`Bearer ${l}`}});if(f.ok){let u=await f.json();if(Array.isArray(u)&&u.length>0)return{name:t,status:"fail",detail:a+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(s==="postgrid"){let f=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(u=>!(e[u]??"").trim());if(f.length>0)return{name:t,status:"warn",detail:a+`, but PostGrid needs your return address and .env is missing ${f.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:a}}async function yr(e,t){let n="Email credentials (SMTP + IMAP)",s=fr(e);if(s==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Es(e))return s==="parked"?{name:"Email account (Microsoft sign-in)",status:"warn",detail:"Outlook mailbox saved in .env but email isn't an active outreach channel (skipped during setup?)",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."}:s==="incomplete"?{name:"Email account (Microsoft sign-in)",status:"fail",detail:"EMAIL_AUTH=oauth-microsoft but EMAIL_ADDRESS is missing from .env",nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}:hr(t);if(s==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(s==="incomplete"){let c=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(f=>f.endsWith("_PORT")?!e[f]||!/^\d+$/.test(e[f].trim()):!e[f]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${c.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=nt(e),r=o&&o!=="custom"?o:ke(e.EMAIL_SMTP_HOST),a={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:r?J[r].usesAccountPassword:void 0,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},l=await oe(a);if(l.ok){if(l.foldersUnverified)return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the mailbox's folder list could not be read, so the Sent and Drafts folder names are unverified`,nextAction:"Re-run doctor; if it persists, check the mailbox's folder names by hand."};let c=Ps(l,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await K())?.command.join(" ")});return c?{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but ${c.detail}`,nextAction:c.nextAction}:{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(l.failureKind==="network")return{name:n,status:"fail",detail:l.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(r){let c=Ye(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(U.dim(` (email login rejected \u2014 probing ${J[r].label}'s other regional servers, up to ~10s each\u2026)`));let f=0;for(let k of c){let d=await oe({...a,emailSmtpHost:k.smtpHost,emailImapHost:k.imapHost});if(!d.ok&&d.failureKind!=="network"&&f++,d.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${k.label} (${k.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${k.smtpHost} and EMAIL_IMAP_HOST=${k.imapHost} in .env (or ask your AI agent to).`}}let u=(l.message??"login rejected").split(/\.\s|\n/)[0];return f===0?{name:n,status:"fail",detail:`${u} \u2014 and none of the alternate servers were reachable either; this looks like a network problem`,nextAction:"Check your connection and re-run doctor before touching the password."}:{name:n,status:"fail",detail:`${u} \u2014 tried all ${J[r].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:r==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":r==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:l.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}function Ps(e,t){let n=[],s=[],o=[];if(e.sentFolderIssue){let{configured:a,detected:l}=e.sentFolderIssue;n.push(`the server has no "${a}" folder \u2014 sent mail isn't being filed, so follow-ups can't see what was sent to whom`),l?s.push(`${t.sentKey}="${l}"`):o.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:a,detected:l}=e.draftsFolderIssue;n.push(`the server has no "${a}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),l?s.push(`${t.draftsKey}="${l}"`):o.push(t.draftsKey)}if(n.length===0)return;let r=[];if(s.length>0&&r.push(`Set ${s.join(" and ")} in .env (or ask your AI agent to).`),o.length>0){let a=t.python||"python3",l=t.account&&t.account!=="primary"?`${a} scripts/gmail.py folders --account ${t.account}`:`${a} scripts/gmail.py folders`;r.push(`Run \`${l}\` to list this mailbox's folder names, then set ${o.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:r.join(" ")}}async function wr(e){let t=[];for(let n of kn(e)){let s=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:s,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:s,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:s,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:s,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let o=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_SENT_FOLDER`,r=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,a=await oe({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,sentFolder:(e[o]??"").trim()||"Sent",draftsFolder:(e[r]??"").trim()||"Drafts"});if(a.ok){let l=Ps(a,{sentKey:o,draftsKey:r,account:n.label,python:(await K())?.command.join(" ")});l?t.push({name:s,status:"warn",detail:`authenticated (${n.smtpHost}), but ${l.detail}`,nextAction:l.nextAction}):t.push({name:s,status:"ok",detail:`authenticated (${n.smtpHost})`})}else t.push({name:s,status:"fail",detail:a.message,nextAction:a.failureKind==="network"?"Looks like a network/host problem \u2014 check this mailbox's SMTP/IMAP hosts in .env.":"Check this mailbox's password and hosts in .env (regional providers often need a different server)."})}return t}async function kr(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",s=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",o=await Xt(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
121
- `)[0]}:{name:n,status:"warn",detail:"not found",nextAction:s}}function Xt(e,t,n=!1){return new Promise(s=>{let o=n?ks([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ks(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:a})),o.on("error",()=>s({code:1,stdout:r,stderr:a}))})}import{existsSync as Ar}from"fs";import{spawnSync as Er}from"child_process";import{join as Pr,resolve as Sr}from"path";import B from"picocolors";async function Ss(e){let t=Sr(e.projectRoot??process.cwd()),n=Pr(t,"scripts","whatsapp.mjs");Ar(n)||(console.error(B.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(B.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(B.dim(`Looked for: ${n}`)),process.exit(1));let s=(e.label??"primary").trim(),o=s.replace(/[^A-Za-z0-9_-]/g,"");o||(console.error(B.red(`Invalid label '${s}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),o!==s&&console.error(B.yellow(`Note: cleaned label '${s}' \u2192 '${o}' (filename-safe characters only).`)),console.log(B.cyan(`Pairing WhatsApp account '${o}'...`)),console.log(B.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
122
- `));let r=Er(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(B.green(`Paired '${o}'.`)),console.log(B.dim(`
121
+ `,n=await K();if(!n)return{name:"Python packages installed",status:"fail",detail:"no Python interpreter found (tried python3, python, py -3)",nextAction:"Fix the Python check above first \u2014 the packages live inside that interpreter."};let i=n.command,o=await Xt(i[0],[...i.slice(1),"-c",t]);return o.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(o.stdout||o.stderr).trim().split(`
122
+ `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function yr(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let a=await Ie({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:a.ok?"ok":"fail",detail:a.ok?"connected":a.message,nextAction:a.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});let i=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(i==="selfhost"){let a=e.SELFHOST_DEPLOY_TARGET??"",l=e.SELFHOST_URL_TEMPLATE??"",c=[],f=Qe(a);f&&c.push(`SELFHOST_DEPLOY_TARGET: ${f}`);let u=Je(l);u&&c.push(`SELFHOST_URL_TEMPLATE: ${u}`),t.push({name:"Self-host deploy config",status:c.length===0?"ok":"fail",detail:c.length===0?`target ${a} (SSH reachability tested at first deploy)`:c.join("; "),nextAction:c.length===0?void 0:"Run `npx klaudius@latest configure` and fix the self-host deployment answers."})}else if(i==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let a=await xe({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:a.ok?"ok":"fail",detail:a.ok?`valid (${a.projectCount??0} Pages project${a.projectCount===1?"":"s"})`:a.message,nextAction:a.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Cloudflare."});else if(i==="netlify")if(e.NETLIFY_AUTH_TOKEN){let a=await Re({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:a.ok?"ok":"fail",detail:a.ok?a.accountSlug?`valid (team: ${a.accountSlug})`:"valid":a.message,nextAction:a.ok?void 0:"Fix the token at https://app.netlify.com/user/applications#personal-access-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Netlify token",status:"fail",detail:"NETLIFY_AUTH_TOKEN missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Netlify."});else if(e.VERCEL_TOKEN){let a=await Ce(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:a.ok?"ok":"fail",detail:a.ok?a.username??"valid":a.message,nextAction:a.ok?void 0:a.kind==="rejected"||a.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then `npx klaudius@latest configure`.":a.kind==="network"?"Couldn't reach Vercel \u2014 check your connection, then re-run `npx klaudius@latest doctor`.":"Vercel's API returned an error \u2014 try again shortly (status.vercel.com), then re-run `npx klaudius@latest doctor`."})}else t.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let a=await ve(e.GOOGLE_PLACES_API_KEY),l=de(e.GOOGLE_PLACES_API_KEY);a.ok&&l.changed?t.push({name:"Google Places API key",status:"fail",detail:"The key works, but the copy stored in .env is not the key we had to send \u2014 "+(l.repairs.length>0?`it contains look-alike characters (${l.repairs.join("; ")}). `:"it contains invisible or stray characters. ")+"The pipeline's scripts read .env directly and will fail on it.",nextAction:"Run `npx klaudius@latest configure` and press Enter through the prompts \u2014 it rewrites .env with the corrected key."}):t.push({name:"Google Places API key",status:a.ok?"ok":"fail",detail:a.ok?"accepted":a.message,nextAction:a.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius@latest configure`."})}else t.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});t.push(await Pr(e,n)),t.push(...await Sr(e)),t.push(await Ar(e)),t.push(await Er(e));let o=(e.NOTIFY_CHANNEL??"").toLowerCase(),r=o==="email"||o==="sms"||o==="none"||o==="off"?o:"telegram";if(r==="none"||r==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(r==="email"){let a=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:a&&e.EMAIL_ADDRESS?"ok":"fail",detail:a&&e.EMAIL_ADDRESS?`alerts go to ${a}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:a&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(r==="sms"){let a=e.NOTIFY_TO||e.TEST_PHONE,l=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:a&&l?"ok":"fail",detail:a&&l?`alerts go to ${a} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:a?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:a&&l?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let a=await on({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:a.ok?"ok":"fail",detail:a.ok?`bot ${a.botHandle??"ok"} (chat_id not tested)`:a.message,nextAction:a.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?t.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):t.push({name:"Notifications",status:"skip",detail:"not configured (optional)"})}function kr(e){let t=r=>!!r&&/^\d+$/.test(r.trim()),n=Pi(e)?!!e.EMAIL_ADDRESS:!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),i=(e.OUTREACH_CHANNELS??"").split(",").map(r=>r.trim()),o=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&i.includes("email");return o&&n?"active":o?"incomplete":n?"parked":"unconfigured"}function Pi(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function wr(e){let t="Email account (Microsoft sign-in)",n=await K(),o=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[a,...l]=n.command,c=ar(a,[...l,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),f=`${c.stdout??""}${c.stderr??""}`.trim();if(c.status===0){let u=/signed in as (\S+)/.exec(f)?.[1];return{name:t,status:"ok",detail:u?`signed in as ${u} (token refresh works)`:"signed in (token refresh works)"}}return{name:t,status:"fail",detail:f.split(`
123
+ `)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await ne(q(e,".ms-token.json"))?{name:t,status:"warn",detail:"token cache present, but no Python found to verify it"}:{name:t,status:"fail",detail:"no Microsoft sign-in found (.ms-token.json missing)",nextAction:o}}async function Ar(e){let t="Database schema up to date",n=(e.SUPABASE_URL??"").trim().replace(/\/+$/,""),i=(e.SUPABASE_SERVICE_KEY??"").trim();if(!n||!i)return{name:t,status:"skip",detail:"Supabase credentials not set"};try{let o=await fetch(`${n}/rest/v1/clients?select=postal_address&limit=1`,{headers:{apikey:i,Authorization:`Bearer ${i}`}});if(o.ok)return{name:t,status:"ok",detail:"clients.postal_address present"};let r=await o.text();return o.status===400&&/postal_address/.test(r)?(e.OUTREACH_CHANNELS??"").split(",").some(l=>l.trim().toLowerCase()==="letter")?{name:t,status:"warn",detail:"clients.postal_address is missing \u2014 this database was provisioned before the letter channel. Captures still work (values are stored under extra), but the letter channel reads the real column.",nextAction:"Run once in the Supabase SQL editor: ALTER TABLE clients ADD COLUMN IF NOT EXISTS postal_address JSONB;"}:{name:t,status:"skip",detail:"clients.postal_address absent \u2014 only needed by the letter channel, which isn't enabled"}:{name:t,status:"skip",detail:`Could not verify (HTTP ${o.status}) \u2014 see the Supabase rows above.`}}catch{return{name:t,status:"skip",detail:"Supabase unreachable \u2014 skipped schema check"}}}async function Er(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(f=>f.trim().toLowerCase()),i=(e.LETTER_PROVIDER??"").trim().toLowerCase(),o=n.includes("letter");if(!o&&(!i||i==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(o&&i!=="pingen"&&i!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!o)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${i} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let r=await wt({provider:i,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!r.ok)return{name:t,status:"fail",detail:r.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let a=`${i} credentials accepted`+(r.friendlyName?` (${r.friendlyName})`:""),l=(e.SUPABASE_ANON_KEY??"").trim();if(!l)return{name:t,status:"warn",detail:a+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let c=cn(l);if(c&&c!=="anon")return{name:t,status:"fail",detail:a+`, but SUPABASE_ANON_KEY holds a '${c}' key \u2014 shipping it in a claim page would expose the whole database`,nextAction:"Replace SUPABASE_ANON_KEY with the key whose role is 'anon' (Supabase dashboard \u2192 Settings \u2192 API keys)."};if(e.SUPABASE_URL)try{let f=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:l,Authorization:`Bearer ${l}`}});if(f.ok){let u=await f.json();if(Array.isArray(u)&&u.length>0)return{name:t,status:"fail",detail:a+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(i==="postgrid"){let f=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(u=>!(e[u]??"").trim());if(f.length>0)return{name:t,status:"warn",detail:a+`, but PostGrid needs your return address and .env is missing ${f.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:a}}async function Pr(e,t){let n="Email credentials (SMTP + IMAP)",i=kr(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Pi(e))return i==="parked"?{name:"Email account (Microsoft sign-in)",status:"warn",detail:"Outlook mailbox saved in .env but email isn't an active outreach channel (skipped during setup?)",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."}:i==="incomplete"?{name:"Email account (Microsoft sign-in)",status:"fail",detail:"EMAIL_AUTH=oauth-microsoft but EMAIL_ADDRESS is missing from .env",nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}:wr(t);if(i==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(i==="incomplete"){let c=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(f=>f.endsWith("_PORT")?!e[f]||!/^\d+$/.test(e[f].trim()):!e[f]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${c.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=ot(e),r=o&&o!=="custom"?o:we(e.EMAIL_SMTP_HOST),a={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:r?X[r].usesAccountPassword:void 0,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},l=await oe(a);if(l.ok){if(l.foldersUnverified)return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the mailbox's folder list could not be read, so the Sent and Drafts folder names are unverified`,nextAction:"Re-run doctor; if it persists, check the mailbox's folder names by hand."};let c=Si(l,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await K())?.command.join(" ")});return c?{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but ${c.detail}`,nextAction:c.nextAction}:{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(l.failureKind==="network")return{name:n,status:"fail",detail:l.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(r){let c=qe(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(U.dim(` (email login rejected \u2014 probing ${X[r].label}'s other regional servers, up to ~10s each\u2026)`));let f=0;for(let A of c){let d=await oe({...a,emailSmtpHost:A.smtpHost,emailImapHost:A.imapHost});if(!d.ok&&d.failureKind!=="network"&&f++,d.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${A.label} (${A.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${A.smtpHost} and EMAIL_IMAP_HOST=${A.imapHost} in .env (or ask your AI agent to).`}}let u=(l.message??"login rejected").split(/\.\s|\n/)[0];return f===0?{name:n,status:"fail",detail:`${u} \u2014 and none of the alternate servers were reachable either; this looks like a network problem`,nextAction:"Check your connection and re-run doctor before touching the password."}:{name:n,status:"fail",detail:`${u} \u2014 tried all ${X[r].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:r==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":r==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:l.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}function Si(e,t){let n=[],i=[],o=[];if(e.sentFolderIssue){let{configured:a,detected:l}=e.sentFolderIssue;n.push(`the server has no "${a}" folder \u2014 sent mail isn't being filed, so follow-ups can't see what was sent to whom`),l?i.push(`${t.sentKey}="${l}"`):o.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:a,detected:l}=e.draftsFolderIssue;n.push(`the server has no "${a}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),l?i.push(`${t.draftsKey}="${l}"`):o.push(t.draftsKey)}if(n.length===0)return;let r=[];if(i.length>0&&r.push(`Set ${i.join(" and ")} in .env (or ask your AI agent to).`),o.length>0){let a=t.python||"python3",l=t.account&&t.account!=="primary"?`${a} scripts/gmail.py folders --account ${t.account}`:`${a} scripts/gmail.py folders`;r.push(`Run \`${l}\` to list this mailbox's folder names, then set ${o.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:r.join(" ")}}async function Sr(e){let t=[];for(let n of An(e)){let i=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:i,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:i,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:i,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:i,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let o=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_SENT_FOLDER`,r=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,a=await oe({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,sentFolder:(e[o]??"").trim()||"Sent",draftsFolder:(e[r]??"").trim()||"Drafts"});if(a.ok){let l=Si(a,{sentKey:o,draftsKey:r,account:n.label,python:(await K())?.command.join(" ")});l?t.push({name:i,status:"warn",detail:`authenticated (${n.smtpHost}), but ${l.detail}`,nextAction:l.nextAction}):t.push({name:i,status:"ok",detail:`authenticated (${n.smtpHost})`})}else t.push({name:i,status:"fail",detail:a.message,nextAction:a.failureKind==="network"?"Looks like a network/host problem \u2014 check this mailbox's SMTP/IMAP hosts in .env.":"Check this mailbox's password and hosts in .env (regional providers often need a different server)."})}return t}async function br(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",i=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",o=await Xt(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
124
+ `)[0]}:{name:n,status:"warn",detail:"not found",nextAction:i}}function Xt(e,t,n=!1){return new Promise(i=>{let o=n?Ai([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Ai(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>i({code:l??1,stdout:r,stderr:a})),o.on("error",()=>i({code:1,stdout:r,stderr:a}))})}import{existsSync as _r}from"fs";import{spawnSync as Tr}from"child_process";import{join as Ir,resolve as Cr}from"path";import V from"picocolors";async function bi(e){let t=Cr(e.projectRoot??process.cwd()),n=Ir(t,"scripts","whatsapp.mjs");_r(n)||(console.error(V.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(V.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(V.dim(`Looked for: ${n}`)),process.exit(1));let i=(e.label??"primary").trim(),o=i.replace(/[^A-Za-z0-9_-]/g,"");o||(console.error(V.red(`Invalid label '${i}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),o!==i&&console.error(V.yellow(`Note: cleaned label '${i}' \u2192 '${o}' (filename-safe characters only).`)),console.log(V.cyan(`Pairing WhatsApp account '${o}'...`)),console.log(V.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
125
+ `));let r=Tr(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(V.green(`Paired '${o}'.`)),console.log(V.dim(`
123
126
  If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
124
127
  WHATSAPP_ACCOUNTS=primary,${o}
125
- (Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(B.red(`Pair failed: ${r.error.message}`)):(console.error(B.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(B.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(B.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(B.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as Ne,spawn as br}from"child_process";import{existsSync as Ge,mkdirSync as _r,readdirSync as Ir,rmSync as Ts,mkdtempSync as Cs}from"fs";import{homedir as Zt,tmpdir as Rs}from"os";import{join as Q}from"path";import se from"picocolors";var Tr=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function bs(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function xs(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&Be()&&vs();let t=Rr();if(t&&!e.reinstall&&!e.from){Is(),console.log(se.green("Opened the Klaudius app.")),_s();return}let n=await Or(e.from);console.log(se.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?vr(n):Lr(n),Is(),console.log(se.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),_s()}function _s(){process.platform==="darwin"?console.log(se.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(se.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function xt(){return Q(Zt(),"Applications","Klaudius.app")}function Os(){return process.env.LOCALAPPDATA??Q(Zt(),"AppData","Local")}function Cr(){return Q(Os(),"Klaudius")}function Be(){let e=Q(Os(),"Programs");try{for(let t of Ir(e)){if(!/laudius/i.test(t))continue;let n=Q(e,t,"Klaudius.exe");if(Ge(n))return n}}catch{}return null}function Rr(){return process.platform==="darwin"?Ge(xt()):Be()!==null}async function xr(){try{let{readFileSync:e}=await import("fs"),n=e(Q(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function Or(e){if(e)return Ge(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await xr();t||(console.error("Couldn't find your license key."),console.error("Run this from inside your Klaudius folder (the one `npx klaudius init` created)."),process.exit(1));let n=`${Tr}?file=${encodeURIComponent(bs())}`,s=Q(Cs(Q(Rs(),"klaudius-app-")),bs());console.log(se.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.32.1"}});if(!o.ok){let l=`HTTP ${o.status}`;try{let c=await o.json();c.reason&&(l=c.reason)}catch{}throw new Error(l)}let r=Buffer.from(await o.arrayBuffer()),{writeFileSync:a}=await import("fs");return a(s,r),s}catch(o){console.error(`Couldn't download the app (${o.message}). If you're offline, try again later; otherwise email hello@klaudius.dev.`),process.exit(1)}}function vr(e){let t=Q(Zt(),"Applications");_r(t,{recursive:!0});let n=Cs(Q(Rs(),"klaudius-app-x-")),s=Ne("ditto",["-xk",e,n],{stdio:"pipe"});s.status!==0&&(console.error(`Couldn't extract the app: ${s.stderr?.toString().trim()}`),process.exit(1));let o=Q(n,"Klaudius.app");Ge(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),Ts(xt(),{recursive:!0,force:!0});let r=Ne("mv",[o,xt()],{stdio:"pipe"});r.status!==0&&(console.error(`Couldn't install to ~/Applications: ${r.stderr?.toString().trim()}`),process.exit(1))}function Lr(e){/\.exe$/i.test(e)||(console.error("Expected the Klaudius installer (.exe). A zip can't be installed here \u2014 an unzipped copy can never update itself."),process.exit(1));let t=Ne(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!$r(6e4)){let s=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,o=Be();if(o&&Ls(o)){console.log(se.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(se.dim("Open it from the Start Menu if it doesn't appear shortly."));return}console.error(`Klaudius didn't finish installing (${s}).`),console.error("Check your Start Menu for Klaudius \u2014 it may still be finishing."),console.error("If it isn't there, email hello@klaudius.dev."),process.exit(1)}vs()}function $r(e){let t=Date.now()+e;for(;;){let n=Be();if(n)return n;if(Date.now()>=t)return null;Nr(500)}}function Nr(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function vs(){let e=Cr();if(!Ge(Q(e,"app","Klaudius.exe")))return;console.log(se.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
128
+ (Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(V.red(`Pair failed: ${r.error.message}`)):(console.error(V.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(V.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(V.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(V.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as Fe,spawn as xr}from"child_process";import{existsSync as Ye,mkdirSync as Rr,readdirSync as vr,rmSync as Ci,mkdtempSync as xi}from"fs";import{homedir as Zt,tmpdir as Ri}from"os";import{join as J}from"path";import ie from"picocolors";var Or=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function _i(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function vi(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&We()&&Li();let t=$r();if(t&&!e.reinstall&&!e.from){Ii(),console.log(ie.green("Opened the Klaudius app.")),Ti();return}let n=await Mr(e.from);console.log(ie.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Dr(n):Fr(n),Ii(),console.log(ie.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),Ti()}function Ti(){process.platform==="darwin"?console.log(ie.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(ie.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function Rt(){return J(Zt(),"Applications","Klaudius.app")}function Oi(){return process.env.LOCALAPPDATA??J(Zt(),"AppData","Local")}function Lr(){return J(Oi(),"Klaudius")}function We(){let e=J(Oi(),"Programs");try{for(let t of vr(e)){if(!/laudius/i.test(t))continue;let n=J(e,t,"Klaudius.exe");if(Ye(n))return n}}catch{}return null}function $r(){return process.platform==="darwin"?Ye(Rt()):We()!==null}async function Nr(){try{let{readFileSync:e}=await import("fs"),n=e(J(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function Mr(e){if(e)return Ye(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await Nr();t||(console.error("Couldn't find your license key."),console.error("Run this from inside your Klaudius folder (the one `npx klaudius init` created)."),process.exit(1));let n=`${Or}?file=${encodeURIComponent(_i())}`,i=J(xi(J(Ri(),"klaudius-app-")),_i());console.log(ie.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.32.3"}});if(!o.ok){let l=`HTTP ${o.status}`;try{let c=await o.json();c.reason&&(l=c.reason)}catch{}throw new Error(l)}let r=Buffer.from(await o.arrayBuffer()),{writeFileSync:a}=await import("fs");return a(i,r),i}catch(o){console.error(`Couldn't download the app (${o.message}). If you're offline, try again later; otherwise email hello@klaudius.dev.`),process.exit(1)}}function Dr(e){let t=J(Zt(),"Applications");Rr(t,{recursive:!0});let n=xi(J(Ri(),"klaudius-app-x-")),i=Fe("ditto",["-xk",e,n],{stdio:"pipe"});i.status!==0&&(console.error(`Couldn't extract the app: ${i.stderr?.toString().trim()}`),process.exit(1));let o=J(n,"Klaudius.app");Ye(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),Ci(Rt(),{recursive:!0,force:!0});let r=Fe("mv",[o,Rt()],{stdio:"pipe"});r.status!==0&&(console.error(`Couldn't install to ~/Applications: ${r.stderr?.toString().trim()}`),process.exit(1))}function Fr(e){/\.exe$/i.test(e)||(console.error("Expected the Klaudius installer (.exe). A zip can't be installed here \u2014 an unzipped copy can never update itself."),process.exit(1));let t=Fe(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Hr(6e4)){let i=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,o=We();if(o&&$i(o)){console.log(ie.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(ie.dim("Open it from the Start Menu if it doesn't appear shortly."));return}console.error(`Klaudius didn't finish installing (${i}).`),console.error("Check your Start Menu for Klaudius \u2014 it may still be finishing."),console.error("If it isn't there, email hello@klaudius.dev."),process.exit(1)}Li()}function Hr(e){let t=Date.now()+e;for(;;){let n=We();if(n)return n;if(Date.now()>=t)return null;Ur(500)}}function Ur(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Li(){let e=Lr();if(!Ye(J(e,"app","Klaudius.exe")))return;console.log(ie.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
126
129
  $legacy = '${e.replace(/'/g,"''")}'
127
130
  # Compare against the directory PLUS its separator, so a sibling folder whose
128
131
  # name merely starts with the same text ("Klaudius Desktop") is never matched.
@@ -136,4 +139,4 @@ foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetF
136
139
  Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
137
140
  }
138
141
  }
139
- }`;Ne("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Ts(e,{recursive:!0,force:!0})}catch{console.log(se.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function Is(){if(process.platform==="darwin"){Ne("open",["-a",xt()],{stdio:"pipe"});return}let e=Be();if(!e||Ls(e))return;br(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function Ls(e){let t=Ne("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(s=>s.trim().toLowerCase()===n)}import{spawnSync as Mr}from"child_process";var en="--use-system-ca";function $s(){let e=process.env.NODE_OPTIONS??"";if(e.includes(en)||!ue().ok)return;let n=e?`${e} ${en}`:en,s=Mr(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});s.signal&&(process.kill(process.pid,s.signal),process.exit(1)),process.exit(s.status??1)}$s();var Fr="0.32.1",ie=new Dr;ie.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Fr);ie.command("preflight").description("Check this machine can run Klaudius (Node, Python, pip, npm, network) \u2014 no project or license needed. Safe for an AI assistant to run, fix, and re-run before init.").action(async()=>{try{await fn({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});ie.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").option("--answers <file>","Non-interactive setup: read answers from a JSON or dotenv-format file (same keys as .env). On a failed check, exits with code 2 and an INIT-BLOCKED line instead of reopening the wizard.").action(async(e,t)=>{try{await us({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers})}catch(n){console.error("init failed:",n.message),process.exit(1)}});ie.command("install").description("Re-run dependency installers against an already-scaffolded project (npm, pip, playwright, patchright)").argument("[target]","Project directory (defaults to current directory)").action(async e=>{try{await fs({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});ie.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await ms({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});ie.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").option("--check","Report whether an update is available without changing anything").action(async e=>{try{await ws({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});ie.command("doctor").description("Diagnose a broken install \u2014 env versions, files, installed deps, credentials").option("--offline","Skip credential validations that require network calls").action(async e=>{try{await As({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});ie.command("app").description("Install (first run) and open the Klaudius desktop app").option("--from <archive>","Install from a local app archive (testing)").option("--reinstall","Reinstall even if already installed").action(async e=>{try{await xs({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});ie.command("pair-whatsapp").description("Link a WhatsApp account to this project (or re-pair if it logged out)").option("--label <name>","Account label (default: primary). Should match a value in WHATSAPP_ACCOUNTS.","primary").action(async e=>{try{await Ss({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ie.parse(process.argv);
142
+ }`;Fe("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Ci(e,{recursive:!0,force:!0})}catch{console.log(ie.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function Ii(){if(process.platform==="darwin"){Fe("open",["-a",Rt()],{stdio:"pipe"});return}let e=We();if(!e||$i(e))return;xr(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function $i(e){let t=Fe("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(i=>i.trim().toLowerCase()===n)}function Ni(e){return new Promise(t=>{if(e.destroyed||e.writableEnded||!e.writable){t();return}let n=()=>t();e.once("error",n);try{e.write("",n)}catch{n()}})}async function en(e=0){await Promise.all([Ni(process.stdout),Ni(process.stderr)]),process.exit(e)}import{spawnSync as jr}from"child_process";var tn="--use-system-ca";function Mi(){let e=process.env.NODE_OPTIONS??"";if(e.includes(tn)||!ue().ok)return;let n=e?`${e} ${tn}`:tn,i=jr(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}Mi();var Gr="0.32.3",se=new Kr;se.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Gr);se.command("preflight").description("Check this machine can run Klaudius (Node, Python, pip, npm, network) \u2014 no project or license needed. Safe for an AI assistant to run, fix, and re-run before init.").action(async()=>{try{await hn({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});se.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").option("--answers <file>","Non-interactive setup: read answers from a JSON or dotenv-format file (same keys as .env). On a failed check, exits with code 2 and an INIT-BLOCKED line instead of reopening the wizard.").action(async(e,t)=>{try{await pi({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await en(process.exitCode??0)}catch(n){console.error("init failed:",n.message),process.exit(1)}});se.command("install").description("Re-run dependency installers against an already-scaffolded project (npm, pip, playwright, patchright)").argument("[target]","Project directory (defaults to current directory)").action(async e=>{try{await hi({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});se.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await gi({}),await en(process.exitCode??0)}catch(e){console.error("configure failed:",e.message),process.exit(1)}});se.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").option("--check","Report whether an update is available without changing anything").action(async e=>{try{await wi({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});se.command("doctor").description("Diagnose a broken install \u2014 env versions, files, installed deps, credentials").option("--offline","Skip credential validations that require network calls").action(async e=>{try{await Ei({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});se.command("app").description("Install (first run) and open the Klaudius desktop app").option("--from <archive>","Install from a local app archive (testing)").option("--reinstall","Reinstall even if already installed").action(async e=>{try{await vi({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});se.command("pair-whatsapp").description("Link a WhatsApp account to this project (or re-pair if it logged out)").option("--label <name>","Account label (default: primary). Should match a value in WHATSAPP_ACCOUNTS.","primary").action(async e=>{try{await bi({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});se.parse(process.argv);