klaudius 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +59 -59
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
- import{b as we,c as Je,d as X,e as x,f as rn,g as an,h as Xe,i as Ze,j as de,k as ln,l as cn,o as dn,q as Ae,r as Ee,s as Pe,t as N}from"./chunk-FNV6SXGT.js";import{Command as Gr}from"commander";import{spawn as fn}from"child_process";import{existsSync as Xi}from"fs";import{homedir as Zi}from"os";import O from"picocolors";import{win32 as Fi}from"path";var Hi=["&","^","%","!"];function Ui(e){return Hi.filter(t=>e.includes(t))}function Se(e){let t=[];for(let{label:n,path:i}of e){let o=Ui(i);o.length>0&&t.push({label:n,path:i,chars:o})}return t}function ji(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=Fi.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(i)?t:null}function be(e,t){let n=ji(e);return n===null?!1:t?t(n):!0}function _e(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 Ki}from"child_process";import{existsSync as Gi}from"fs";import{homedir as Vi}from"os";import{delimiter as Bi,join as et}from"path";var Yi=new Set(["Restricted","AllSigned"]);function Wi(e,t=Gi){for(let n of e.split(Bi)){let i=n.replace(/"/g,"");if(!i)continue;let o=et(i,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let a=et(i,r);if(t(a))return{path:a,isPs1:!1}}}return null}async function pn(){let e=Wi(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await zi();if(!t)return{blocked:!1,shimPath:e.path};let n=et(Vi(),".local","node")+"\\";return{blocked:Yi.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function zi(){let e=et(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await un(e)??await un("powershell.exe")}function un(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let i=Ki(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 qi}from"child_process";var Ke=3,tt=10,Qi=[["python3"],["python"],["py","-3"]];async function K(){for(let e of Qi){let t=await nt(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 Te(){let e=Ji(),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 ${Ke}.${tt}+ is not installed (or not on PATH). Install it from ${e}.`+a}}let{command:n,version:i,major:o,minor:r}=t;return o<Ke||o===Ke&&r<tt?{ok:!1,version:i,major:o,minor:r,command:n,message:`Your installed Python is ${i}. Klaudius needs Python ${Ke}.${tt} or newer (the pipeline depends on packages that only ship wheels for ${Ke}.${tt}+). 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 Ji(){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 nt(e,t){return new Promise(n=>{let i=qi(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 hn=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function mn(e={}){console.log(O.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
- `));let t=[];t.push(es());let n=await Te();if(t.push(ts(n)),t.push(await ns(n.command)),t.push(await is()),process.platform==="win32"){let o=await ss();o&&t.push(o);let r=await os();r&&t.push(r)}t.push(await rs());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;as(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 es(){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 ts(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 ns(e){let t=e??["python3"],n=await it(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 is(){let e=process.platform==="win32",t=await it("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 it("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 ss(){let e=await pn();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 os(){let e=Se([{label:"your Windows user folder",path:Zi()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await it("npm",["config","get","script-shell"],!0),i=n.code===0?n.stdout.trim():void 0;if(be(i,Xi))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}=_e(e,"preflight"),a=e.some(l=>l.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function rs(){try{return await fetch(hn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:hn}}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 as(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 it(e,t,n=!1){return new Promise(i=>{let o=n?fn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):fn(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 Vt,readdir as pi,readFile as Bt,stat as Yt,writeFile as Gt}from"fs/promises";import{spawnSync as Wt}from"child_process";import{homedir as Oo}from"os";import{resolve as Lo,isAbsolute as $o,join as Z,normalize as No}from"path";import*as P from"@clack/prompts";import h from"picocolors";var ls={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"},cs={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 gn(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9.,  ]*$/.test(n))return n;let i=cs[(t??"").toUpperCase()];return i?`${i.pre??""}${n}${i.post??""}`:n}function Nt(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?ls[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 Mt="claude-code",Dt="gpt-5.6-terra";function yn(e){if(e==="claude-code"||e==="codex")return e}var ds=["claude-pro","claude-max-5x","claude-max-20x","claude-team-standard","claude-team-premium","claude-other","codex-plus","codex-pro","codex-business","codex-business-premium","codex-other"];function st(e){let t=e?.trim().toLowerCase()??"";return ds.includes(t)?t:void 0}function ot(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 Ft="vercel";function kn(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function wn(e){if(e==="telegram"||e==="email"||e==="sms")return e}function An(e){if(e==="password"||e==="oauth-microsoft")return e}function us(e){if(e==="custom"||e!==void 0&&Object.hasOwn(X,e))return e}function rt(e){let t=us(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 En(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 at(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??Mt),i("AI_PLAN",e.aiPlan),i("QA_PHASE",e.qaPhase??Ee(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",gn(e.pricing,e.countryCode)),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",gn(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",Nt(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??Ft),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(`
2
+ import{b as we,c as Xe,d as X,e as I,f as ln,g as cn,h as Ze,i as et,j as de,k as dn,l as un,o as pn,q as Ae,r as Ee,s as Pe,t as N}from"./chunk-FNV6SXGT.js";import{Command as Qr}from"commander";import{spawn as mn}from"child_process";import{existsSync as ti}from"fs";import{homedir as ni}from"os";import L from"picocolors";import{win32 as js}from"path";var Ks=["&","^","%","!"];function Gs(e){return Ks.filter(t=>e.includes(t))}function Se(e){let t=[];for(let{label:n,path:s}of e){let o=Gs(s);o.length>0&&t.push({label:n,path:s,chars:o})}return t}function Bs(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=js.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(s)?t:null}function be(e,t){let n=Bs(e);return n===null?!1:t?t(n):!0}function _e(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 Vs}from"child_process";import{existsSync as Ys}from"fs";import{homedir as Ws}from"os";import{delimiter as qs,join as tt}from"path";var zs=new Set(["Restricted","AllSigned"]);function Qs(e,t=Ys){for(let n of e.split(qs)){let s=n.replace(/"/g,"");if(!s)continue;let o=tt(s,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let a=tt(s,r);if(t(a))return{path:a,isPs1:!1}}}return null}async function hn(){let e=Qs(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Js();if(!t)return{blocked:!1,shimPath:e.path};let n=tt(Ws(),".local","node")+"\\";return{blocked:zs.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Js(){let e=tt(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await fn(e)??await fn("powershell.exe")}function fn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let s=Vs(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 Xs}from"child_process";var Ge=3,nt=10,Zs=[["python3"],["python"],["py","-3"]];async function K(){for(let e of Zs){let t=await st(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 Te(){let e=ei(),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 ${Ge}.${nt}+ is not installed (or not on PATH). Install it from ${e}.`+a}}let{command:n,version:s,major:o,minor:r}=t;return o<Ge||o===Ge&&r<nt?{ok:!1,version:s,major:o,minor:r,command:n,message:`Your installed Python is ${s}. Klaudius needs Python ${Ge}.${nt} or newer (the pipeline depends on packages that only ship wheels for ${Ge}.${nt}+). 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 ei(){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 st(e,t){return new Promise(n=>{let s=Xs(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 gn=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function yn(e={}){console.log(L.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
+ `));let t=[];t.push(si());let n=await Te();if(t.push(ii(n)),t.push(await oi(n.command)),t.push(await ri()),process.platform==="win32"){let o=await ai();o&&t.push(o);let r=await li();r&&t.push(r)}t.push(await ci());for(let o of t){let r=o.status==="ok"?L.green("\u2713"):o.status==="warn"?L.yellow("!"):L.red("\u2717");console.log(` ${r} ${o.name}${o.detail?L.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${L.dim("\u2192")} ${L.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;di(o);return}console.log(L.red(L.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(L.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(L.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function si(){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 ii(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 oi(e){let t=e??["python3"],n=await it(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 ri(){let e=process.platform==="win32",t=await it("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 it("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 ai(){let e=await hn();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 li(){let e=Se([{label:"your Windows user folder",path:ni()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await it("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(be(s,ti))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}=_e(e,"preflight"),a=e.some(l=>l.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function ci(){try{return await fetch(gn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:gn}}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 di(e=0){e>0?console.log(L.green(L.bold("Your machine is ready."))+L.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(L.green(L.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(L.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(` ${L.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(L.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(L.dim(" run it in a new terminal window.")),console.log()}function it(e,t,n=!1){return new Promise(s=>{let o=n?mn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):mn(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 Yt,readdir as hs,readFile as Wt,stat as qt,writeFile as Vt}from"fs/promises";import{spawnSync as zt}from"child_process";import{homedir as Fo}from"os";import{resolve as Uo,isAbsolute as Ho,join as Z,normalize as jo}from"path";import*as P from"@clack/prompts";import m from"picocolors";var ui={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"},pi={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 kn(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9.,  ]*$/.test(n))return n;let s=pi[(t??"").toUpperCase()];return s?`${s.pre??""}${n}${s.post??""}`:n}function Mt(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?ui[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 Ft="claude-code",Ut="gpt-5.6-terra";function wn(e){if(e==="claude-code"||e==="codex")return e}var fi=["claude-pro","claude-max-5x","claude-max-20x","claude-team-standard","claude-team-premium","claude-other","codex-plus","codex-pro","codex-business","codex-business-premium","codex-other"];function ot(e){let t=e?.trim().toLowerCase()??"";return fi.includes(t)?t:void 0}function rt(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 Ht="vercel";function An(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function En(e){if(e==="telegram"||e==="email"||e==="sms")return e}function Pn(e){if(e==="password"||e==="oauth-microsoft")return e}function hi(e){if(e==="custom"||e!==void 0&&Object.hasOwn(X,e))return e}function at(e){let t=hi(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[s,o]of Object.entries(X))if(o.smtpHost===n)return s;return"custom"}}function Sn(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 lt(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??Ft),s("AI_PLAN",e.aiPlan),s("QA_PHASE",e.qaPhase??Ee(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",kn(e.pricing,e.countryCode)),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",kn(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",Mt(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??Ht),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(`
5
5
  `)+`
6
- `}function lt(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 ct(e){let t=e.supabaseProjectRef,n=ps(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&&Ae.has(e.aiPlan)?[`# Set by the wizard for ${Pe[e.aiPlan]}. Change or delete to use Codex's default.`,`model = "${Dt}"`,""]:[],"[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 ps(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Pn=[{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 fs(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function Sn(e,t,n){let i=n.filter(a=>!(a.key in t));if(i.length===0)return null;let o=e.endsWith(`
6
+ `}function ct(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 dt(e){let t=e.supabaseProjectRef,n=mi(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&&Ae.has(e.aiPlan)?[`# Set by the wizard for ${Pe[e.aiPlan]}. Change or delete to use Codex's default.`,`model = "${Ut}"`,""]:[],"[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 mi(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var bn=[{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 gi(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function _n(e,t,n){let s=n.filter(a=>!(a.key in t));if(s.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 i)r.push(""),a.comment&&r.push(`# ${a.comment}`),r.push(fs(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 s)r.push(""),a.comment&&r.push(`# ${a.comment}`),r.push(gi(a.key,a.value));return e+o+r.join(`
11
11
  `)+`
12
- `}function hs(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=hs(i.slice(o+1).trim());t[r]=a}return t}function bn(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:yn(e.AI_AGENT)??Mt,aiPlan:st(e.AI_PLAN),qaPhase:ot(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:rt(e),emailAuth:An(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:Nt(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:kn(e.DEPLOY_PROVIDER)??Ft,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:wn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function dt(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=kn(e.DEPLOY_PROVIDER)??Ft,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:yn(e.AI_AGENT)??Mt,aiPlan:st(e.AI_PLAN),qaPhase:ot(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:rt(e),emailAuth:An(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:Nt(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:wn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Aa,mkdir as Ea,readdir as Ps,stat as Pa}from"fs/promises";import{dirname as ba,join as vn,relative as Ss,sep as bs}from"path";import{fileURLToPath as Ta}from"url";import{createHash as _n}from"crypto";import{readFile as ms}from"fs/promises";async function Ie(e){let t=await ms(e);return _n("sha256").update(t).digest("hex")}function Ht(e){return _n("sha256").update(e).digest("hex")}import{mkdir as gs,readFile as ys,writeFile as ks,access as ws}from"fs/promises";import{dirname as As,join as Tn}from"path";var Es=".klaudius",In=`${Es}/manifest.json`,ut=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json"]),Cn=new Set(["clients/README.md"]),pt=new Set(["package-lock.json"]);async function xn(e){let t=Tn(e,In);try{await ws(t)}catch{return null}let n=await ys(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 Ge(e,t){let n=Tn(e,In);await gs(As(n),{recursive:!0}),await ks(n,JSON.stringify(t,null,2)+`
14
- `,"utf-8")}function Rn(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 Ps(e,{withFileTypes:!0}),i=[];for(let o of n){let r=vn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?i.push(...await ge(r,t)):o.isFile()&&i.push(Ss(t,r).split(bs).join("/")))}return i}async function On(e){let t=await ge(e),n={};for(let i of t)ut.has(i)||(n[i]=await Ie(vn(e,i)));return n}import{copyFile as _s,mkdir as Ln,mkdtemp as Ts,readdir as $n,rm as Nn}from"fs/promises";import{tmpdir as Is}from"os";import{dirname as Cs,join as ft}from"path";import{Readable as xs}from"stream";import*as Mn from"tar";var Rs="https://klaudius.dev/api/template";function vs(e){return xs.fromWeb(e)}async function ht(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Rs,n="0.33.0",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 Ts(ft(Is(),"klaudius-template-")),a=0;try{try{await new Promise((f,u)=>{let A=Mn.extract({cwd:r,strict:!0});A.on("finish",f),A.on("error",u),vs(i.body).on("error",u).pipe(A)})}catch(f){throw new Error(`Failed to extract template archive: ${f.message}`)}await Ln(e.destDir,{recursive:!0});let l=new Set(await $n(e.destDir)),c=await ge(r);try{for(let f of c){let u=ft(e.destDir,f);await Ln(Cs(u),{recursive:!0}),await _s(ft(r,f),u),a++}}catch(f){let u=await $n(e.destDir).catch(()=>[]);for(let A of u)l.has(A)||await Nn(ft(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 Nn(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:a,tier:o}}import{copyFile as Os,mkdir as Ls,readFile as Dn,rm as $s}from"fs/promises";import{dirname as Ns,join as ye}from"path";import{structuredPatch as Ms}from"diff";var Fn=ye(".klaudius","base"),mt=ye(".klaudius","conflict-base");async function gt(e,t,n){let i=ye(e,Fn);await $s(i,{recursive:!0,force:!0});for(let o of n){let r=ye(i,o);await Ls(Ns(r),{recursive:!0}),await Os(ye(t,o),r)}}async function Hn(e,t){try{return await Dn(ye(e,Fn,t),"utf-8")}catch{return null}}async function Un(e,t){try{return await Dn(ye(e,mt,t),"utf-8")}catch{return null}}function jn(e,t,n,i){return Ce(n)?null:e!==null&&!Ce(e)&&(!i||Ht(e)===i)?e:t!==null&&!Ce(t)&&i&&Ht(t)===i?t:null}function Ce(e){return e.includes("\0")||e.includes("\uFFFD")}function Kn(e,t,n=60){let i=Ms("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 Ds="https://registry.npmjs.org/klaudius/latest";async function Fs(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Ds,{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 Hs(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 yt(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Fs();!n||!Hs(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 Us}from"crypto";import{hostname as Gn,userInfo as js,platform as Vn,arch as Bn}from"os";var Ks="https://klaudius.dev",Gs="/api/licenses/validate",Vs="0.33.0";async function Yn(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??Ks).replace(/\/$/,"")+Gs,o=Ve(),r;try{r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Gn(),os:`${Vn()}-${Bn()}`,cli_version:Vs})})}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 Ve(){let e=[Gn(),js().username,Vn(),Bn()].join("|");return Us("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Bs}from"fs/promises";import{join as Ys}from"path";async function xe(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 Wn(e){let t;try{t=await Bs(Ys(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 Ws(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 zs(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&&Ws(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 Re(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,...zs(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 zn="https://api.cloudflare.com/client/v4";function qn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ve(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${zn}/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})`:""}. ${qn(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(`${zn}/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:qn(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 Oe(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 qs(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 Le(e){let t=ln(e);if(t)return{ok:!1,message:t};let n=de(e),i=n.value,o=r=>{let a=[r],l=cn(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(qs(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 Js}from"imapflow";function Xs(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function Jn(e,t,n){let i=t.toLowerCase(),o=e.filter(Xs);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 Xn(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:Zn(a,"SMTP",e.usesAccountPassword),failureKind:Xn(a)}}finally{t.close()}let n=new Js({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=Jn(a,e.sentFolder,"\\Sent")),e.draftsFolder&&(o=Jn(a,e.draftsFolder,"\\Drafts"))}catch{r=!0}await n.logout()}catch(a){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Zn(a,"IMAP",e.usesAccountPassword),failureKind:Xn(a)}}return{ok:!0,sentFolderIssue:i,draftsFolderIssue:o,foldersUnverified:r}}function Zn(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:
12
+ `}function yi(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=yi(s.slice(o+1).trim());t[r]=a}return t}function Tn(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:wn(e.AI_AGENT)??Ft,aiPlan:ot(e.AI_PLAN),qaPhase:rt(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:at(e),emailAuth:Pn(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:Mt(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:An(e.DEPLOY_PROVIDER)??Ht,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:En(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function ut(e){let t=_=>{let ce=e[_];if(!ce)return;let U=parseInt(ce,10);return isNaN(U)?void 0:U},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=An(e.DEPLOY_PROVIDER)??Ht,f=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,E=e.CLOUDFLARE_ACCOUNT_ID,d=e.NETLIFY_AUTH_TOKEN,b=e.SELFHOST_DEPLOY_TARGET,g=e.SELFHOST_URL_TEMPLATE;if(!a||!n||!s||!o||!r||!(c==="cloudflare"?!!u&&!!E:c==="netlify"?!!d:c==="selfhost"?!!b&&!!g:!!f))return null;let S=e.SMS_PROVIDER,x=_=>_==="email"||_==="sms"||_==="whatsapp"||_==="letter",Y=e.OUTREACH_CHANNELS?.split(",").map(_=>_.trim()).filter(x),le=e.OUTREACH_PRIORITY?.split(",").map(_=>_.trim()).filter(x),v=e.WHATSAPP_ACCOUNTS?.split(",").map(_=>_.trim()).filter(_=>_.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:wn(e.AI_AGENT)??Ft,aiPlan:ot(e.AI_PLAN),qaPhase:rt(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:Y&&Y.length>0?Y:void 0,outreachPriority:le&&le.length>0?le:void 0,whatsappAccounts:v&&v.length>0?v:void 0,emailProvider:at(e),emailAuth:Pn(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:Mt(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:E||void 0,netlifyAuthToken:d||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:b||void 0,selfhostUrlTemplate:g||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:En(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Ia,mkdir as Ca,readdir as _i,stat as xa}from"fs/promises";import{dirname as va,join as Ln,relative as Ti,sep as Ii}from"path";import{fileURLToPath as La}from"url";import{createHash as In}from"crypto";import{readFile as ki}from"fs/promises";async function Ie(e){let t=await ki(e);return In("sha256").update(t).digest("hex")}function jt(e){return In("sha256").update(e).digest("hex")}import{mkdir as wi,readFile as Ai,writeFile as Ei,access as Pi}from"fs/promises";import{dirname as Si,join as Cn}from"path";var bi=".klaudius",xn=`${bi}/manifest.json`,pt=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json"]),Rn=new Set(["clients/README.md"]),ft=new Set(["package-lock.json"]);async function vn(e){let t=Cn(e,xn);try{await Pi(t)}catch{return null}let n=await Ai(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 Be(e,t){let n=Cn(e,xn);await wi(Si(n),{recursive:!0}),await Ei(n,JSON.stringify(t,null,2)+`
14
+ `,"utf-8")}function On(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 _i(e,{withFileTypes:!0}),s=[];for(let o of n){let r=Ln(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await ge(r,t)):o.isFile()&&s.push(Ti(t,r).split(Ii).join("/")))}return s}async function $n(e){let t=await ge(e),n={};for(let s of t)pt.has(s)||(n[s]=await Ie(Ln(e,s)));return n}import{copyFile as Ci,mkdir as Nn,mkdtemp as xi,readdir as Dn,rm as Mn}from"fs/promises";import{tmpdir as Ri}from"os";import{dirname as vi,join as ht}from"path";import{Readable as Oi}from"stream";import*as Fn from"tar";var Li="https://klaudius.dev/api/template";function $i(e){return Oi.fromWeb(e)}async function mt(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Li,n="0.34.0",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: ${I(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 xi(ht(Ri(),"klaudius-template-")),a=0;try{try{await new Promise((f,u)=>{let E=Fn.extract({cwd:r,strict:!0});E.on("finish",f),E.on("error",u),$i(s.body).on("error",u).pipe(E)})}catch(f){throw new Error(`Failed to extract template archive: ${f.message}`)}await Nn(e.destDir,{recursive:!0});let l=new Set(await Dn(e.destDir)),c=await ge(r);try{for(let f of c){let u=ht(e.destDir,f);await Nn(vi(u),{recursive:!0}),await Ci(ht(r,f),u),a++}}catch(f){let u=await Dn(e.destDir).catch(()=>[]);for(let E of u)l.has(E)||await Mn(ht(e.destDir,E),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${f.message}`)}}finally{await Mn(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:a,tier:o}}import{copyFile as Ni,mkdir as Di,readFile as Un,rm as Mi}from"fs/promises";import{dirname as Fi,join as ye}from"path";import{structuredPatch as Ui}from"diff";var Hn=ye(".klaudius","base"),gt=ye(".klaudius","conflict-base");async function yt(e,t,n){let s=ye(e,Hn);await Mi(s,{recursive:!0,force:!0});for(let o of n){let r=ye(s,o);await Di(Fi(r),{recursive:!0}),await Ni(ye(t,o),r)}}async function jn(e,t){try{return await Un(ye(e,Hn,t),"utf-8")}catch{return null}}async function Kn(e,t){try{return await Un(ye(e,gt,t),"utf-8")}catch{return null}}function Gn(e,t,n,s){return Ce(n)?null:e!==null&&!Ce(e)&&(!s||jt(e)===s)?e:t!==null&&!Ce(t)&&s&&jt(t)===s?t:null}function Ce(e){return e.includes("\0")||e.includes("\uFFFD")}function Bn(e,t,n=60){let s=Ui("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 Hi="https://registry.npmjs.org/klaudius/latest";async function ji(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Hi,{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 Ki(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 kt(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await ji();!n||!Ki(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 Gi}from"crypto";import{hostname as Vn,userInfo as Bi,platform as Yn,arch as Wn}from"os";var Vi="https://klaudius.dev",Yi="/api/licenses/validate",Wi="0.34.0";async function qn(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??Vi).replace(/\/$/,"")+Yi,o=Ve(),r;try{r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Vn(),os:`${Yn()}-${Wn()}`,cli_version:Wi})})}catch(l){return{ok:!1,reason:`Could not reach the Klaudius license server (${I(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 Ve(){let e=[Vn(),Bi().username,Yn(),Wn()].join("|");return Gi("sha256").update(e).digest("hex").slice(0,32)}import{readFile as qi}from"fs/promises";import{join as zi}from"path";async function xe(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: ${I(n)}`}}}function zn(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function wt(e){let t;try{t=await qi(zi(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{ok:!1,message:Xi(s.status,o)}}catch(s){return{ok:!1,message:`Schema apply failed: ${I(s)}`}}}function Qi(e){let t=[...e.matchAll(/ALTER TABLE clients ADD COLUMN IF NOT EXISTS (\w+)/g)].map(s=>s[1]),n=[...e.matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/g)].map(s=>s[1]);return{clientsColumns:[...new Set(t)],tables:[...new Set(n)]}}function Ji(e,t){let n="";try{let o=JSON.parse(t);o&&typeof o.code=="string"&&(n=o.code)}catch{}return{missing:e===400&&n==="42703"||e===404&&(n==="PGRST205"||n==="42P01"),code:n}}async function At(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{clientsColumns:s,tables:o}=Qi(e.sql),r=[];s.length>0&&r.push({path:`clients?select=${s.join(",")}&limit=0`,label:"clients columns"});for(let l of o)l!=="clients"&&r.push({path:`${l}?select=*&limit=0`,label:`${l} table`});let a=[];try{for(let l of r){let c=await fetch(`${t}/rest/v1/${l.path}`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(c.ok)continue;let f=Ji(c.status,await c.text());if(f.missing){a.push(l.label);continue}return{ok:!1,missing:a,unreachable:`HTTP ${c.status}${f.code?` ${f.code}`:""}`}}}catch(l){return{ok:!1,missing:a,unreachable:I(l)}}return{ok:a.length===0,missing:a}}function Xi(e,t){let n=t;try{let s=JSON.parse(t);s&&typeof s.message=="string"&&(n=s.message)}catch{}return n=n.replace(/\s+/g," ").trim().slice(0,300),e===401?"Supabase rejected the access token (HTTP 401) \u2014 SUPABASE_PAT in .env is invalid, expired or revoked. Create a new token at https://supabase.com/dashboard/account/tokens and run `npx klaudius@latest configure`.":e===403?"The Supabase access token doesn't cover this project (HTTP 403) \u2014 it was scoped to a different organisation or project. Create a token that includes this project at https://supabase.com/dashboard/account/tokens and run `npx klaudius@latest configure`.":e===429?"Supabase rate-limited the request (HTTP 429). Wait a minute and try again.":`Supabase Management API rejected the schema (HTTP ${e}): ${n}`}function Zi(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 eo(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&&Zi(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 Re(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let s=await t.text().catch(()=>"");return{ok:!1,...eo(t.status,s)}}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: ${I(t)}`}}}var Qn="https://api.cloudflare.com/client/v4";function Jn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ve(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${Qn}/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})`:""}. ${Jn(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}try{let o=await fetch(`${Qn}/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:Jn(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: ${I(o)}`}}}var Xn="https://api.netlify.com/api/v1";async function Oe(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${Xn}/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: ${I(s)}`}}try{let s=await fetch(`${Xn}/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: ${I(s)}`}}}function to(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 Le(e){let t=dn(e);if(t)return{ok:!1,message:t};let n=de(e),s=n.value,o=r=>{let a=[r],l=un(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(to(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: ${I(r)}`}}}import no from"nodemailer";import{ImapFlow as so}from"imapflow";function io(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function Zn(e,t,n){let s=t.toLowerCase(),o=e.filter(io);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 es(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=no.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:ts(a,"SMTP",e.usesAccountPassword),failureKind:es(a)}}finally{t.close()}let n=new so({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=Zn(a,e.sentFolder,"\\Sent")),e.draftsFolder&&(o=Zn(a,e.draftsFolder,"\\Drafts"))}catch{r=!0}await n.logout()}catch(a){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:ts(a,"IMAP",e.usesAccountPassword),failureKind:es(a)}}return{ok:!0,sentFolderIssue:s,draftsFolderIssue:o,foldersUnverified:r}}function ts(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:
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,109 +23,109 @@ import{b as we,c as Je,d as X,e as x,f as rn,g as an,h as Xe,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: ${i}`}import*as kt from"@clack/prompts";var Zs=[{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 i=!1;for(let o of Zs){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 kt.confirm({message:`Use "${r.detected}" instead?`,initialValue:!0});if(kt.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 ei(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 At(e){return e.provider==="pingen"?eo(e):to(e)}async function eo(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 to(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 no}from"child_process";async function ti(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 io(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 io(e){return new Promise(t=>{let n=no("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 Et}from"child_process";import{existsSync as so}from"fs";import{homedir as oo}from"os";function ro(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var $e=2,ni=2e3,ao=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function ii(e,t){let n=e+`
27
- `+t;return ao.some(i=>i.test(n))}function si(e){return new Promise(t=>setTimeout(t,e))}function lo(e,t,n){return new Promise(i=>{let o=n.shell?Et([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):Et(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 Ut(e,t,n){let i={code:0,stdout:"",stderr:""};for(let o=0;o<=$e;o++){if(i=await lo(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!ii(i.stderr,i.stdout))return i;o<$e&&(s.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${$e+1})\u2026`),await si(ni))}return i}function co(e,t,n){return new Promise(i=>{let o=Et(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 uo=[{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 po(e){let t=`${e.stderr??""}
28
- ${e.stdout??""}`;return uo.find(i=>i.pattern.test(t))?.hint}async function fo(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<=$e;f++){if(c=await co(o[0],[...o.slice(1),...l],{cwd:e}),c.code===0||!ii(c.stderr,c.stdout))return c;f<$e&&(s.detail(`pip install hit a transient network error \u2014 retrying (${f+2}/${$e+1})\u2026`),await si(ni))}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 Pt(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=ro(),i=process.platform==="win32",o;if(i){let u=Se([{label:"your Windows user folder",path:oo()},{label:"the project folder",path:e}]);if(u.length>0){let A=await new Promise(b=>{let g=Et("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(!be(d,so)){let{detail:b,action:g}=_e(u,"install");o=`${b}. ${g}`}}}let r=(u,A)=>{let d=po(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 Ut("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 fo(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 Ut("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 Ut("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 ho,access as mo}from"fs/promises";import{dirname as go,join as yo}from"path";async function oi(){let e=await nt("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 jt(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await oi();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 ko(e){let[t,...n]=e.command,i=await nt(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=yo(go(o),"python3.exe"),a=await mo(r).then(()=>!0,()=>!1);if(!a){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await ho(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let l=await oi();return{ok:!0,target:r,created:!a,verified:l.state==="real",postState:l.state==="real"?void 0:l.state}}var wo="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 St(){let e=await jt();if(e.status!=="broken")return;let t=await ko(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(wo);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 Ao,spawnSync as ri}from"child_process";import{mkdtemp as Eo,rm as Po,rmdir as So,writeFile as bo,stat as Kt,unlink as _o,mkdir as To}from"fs/promises";import{createServer as Io}from"net";import{tmpdir as Co}from"os";import{join as Ne}from"path";function xo(){return new Promise((e,t)=>{let n=Io();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 bt(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?ri(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):ri("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function _t(e){try{return await Ro(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Ro(e){let t=`klaudius-smoke-${process.pid}`,n=Ne(".klaudius",`qa-smoke-${process.pid}.png`),i=Ne(e,n),o,r,a=!1;try{o=await Eo(Ne(Co(),"klaudius-qa-smoke-")),await bo(Ne(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let l=await xo();r=Ao("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=Ne(e,".klaudius"),d=await Kt(A).then(()=>!0,()=>!1);await To(A,{recursive:!0}),a=!d;let b=bt(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=bt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await Kt(i).catch(()=>null);if((!k||k.size===0)&&(g=bt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await Kt(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{bt(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await _o(i).catch(()=>{}),a&&await So(Ne(e,".klaudius")).catch(()=>{}),o&&await Po(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as ai,readFile as vo,writeFile as li}from"fs/promises";import{join as Tt}from"path";var Me="Bash(claude --bg --permission-mode auto *)";async function ci(e){let t;try{t=await vo(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 De(e,t){let n=Tt(e,".claude"),i=Tt(n,"settings.local.json"),o=".claude/settings.local.json";try{await ai(n,{recursive:!0});let r=await ci(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 li(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 It(e,t){let n=Tt(e,".claude");await ai(n,{recursive:!0});let i=Tt(n,"settings.json"),o=await ci(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 li(i,JSON.stringify(l,null,2)+`
30
- `,"utf-8")}var di="0.33.0",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 Mo(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 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 ${Ct(Fe(e))}`}function Fe(e){if(process.platform==="win32")return e;let t=Oo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Do(e){let t=[];try{let i=(await pi(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 ui(Z(r,".env")))continue;let a=await ui(Z(r,".klaudius","manifest.json"));if(t.push({path:r,finished:a}),t.length>=3)break}}catch{}return t}async function ui(e){try{return await Yt(e),!0}catch{return!1}}function Ct(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 ${Fe(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 fi(e){let t=e.target??".",n=$o(t)?t:Lo(process.cwd(),t),i=jo(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"&&Ko()&&(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 yt("init",di);let o=await Fo(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 ${Ct(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 Do(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: ${Fe(n)}`),s.blank();for(let m of y)s.detail(m.finished?`Found a finished project at ${Fe(m.path)}. To work in it:`:`Found an unfinished setup at ${Fe(m.path)}. To pick up where it left off:`),s.blank(),m.finished?(console.log(` ${h.cyan(`cd ${Fe(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 Mo(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 Uo(a),c=P.spinner();c.start("Validating license");let f=await Yn(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 Te();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 St();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=dt(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 Ho(n)==="resume"){let y=await Bt(o.envPath,"utf-8"),m=dt(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, on the smaller ChatGPT plans, the model).`}))):(s.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),d=await N())}else{let y=await Bt(o.envPath,"utf-8"),m=dt(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 xe({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}
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 Et from"@clack/prompts";var oo=[{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 Pt(e,t,n){let s=!1;for(let o of oo){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 Et.confirm({message:`Use "${r.detected}" instead?`,initialValue:!0});if(Et.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 ns(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: ${I(s)}`}}}async function St(e){return e.provider==="pingen"?ro(e):ao(e)}async function ro(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: ${I(s)}`}}}async function ao(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: ${I(t)}`}}}import{spawn as lo}from"child_process";async function ss(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 co(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 co(e){return new Promise(t=>{let n=lo("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 bt}from"child_process";import{existsSync as uo}from"fs";import{homedir as po}from"os";function fo(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var $e=2,is=2e3,ho=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function os(e,t){let n=e+`
27
+ `+t;return ho.some(s=>s.test(n))}function rs(e){return new Promise(t=>setTimeout(t,e))}function mo(e,t,n){return new Promise(s=>{let o=n.shell?bt([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):bt(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 Kt(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=$e;o++){if(s=await mo(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!os(s.stderr,s.stdout))return s;o<$e&&(i.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${$e+1})\u2026`),await rs(is))}return s}function go(e,t,n){return new Promise(s=>{let o=bt(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 yo=[{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 ko(e){let t=`${e.stderr??""}
28
+ ${e.stdout??""}`;return yo.find(s=>s.pattern.test(t))?.hint}async function wo(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<=$e;f++){if(c=await go(o[0],[...o.slice(1),...l],{cwd:e}),c.code===0||!os(c.stderr,c.stdout))return c;f<$e&&(i.detail(`pip install hit a transient network error \u2014 retrying (${f+2}/${$e+1})\u2026`),await rs(is))}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 _t(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=fo(),s=process.platform==="win32",o;if(s){let u=Se([{label:"your Windows user folder",path:po()},{label:"the project folder",path:e}]);if(u.length>0){let E=await new Promise(b=>{let g=bt("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),k="",S="";g.stdout?.on("data",x=>{k+=x.toString()}),g.stderr?.on("data",x=>{S+=x.toString()}),g.on("close",x=>b({code:x??1,stdout:k,stderr:S})),g.on("error",x=>b({code:1,stdout:k,stderr:x.message}))}),d=E.code===0?E.stdout.trim():void 0;if(!be(d,uo)){let{detail:b,action:g}=_e(u,"install");o=`${b}. ${g}`}}}let r=(u,E)=>{let d=ko(E);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 Kt("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 wo(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 Kt("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 Kt("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 Ao,access as Eo}from"fs/promises";import{dirname as Po,join as So}from"path";async function as(){let e=await st("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 Gt(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await as();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 bo(e){let[t,...n]=e.command,s=await st(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=So(Po(o),"python3.exe"),a=await Eo(r).then(()=>!0,()=>!1);if(!a){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await Ao(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let l=await as();return{ok:!0,target:r,created:!a,verified:l.state==="real",postState:l.state==="real"?void 0:l.state}}var _o="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 Tt(){let e=await Gt();if(e.status!=="broken")return;let t=await bo(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(_o);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 To,spawnSync as ls}from"child_process";import{mkdtemp as Io,rm as Co,rmdir as xo,writeFile as Ro,stat as Bt,unlink as vo,mkdir as Oo}from"fs/promises";import{createServer as Lo}from"net";import{tmpdir as $o}from"os";import{join as Ne}from"path";function No(){return new Promise((e,t)=>{let n=Lo();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 It(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?ls(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):ls("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function Ct(e){try{return await Do(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Do(e){let t=`klaudius-smoke-${process.pid}`,n=Ne(".klaudius",`qa-smoke-${process.pid}.png`),s=Ne(e,n),o,r,a=!1;try{o=await Io(Ne($o(),"klaudius-qa-smoke-")),await Ro(Ne(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let l=await No();r=To("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(x=>setTimeout(x,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 E=Ne(e,".klaudius"),d=await Bt(E).then(()=>!0,()=>!1);await Oo(E,{recursive:!0}),a=!d;let b=It(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=It(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await Bt(s).catch(()=>null);if((!k||k.size===0)&&(g=It(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await Bt(s).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{It(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await vo(s).catch(()=>{}),a&&await xo(Ne(e,".klaudius")).catch(()=>{}),o&&await Co(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as cs,readFile as Mo,writeFile as ds}from"fs/promises";import{join as xt}from"path";var De="Bash(claude --bg --permission-mode auto *)";async function us(e){let t;try{t=await Mo(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 Me(e,t){let n=xt(e,".claude"),s=xt(n,"settings.local.json"),o=".claude/settings.local.json";try{await cs(n,{recursive:!0});let r=await us(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 ds(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 Rt(e,t){let n=xt(e,".claude");await cs(n,{recursive:!0});let s=xt(n,"settings.json"),o=await us(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 ds(s,JSON.stringify(l,null,2)+`
30
+ `,"utf-8")}var ps="0.34.0",$=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 Ko(e){let t;try{t=await Wt(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 ${vt(Fe(e))}`}function Fe(e){if(process.platform==="win32")return e;let t=Fo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Go(e){let t=[];try{let s=(await hs(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let r=Z(e,o.name);if(!await fs(Z(r,".env")))continue;let a=await fs(Z(r,".klaudius","manifest.json"));if(t.push({path:r,finished:a}),t.length>=3)break}}catch{}return t}async function fs(e){try{return await qt(e),!0}catch{return!1}}function vt(e){return/\s/.test(e)?`"${e}"`:e}function te(e,t,n){i.blank(),i.error(`${t} validation failed ${$} 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(` ${m.cyan(re(e))}`),i.blank(),i.detail(` (Your .env is at ${Fe(Z(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 ms(e){let t=e.target??".",n=Ho(t)?t:Uo(process.cwd(),t),s=Wo(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(` ${m.cyan("cd $HOME\\Documents")}`),console.log(` ${m.cyan("npx klaudius@latest init my-agency")}`)):(i.detail("For example:"),console.log(` ${m.cyan("cd ~/Documents")}`),console.log(` ${m.cyan("npx klaudius@latest init my-agency")}`)),i.blank(),process.exit(1)),process.platform==="win32"&&qo()&&(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 kt("init",ps);let o=await Bo(n);if(o.kind==="scaffolded"){i.blank(),i.warn(`Found an existing Klaudius project at ${m.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(` ${m.cyan(`cd ${vt(t)}`)}`),console.log(` ${m.cyan("npx klaudius@latest install")} ${m.dim("# retries npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${m.cyan("npx klaudius@latest doctor")} ${m.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(` ${m.cyan("npx klaudius@latest doctor")} ${m.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${m.cyan("npx klaudius@latest configure")} ${m.dim("# change a credential / API key")}`),console.log(` ${m.cyan("npx klaudius@latest update")} ${m.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===".",y=await Go(n);if(y.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: ${Fe(n)}`),i.blank();for(let h of y)i.detail(h.finished?`Found a finished project at ${Fe(h.path)}. To work in it:`:`Found an unfinished setup at ${Fe(h.path)}. To pick up where it left off:`),i.blank(),h.finished?(console.log(` ${m.cyan(`cd ${Fe(h.path)}`)}`),console.log(` ${m.cyan("claude")} ${m.dim("# open Claude Code in the project")}`)):console.log(` ${m.cyan(re(h.path))} ${m.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(` ${m.cyan("npx klaudius@latest init my-agency")}`),i.blank(),i.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${m.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(` ${m.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 Ko(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 Yo(a),c=P.spinner();c.start("Validating license");let f=await qn(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 Te();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 Tt();let E=ue();E.ok||(i.error(E.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,b=!1;if(r){let p=ut(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 Vo(n)==="resume"){let y=await Wt(o.envPath,"utf-8"),h=ut(G(y));h?(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=h,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, on the smaller ChatGPT plans, the model).`}))):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),d=await N())}else{let y=await Wt(o.envPath,"utf-8"),h=ut(G(y));d=await N(h??{})}else d=await N();d.licenseKey=l,await D(n,d),b||(i.success("Saved .env"),i.success(d.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let p=1;;p++){let y=P.spinner();y.start("Validating Supabase credentials");let h=await xe({url:d.supabaseUrl,serviceKey:d.supabaseServiceKey});if(h.ok){y.stop("Supabase credentials accepted");break}y.stop(h.message??"Supabase check failed",2),p>=$&&te(n,"Supabase",h.message??"Supabase check failed");let A=h.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 ${$})`),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}
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(s.blank(),d.deployProvider==="cloudflare")for(let p=1;;p++){let y=P.spinner();y.start("Validating Cloudflare token + account");let m=await ve({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}
35
+ field to keep what's already there.`}),await D(n,d)}if(i.blank(),d.deployProvider==="cloudflare")for(let p=1;;p++){let y=P.spinner();y.start("Validating Cloudflare token + account");let h=await ve({token:d.cloudflareApiToken??"",accountId:d.cloudflareAccountId??""});if(h.ok){y.stop(`Cloudflare credentials accepted (${h.projectCount??0} existing Pages project${h.projectCount===1?"":"s"})`);break}y.stop(h.message??"Cloudflare check failed",2),p>=$&&te(n,"Cloudflare",h.message??"Cloudflare check failed");let A=h.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 ${$})`),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}
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 y=P.spinner();y.start("Validating Netlify token");let m=await Oe({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}
40
+ the current value.`}),await D(n,d)}else if(d.deployProvider==="netlify")for(let p=1;;p++){let y=P.spinner();y.start("Validating Netlify token");let h=await Oe({token:d.netlifyAuthToken??""});if(h.ok){y.stop(h.accountSlug?`Netlify token accepted (team: ${h.accountSlug})`:"Netlify token accepted");break}y.stop(h.message??"Netlify check failed",2),p>=$&&te(n,"Netlify",h.message??"Netlify check failed");let A=h.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 ${$})`),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}
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 y=Xe(d.selfhostDeployTarget??""),m=Ze(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}
45
+ and paste it below. Press Enter to keep the current value.`}),await D(n,d)}else if(d.deployProvider==="selfhost")for(let p=1;;p++){let y=Ze(d.selfhostDeployTarget??""),h=et(d.selfhostUrlTemplate??"");if(!y&&!h){i.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let A=[y&&`SELFHOST_DEPLOY_TARGET: ${y}`,h&&`SELFHOST_URL_TEMPLATE: ${h}`].filter(Boolean).join(`
46
+ `);p>=$&&te(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 ${$})`),i.blank(),d=await N(d,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
47
+ ${A}
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 y=P.spinner();y.start("Validating Vercel token");let m=await Re(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}
49
+ Re-enter them below. Press Enter on a field to keep its current value.`}),await D(n,d)}else for(let p=1;;p++){let y=P.spinner();y.start("Validating Vercel token");let h=await Re(d.vercelToken??"");if(h.ok){y.stop(h.username?`Vercel token accepted (signed in as ${h.username})`:"Vercel token accepted");break}y.stop(h.message,2);let A=h.message,T=h.kind==="rejected"||h.kind==="scope",C=T?`${A} Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration).`:A;p>=$&&te(n,"Vercel",C),i.blank(),F&&H("vercel",C),i.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${p+1} of ${$})`),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:T?`${A}
50
50
 
51
51
  Create a new token at https://vercel.com/account/settings/tokens
52
52
  (Scope: Full Account, Expiration: No Expiration) and paste it
53
- below. Press Enter to keep the current value.`:`${E}
53
+ below. Press Enter to keep the current value.`:`${A}
54
54
 
55
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 Le(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:
56
+ different token.`}),await D(n,d)}i.blank();for(let p=1;;p++){let y=de(d.googlePlacesApiKey??""),h=P.spinner();h.start("Validating Google Places API key");let A=await Le(d.googlePlacesApiKey??"");if(A.ok){if(h.stop("Google Places API key accepted"),y.changed){if(y.repairs.length>0){i.blank(),i.warn("Corrected look-alike characters in your Google Places API key:");for(let C of y.repairs)i.detail(` ${C}`);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=y.value,await D(n,d)}break}h.stop(A.message??"Google Places check failed",2),p>=$&&te(n,"Google Places",A.message??"Google Places check failed");let T=A.message??"Google Places check failed";i.blank(),F&&H("google-places",T),i.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${p+1} of ${$})`),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:
57
57
  ${T}
58
58
 
59
59
  Generate (or fix) the key at https://console.cloud.google.com
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 wt(D,d,{nonInteractive:F,onCancel:()=>{P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
60
+ and paste it below. Press Enter to keep the current value.`}),await D(n,d)}let g=!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,y=!1,h;for(;!y;){p++;let A=P.spinner();A.start("Validating email credentials (SMTP + IMAP)");let T=d.emailProvider&&d.emailProvider!=="custom"?d.emailProvider:we(d.emailSmtpHost),C=T?X[T]:void 0,M=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:C?.usesAccountPassword,sentFolder:(d.emailSentFolder??"").trim()||"Sent",draftsFolder:(d.emailDraftsFolder??"").trim()||"Drafts"});if(M.ok){A.stop("Email credentials accepted (SMTP + IMAP)"),await Pt(M,d,{nonInteractive:F,onCancel:()=>{P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
61
61
 
62
62
  ${re(n)}
63
- `),process.exit(0)}})&&await M(n,d);break}E.stop(D.message??"Email check failed",2);let Qe=`${T}\0${d.emailAddress}\0${d.emailPassword}`;if(I&&D.failureKind!=="network"&&m!==Qe){m=Qe;let me=Je(T,d.emailSmtpHost,d.emailImapHost),ee,on=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 Lt=P.spinner();Lt.start(`Trying ${Q.label} (${Q.smtpHost})`);let $t=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($t.ok){Lt.stop(`${Q.label}: your login works here (${Q.smtpHost})`),ee=Q;break}$t.failureKind!=="network"&&on++,Lt.stop($t.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:
63
+ `),process.exit(0)}})&&await D(n,d);break}A.stop(M.message??"Email check failed",2);let Je=`${T}\0${d.emailAddress}\0${d.emailPassword}`;if(C&&M.failureKind!=="network"&&h!==Je){h=Je;let me=Xe(T,d.emailSmtpHost,d.emailImapHost),ee,an=0;if(me.length>0){i.blank(),i.warn(`That server rejected the login. ${C.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let Q of me){let Nt=P.spinner();Nt.start(`Trying ${Q.label} (${Q.smtpHost})`);let Dt=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(Dt.ok){Nt.stop(`${Q.label}: your login works here (${Q.smtpHost})`),ee=Q;break}Dt.failureKind!=="network"&&an++,Nt.stop(Dt.failureKind==="network"?`${Q.label}: unreachable`:`${Q.label}: rejected too`,2)}}if(ee){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 ${ee.label} servers automatically.`),d.emailSmtpHost=ee.smtpHost,d.emailImapHost=ee.imapHost,await D(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:
64
64
 
65
65
  ${re(n)}
66
- `),process.exit(0)),Q){d.emailSmtpHost=ee.smtpHost,d.emailImapHost=ee.imapHost,await M(n,d);continue}}else me.length>0&&(s.blank(),on===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 sn=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",sn);let Ot=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(Ot)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
66
+ `),process.exit(0)),Q){d.emailSmtpHost=ee.smtpHost,d.emailImapHost=ee.imapHost,await D(n,d);continue}}else me.length>0&&(i.blank(),an===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."):C.noAltWorkedHint&&i.warn(C.noAltWorkedHint))}let rn=M.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",rn);let $t=await P.select({message:`What would you like to do? ${m.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($t)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
67
67
 
68
68
  ${re(n)}
69
- `),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),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}Ot==="edit"&&(s.blank(),d=await N(d,{onlySection:"email",banner:`${D.failedAt==="imap"?"IMAP":"SMTP"} check failed:
70
- ${sn}
69
+ `),process.exit(0)),$t==="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 D(n,d),g=!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."),y=!0;break}$t==="edit"&&(i.blank(),d=await N(d,{onlySection:"email",banner:`${M.failedAt==="imap"?"IMAP":"SMTP"} check failed:
70
+ ${rn}
71
71
 
72
72
  Re-enter the email address, app password, or server details below.
73
73
  Press Enter on any field to keep its current value.
74
74
 
75
75
  Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
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 ei({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}
76
+ at the "Server settings" question.`}),await D(n,d))}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="twilio"&&d.twilioAccountSid&&d.twilioAuthToken){i.blank();for(let p=1;;p++){let y=P.spinner();y.start("Validating Twilio credentials");let h=await ns({accountSid:d.twilioAccountSid,authToken:d.twilioAuthToken});if(h.ok){y.stop(h.friendlyName?`Twilio credentials accepted (${h.friendlyName})`:"Twilio credentials accepted");break}y.stop(h.message??"Twilio check failed",2),p>=$&&te(n,"Twilio",h.message??"Twilio check failed");let A=h.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 ${$})`),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:
77
+ ${A}
78
78
 
79
79
  Re-enter the Account SID or Auth Token below.
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 At({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}
80
+ Press Enter on any field to keep its current value.`}),await D(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("letter")&&d.letterProvider){i.blank();for(let p=1;;p++){let y=P.spinner();y.start("Validating letter provider credentials");let h=await St({provider:d.letterProvider,pingenClientId:d.pingenClientId,pingenClientSecret:d.pingenClientSecret,pingenOrgId:d.pingenOrgId,postgridApiKey:d.postgridApiKey});if(h.ok){y.stop(h.friendlyName?`Letter provider credentials accepted (${h.friendlyName})`:"Letter provider credentials accepted");break}y.stop(h.message??"Letter provider check failed",2),p>=$&&te(n,"Letter provider",h.message??"Letter provider check failed");let A=h.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 ${$})`),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:
81
+ ${A}
82
82
 
83
83
  Re-enter them below.
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 ti({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:
84
+ Press Enter on any field to keep its current value.`}),await D(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="imessage"&&d.testPhone){i.blank();for(let p=1;;p++){let y=P.spinner();y.start("Validating iMessage setup (sending a test ping)");let h=await ss({testPhone:d.testPhone});if(h.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:
85
85
 
86
86
  ${re(n)}
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.
87
+ `),process.exit(0)),T)break;y.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),p>=$&&te(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.
88
88
  Re-check the number below (international format with a leading +).
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}
89
+ Press Enter on any field to keep its current value.`}),await D(n,d);continue}y.stop(h.message??"iMessage check failed",2),p>=$&&te(n,"iMessage",h.message??"iMessage check failed");let A=h.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 ${$})`),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:
90
+ ${A}
91
91
 
92
92
  Either fix the underlying issue (sign in to Messages.app, configure
93
93
  Text Message Forwarding) and press Enter through, or change SMS
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 an({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:
94
+ provider to Twilio.`}),await D(n,d)}}if((d.notifyChannel??"telegram")==="telegram"&&d.telegramBotToken&&d.telegramChatId){i.blank();let p=0,y=!1;for(;!y;){p++;let h=P.spinner();h.start("Validating Telegram bot + chat (sending a test ping)");let A=await cn({botToken:d.telegramBotToken,chatId:d.telegramChatId});if(A.ok){h.stop(A.botHandle?`Telegram bot ${A.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),y=!0;break}h.stop(A.message??"Telegram check failed",2);let T=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",T);let C=await P.select({message:`What would you like to do? ${m.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(C)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
95
95
 
96
96
  ${re(n)}
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:
97
+ `),process.exit(0)),C==="skip"){d.telegramBotToken=void 0,d.telegramChatId=void 0,await D(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`."),y=!0;break}if(C==="edit"&&(i.blank(),d=await N(d,{onlySection:"notifications",banner:`Telegram check failed:
98
98
  ${T}
99
99
 
100
100
  Re-enter the bot token or chat_id below.
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 ht({licenseKey:l,machineId:Ve(),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 Vt(Z(n,"clients"),{recursive:!0});let C=await On(n);await Ge(n,Rn(di,C)),s.success("Wrote .klaudius/manifest.json");try{await gt(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 Wn({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 Pt(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 _t(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
101
+ Press Enter on any field to keep its current value.`}),await D(n,d),(d.notifyChannel??"telegram")!=="telegram"||!d.telegramBotToken||!d.telegramChatId)){i.success("Skipped Telegram. Setup will continue."),y=!0;break}}}i.blank();let k=P.spinner();k.start("Downloading Klaudius template");let S;try{S=(await mt({licenseKey:l,machineId:Ve(),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 ${m.bold(n)}`)}catch(p){k.stop(p.message,2);let y=d.aiAgent==="codex"?".codex/config.toml":".mcp.json";i.detail(`Your .env / ${y} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await Yt(Z(n,"clients"),{recursive:!0});let x=await $n(n);await Be(n,On(ps,x)),i.success("Wrote .klaudius/manifest.json");try{await yt(n,n,Object.keys(x))}catch{}let Y=!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=P.spinner();p.start("Applying schema to Supabase");let y=await wt({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),Y=!0,le=`https://supabase.com/dashboard/project/${d.supabaseProjectRef}/sql/new`)}let v=[],_={};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 _t(n);if(i.detail(`npm: ${p.npm}, pip: ${p.pip}, playwright: ${p.playwright}, patchright: ${p.patchright}`),p.npm==="failed"&&v.push("npm"),p.pip==="failed"&&v.push("pip"),p.playwright==="failed"&&v.push("playwright"),p.patchright==="failed"&&v.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 y=await Ct(n);y.ok?i.success("QA screenshot chain verified (local page served and screenshotted)."):(i.warn(`QA screenshot chain check failed${y.stage?` (${y.stage})`:""}: ${y.detail??"unknown"}`),y.remediation&&i.detail(y.remediation))}}let ce=d.outreachEnabled&&d.outreachPriority?.includes("whatsapp")&&(d.whatsappAccounts?.length??0)>0,U=!e.skipInstall&&!v.includes("npm");if(ce&&U){i.blank(),i.heading("Linking WhatsApp accounts"),console.log(m.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
102
102
  phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
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=Wt(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"),je=!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&&je){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
103
+ Link a Device, and point it at the QR shown in this terminal.`)),i.blank();for(let p of d.whatsappAccounts){console.log(m.cyan(`Pairing WhatsApp account '${p}'...`)),console.log(m.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${p})`));let y=zt(process.execPath,["scripts/whatsapp.mjs","pair","--account",p],{cwd:n,stdio:"inherit"});y.status===0?i.detail(`Paired '${p}'.`):(console.log(m.yellow(`'${p}' did not pair (exit ${y.status??"signalled"}). You can finish later via:`)),console.log(m.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))),i.blank()}}else if(ce&&!U){i.blank(),console.log(m.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(m.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let p of d.whatsappAccounts)console.log(m.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))}let ke=d.emailAuth==="oauth-microsoft"&&d.outreachEnabled&&d.outreachChannels?.includes("email"),Ke=!e.skipInstall&&!v.includes("pip"),w=p=>{console.log(m.dim("Connect it any time from the project folder with:")),console.log(m.cyan(` ${p?p.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(m.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(ke&&Ke){i.blank(),i.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(m.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
104
104
  password. Your browser will open to Microsoft's sign-in page \u2014
105
105
  sign in as `+(d.emailAddress??"your outreach mailbox")+` and approve.
106
106
  (No browser on this machine? It falls back to a short code you can
107
- enter from any device.)`)),s.blank();let p=await K();if(p){let[y,...m]=p.command,E=Wt(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&&!je&&(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,Qe]of Object.entries(_))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${Qe}`)),s.blank();let p=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${Ct(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 ${Go()}`)),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(Vo(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 Vt(e,{recursive:!0}),await Gt(Z(e,".env"),at(t),"utf-8"),t.aiAgent==="codex"?(await Vt(Z(e,".codex"),{recursive:!0}),await Gt(Z(e,".codex","config.toml"),ct(t),"utf-8")):(await Gt(Z(e,".mcp.json"),lt(t),"utf-8"),await It(e,"supabase"),await De(e,Me))}async function Fo(e){try{(await Yt(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await pi(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 Yt(Z(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Ho(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 Uo(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 jo(e){let t=No(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 Ko(){if(process.platform!=="win32")return!1;try{return Wt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Go(){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 Vo(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??Ee(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${Pe[e.aiPlan]}`),console.log(h.dim(r?` \u2192 QA pass off${Ae.has(e.aiPlan)&&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 ${Ct(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 Bo,readFile as Yo}from"fs/promises";import{join as zt,resolve as Wo}from"path";import Y from"picocolors";async function mi(e){let t=e.target?Wo(process.cwd(),e.target):process.cwd(),n=await hi(zt(t,".env")),i=await hi(zt(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 Yo(zt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}s.heading("Installing dependencies");let r=await Pt(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 hi(e){try{return await Bo(e),!0}catch{return!1}}import{readFile as zo,writeFile as qt,access as qo}from"fs/promises";import{join as He}from"path";import*as W from"@clack/prompts";import ae from"picocolors";import{mkdir as Qo}from"fs/promises";import{spawnSync as gi}from"child_process";async function yi(e){let t=e.projectRoot??process.cwd(),n=He(t,".env"),i=He(t,".mcp.json"),o=He(t,".codex","config.toml"),r=await Qt(He(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 zo(n,"utf-8");c=G(g)}catch{s.warn("No .env found. Starting from an empty configuration.")}let f=bn(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 xe({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=Xo(u,c);if(d==="vercel"){let g=W.spinner();g.start("Validating Vercel token");let k=await Re(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 ve({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 Oe({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 Le(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(Jo(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 wt(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 qt(n,at(u),"utf-8"),s.success("Updated .env"),u.aiAgent==="codex"?(await Qo(He(t,".codex"),{recursive:!0}),await qt(o,ct(u),"utf-8"),s.success("Updated .codex/config.toml")):(await qt(i,lt(u),"utf-8"),s.success("Updated .mcp.json"),await It(t,"supabase"),await De(t,Me)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let g=await K();if(!(g!==null&&gi(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`):gi(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 Zo(t,r)}function Jo(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 Xo(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 Zo(e,t){let n=await Qt(He(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 qo(e),!0}catch{return!1}}import{copyFile as ki,mkdir as Jt,readFile as xt,rm as fe,writeFile as Rt,access as wi}from"fs/promises";import{dirname as Xt,join as $}from"path";import{tmpdir as er}from"os";import*as he from"@clack/prompts";import Be from"picocolors";var Ye="0.33.0";async function Ai(e){let t=e.projectRoot??process.cwd(),n=await xn(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 ut)delete n.files[w];let i,o=$(t,".env"),r,a;try{r=await xt(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:Sn(r,a,Pn);l!==null&&(await Rt(o,l,"utf-8"),s.detail("Backfilled new env keys")),await yt("update",Ye),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Ye}`),await St();let f=a.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&f==="claude-code"&&await De(t,Me)==="added"&&s.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=$(er(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{s.heading("Downloading the latest Klaudius template");let w=await ht({licenseKey:i,machineId:Ve(),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 tr(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(Be.green("Already up to date.")):(s.detail(`${z(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(Be.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 xt(w,"utf-8"),p=await xt($(A,".gitignore"),"utf-8"),{merged:y,added:m}=nr(v,p);m.length>0&&await Rt(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 je=async()=>{let w=!1,v=p=>fe(p,{recursive:!0,force:!0}).catch(()=>{w=!0});await v($(t,".klaudius","incoming")),await v($(t,mt)),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 je(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ye,await Ge(t,n)),s.blank(),he.outro(Be.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 Jt(Xt(p),{recursive:!0}),await ki(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 Jt(Xt(T),{recursive:!0}),await ki(E,T)}let v=new Map,p=new Map;for(let m of B){let E=await Hn(t,m.path),T=await Un(t,m.path),I=await xt($(A,m.path),"utf-8"),D=jn(E,T,I,m.manifestHash);D!==null?(p.set(m.path,D),v.set(m.path,Kn(D,I))):E!==null&&(Ce(E)||Ce(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,mt);try{await fe(y,{recursive:!0,force:!0})}catch{}for(let[m,E]of p){let T=$(y,m);await Jt(Xt(T),{recursive:!0}),await Rt(T,E,"utf-8")}await Rt($(t,".klaudius","conflicts.md"),ir(j,n.templateVersion,Ye,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=Ye,j.length===0?(delete n.pendingConflicts,await je()):n.pendingConflicts=j.length,await Ge(t,n);try{await gt(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(Be.green("Update complete."));else{let w=f==="codex"?"Codex":"Claude Code";he.outro(Be.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 tr(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 Ie($(e,l)),f=n.files[l],u=$(t,l),A;try{await wi(u),A=await Ie(u)}catch{let b=f!==void 0&&!Cn.has(l)&&!pt.has(l)?"locally-deleted":"new";a.push({path:l,state:b,canonicalHash:c,manifestHash:f});continue}let d=pt.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 wi(f),u=await Ie(f)}catch{delete n.files[l];continue}u===c||pt.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 nr(e,t){let n=e.includes(`\r
107
+ enter from any device.)`)),i.blank();let p=await K();if(p){let[y,...h]=p.command,A=zt(y,[...h,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});A.status===0?i.success("Outlook mailbox connected."):(i.blank(),console.log(m.yellow(`The Microsoft sign-in didn't complete (exit ${A.status??"signalled"}). Setup continues without it.`)),w(p))}else console.log(m.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),w(null)}else ke&&!Ke&&(i.blank(),console.log(m.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(m.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(m.cyan(" python3 scripts/ms_oauth.py login")));i.blank();let O=[...v,...Y?["schema"]:[]];if(O.length>0){P.outro(m.yellow(m.bold(`Setup paused \u2014 ${O.join(", ")} failed.`))),console.log(m.dim("Your credentials and project files are all saved.")),i.blank();for(let[M,Je]of Object.entries(_))console.log(m.yellow(`Likely cause of ${M} failure:`)),console.log(m.dim(` ${Je}`)),i.blank();let p=n!==process.cwd()&&e.target?` ${m.cyan(`cd ${vt(e.target)}`)}
108
+ `:"",y=d.aiAgent==="codex"?"codex":"claude",h=d.aiAgent==="codex"?"Codex":"Claude Code",A=d.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";v.length>0&&(console.log(m.dim(`Easiest fix \u2014 let ${h} finish it for you:`)),i.blank(),p&&process.stdout.write(p),console.log(` ${m.cyan(y)} ${m.dim(`# open ${h} in this folder`)}`),console.log(m.dim(" Then paste:")),console.log(m.cyan(` "Finish my Klaudius install \u2014 ${v.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(m.dim(` (Don't have ${h} yet? Install with: \`${A}\`)`)),i.blank(),console.log(m.dim("Or do it yourself:")),i.blank(),p&&process.stdout.write(p),console.log(` ${m.cyan("npx klaudius@latest install")} ${m.dim("# retry the failing installers")}`),console.log(` ${m.cyan("npx klaudius@latest doctor")} ${m.dim("# verify everything")}`),i.blank()),Y&&(console.log(m.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${m.cyan(le)}`),console.log(m.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),v.includes("pip")&&!_.pip&&(console.log(m.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(m.dim(`Python 3.10+. Install a newer one from ${zo()}`)),console.log(m.dim("and open a fresh Terminal before retrying.")),i.blank());let C=["npm","playwright","patchright"].filter(M=>v.includes(M)&&!_[M]);if(C.length>0){let M=C.length===1?"keeps":"keep";console.log(m.dim(`If ${C.join(" / ")} ${M} failing with network errors (ECONNRESET,`)),console.log(m.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(m.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}g&&(console.log(m.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${h}`)),console.log(m.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(m.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Qo(d,n,e.target),g){let p=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(m.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(m.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(m.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(m.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(m.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(m.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(m.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(i.blank(),console.log(m.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 D(e,t){await Yt(e,{recursive:!0}),await Vt(Z(e,".env"),lt(t),"utf-8"),t.aiAgent==="codex"?(await Yt(Z(e,".codex"),{recursive:!0}),await Vt(Z(e,".codex","config.toml"),dt(t),"utf-8")):(await Vt(Z(e,".mcp.json"),ct(t),"utf-8"),await Rt(e,"supabase"),await Me(e,De))}async function Bo(e){try{(await qt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await hs(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:Z(e,".env")};if(a&&r){let l=!0;try{l=!(await qt(Z(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Vo(e){i.blank(),i.warn(`Found a partial setup at ${m.bold(e)}.`),i.detail(`A previous init wrote ${m.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await P.select({message:`How would you like to proceed? ${m.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 Yo(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 Wo(e){let t=jo(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 qo(){if(process.platform!=="win32")return!1;try{return zt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function zo(){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 Qo(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(m.green(m.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ee(e.aiPlan))==="off";console.log(`${m.bold("Your plan:")} ${Pe[e.aiPlan]}`),console.log(m.dim(r?` \u2192 QA pass off${Ae.has(e.aiPlan)&&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(m.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(m.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let r=`cd ${vt(n)}`;console.log(` ${m.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${m.dim("# go into your project folder")}`)}console.log(` ${m.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${m.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(m.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${m.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${m.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${m.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${m.cyan('"Run the pipeline for one client."')}`),console.log(m.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(m.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(m.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as Jo,readFile as Xo}from"fs/promises";import{join as Qt,resolve as Zo}from"path";import W from"picocolors";async function ys(e){let t=e.target?Zo(process.cwd(),e.target):process.cwd(),n=await gs(Qt(t,".env")),s=await gs(Qt(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 Xo(Qt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await _t(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(W.green(W.bold("All dependencies installed."))),console.log(W.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(W.yellow(W.bold(`${a.join(", ")} still failing.`))),i.blank();for(let[u,E]of Object.entries(r.hints??{}))console.log(W.yellow(`Likely cause of ${u} failure:`)),console.log(W.dim(` ${E}`)),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(W.dim("Options:")),console.log(W.dim(` \u2022 Open ${c} in this folder (\`${l}\`) and paste:`)),console.log(W.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(W.dim(` (Don't have ${c} yet? Install with: \`${f}\`)`)),console.log(W.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(W.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function gs(e){try{return await Jo(e),!0}catch{return!1}}import{readFile as er,writeFile as Jt,access as tr}from"fs/promises";import{join as Ue}from"path";import*as q from"@clack/prompts";import ae from"picocolors";import{mkdir as nr}from"fs/promises";import{spawnSync as ks}from"child_process";async function ws(e){let t=e.projectRoot??process.cwd(),n=Ue(t,".env"),s=Ue(t,".mcp.json"),o=Ue(t,".codex","config.toml"),r=await Xt(Ue(t,".klaudius","manifest.json")),a=await Xt(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 g=await er(n,"utf-8");c=G(g)}catch{i.warn("No .env found. Starting from an empty configuration.")}let f=Tn(c);Object.keys(c).length>0&&(f.pipelineModes??=["classic"]),q.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await N(f),E=f.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==E&&(i.error(`Switching AI coding agent (${E} \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 g=await xe({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});g.ok||(i.error(g.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let d=ir(u,c);if(d==="vercel"){let g=q.spinner();g.start("Validating Vercel token");let k=await Re(u.vercelToken??"");k.ok?g.stop(k.username?`Vercel token accepted (signed in as ${k.username})`:"Vercel token accepted"):(g.stop(k.message,2),i.warn("Writing the token exactly as you entered it \u2014 not verified."),i.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=q.spinner();g.start("Validating Cloudflare token + account");let k=await ve({token:u.cloudflareApiToken??"",accountId:u.cloudflareAccountId??""});k.ok?g.stop("Cloudflare credentials accepted"):(g.stop(k.message??"Cloudflare check failed",2),i.warn("Writing the credentials exactly as you entered them \u2014 not verified."),i.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(d==="netlify"){let g=q.spinner();g.start("Validating Netlify token");let k=await Oe({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),i.warn("Writing the token exactly as you entered it \u2014 not verified."),i.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let b=de(u.googlePlacesApiKey??"");if(b.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let g=await Le(u.googlePlacesApiKey);if(g.ok){if(b.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let k of b.repairs)i.detail(` ${k}`);i.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=b.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(g.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(sr(u,c)){let g=q.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 Pt(S,u,{nonInteractive:!1,onCancel:()=>i.detail("Left the folder names as they are.")})):(g.stop(S.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.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 Jt(n,lt(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await nr(Ue(t,".codex"),{recursive:!0}),await Jt(o,dt(u),"utf-8"),i.success("Updated .codex/config.toml")):(await Jt(s,ct(u),"utf-8"),i.success("Updated .mcp.json"),await Rt(t,"supabase"),await Me(t,De)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let g=await K();if(!(g!==null&&ks(g.command[0],[...g.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!g)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 S=await q.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});q.isCancel(S)||!S?i.detail(`Skipped. Connect it any time with: ${g.command.join(" ")} scripts/ms_oauth.py login`):ks(g.command[0],[...g.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: ${g.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),q.outro(ae.green("Configuration updated.")),await or(t,r)}function sr(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]??""))}function ir(e,t){let n=(s,o)=>(s??"")!==(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 or(e,t){let n=await Xt(Ue(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 Xt(e){try{return await tr(e),!0}catch{return!1}}import{copyFile as As,mkdir as Zt,readFile as Ye,rm as fe,writeFile as Ot,access as Es}from"fs/promises";import{dirname as en,join as R}from"path";import{tmpdir as rr}from"os";import*as he from"@clack/prompts";import We from"picocolors";var qe="0.34.0";async function Ss(e){let t=e.projectRoot??process.cwd(),n=await vn(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 pt)delete n.files[w];let s,o=R(t,".env"),r,a;try{r=await Ye(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:_n(r,a,bn);l!==null&&(await Ot(o,l,"utf-8"),i.detail("Backfilled new env keys")),await kt("update",qe),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${qe}`),await Tt();let f=a.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&f==="claude-code"&&await Me(t,De)==="added"&&i.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=R(rr(),`klaudius-update-${process.pid}-${Date.now()}`),E;try{i.heading("Downloading the latest Klaudius template");let w=await mt({licenseKey:s,machineId:Ve(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:f,destDir:u});i.success(`Fetched ${w.filesExtracted} canonical files`),E=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 lr(E,t,n);if(e.check){let w=d.filter(h=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(h.state)),O=d.filter(h=>["conflict","locally-deleted","removed-modified"].includes(h.state)),p="unknown";if(a.SUPABASE_URL&&a.SUPABASE_SERVICE_KEY){let h=await Ye(R(E,"scripts","schema.sql"),"utf-8").catch(()=>""),A=await At({url:a.SUPABASE_URL,serviceKey:a.SUPABASE_SERVICE_KEY,sql:h});A.unreachable?i.detail(`Database schema not checked (${A.unreachable}).`):A.ok?p="current":(p="stale",i.detail(`Database schema is behind (missing: ${A.missing.join(", ")}); update applies scripts/schema.sql.`))}let y=w.length>0||p==="stale";i.blank(),y?(w.length>0&&i.detail(`${z(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(We.yellow("An update is available."))):he.outro(We.green("Already up to date.")),console.log(`[klaudius-update-check] status=${y?"behind":"current"} pending=${w.length+(p==="stale"?1:0)} conflicts=${O.length} schema=${p}`),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=R(t,".gitignore"),O=await Ye(w,"utf-8"),p=await Ye(R(E,".gitignore"),"utf-8"),{merged:y,added:h}=cr(O,p);h.length>0&&await Ot(w,y,"utf-8"),n.files[".gitignore"]=g.canonicalHash,g.state="gitignore-merged",b=!0,i.detail(h.length>0?`.gitignore auto-merged: kept all your lines, appended ${z(h.length,"new canonical pattern")}: ${h.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"),x=d.filter(w=>w.state==="user-only"),Y=d.filter(w=>w.state==="conflict"),le=d.filter(w=>w.state==="no-change"),v=d.filter(w=>w.state==="locally-deleted"),_=d.filter(w=>w.state==="removed-clean"),ce=d.filter(w=>w.state==="removed-modified"),U=[...Y,...v,...ce],ke=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${z(le.length,"file")} unchanged`),i.detail(`${z(k.length,"new file")}`),i.detail(`${z(S.length,"file")} updated cleanly (no local edits)`),i.detail(`${z(x.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${z(_.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${z(Y.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${z(v.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${z(ce.length,"file")} removed upstream but edited locally (need your decision)`),ke>0&&(i.detail(`${z(ke,"file")} kept deleted (previously resolved \u2014 skipped)`),ke<=10))for(let w of n.ignored)i.detail(` kept deleted: ${w}`);let Ke=async()=>{let w=!1,O=p=>fe(p,{recursive:!0,force:!0}).catch(()=>{w=!0});await O(R(t,".klaudius","incoming")),await O(R(t,gt)),await O(R(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(k.length===0&&S.length===0&&_.length===0&&U.length===0&&!b){await Ps(t,a,!1),await Ke(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=qe,await Be(t,n)),i.blank(),he.outro(We.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[...k,...S]){let O=R(E,w.path),p=R(t,w.path);await Zt(en(p),{recursive:!0}),await As(O,p),n.files[w.path]=w.canonicalHash}k.length+S.length>0&&i.success(`Wrote ${z(k.length+S.length,"file")}`),[...k,...S].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 O=R(t,w.path);await fe(O,{force:!0}),delete n.files[w.path]}if(_.length>0&&i.success(`Deleted ${z(_.length,"file")} removed upstream`),await Ps(t,a,U.some(w=>w.path==="scripts/schema.sql")),U.length>0){i.blank(),i.heading(`${U.length} conflict(s) need resolution`);let w=R(t,".klaudius","incoming");try{await fe(w,{recursive:!0,force:!0})}catch{}for(let h of[...Y,...v]){let A=R(E,h.path),T=R(w,h.path);await Zt(en(T),{recursive:!0}),await As(A,T)}let O=new Map,p=new Map;for(let h of Y){let A=await jn(t,h.path),T=await Kn(t,h.path),C=await Ye(R(E,h.path),"utf-8"),M=Gn(A,T,C,h.manifestHash);M!==null?(p.set(h.path,M),O.set(h.path,Bn(M,C))):A!==null&&(Ce(A)||Ce(C))?O.set(h.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+h.path+"` directly._"]):A===null?O.set(h.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._"]):O.set(h.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/"+h.path+"` directly._"])}let y=R(t,gt);try{await fe(y,{recursive:!0,force:!0})}catch{}for(let[h,A]of p){let T=R(y,h);await Zt(en(T),{recursive:!0}),await Ot(T,A,"utf-8")}await Ot(R(t,".klaudius","conflicts.md"),dr(U,n.templateVersion,qe,O,p),"utf-8"),Y.length+v.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=qe,U.length===0?(delete n.pendingConflicts,await Ke()):n.pendingConflicts=U.length,await Be(t,n);try{await yt(t,E,await ge(E))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),U.length===0)he.outro(We.green("Update complete."));else{let w=f==="codex"?"Codex":"Claude Code";he.outro(We.yellow(`${U.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 Ps(e,t,n){let s=await ar(e,t,n);return console.log(`[klaudius-update] schema=${s}`),s}async function ar(e,t,n){let s=(t.SUPABASE_PAT??"").replace(/\s+/g,""),o=(t.SUPABASE_PROJECT_REF??"").trim();if(!s||!o)return i.detail("Database schema not checked: SUPABASE_PAT / SUPABASE_PROJECT_REF aren't in .env. Run `npx klaudius@latest configure` to add them, or paste scripts/schema.sql into your Supabase SQL editor (safe to re-run)."),"skipped";let r=await wt({projectRoot:e,pat:s,projectRef:o});return r.ok?(i.success(n?"Database schema applied from your current scripts/schema.sql \u2014 resolve its conflict, then run update again to apply the new version":"Database schema up to date"),"applied"):(i.warn(r.message??"Database schema could not be applied"),i.detail(`Paste scripts/schema.sql into the SQL editor to apply it by hand (safe to re-run): ${zn(o)}`),"failed")}async function lr(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 Ie(R(e,l)),f=n.files[l],u=R(t,l),E;try{await Es(u),E=await Ie(u)}catch{let b=f!==void 0&&!Rn.has(l)&&!ft.has(l)?"locally-deleted":"new";a.push({path:l,state:b,canonicalHash:c,manifestHash:f});continue}let d=ft.has(l);c===f?E===f||d?a.push({path:l,state:"no-change",canonicalHash:c,localHash:E,manifestHash:f}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:E,manifestHash:f}):E===f||d?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:E,manifestHash:f}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:E,manifestHash:f})}for(let l of Object.keys(n.files)){if(o.has(l))continue;let c=n.files[l],f=R(t,l),u;try{await Es(f),u=await Ie(f)}catch{delete n.files[l];continue}u===c||ft.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 cr(e,t){let n=e.includes(`\r
110
110
  `)?`\r
111
111
  `:`
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 ir(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 sr}from"fs";import{access as or,readFile as We,stat as rr}from"fs/promises";import{homedir as ar}from"os";import{join as q}from"path";import U from"picocolors";import{spawn as Ei,spawnSync as lr}from"child_process";async function Pi(e){let t=e.projectRoot??process.cwd(),n=[];console.log(U.bold(`Klaudius doctor \u2014 checking your project\u2026
114
- `)),n.push(await cr());let i=await hr();i&&n.push(i),n.push(await dr());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 We(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 We(o,"utf-8"))}catch{}let k=st(g.AI_PLAN),S=ot(g.QA_PHASE)??Ee(k);A=S==="off";let C=k&&Ae.has(k)&&u==="codex"?` \xB7 model pin ${Dt}`:"";n.push({name:"Plan / QA pass",status:k?"ok":"warn",detail:k?`${Pe[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 and Claude Team / ChatGPT Business Standard seats 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 We(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 _r(u)),process.platform==="win32"){let g=await ur(t);g&&n.push(g)}if(n.push(await pr(t)),n.push(await fr(t)),n.push(await mr(t,A)),n.push(await yr()),n.push(await gr(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 We(o,"utf-8"),k=G(g);await kr(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 or(e),!0}catch{return!1}}async function cr(){let e=await Te();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 dr(){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 ur(e){let t=Se([{label:"your Windows user folder",path:ar()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",i=await Zt("npm",["config","get","script-shell"],!0),o=i.code===0?i.stdout.trim():void 0;if(be(o,sr))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}=_e(t,"doctor"),l=t.some(c=>c.chars.includes("&"));return{name:n,status:l?"fail":"warn",detail:r,nextAction:a}}async function pr(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 rr(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 fr(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 hr(){let e=await jt();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 mr(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 _t(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 gr(e){let t=q(e,".klaudius","notify-failures.log");try{let n=(await We(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 yr(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
112
+ `,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 dr(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 E=s.get(u.path);E&&E.length>0&&(c.push(""),c.push("**What upstream changed since your base:**"),c.push(""),c.push(...E),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 ur}from"fs";import{access as pr,readFile as He,stat as fr}from"fs/promises";import{homedir as hr}from"os";import{join as B}from"path";import j from"picocolors";import{spawn as bs,spawnSync as mr}from"child_process";async function _s(e){let t=e.projectRoot??process.cwd(),n=[];console.log(j.bold(`Klaudius doctor \u2014 checking your project\u2026
114
+ `)),n.push(await gr());let s=await Er();s&&n.push(s),n.push(await yr());let o=B(t,".env"),r=B(t,".klaudius","manifest.json"),a=B(t,".mcp.json"),l=B(t,".codex","config.toml"),c=await ne(o),f=await ne(r),u="claude-code";if(c)try{G(await He(o,"utf-8")).AI_AGENT==="codex"&&(u="codex")}catch{}if(u==="claude-code"){let g=await ne(B(t,"AGENTS.md")),k=!await ne(B(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 E=!1;if(c){let g={};try{g=G(await He(o,"utf-8"))}catch{}let k=ot(g.AI_PLAN),S=rt(g.QA_PHASE)??Ee(k);E=S==="off";let x=k&&Ae.has(k)&&u==="codex"?` \xB7 model pin ${Ut}`:"";n.push({name:"Plan / QA pass",status:k?"ok":"warn",detail:k?`${Pe[k]} \xB7 QA pass ${S}${x}`:`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, or a Standard seat on Claude Team or ChatGPT Business, 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 He(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 Or(u)),process.platform==="win32"){let g=await kr(t);g&&n.push(g)}if(n.push(await wr(t)),n.push(await Ar(t)),n.push(await Pr(t,E)),n.push(await br()),n.push(await Sr(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 He(o,"utf-8"),k=G(g);await _r(k,n,t)}console.log();for(let g of n){let k=g.status==="ok"?j.green("\u2713"):g.status==="warn"?j.yellow("\u26A0"):g.status==="skip"?j.dim("\xB7"):j.red("\u2717");console.log(` ${k} ${g.name}${g.detail?j.dim(` \u2014 ${g.detail}`):""}`),g.nextAction&&console.log(` ${j.dim("\u2192")} ${j.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(j.green(j.bold("Everything checks out. You're good to go."))):d===0?console.log(j.yellow(j.bold(`${b} warning${b===1?"":"s"} \u2014 review above.`))):(console.log(j.red(j.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 pr(e),!0}catch{return!1}}async function gr(){let e=await Te();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 yr(){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 kr(e){let t=Se([{label:"your Windows user folder",path:hr()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",s=await tn("npm",["config","get","script-shell"],!0),o=s.code===0?s.stdout.trim():void 0;if(be(o,ur))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}=_e(t,"doctor"),l=t.some(c=>c.chars.includes("&"));return{name:n,status:l?"fail":"warn",detail:r,nextAction:a}}async function wr(e){let t=B(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 fr(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"?B(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?B(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):B(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 Er(){let e=await Gt();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 Pr(e,t){if(!await ne(B(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 Ct(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 Sr(e){let t=B(e,".klaudius","notify-failures.log");try{let n=(await He(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 br(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
115
115
  try:
116
116
  ${e.map(r=>` import ${r}`).join(`
117
117
  `)}
118
118
  except Exception as e:
119
119
  print(str(e))
120
120
  sys.exit(1)
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 Zt(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 kr(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let a=await xe({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=Xe(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(i==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let a=await ve({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 Oe({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 Re(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 Le(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 Sr(e,n)),t.push(...await br(e)),t.push(await Er(e)),t.push(await Pr(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 rn({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 wr(e){let t=r=>!!r&&/^\d+$/.test(r.trim()),n=Si(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 Si(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function Ar(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=lr(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 Er(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 Pr(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 At({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=dn(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 Sr(e,t){let n="Email credentials (SMTP + IMAP)",i=wr(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Si(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."}:Ar(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=rt(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=bi(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=Je(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 bi(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 br(e){let t=[];for(let n of En(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=bi(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 _r(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 Zt(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 Zt(e,t,n=!1){return new Promise(i=>{let o=n?Ei([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Ei(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 Tr}from"fs";import{spawnSync as Ir}from"child_process";import{join as Cr,resolve as xr}from"path";import V from"picocolors";async function _i(e){let t=xr(e.projectRoot??process.cwd()),n=Cr(t,"scripts","whatsapp.mjs");Tr(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=Ir(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(V.green(`Paired '${o}'.`)),console.log(V.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 s=n.command,o=await tn(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(`
122
+ `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function _r(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let a=await xe({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=Ze(a);f&&c.push(`SELFHOST_DEPLOY_TARGET: ${f}`);let u=et(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 ve({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 Oe({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 Re(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 Le(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 Rr(e,n)),t.push(...await vr(e)),t.push(await Cr(e,n)),t.push(await xr(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 ln({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 Tr(e){let t=r=>!!r&&/^\d+$/.test(r.trim()),n=Ts(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 Ts(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function Ir(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=mr(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(B(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 Cr(e,t){let n="Database schema up to date",s=(e.SUPABASE_URL??"").trim(),o=(e.SUPABASE_SERVICE_KEY??"").trim();if(!s||!o)return{name:n,status:"skip",detail:"Supabase credentials not set"};let r="";try{r=await He(B(t,"scripts","schema.sql"),"utf-8")}catch{return{name:n,status:"skip",detail:"scripts/schema.sql missing \u2014 run `npx klaudius@latest update`"}}let a=await At({url:s,serviceKey:o,sql:r});return a.unreachable?{name:n,status:"skip",detail:`Could not verify (${a.unreachable}) \u2014 see the Supabase rows above.`}:a.ok?{name:n,status:"ok",detail:"every table and column the pipeline expects is present"}:{name:n,status:"warn",detail:`missing: ${a.missing.join(", ")} \u2014 this database was provisioned before they were added, so the pipeline files ahead of it will fail on them.`,nextAction:"Run `npx klaudius@latest update` \u2014 it re-applies scripts/schema.sql (safe on an existing database). Or paste scripts/schema.sql into your Supabase SQL editor."}}async function xr(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 St({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=pn(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 Rr(e,t){let n="Email credentials (SMTP + IMAP)",s=Tr(e);if(s==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Ts(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."}:Ir(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=at(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=Is(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=Xe(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(j.dim(` (email login rejected \u2014 probing ${X[r].label}'s other regional servers, up to ~10s each\u2026)`));let f=0;for(let E of c){let d=await oe({...a,emailSmtpHost:E.smtpHost,emailImapHost:E.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 ${E.label} (${E.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${E.smtpHost} and EMAIL_IMAP_HOST=${E.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 Is(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 vr(e){let t=[];for(let n of Sn(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=Is(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 Or(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 tn(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:s}}function tn(e,t,n=!1){return new Promise(s=>{let o=n?bs([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):bs(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 Lr}from"fs";import{spawnSync as $r}from"child_process";import{join as Nr,resolve as Dr}from"path";import V from"picocolors";async function Cs(e){let t=Dr(e.projectRoot??process.cwd()),n=Nr(t,"scripts","whatsapp.mjs");Lr(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 s=(e.label??"primary").trim(),o=s.replace(/[^A-Za-z0-9_-]/g,"");o||(console.error(V.red(`Invalid label '${s}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),o!==s&&console.error(V.yellow(`Note: cleaned label '${s}' \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=$r(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(V.green(`Paired '${o}'.`)),console.log(V.dim(`
126
126
  If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
127
127
  WHATSAPP_ACCOUNTS=primary,${o}
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 Ue,spawn as Rr}from"child_process";import{existsSync as ze,mkdirSync as vr,readdirSync as Or,rmSync as xi,mkdtempSync as Ri}from"fs";import{homedir as en,tmpdir as vi}from"os";import{join as J}from"path";import ie from"picocolors";var Lr=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function Ti(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Oi(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&qe()&&$i();let t=Nr();if(t&&!e.reinstall&&!e.from){Ci(),console.log(ie.green("Opened the Klaudius app.")),Ii();return}let n=await Dr(e.from);console.log(ie.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Fr(n):Hr(n),Ci(),console.log(ie.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),Ii()}function Ii(){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 vt(){return J(en(),"Applications","Klaudius.app")}function Li(){return process.env.LOCALAPPDATA??J(en(),"AppData","Local")}function $r(){return J(Li(),"Klaudius")}function qe(){let e=J(Li(),"Programs");try{for(let t of Or(e)){if(!/laudius/i.test(t))continue;let n=J(e,t,"Klaudius.exe");if(ze(n))return n}}catch{}return null}function Nr(){return process.platform==="darwin"?ze(vt()):qe()!==null}async function Mr(){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 Dr(e){if(e)return ze(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await Mr();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=`${Lr}?file=${encodeURIComponent(Ti())}`,i=J(Ri(J(vi(),"klaudius-app-")),Ti());console.log(ie.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.33.0"}});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 Fr(e){let t=J(en(),"Applications");vr(t,{recursive:!0});let n=Ri(J(vi(),"klaudius-app-x-")),i=Ue("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");ze(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),xi(vt(),{recursive:!0,force:!0});let r=Ue("mv",[o,vt()],{stdio:"pipe"});r.status!==0&&(console.error(`Couldn't install to ~/Applications: ${r.stderr?.toString().trim()}`),process.exit(1))}function Hr(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=Ue(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Ur(6e4)){let i=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,o=qe();if(o&&Ni(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)}$i()}function Ur(e){let t=Date.now()+e;for(;;){let n=qe();if(n)return n;if(Date.now()>=t)return null;jr(500)}}function jr(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function $i(){let e=$r();if(!ze(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=`
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 je,spawn as Mr}from"child_process";import{existsSync as ze,mkdirSync as Fr,readdirSync as Ur,rmSync as Os,mkdtempSync as Ls}from"fs";import{homedir as nn,tmpdir as $s}from"os";import{join as J}from"path";import se from"picocolors";var Hr=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function xs(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Ns(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&Qe()&&Ms();let t=Kr();if(t&&!e.reinstall&&!e.from){vs(),console.log(se.green("Opened the Klaudius app.")),Rs();return}let n=await Br(e.from);console.log(se.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Vr(n):Yr(n),vs(),console.log(se.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),Rs()}function Rs(){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 Lt(){return J(nn(),"Applications","Klaudius.app")}function Ds(){return process.env.LOCALAPPDATA??J(nn(),"AppData","Local")}function jr(){return J(Ds(),"Klaudius")}function Qe(){let e=J(Ds(),"Programs");try{for(let t of Ur(e)){if(!/laudius/i.test(t))continue;let n=J(e,t,"Klaudius.exe");if(ze(n))return n}}catch{}return null}function Kr(){return process.platform==="darwin"?ze(Lt()):Qe()!==null}async function Gr(){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 Br(e){if(e)return ze(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await Gr();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=`${Hr}?file=${encodeURIComponent(xs())}`,s=J(Ls(J($s(),"klaudius-app-")),xs());console.log(se.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.34.0"}});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=J(nn(),"Applications");Fr(t,{recursive:!0});let n=Ls(J($s(),"klaudius-app-x-")),s=je("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=J(n,"Klaudius.app");ze(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),Os(Lt(),{recursive:!0,force:!0});let r=je("mv",[o,Lt()],{stdio:"pipe"});r.status!==0&&(console.error(`Couldn't install to ~/Applications: ${r.stderr?.toString().trim()}`),process.exit(1))}function Yr(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=je(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Wr(6e4)){let s=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,o=Qe();if(o&&Fs(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)}Ms()}function Wr(e){let t=Date.now()+e;for(;;){let n=Qe();if(n)return n;if(Date.now()>=t)return null;qr(500)}}function qr(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Ms(){let e=jr();if(!ze(J(e,"app","Klaudius.exe")))return;console.log(se.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
129
129
  $legacy = '${e.replace(/'/g,"''")}'
130
130
  # Compare against the directory PLUS its separator, so a sibling folder whose
131
131
  # name merely starts with the same text ("Klaudius Desktop") is never matched.
@@ -139,4 +139,4 @@ foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetF
139
139
  Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
140
140
  }
141
141
  }
142
- }`;Ue("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{xi(e,{recursive:!0,force:!0})}catch{console.log(ie.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function Ci(){if(process.platform==="darwin"){Ue("open",["-a",vt()],{stdio:"pipe"});return}let e=qe();if(!e||Ni(e))return;Rr(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function Ni(e){let t=Ue("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 Mi(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 tn(e=0){await Promise.all([Mi(process.stdout),Mi(process.stderr)]),process.exit(e)}import{spawnSync as Kr}from"child_process";var nn="--use-system-ca";function Di(){let e=process.env.NODE_OPTIONS??"";if(e.includes(nn)||!ue().ok)return;let n=e?`${e} ${nn}`:nn,i=Kr(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)}Di();var Vr="0.33.0",se=new Gr;se.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Vr);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 mn({})}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 fi({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await tn(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 mi({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 yi({}),await tn(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 Ai({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 Pi({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 Oi({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 _i({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});se.parse(process.argv);
142
+ }`;je("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Os(e,{recursive:!0,force:!0})}catch{console.log(se.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function vs(){if(process.platform==="darwin"){je("open",["-a",Lt()],{stdio:"pipe"});return}let e=Qe();if(!e||Fs(e))return;Mr(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function Fs(e){let t=je("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)}function Us(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 sn(e=0){await Promise.all([Us(process.stdout),Us(process.stderr)]),process.exit(e)}import{spawnSync as zr}from"child_process";var on="--use-system-ca";function Hs(){let e=process.env.NODE_OPTIONS??"";if(e.includes(on)||!ue().ok)return;let n=e?`${e} ${on}`:on,s=zr(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)}Hs();var Jr="0.34.0",ie=new Qr;ie.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Jr);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 yn({})}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 ms({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await sn(process.exitCode??0)}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 ys({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 ws({}),await sn(process.exitCode??0)}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 Ss({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 _s({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 Ns({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 Cs({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ie.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klaudius",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code or Codex (find, build, deploy, outreach end-to-end).",
5
5
  "homepage": "https://klaudius.dev",
6
6
  "bugs": {