klaudius 0.34.1 → 0.35.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 (3) hide show
  1. package/README.md +1 -0
  2. package/dist/bin.js +80 -73
  3. package/package.json +2 -2
package/dist/bin.js CHANGED
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env node
2
- import{b as Pe,c as ut,d as Q,e as I,f as Sn,g as bn,h as pt,i as ft,j as _n,k as ge,l as Tn,m as In,p as Cn,r as Ie,s as Ce,t as Re,u as F}from"./chunk-3XX6MJ72.js";import{Command as ha}from"commander";import{spawn as On}from"child_process";import{existsSync as ki}from"fs";import{homedir as Ai}from"os";import N from"picocolors";import{win32 as oi}from"path";var ri=["&","^","%","!"];function ai(e){return ri.filter(t=>e.includes(t))}function xe(e){let t=[];for(let{label:n,path:s}of e){let o=ai(s);o.length>0&&t.push({label:n,path:s,chars:o})}return t}function li(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=oi.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(s)?t:null}function Oe(e,t){let n=li(e);return n===null?!1:t?t(n):!0}function ve(e,t){let n=e[0],s=[...new Set(e.flatMap(p=>p.chars))],o=s.map(p=>`"${p}"`).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 ye(){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 ci}from"child_process";import{existsSync as di}from"fs";import{homedir as ui}from"os";import{delimiter as pi,join as ht}from"path";var fi=new Set(["Restricted","AllSigned"]);function hi(e,t=di){for(let n of e.split(pi)){let s=n.replace(/"/g,"");if(!s)continue;let o=ht(s,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let a=ht(s,r);if(t(a))return{path:a,isPs1:!1}}}return null}async function xn(){let e=hi(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await mi();if(!t)return{blocked:!1,shimPath:e.path};let n=ht(ui(),".local","node")+"\\";return{blocked:fi.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function mi(){let e=ht(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await Rn(e)??await Rn("powershell.exe")}function Rn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let s=ci(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 gi}from"child_process";var Ze=3,mt=10,yi=[["python3"],["python"],["py","-3"]];async function W(){for(let e of yi){let t=await gt(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 Le(){let e=wi(),t=await W();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 ${Ze}.${mt}+ is not installed (or not on PATH). Install it from ${e}.`+a}}let{command:n,version:s,major:o,minor:r}=t;return o<Ze||o===Ze&&r<mt?{ok:!1,version:s,major:o,minor:r,command:n,message:`Your installed Python is ${s}. Klaudius needs Python ${Ze}.${mt} or newer (the pipeline depends on packages that only ship wheels for ${Ze}.${mt}+). 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 wi(){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 gt(e,t){return new Promise(n=>{let s=gi(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 vn=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function Ln(e={}){console.log(N.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
- `));let t=[];t.push(Ei());let n=await Le();if(t.push(Pi(n)),t.push(await Si(n.command)),t.push(await bi()),process.platform==="win32"){let o=await _i();o&&t.push(o);let r=await Ti();r&&t.push(r)}t.push(await Ii());for(let o of t){let r=o.status==="ok"?N.green("\u2713"):o.status==="warn"?N.yellow("!"):N.red("\u2717");console.log(` ${r} ${o.name}${o.detail?N.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${N.dim("\u2192")} ${N.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;Ci(o);return}console.log(N.red(N.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(N.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(N.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Ei(){let e=ye();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 Pi(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 Si(e){let t=e??["python3"],n=await yt(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 bi(){let e=process.platform==="win32",t=await yt("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 yt("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 _i(){let e=await xn();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 Ti(){let e=xe([{label:"your Windows user folder",path:Ai()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await yt("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(Oe(s,ki))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(d=>`"${d}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=ve(e,"preflight"),a=e.some(d=>d.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function Ii(){try{return await fetch(vn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:vn}}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 Ci(e=0){e>0?console.log(N.green(N.bold("Your machine is ready."))+N.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(N.green(N.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(N.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(` ${N.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(N.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(N.dim(" run it in a new terminal window.")),console.log()}function yt(e,t,n=!1){return new Promise(s=>{let o=n?On([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):On(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",d=>{r+=d.toString()}),o.stderr?.on("data",d=>{a+=d.toString()}),o.on("close",d=>s({code:d??1,stdout:r,stderr:a})),o.on("error",()=>s({code:1,stdout:r,stderr:a}))})}import{mkdir as Bt,readdir as Os,readFile as Ve,rm as Cs,stat as cn,writeFile as it}from"fs/promises";import{spawnSync as dn}from"child_process";import{existsSync as tr}from"fs";import{homedir as vs}from"os";import{resolve as nr,isAbsolute as sr,join as j,normalize as ir}from"path";import*as E from"@clack/prompts";import h from"picocolors";var Ri={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"},xi={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 wt(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9.,  ]*$/.test(n))return n;let s=xi[(t??"").toUpperCase()];return s?`${s.pre??""}${n}${s.post??""}`:n}function Jt(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?Ri[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 Xt="claude-code",Zt="gpt-5.6-terra";function Nn(e){if(e==="claude-code"||e==="codex")return e}var Oi=["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 kt(e){let t=e?.trim().toLowerCase()??"";return Oi.includes(t)?t:void 0}function At(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 en="vercel";function $n(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function Mn(e){if(e==="telegram"||e==="email"||e==="sms")return e}function Dn(e){if(e==="password"||e==="oauth-microsoft")return e}function vi(e){if(e==="custom"||e!==void 0&&Object.hasOwn(Q,e))return e}function et(e){let t=vi(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[s,o]of Object.entries(Q))if(o.smtpHost===n)return s;return"custom"}}function Fn(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=d=>{let c=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${d}`];return c?.trim()?c.trim():void 0},a=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(d=>!r(d)).map(d=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${d}`);for(let d of["SMTP_PORT","IMAP_PORT"]){let c=r(d);c!==void 0&&!/^\d+$/.test(c)&&a.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${d}`)}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 Et(e){let t=[],n=d=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${d}`),t.push("# "+"=".repeat(60)),t.push("")},s=(d,c)=>{if(c==null||c===""){t.push(`# ${d}=`);return}let p=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(p)){let u=p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${d}="${u}"`)}else t.push(`${d}=${p}`)};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??Xt),s("AI_PLAN",e.aiPlan),s("QA_PHASE",e.qaPhase??Ce(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",wt(e.pricing,e.countryCode)),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",wt(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",Jt(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??en),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(d=>/^#?\s*([A-Z0-9_]+)=/.exec(d)?.[1]).filter(d=>!!d)),a=Object.entries(e.preservedEnv??{}).filter(([d])=>!r.has(d));if(a.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[d,c]of a)s(d,c)}return t.join(`
2
+ import{b as Me,c as Tt,d as ce,e as H,f as Wn,g as qn,h as _t,i as It,j as zn,k as Re,l as Jn,m as Qn,p as Xn,r as He,s as je,t as Ke,u as z}from"./chunk-3XX6MJ72.js";import{Command as Tl}from"commander";import{spawn as ti}from"child_process";import{existsSync as so}from"fs";import{homedir as oo}from"os";import V from"picocolors";import{win32 as Bs}from"path";var Vs=["&","^","%","!"];function Ys(e){return Vs.filter(t=>e.includes(t))}function Ge(e){let t=[];for(let{label:n,path:i}of e){let s=Ys(i);s.length>0&&t.push({label:n,path:i,chars:s})}return t}function Ws(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=Bs.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(i)?t:null}function Be(e,t){let n=Ws(e);return n===null?!1:t?t(n):!0}function Ve(e,t){let n=e[0],i=[...new Set(e.flatMap(p=>p.chars))],s=i.map(p=>`"${p}"`).join(", "),o=i.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${s} in it ${o?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${o?"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 ve(){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),s=parseInt(t[3],10),o=`${n}.${i}.${s}`;return n<22||n===22&&i<15?{ok:!1,version:o,major:n,minor:i,message:`Your installed Node.js is ${o}. 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:o,major:n,minor:i}}import{spawn as qs}from"child_process";import{existsSync as zs}from"fs";import{homedir as Js}from"os";import{delimiter as Qs,join as Ct}from"path";var Xs=new Set(["Restricted","AllSigned"]);function Zs(e,t=zs){for(let n of e.split(Qs)){let i=n.replace(/"/g,"");if(!i)continue;let s=Ct(i,"npx.ps1");if(t(s))return{path:s,isPs1:!0};for(let o of["npx.exe","npx.bat","npx.cmd"]){let r=Ct(i,o);if(t(r))return{path:r,isPs1:!1}}}return null}async function ei(){let e=Zs(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await eo();if(!t)return{blocked:!1,shimPath:e.path};let n=Ct(Js(),".local","node")+"\\";return{blocked:Xs.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function eo(){let e=Ct(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await Zn(e)??await Zn("powershell.exe")}function Zn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let i=qs(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),s="",o=setTimeout(()=>{i.kill(),n(null)},8e3);i.stdout.on("data",r=>{s+=r.toString()}),i.stderr?.resume(),i.on("close",r=>{clearTimeout(o),n(r===0&&s.trim()?s.trim():null)}),i.on("error",()=>{clearTimeout(o),n(null)})})}import{spawn as to}from"child_process";var dt=3,Rt=10,no=[["python3"],["python"],["py","-3"]];async function se(){for(let e of no){let t=await vt(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 s=parseInt(i[1],10),o=parseInt(i[2],10),r=i[3]?`${s}.${o}.${i[3]}`:`${s}.${o}`;return{command:[...e],version:r,major:s,minor:o}}return null}async function Ye(){let e=io(),t=await se();if(!t){let r=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 ${dt}.${Rt}+ is not installed (or not on PATH). Install it from ${e}.`+r}}let{command:n,version:i,major:s,minor:o}=t;return s<dt||s===dt&&o<Rt?{ok:!1,version:i,major:s,minor:o,command:n,message:`Your installed Python is ${i}. Klaudius needs Python ${dt}.${Rt} or newer (the pipeline depends on packages that only ship wheels for ${dt}.${Rt}+). 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:s,minor:o,command:n}}function io(){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 vt(e,t){return new Promise(n=>{let i=to(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),s="",o="";i.stdout?.on("data",r=>{s+=r.toString()}),i.stderr?.on("data",r=>{o+=r.toString()}),i.on("close",r=>n({code:r??1,stdout:s,stderr:o})),i.on("error",()=>n({code:1,stdout:s,stderr:o}))})}var ni=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function ii(e={}){console.log(V.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
+ `));let t=[];t.push(ro());let n=await Ye();if(t.push(ao(n)),t.push(await lo(n.command)),t.push(await co()),process.platform==="win32"){let s=await uo();s&&t.push(s);let o=await po();o&&t.push(o)}t.push(await fo());for(let s of t){let o=s.status==="ok"?V.green("\u2713"):s.status==="warn"?V.yellow("!"):V.red("\u2717");console.log(` ${o} ${s.name}${s.detail?V.dim(` \u2014 ${s.detail}`):""}`),s.nextAction&&console.log(` ${V.dim("\u2192")} ${V.cyan(s.nextAction)}`)}console.log();let i=t.filter(s=>s.status==="fail");if(i.length===0){let s=t.filter(o=>o.status==="warn").length;ho(s);return}console.log(V.red(V.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(V.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(V.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function ro(){let e=ve();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 ao(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 lo(e){let t=e??["python3"],n=await xt(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 co(){let e=process.platform==="win32",t=await xt("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 xt("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 uo(){let e=await ei();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 po(){let e=Ge([{label:"your Windows user folder",path:oo()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await xt("npm",["config","get","script-shell"],!0),i=n.code===0?n.stdout.trim():void 0;if(Be(i,so))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${i}) handles it`};let{detail:s,action:o}=Ve(e,"preflight"),r=e.some(c=>c.chars.includes("&"));return{name:t,status:r?"fail":"warn",detail:s,nextAction:o}}async function fo(){try{return await fetch(ni,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:ni}}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 ho(e=0){e>0?console.log(V.green(V.bold("Your machine is ready."))+V.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(V.green(V.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(V.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(` ${V.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(V.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(V.dim(" run it in a new terminal window.")),console.log()}function xt(e,t,n=!1){return new Promise(i=>{let s=n?ti([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ti(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",c=>{o+=c.toString()}),s.stderr?.on("data",c=>{r+=c.toString()}),s.on("close",c=>i({code:c??1,stdout:o,stderr:r})),s.on("error",()=>i({code:1,stdout:o,stderr:r}))})}import{mkdir as on,readdir as ss,readFile as nt,rm as ts,stat as In,writeFile as gt}from"fs/promises";import{spawnSync as Cn}from"child_process";import{existsSync as jr}from"fs";import{homedir as os}from"os";import{resolve as Kr,isAbsolute as Gr,join as X,normalize as Br}from"path";import*as T from"@clack/prompts";import g from"picocolors";var mo={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"},go={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 Ot(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9.,  ]*$/.test(n))return n;let i=go[(t??"").toUpperCase()];return i?`${i.pre??""}${n}${i.post??""}`:n}function mn(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?mo[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 gn="claude-code",yn="gpt-5.6-terra";function si(e){if(e==="claude-code"||e==="codex")return e}var yo=["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 $t(e){let t=e?.trim().toLowerCase()??"";return yo.includes(t)?t:void 0}function Lt(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 wn="vercel";function oi(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function ri(e){if(e==="telegram"||e==="email"||e==="sms")return e}function ai(e){if(e==="password"||e==="oauth-microsoft")return e}function wo(e){if(e==="custom"||e!==void 0&&Object.hasOwn(ce,e))return e}function ut(e){let t=wo(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[i,s]of Object.entries(ce))if(s.smtpHost===n)return i;return"custom"}}function li(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let i of t.split(",")){let s=i.trim().toLowerCase();s&&s!=="primary"&&!n.includes(s)&&n.push(s)}return n.map(i=>{let s=/^[a-z0-9_]+$/.test(i)&&i!=="auto",o=c=>{let u=e[`EMAIL_ACCOUNT_${i.toUpperCase()}_${c}`];return u?.trim()?u.trim():void 0},r=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(c=>!o(c)).map(c=>`EMAIL_ACCOUNT_${i.toUpperCase()}_${c}`);for(let c of["SMTP_PORT","IMAP_PORT"]){let u=o(c);u!==void 0&&!/^\d+$/.test(u)&&r.push(`EMAIL_ACCOUNT_${i.toUpperCase()}_${c}`)}return{label:i,valid:s,auth:(o("AUTH")??"password").toLowerCase(),address:o("ADDRESS"),missing:r,smtpHost:o("SMTP_HOST"),smtpPort:parseInt(o("SMTP_PORT")??"587",10),imapHost:o("IMAP_HOST"),imapPort:parseInt(o("IMAP_PORT")??"993",10),password:o("PASSWORD"),login:o("LOGIN")}})}function Nt(e){let t=[],n=c=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${c}`),t.push("# "+"=".repeat(60)),t.push("")},i=(c,u)=>{if(u==null||u===""){t.push(`# ${c}=`);return}let p=String(u);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(p)){let d=p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${c}="${d}"`)}else t.push(`${c}=${p}`)};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??gn),i("AI_PLAN",e.aiPlan),i("QA_PHASE",e.qaPhase??je(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 s=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];i("PIPELINE_MODES",[...new Set(s)].join(",")),n("Pricing"),i("PRICING",Ot(e.pricing,e.countryCode)),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",Ot(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",mn(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??wn),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 o=new Set(t.map(c=>/^#?\s*([A-Z0-9_]+)=/.exec(c)?.[1]).filter(c=>!!c)),r=Object.entries(e.preservedEnv??{}).filter(([c])=>!o.has(c));if(r.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[c,u]of r)i(c,u)}return t.join(`
5
5
  `)+`
6
- `}function Pt(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 St(e){let t=e.supabaseProjectRef,n=Li(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&&Ie.has(e.aiPlan)?[`# Set by the wizard for ${Re[e.aiPlan]}. Change or delete to use Codex's default.`,`model = "${Zt}"`,""]:[],"[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 Li(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Un=[{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 Ni(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function Hn(e,t,n){let s=n.filter(a=>!(a.key in t));if(s.length===0)return null;let o=e.endsWith(`
6
+ `}function Mt(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=ko(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&&He.has(e.aiPlan)?[`# Set by the wizard for ${Ke[e.aiPlan]}. Change or delete to use Codex's default.`,`model = "${yn}"`,""]:[],"[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 ko(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var ci=[{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 Ao(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function di(e,t,n){let i=n.filter(r=>!(r.key in t));if(i.length===0)return null;let s=e.endsWith(`
9
9
  `)?"":`
10
- `,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let a of s)r.push(""),a.comment&&r.push(`# ${a.comment}`),r.push(Ni(a.key,a.value));return e+o+r.join(`
10
+ `,o=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let r of i)o.push(""),r.comment&&o.push(`# ${r.comment}`),o.push(Ao(r.key,r.value));return e+s+o.join(`
11
11
  `)+`
12
- `}function $i(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 V(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=$i(s.slice(o+1).trim());t[r]=a}return t}var jn=["VERCEL_TOKEN","CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","NETLIFY_AUTH_TOKEN","EMAIL_PROVIDER","EMAIL_AUTH","EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT","SMS_PROVIDER","TEST_PHONE","TWILIO_ACCOUNT_SID","TWILIO_AUTH_TOKEN","TWILIO_PHONE_NUMBER","WHATSAPP_ACCOUNTS","LETTER_PROVIDER","PINGEN_CLIENT_ID","PINGEN_CLIENT_SECRET","PINGEN_ORG_ID","POSTGRID_API_KEY","NOTIFY_CHANNEL","TELEGRAM_BOT_TOKEN","TELEGRAM_CHAT_ID"];function Kn(e,t,n={}){let s={...e},o=c=>(t[c]??"").trim()!=="";if(!o("PRICING_TERMS")&&(o("PRICING")||o("PRICING_MONTHLY"))){let c=_n(wt(t.PRICING,s.countryCode)??"",wt(t.PRICING_MONTHLY,s.countryCode)??"");s.pricing=c.pricing,s.pricingTerms=c.pricingTerms,s.pricingMonthly=c.pricingMonthly}s.signature&&s.name&&s.signature.trim()===s.name.trim()&&(s.signature=void 0),o("EMAIL_FROM_NAME")||(s.emailFromName=s.name?.trim()&&s.emailAddress?.trim()?s.name.trim():void 0);let r=s.emailProvider&&s.emailProvider!=="custom"?Q[s.emailProvider]:void 0,a=et(n)===s.emailProvider&&(n.EMAIL_ADDRESS??"").trim().toLowerCase()===(s.emailAddress??"").trim().toLowerCase(),d=[["EMAIL_SENT_FOLDER","emailSentFolder",r?.sentFolder],["EMAIL_DRAFTS_FOLDER","emailDraftsFolder",r?.draftsFolder],["EMAIL_INBOX_FOLDER","emailInboxFolder",r?.inboxFolder]];for(let[c,p,u]of d)o(c)||a&&(n[c]??"").trim()||(s[p]=u);return s}function Gn(e){let t=d=>{let c=e[d];if(!c)return;let p=parseInt(c,10);return isNaN(p)?void 0:p},n=e.SMS_PROVIDER,s=d=>d==="email"||d==="sms"||d==="whatsapp"||d==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(d=>d.trim()).filter(s),r=e.OUTREACH_PRIORITY?.split(",").map(d=>d.trim()).filter(s),a=e.WHATSAPP_ACCOUNTS?.split(",").map(d=>d.trim()).filter(d=>d.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Nn(e.AI_AGENT)??Xt,aiPlan:kt(e.AI_PLAN),qaPhase:At(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(d=>d.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:et(e),emailAuth:Dn(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:Jt(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:$n(e.DEPLOY_PROVIDER)??en,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:Mn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function bt(e){let t=b=>{let ie=e[b];if(!ie)return;let B=parseInt(ie,10);return isNaN(B)?void 0:B},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,d=e.PRICING_TERMS||"one-off, no monthly fees",c=$n(e.DEPLOY_PROVIDER)??en,p=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,A=e.CLOUDFLARE_ACCOUNT_ID,P=e.NETLIFY_AUTH_TOKEN,T=e.SELFHOST_DEPLOY_TARGET,m=e.SELFHOST_URL_TEMPLATE;if(!a||!n||!s||!o||!r||!(c==="cloudflare"?!!u&&!!A:c==="netlify"?!!P:c==="selfhost"?!!T&&!!m:!!p))return null;let S=e.SMS_PROVIDER,C=b=>b==="email"||b==="sms"||b==="whatsapp"||b==="letter",G=e.OUTREACH_CHANNELS?.split(",").map(b=>b.trim()).filter(C),me=e.OUTREACH_PRIORITY?.split(",").map(b=>b.trim()).filter(C),ne=e.WHATSAPP_ACCOUNTS?.split(",").map(b=>b.trim()).filter(b=>b.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Nn(e.AI_AGENT)??Xt,aiPlan:kt(e.AI_PLAN),qaPhase:At(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(b=>b.trim().toLowerCase()).filter(Boolean):void 0,pricing:a,pricingTerms:d,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:G&&G.length>0?G:void 0,outreachPriority:me&&me.length>0?me:void 0,whatsappAccounts:ne&&ne.length>0?ne:void 0,emailProvider:et(e),emailAuth:Dn(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:Jt(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:p,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:A||void 0,netlifyAuthToken:P||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:T||void 0,selfhostUrlTemplate:m||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:Mn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Ya,mkdir as Wa,readdir as Ki,stat as qa}from"fs/promises";import{dirname as Qa,join as Qn,relative as Gi,sep as Bi}from"path";import{fileURLToPath as Xa}from"url";import{createHash as Bn}from"crypto";import{readFile as Mi}from"fs/promises";async function Ne(e){let t=await Mi(e);return Bn("sha256").update(t).digest("hex")}function tn(e){return Bn("sha256").update(e).digest("hex")}import{mkdir as Di,readFile as Fi,writeFile as Ui,access as Hi}from"fs/promises";import{dirname as ji,join as Vn}from"path";var tt=".klaudius",Yn=`${tt}/manifest.json`,_t=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json"]),Wn=new Set(["clients/README.md"]),Tt=new Set(["package-lock.json"]);async function qn(e){let t=Vn(e,Yn);try{await Hi(t)}catch{return null}let n=await Fi(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 nt(e,t){let n=Vn(e,Yn);await Di(ji(n),{recursive:!0}),await Ui(n,JSON.stringify(t,null,2)+`
14
- `,"utf-8")}function zn(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function Se(e,t=e){let n=await Ki(e,{withFileTypes:!0}),s=[];for(let o of n){let r=Qn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await Se(r,t)):o.isFile()&&s.push(Gi(t,r).split(Bi).join("/")))}return s}async function Jn(e){let t=await Se(e),n={};for(let s of t)_t.has(s)||(n[s]=await Ne(Qn(e,s)));return n}import{copyFile as Vi,mkdir as Xn,mkdtemp as Yi,readdir as Zn,rm as es}from"fs/promises";import{tmpdir as Wi}from"os";import{dirname as qi,join as It}from"path";import{Readable as zi}from"stream";import*as ts from"tar";var Qi="https://klaudius.dev/api/template";function Ji(e){return zi.fromWeb(e)}async function Ct(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Qi,n="0.34.1",s;try{s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(d){throw new Error(`Could not reach klaudius.dev to download the template: ${I(d)}`)}if(!s.ok){let d="";try{let c=await s.json();d=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${d}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),r=await Yi(It(Wi(),"klaudius-template-")),a=0;try{try{await new Promise((p,u)=>{let A=ts.extract({cwd:r,strict:!0});A.on("finish",p),A.on("error",u),Ji(s.body).on("error",u).pipe(A)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await Xn(e.destDir,{recursive:!0});let d=new Set(await Zn(e.destDir)),c=await Se(r);try{for(let p of c){let u=It(e.destDir,p);await Xn(qi(u),{recursive:!0}),await Vi(It(r,p),u),a++}}catch(p){let u=await Zn(e.destDir).catch(()=>[]);for(let A of u)d.has(A)||await es(It(e.destDir,A),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await es(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:a,tier:o}}import{copyFile as Xi,mkdir as Zi,readFile as ns,rm as eo}from"fs/promises";import{dirname as to,join as be}from"path";import{structuredPatch as no}from"diff";var ss=be(".klaudius","base"),Rt=be(".klaudius","conflict-base");async function xt(e,t,n){let s=be(e,ss);await eo(s,{recursive:!0,force:!0});for(let o of n){let r=be(s,o);await Zi(to(r),{recursive:!0}),await Xi(be(t,o),r)}}async function is(e,t){try{return await ns(be(e,ss,t),"utf-8")}catch{return null}}async function os(e,t){try{return await ns(be(e,Rt,t),"utf-8")}catch{return null}}function rs(e,t,n,s){return $e(n)?null:e!==null&&!$e(e)&&(!s||tn(e)===s)?e:t!==null&&!$e(t)&&s&&tn(t)===s?t:null}function $e(e){return e.includes("\0")||e.includes("\uFFFD")}function as(e,t,n=60){let s=no("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,d=!1;for(let c of s.hunks){if(a>=n){d=!0;break}r.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),a+=1;let p=Math.max(n-a,0),u=c.lines.slice(0,p);if(r.push(...u),a+=u.length,u.length<c.lines.length){d=!0;break}}return r.push("```"),d&&r.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),r}import we from"picocolors";var i={info:e=>console.log(we.cyan("\u2139"),e),success:e=>console.log(we.green("\u2713"),e),warn:e=>console.log(we.yellow("\u26A0"),e),error:e=>console.error(we.red("\u2717"),e),step:e=>console.log(we.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
15
- `+we.bold(we.cyan(e))),detail:e=>console.log(we.dim(" "+e))};var so="https://registry.npmjs.org/klaudius/latest";async function io(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(so,{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 oo(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 Ot(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await io();!n||!oo(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 ro}from"crypto";import{hostname as ls,userInfo as ao,platform as cs,arch as ds}from"os";var lo="https://klaudius.dev",co="/api/licenses/validate",uo="0.34.1";async function us(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??lo).replace(/\/$/,"")+co,o=st(),r;try{r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:ls(),os:`${cs()}-${ds()}`,cli_version:uo})})}catch(d){return{ok:!1,reason:`Could not reach the Klaudius license server (${I(d)}). 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 st(){let e=[ls(),ao().username,cs(),ds()].join("|");return ro("sha256").update(e).digest("hex").slice(0,32)}import{readFile as po}from"fs/promises";import{join as fo}from"path";async function Me(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 ps(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function vt(e){let t;try{t=await po(fo(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:go(s.status,o)}}catch(s){return{ok:!1,message:`Schema apply failed: ${I(s)}`}}}function ho(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 mo(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 Lt(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{clientsColumns:s,tables:o}=ho(e.sql),r=[];s.length>0&&r.push({path:`clients?select=${s.join(",")}&limit=0`,label:"clients columns"});for(let d of o)d!=="clients"&&r.push({path:`${d}?select=*&limit=0`,label:`${d} table`});let a=[];try{for(let d of r){let c=await fetch(`${t}/rest/v1/${d.path}`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(c.ok)continue;let p=mo(c.status,await c.text());if(p.missing){a.push(d.label);continue}return{ok:!1,missing:a,unreachable:`HTTP ${c.status}${p.code?` ${p.code}`:""}`}}}catch(d){return{ok:!1,missing:a,unreachable:I(d)}}return{ok:a.length===0,missing:a}}function go(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 yo(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 wo(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&&yo(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 De(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,...wo(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 fs="https://api.cloudflare.com/client/v4";function hs(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Fe(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${fs}/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})`:""}. ${hs(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(`${fs}/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:hs(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 ms="https://api.netlify.com/api/v1";async function Ue(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${ms}/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(`${ms}/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 ko(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 He(e){let t=Tn(e);if(t)return{ok:!1,message:t};let n=ge(e),s=n.value,o=r=>{let a=[r],d=In(e);return d&&a.push(d),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 d=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(d))?{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(ko(r.status,d))}:{ok:!1,message:o(`Google API returned HTTP ${r.status}${d?`: ${d}`:""}.`)}}catch(r){return{ok:!1,message:`Could not reach Google: ${I(r)}`}}}import Ao from"nodemailer";import{ImapFlow as Eo}from"imapflow";function Po(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function gs(e,t,n){let s=t.toLowerCase(),o=e.filter(Po);if(o.some(d=>d.path.toLowerCase()===s))return;let r=s.startsWith("inbox")?void 0:[`inbox.${s}`,`inbox/${s}`],a=o.find(d=>d.specialUse===n)?.path??(r&&o.find(d=>r.includes(d.path.toLowerCase()))?.path);return{configured:t,detected:a||void 0}}function nn(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 pe(e){let t=Ao.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:ys(a,"SMTP",e.usesAccountPassword,e.knownProvider),failureKind:nn(a)}}finally{t.close()}let n=new Eo({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=gs(a,e.sentFolder,"\\Sent")),e.draftsFolder&&(o=gs(a,e.draftsFolder,"\\Drafts"))}catch{r=!0}await n.logout()}catch(a){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:ys(a,"IMAP",e.usesAccountPassword,e.knownProvider),failureKind:nn(a)}}return{ok:!0,sentFolderIssue:s,draftsFolderIssue:o,foldersUnverified:r}}function ys(e,t,n,s){let o=e instanceof Error?e.message:String(e),r=o.toLowerCase();return nn(e)==="auth"||r.includes("invalid credentials")||r.includes("authentication failed")||r.includes("auth failed")||r.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
12
+ `}function Eo(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 te(e){let t={};for(let n of e.split(`
13
+ `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.indexOf("=");if(s===-1)continue;let o=i.slice(0,s).trim(),r=Eo(i.slice(s+1).trim());t[o]=r}return t}var ui=["VERCEL_TOKEN","CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","NETLIFY_AUTH_TOKEN","EMAIL_PROVIDER","EMAIL_AUTH","EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT","SMS_PROVIDER","TEST_PHONE","TWILIO_ACCOUNT_SID","TWILIO_AUTH_TOKEN","TWILIO_PHONE_NUMBER","WHATSAPP_ACCOUNTS","LETTER_PROVIDER","PINGEN_CLIENT_ID","PINGEN_CLIENT_SECRET","PINGEN_ORG_ID","POSTGRID_API_KEY","NOTIFY_CHANNEL","TELEGRAM_BOT_TOKEN","TELEGRAM_CHAT_ID"];function pi(e,t,n={}){let i={...e},s=u=>(t[u]??"").trim()!=="";if(!s("PRICING_TERMS")&&(s("PRICING")||s("PRICING_MONTHLY"))){let u=zn(Ot(t.PRICING,i.countryCode)??"",Ot(t.PRICING_MONTHLY,i.countryCode)??"");i.pricing=u.pricing,i.pricingTerms=u.pricingTerms,i.pricingMonthly=u.pricingMonthly}i.signature&&i.name&&i.signature.trim()===i.name.trim()&&(i.signature=void 0),s("EMAIL_FROM_NAME")||(i.emailFromName=i.name?.trim()&&i.emailAddress?.trim()?i.name.trim():void 0);let o=i.emailProvider&&i.emailProvider!=="custom"?ce[i.emailProvider]:void 0,r=ut(n)===i.emailProvider&&(n.EMAIL_ADDRESS??"").trim().toLowerCase()===(i.emailAddress??"").trim().toLowerCase(),c=[["EMAIL_SENT_FOLDER","emailSentFolder",o?.sentFolder],["EMAIL_DRAFTS_FOLDER","emailDraftsFolder",o?.draftsFolder],["EMAIL_INBOX_FOLDER","emailInboxFolder",o?.inboxFolder]];for(let[u,p,d]of c)s(u)||r&&(n[u]??"").trim()||(i[p]=d);return i}function fi(e){let t=c=>{let u=e[c];if(!u)return;let p=parseInt(u,10);return isNaN(p)?void 0:p},n=e.SMS_PROVIDER,i=c=>c==="email"||c==="sms"||c==="whatsapp"||c==="letter",s=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(i),o=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(i),r=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:si(e.AI_AGENT)??gn,aiPlan:$t(e.AI_PLAN),qaPhase:Lt(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(c=>c.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:s&&s.length>0?s:void 0,outreachPriority:o&&o.length>0?o:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailProvider:ut(e),emailAuth:ai(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:mn(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:oi(e.DEPLOY_PROVIDER)??wn,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:ri(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function Ft(e){let t=S=>{let I=e[S];if(!I)return;let N=parseInt(I,10);return isNaN(N)?void 0:N},n=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),s=e.SUPABASE_PAT?.replace(/\s+/g,""),o=e.SUPABASE_PROJECT_REF,r=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",u=oi(e.DEPLOY_PROVIDER)??wn,p=e.VERCEL_TOKEN,d=e.CLOUDFLARE_API_TOKEN,y=e.CLOUDFLARE_ACCOUNT_ID,f=e.NETLIFY_AUTH_TOKEN,A=e.SELFHOST_DEPLOY_TARGET,h=e.SELFHOST_URL_TEMPLATE;if(!r||!n||!i||!s||!o||!(u==="cloudflare"?!!d&&!!y:u==="netlify"?!!f:u==="selfhost"?!!A&&!!h:!!p))return null;let P=e.SMS_PROVIDER,R=S=>S==="email"||S==="sms"||S==="whatsapp"||S==="letter",x=e.OUTREACH_CHANNELS?.split(",").map(S=>S.trim()).filter(R),v=e.OUTREACH_PRIORITY?.split(",").map(S=>S.trim()).filter(R),L=e.WHATSAPP_ACCOUNTS?.split(",").map(S=>S.trim()).filter(S=>S.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:si(e.AI_AGENT)??gn,aiPlan:$t(e.AI_PLAN),qaPhase:Lt(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(S=>S.trim().toLowerCase()).filter(Boolean):void 0,pricing:r,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:x&&x.length>0?x:void 0,outreachPriority:v&&v.length>0?v:void 0,whatsappAccounts:L&&L.length>0?L:void 0,emailProvider:ut(e),emailAuth:ai(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:P==="imessage"||P==="twilio"?P:void 0,testPhone:mn(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:u,vercelToken:p,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:d||void 0,cloudflareAccountId:y||void 0,netlifyAuthToken:f||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:A||void 0,selfhostUrlTemplate:h||void 0,supabaseUrl:n,supabaseServiceKey:i,supabasePat:s,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:o,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:ri(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as rc,mkdir as ac,readdir as Ro,stat as lc}from"fs/promises";import{dirname as dc,join as Pi,relative as vo,sep as xo}from"path";import{fileURLToPath as pc}from"url";import{createHash as hi}from"crypto";import{readFile as Po}from"fs/promises";async function ge(e){let t=await Po(e);return hi("sha256").update(t).digest("hex")}function kn(e){return hi("sha256").update(e).digest("hex")}import{mkdir as To,readFile as _o,access as Io}from"fs/promises";import{dirname as Co,join as wi}from"path";import{chmod as mi,rename as bo,unlink as So,writeFile as gi}from"fs/promises";var yi=new Set(["EPERM","EACCES","EBUSY"]);async function pt(e,t,n){let i=`${e}.${process.pid}-${Date.now()}.tmp`;await gi(i,t);for(let s=1;;s++)try{await bo(i,e),n!==void 0&&await mi(e,n).catch(()=>{});return}catch(o){let r=o.code??"";if(yi.has(r)&&s<5){await new Promise(c=>setTimeout(c,50*s));continue}if(await So(i).catch(()=>{}),!yi.has(r))throw o;await gi(e,t),n!==void 0&&await mi(e,n).catch(()=>{});return}}var ft=".klaudius",ki=`${ft}/manifest.json`,Ut=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json"]),Ai=new Set(["clients/README.md"]),Ht=new Set(["package-lock.json"]);async function jt(e){let t=wi(e,ki);try{await Io(t)}catch{return null}let n=await _o(t,"utf-8"),i=JSON.parse(n),s={};for(let[o,r]of Object.entries(i.files??{}))s[o.split("\\").join("/")]=r;return i.files=s,Array.isArray(i.ignored)?i.ignored=i.ignored.filter(o=>typeof o=="string").map(o=>o.split("\\").join("/")):delete i.ignored,i}async function xe(e,t){let n=wi(e,ki);await To(Co(n),{recursive:!0}),await pt(n,JSON.stringify(t,null,2)+`
14
+ `)}function Ei(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function De(e,t=e){let n=await Ro(e,{withFileTypes:!0}),i=[];for(let s of n){let o=Pi(e,s.name);s.name===".klaudius"&&e===t||(s.isDirectory()?i.push(...await De(o,t)):s.isFile()&&i.push(vo(t,o).split(xo).join("/")))}return i}async function bi(e){let t=await De(e),n={};for(let i of t)Ut.has(i)||(n[i]=await ge(Pi(e,i)));return n}import{copyFile as Oo,mkdir as Si,mkdtemp as $o,readdir as Ti,rm as _i}from"fs/promises";import{tmpdir as Lo}from"os";import{dirname as No,join as Kt}from"path";import{Readable as Mo}from"stream";import*as Ii from"tar";var Do="https://klaudius.dev/api/template";function Fo(e){return Mo.fromWeb(e)}async function Gt(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Do,n="0.35.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(c){throw new Error(`Could not reach klaudius.dev to download the template: ${H(c)}`)}if(!i.ok){let c="";try{let u=await i.json();c=u.reason?` (${u.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${i.status}${c}`)}if(!i.body)throw new Error("Template download succeeded but response had no body");let s=i.headers.get("x-klaudius-tier"),o=await $o(Kt(Lo(),"klaudius-template-")),r=0;try{try{await new Promise((p,d)=>{let y=Ii.extract({cwd:o,strict:!0});y.on("finish",p),y.on("error",d),Fo(i.body).on("error",d).pipe(y)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await Si(e.destDir,{recursive:!0});let c=new Set(await Ti(e.destDir)),u=await De(o);try{for(let p of u){let d=Kt(e.destDir,p);await Si(No(d),{recursive:!0}),await Oo(Kt(o,p),d),r++}}catch(p){let d=await Ti(e.destDir).catch(()=>[]);for(let y of d)c.has(y)||await _i(Kt(e.destDir,y),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await _i(o,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:r,tier:s}}import{copyFile as Uo,mkdir as Ci,readFile as An,rm as Ho,writeFile as jo}from"fs/promises";import{dirname as Ko,join as Se}from"path";import{structuredPatch as Go}from"diff";var ht=Se(".klaudius","base"),Te=Se(".klaudius","conflict-base"),Ri=".klaudius-snapshot-id";async function Bt(e,t,n,i){let s=Se(e,ht);await Ho(s,{recursive:!0,force:!0}),await Ci(s,{recursive:!0});for(let o of n){let r=Se(s,o);await Ci(Ko(r),{recursive:!0}),await Uo(Se(t,o),r)}i!==void 0&&await jo(Se(s,Ri),i,"utf-8")}async function vi(e){try{return(await An(Se(e,ht,Ri),"utf-8")).trim()}catch{return null}}async function xi(e,t){try{return await An(Se(e,ht,t),"utf-8")}catch{return null}}async function Oi(e,t){try{return await An(Se(e,Te,t),"utf-8")}catch{return null}}function $i(e,t,n,i){return!i||Oe(n)?null:e!==null&&!Oe(e)&&kn(e)===i?e:t!==null&&!Oe(t)&&kn(t)===i?t:null}function Oe(e){return e.includes("\0")||e.includes("\uFFFD")}function Li(e,t,n=60){let i=Go("base","new",e,t,"","",{context:2});if(i.hunks.length===0)return["Upstream content is identical to your base for this file."];let s=i.hunks.map(u=>`${u.newStart}-${u.newStart+Math.max(u.newLines-1,0)}`).join(", "),o=[`Upstream changed ${i.hunks.length} hunk(s) (new-version lines ${s}):`,"","```diff"],r=0,c=!1;for(let u of i.hunks){if(r>=n){c=!0;break}o.push(`@@ -${u.oldStart},${u.oldLines} +${u.newStart},${u.newLines} @@`),r+=1;let p=Math.max(n-r,0),d=u.lines.slice(0,p);if(o.push(...d),r+=d.length,d.length<u.lines.length){c=!0;break}}return o.push("```"),c&&o.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),o}import $e from"picocolors";var a={info:e=>console.log($e.cyan("\u2139"),e),success:e=>console.log($e.green("\u2713"),e),warn:e=>console.log($e.yellow("\u26A0"),e),error:e=>console.error($e.red("\u2717"),e),step:e=>console.log($e.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
15
+ `+$e.bold($e.cyan(e))),detail:e=>console.log($e.dim(" "+e))};var Bo="https://registry.npmjs.org/klaudius/latest";async function Vo(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Bo,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let s=await i.json();return typeof s.version=="string"?s.version:null}catch{return null}finally{clearTimeout(n)}}function Yo(e,t){let n=o=>o.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),i=n(e),s=n(t);if(i.length<3||s.length<3)return!1;for(let o=0;o<3;o++){if(Number.isNaN(i[o])||Number.isNaN(s[o]))return!1;if(i[o]>s[o])return!0;if(i[o]<s[o])return!1}return!1}async function Vt(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Vo();!n||!Yo(n,t)||(a.blank(),a.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(a.detail("Your project content is fetched fresh either way, so you're not missing any"),a.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),a.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),a.blank())}import{createHash as Wo}from"crypto";import{hostname as Ni,userInfo as qo,platform as Mi,arch as Di}from"os";var zo="https://klaudius.dev",Jo="/api/licenses/validate",Qo="0.35.0";async function Fi(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??zo).replace(/\/$/,"")+Jo,s=mt(),o;try{o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:s,hostname:Ni(),os:`${Mi()}-${Di()}`,cli_version:Qo})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${H(c)}). Check your internet connection or try again later.`}}let r;try{r=await o.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${o.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${o.status}).`}}function mt(){let e=[Ni(),qo().username,Mi(),Di()].join("|");return Wo("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Xo}from"fs/promises";import{join as Zo}from"path";async function We(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: ${H(n)}`}}}function Ui(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function Yt(e){let t;try{t=await Xo(Zo(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 s=await i.text();return{ok:!1,message:nr(i.status,s)}}catch(i){return{ok:!1,message:`Schema apply failed: ${H(i)}`}}}function er(e){let t=[...e.matchAll(/ALTER TABLE clients ADD COLUMN IF NOT EXISTS (\w+)/g)].map(i=>i[1]),n=[...e.matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/g)].map(i=>i[1]);return{clientsColumns:[...new Set(t)],tables:[...new Set(n)]}}function tr(e,t){let n="";try{let s=JSON.parse(t);s&&typeof s.code=="string"&&(n=s.code)}catch{}return{missing:e===400&&n==="42703"||e===404&&(n==="PGRST205"||n==="42P01"),code:n}}async function Wt(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{clientsColumns:i,tables:s}=er(e.sql),o=[];i.length>0&&o.push({path:`clients?select=${i.join(",")}&limit=0`,label:"clients columns"});for(let c of s)c!=="clients"&&o.push({path:`${c}?select=*&limit=0`,label:`${c} table`});let r=[];try{for(let c of o){let u=await fetch(`${t}/rest/v1/${c.path}`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(u.ok)continue;let p=tr(u.status,await u.text());if(p.missing){r.push(c.label);continue}return{ok:!1,missing:r,unreachable:`HTTP ${u.status}${p.code?` ${p.code}`:""}`}}}catch(c){return{ok:!1,missing:r,unreachable:H(c)}}return{ok:r.length===0,missing:r}}function nr(e,t){let n=t;try{let i=JSON.parse(t);i&&typeof i.message=="string"&&(n=i.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 ir(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 sr(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&&ir(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 qe(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,...sr(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: ${H(t)}`}}}var Hi="https://api.cloudflare.com/client/v4";function ji(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ze(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let s=await fetch(`${Hi}/user/tokens/verify`,{headers:i});if(s.status===401||s.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} verifying the token. Try again or check cloudflarestatus.com.`};let o=await s.json(),r=o.result?.status;if(o.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${ji(o)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}try{let s=await fetch(`${Hi}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:i});if(s.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(s.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(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let o=await s.json();return o.success===!1?{ok:!1,message:ji(o)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(o.result)?o.result.length:void 0}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}}var Ki="https://api.netlify.com/api/v1";async function Je(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${Ki}/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: ${H(i)}`}}try{let i=await fetch(`${Ki}/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 s=await i.json(),o=Array.isArray(s)?s:[];if(o.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 r=typeof o[0]?.slug=="string"?o[0].slug:void 0;return{ok:!0,accountCount:o.length,accountSlug:r}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${H(i)}`}}}function or(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 Qe(e){let t=Jn(e);if(t)return{ok:!1,message:t};let n=Re(e),i=n.value,s=o=>{let r=[o],c=Qn(e);return c&&r.push(c),n.repairs.length>0&&r.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.`),r.join(`
16
+ `)};try{let o=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(o.ok)return{ok:!0};if(o.status===429)return{ok:!0};let r={};try{r=await o.json()}catch{}let c=r.error?.message??"",u=r.error?.status??"";return o.status===400&&(u==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(c))?{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.)"}:o.status===401||o.status===403?{ok:!1,message:s(or(o.status,c))}:{ok:!1,message:s(`Google API returned HTTP ${o.status}${c?`: ${c}`:""}.`)}}catch(o){return{ok:!1,message:`Could not reach Google: ${H(o)}`}}}import rr from"nodemailer";import{ImapFlow as ar}from"imapflow";function lr(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function Gi(e,t,n){let i=t.toLowerCase(),s=e.filter(lr);if(s.some(c=>c.path.toLowerCase()===i))return;let o=i.startsWith("inbox")?void 0:[`inbox.${i}`,`inbox/${i}`],r=s.find(c=>c.specialUse===n)?.path??(o&&s.find(c=>o.includes(c.path.toLowerCase()))?.path);return{configured:t,detected:r||void 0}}function En(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 _e(e){let t=rr.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(r){return{ok:!1,failedAt:"smtp",message:Bi(r,"SMTP",e.usesAccountPassword,e.knownProvider),failureKind:En(r)}}finally{t.close()}let n=new ar({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,s,o;try{if(await n.connect(),e.sentFolder||e.draftsFolder)try{let r=await n.list();e.sentFolder&&(i=Gi(r,e.sentFolder,"\\Sent")),e.draftsFolder&&(s=Gi(r,e.draftsFolder,"\\Drafts"))}catch{o=!0}await n.logout()}catch(r){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Bi(r,"IMAP",e.usesAccountPassword,e.knownProvider),failureKind:En(r)}}return{ok:!0,sentFolderIssue:i,draftsFolderIssue:s,foldersUnverified:o}}function Bi(e,t,n,i){let s=e instanceof Error?e.message:String(e),o=s.toLowerCase();return En(e)==="auth"||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
20
- access is enabled and 2FA is off in your provider's settings.`:s===!1?`${t} rejected the credentials. Most common causes:
20
+ access is enabled and 2FA is off in your provider's settings.`:i===!1?`${t} rejected the credentials. Most common causes:
21
21
  \u2022 The password is wrong or mistyped. Signing in to the mailbox's webmail
22
22
  with it is a quick way to check.
23
23
  \u2022 The email address isn't this mailbox's login name.
@@ -28,112 +28,119 @@ import{b as Pe,c as ut,d as Q,e as I,f as Sn,g as bn,h as pt,i as ft,j as _n,k a
28
28
  \u2022 The address is an alias (e.g. a Google Workspace alias domain) \u2014 the
29
29
  sign-in must use the account's primary address. Keep the alias as
30
30
  EMAIL_ADDRESS and set EMAIL_LOGIN in .env to the primary address.
31
- \u2022 2FA is required but no app-specific password was generated.`:r.includes("etimedout")||r.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:r.includes("enotfound")||r.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${o}`}import*as Nt from"@clack/prompts";var So=[{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 $t(e,t,n){let s=!1;for(let o of So){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 Nt.confirm({message:`Use "${r.detected}" instead?`,initialValue:!0});if(Nt.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 ws(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 Mt(e){return e.provider==="pingen"?bo(e):_o(e)}async function bo(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 _o(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 To}from"child_process";async function ks(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 Io(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 Io(e){return new Promise(t=>{let n=To("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 Dt}from"child_process";import{existsSync as Co}from"fs";import{homedir as Ro}from"os";function xo(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var je=2,As=2e3,Oo=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Es(e,t){let n=e+`
32
- `+t;return Oo.some(s=>s.test(n))}function Ps(e){return new Promise(t=>setTimeout(t,e))}function vo(e,t,n){return new Promise(s=>{let o=n.shell?Dt([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):Dt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),r="",a="";o.stdout?.on("data",d=>{let c=d.toString();r+=c,process.stdout.write(c)}),o.stderr?.on("data",d=>{let c=d.toString();a+=c,process.stderr.write(c)}),o.on("close",d=>s({code:d??1,stdout:r,stderr:a})),o.on("error",d=>s({code:1,stdout:r,stderr:a+d.message}))})}async function sn(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=je;o++){if(s=await vo(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!Es(s.stderr,s.stdout))return s;o<je&&(i.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${je+1})\u2026`),await Ps(As))}return s}function Lo(e,t,n){return new Promise(s=>{let o=Dt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",d=>{r+=d.toString()}),o.stderr?.on("data",d=>{a+=d.toString()}),o.on("close",d=>s({code:d??1,stdout:r,stderr:a})),o.on("error",d=>s({code:1,stdout:r,stderr:a+d.message}))})}var No=[{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 $o(e){let t=`${e.stderr??""}
33
- ${e.stdout??""}`;return No.find(s=>s.pattern.test(t))?.hint}async function Mo(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await W())?.command??["python3"],r=async d=>{let c={code:0,stdout:"",stderr:""};for(let p=0;p<=je;p++){if(c=await Lo(o[0],[...o.slice(1),...d],{cwd:e}),c.code===0||!Es(c.stderr,c.stdout))return c;p<je&&(i.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${je+1})\u2026`),await Ps(As))}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 Ft(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=xo(),s=process.platform==="win32",o;if(s){let u=xe([{label:"your Windows user folder",path:Ro()},{label:"the project folder",path:e}]);if(u.length>0){let A=await new Promise(T=>{let m=Dt("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),l="",S="";m.stdout?.on("data",C=>{l+=C.toString()}),m.stderr?.on("data",C=>{S+=C.toString()}),m.on("close",C=>T({code:C??1,stdout:l,stderr:S})),m.on("error",C=>T({code:1,stdout:l,stderr:C.message}))}),P=A.code===0?A.stdout.trim():void 0;if(!Oe(P,Co)){let{detail:T,action:m}=ve(u,"install");o=`${T}. ${m}`}}}let r=(u,A)=>{let P=$o(A);if(P){(t.hints??={})[u]=P;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 sn("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 d=await Mo(e);t.pip=d.code===0?"ok":"failed",d.code!==0&&r("pip",d),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await sn("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 p=await sn("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:s});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&r("patchright",p),t}import{copyFile as Do,access as Fo}from"fs/promises";import{dirname as Uo,join as Ho}from"path";async function Ss(){let e=await gt("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 on(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await Ss();if(e.state==="real")return{status:"ok",version:e.version};let t=await W();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function jo(e){let[t,...n]=e.command,s=await gt(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=Ho(Uo(o),"python3.exe"),a=await Fo(r).then(()=>!0,()=>!1);if(!a){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await Do(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let d=await Ss();return{ok:!0,target:r,created:!a,verified:d.state==="real",postState:d.state==="real"?void 0:d.state}}var Ko="A real python3.exe now exists, but the Microsoft Store placeholder still shadows it. Turn OFF both `python.exe` and `python3.exe` under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases, then open a fresh terminal.";async function Ut(){let e=await on();if(e.status!=="broken")return;let t=await jo(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(Ko);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 Go,spawnSync as bs}from"child_process";import{mkdtemp as Bo,rm as Vo,rmdir as Yo,writeFile as Wo,stat as rn,unlink as qo,mkdir as zo}from"fs/promises";import{createServer as Qo}from"net";import{tmpdir as Jo}from"os";import{join as Ke}from"path";function Xo(){return new Promise((e,t)=>{let n=Qo();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 Ht(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?bs(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):bs("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function jt(e){try{return await Zo(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Zo(e){let t=`klaudius-smoke-${process.pid}`,n=Ke(".klaudius",`qa-smoke-${process.pid}.png`),s=Ke(e,n),o,r,a=!1;try{o=await Bo(Ke(Jo(),"klaudius-qa-smoke-")),await Wo(Ke(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let d=await Xo();r=Go("python3",["-m","http.server",String(d),"--directory",o],{stdio:"ignore",shell:!1});let c=!1;r.on("error",()=>{c=!0}),r.on("exit",()=>{c=!0});let p=`http://127.0.0.1:${d}/`,u=!1;for(let S=0;S<24&&!c;S++)try{if((await fetch(p,{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=Ke(e,".klaudius"),P=await rn(A).then(()=>!0,()=>!1);await zo(A,{recursive:!0}),a=!P;let T=Ht(e,[`-s=${t}`,"open",p]);if(T.status!==0)return{ok:!1,stage:"browser",detail:((T.stderr??"")+(T.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 m=Ht(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await rn(s).catch(()=>null);if((!l||l.size===0)&&(m=Ht(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await rn(s).catch(()=>null)),!l||l.size===0){let S=((m.stderr??"")+(m.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{Ht(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await qo(s).catch(()=>{}),a&&await Yo(Ke(e,".klaudius")).catch(()=>{}),o&&await Vo(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as _s,readFile as er,writeFile as Ts}from"fs/promises";import{join as Kt}from"path";var Ge="Bash(claude --bg --permission-mode auto *)";async function Is(e){let t;try{t=await er(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 Be(e,t){let n=Kt(e,".claude"),s=Kt(n,"settings.local.json"),o=".claude/settings.local.json";try{await _s(n,{recursive:!0});let r=await Is(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:{},d=a.allow,c=Array.isArray(d)?d.filter(u=>typeof u=="string"):[];if(c.includes(t))return"present";c.push(t);let p={...r,permissions:{...a,allow:c}};return await Ts(s,JSON.stringify(p,null,2)+`
34
- `,"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 Gt(e,t){let n=Kt(e,".claude");await _s(n,{recursive:!0});let s=Kt(n,"settings.json"),o=await Is(s)??{},r=o.enabledMcpjsonServers,a=Array.isArray(r)?r.filter(c=>typeof c=="string"):[];a.includes(t)||a.push(t);let d={...o,enabledMcpjsonServers:a};await Ts(s,JSON.stringify(d,null,2)+`
35
- `,"utf-8")}var Rs="0.34.1",$=5,x=!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)}function an(e){return j(e,tt,"setup-pending")}function ln(e){return j(e,tt,"ms-signin.json")}async function xs(e){return Ve(j(e,".ms-token.json"),"utf-8").then(t=>String(JSON.parse(t).account?.address??"")).then(t=>t.trim().toLowerCase()).catch(()=>"")}function or(e){let t=process.env.KLAUDIUS_WHATSAPP_STATE_DIR||j(vs(),".klaudius","whatsapp");return tr(j(t,e,"auth","creds.json"))}async function rr(e){let t;try{t=await Ve(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 V(t)}function fe(e){return`npx klaudius@latest init ${Yt(Ye(e))}`}function Ye(e){if(process.platform==="win32")return e;let t=vs();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function ar(e){let t=[];try{let s=(await Os(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let r=j(e,o.name);if(!await Vt(j(r,".env")))continue;let a=await Vt(j(r,".klaudius","manifest.json"));if(t.push({path:r,finished:a}),t.length>=3)break}}catch{}return t}async function Vt(e){try{return await cn(e),!0}catch{return!1}}function Yt(e){return/\s/.test(e)?`"${e}"`:e}function re(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(` ${h.cyan(fe(e))}`),i.blank(),i.detail(` (Your .env is at ${Ye(j(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 Ls(e){let t=e.target??".",n=sr(t)?t:nr(process.cwd(),t),s=ur(n);s&&(i.error("Klaudius can't be installed inside a protected system folder."),i.detail(`Path: ${n}`),i.detail(`Reason: ${s}`),i.blank(),i.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),i.blank(),process.platform==="win32"?(i.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${h.cyan("cd $HOME\\Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)):(i.detail("For example:"),console.log(` ${h.cyan("cd ~/Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)),i.blank(),process.exit(1)),process.platform==="win32"&&pr()&&(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 Ot("init",Rs);let o=await lr(n),r=o.kind==="scaffolded"&&!!e.answers&&await Vt(an(n));if(o.kind==="scaffolded"&&!r){i.blank(),i.warn(`Found an existing Klaudius project at ${h.bold(n)}.`),i.detail("(Your .env and project files are in place.)"),i.blank(),o.nodeModulesMissing?(i.detail("It looks like a previous setup didn't finish installing dependencies."),i.detail("To pick up where it left off, run:"),i.blank(),n!==process.cwd()&&console.log(` ${h.cyan(`cd ${Yt(t)}`)}`),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retries npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Everything is scaffolded and dependencies look installed."),i.detail("Pick the action you wanted:"),i.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${h.cyan("npx klaudius@latest configure")} ${h.dim("# change a credential / API key")}`),console.log(` ${h.cyan("npx klaudius@latest update")} ${h.dim("# pull the latest skills, scripts, lessons")}`),i.blank()),i.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),i.blank();return}if(o.kind==="occupied"){let f=t===".",y=await ar(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: ${Ye(n)}`),i.blank();for(let g of y)i.detail(g.finished?`Found a finished project at ${Ye(g.path)}. To work in it:`:`Found an unfinished setup at ${Ye(g.path)}. To pick up where it left off:`),i.blank(),g.finished?(console.log(` ${h.cyan(`cd ${Ye(g.path)}`)}`),console.log(` ${h.cyan("claude")} ${h.dim("# open Claude Code in the project")}`)):console.log(` ${h.cyan(fe(g.path))} ${h.dim("# then pick Resume")}`),i.blank();process.exit(1)}i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),i.blank(),f?(i.detail("Two ways forward:"),i.blank(),i.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`),i.blank(),i.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${h.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(i.detail(`The folder '${t}' already exists and isn't empty.`),i.detail("Either pick a different name:"),console.log(` ${h.cyan(`npx klaudius@latest init ${t}-2`)}`),i.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=null;e.answers&&(x=!0,a=await rr(e.answers),i.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let d=a??{},c={};if(a){let f=await Ve(j(n,".env"),"utf-8").catch(()=>null);f&&(c=V(f),a={...Object.fromEntries(Object.entries(c).filter(([g])=>!jn.includes(g))),...a})}let p=e.license??a?.KLAUDIUS_LICENSE_KEY;x&&(!p||p.trim().length===0)&&H("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let u=await dr(p),A=E.spinner();A.start("Validating license");let P=await us(u);P.ok||(A.stop(`License invalid: ${P.reason??"unknown"}`,2),i.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),x&&H("license",`${P.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)),A.stop(`License valid (${P.tier??"core"} tier)`);let T=await Le();T.ok||(i.error(T.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${fe(n)}`),process.exit(1)),await Ut();let m=ye();m.ok||(i.error(m.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${fe(n)}`),process.exit(1));let l,S=!1;if(a){let f=bt(a);f||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."),l=Kn(f,d,c),i.success("Loaded setup answers (non-interactive mode)");let y=c.AI_AGENT==="codex"?"codex":"claude-code";if(r&&y!==(l.aiAgent??"claude-code")){let g=k=>k==="codex"?"Codex":"Claude Code";H("install",`This folder was set up for ${g(y)}, so it can't carry on as ${g(l.aiAgent??"claude-code")}. Give the folder a different name to set up fresh, or switch back.`)}}else if(o.kind==="partial")if(await cr(n)==="resume"){let y=await Ve(o.envPath,"utf-8"),g=bt(V(y));g?(i.success("Resuming with values from your existing .env"),i.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=g,S=!0,l.aiPlan||(l=await F(l,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
36
- 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."),l=await F())}else{let y=await Ve(o.envPath,"utf-8"),g=bt(V(y));l=await F(g??{})}else l=await F();l.licenseKey=u,await U(n,l),S||(i.success("Saved .env"),i.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let f=1;;f++){let y=E.spinner();y.start("Validating Supabase credentials");let g=await Me({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(g.ok){y.stop("Supabase credentials accepted");break}y.stop(g.message??"Supabase check failed",2),f>=$&&re(n,"Supabase",g.message??"Supabase check failed");let k=g.message??"Supabase check failed";i.blank(),x&&H("supabase",k),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
37
- ${k}
31
+ \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 qt from"@clack/prompts";var cr=[{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 zt(e,t,n){let i=!1;for(let s of cr){let o=s.issue(e);if(o){if(a.blank(),o.detected){if(n.nonInteractive){t[s.key]=o.detected,i=!0,a.warn(`Your mailbox has no "${o.configured}" folder \u2014 it calls its ${s.label} folder "${o.detected}". Using that.`);continue}a.warn(`Your mailbox has no "${o.configured}" folder.`),a.detail(`It calls its ${s.label} folder "${o.detected}".`);let r=await qt.confirm({message:`Use "${o.detected}" instead?`,initialValue:!0});if(qt.isCancel(r))return n.onCancel?.(),i;r?(t[s.key]=o.detected,i=!0,a.success(`${s.envKey} set to "${o.detected}"`)):a.warn(`Keeping "${o.configured}". ${s.consequence}`);continue}a.warn(`Your mailbox has no "${o.configured}" folder. ${s.consequence}`),a.detail(`After setup, ask your AI agent to list the mailbox's folders and set ${s.envKey} in .env to the real name.`)}}return i}async function Vi(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 s=await i.json();return s.status&&s.status!=="active"?{ok:!1,message:`Twilio account is in '${s.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:s.friendly_name}}catch(i){return{ok:!1,message:`Could not reach Twilio: ${H(i)}`}}}async function Jt(e){return e.provider==="pingen"?dr(e):ur(e)}async function dr(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 s=(await i.json()).access_token;if(!s)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let o=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${s}`}});return o.status===403||o.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"}:o.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${o.status}. Try again shortly.`}}catch(i){return{ok:!1,message:`Could not reach Pingen: ${H(i)}`}}}async function ur(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: ${H(t)}`}}}import{spawn as pr}from"child_process";async function Yi(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 fr(n);if(i.code===0)return{ok:!0};let s=i.stderr.toLowerCase();return s.includes("can't get application")||s.includes("isn't running")||s.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."}:s.includes("(-1728)")||s.includes("not found")||s.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.`}:s.includes("(-1719)")||s.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 fr(e){return new Promise(t=>{let n=pr("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),i="";n.stderr.on("data",s=>{i+=s.toString()}),n.on("close",s=>t({code:s??1,stderr:i})),n.on("error",s=>t({code:1,stderr:s.message}))})}import{spawn as Qt}from"child_process";import{existsSync as hr}from"fs";import{homedir as mr}from"os";function gr(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var Xe=2,Wi=2e3,yr=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function qi(e,t){let n=e+`
32
+ `+t;return yr.some(i=>i.test(n))}function zi(e){return new Promise(t=>setTimeout(t,e))}function wr(e,t,n){return new Promise(i=>{let s=n.shell?Qt([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):Qt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),o="",r="";s.stdout?.on("data",c=>{let u=c.toString();o+=u,process.stdout.write(u)}),s.stderr?.on("data",c=>{let u=c.toString();r+=u,process.stderr.write(u)}),s.on("close",c=>i({code:c??1,stdout:o,stderr:r})),s.on("error",c=>i({code:1,stdout:o,stderr:r+c.message}))})}async function Pn(e,t,n){let i={code:0,stdout:"",stderr:""};for(let s=0;s<=Xe;s++){if(i=await wr(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!qi(i.stderr,i.stdout))return i;s<Xe&&(a.detail(`${n.label} failed with a transient network error \u2014 retrying (${s+2}/${Xe+1})\u2026`),await zi(Wi))}return i}function kr(e,t,n){return new Promise(i=>{let s=Qt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",c=>{o+=c.toString()}),s.stderr?.on("data",c=>{r+=c.toString()}),s.on("close",c=>i({code:c??1,stdout:o,stderr:r})),s.on("error",c=>i({code:1,stdout:o,stderr:r+c.message}))})}var Ar=[{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 Er(e){let t=`${e.stderr??""}
33
+ ${e.stdout??""}`;return Ar.find(i=>i.pattern.test(t))?.hint}async function Pr(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],s=(await se())?.command??["python3"],o=async c=>{let u={code:0,stdout:"",stderr:""};for(let p=0;p<=Xe;p++){if(u=await kr(s[0],[...s.slice(1),...c],{cwd:e}),u.code===0||!qi(u.stderr,u.stdout))return u;p<Xe&&(a.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${Xe+1})\u2026`),await zi(Wi))}return u},r=await o([...n,"--break-system-packages",...t]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(a.detail("Older pip detected; retrying without --break-system-packages"),r=await o([...n,...t])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function Xt(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=gr(),i=process.platform==="win32",s;if(i){let d=Ge([{label:"your Windows user folder",path:mr()},{label:"the project folder",path:e}]);if(d.length>0){let y=await new Promise(A=>{let h=Qt("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),l="",P="";h.stdout?.on("data",R=>{l+=R.toString()}),h.stderr?.on("data",R=>{P+=R.toString()}),h.on("close",R=>A({code:R??1,stdout:l,stderr:P})),h.on("error",R=>A({code:1,stdout:l,stderr:R.message}))}),f=y.code===0?y.stdout.trim():void 0;if(!Be(f,hr)){let{detail:A,action:h}=Ve(d,"install");s=`${A}. ${h}`}}}let o=(d,y)=>{let f=Er(y);if(f){(t.hints??={})[d]=f;return}s&&(d==="npm"||d==="playwright"||d==="patchright")&&!Object.values(t.hints??{}).includes(s)&&((t.hints??={})[d]=s)};a.step("Running npm install (Next.js, Playwright JS, etc.)...");let r=await Pn("npm",["install"],{cwd:e,label:"npm install",env:n,shell:i});t.npm=r.code===0?"ok":"failed",r.code!==0&&o("npm",r),a.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let c=await Pr(e);t.pip=c.code===0?"ok":"failed",c.code!==0&&o("pip",c),a.step("Installing Playwright browser (chromium ~200MB; one-time)...");let u=await Pn("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:i});t.playwright=u.code===0?"ok":"failed",u.code!==0&&o("playwright",u),a.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await Pn("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:i});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&o("patchright",p),t}import{copyFile as br,access as Sr}from"fs/promises";import{dirname as Tr,join as _r}from"path";async function Ji(){let e=await vt("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 bn(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await Ji();if(e.state==="real")return{status:"ok",version:e.version};let t=await se();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function Ir(e){let[t,...n]=e.command,i=await vt(t,[...n,"-c","import sys; print(sys.executable)"]),s=i.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(i.code!==0||!s)return{ok:!1,reason:"no-exe-path"};let o=_r(Tr(s),"python3.exe"),r=await Sr(o).then(()=>!0,()=>!1);if(!r){if(/[\\/]WindowsApps[\\/]/i.test(o))return{ok:!1,reason:"store-python",target:o};try{await br(s,o)}catch{return{ok:!1,reason:"not-writable",target:o,manualCommand:`copy "${s}" "${o}"`}}}let c=await Ji();return{ok:!0,target:o,created:!r,verified:c.state==="real",postState:c.state==="real"?void 0:c.state}}var Cr="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 Zt(){let e=await bn();if(e.status!=="broken")return;let t=await Ir(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.";a.success(n);return}if(t.ok&&t.postState==="stub"){a.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),a.detail(Cr);return}if(t.ok){a.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."),a.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"){a.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"){a.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),a.detail(t.manualCommand??"");return}a.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 Rr,spawnSync as Qi}from"child_process";import{mkdtemp as vr,rm as xr,rmdir as Or,writeFile as $r,stat as Sn,unlink as Lr,mkdir as Nr}from"fs/promises";import{createServer as Mr}from"net";import{tmpdir as Dr}from"os";import{join as Ze}from"path";function Fr(){return new Promise((e,t)=>{let n=Mr();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let i=n.address(),s=typeof i=="object"&&i?i.port:0;n.close(()=>e(s))})})}function en(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?Qi(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):Qi("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function tn(e){try{return await Ur(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Ur(e){let t=`klaudius-smoke-${process.pid}`,n=Ze(".klaudius",`qa-smoke-${process.pid}.png`),i=Ze(e,n),s,o,r=!1;try{s=await vr(Ze(Dr(),"klaudius-qa-smoke-")),await $r(Ze(s,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let c=await Fr();o=Rr("python3",["-m","http.server",String(c),"--directory",s],{stdio:"ignore",shell:!1});let u=!1;o.on("error",()=>{u=!0}),o.on("exit",()=>{u=!0});let p=`http://127.0.0.1:${c}/`,d=!1;for(let P=0;P<24&&!u;P++)try{if((await fetch(p,{signal:AbortSignal.timeout(1e3)})).ok){d=!0;break}}catch{await new Promise(R=>setTimeout(R,500))}if(!d)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 y=Ze(e,".klaudius"),f=await Sn(y).then(()=>!0,()=>!1);await Nr(y,{recursive:!0}),r=!f;let A=en(e,[`-s=${t}`,"open",p]);if(A.status!==0)return{ok:!1,stage:"browser",detail:((A.stderr??"")+(A.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 h=en(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await Sn(i).catch(()=>null);if((!l||l.size===0)&&(h=en(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await Sn(i).catch(()=>null)),!l||l.size===0){let P=((h.stderr??"")+(h.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${P?` (${P})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{en(e,[`-s=${t}`,"close"]),o&&!o.killed&&o.kill(),await Lr(i).catch(()=>{}),r&&await Or(Ze(e,".klaudius")).catch(()=>{}),s&&await xr(s,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as Xi,readFile as Hr,writeFile as Zi}from"fs/promises";import{join as nn}from"path";var et="Bash(claude --bg --permission-mode auto *)";async function es(e){let t;try{t=await Hr(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 tt(e,t){let n=nn(e,".claude"),i=nn(n,"settings.local.json"),s=".claude/settings.local.json";try{await Xi(n,{recursive:!0});let o=await es(i);if(o===null)return a.warn(`${s} isn't valid JSON, so it was left as-is. Fix it and re-run to pre-approve the parallel-run dispatch.`),"skipped";let r=o.permissions&&typeof o.permissions=="object"&&!Array.isArray(o.permissions)?o.permissions:{},c=r.allow,u=Array.isArray(c)?c.filter(d=>typeof d=="string"):[];if(u.includes(t))return"present";u.push(t);let p={...o,permissions:{...r,allow:u}};return await Zi(i,JSON.stringify(p,null,2)+`
34
+ `,"utf-8"),"added"}catch(o){return a.warn(`Couldn't write ${s} (${o instanceof Error?o.message:String(o)}). The parallel-run dispatch may occasionally ask for approval.`),"skipped"}}async function sn(e,t){let n=nn(e,".claude");await Xi(n,{recursive:!0});let i=nn(n,"settings.json"),s=await es(i)??{},o=s.enabledMcpjsonServers,r=Array.isArray(o)?o.filter(u=>typeof u=="string"):[];r.includes(t)||r.push(t);let c={...s,enabledMcpjsonServers:r};await Zi(i,JSON.stringify(c,null,2)+`
35
+ `,"utf-8")}var ns="0.35.0",Y=5,G=!1;function Q(e,t){a.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)}function Tn(e){return X(e,ft,"setup-pending")}function _n(e){return X(e,ft,"ms-signin.json")}async function is(e){return nt(X(e,".ms-token.json"),"utf-8").then(t=>String(JSON.parse(t).account?.address??"")).then(t=>t.trim().toLowerCase()).catch(()=>"")}function Vr(e){let t=process.env.KLAUDIUS_WHATSAPP_STATE_DIR||X(os(),".klaudius","whatsapp");return jr(X(t,e,"auth","creds.json"))}async function Yr(e){let t;try{t=await nt(e,"utf-8")}catch{Q("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let i=JSON.parse(n),s={};for(let[o,r]of Object.entries(i))r!=null&&(s[o]=typeof r=="string"?r:String(r));return s}catch(i){Q("answers",`Answers file is not valid JSON: ${i.message}`)}return te(t)}function Ie(e){return`npx klaudius@latest init ${an(it(e))}`}function it(e){if(process.platform==="win32")return e;let t=os();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Wr(e){let t=[];try{let i=(await ss(e,{withFileTypes:!0})).filter(s=>s.isDirectory()&&!s.name.startsWith(".")).slice(0,200);for(let s of i){let o=X(e,s.name);if(!await rn(X(o,".env")))continue;let r=await rn(X(o,".klaudius","manifest.json"));if(t.push({path:o,finished:r}),t.length>=3)break}}catch{}return t}async function rn(e){try{return await In(e),!0}catch{return!1}}function an(e){return/\s/.test(e)?`"${e}"`:e}function ke(e,t,n){a.blank(),a.error(`${t} validation failed ${Y} times in a row. Pausing setup so you don't get stuck in a loop.`),a.detail(`Last error: ${n}`),a.blank(),a.detail("Your credentials are saved in `.env`. Two ways forward:"),a.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),a.blank(),console.log(` ${g.cyan(Ie(e))}`),a.blank(),a.detail(` (Your .env is at ${it(X(e,".env"))} \u2014 open it in any text editor.)`),a.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),a.blank(),process.exit(1)}async function rs(e){let t=e.target??".",n=Gr(t)?t:Kr(process.cwd(),t),i=Qr(n);i&&(a.error("Klaudius can't be installed inside a protected system folder."),a.detail(`Path: ${n}`),a.detail(`Reason: ${i}`),a.blank(),a.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),a.blank(),process.platform==="win32"?(a.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${g.cyan("cd $HOME\\Documents")}`),console.log(` ${g.cyan("npx klaudius@latest init my-agency")}`)):(a.detail("For example:"),console.log(` ${g.cyan("cd ~/Documents")}`),console.log(` ${g.cyan("npx klaudius@latest init my-agency")}`)),a.blank(),process.exit(1)),process.platform==="win32"&&Xr()&&(a.warn("You appear to be running in an elevated (Administrator) PowerShell."),a.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."),a.blank()),await Vt("init",ns);let s=await qr(n),o=s.kind==="scaffolded"&&!!e.answers&&await rn(Tn(n));if(s.kind==="scaffolded"&&!o){a.blank(),a.warn(`Found an existing Klaudius project at ${g.bold(n)}.`),a.detail("(Your .env and project files are in place.)"),a.blank(),s.nodeModulesMissing?(a.detail("It looks like a previous setup didn't finish installing dependencies."),a.detail("To pick up where it left off, run:"),a.blank(),n!==process.cwd()&&console.log(` ${g.cyan(`cd ${an(t)}`)}`),console.log(` ${g.cyan("npx klaudius@latest install")} ${g.dim("# retries npm + pip + browsers; idempotent")}`),a.blank(),a.detail("Then verify with:"),a.blank(),console.log(` ${g.cyan("npx klaudius@latest doctor")} ${g.dim("# checks Node / Python / installers / credentials")}`),a.blank()):(a.detail("Everything is scaffolded and dependencies look installed."),a.detail("Pick the action you wanted:"),a.blank(),console.log(` ${g.cyan("npx klaudius@latest doctor")} ${g.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${g.cyan("npx klaudius@latest configure")} ${g.dim("# change a credential / API key")}`),console.log(` ${g.cyan("npx klaudius@latest update")} ${g.dim("# pull the latest skills, scripts, lessons")}`),a.blank()),a.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),a.blank();return}if(s.kind==="occupied"){let m=t===".",k=await Wr(n);if(k.length>0){a.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),a.detail(`You're in: ${it(n)}`),a.blank();for(let w of k)a.detail(w.finished?`Found a finished project at ${it(w.path)}. To work in it:`:`Found an unfinished setup at ${it(w.path)}. To pick up where it left off:`),a.blank(),w.finished?(console.log(` ${g.cyan(`cd ${it(w.path)}`)}`),console.log(` ${g.cyan("claude")} ${g.dim("# open Claude Code in the project")}`)):console.log(` ${g.cyan(Ie(w.path))} ${g.dim("# then pick Resume")}`),a.blank();process.exit(1)}a.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),a.detail(`Path: ${n}`),a.detail(`Contains: ${s.entries.slice(0,5).join(", ")}${s.entries.length>5?`, \u2026 (+${s.entries.length-5} more)`:""}`),a.blank(),m?(a.detail("Two ways forward:"),a.blank(),a.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${g.cyan("npx klaudius@latest init my-agency")}`),a.blank(),a.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${g.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(a.detail(`The folder '${t}' already exists and isn't empty.`),a.detail("Either pick a different name:"),console.log(` ${g.cyan(`npx klaudius@latest init ${t}-2`)}`),a.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=null;e.answers&&(G=!0,r=await Yr(e.answers),a.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let c=r??{},u={};if(r){let m=await nt(X(n,".env"),"utf-8").catch(()=>null);m&&(u=te(m),r={...Object.fromEntries(Object.entries(u).filter(([w])=>!ui.includes(w))),...r})}let p=e.license??r?.KLAUDIUS_LICENSE_KEY;G&&(!p||p.trim().length===0)&&Q("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let d=await Jr(p),y=T.spinner();y.start("Validating license");let f=await Fi(d);f.ok||(y.stop(`License invalid: ${f.reason??"unknown"}`,2),a.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),G&&Q("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)),y.stop(`License valid (${f.tier??"core"} tier)`);let A=await Ye();A.ok||(a.error(A.message??"Python version check failed."),a.blank(),a.detail(`Once you've installed Python 3.10+, re-run the same command: ${Ie(n)}`),process.exit(1)),await Zt();let h=ve();h.ok||(a.error(h.message??"Node.js version check failed."),a.blank(),a.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${Ie(n)}`),process.exit(1));let l,P=!1;if(r){let m=Ft(r);m||Q("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."),l=pi(m,c,u),a.success("Loaded setup answers (non-interactive mode)");let k=u.AI_AGENT==="codex"?"codex":"claude-code";if(o&&k!==(l.aiAgent??"claude-code")){let w=b=>b==="codex"?"Codex":"Claude Code";Q("install",`This folder was set up for ${w(k)}, so it can't carry on as ${w(l.aiAgent??"claude-code")}. Give the folder a different name to set up fresh, or switch back.`)}}else if(s.kind==="partial")if(await zr(n)==="resume"){let k=await nt(s.envPath,"utf-8"),w=Ft(te(k));w?(a.success("Resuming with values from your existing .env"),a.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=w,P=!0,l.aiPlan||(l=await z(l,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
36
+ runs on. It sets the QA-pass default (and, on the smaller ChatGPT plans, the model).`}))):(a.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await z())}else{let k=await nt(s.envPath,"utf-8"),w=Ft(te(k));l=await z(w??{})}else l=await z();l.licenseKey=d,await J(n,l),P||(a.success("Saved .env"),a.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),a.blank();for(let m=1;;m++){let k=T.spinner();k.start("Validating Supabase credentials");let w=await We({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(w.ok){k.stop("Supabase credentials accepted");break}k.stop(w.message??"Supabase check failed",2),m>=Y&&ke(n,"Supabase",w.message??"Supabase check failed");let b=w.message??"Supabase check failed";a.blank(),G&&Q("supabase",b),a.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${m+1} of ${Y})`),a.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await z(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
37
+ ${b}
38
38
 
39
39
  Re-enter the URL, secret key, or PAT below. Press Enter on any
40
- field to keep what's already there.`}),await U(n,l)}if(i.blank(),l.deployProvider==="cloudflare")for(let f=1;;f++){let y=E.spinner();y.start("Validating Cloudflare token + account");let g=await Fe({token:l.cloudflareApiToken??"",accountId:l.cloudflareAccountId??""});if(g.ok){y.stop(`Cloudflare credentials accepted (${g.projectCount??0} existing Pages project${g.projectCount===1?"":"s"})`);break}y.stop(g.message??"Cloudflare check failed",2),f>=$&&re(n,"Cloudflare",g.message??"Cloudflare check failed");let k=g.message??"Cloudflare check failed";i.blank(),x&&H("cloudflare",k),i.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
41
- ${k}
40
+ field to keep what's already there.`}),await J(n,l)}if(a.blank(),l.deployProvider==="cloudflare")for(let m=1;;m++){let k=T.spinner();k.start("Validating Cloudflare token + account");let w=await ze({token:l.cloudflareApiToken??"",accountId:l.cloudflareAccountId??""});if(w.ok){k.stop(`Cloudflare credentials accepted (${w.projectCount??0} existing Pages project${w.projectCount===1?"":"s"})`);break}k.stop(w.message??"Cloudflare check failed",2),m>=Y&&ke(n,"Cloudflare",w.message??"Cloudflare check failed");let b=w.message??"Cloudflare check failed";a.blank(),G&&Q("cloudflare",b),a.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${m+1} of ${Y})`),a.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await z(l,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
41
+ ${b}
42
42
 
43
43
  Re-enter the API token or Account ID below. The token needs the
44
44
  "Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
45
- the current value.`}),await U(n,l)}else if(l.deployProvider==="netlify")for(let f=1;;f++){let y=E.spinner();y.start("Validating Netlify token");let g=await Ue({token:l.netlifyAuthToken??""});if(g.ok){y.stop(g.accountSlug?`Netlify token accepted (team: ${g.accountSlug})`:"Netlify token accepted");break}y.stop(g.message??"Netlify check failed",2),f>=$&&re(n,"Netlify",g.message??"Netlify check failed");let k=g.message??"Netlify check failed";i.blank(),x&&H("netlify",k),i.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"netlify",banner:`Netlify rejected the token:
46
- ${k}
45
+ the current value.`}),await J(n,l)}else if(l.deployProvider==="netlify")for(let m=1;;m++){let k=T.spinner();k.start("Validating Netlify token");let w=await Je({token:l.netlifyAuthToken??""});if(w.ok){k.stop(w.accountSlug?`Netlify token accepted (team: ${w.accountSlug})`:"Netlify token accepted");break}k.stop(w.message??"Netlify check failed",2),m>=Y&&ke(n,"Netlify",w.message??"Netlify check failed");let b=w.message??"Netlify check failed";a.blank(),G&&Q("netlify",b),a.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${m+1} of ${Y})`),a.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await z(l,{onlySection:"netlify",banner:`Netlify rejected the token:
46
+ ${b}
47
47
 
48
48
  Generate a new token at
49
49
  https://app.netlify.com/user/applications#personal-access-tokens
50
- and paste it below. Press Enter to keep the current value.`}),await U(n,l)}else if(l.deployProvider==="selfhost")for(let f=1;;f++){let y=pt(l.selfhostDeployTarget??""),g=ft(l.selfhostUrlTemplate??"");if(!y&&!g){i.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let k=[y&&`SELFHOST_DEPLOY_TARGET: ${y}`,g&&`SELFHOST_URL_TEMPLATE: ${g}`].filter(Boolean).join(`
51
- `);f>=$&&re(n,"Self-host",k),i.blank(),x&&H("selfhost",k),i.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${f+1} of ${$})`),i.blank(),l=await F(l,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
52
- ${k}
50
+ and paste it below. Press Enter to keep the current value.`}),await J(n,l)}else if(l.deployProvider==="selfhost")for(let m=1;;m++){let k=_t(l.selfhostDeployTarget??""),w=It(l.selfhostUrlTemplate??"");if(!k&&!w){a.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let b=[k&&`SELFHOST_DEPLOY_TARGET: ${k}`,w&&`SELFHOST_URL_TEMPLATE: ${w}`].filter(Boolean).join(`
51
+ `);m>=Y&&ke(n,"Self-host",b),a.blank(),G&&Q("selfhost",b),a.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${m+1} of ${Y})`),a.blank(),l=await z(l,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
52
+ ${b}
53
53
 
54
- Re-enter them below. Press Enter on a field to keep its current value.`}),await U(n,l)}else for(let f=1;;f++){let y=E.spinner();y.start("Validating Vercel token");let g=await De(l.vercelToken??"");if(g.ok){y.stop(g.username?`Vercel token accepted (signed in as ${g.username})`:"Vercel token accepted");break}y.stop(g.message,2);let k=g.message,R=g.kind==="rejected"||g.kind==="scope",M=R?`${k} Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration).`:k;f>=$&&re(n,"Vercel",M),i.blank(),x&&H("vercel",M),i.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"vercel",banner:R?`${k}
54
+ Re-enter them below. Press Enter on a field to keep its current value.`}),await J(n,l)}else for(let m=1;;m++){let k=T.spinner();k.start("Validating Vercel token");let w=await qe(l.vercelToken??"");if(w.ok){k.stop(w.username?`Vercel token accepted (signed in as ${w.username})`:"Vercel token accepted");break}k.stop(w.message,2);let b=w.message,K=w.kind==="rejected"||w.kind==="scope",W=K?`${b} Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration).`:b;m>=Y&&ke(n,"Vercel",W),a.blank(),G&&Q("vercel",W),a.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${m+1} of ${Y})`),a.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await z(l,{onlySection:"vercel",banner:K?`${b}
55
55
 
56
56
  Create a new token at https://vercel.com/account/settings/tokens
57
57
  (Scope: Full Account, Expiration: No Expiration) and paste it
58
- below. Press Enter to keep the current value.`:`${k}
58
+ below. Press Enter to keep the current value.`:`${b}
59
59
 
60
60
  Press Enter to keep the current value and try again, or paste a
61
- different token.`}),await U(n,l)}i.blank();for(let f=1;;f++){let y=ge(l.googlePlacesApiKey??""),g=E.spinner();g.start("Validating Google Places API key");let k=await He(l.googlePlacesApiKey??"");if(k.ok){if(g.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 M of y.repairs)i.detail(` ${M}`);i.detail("These come from keys that were transcribed rather than copied."),i.detail("Google accepted the corrected key, and .env now holds it.")}l.googlePlacesApiKey=y.value,await U(n,l)}break}g.stop(k.message??"Google Places check failed",2),f>=$&&re(n,"Google Places",k.message??"Google Places check failed");let R=k.message??"Google Places check failed";i.blank(),x&&H("google-places",R),i.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"google-places",banner:`Google rejected the key:
62
- ${R}
61
+ different token.`}),await J(n,l)}a.blank();for(let m=1;;m++){let k=Re(l.googlePlacesApiKey??""),w=T.spinner();w.start("Validating Google Places API key");let b=await Qe(l.googlePlacesApiKey??"");if(b.ok){if(w.stop("Google Places API key accepted"),k.changed){if(k.repairs.length>0){a.blank(),a.warn("Corrected look-alike characters in your Google Places API key:");for(let W of k.repairs)a.detail(` ${W}`);a.detail("These come from keys that were transcribed rather than copied."),a.detail("Google accepted the corrected key, and .env now holds it.")}l.googlePlacesApiKey=k.value,await J(n,l)}break}w.stop(b.message??"Google Places check failed",2),m>=Y&&ke(n,"Google Places",b.message??"Google Places check failed");let K=b.message??"Google Places check failed";a.blank(),G&&Q("google-places",K),a.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${m+1} of ${Y})`),a.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await z(l,{onlySection:"google-places",banner:`Google rejected the key:
62
+ ${K}
63
63
 
64
64
  Generate (or fix) the key at https://console.cloud.google.com
65
- and paste it below. Press Enter to keep the current value.`}),await U(n,l)}let C=!1;if(x&&l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAuth!=="oauth-microsoft"){let f=[["email address",l.emailAddress],["password",l.emailPassword],["SMTP host",l.emailSmtpHost],["IMAP host",l.emailImapHost]].filter(([,k])=>!k).map(([k])=>k),y=[["SMTP port",l.emailSmtpPort],["IMAP port",l.emailImapPort]].filter(([,k])=>!k).map(([k])=>k),g=[...f.length>0?[`the ${f.join(", ")} ${f.length===1?"is":"are"} missing`]:[],...y.length>0?[`the ${y.join(" and ")} ${y.length===1?"isn't a number":"aren't numbers"}`]:[]];g.length>0&&H("email",`Email outreach is switched on, but ${g.join(", and ")}. Fill ${g.length===1&&f.length+y.length===1?"it":"them"} in, or turn email off.`)}if(l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAddress&&l.emailPassword&&l.emailSmtpHost&&l.emailSmtpPort&&l.emailImapHost&&l.emailImapPort){i.blank();let f=0,y=!1,g;for(;!y;){f++;let k=E.spinner();k.start("Validating email credentials (SMTP + IMAP)");let R=l.emailProvider&&l.emailProvider!=="custom"?l.emailProvider:Pe(l.emailSmtpHost),M=R?Q[R]:void 0,D=await pe({emailAddress:l.emailAddress,emailLogin:l.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:l.emailPassword,emailSmtpHost:l.emailSmtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:l.emailImapHost,emailImapPort:l.emailImapPort,usesAccountPassword:M?.usesAccountPassword,knownProvider:!!M,sentFolder:(l.emailSentFolder??"").trim()||"Sent",draftsFolder:(l.emailDraftsFolder??"").trim()||"Drafts"});if(D.ok){k.stop("Email credentials accepted (SMTP + IMAP)"),await $t(D,l,{nonInteractive:x,onCancel:()=>{E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
65
+ and paste it below. Press Enter to keep the current value.`}),await J(n,l)}let R=!1;if(G&&l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAuth!=="oauth-microsoft"){let m=[["email address",l.emailAddress],["password",l.emailPassword],["SMTP host",l.emailSmtpHost],["IMAP host",l.emailImapHost]].filter(([,b])=>!b).map(([b])=>b),k=[["SMTP port",l.emailSmtpPort],["IMAP port",l.emailImapPort]].filter(([,b])=>!b).map(([b])=>b),w=[...m.length>0?[`the ${m.join(", ")} ${m.length===1?"is":"are"} missing`]:[],...k.length>0?[`the ${k.join(" and ")} ${k.length===1?"isn't a number":"aren't numbers"}`]:[]];w.length>0&&Q("email",`Email outreach is switched on, but ${w.join(", and ")}. Fill ${w.length===1&&m.length+k.length===1?"it":"them"} in, or turn email off.`)}if(l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAddress&&l.emailPassword&&l.emailSmtpHost&&l.emailSmtpPort&&l.emailImapHost&&l.emailImapPort){a.blank();let m=0,k=!1,w;for(;!k;){m++;let b=T.spinner();b.start("Validating email credentials (SMTP + IMAP)");let K=l.emailProvider&&l.emailProvider!=="custom"?l.emailProvider:Me(l.emailSmtpHost),W=K?ce[K]:void 0,q=await _e({emailAddress:l.emailAddress,emailLogin:l.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:l.emailPassword,emailSmtpHost:l.emailSmtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:l.emailImapHost,emailImapPort:l.emailImapPort,usesAccountPassword:W?.usesAccountPassword,knownProvider:!!W,sentFolder:(l.emailSentFolder??"").trim()||"Sent",draftsFolder:(l.emailDraftsFolder??"").trim()||"Drafts"});if(q.ok){b.stop("Email credentials accepted (SMTP + IMAP)"),await zt(q,l,{nonInteractive:G,onCancel:()=>{T.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
66
66
 
67
- ${fe(n)}
68
- `),process.exit(0)}})&&await U(n,l);break}k.stop(D.message??"Email check failed",2);let Te=`${R}\0${l.emailAddress}\0${l.emailPassword}`;if(M&&D.failureKind!=="network"&&g!==Te){g=Te;let Ee=ut(R,l.emailSmtpHost,l.emailImapHost),oe,Pn=0;if(Ee.length>0){i.blank(),i.warn(`That server rejected the login. ${M.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let ee of Ee){let zt=E.spinner();zt.start(`Trying ${ee.label} (${ee.smtpHost})`);let Qt=await pe({emailAddress:l.emailAddress,emailLogin:l.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:l.emailPassword,emailSmtpHost:ee.smtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:ee.imapHost,emailImapPort:l.emailImapPort});if(Qt.ok){zt.stop(`${ee.label}: your login works here (${ee.smtpHost})`),oe=ee;break}Qt.failureKind!=="network"&&Pn++,zt.stop(Qt.failureKind==="network"?`${ee.label}: unreachable`:`${ee.label}: rejected too`,2)}}if(oe){if(i.blank(),i.success("Found it \u2014 your password was right all along; the server was the only problem."),x){i.detail(`Non-interactive: using the working ${oe.label} servers automatically.`),l.emailSmtpHost=oe.smtpHost,l.emailImapHost=oe.imapHost,await U(n,l);continue}let ee=await E.confirm({message:`Use the ${oe.label} servers (${oe.smtpHost} / ${oe.imapHost})?`,initialValue:!0});if(E.isCancel(ee)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
67
+ ${Ie(n)}
68
+ `),process.exit(0)}})&&await J(n,l);break}b.stop(q.message??"Email check failed",2);let Ue=`${K}\0${l.emailAddress}\0${l.emailPassword}`;if(W&&q.failureKind!=="network"&&w!==Ue){w=Ue;let Ne=Tt(K,l.emailSmtpHost,l.emailImapHost),we,Yn=0;if(Ne.length>0){a.blank(),a.warn(`That server rejected the login. ${W.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let he of Ne){let fn=T.spinner();fn.start(`Trying ${he.label} (${he.smtpHost})`);let hn=await _e({emailAddress:l.emailAddress,emailLogin:l.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:l.emailPassword,emailSmtpHost:he.smtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:he.imapHost,emailImapPort:l.emailImapPort});if(hn.ok){fn.stop(`${he.label}: your login works here (${he.smtpHost})`),we=he;break}hn.failureKind!=="network"&&Yn++,fn.stop(hn.failureKind==="network"?`${he.label}: unreachable`:`${he.label}: rejected too`,2)}}if(we){if(a.blank(),a.success("Found it \u2014 your password was right all along; the server was the only problem."),G){a.detail(`Non-interactive: using the working ${we.label} servers automatically.`),l.emailSmtpHost=we.smtpHost,l.emailImapHost=we.imapHost,await J(n,l);continue}let he=await T.confirm({message:`Use the ${we.label} servers (${we.smtpHost} / ${we.imapHost})?`,initialValue:!0});if(T.isCancel(he)&&(T.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
69
69
 
70
- ${fe(n)}
71
- `),process.exit(0)),ee){l.emailSmtpHost=oe.smtpHost,l.emailImapHost=oe.imapHost,await U(n,l);continue}}else Ee.length>0&&(i.blank(),Pn===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."):M.noAltWorkedHint&&i.warn(M.noAltWorkedHint))}let Xe=D.message??"Email check failed";i.blank(),i.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),i.detail("You can skip it now and wire it up later from inside the project."),i.blank(),x&&H("email",Xe);let ue=await E.select({message:`What would you like to do? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:f>=3?"skip":f>=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(E.isCancel(ue)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
70
+ ${Ie(n)}
71
+ `),process.exit(0)),he){l.emailSmtpHost=we.smtpHost,l.emailImapHost=we.imapHost,await J(n,l);continue}}else Ne.length>0&&(a.blank(),Yn===0?a.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."):W.noAltWorkedHint&&a.warn(W.noAltWorkedHint))}let ct=q.message??"Email check failed";a.blank(),a.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),a.detail("You can skip it now and wire it up later from inside the project."),a.blank(),G&&Q("email",ct);let be=await T.select({message:`What would you like to do? ${g.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:m>=3?"skip":m>=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(T.isCancel(be)&&(T.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
72
72
 
73
- ${fe(n)}
74
- `),process.exit(0)),ue==="skip"){l.outreachChannels=(l.outreachChannels??[]).filter(Ee=>Ee!=="email"),l.outreachPriority=(l.outreachPriority??[]).filter(Ee=>Ee!=="email"),l.outreachChannels.length===0&&(l.outreachEnabled=!1),await U(n,l),C=!0,i.success("Skipped email for now. Setup will continue."),l.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}ue==="edit"&&(i.blank(),l=await F(l,{onlySection:"email",banner:`${D.failedAt==="imap"?"IMAP":"SMTP"} check failed:
75
- ${Xe}
73
+ ${Ie(n)}
74
+ `),process.exit(0)),be==="skip"){l.outreachChannels=(l.outreachChannels??[]).filter(Ne=>Ne!=="email"),l.outreachPriority=(l.outreachPriority??[]).filter(Ne=>Ne!=="email"),l.outreachChannels.length===0&&(l.outreachEnabled=!1),await J(n,l),R=!0,a.success("Skipped email for now. Setup will continue."),l.outreachEnabled?a.detail("Outreach will use your other channel(s); email stays off until it's fixed."):a.detail("Automated outreach is off until email is fixed \u2014 everything else works."),k=!0;break}be==="edit"&&(a.blank(),l=await z(l,{onlySection:"email",banner:`${q.failedAt==="imap"?"IMAP":"SMTP"} check failed:
75
+ ${ct}
76
76
 
77
77
  Re-enter the email address, app password, or server details below.
78
78
  Press Enter on any field to keep its current value.
79
79
 
80
80
  Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
81
- at the "Server settings" question.`}),await U(n,l))}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="twilio"&&l.twilioAccountSid&&l.twilioAuthToken){i.blank();for(let f=1;;f++){let y=E.spinner();y.start("Validating Twilio credentials");let g=await ws({accountSid:l.twilioAccountSid,authToken:l.twilioAuthToken});if(g.ok){y.stop(g.friendlyName?`Twilio credentials accepted (${g.friendlyName})`:"Twilio credentials accepted");break}y.stop(g.message??"Twilio check failed",2),f>=$&&re(n,"Twilio",g.message??"Twilio check failed");let k=g.message??"Twilio check failed";i.blank(),x&&H("sms",k),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"sms",banner:`Twilio rejected the credentials:
82
- ${k}
81
+ at the "Server settings" question.`}),await J(n,l))}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="twilio"&&l.twilioAccountSid&&l.twilioAuthToken){a.blank();for(let m=1;;m++){let k=T.spinner();k.start("Validating Twilio credentials");let w=await Vi({accountSid:l.twilioAccountSid,authToken:l.twilioAuthToken});if(w.ok){k.stop(w.friendlyName?`Twilio credentials accepted (${w.friendlyName})`:"Twilio credentials accepted");break}k.stop(w.message??"Twilio check failed",2),m>=Y&&ke(n,"Twilio",w.message??"Twilio check failed");let b=w.message??"Twilio check failed";a.blank(),G&&Q("sms",b),a.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${m+1} of ${Y})`),a.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await z(l,{onlySection:"sms",banner:`Twilio rejected the credentials:
82
+ ${b}
83
83
 
84
84
  Re-enter the Account SID or Auth Token below.
85
- Press Enter on any field to keep its current value.`}),await U(n,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("letter")&&l.letterProvider){i.blank();for(let f=1;;f++){let y=E.spinner();y.start("Validating letter provider credentials");let g=await Mt({provider:l.letterProvider,pingenClientId:l.pingenClientId,pingenClientSecret:l.pingenClientSecret,pingenOrgId:l.pingenOrgId,postgridApiKey:l.postgridApiKey});if(g.ok){y.stop(g.friendlyName?`Letter provider credentials accepted (${g.friendlyName})`:"Letter provider credentials accepted");break}y.stop(g.message??"Letter provider check failed",2),f>=$&&re(n,"Letter provider",g.message??"Letter provider check failed");let k=g.message??"Letter provider check failed";i.blank(),x&&H("letter",k),i.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"letter",banner:`The letter provider rejected the credentials:
86
- ${k}
85
+ Press Enter on any field to keep its current value.`}),await J(n,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("letter")&&l.letterProvider){a.blank();for(let m=1;;m++){let k=T.spinner();k.start("Validating letter provider credentials");let w=await Jt({provider:l.letterProvider,pingenClientId:l.pingenClientId,pingenClientSecret:l.pingenClientSecret,pingenOrgId:l.pingenOrgId,postgridApiKey:l.postgridApiKey});if(w.ok){k.stop(w.friendlyName?`Letter provider credentials accepted (${w.friendlyName})`:"Letter provider credentials accepted");break}k.stop(w.message??"Letter provider check failed",2),m>=Y&&ke(n,"Letter provider",w.message??"Letter provider check failed");let b=w.message??"Letter provider check failed";a.blank(),G&&Q("letter",b),a.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${m+1} of ${Y})`),a.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await z(l,{onlySection:"letter",banner:`The letter provider rejected the credentials:
86
+ ${b}
87
87
 
88
88
  Re-enter them below.
89
- Press Enter on any field to keep its current value.`}),await U(n,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="imessage"&&l.testPhone){i.blank();for(let f=1;;f++){let y=E.spinner();y.start("Validating iMessage setup (sending a test ping)");let g=await ks({testPhone:l.testPhone});if(g.ok){if(y.stop("iMessage dispatched (check your phone for the test ping)"),x){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 R=await E.confirm({message:"Did the test message actually arrive on your phone?",initialValue:!0});if(E.isCancel(R)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
89
+ Press Enter on any field to keep its current value.`}),await J(n,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="imessage"&&l.testPhone){a.blank();for(let m=1;;m++){let k=T.spinner();k.start("Validating iMessage setup (sending a test ping)");let w=await Yi({testPhone:l.testPhone});if(w.ok){if(k.stop("iMessage dispatched (check your phone for the test ping)"),G){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 K=await T.confirm({message:"Did the test message actually arrive on your phone?",initialValue:!0});if(T.isCancel(K)&&(T.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
90
90
 
91
- ${fe(n)}
92
- `),process.exit(0)),R)break;y.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),f>=$&&re(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(),l=await F(l,{onlySection:"sms",banner:`The test message was dispatched but never arrived on your phone.
91
+ ${Ie(n)}
92
+ `),process.exit(0)),K)break;k.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),m>=Y&&ke(n,"iMessage","Test message dispatched but never delivered"),a.blank(),a.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."),a.blank(),l=await z(l,{onlySection:"sms",banner:`The test message was dispatched but never arrived on your phone.
93
93
  Re-check the number below (international format with a leading +).
94
- Press Enter on any field to keep its current value.`}),await U(n,l);continue}y.stop(g.message??"iMessage check failed",2),f>=$&&re(n,"iMessage",g.message??"iMessage check failed");let k=g.message??"iMessage check failed";i.blank(),x&&H("sms",k),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"sms",banner:`iMessage check failed:
95
- ${k}
94
+ Press Enter on any field to keep its current value.`}),await J(n,l);continue}k.stop(w.message??"iMessage check failed",2),m>=Y&&ke(n,"iMessage",w.message??"iMessage check failed");let b=w.message??"iMessage check failed";a.blank(),G&&Q("sms",b),a.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${m+1} of ${Y})`),a.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await z(l,{onlySection:"sms",banner:`iMessage check failed:
95
+ ${b}
96
96
 
97
97
  Either fix the underlying issue (sign in to Messages.app, configure
98
98
  Text Message Forwarding) and press Enter through, or change SMS
99
- provider to Twilio.`}),await U(n,l)}}if((l.notifyChannel??"telegram")==="telegram"&&l.telegramBotToken&&l.telegramChatId){i.blank();let f=0,y=!1;for(;!y;){f++;let g=E.spinner();g.start("Validating Telegram bot + chat (sending a test ping)");let k=await bn({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(k.ok){g.stop(k.botHandle?`Telegram bot ${k.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),y=!0;break}g.stop(k.message??"Telegram check failed",2);let R=k.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(),x&&H("notifications",R);let M=await E.select({message:`What would you like to do? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:f>=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(E.isCancel(M)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
99
+ provider to Twilio.`}),await J(n,l)}}if((l.notifyChannel??"telegram")==="telegram"&&l.telegramBotToken&&l.telegramChatId){a.blank();let m=0,k=!1;for(;!k;){m++;let w=T.spinner();w.start("Validating Telegram bot + chat (sending a test ping)");let b=await qn({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(b.ok){w.stop(b.botHandle?`Telegram bot ${b.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),k=!0;break}w.stop(b.message??"Telegram check failed",2);let K=b.message??"Telegram check failed";a.blank(),a.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),a.blank(),G&&Q("notifications",K);let W=await T.select({message:`What would you like to do? ${g.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:m>=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(T.isCancel(W)&&(T.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
100
100
 
101
- ${fe(n)}
102
- `),process.exit(0)),M==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await U(n,l),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(M==="edit"&&(i.blank(),l=await F(l,{onlySection:"notifications",banner:`Telegram check failed:
103
- ${R}
101
+ ${Ie(n)}
102
+ `),process.exit(0)),W==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await J(n,l),a.success("Skipped Telegram. Setup will continue."),a.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`."),k=!0;break}if(W==="edit"&&(a.blank(),l=await z(l,{onlySection:"notifications",banner:`Telegram check failed:
103
+ ${K}
104
104
 
105
105
  Re-enter the bot token or chat_id below.
106
- Press Enter on any field to keep its current value.`}),await U(n,l),(l.notifyChannel??"telegram")!=="telegram"||!l.telegramBotToken||!l.telegramChatId)){i.success("Skipped Telegram. Setup will continue."),y=!0;break}}}if(i.blank(),r)i.detail("Picking up the setup that didn't finish in this folder \u2014 your files are already here.");else{let f=E.spinner();f.start("Downloading Klaudius template");let y;try{y=(await Ct({licenseKey:u,machineId:st(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:n})).filesExtracted,f.stop(`Downloaded ${y} files into ${h.bold(n)}`)}catch(k){f.stop(k.message,2);let R=l.aiAgent==="codex"?".codex/config.toml":".mcp.json";i.detail(`Your .env / ${R} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await Bt(j(n,"clients"),{recursive:!0});let g=await Jn(n);x&&(await Bt(j(n,tt),{recursive:!0}),await it(an(n),`${new Date().toISOString()}
107
- `,"utf-8")),await nt(n,zn(Rs,g)),i.success("Wrote .klaudius/manifest.json");try{await xt(n,n,Object.keys(g))}catch{}}let G=!1,me="",ne="";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: ${l.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+l.supabaseProjectRef+"/sql/new").replace(l.supabaseProjectRef+".supabase.co","")}`);else{i.blank();let f=E.spinner();f.start("Applying schema to Supabase");let y=await vt({projectRoot:n,pat:l.supabasePat,projectRef:l.supabaseProjectRef});y.ok?f.stop("Schema applied (or already present)"):(f.stop(y.message??"Schema apply failed",2),G=!0,me=y.message?.trim()||"the database refused the request",ne=`https://supabase.com/dashboard/project/${l.supabaseProjectRef}/sql/new`)}let b=[],ie={};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 f=await Ft(n);if(i.detail(`npm: ${f.npm}, pip: ${f.pip}, playwright: ${f.playwright}, patchright: ${f.patchright}`),f.npm==="failed"&&b.push("npm"),f.pip==="failed"&&b.push("pip"),f.playwright==="failed"&&b.push("playwright"),f.patchright==="failed"&&b.push("patchright"),ie=f.hints??{},f.npm!=="failed"&&f.playwright!=="failed"){i.step("Checking the QA screenshot chain (serving a test page and screenshotting it)\u2026");let y=await jt(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 B=l.outreachEnabled&&l.outreachPriority?.includes("whatsapp")&&(l.whatsappAccounts?.length??0)>0,_e=!e.skipInstall&&!b.includes("npm"),Qe=(l.whatsappAccounts??[]).filter(f=>!(r&&or(f)));if(B&&_e&&Qe.length>0){i.blank(),i.heading("Linking WhatsApp accounts"),console.log(h.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
106
+ Press Enter on any field to keep its current value.`}),await J(n,l),(l.notifyChannel??"telegram")!=="telegram"||!l.telegramBotToken||!l.telegramChatId)){a.success("Skipped Telegram. Setup will continue."),k=!0;break}}}if(a.blank(),o)a.detail("Picking up the setup that didn't finish in this folder \u2014 your files are already here.");else{let m=T.spinner();m.start("Downloading Klaudius template");let k;try{k=(await Gt({licenseKey:d,machineId:mt(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:n})).filesExtracted,m.stop(`Downloaded ${k} files into ${g.bold(n)}`)}catch(b){m.stop(b.message,2);let K=l.aiAgent==="codex"?".codex/config.toml":".mcp.json";a.detail(`Your .env / ${K} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await on(X(n,"clients"),{recursive:!0});let w=await bi(n);G&&(await on(X(n,ft),{recursive:!0}),await gt(Tn(n),`${new Date().toISOString()}
107
+ `,"utf-8")),await xe(n,Ei(ns,w)),a.success("Wrote .klaudius/manifest.json");try{await Bt(n,n,Object.keys(w))}catch{}}let x=!1,v="",L="";if(e.skipSchema)a.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),a.detail(`Apply manually later via the SQL editor: ${l.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+l.supabaseProjectRef+"/sql/new").replace(l.supabaseProjectRef+".supabase.co","")}`);else{a.blank();let m=T.spinner();m.start("Applying schema to Supabase");let k=await Yt({projectRoot:n,pat:l.supabasePat,projectRef:l.supabaseProjectRef});k.ok?m.stop("Schema applied (or already present)"):(m.stop(k.message??"Schema apply failed",2),x=!0,v=k.message?.trim()||"the database refused the request",L=`https://supabase.com/dashboard/project/${l.supabaseProjectRef}/sql/new`)}let S=[],I={};if(e.skipInstall)a.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{a.blank(),a.heading("Installing dependencies");let m=await Xt(n);if(a.detail(`npm: ${m.npm}, pip: ${m.pip}, playwright: ${m.playwright}, patchright: ${m.patchright}`),m.npm==="failed"&&S.push("npm"),m.pip==="failed"&&S.push("pip"),m.playwright==="failed"&&S.push("playwright"),m.patchright==="failed"&&S.push("patchright"),I=m.hints??{},m.npm!=="failed"&&m.playwright!=="failed"){a.step("Checking the QA screenshot chain (serving a test page and screenshotting it)\u2026");let k=await tn(n);k.ok?a.success("QA screenshot chain verified (local page served and screenshotted)."):(a.warn(`QA screenshot chain check failed${k.stage?` (${k.stage})`:""}: ${k.detail??"unknown"}`),k.remediation&&a.detail(k.remediation))}}let N=l.outreachEnabled&&l.outreachPriority?.includes("whatsapp")&&(l.whatsappAccounts?.length??0)>0,j=!e.skipInstall&&!S.includes("npm"),M=(l.whatsappAccounts??[]).filter(m=>!(o&&Vr(m)));if(N&&j&&M.length>0){a.blank(),a.heading("Linking WhatsApp accounts"),console.log(g.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
108
108
  phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
109
- Link a Device, and point it at the QR shown in this terminal.`)),i.blank();for(let f of Qe){console.log(h.cyan(`Pairing WhatsApp account '${f}'...`)),console.log(h.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${f})`));let y=dn(process.execPath,["scripts/whatsapp.mjs","pair","--account",f],{cwd:n,stdio:"inherit"});y.status===0?i.detail(`Paired '${f}'.`):(console.log(h.yellow(`'${f}' did not pair (exit ${y.status??"signalled"}). You can finish later via:`)),console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${f}`))),i.blank()}}else if(B&&!_e){i.blank(),console.log(h.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let f of l.whatsappAccounts)console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${f}`))}let w=l.emailAuth==="oauth-microsoft"&&l.outreachEnabled&&l.outreachChannels?.includes("email"),v=!e.skipInstall&&!b.includes("pip"),L=(l.emailAddress??"").trim().toLowerCase(),se=await xs(n),_=await Ve(ln(n),"utf-8").then(f=>JSON.parse(f)).catch(()=>null),K=String(_?.entered??"").trim().toLowerCase(),de=String(_?.token??"").trim().toLowerCase(),Je=r&&(se!==""&&(se===L||K!==""&&K===L&&de===se))&&await Vt(j(n,".ms-token.json")),An=f=>{console.log(h.dim("Connect it any time from the project folder with:")),console.log(h.cyan(` ${f?f.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(h.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(w&&Je)i.blank(),i.detail("Your Outlook mailbox is already connected \u2014 leaving that sign-in alone.");else if(w&&v){i.blank(),i.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(h.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
109
+ Link a Device, and point it at the QR shown in this terminal.`)),a.blank();for(let m of M){console.log(g.cyan(`Pairing WhatsApp account '${m}'...`)),console.log(g.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${m})`));let k=Cn(process.execPath,["scripts/whatsapp.mjs","pair","--account",m],{cwd:n,stdio:"inherit"});k.status===0?a.detail(`Paired '${m}'.`):(console.log(g.yellow(`'${m}' did not pair (exit ${k.status??"signalled"}). You can finish later via:`)),console.log(g.cyan(` npx klaudius@latest pair-whatsapp --label ${m}`))),a.blank()}}else if(N&&!j){a.blank(),console.log(g.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(g.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let m of l.whatsappAccounts)console.log(g.cyan(` npx klaudius@latest pair-whatsapp --label ${m}`))}let pe=l.emailAuth==="oauth-microsoft"&&l.outreachEnabled&&l.outreachChannels?.includes("email"),C=!e.skipInstall&&!S.includes("pip"),B=(l.emailAddress??"").trim().toLowerCase(),ie=await is(n),Z=await nt(_n(n),"utf-8").then(m=>JSON.parse(m)).catch(()=>null),fe=String(Z?.entered??"").trim().toLowerCase(),E=String(Z?.token??"").trim().toLowerCase(),U=o&&(ie!==""&&(ie===B||fe!==""&&fe===B&&E===ie))&&await rn(X(n,".ms-token.json")),le=m=>{console.log(g.dim("Connect it any time from the project folder with:")),console.log(g.cyan(` ${m?m.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(g.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(pe&&U)a.blank(),a.detail("Your Outlook mailbox is already connected \u2014 leaving that sign-in alone.");else if(pe&&C){a.blank(),a.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(g.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
110
110
  password. Your browser will open to Microsoft's sign-in page \u2014
111
111
  sign in as `+(l.emailAddress??"your outreach mailbox")+` and approve.
112
112
  (No browser on this machine? It falls back to a short code you can
113
- enter from any device.)`)),i.blank();let f=await W();if(f){let[y,...g]=f.command,k=dn(y,[...g,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});if(k.status===0){if(i.success("Outlook mailbox connected."),x){let R={entered:(l.emailAddress??"").trim(),token:await xs(n)};await it(ln(n),`${JSON.stringify(R)}
114
- `,"utf-8").catch(()=>{})}}else i.blank(),console.log(h.yellow(`The Microsoft sign-in didn't complete (exit ${k.status??"signalled"}). Setup continues without it.`)),An(f)}else console.log(h.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),An(null)}else w&&!v&&(i.blank(),console.log(h.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(h.cyan(" python3 scripts/ms_oauth.py login")));i.blank();let En=[...b,...G?["schema"]:[]];if(En.length>0){E.outro(h.yellow(h.bold(`Setup paused \u2014 ${En.join(", ")} failed.`))),console.log(h.dim("Your credentials and project files are all saved.")),i.blank();for(let[D,Te]of Object.entries(ie))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${Te}`)),i.blank();let f=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${Yt(e.target)}`)}
115
- `:"",y=l.aiAgent==="codex"?"codex":"claude",g=l.aiAgent==="codex"?"Codex":"Claude Code",k=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";b.length>0&&(console.log(h.dim(`Easiest fix \u2014 let ${g} finish it for you:`)),i.blank(),f&&process.stdout.write(f),console.log(` ${h.cyan(y)} ${h.dim(`# open ${g} in this folder`)}`),console.log(h.dim(" Then paste:")),console.log(h.cyan(` "Finish my Klaudius install \u2014 ${b.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(h.dim(` (Don't have ${g} yet? Install with: \`${k}\`)`)),i.blank(),console.log(h.dim("Or do it yourself:")),i.blank(),f&&process.stdout.write(f),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retry the failing installers")}`),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify everything")}`),i.blank()),G&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(ne)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),b.includes("pip")&&!ie.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 ${fr()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),i.blank());let M=["npm","playwright","patchright"].filter(D=>b.includes(D)&&!ie[D]);if(M.length>0){let D=M.length===1?"keeps":"keep";console.log(h.dim(`If ${M.join(" / ")} ${D} failing with network errors (ECONNRESET,`)),console.log(h.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(h.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}if(C&&(console.log(h.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${g}`)),console.log(h.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(h.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank(),x){let D=[];G&&D.push(`Couldn't create the database tables: ${me.replace(/[:.\s]+$/,"")}. Check the database access token on the Database step.`);let Te=b.filter(ue=>ue==="playwright"||ue==="patchright"),Xe=b.filter(ue=>ue!=="playwright"&&ue!=="patchright");Xe.length>0&&D.push(`Couldn't finish installing ${Xe.join(", ")}. The install output says why.`),Te.length>0&&D.push("Couldn't download the browsers Klaudius uses to gather business details, check the sites it builds and make invoices. The install output says why. If your network blocks large downloads, a different network, such as a phone hotspot, often gets past it."),D.push("Then try again \u2014 setup carries on from here. If it keeps failing, email hello@klaudius.dev with the last few lines."),H(G&&b.length===0?"supabase":"install",D.join(`
116
- `))}return}if(await Cs(an(n),{force:!0}),await Cs(ln(n),{force:!0}),hr(l,n,e.target),C){let f=l.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 ${f}:`)),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."')),l.outreachEnabled&&(l.outreachChannels??[]).length>0&&(i.blank(),console.log(h.yellow(`Note: your other channel(s) \u2014 ${(l.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),i.blank()}}async function U(e,t){await Bt(e,{recursive:!0}),await it(j(e,".env"),Et(t),"utf-8"),t.aiAgent==="codex"?(await Bt(j(e,".codex"),{recursive:!0}),await it(j(e,".codex","config.toml"),St(t),"utf-8")):(await it(j(e,".mcp.json"),Pt(t),"utf-8"),await Gt(e,"supabase"),await Be(e,Ge))}async function lr(e){try{(await cn(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Os(e),n=t.filter(d=>!d.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(d=>s.has(d)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:j(e,".env")};if(a&&r){let d=!0;try{d=!(await cn(j(e,"node_modules"))).isDirectory()}catch{d=!0}return{kind:"scaffolded",nodeModulesMissing:d}}return{kind:"occupied",entries:n}}async function cr(e){i.blank(),i.warn(`Found a partial setup at ${h.bold(e)}.`),i.detail(`A previous init wrote ${h.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await E.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 E.isCancel(t)&&(E.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function dr(e){if(e&&e.trim().length>0)return e;E.intro("Klaudius");let t=await E.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 E.isCancel(t)&&(E.cancel("Setup cancelled. No files written."),process.exit(0)),t}function ur(e){let t=ir(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 pr(){if(process.platform!=="win32")return!1;try{return dn("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function fr(){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 hr(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(E.outro(h.green(h.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ce(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${Re[e.aiPlan]}`),console.log(h.dim(r?` \u2192 QA pass off${Ie.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\`.`)),i.blank()}if(console.log(h.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let r=`cd ${Yt(n)}`;console.log(` ${h.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${h.dim("# go into your project folder")}`)}console.log(` ${h.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${h.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(h.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${h.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${h.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${h.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${h.cyan('"Run the pipeline for one client."')}`),console.log(h.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),i.blank(),e.aiAgent!=="codex"&&(console.log(h.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(h.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as mr,readFile as gr}from"fs/promises";import{join as un,resolve as yr}from"path";import J from"picocolors";async function $s(e){let t=e.target?yr(process.cwd(),e.target):process.cwd(),n=await Ns(un(t,".env")),s=await Ns(un(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{V(await gr(un(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await Ft(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(J.green(J.bold("All dependencies installed."))),console.log(J.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(J.yellow(J.bold(`${a.join(", ")} still failing.`))),i.blank();for(let[u,A]of Object.entries(r.hints??{}))console.log(J.yellow(`Likely cause of ${u} failure:`)),console.log(J.dim(` ${A}`)),i.blank();let d=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",p=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(J.dim("Options:")),console.log(J.dim(` \u2022 Open ${c} in this folder (\`${d}\`) and paste:`)),console.log(J.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(J.dim(` (Don't have ${c} yet? Install with: \`${p}\`)`)),console.log(J.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(J.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function Ns(e){try{return await mr(e),!0}catch{return!1}}import{readFile as wr,writeFile as pn,access as kr}from"fs/promises";import{join as We}from"path";import*as X from"@clack/prompts";import he from"picocolors";import{mkdir as Ar}from"fs/promises";import{spawnSync as Ms}from"child_process";async function Ds(e){let t=e.projectRoot??process.cwd(),n=We(t,".env"),s=We(t,".mcp.json"),o=We(t,".codex","config.toml"),r=await fn(We(t,".klaudius","manifest.json")),a=await fn(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 d=ye();d.ok||(i.error(d.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 m=await wr(n,"utf-8");c=V(m)}catch{i.warn("No .env found. Starting from an empty configuration.")}let p=Gn(c);Object.keys(c).length>0&&(p.pipelineModes??=["classic"]),X.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await F(p),A=p.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==A&&(i.error(`Switching AI coding agent (${A} \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(` ${he.cyan("npx klaudius@latest init <new-folder>")} ${he.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 m=await Me({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});m.ok||(i.error(m.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let P=Pr(u,c);if(P==="vercel"){let m=X.spinner();m.start("Validating Vercel token");let l=await De(u.vercelToken??"");l.ok?m.stop(l.username?`Vercel token accepted (signed in as ${l.username})`:"Vercel token accepted"):(m.stop(l.message,2),i.warn("Writing the token exactly as you entered it \u2014 not verified."),i.detail(l.kind==="rejected"||l.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`.":l.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(P==="cloudflare"){let m=X.spinner();m.start("Validating Cloudflare token + account");let l=await Fe({token:u.cloudflareApiToken??"",accountId:u.cloudflareAccountId??""});l.ok?m.stop("Cloudflare credentials accepted"):(m.stop(l.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(P==="netlify"){let m=X.spinner();m.start("Validating Netlify token");let l=await Ue({token:u.netlifyAuthToken??""});l.ok?m.stop(l.accountSlug?`Netlify token accepted (team: ${l.accountSlug})`:"Netlify token accepted"):(m.stop(l.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 T=ge(u.googlePlacesApiKey??"");if(T.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let m=await He(u.googlePlacesApiKey);if(m.ok){if(T.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let l of T.repairs)i.detail(` ${l}`);i.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=T.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(m.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(Er(u,c)){let m=X.spinner();m.start("Validating email credentials (SMTP + IMAP)");let l=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:Pe(u.emailSmtpHost),S=await pe({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:l?Q[l].usesAccountPassword:void 0,knownProvider:!!l,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});S.ok?(m.stop("Email credentials accepted (SMTP + IMAP)"),await $t(S,u,{nonInteractive:!1,onCancel:()=>i.detail("Left the folder names as they are.")})):(m.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 pn(n,Et(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await Ar(We(t,".codex"),{recursive:!0}),await pn(o,St(u),"utf-8"),i.success("Updated .codex/config.toml")):(await pn(s,Pt(u),"utf-8"),i.success("Updated .mcp.json"),await Gt(t,"supabase"),await Be(t,Ge)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let m=await W();if(!(m!==null&&Ms(m.command[0],[...m.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!m)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 X.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});X.isCancel(S)||!S?i.detail(`Skipped. Connect it any time with: ${m.command.join(" ")} scripts/ms_oauth.py login`):Ms(m.command[0],[...m.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: ${m.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),X.outro(he.green("Configuration updated.")),await Sr(t,r)}function Er(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 Pr(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 Sr(e,t){let n=await fn(We(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(` ${he.cyan("npx klaudius@latest install")} ${he.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${he.cyan("npx klaudius@latest doctor")} ${he.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(` ${he.cyan("npx klaudius@latest init")} ${he.dim("# pick Resume when prompted")}`),i.blank())}async function fn(e){try{return await kr(e),!0}catch{return!1}}import{copyFile as Fs,mkdir as hn,readFile as ot,rm as ke,writeFile as Wt,access as Us}from"fs/promises";import{dirname as mn,join as O}from"path";import{tmpdir as br}from"os";import*as Ae from"@clack/prompts";import rt from"picocolors";var at="0.34.1";async function js(e){let t=e.projectRoot??process.cwd(),n=await qn(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 _t)delete n.files[w];let s,o=O(t,".env"),r,a;try{r=await ot(o,"utf-8"),a=V(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 d=e.check?null:Hn(r,a,Un);d!==null&&(await Wt(o,d,"utf-8"),i.detail("Backfilled new env keys")),await Ot("update",at),Ae.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${at}`),await Ut();let p=a.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&p==="claude-code"&&await Be(t,Ge)==="added"&&i.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=O(br(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{i.heading("Downloading the latest Klaudius template");let w=await Ct({licenseKey:s,machineId:st(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});i.success(`Fetched ${w.filesExtracted} canonical files`),A=u}catch(w){i.error(w.message),i.detail("Update aborted. Your project is unchanged."),await ke(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let P=await Tr(A,t,n);if(e.check){let w=P.filter(_=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(_.state)),v=P.filter(_=>["conflict","locally-deleted","removed-modified"].includes(_.state)),L="unknown";if(a.SUPABASE_URL&&a.SUPABASE_SERVICE_KEY){let _=await ot(O(A,"scripts","schema.sql"),"utf-8").catch(()=>""),K=await Lt({url:a.SUPABASE_URL,serviceKey:a.SUPABASE_SERVICE_KEY,sql:_});K.unreachable?i.detail(`Database schema not checked (${K.unreachable}).`):K.ok?L="current":(L="stale",i.detail(`Database schema is behind (missing: ${K.missing.join(", ")}); update applies scripts/schema.sql.`))}let se=w.length>0||L==="stale";i.blank(),se?(w.length>0&&i.detail(`${Z(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),Ae.outro(rt.yellow("An update is available."))):Ae.outro(rt.green("Already up to date.")),console.log(`[klaudius-update-check] status=${se?"behind":"current"} pending=${w.length+(L==="stale"?1:0)} conflicts=${v.length} schema=${L}`),await ke(u,{recursive:!0,force:!0}).catch(()=>{});return}let T=!1,m=P.find(w=>w.path===".gitignore"&&w.state==="conflict");if(m){let w=O(t,".gitignore"),v=await ot(w,"utf-8"),L=await ot(O(A,".gitignore"),"utf-8"),{merged:se,added:_}=Ir(v,L);_.length>0&&await Wt(w,se,"utf-8"),n.files[".gitignore"]=m.canonicalHash,m.state="gitignore-merged",T=!0,i.detail(_.length>0?`.gitignore auto-merged: kept all your lines, appended ${Z(_.length,"new canonical pattern")}: ${_.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let l=P.filter(w=>w.state==="new"),S=P.filter(w=>w.state==="clean-update"),C=P.filter(w=>w.state==="user-only"),G=P.filter(w=>w.state==="conflict"),me=P.filter(w=>w.state==="no-change"),ne=P.filter(w=>w.state==="locally-deleted"),b=P.filter(w=>w.state==="removed-clean"),ie=P.filter(w=>w.state==="removed-modified"),B=[...G,...ne,...ie],_e=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${Z(me.length,"file")} unchanged`),i.detail(`${Z(l.length,"new file")}`),i.detail(`${Z(S.length,"file")} updated cleanly (no local edits)`),i.detail(`${Z(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${Z(b.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${Z(G.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${Z(ne.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${Z(ie.length,"file")} removed upstream but edited locally (need your decision)`),_e>0&&(i.detail(`${Z(_e,"file")} kept deleted (previously resolved \u2014 skipped)`),_e<=10))for(let w of n.ignored)i.detail(` kept deleted: ${w}`);let Qe=async()=>{let w=!1,v=L=>ke(L,{recursive:!0,force:!0}).catch(()=>{w=!0});await v(O(t,".klaudius","incoming")),await v(O(t,Rt)),await v(O(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(l.length===0&&S.length===0&&b.length===0&&B.length===0&&!T){await Hs(t,a,!1),await Qe(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=at,await nt(t,n)),i.blank(),Ae.outro(rt.green("Already up to date.")),await ke(u,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let w of[...l,...S]){let v=O(A,w.path),L=O(t,w.path);await hn(mn(L),{recursive:!0}),await Fs(v,L),n.files[w.path]=w.canonicalHash}l.length+S.length>0&&i.success(`Wrote ${Z(l.length+S.length,"file")}`),[...l,...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 b){let v=O(t,w.path);await ke(v,{force:!0}),delete n.files[w.path]}if(b.length>0&&i.success(`Deleted ${Z(b.length,"file")} removed upstream`),await Hs(t,a,B.some(w=>w.path==="scripts/schema.sql")),B.length>0){i.blank(),i.heading(`${B.length} conflict(s) need resolution`);let w=O(t,".klaudius","incoming");try{await ke(w,{recursive:!0,force:!0})}catch{}for(let _ of[...G,...ne]){let K=O(A,_.path),de=O(w,_.path);await hn(mn(de),{recursive:!0}),await Fs(K,de)}let v=new Map,L=new Map;for(let _ of G){let K=await is(t,_.path),de=await os(t,_.path),dt=await ot(O(A,_.path),"utf-8"),Je=rs(K,de,dt,_.manifestHash);Je!==null?(L.set(_.path,Je),v.set(_.path,as(Je,dt))):K!==null&&($e(K)||$e(dt))?v.set(_.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+_.path+"` directly._"]):K===null?v.set(_.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(_.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/"+_.path+"` directly._"])}let se=O(t,Rt);try{await ke(se,{recursive:!0,force:!0})}catch{}for(let[_,K]of L){let de=O(se,_);await hn(mn(de),{recursive:!0}),await Wt(de,K,"utf-8")}await Wt(O(t,".klaudius","conflicts.md"),Cr(B,n.templateVersion,at,v,L),"utf-8"),G.length+ne.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),L.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=at,B.length===0?(delete n.pendingConflicts,await Qe()):n.pendingConflicts=B.length,await nt(t,n);try{await xt(t,A,await Se(A))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),B.length===0)Ae.outro(rt.green("Update complete."));else{let w=p==="codex"?"Codex":"Claude Code";Ae.outro(rt.yellow(`${B.length} conflict(s) staged. Open ${w} in this project and ask:
117
- "Run /resolve-conflicts"`))}await ke(u,{recursive:!0,force:!0}).catch(()=>{})}async function Hs(e,t,n){let s=await _r(e,t,n);return console.log(`[klaudius-update] schema=${s}`),s}async function _r(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 vt({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): ${ps(o)}`),"failed")}async function Tr(e,t,n){let s=await Se(e),o=new Set(s),r=new Set(n.ignored??[]),a=[];for(let d of s){if(r.has(d))continue;let c=await Ne(O(e,d)),p=n.files[d],u=O(t,d),A;try{await Us(u),A=await Ne(u)}catch{let T=p!==void 0&&!Wn.has(d)&&!Tt.has(d)?"locally-deleted":"new";a.push({path:d,state:T,canonicalHash:c,manifestHash:p});continue}let P=Tt.has(d);c===p?A===p||P?a.push({path:d,state:"no-change",canonicalHash:c,localHash:A,manifestHash:p}):a.push({path:d,state:"user-only",canonicalHash:c,localHash:A,manifestHash:p}):A===p||P?a.push({path:d,state:"clean-update",canonicalHash:c,localHash:A,manifestHash:p}):a.push({path:d,state:"conflict",canonicalHash:c,localHash:A,manifestHash:p})}for(let d of Object.keys(n.files)){if(o.has(d))continue;let c=n.files[d],p=O(t,d),u;try{await Us(p),u=await Ne(p)}catch{delete n.files[d];continue}u===c||Tt.has(d)?a.push({path:d,state:"removed-clean",localHash:u,manifestHash:c}):a.push({path:d,state:"removed-modified",localHash:u,manifestHash:c})}return a}function Z(e,t){return`${e} ${t}${e===1?"":"s"}`}function Ir(e,t){let n=e.includes(`\r
113
+ enter from any device.)`)),a.blank();let m=await se();if(m){let[k,...w]=m.command,b=Cn(k,[...w,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});if(b.status===0){if(a.success("Outlook mailbox connected."),G){let K={entered:(l.emailAddress??"").trim(),token:await is(n)};await gt(_n(n),`${JSON.stringify(K)}
114
+ `,"utf-8").catch(()=>{})}}else a.blank(),console.log(g.yellow(`The Microsoft sign-in didn't complete (exit ${b.status??"signalled"}). Setup continues without it.`)),le(m)}else console.log(g.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),le(null)}else pe&&!C&&(a.blank(),console.log(g.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(g.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(g.cyan(" python3 scripts/ms_oauth.py login")));a.blank();let _=[...S,...x?["schema"]:[]];if(_.length>0){T.outro(g.yellow(g.bold(`Setup paused \u2014 ${_.join(", ")} failed.`))),console.log(g.dim("Your credentials and project files are all saved.")),a.blank();for(let[q,Ue]of Object.entries(I))console.log(g.yellow(`Likely cause of ${q} failure:`)),console.log(g.dim(` ${Ue}`)),a.blank();let m=n!==process.cwd()&&e.target?` ${g.cyan(`cd ${an(e.target)}`)}
115
+ `:"",k=l.aiAgent==="codex"?"codex":"claude",w=l.aiAgent==="codex"?"Codex":"Claude Code",b=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";S.length>0&&(console.log(g.dim(`Easiest fix \u2014 let ${w} finish it for you:`)),a.blank(),m&&process.stdout.write(m),console.log(` ${g.cyan(k)} ${g.dim(`# open ${w} in this folder`)}`),console.log(g.dim(" Then paste:")),console.log(g.cyan(` "Finish my Klaudius install \u2014 ${S.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),a.blank(),console.log(g.dim(` (Don't have ${w} yet? Install with: \`${b}\`)`)),a.blank(),console.log(g.dim("Or do it yourself:")),a.blank(),m&&process.stdout.write(m),console.log(` ${g.cyan("npx klaudius@latest install")} ${g.dim("# retry the failing installers")}`),console.log(` ${g.cyan("npx klaudius@latest doctor")} ${g.dim("# verify everything")}`),a.blank()),x&&(console.log(g.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${g.cyan(L)}`),console.log(g.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),a.blank()),S.includes("pip")&&!I.pip&&(console.log(g.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(g.dim(`Python 3.10+. Install a newer one from ${Zr()}`)),console.log(g.dim("and open a fresh Terminal before retrying.")),a.blank());let W=["npm","playwright","patchright"].filter(q=>S.includes(q)&&!I[q]);if(W.length>0){let q=W.length===1?"keeps":"keep";console.log(g.dim(`If ${W.join(" / ")} ${q} failing with network errors (ECONNRESET,`)),console.log(g.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(g.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),a.blank()}if(R&&(console.log(g.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${w}`)),console.log(g.dim("to finish setting it up \u2014 your email details are saved in .env.")),a.blank()),console.log(g.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),a.blank(),G){let q=[];x&&q.push(`Couldn't create the database tables: ${v.replace(/[:.\s]+$/,"")}. Check the database access token on the Database step.`);let Ue=S.filter(be=>be==="playwright"||be==="patchright"),ct=S.filter(be=>be!=="playwright"&&be!=="patchright");ct.length>0&&q.push(`Couldn't finish installing ${ct.join(", ")}. The install output says why.`),Ue.length>0&&q.push("Couldn't download the browsers Klaudius uses to gather business details, check the sites it builds and make invoices. The install output says why. If your network blocks large downloads, a different network, such as a phone hotspot, often gets past it."),q.push("Then try again \u2014 setup carries on from here. If it keeps failing, email hello@klaudius.dev with the last few lines."),Q(x&&S.length===0?"supabase":"install",q.join(`
116
+ `))}return}if(await ts(Tn(n),{force:!0}),await ts(_n(n),{force:!0}),ea(l,n,e.target),R){let m=l.aiAgent==="codex"?"Codex":"Claude Code";console.log(g.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(g.dim(`Your details are saved in .env. To finish it, ask ${m}:`)),console.log(g.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(g.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(g.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(g.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(g.cyan(' and send a test email to my own address to confirm."')),l.outreachEnabled&&(l.outreachChannels??[]).length>0&&(a.blank(),console.log(g.yellow(`Note: your other channel(s) \u2014 ${(l.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),a.blank()}}async function J(e,t){await on(e,{recursive:!0}),await gt(X(e,".env"),Nt(t),"utf-8"),t.aiAgent==="codex"?(await on(X(e,".codex"),{recursive:!0}),await gt(X(e,".codex","config.toml"),Dt(t),"utf-8")):(await gt(X(e,".mcp.json"),Mt(t),"utf-8"),await sn(e,"supabase"),await tt(e,et))}async function qr(e){try{(await In(e)).isDirectory()||(a.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ss(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),s=n.every(c=>i.has(c)),o=n.includes(".env"),r=t.includes(".klaudius");if(s&&o&&!r)return{kind:"partial",envPath:X(e,".env")};if(r&&o){let c=!0;try{c=!(await In(X(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function zr(e){a.blank(),a.warn(`Found a partial setup at ${g.bold(e)}.`),a.detail(`A previous init wrote ${g.bold(".env")} but didn't finish scaffolding.`),a.blank();let t=await T.select({message:`How would you like to proceed? ${g.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 T.isCancel(t)&&(T.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Jr(e){if(e&&e.trim().length>0)return e;T.intro("Klaudius");let t=await T.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 T.isCancel(t)&&(T.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Qr(e){let t=Br(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 Xr(){if(process.platform!=="win32")return!1;try{return Cn("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Zr(){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 ea(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",s=e.aiAgent==="codex"?"Codex":"Claude Code";if(T.outro(g.green(g.bold("Project ready."))),e.aiPlan){let o=(e.qaPhase??je(e.aiPlan))==="off";console.log(`${g.bold("Your plan:")} ${Ke[e.aiPlan]}`),console.log(g.dim(o?` \u2192 QA pass off${He.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(g.dim(` Change it any time: ask ${s} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),a.blank()}if(console.log(g.bold("Next steps:")),a.blank(),t!==process.cwd()&&n){let o=`cd ${an(n)}`;console.log(` ${g.cyan(o)}${" ".repeat(Math.max(1,27-o.length))}${g.dim("# go into your project folder")}`)}console.log(` ${g.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${g.dim(`# opens ${s} in this project`)}`),a.blank(),console.log(g.bold(`Some starter prompts for ${s}:`)),a.blank(),console.log(` ${g.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${g.cyan(`I know I'm ready to start using Klaudius."`)}`),a.blank(),console.log(` ${g.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),a.blank(),console.log(` ${g.cyan('"Run the pipeline for one client."')}`),console.log(g.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.")),a.blank(),e.aiAgent!=="codex"&&(console.log(g.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(g.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),a.blank())}import{access as ta,readFile as na}from"fs/promises";import{join as Rn,resolve as ia}from"path";import de from"picocolors";async function ls(e){let t=e.target?ia(process.cwd(),e.target):process.cwd(),n=await as(Rn(t,".env")),i=await as(Rn(t,"package.json"));(!n||!i)&&(a.error("This doesn't look like a Klaudius project."),a.detail(`Path: ${t}`),n||a.detail("Missing: .env"),i||a.detail("Missing: package.json"),a.blank(),a.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),a.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let s="claude-code";try{te(await na(Rn(t,".env"),"utf-8")).AI_AGENT==="codex"&&(s="codex")}catch{}a.heading("Installing dependencies");let o=await Xt(t);a.blank(),a.detail(`npm: ${o.npm}, pip: ${o.pip}, playwright: ${o.playwright}, patchright: ${o.patchright}`);let r=[];if(o.npm==="failed"&&r.push("npm"),o.pip==="failed"&&r.push("pip"),o.playwright==="failed"&&r.push("playwright"),o.patchright==="failed"&&r.push("patchright"),r.length===0){a.blank(),console.log(de.green(de.bold("All dependencies installed."))),console.log(de.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),a.blank();return}a.blank(),console.log(de.yellow(de.bold(`${r.join(", ")} still failing.`))),a.blank();for(let[d,y]of Object.entries(o.hints??{}))console.log(de.yellow(`Likely cause of ${d} failure:`)),console.log(de.dim(` ${y}`)),a.blank();let c=s==="codex"?"codex":"claude",u=s==="codex"?"Codex":"Claude Code",p=s==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(de.dim("Options:")),console.log(de.dim(` \u2022 Open ${u} in this folder (\`${c}\`) and paste:`)),console.log(de.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(de.dim(` (Don't have ${u} yet? Install with: \`${p}\`)`)),console.log(de.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(de.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),a.blank(),process.exitCode=1}async function as(e){try{return await ta(e),!0}catch{return!1}}import{readFile as sa,writeFile as vn,access as oa}from"fs/promises";import{join as st}from"path";import*as ue from"@clack/prompts";import Ce from"picocolors";import{mkdir as ra}from"fs/promises";import{spawnSync as cs}from"child_process";async function ds(e){let t=e.projectRoot??process.cwd(),n=st(t,".env"),i=st(t,".mcp.json"),s=st(t,".codex","config.toml"),o=await xn(st(t,".klaudius","manifest.json")),r=await xn(n);!o&&!r&&(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ve();c.ok||(a.error(c.message??"Node.js version check failed."),a.blank(),a.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let u={};try{let h=await sa(n,"utf-8");u=te(h)}catch{a.warn("No .env found. Starting from an empty configuration.")}let p=fi(u);Object.keys(u).length>0&&(p.pipelineModes??=["classic"]),ue.intro("Reconfigure Klaudius"),a.detail("Press Enter on any prompt to keep its current value."),a.blank();let d=await z(p),y=p.aiAgent??"claude-code";if(d.aiAgent&&d.aiAgent!==y&&(a.error(`Switching AI coding agent (${y} \u2192 ${d.aiAgent}) isn't supported via configure.`),a.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),a.blank(),console.log(` ${Ce.cyan("npx klaudius@latest init <new-folder>")} ${Ce.dim("# pick the new agent in the wizard")}`),a.blank(),a.detail(".env is unchanged."),process.exit(1)),d.supabaseUrl!==u.SUPABASE_URL||d.supabaseServiceKey!==u.SUPABASE_SERVICE_KEY){a.heading("Re-validating Supabase credentials");let h=await We({url:d.supabaseUrl,serviceKey:d.supabaseServiceKey});h.ok||(a.error(h.message??"Supabase check failed"),a.warn("Aborting. .env not modified."),process.exit(1)),a.success("Supabase credentials accepted")}let f=la(d,u);if(f==="vercel"){let h=ue.spinner();h.start("Validating Vercel token");let l=await qe(d.vercelToken??"");l.ok?h.stop(l.username?`Vercel token accepted (signed in as ${l.username})`:"Vercel token accepted"):(h.stop(l.message,2),a.warn("Writing the token exactly as you entered it \u2014 not verified."),a.detail(l.kind==="rejected"||l.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`.":l.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(f==="cloudflare"){let h=ue.spinner();h.start("Validating Cloudflare token + account");let l=await ze({token:d.cloudflareApiToken??"",accountId:d.cloudflareAccountId??""});l.ok?h.stop("Cloudflare credentials accepted"):(h.stop(l.message??"Cloudflare check failed",2),a.warn("Writing the credentials exactly as you entered them \u2014 not verified."),a.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(f==="netlify"){let h=ue.spinner();h.start("Validating Netlify token");let l=await Je({token:d.netlifyAuthToken??""});l.ok?h.stop(l.accountSlug?`Netlify token accepted (team: ${l.accountSlug})`:"Netlify token accepted"):(h.stop(l.message??"Netlify check failed",2),a.warn("Writing the token exactly as you entered it \u2014 not verified."),a.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let A=Re(d.googlePlacesApiKey??"");if(A.changed&&d.googlePlacesApiKey){a.heading("Checking your Google Places API key");let h=await Qe(d.googlePlacesApiKey);if(h.ok){if(A.repairs.length>0){a.warn("Corrected look-alike characters in your Google Places API key:");for(let l of A.repairs)a.detail(` ${l}`);a.detail("These come from keys that were transcribed rather than copied.")}d.googlePlacesApiKey=A.value,a.success("Google accepted the key \u2014 writing the corrected value to .env")}else a.error(h.message??"Google rejected the Google Places API key"),a.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),a.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(aa(d,u)){let h=ue.spinner();h.start("Validating email credentials (SMTP + IMAP)");let l=d.emailProvider&&d.emailProvider!=="custom"?d.emailProvider:Me(d.emailSmtpHost),P=await _e({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:l?ce[l].usesAccountPassword:void 0,knownProvider:!!l,sentFolder:(d.emailSentFolder??"").trim()||"Sent",draftsFolder:(d.emailDraftsFolder??"").trim()||"Drafts"});P.ok?(h.stop("Email credentials accepted (SMTP + IMAP)"),await zt(P,d,{nonInteractive:!1,onCancel:()=>a.detail("Left the folder names as they are.")})):(h.stop(P.message??"Email check failed",2),a.warn("Writing the email settings exactly as you entered them \u2014 not verified."),a.detail(P.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 vn(n,Nt(d),"utf-8"),a.success("Updated .env"),d.aiAgent==="codex"?(await ra(st(t,".codex"),{recursive:!0}),await vn(s,Dt(d),"utf-8"),a.success("Updated .codex/config.toml")):(await vn(i,Mt(d),"utf-8"),a.success("Updated .mcp.json"),await sn(t,"supabase"),await tt(t,et)),d.emailAuth==="oauth-microsoft"&&d.outreachEnabled&&d.outreachChannels?.includes("email")){let h=await se();if(!(h!==null&&cs(h.command[0],[...h.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(a.blank(),!h)a.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),a.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let P=await ue.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});ue.isCancel(P)||!P?a.detail(`Skipped. Connect it any time with: ${h.command.join(" ")} scripts/ms_oauth.py login`):cs(h.command[0],[...h.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?a.success("Outlook mailbox connected."):(a.warn("The Microsoft sign-in didn't complete."),a.detail(`Connect it any time with: ${h.command.join(" ")} scripts/ms_oauth.py login`))}}a.blank(),ue.outro(Ce.green("Configuration updated.")),await ca(t,o)}function aa(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(([s])=>s===void 0||s===""))return!1;let i=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([s,o])=>String(s)!==(t[o]??""))||i.some(([s,o])=>s!==void 0&&s!==(t[o]??""))}function la(e,t){let n=(i,s)=>(i??"")!==(t[s]??"");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 ca(e,t){let n=await xn(st(e,"node_modules"));a.blank(),t?n||(a.detail("Your project files are in place but dependencies aren't installed yet."),a.detail("To finish setup, run:"),a.blank(),console.log(` ${Ce.cyan("npx klaudius@latest install")} ${Ce.dim("# (re-)installs npm + pip + browsers; idempotent")}`),a.blank(),a.detail("Then verify with:"),a.blank(),console.log(` ${Ce.cyan("npx klaudius@latest doctor")} ${Ce.dim("# checks Node / Python / installers / credentials")}`),a.blank()):(a.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),a.detail("To finish setup, run:"),a.blank(),console.log(` ${Ce.cyan("npx klaudius@latest init")} ${Ce.dim("# pick Resume when prompted")}`),a.blank())}async function xn(e){try{return await oa(e),!0}catch{return!1}}import{copyFile as Un,mkdir as cn,readFile as At,rm as Ae,writeFile as dn,access as Hn}from"fs/promises";import{dirname as un,join as O}from"path";import{tmpdir as La}from"os";import*as Le from"@clack/prompts";import Et from"picocolors";import{execFile as Dn}from"child_process";import{createHash as da}from"crypto";import{access as ua,copyFile as ws,lstat as pa,mkdir as Ln,mkdtemp as ks,open as fa,readFile as oe,realpath as ha,rm as rt,stat as As,unlink as ma,writeFile as wt}from"fs/promises";import{tmpdir as Es}from"os";import{dirname as Fe,isAbsolute as On,join as F,relative as us,resolve as yt}from"path";var Nn={"Edit conflict":["keep-mine","take-new","check-merge","merge","auto-merge"],"Deleted locally":["restore","keep-deleted"],"Removed upstream":["keep-mine","delete"]},Mn=F(".klaudius","conflicts.md"),Fn=F(".klaudius","incoming"),ga=F(".klaudius","resolve.lock"),kt=F(".klaudius","merged"),ya=12e4,wa=3e4,ka=[["keepMine","keep-mine"],["takeNew","take-new"],["checkMerge","check-merge"],["merge","merge"],["autoMerge","auto-merge"],["restore","restore"],["keepDeleted","keep-deleted"],["delete","delete"]];function Ps(e,t){let n=ka.filter(([s])=>t[s]!==void 0&&t[s]!==!1),i=[t.checkMerge,t.merge].find(s=>typeof s=="string");return{path:e,action:n.length===1?n[0][1]:void 0,draft:i,finish:t.finish===!0}}function Aa(e){let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return`.klaudius/merged/draft${n>0?t.slice(n):""}`}function ps(e,t,n,i){if(/^(<<<<<<<|>>>>>>>)/m.test(t))return"still has conflict markers (<<<<<<< or >>>>>>>): finish the merge first";if(!e.toLowerCase().endsWith(".json")||n===null||i===null)return null;let s=r=>{try{return JSON.parse(r.replace(/^/,"")),null}catch(c){return c.message}};if(s(n)!==null||s(i)!==null)return null;let o=s(t);return o===null?null:`isn't valid JSON (${o})`}function $n(e){let t=[];for(let n=0;n<e.length;n++){let i=e[n];if(i==='"'){let s=n+1;for(;s<e.length&&e[s]!=='"';)s+=e[s]==="\\"?2:1;let o=s+1;for(;o<e.length&&/\s/.test(e[o]);)o++;let r=t[t.length-1];if(e[o]===":"&&r){let c=e.slice(n+1,s);if(r.has(c))return c;r.add(c)}n=s}else i==="{"?t.push(new Set):i==="["?t.push(null):(i==="}"||i==="]")&&t.pop()}return null}var Ea={".js":[process.execPath,["--check"]],".mjs":[process.execPath,["--check"]],".cjs":[process.execPath,["--check"]],".sh":["bash",["-n"]],".py":["python3",["-c","import ast, sys; ast.parse(open(sys.argv[1], 'rb').read(), sys.argv[1])"]]};async function fs(e,t,n,i,s){let o=e.slice(e.lastIndexOf("/")+1),r=o.lastIndexOf("."),c=r>0?o.slice(r).toLowerCase():"";if(c===".json"){let f=h=>{try{return JSON.parse(h.replace(/^/,"")),!0}catch{return!1}};if(!f(n)||!f(i)||$n(n)!==null||$n(i)!==null)return null;let A=$n(t.toString());return A===null?null:`gives the key "${A}" twice`}let u=c===".js"?await Pa(s)==="module"?".mjs":".cjs":c,p=Ea[u];if(!p)return null;let d={...process.env,NO_COLOR:"1",PYTHON_COLORS:"0"};delete d.FORCE_COLOR;let y;try{y=await ks(F(Es(),"klaudius-check-"))}catch{return null}try{let f=async(h,l)=>{let P=F(y,`${l}${u}`);await wt(P,h);let R=await ha(P).catch(()=>P);return new Promise(x=>Dn(p[0],[...p[1],P],{windowsHide:!0,timeout:1e4,env:d},(v,L,S)=>{if(!v||v.killed||v.signal||typeof v.code!="number")return x(null);let I=String(S).split(/\r?\n/).map(M=>M.split(R).join(e).split(P).join(e).trim()).filter(Boolean),N=I.find(M=>/^\w*Error\b|syntax error/i.test(M))??I[I.length-1]??v.message.split(`
117
+ `)[0],j=I.find(M=>M.includes(e))?.match(/(?:line |:)(\d+)/)?.[1];x(j&&!/\bline \d+/.test(N)?`${N}, line ${j}`:N)}))};if(await f(n,"yours")!==null||await f(i,"new")!==null)return null;let A=await f(t,"merged");return A===null?null:`no longer parses (${A})`}catch{return null}finally{await rt(y,{recursive:!0,force:!0}).catch(()=>{})}}async function Pa(e){for(let t=yt(e);;t=Fe(t)){let n=await oe(F(t,"package.json"),"utf-8").catch(()=>null);if(n!==null)try{return JSON.parse(n).type??"commonjs"}catch{return"commonjs"}if(Fe(t)===t)return"commonjs"}}function ba(e){let t=e.split(`
118
+ `),n=[],i=!1;t.forEach((o,r)=>{o.startsWith("```")?i=!i:!i&&o.startsWith("## ")&&n.push({path:o.slice(3).trim(),start:r})});let s=n.map((o,r)=>{let c=r+1<n.length?n[r+1].start:t.length,p=t.slice(o.start,c).find(d=>d.startsWith("**Type:**"))?.slice(9).trim();return{...o,end:c,type:p!==void 0&&p in Nn?p:null}});return{lines:t,sections:s}}function Sa(e,t,n){let i=[...e.lines.slice(0,t.start),...e.lines.slice(t.end)],s=i.findIndex(r=>r.startsWith("Updating from")),o=s>=0&&s+2<e.sections[0].start?i[s+2]:"";return o.trim()!==""&&!o.startsWith("Open ")&&!o.startsWith("---")&&(i[s+2]=`${n} ${n===1?"conflict is":"conflicts are"} still waiting for a decision; the others are settled.`),i.join(`
119
+ `)}function Ta(e){let t=e.match(/^Generated by .* on (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/m)?.[1];return`.klaudius/backup/resolve-${t?t.replace(/[:.]/g,"-"):"undated"}`}var ot=e=>ua(e).then(()=>!0,()=>!1);async function _a(e,t,n){let i=`${n}.bak`;for(let o=2;await ot(F(e,t,i));o++)i=`${n}.${o}.bak`;let s=F(e,t,i);return await Ln(Fe(s),{recursive:!0}),await ws(F(e,n),s),`${t}/${i}`}function Ia(e,t,n,i){let s=y=>{let f=new Map;for(let A of y.split(/\r\n|\r|\n/))A.trim()&&f.set(A,(f.get(A)??0)+1);return f},o=(y,f)=>y.get(f)??0,r=s(e),c=s(i),u=[["Your",s(t)],["The update's",s(n)]],p=y=>{let f=o(r,y),A=o(u[0][1],y)-f,h=o(u[1][1],y)-f,l=Math.max(0,f+A+h);return A>0&&h>0?{min:f+Math.max(A,h),max:l}:A<0&&h<0?{min:l,max:Math.max(0,f+Math.min(A,h))}:{min:l,max:l}},d=[];for(let[y,f]of u){let A=[...new Set([...f.keys(),...r.keys()])].filter(P=>o(f,P)!==o(r,P)),h=A.filter(P=>o(f,P)>o(r,P)&&o(c,P)<p(P).min),l=A.filter(P=>o(f,P)<o(r,P)&&o(c,P)>p(P).max);d.push(`${y} edits kept: ${A.length-h.length-l.length} of ${A.length}`);for(let P of h)d.push(` dropped: ${P.trim().slice(0,120)}`);for(let P of l)d.push(` still present: ${P.trim().slice(0,120)}`)}return d}function Ca(e,t,n){return new Promise(i=>{Dn("git",["merge-file","-p",e,t,n],{encoding:"buffer",maxBuffer:64*1024*1024,windowsHide:!0},(s,o)=>{if(!s)return i({merged:o});let r=s.code;if(typeof r=="number"&&r>0&&r<128)return i({overlaps:r});i({unavailable:s.message.split(`
120
+ `)[0]})})})}var hs=40;function Ra(e,t){let n=c=>{let u=c.toLowerCase(),p=new Map;for(let d=0;d<u.length-1;d++)p.set(u.slice(d,d+2),(p.get(u.slice(d,d+2))??0)+1);return p},[i,s]=[n(e),n(t)],o=0,r=0;for(let[c,u]of i)o+=Math.min(u,s.get(c)??0),r+=u;for(let c of s.values())r+=c;return r>0&&2*o/r>=.5}async function va(e,t,n,i){let s=r=>r.replace(/\r\n?/g,`
121
+ `),o;try{o=await ks(F(Es(),"klaudius-clash-"))}catch{return[]}try{let[r,c,u]=["mine","base","theirs"].map(v=>F(o,v));await wt(r,s(t)),await wt(c,s(e)),await wt(u,s(n));let p=await new Promise(v=>Dn("git",["merge-file","-p","--diff3",`--marker-size=${hs}`,r,c,u],{encoding:"utf8",maxBuffer:64*1024*1024,windowsHide:!0},(L,S)=>{let I=L?.code;v(!L||typeof I=="number"&&I>0&&I<128?S:null)}));if(p===null)return[];let d=v=>{let L=new Map;for(let S of s(v).split(`
122
+ `)){let I=S.trim();I&&L.set(I,(L.get(I)??0)+1)}return L},y=(v,L)=>v.get(L)??0,[f,A,h]=[d(i),d(t),d(n)],l=v=>v.repeat(hs),P=[],R=null,x={mine:[],base:[],theirs:[]};for(let v of p.split(`
123
+ `))if(v.startsWith(`${l("<")} `))R="mine",x={mine:[],base:[],theirs:[]};else if(R&&v.startsWith(`${l("|")} `))R="base";else if(R&&v===l("="))R="theirs";else if(R&&v.startsWith(`${l(">")} `)){let L=j=>j.map(M=>M.trim()),S=L(x.mine),I=L(x.base),N=L(x.theirs);if(I.length>0&&S.length===I.length&&N.length===I.length)for(let j=0;j<I.length;j++){let[M,pe,C]=[S[j],I[j],N[j]];!M||!C||M===pe||C===pe||M===C||!Ra(M,C)||y(f,M)>y(h,M)&&y(f,C)>y(A,C)&&P.push(` kept both versions: ${M.slice(0,120)} / ${C.slice(0,120)}`)}R=null}else R&&x[R].push(v);return P}catch{return[]}finally{await rt(o,{recursive:!0,force:!0}).catch(()=>{})}}async function ms(e,t,n,i){let s=await oe(F(e,Te,t),"utf-8").catch(()=>null);if(s===null)return["No pre-edit base was staged for this file, so there is no line check. Say in plain words what the merge keeps from each side."];let o=await oe(F(e,i,`${t}.bak`),"utf-8").catch(()=>null)??await oe(F(e,t),"utf-8").catch(()=>""),r=await oe(F(e,Fn,t),"utf-8");return[s,o,r,n].some(Oe)?["Binary file: no line check."]:["Line check against the pre-edit base:",...Ia(s,o,r,n),...await va(s,o,r,n)]}function ln(e,t,n=0){for(let i of e)console.log(i);return console.log(`[klaudius-resolve] ${t}`),n}function D(e,t){return console.error(`${e} Nothing was changed.`),console.log(`[klaudius-resolve] refused${t===void 0?"":` remaining=${t}`}`),1}async function gs(e,t,n,i){let s=n?.match(/to \*\*([^*]+)\*\*/)?.[1]?.trim();(i||s||t.pendingConflicts!==void 0)&&(s&&(t.templateVersion=s),delete t.pendingConflicts,t.updatedAt=new Date().toISOString(),await xe(e,t));let o=c=>rt(F(e,c),{recursive:!0,force:!0,maxRetries:3}).then(()=>!0,()=>!1);if(!await o(Mn))return{complete:!1,lines:[".klaudius/conflicts.md couldn't be removed, so the update staging was kept. Close anything that has it open, then run the same command again."]};let r=!1;for(let c of[Fn,Te,kt])await o(c)||(r=!0);return{complete:!0,lines:[r?"Nothing is waiting for a decision. Some staging under .klaudius/ couldn't be removed; the next update clears it.":"Nothing is waiting for a decision. Update staging cleared."]}}var ys=e=>new Promise(t=>setTimeout(t,e));function xa(e,t){if(Date.now()-t>ya)return!0;let n=Number(e.trim());if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!1}catch(i){return i.code==="ESRCH"}}async function Oa(e,t){let n=F(e,ga),i=Date.now(),s=!1,o=0;for(;;)try{let r=await fa(n,"wx");await r.writeFile(String(process.pid)).finally(()=>r.close());break}catch(r){let c=r.code;if(c!=="EEXIST"&&c!=="EPERM")throw r;let u=await As(n).catch(()=>null);if(u===null){if(c==="EPERM"&&++o>5)throw r;await ys(50);continue}let p=await oe(n,"utf-8").catch(()=>"");if(!s&&xa(p,u.mtimeMs)){s=!0,await oe(n,"utf-8").catch(()=>"")===p&&await rt(n).catch(d=>{if(d.code!=="ENOENT")throw new Error(`.klaudius/resolve.lock was left by an earlier run and can't be removed (${d.message})`)});continue}if(Date.now()-i>wa)return null;await ys(100)}try{return await t()}finally{await rt(n,{force:!0}).catch(()=>{})}}async function bs(e){let t=e.projectRoot??process.cwd();return await ot(F(t,".klaudius","manifest.json"))?await Oa(t,()=>$a(t,e))??D("Another resolve is still running in this project; run this again once it has finished."):D("No .klaudius/manifest.json here: run this from the Klaudius project folder.")}async function $a(e,t){let n;try{n=await jt(e)}catch(C){return D(`.klaudius/manifest.json can't be read (${C.message}).`)}if(!n)return D("No .klaudius/manifest.json here: run this from the Klaudius project folder.");let i=await oe(F(e,Mn),"utf-8").catch(()=>null),s=i===null?null:ba(i);if(t.finish){if(t.path||t.action)return D("--finish takes no file or action.");let C=s?.sections.length??0;if(C>0)return D(`${C} ${C===1?"conflict is":"conflicts are"} still waiting in .klaudius/conflicts.md.`,C);let B=await gs(e,n,i,!1);return ln(B.lines,B.complete?"finished remaining=0":"remaining=0 incomplete",B.complete?0:1)}if(!t.path||!t.action)return D("Name one file and exactly one action.",s?.sections.length);if(!s)return D("No conflicts are staged (.klaudius/conflicts.md is missing).",0);let o=s.sections.length,r=t.path.split("\\").join("/");if(On(t.path)&&(r=us(e,t.path).split("\\").join("/")),r=r.replace(/^\.\//,""),r===""||On(r)||/^[a-zA-Z]:/.test(r)||r.split("/").includes(".."))return D(`${t.path} isn't a path inside this project.`,o);let c=s.sections.find(C=>C.path===r);if(!c)return D(`${r} isn't waiting in .klaudius/conflicts.md (waiting: ${s.sections.map(C=>C.path).join(", ")||"none"}).`,o);let u=F(e,r),p=F(e,Fn,r),d=await ot(u),y=await ot(p),f=c.type??(y?d?"Edit conflict":"Deleted locally":"Removed upstream"),A=t.action;if(!Nn[f].includes(A))return D(`${r} is a "${f}" conflict; its options are ${Nn[f].map(C=>`--${C}`).join(", ")}.`,o);if(f!=="Removed upstream"&&!y)return D(`The staged new version .klaudius/incoming/${r} is missing; run npx klaudius@latest update to stage it again.`,o);if(f==="Edit conflict"&&!d&&(A==="keep-mine"||A==="check-merge"||A==="merge"||A==="auto-merge"))return D(`${r} is no longer on disk, so there's no version of yours to ${A==="keep-mine"?"keep":"merge"}; choose --take-new.`,o);let h=Ta(i),l=null,P=[];if(A==="check-merge"||A==="merge"){if(!t.draft)return D(`--${A} needs the merged draft's path.`,o);if(l=yt(e,t.draft),process.platform==="linux"?l===yt(u):l.toLowerCase()===yt(u).toLowerCase())return D(`Write the merged version to its own draft file (${Aa(r)}), not over ${r}: the original is what gets backed up.`,o);let B=await oe(l,"utf-8").catch(()=>null);if(B===null)return D(`Can't read the draft ${t.draft}.`,o);let ie=await oe(p,"utf-8").catch(()=>null),Z=await oe(u,"utf-8").catch(()=>null),fe=ps(r,B,ie,Z)??(ie!==null&&Z!==null?await fs(r,B,Z,ie,Fe(u)):null);if(fe)return D(`The draft ${t.draft} ${fe}.`,o);if(P=await ms(e,r,B,h),A==="check-merge")return ln(P,`checked path=${r} remaining=${o}`)}let R=null;if(A==="auto-merge"){if(r.split("/").pop()===".gitignore")return D(".gitignore is only merged as a union (every line of the user's kept, the new patterns added, nothing removed), so it can't be merged automatically; merge it by hand.",o);let C=F(e,Te,r);if(!await ot(C))return D(`${r} has no pre-edit base, so it can't be merged automatically; merge it by hand.`,o);let B=F(e,h,`${r}.bak`),ie=await ot(B)?B:u,Z=await Ca(ie,C,p);if("overlaps"in Z)return D(`Your edits and the update's overlap in ${r} (${Z.overlaps} place${Z.overlaps===1?"":"s"}), so it can't be merged automatically; merge it by hand.`,o);if("unavailable"in Z)return D(`git merge-file couldn't run (${Z.unavailable}), so ${r} can't be merged automatically; merge it by hand.`,o);let fe=Z.merged.toString("utf-8"),E=await oe(p,"utf-8").catch(()=>null),$=await oe(ie,"utf-8").catch(()=>null),U=ps(r,fe,E,$)??(E!==null&&$!==null?await fs(r,Z.merged,$,E,Fe(u)):null);if(U)return D(`The automatic merge of ${r} ${U}; merge it by hand.`,o);P=await ms(e,r,fe,h);let le=P.filter(_=>/^\s+(dropped|still present|kept both versions):/.test(_)).map(_=>_.trim());if(le.length>0)return D(`The automatic merge of ${r} doesn't keep every edit (${le.join("; ")}); merge it by hand.`,o);R=Z.merged}if(A==="keep-deleted"&&d)return D(`${r} exists again, so it can't stay deleted; choose --restore, or move the file away first.`,o);let x=y?await ge(p):void 0,v=A==="take-new"||A==="restore"?x:A==="merge"?await ge(l):R?da("sha256").update(R).digest("hex"):void 0,L=d&&(A==="delete"||v!==void 0&&await ge(u)!==v),S=null;if(L)try{S=await _a(e,h,r)}catch(C){return D(`Couldn't save a backup copy of ${r} (${C.message}).`,o)}let I=[];switch(A){case"keep-mine":f==="Edit conflict"?(n.files[r]=x,I.push(`Kept your version of ${r}. Later updates treat it as your edit.`)):(delete n.files[r],I.push(`Kept ${r}. Klaudius no longer tracks it, so updates leave it alone.`));break;case"take-new":case"restore":await Ln(Fe(u),{recursive:!0}),await ws(p,u),n.files[r]=x,n.ignored&&(n.ignored=n.ignored.filter(C=>C!==r)),I.push(A==="take-new"?`Replaced ${r} with the new version.`:`Restored ${r} in its new version.`);break;case"merge":case"auto-merge":{let C=d?(await As(u)).mode&4095:void 0,B=R??await oe(l);await Ln(Fe(u),{recursive:!0}),d&&(await pa(u)).isSymbolicLink()?await wt(u,B):await pt(u,B,C),n.files[r]=x,I.push(`Wrote the merged version to ${r}.`,...P);break}case"keep-deleted":delete n.files[r],n.ignored=[...new Set([...n.ignored??[],r])],I.push(`${r} stays deleted; updates won't reinstall it.`);break;case"delete":d&&await rt(u,{force:!0}),delete n.files[r],I.push(`Deleted ${r}.`);break}S&&I.push(`Your previous version is saved at ${S}.`);let N=o-1,j=!0;if(N>0)n.pendingConflicts=N,n.updatedAt=new Date().toISOString(),await xe(e,n),await pt(F(e,Mn),Sa(s,c,N));else{let C=await gs(e,n,i,!0);I.push(...C.lines),j=C.complete}let M=l===null?"":us(yt(e,kt),l);j&&M&&!M.startsWith("..")&&!On(M)&&await ma(l).catch(()=>{});let pe=`path=${r} action=${A} remaining=${N}`;return j?ln(I,pe):ln(I,`${pe} incomplete`,1)}var Pt="0.35.0";async function _s(e){let t=e.projectRoot??process.cwd(),n=await jt(t);n||(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let E of Ut)delete n.files[E];let i,s=O(t,".env"),o,r;try{o=await At(s,"utf-8"),r=te(o)}catch{a.error("Couldn't read .env from this directory."),a.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=r.KLAUDIUS_LICENSE_KEY??"",i||(a.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),a.detail("This file is created by `npx klaudius@latest init`. If your project predates"),a.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),a.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=e.check?null:di(o,r,ci);c!==null&&(await dn(s,c,"utf-8"),a.detail("Backfilled new env keys")),await Vt("update",Pt),Le.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Pt}`),await Zt();let p=r.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&p==="claude-code"&&await tt(t,et)==="added"&&a.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let d=O(La(),`klaudius-update-${process.pid}-${Date.now()}`),y;try{a.heading("Downloading the latest Klaudius template");let E=await Gt({licenseKey:i,machineId:mt(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:d});a.success(`Fetched ${E.filesExtracted} canonical files`),y=d}catch(E){a.error(E.message),a.detail("Update aborted. Your project is unchanged."),await Ae(d,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let f=await Ma(y,t,n);if(e.check){let E=f.filter(_=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(_.state)),$=f.filter(_=>["conflict","locally-deleted","removed-modified"].includes(_.state)&&!(_.path===".gitignore"&&_.state==="conflict")),U="unknown";if(r.SUPABASE_URL&&r.SUPABASE_SERVICE_KEY){let _=await At(O(y,"scripts","schema.sql"),"utf-8").catch(()=>""),m=await Wt({url:r.SUPABASE_URL,serviceKey:r.SUPABASE_SERVICE_KEY,sql:_});m.unreachable?a.detail(`Database schema not checked (${m.unreachable}).`):m.ok?U="current":(U="stale",a.detail(`Database schema is behind (missing: ${m.missing.join(", ")}); update applies scripts/schema.sql.`))}let le=E.length>0||U==="stale";a.blank(),le?(E.length>0&&a.detail(`${ee(E.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),Le.outro(Et.yellow("An update is available."))):Le.outro(Et.green("Already up to date.")),console.log(`[klaudius-update-check] status=${le?"behind":"current"} pending=${E.length+(U==="stale"?1:0)} conflicts=${$.length} schema=${U}`),await Ae(d,{recursive:!0,force:!0}).catch(()=>{});return}let A=!1,h=f.find(E=>E.path===".gitignore"&&E.state==="conflict");if(h){let E=O(t,".gitignore"),$=await At(E,"utf-8"),U=await At(O(y,".gitignore"),"utf-8"),{merged:le,added:_}=Fa($,U);_.length>0&&await dn(E,le,"utf-8"),n.files[".gitignore"]=h.canonicalHash,h.state="gitignore-merged",A=!0,a.detail(_.length>0?`.gitignore auto-merged: kept all your lines, appended ${ee(_.length,"new canonical pattern")}: ${_.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let l=f.filter(E=>E.state==="new"),P=f.filter(E=>E.state==="clean-update"),R=f.filter(E=>E.state==="user-only"),x=f.filter(E=>E.state==="conflict"),v=f.filter(E=>E.state==="no-change"),L=f.filter(E=>E.state==="locally-deleted"),S=f.filter(E=>E.state==="removed-clean"),I=f.filter(E=>E.state==="removed-modified"),N=[...x,...L,...I],j=n.ignored?.length??0;a.blank(),a.heading("Change summary"),a.detail(`${ee(v.length,"file")} unchanged`),a.detail(`${ee(l.length,"new file")}`),a.detail(`${ee(P.length,"file")} updated cleanly (no local edits)`),a.detail(`${ee(R.length,"file")} you've edited (no upstream change \u2014 left alone)`),a.detail(`${ee(S.length,"file")} removed upstream (deleted cleanly)`);let M=x.filter(E=>E.reason==="untracked-local").length,pe=x.filter(E=>E.reason==="manifest-mismatch").length;a.detail(`${ee(x.filter(E=>!E.reason).length,"file")} with conflicts (you edited AND we have a new version)`),M>0&&a.detail(`${ee(M,"file")} of your own at a path the new version now ships (need your decision)`),pe>0&&a.detail(`${jn(pe)}, and we have a new version (need your decision)`),a.detail(`${ee(L.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`);let C=I.filter(E=>E.reason==="manifest-mismatch").length;if(a.detail(`${ee(I.length-C,"file")} removed upstream but edited locally (need your decision)`),C>0&&a.detail(`${jn(C)}, removed upstream (need your decision)`),j>0&&(a.detail(`${ee(j,"file")} kept deleted (previously resolved \u2014 skipped)`),j<=10))for(let E of n.ignored)a.detail(` kept deleted: ${E}`);let B=async()=>{let E=!1,$=U=>Ae(U,{recursive:!0,force:!0}).catch(()=>{E=!0});await $(O(t,".klaudius","incoming")),await $(O(t,Te)),await $(O(t,kt)),await $(O(t,".klaudius","conflicts.md")),E&&a.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/, .klaudius/merged/ and .klaudius/conflicts.md by hand)")};if(l.length===0&&P.length===0&&S.length===0&&N.length===0&&!A){await Ss(t,r,!1),await B(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Pt,await xe(t,n)),a.blank(),Le.outro(Et.green("Already up to date.")),await Ae(d,{recursive:!0,force:!0}).catch(()=>{});return}let ie=new Date().toISOString().replace(/[:.]/g,"-"),Z=`.klaudius/backup/update-${ie}`,fe=0;for(let E of[...P,...S]){if(E.localHash===void 0||E.localHash===E.canonicalHash)continue;let $=O(t,Z,`${E.path}.bak`);try{await cn(un($),{recursive:!0}),await Un(O(t,E.path),$)}catch(U){a.error(`Couldn't save a backup copy of ${E.path}: ${U.message}`),a.detail("Update stopped before replacing or removing any files (additions already made, such as new .env keys, are kept)."),await Ae(d,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}fe++}a.blank(),a.heading("Applying clean updates");for(let E of[...l,...P]){let $=O(y,E.path),U=O(t,E.path);await cn(un(U),{recursive:!0}),await Un($,U),n.files[E.path]=E.canonicalHash}l.length+P.length>0&&a.success(`Wrote ${ee(l.length+P.length,"file")}`),[...l,...P].some(E=>E.path==="package.json"||E.path==="package-lock.json")&&a.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let E of S){let $=O(t,E.path);await Ae($,{force:!0}),delete n.files[E.path]}if(S.length>0){a.success(`Deleted ${ee(S.length,"file")} removed upstream`);for(let E of S.slice(0,20))a.detail(` removed: ${E.path}`);S.length>20&&a.detail(` \u2026and ${S.length-20} more`)}if(fe>0&&a.detail(`Previous copies of the ${ee(fe,"file")} replaced or removed are in ${Z}/ (each saved as <name>.bak)`),await Ss(t,r,N.some(E=>E.path==="scripts/schema.sql")),N.length>0){a.blank(),a.heading(`${N.length} conflict(s) need resolution`);let E=O(t,".klaudius","incoming");try{await Ae(E,{recursive:!0,force:!0})}catch{}await Ae(O(t,kt),{recursive:!0,force:!0}).catch(()=>{});for(let _ of[...x,...L]){let m=O(y,_.path),k=O(E,_.path);await cn(un(k),{recursive:!0}),await Un(m,k)}let $=new Map,U=new Map;for(let _ of x){let m=await xi(t,_.path),k=await Oi(t,_.path),w=await At(O(y,_.path),"utf-8"),b=$i(m,k,w,_.manifestHash);_.reason==="untracked-local"?$.set(_.path,["_Klaudius doesn't track this file (it's your own, or one kept after an earlier version dropped it), and the new version ships one at the same path. No common base exists: compare your copy with `.klaudius/incoming/"+_.path+"` directly._"]):_.reason==="manifest-mismatch"?$.set(_.path,["_The manifest's entry for this file isn't the version Klaudius last installed (a hand-edited manifest, a conflict resolved outside `/resolve-conflicts`, or a folder restored from an older copy), so your copy was left in place. No verified base exists: compare it with `.klaudius/incoming/"+_.path+"` directly. If the file was never changed on purpose, taking the new version is safe._"]):b!==null?(U.set(_.path,b),$.set(_.path,Li(b,w))):m!==null&&(Oe(m)||Oe(w))?$.set(_.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+_.path+"` directly._"]):m===null?$.set(_.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._"]):$.set(_.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/"+_.path+"` directly._"])}let le=O(t,Te);try{await Ae(le,{recursive:!0,force:!0})}catch{}for(let[_,m]of U){let k=O(le,_);await cn(un(k),{recursive:!0}),await dn(k,m,"utf-8")}await dn(O(t,".klaudius","conflicts.md"),Ua(N,n.templateVersion,Pt,$,U),"utf-8"),x.length+L.length>0&&a.detail("Staged canonical versions to .klaudius/incoming/"),U.size>0&&a.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),a.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Pt,n.baseSnapshot=ie,N.length===0?(delete n.pendingConflicts,await B()):n.pendingConflicts=N.length,await xe(t,n);try{await Bt(t,y,await De(y),ie)}catch{a.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(a.blank(),N.length===0)Le.outro(Et.green("Update complete."));else{let E=p==="codex"?"Codex":"Claude Code";Le.outro(Et.yellow(`${N.length} conflict(s) staged. Open ${E} in this project and ask:
124
+ "Run /resolve-conflicts"`))}await Ae(d,{recursive:!0,force:!0}).catch(()=>{})}async function Ss(e,t,n){let i=await Na(e,t,n);return console.log(`[klaudius-update] schema=${i}`),i}async function Na(e,t,n){let i=(t.SUPABASE_PAT??"").replace(/\s+/g,""),s=(t.SUPABASE_PROJECT_REF??"").trim();if(!i||!s)return a.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 o=await Yt({projectRoot:e,pat:i,projectRef:s});return o.ok?(a.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"):(a.warn(o.message??"Database schema could not be applied"),a.detail(`Paste scripts/schema.sql into the SQL editor to apply it by hand (safe to re-run): ${Ui(s)}`),"failed")}async function Ma(e,t,n){let i=await De(e),s=new Set(i),o=new Map;for(let p of i)o.set(p,await ge(O(e,p)));let r=await Da(t,n,o),c=new Set(n.ignored??[]),u=[];for(let p of i){if(c.has(p))continue;let d=o.get(p),y=n.files[p],f=O(t,p),A;try{await Hn(f),A=await ge(f)}catch{let l=y!==void 0&&!Ai.has(p)&&!Ht.has(p)?"locally-deleted":"new";u.push({path:p,state:l,canonicalHash:d,manifestHash:y});continue}let h=Ht.has(p);d===y?A===y||h?u.push({path:p,state:"no-change",canonicalHash:d,localHash:A,manifestHash:y}):u.push({path:p,state:"user-only",canonicalHash:d,localHash:A,manifestHash:y}):A===d||h?u.push({path:p,state:"clean-update",canonicalHash:d,localHash:A,manifestHash:y}):y===void 0?u.push({path:p,state:"conflict",reason:"untracked-local",canonicalHash:d,localHash:A,manifestHash:y}):A!==y?u.push({path:p,state:"conflict",canonicalHash:d,localHash:A,manifestHash:y}):await r(p,y)?u.push({path:p,state:"conflict",reason:"manifest-mismatch",canonicalHash:d,localHash:A,manifestHash:y}):u.push({path:p,state:"clean-update",canonicalHash:d,localHash:A,manifestHash:y})}for(let p of Object.keys(n.files)){if(s.has(p))continue;let d=n.files[p],y=O(t,p),f;try{await Hn(y),f=await ge(y)}catch{delete n.files[p];continue}Ht.has(p)?u.push({path:p,state:"removed-clean",localHash:f,manifestHash:d}):f!==d?u.push({path:p,state:"removed-modified",localHash:f,manifestHash:d}):await r(p,d)?u.push({path:p,state:"removed-modified",reason:"manifest-mismatch",localHash:f,manifestHash:d}):u.push({path:p,state:"removed-clean",localHash:f,manifestHash:d})}return u}async function Da(e,t,n){let i=O(e,ht),s=async p=>{try{return await ge(p)}catch{return null}},o=async(p,d,y)=>{let f=await s(O(i,p));return f===d||await s(O(e,Te,p))===d?!1:f!==null||y},r=await vi(e),c=r!==null&&r===t.baseSnapshot,u=c;if(!c&&r===null&&t.baseSnapshot===void 0&&await Hn(i).then(()=>!0,()=>!1)){u=!0;for(let[p,d]of Object.entries(t.files)){if(n.get(p)!==d)continue;let y=await s(O(i,p));if(y!==null&&y!==d){u=!1;break}}}return async(p,d)=>u&&await o(p,d,c)}function jn(e){return`${ee(e,"file")} Klaudius can't confirm ${e===1?"is":"are"} unedited`}function Ts(e){return e.reason==="manifest-mismatch"?"Hash the manifest records: ":"Hash at last install/update:"}function ee(e,t){return`${e} ${t}${e===1?"":"s"}`}function Fa(e,t){let n=e.includes(`\r
118
125
  `)?`\r
119
126
  `:`
120
- `,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 p=c.trim();p===""||p.startsWith("#")||o.has(p)||(r.push(p),o.add(p))}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 d=[...new Set(s.map(c=>c.trim()).filter(c=>c.startsWith("!")))].filter(c=>!r.includes(c));return a.push(...d,""),{merged:a.join(n),added:r}}function Cr(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,d=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 p=[];r>0&&p.push(`${r} file${r===1?"":"s"} ha${r===1?"s":"ve"} BOTH local edits AND upstream changes`),a>0&&p.push(`${a} file${a===1?"":"s"} you deleted locally ${a===1?"is":"are"} still shipped by the canonical template`),d>0&&p.push(`${d} file${d===1?"":"s"} ${d===1?"was":"were"} removed upstream but edited locally`),c.push(p.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=s.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(`
121
- `)}import{existsSync as Rr}from"fs";import{access as xr,readFile as qe,stat as Or}from"fs/promises";import{homedir as vr}from"os";import{join as q}from"path";import Y from"picocolors";import{spawn as Ks,spawnSync as Lr}from"child_process";async function Gs(e){let t=e.projectRoot??process.cwd(),n=[];console.log(Y.bold(`Klaudius doctor \u2014 checking your project\u2026
122
- `)),n.push(await Nr());let s=await Ur();s&&n.push(s),n.push(await $r());let o=q(t,".env"),r=q(t,".klaudius","manifest.json"),a=q(t,".mcp.json"),d=q(t,".codex","config.toml"),c=await ae(o),p=await ae(r),u="claude-code";if(c)try{V(await qe(o,"utf-8")).AI_AGENT==="codex"&&(u="codex")}catch{}if(u==="claude-code"){let m=await ae(q(t,"AGENTS.md")),l=!await ae(q(t,".claude"));m&&l&&(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 m={};try{m=V(await qe(o,"utf-8"))}catch{}let l=kt(m.AI_PLAN),S=At(m.QA_PHASE)??Ce(l);A=S==="off";let C=l&&Ie.has(l)&&u==="codex"?` \xB7 model pin ${Zt}`:"";n.push({name:"Plan / QA pass",status:l?"ok":"warn",detail:l?`${Re[l]} \xB7 QA pass ${S}${C}`:`plan not set \xB7 QA pass ${S}`,nextAction:l?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 m=0,l="";if(p)try{let S=JSON.parse(await qe(r,"utf-8"));m=typeof S.pendingConflicts=="number"?S.pendingConflicts:0,l=typeof S.templateVersion=="string"?S.templateVersion:""}catch{}n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?m>0?"warn":"ok":"fail",detail:p?m>0?`${l||"version unknown"} \u2014 ${m} conflict${m===1?"":"s"} from the last update still unresolved`:l?`${r} (template ${l})`:r:"missing",nextAction:p?m>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 m=await ae(d);n.push({name:".codex/config.toml present",status:m?"ok":"warn",detail:m?d:"missing",nextAction:m?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let m=await ae(a);n.push({name:".mcp.json present",status:m?"ok":"warn",detail:m?a:"missing",nextAction:m?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await Qr(u)),process.platform==="win32"){let m=await Mr(t);m&&n.push(m)}if(n.push(await Dr(t)),n.push(await Fr(t)),n.push(await Hr(t,A)),n.push(await Kr()),n.push(await jr(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 m=await qe(o,"utf-8"),l=V(m);await Gr(l,n,t)}console.log();for(let m of n){let l=m.status==="ok"?Y.green("\u2713"):m.status==="warn"?Y.yellow("\u26A0"):m.status==="skip"?Y.dim("\xB7"):Y.red("\u2717");console.log(` ${l} ${m.name}${m.detail?Y.dim(` \u2014 ${m.detail}`):""}`),m.nextAction&&console.log(` ${Y.dim("\u2192")} ${Y.cyan(m.nextAction)}`)}let P=n.filter(m=>m.status==="fail").length,T=n.filter(m=>m.status==="warn").length;console.log(),P===0&&T===0?console.log(Y.green(Y.bold("Everything checks out. You're good to go."))):P===0?console.log(Y.yellow(Y.bold(`${T} warning${T===1?"":"s"} \u2014 review above.`))):(console.log(Y.red(Y.bold(`${P} failed check${P===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function ae(e){try{return await xr(e),!0}catch{return!1}}async function Nr(){let e=await Le();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 $r(){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 Mr(e){let t=xe([{label:"your Windows user folder",path:vr()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",s=await gn("npm",["config","get","script-shell"],!0),o=s.code===0?s.stdout.trim():void 0;if(Oe(o,Rr))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}=ve(t,"doctor"),d=t.some(c=>c.chars.includes("&"));return{name:n,status:d?"fail":"warn",detail:r,nextAction:a}}async function Dr(e){let t=q(e,"node_modules");if(!await ae(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await Or(t)).isDirectory())return{name:"node_modules installed",status:"warn",detail:"exists but isn't a directory"}}catch{}return{name:"node_modules installed",status:"ok"}}async function 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 ae(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 Ur(){let e=await on();return e.status==="irrelevant"?null:e.status==="ok"?{name:"python3 runtime command",status:"ok",detail:`Python ${e.version}`}:e.status==="no-python"?{name:"python3 runtime command",status:"skip",detail:"no Python found \u2014 see the Python check above"}:{name:"python3 runtime command",status:"fail",detail:e.literal==="stub"?"`python3` is the Microsoft Store placeholder \u2014 every pipeline `python3` call dies":`\`python3\` is missing (your Python answers to \`${e.fallback.command.join(" ")}\`) \u2014 every pipeline \`python3\` call dies`,nextAction:"Fixed automatically by the updater \u2014 running `npx klaudius@latest update` creates the python3 alias from the real Python."}}async function Hr(e,t){if(!await ae(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 s=await jt(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 jr(e){let t=q(e,".klaudius","notify-failures.log");try{let n=(await qe(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 Kr(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
127
+ `,i=e.split(/\r?\n/),s=new Set(i.map(u=>u.trim()).filter(u=>u!=="")),o=[];for(let u of t.split(/\r?\n/)){let p=u.trim();p===""||p.startsWith("#")||s.has(p)||(o.push(p),s.add(p))}if(o.length===0)return{merged:e,added:o};let r=[...i];for(;r.length>0&&r[r.length-1].trim()==="";)r.pop();r.push("","# Added by `klaudius update` (new canonical ignore patterns)",...o);let c=[...new Set(i.map(u=>u.trim()).filter(u=>u.startsWith("!")))].filter(u=>!o.includes(u));return r.push(...c,""),{merged:r.join(n),added:o}}function Ua(e,t,n,i=new Map,s=new Map){let o=e.filter(f=>f.state==="conflict"&&!f.reason).length,r=e.filter(f=>f.reason==="untracked-local").length,c=e.filter(f=>f.reason==="manifest-mismatch").length,u=e.filter(f=>f.state==="locally-deleted").length,p=e.filter(f=>f.state==="removed-modified"&&!f.reason).length,d=[];d.push("# Update Conflicts"),d.push(""),d.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),d.push(`Updating from canonical version **${t}** to **${n}**.`),d.push("");let y=[];o>0&&y.push(`${o} file${o===1?"":"s"} ha${o===1?"s":"ve"} BOTH local edits AND upstream changes`),r>0&&y.push(`${r} file${r===1?"":"s"} of your own ${r===1?"sits":"sit"} at a path the new version now ships`),c>0&&y.push(`${jn(c)} and ${c===1?"has":"have"} upstream changes or removals`),u>0&&y.push(`${u} file${u===1?"":"s"} you deleted locally ${u===1?"is":"are"} still shipped by the canonical template`),p>0&&y.push(`${p} file${p===1?"":"s"} ${p===1?"was":"were"} removed upstream but edited locally`),d.push(y.join(", and ")+"."),d.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."),d.push(""),d.push("---"),d.push("");for(let f of e){if(d.push(`## ${f.path}`),d.push(""),f.state==="locally-deleted")d.push("**Type:** Deleted locally"),d.push(""),d.push("- You deleted this file after it was installed; the canonical template still ships it."),d.push(`- New canonical version staged at: \`.klaudius/incoming/${f.path}\``),d.push(`- Hash at last install/update: \`${(f.manifestHash??"(none)").slice(0,16)}\``),d.push(`- New canonical hash: \`${(f.canonicalHash??"(none)").slice(0,16)}\``),d.push(""),d.push("**Resolution options for the SKILL to walk through:**"),d.push(""),d.push("1. Restore \u2014 copy the canonical version back into place"),d.push("2. Keep deleted \u2014 never reinstall this file (recorded in the manifest's ignore list)");else if(f.state==="removed-modified")d.push("**Type:** Removed upstream"),d.push(""),d.push(`- Your local copy: \`${f.path}\``),d.push("- This file no longer exists in the canonical template."),d.push(f.reason==="manifest-mismatch"?"- The manifest's entry for this file isn't the version Klaudius last installed (a hand-edited manifest, a conflict resolved outside `/resolve-conflicts`, or a folder restored from an older copy), so your copy is treated as edited. If it was never changed on purpose, deleting it matches the new version.":"- You've modified it locally since install."),d.push(`- ${Ts(f)} \`${(f.manifestHash??"(none)").slice(0,16)}\``),d.push(`- Your local hash now: \`${(f.localHash??"(missing)").slice(0,16)}\``),d.push(""),d.push("**Resolution options for the SKILL to walk through:**"),d.push(""),d.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),d.push("2. Delete \u2014 remove the file from disk and from the manifest");else{d.push("**Type:** Edit conflict"),d.push(""),d.push(`- ${f.reason?"Your version":"Your version (with your local edits)"}: \`${f.path}\``),d.push(`- New canonical version: \`.klaudius/incoming/${f.path}\``),s.has(f.path)&&d.push(`- Pre-edit base (3-way merge ancestor): \`.klaudius/conflict-base/${f.path}\``),d.push(`- ${Ts(f)} \`${(f.manifestHash??"(none)").slice(0,16)}\``),d.push(`- Your local hash now: \`${(f.localHash??"(missing)").slice(0,16)}\``),d.push(`- New canonical hash: \`${(f.canonicalHash??"(none)").slice(0,16)}\``);let A=i.get(f.path);if(A&&A.length>0){let h=s.has(f.path);d.push(""),d.push(h?"**What upstream changed since your base:**":"**About this conflict:**"),d.push(""),d.push(...A),h&&(d.push(""),d.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._"))}d.push(""),d.push("**Resolution options for the SKILL to walk through:**"),d.push(""),d.push("1. Keep mine \u2014 discard the new canonical changes"),d.push("2. Take new \u2014 overwrite my edits with the new version"),d.push("3. Merge \u2014 review both side-by-side and produce a combined version")}d.push(""),d.push("---"),d.push("")}return d.join(`
128
+ `)}import{existsSync as Ha}from"fs";import{access as ja,readFile as at,stat as Ka}from"fs/promises";import{homedir as Ga}from"os";import{join as re}from"path";import ne from"picocolors";import{spawn as Is,spawnSync as Ba}from"child_process";async function Cs(e){let t=e.projectRoot??process.cwd(),n=[];console.log(ne.bold(`Klaudius doctor \u2014 checking your project\u2026
129
+ `)),n.push(await Va());let i=await Ja();i&&n.push(i),n.push(await Ya());let s=re(t,".env"),o=re(t,".klaudius","manifest.json"),r=re(t,".mcp.json"),c=re(t,".codex","config.toml"),u=await Ee(s),p=await Ee(o),d="claude-code";if(u)try{te(await at(s,"utf-8")).AI_AGENT==="codex"&&(d="codex")}catch{}if(d==="claude-code"){let h=await Ee(re(t,"AGENTS.md")),l=!await Ee(re(t,".claude"));h&&l&&(d="codex")}n.push({name:".env present",status:u?"ok":"fail",detail:u?s:"missing",nextAction:u?void 0:"Run `npx klaudius@latest init` in this folder."});let y=!1;if(u){let h={};try{h=te(await at(s,"utf-8"))}catch{}let l=$t(h.AI_PLAN),P=Lt(h.QA_PHASE)??je(l);y=P==="off";let R=l&&He.has(l)&&d==="codex"?` \xB7 model pin ${yn}`:"";n.push({name:"Plan / QA pass",status:l?"ok":"warn",detail:l?`${Ke[l]} \xB7 QA pass ${P}${R}`:`plan not set \xB7 QA pass ${P}`,nextAction:l?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 h=0,l="";if(p)try{let P=JSON.parse(await at(o,"utf-8"));h=typeof P.pendingConflicts=="number"?P.pendingConflicts:0,l=typeof P.templateVersion=="string"?P.templateVersion:""}catch{}n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?h>0?"warn":"ok":"fail",detail:p?h>0?`${l||"version unknown"} \u2014 ${h} conflict${h===1?"":"s"} from the last update still unresolved`:l?`${o} (template ${l})`:o:"missing",nextAction:p?h>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:u?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."})}if(d==="codex"){let h=await Ee(c);n.push({name:".codex/config.toml present",status:h?"ok":"warn",detail:h?c:"missing",nextAction:h?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let h=await Ee(r);n.push({name:".mcp.json present",status:h?"ok":"warn",detail:h?r:"missing",nextAction:h?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await al(d)),process.platform==="win32"){let h=await Wa(t);h&&n.push(h)}if(n.push(await qa(t)),n.push(await za(t)),n.push(await Qa(t,y)),n.push(await Za()),n.push(await Xa(t)),!u)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 h=await at(s,"utf-8"),l=te(h);await el(l,n,t)}console.log();for(let h of n){let l=h.status==="ok"?ne.green("\u2713"):h.status==="warn"?ne.yellow("\u26A0"):h.status==="skip"?ne.dim("\xB7"):ne.red("\u2717");console.log(` ${l} ${h.name}${h.detail?ne.dim(` \u2014 ${h.detail}`):""}`),h.nextAction&&console.log(` ${ne.dim("\u2192")} ${ne.cyan(h.nextAction)}`)}let f=n.filter(h=>h.status==="fail").length,A=n.filter(h=>h.status==="warn").length;console.log(),f===0&&A===0?console.log(ne.green(ne.bold("Everything checks out. You're good to go."))):f===0?console.log(ne.yellow(ne.bold(`${A} warning${A===1?"":"s"} \u2014 review above.`))):(console.log(ne.red(ne.bold(`${f} failed check${f===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function Ee(e){try{return await ja(e),!0}catch{return!1}}async function Va(){let e=await Ye();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 Ya(){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 Wa(e){let t=Ge([{label:"your Windows user folder",path:Ga()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",i=await Kn("npm",["config","get","script-shell"],!0),s=i.code===0?i.stdout.trim():void 0;if(Be(s,Ha))return{name:n,status:"ok",detail:`${t[0].label} contains ${t[0].chars.map(u=>`"${u}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=Ve(t,"doctor"),c=t.some(u=>u.chars.includes("&"));return{name:n,status:c?"fail":"warn",detail:o,nextAction:r}}async function qa(e){let t=re(e,"node_modules");if(!await Ee(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await Ka(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 za(e){let t=process.platform==="darwin"?re(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?re(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):re(process.env.HOME??"",".cache","ms-playwright");return await Ee(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 Ja(){let e=await bn();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 Qa(e,t){if(!await Ee(re(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 tn(e);if(i.ok)return{name:"QA screenshot chain",status:"ok",detail:"served a page with python3 and screenshotted it"};let s=i.stage!=="python3-server"&&t;return{name:"QA screenshot chain",status:s?"warn":"fail",detail:`${i.stage?`${i.stage}: `:""}${i.detail??"failed"}`+(s?" (QA pass is off \u2014 this matters when you enable it, and for browser-based gathering)":""),nextAction:i.remediation}}async function Xa(e){let t=re(e,".klaudius","notify-failures.log");try{let n=(await at(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 Za(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
123
130
  try:
124
- ${e.map(r=>` import ${r}`).join(`
131
+ ${e.map(o=>` import ${o}`).join(`
125
132
  `)}
126
133
  except Exception as e:
127
134
  print(str(e))
128
135
  sys.exit(1)
129
- `,n=await W();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 gn(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(`
130
- `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function Gr(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let a=await Me({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??"",d=e.SELFHOST_URL_TEMPLATE??"",c=[],p=pt(a);p&&c.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let u=ft(d);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 Fe({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 Ue({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 De(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 He(e.GOOGLE_PLACES_API_KEY),d=ge(e.GOOGLE_PLACES_API_KEY);a.ok&&d.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 "+(d.repairs.length>0?`it contains look-alike characters (${d.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 qr(e,n)),t.push(...await zr(e)),t.push(await Yr(e,n)),t.push(await Wr(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,d=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:a&&d?"ok":"fail",detail:a&&d?`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&&d?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let a=await Sn({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:a.ok?"ok":"fail",detail:a.ok?`bot ${a.botHandle??"ok"} (chat_id not tested)`:a.message,nextAction:a.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?t.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):t.push({name:"Notifications",status:"skip",detail:"not configured (optional)"})}function Br(e){let t=r=>!!r&&/^\d+$/.test(r.trim()),n=Bs(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 Bs(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function Vr(e){let t="Email account (Microsoft sign-in)",n=await W(),o=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[a,...d]=n.command,c=Lr(a,[...d,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),p=`${c.stdout??""}${c.stderr??""}`.trim();if(c.status===0){let u=/signed in as (\S+)/.exec(p)?.[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:p.split(`
131
- `)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await ae(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 Yr(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 qe(q(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 Lt({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 Wr(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(p=>p.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 Mt({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})`:""),d=(e.SUPABASE_ANON_KEY??"").trim();if(!d)return{name:t,status:"warn",detail:a+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let c=Cn(d);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 p=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:d,Authorization:`Bearer ${d}`}});if(p.ok){let u=await p.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 p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(u=>!(e[u]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:a+`, but PostGrid needs your return address and .env is missing ${p.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 qr(e,t){let n="Email credentials (SMTP + IMAP)",s=Br(e);if(s==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Bs(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."}:Vr(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(p=>p.endsWith("_PORT")?!e[p]||!/^\d+$/.test(e[p].trim()):!e[p]);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=et(e),r=o&&o!=="custom"?o:Pe(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?Q[r].usesAccountPassword:void 0,knownProvider:!!r,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},d=await pe(a);if(d.ok){if(d.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=Vs(d,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await W())?.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(d.failureKind==="network")return{name:n,status:"fail",detail:d.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=ut(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(Y.dim(` (email login rejected \u2014 probing ${Q[r].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let A of c){let P=await pe({...a,emailSmtpHost:A.smtpHost,emailImapHost:A.imapHost});if(!P.ok&&P.failureKind!=="network"&&p++,P.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=(d.message??"login rejected").split(/\.\s|\n/)[0];return p===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 ${Q[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:d.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}function Vs(e,t){let n=[],s=[],o=[];if(e.sentFolderIssue){let{configured:a,detected:d}=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`),d?s.push(`${t.sentKey}="${d}"`):o.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:a,detected:d}=e.draftsFolderIssue;n.push(`the server has no "${a}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),d?s.push(`${t.draftsKey}="${d}"`):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",d=t.account&&t.account!=="primary"?`${a} scripts/gmail.py folders --account ${t.account}`:`${a} scripts/gmail.py folders`;r.push(`Run \`${d}\` to list this mailbox's folder names, then set ${o.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:r.join(" ")}}async function zr(e){let t=[];for(let n of Fn(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=Pe(n.smtpHost),d=await pe({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,usesAccountPassword:a?Q[a].usesAccountPassword:void 0,knownProvider:!!a,sentFolder:(e[o]??"").trim()||"Sent",draftsFolder:(e[r]??"").trim()||"Drafts"});if(d.ok){let c=Vs(d,{sentKey:o,draftsKey:r,account:n.label,python:(await W())?.command.join(" ")});c?t.push({name:s,status:"warn",detail:`authenticated (${n.smtpHost}), but ${c.detail}`,nextAction:c.nextAction}):t.push({name:s,status:"ok",detail:`authenticated (${n.smtpHost})`})}else t.push({name:s,status:"fail",detail:d.message,nextAction:d.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 Qr(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 gn(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
132
- `)[0]}:{name:n,status:"warn",detail:"not found",nextAction:s}}function gn(e,t,n=!1){return new Promise(s=>{let o=n?Ks([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Ks(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",d=>{r+=d.toString()}),o.stderr?.on("data",d=>{a+=d.toString()}),o.on("close",d=>s({code:d??1,stdout:r,stderr:a})),o.on("error",()=>s({code:1,stdout:r,stderr:a}))})}import{existsSync as Jr}from"fs";import{spawnSync as Xr}from"child_process";import{join as Zr,resolve as ea}from"path";import z from"picocolors";async function Ys(e){let t=ea(e.projectRoot??process.cwd()),n=Zr(t,"scripts","whatsapp.mjs");Jr(n)||(console.error(z.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(z.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(z.dim(`Looked for: ${n}`)),process.exit(1));let s=(e.label??"primary").trim(),o=s.replace(/[^A-Za-z0-9_-]/g,"");o||(console.error(z.red(`Invalid label '${s}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),o!==s&&console.error(z.yellow(`Note: cleaned label '${s}' \u2192 '${o}' (filename-safe characters only).`)),console.log(z.cyan(`Pairing WhatsApp account '${o}'...`)),console.log(z.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.
133
- `));let r=Xr(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(z.green(`Paired '${o}'.`)),console.log(z.dim(`
134
- If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
135
- WHATSAPP_ACCOUNTS=primary,${o}
136
- (Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(z.red(`Pair failed: ${r.error.message}`)):(console.error(z.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(z.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(z.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(z.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as ze,spawn as ta}from"child_process";import{existsSync as lt,mkdirSync as na,readdirSync as sa,rmSync as Qs,mkdtempSync as Js}from"fs";import{homedir as yn,tmpdir as Xs}from"os";import{join as te}from"path";import le from"picocolors";var ia=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function Ws(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Zs(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&ct()&&ti();let t=ra();if(t&&!e.reinstall&&!e.from){zs(),console.log(le.green("Opened the Klaudius app.")),qs();return}let n=await la(e.from);console.log(le.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?ca(n):da(n),zs(),console.log(le.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),qs()}function qs(){process.platform==="darwin"?console.log(le.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(le.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function qt(){return te(yn(),"Applications","Klaudius.app")}function ei(){return process.env.LOCALAPPDATA??te(yn(),"AppData","Local")}function oa(){return te(ei(),"Klaudius")}function ct(){let e=te(ei(),"Programs");try{for(let t of sa(e)){if(!/laudius/i.test(t))continue;let n=te(e,t,"Klaudius.exe");if(lt(n))return n}}catch{}return null}function ra(){return process.platform==="darwin"?lt(qt()):ct()!==null}async function aa(){try{let{readFileSync:e}=await import("fs"),n=e(te(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function la(e){if(e)return lt(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await aa();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=`${ia}?file=${encodeURIComponent(Ws())}`,s=te(Js(te(Xs(),"klaudius-app-")),Ws());console.log(le.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.34.1"}});if(!o.ok){let d=`HTTP ${o.status}`;try{let c=await o.json();c.reason&&(d=c.reason)}catch{}throw new Error(d)}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 ca(e){let t=te(yn(),"Applications");na(t,{recursive:!0});let n=Js(te(Xs(),"klaudius-app-x-")),s=ze("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=te(n,"Klaudius.app");lt(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),Qs(qt(),{recursive:!0,force:!0});let r=ze("mv",[o,qt()],{stdio:"pipe"});r.status!==0&&(console.error(`Couldn't install to ~/Applications: ${r.stderr?.toString().trim()}`),process.exit(1))}function da(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=ze(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!ua(6e4)){let s=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,o=ct();if(o&&ni(o)){console.log(le.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(le.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)}ti()}function ua(e){let t=Date.now()+e;for(;;){let n=ct();if(n)return n;if(Date.now()>=t)return null;pa(500)}}function pa(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function ti(){let e=oa();if(!lt(te(e,"app","Klaudius.exe")))return;console.log(le.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
136
+ `,n=await se();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,s=await Kn(i[0],[...i.slice(1),"-c",t]);return s.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(s.stdout||s.stderr).trim().split(`
137
+ `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function el(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let r=await We({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:r.ok?"ok":"fail",detail:r.ok?"connected":r.message,nextAction:r.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 r=e.SELFHOST_DEPLOY_TARGET??"",c=e.SELFHOST_URL_TEMPLATE??"",u=[],p=_t(r);p&&u.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let d=It(c);d&&u.push(`SELFHOST_URL_TEMPLATE: ${d}`),t.push({name:"Self-host deploy config",status:u.length===0?"ok":"fail",detail:u.length===0?`target ${r} (SSH reachability tested at first deploy)`:u.join("; "),nextAction:u.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 r=await ze({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:r.ok?"ok":"fail",detail:r.ok?`valid (${r.projectCount??0} Pages project${r.projectCount===1?"":"s"})`:r.message,nextAction:r.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 r=await Je({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:r.ok?"ok":"fail",detail:r.ok?r.accountSlug?`valid (team: ${r.accountSlug})`:"valid":r.message,nextAction:r.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 r=await qe(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:r.ok?"ok":"fail",detail:r.ok?r.username??"valid":r.message,nextAction:r.ok?void 0:r.kind==="rejected"||r.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then `npx klaudius@latest configure`.":r.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 r=await Qe(e.GOOGLE_PLACES_API_KEY),c=Re(e.GOOGLE_PLACES_API_KEY);r.ok&&c.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 "+(c.repairs.length>0?`it contains look-alike characters (${c.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:r.ok?"ok":"fail",detail:r.ok?"accepted":r.message,nextAction:r.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 ol(e,n)),t.push(...await rl(e)),t.push(await il(e,n)),t.push(await sl(e));let s=(e.NOTIFY_CHANNEL??"").toLowerCase(),o=s==="email"||s==="sms"||s==="none"||s==="off"?s:"telegram";if(o==="none"||o==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(o==="email"){let r=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:r&&e.EMAIL_ADDRESS?"ok":"fail",detail:r&&e.EMAIL_ADDRESS?`alerts go to ${r}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:r&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(o==="sms"){let r=e.NOTIFY_TO||e.TEST_PHONE,c=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:r&&c?"ok":"fail",detail:r&&c?`alerts go to ${r} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:r?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:r&&c?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let r=await Wn({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:r.ok?"ok":"fail",detail:r.ok?`bot ${r.botHandle??"ok"} (chat_id not tested)`:r.message,nextAction:r.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 tl(e){let t=o=>!!o&&/^\d+$/.test(o.trim()),n=Rs(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(o=>o.trim()),s=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&i.includes("email");return s&&n?"active":s?"incomplete":n?"parked":"unconfigured"}function Rs(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function nl(e){let t="Email account (Microsoft sign-in)",n=await se(),s=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[r,...c]=n.command,u=Ba(r,[...c,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),p=`${u.stdout??""}${u.stderr??""}`.trim();if(u.status===0){let d=/signed in as (\S+)/.exec(p)?.[1];return{name:t,status:"ok",detail:d?`signed in as ${d} (token refresh works)`:"signed in (token refresh works)"}}return{name:t,status:"fail",detail:p.split(`
138
+ `)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:s}}return await Ee(re(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:s}}async function il(e,t){let n="Database schema up to date",i=(e.SUPABASE_URL??"").trim(),s=(e.SUPABASE_SERVICE_KEY??"").trim();if(!i||!s)return{name:n,status:"skip",detail:"Supabase credentials not set"};let o="";try{o=await at(re(t,"scripts","schema.sql"),"utf-8")}catch{return{name:n,status:"skip",detail:"scripts/schema.sql missing \u2014 run `npx klaudius@latest update`"}}let r=await Wt({url:i,serviceKey:s,sql:o});return r.unreachable?{name:n,status:"skip",detail:`Could not verify (${r.unreachable}) \u2014 see the Supabase rows above.`}:r.ok?{name:n,status:"ok",detail:"every table and column the pipeline expects is present"}:{name:n,status:"warn",detail:`missing: ${r.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 sl(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(p=>p.trim().toLowerCase()),i=(e.LETTER_PROVIDER??"").trim().toLowerCase(),s=n.includes("letter");if(!s&&(!i||i==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(s&&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(!s)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 o=await Jt({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(!o.ok)return{name:t,status:"fail",detail:o.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let r=`${i} credentials accepted`+(o.friendlyName?` (${o.friendlyName})`:""),c=(e.SUPABASE_ANON_KEY??"").trim();if(!c)return{name:t,status:"warn",detail:r+", 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 u=Xn(c);if(u&&u!=="anon")return{name:t,status:"fail",detail:r+`, but SUPABASE_ANON_KEY holds a '${u}' 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 p=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:c,Authorization:`Bearer ${c}`}});if(p.ok){let d=await p.json();if(Array.isArray(d)&&d.length>0)return{name:t,status:"fail",detail:r+", 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 p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(d=>!(e[d]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:r+`, but PostGrid needs your return address and .env is missing ${p.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:r}}async function ol(e,t){let n="Email credentials (SMTP + IMAP)",i=tl(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Rs(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."}:nl(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 u=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(p=>p.endsWith("_PORT")?!e[p]||!/^\d+$/.test(e[p].trim()):!e[p]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${u.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let s=ut(e),o=s&&s!=="custom"?s:Me(e.EMAIL_SMTP_HOST),r={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:o?ce[o].usesAccountPassword:void 0,knownProvider:!!o,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},c=await _e(r);if(c.ok){if(c.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 u=vs(c,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await se())?.command.join(" ")});return u?{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but ${u.detail}`,nextAction:u.nextAction}:{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(c.failureKind==="network")return{name:n,status:"fail",detail:c.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(o){let u=Tt(o,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(u.length>0){console.log(ne.dim(` (email login rejected \u2014 probing ${ce[o].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let y of u){let f=await _e({...r,emailSmtpHost:y.smtpHost,emailImapHost:y.imapHost});if(!f.ok&&f.failureKind!=="network"&&p++,f.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${y.label} (${y.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${y.smtpHost} and EMAIL_IMAP_HOST=${y.imapHost} in .env (or ask your AI agent to).`}}let d=(c.message??"login rejected").split(/\.\s|\n/)[0];return p===0?{name:n,status:"fail",detail:`${d} \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:`${d} \u2014 tried all ${ce[o].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:o==="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`.":o==="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:c.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}function vs(e,t){let n=[],i=[],s=[];if(e.sentFolderIssue){let{configured:r,detected:c}=e.sentFolderIssue;n.push(`the server has no "${r}" folder \u2014 sent mail isn't being filed, so follow-ups can't see what was sent to whom`),c?i.push(`${t.sentKey}="${c}"`):s.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:r,detected:c}=e.draftsFolderIssue;n.push(`the server has no "${r}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),c?i.push(`${t.draftsKey}="${c}"`):s.push(t.draftsKey)}if(n.length===0)return;let o=[];if(i.length>0&&o.push(`Set ${i.join(" and ")} in .env (or ask your AI agent to).`),s.length>0){let r=t.python||"python3",c=t.account&&t.account!=="primary"?`${r} scripts/gmail.py folders --account ${t.account}`:`${r} scripts/gmail.py folders`;o.push(`Run \`${c}\` to list this mailbox's folder names, then set ${s.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:o.join(" ")}}async function rl(e){let t=[];for(let n of li(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 s=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_SENT_FOLDER`,o=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,r=Me(n.smtpHost),c=await _e({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,usesAccountPassword:r?ce[r].usesAccountPassword:void 0,knownProvider:!!r,sentFolder:(e[s]??"").trim()||"Sent",draftsFolder:(e[o]??"").trim()||"Drafts"});if(c.ok){let u=vs(c,{sentKey:s,draftsKey:o,account:n.label,python:(await se())?.command.join(" ")});u?t.push({name:i,status:"warn",detail:`authenticated (${n.smtpHost}), but ${u.detail}`,nextAction:u.nextAction}):t.push({name:i,status:"ok",detail:`authenticated (${n.smtpHost})`})}else t.push({name:i,status:"fail",detail:c.message,nextAction:c.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 al(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`.",s=await Kn(t,["--version"],process.platform==="win32");return s.code===0?{name:n,status:"ok",detail:(s.stdout||s.stderr).trim().split(`
139
+ `)[0]}:{name:n,status:"warn",detail:"not found",nextAction:i}}function Kn(e,t,n=!1){return new Promise(i=>{let s=n?Is([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Is(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",c=>{o+=c.toString()}),s.stderr?.on("data",c=>{r+=c.toString()}),s.on("close",c=>i({code:c??1,stdout:o,stderr:r})),s.on("error",()=>i({code:1,stdout:o,stderr:r}))})}import{existsSync as ll}from"fs";import{spawnSync as cl}from"child_process";import{join as dl,resolve as ul}from"path";import ae from"picocolors";async function xs(e){let t=ul(e.projectRoot??process.cwd()),n=dl(t,"scripts","whatsapp.mjs");ll(n)||(console.error(ae.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(ae.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(ae.dim(`Looked for: ${n}`)),process.exit(1));let i=(e.label??"primary").trim(),s=i.replace(/[^A-Za-z0-9_-]/g,"");s||(console.error(ae.red(`Invalid label '${i}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),s!==i&&console.error(ae.yellow(`Note: cleaned label '${i}' \u2192 '${s}' (filename-safe characters only).`)),console.log(ae.cyan(`Pairing WhatsApp account '${s}'...`)),console.log(ae.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.
140
+ `));let o=cl(process.execPath,[n,"pair","--account",s],{cwd:t,stdio:"inherit"});if(o.status===0){console.log(ae.green(`Paired '${s}'.`)),console.log(ae.dim(`
141
+ If you haven't already, add '${s}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
142
+ WHATSAPP_ACCOUNTS=primary,${s}
143
+ (Skip this if '${s}' is already there or you set it via the init wizard.)`));return}o.error?console.error(ae.red(`Pair failed: ${o.error.message}`)):(console.error(ae.red(`Pair did not complete (exit ${o.status??"signalled"}). Common causes:`)),console.error(ae.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(ae.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(ae.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${s}/daemon.log`))),process.exit(o.status??1)}import{spawnSync as lt,spawn as pl}from"child_process";import{existsSync as bt,mkdirSync as fl,readdirSync as hl,rmSync as Ns,mkdtempSync as Ms}from"fs";import{homedir as Gn,tmpdir as Ds}from"os";import{join as me}from"path";import Pe from"picocolors";var ml=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function Os(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Fs(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&St()&&Hs();let t=yl();if(t&&!e.reinstall&&!e.from){Ls(),console.log(Pe.green("Opened the Klaudius app.")),$s();return}let n=await kl(e.from);console.log(Pe.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Al(n):El(n),Ls(),console.log(Pe.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),$s()}function $s(){process.platform==="darwin"?console.log(Pe.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(Pe.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function pn(){return me(Gn(),"Applications","Klaudius.app")}function Us(){return process.env.LOCALAPPDATA??me(Gn(),"AppData","Local")}function gl(){return me(Us(),"Klaudius")}function St(){let e=me(Us(),"Programs");try{for(let t of hl(e)){if(!/laudius/i.test(t))continue;let n=me(e,t,"Klaudius.exe");if(bt(n))return n}}catch{}return null}function yl(){return process.platform==="darwin"?bt(pn()):St()!==null}async function wl(){try{let{readFileSync:e}=await import("fs"),n=e(me(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function kl(e){if(e)return bt(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await wl();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=`${ml}?file=${encodeURIComponent(Os())}`,i=me(Ms(me(Ds(),"klaudius-app-")),Os());console.log(Pe.cyan("Downloading the Klaudius app\u2026"));try{let s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.35.0"}});if(!s.ok){let c=`HTTP ${s.status}`;try{let u=await s.json();u.reason&&(c=u.reason)}catch{}throw new Error(c)}let o=Buffer.from(await s.arrayBuffer()),{writeFileSync:r}=await import("fs");return r(i,o),i}catch(s){console.error(`Couldn't download the app (${s.message}). If you're offline, try again later; otherwise email hello@klaudius.dev.`),process.exit(1)}}function Al(e){let t=me(Gn(),"Applications");fl(t,{recursive:!0});let n=Ms(me(Ds(),"klaudius-app-x-")),i=lt("ditto",["-xk",e,n],{stdio:"pipe"});i.status!==0&&(console.error(`Couldn't extract the app: ${i.stderr?.toString().trim()}`),process.exit(1));let s=me(n,"Klaudius.app");bt(s)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),Ns(pn(),{recursive:!0,force:!0});let o=lt("mv",[s,pn()],{stdio:"pipe"});o.status!==0&&(console.error(`Couldn't install to ~/Applications: ${o.stderr?.toString().trim()}`),process.exit(1))}function El(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=lt(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Pl(6e4)){let i=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,s=St();if(s&&js(s)){console.log(Pe.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(Pe.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)}Hs()}function Pl(e){let t=Date.now()+e;for(;;){let n=St();if(n)return n;if(Date.now()>=t)return null;bl(500)}}function bl(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Hs(){let e=gl();if(!bt(me(e,"app","Klaudius.exe")))return;console.log(Pe.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
137
144
  $legacy = '${e.replace(/'/g,"''")}'
138
145
  # Compare against the directory PLUS its separator, so a sibling folder whose
139
146
  # name merely starts with the same text ("Klaudius Desktop") is never matched.
@@ -147,4 +154,4 @@ foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetF
147
154
  Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
148
155
  }
149
156
  }
150
- }`;ze("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Qs(e,{recursive:!0,force:!0})}catch{console.log(le.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function zs(){if(process.platform==="darwin"){ze("open",["-a",qt()],{stdio:"pipe"});return}let e=ct();if(!e||ni(e))return;ta(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function ni(e){let t=ze("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 si(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 wn(e=0){await Promise.all([si(process.stdout),si(process.stderr)]),process.exit(e)}import{spawnSync as fa}from"child_process";var kn="--use-system-ca";function ii(){let e=process.env.NODE_OPTIONS??"";if(e.includes(kn)||!ye().ok)return;let n=e?`${e} ${kn}`:kn,s=fa(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)}ii();var ma="0.34.1",ce=new ha;ce.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(ma);ce.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 Ln({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});ce.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 Ls({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await wn(process.exitCode??0)}catch(n){console.error("init failed:",n.message),process.exit(1)}});ce.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 $s({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});ce.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await Ds({}),await wn(process.exitCode??0)}catch(e){console.error("configure failed:",e.message),process.exit(1)}});ce.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 js({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});ce.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 Gs({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});ce.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 Zs({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});ce.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 Ys({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ce.parse(process.argv);
157
+ }`;lt("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Ns(e,{recursive:!0,force:!0})}catch{console.log(Pe.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function Ls(){if(process.platform==="darwin"){lt("open",["-a",pn()],{stdio:"pipe"});return}let e=St();if(!e||js(e))return;pl(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function js(e){let t=lt("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 Ks(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 Bn(e=0){await Promise.all([Ks(process.stdout),Ks(process.stderr)]),process.exit(e)}import{spawnSync as Sl}from"child_process";var Vn="--use-system-ca";function Gs(){let e=process.env.NODE_OPTIONS??"";if(e.includes(Vn)||!ve().ok)return;let n=e?`${e} ${Vn}`:Vn,i=Sl(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)}Gs();var _l="0.35.0",ye=new Tl;ye.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(_l);ye.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 ii({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});ye.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 rs({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await Bn(process.exitCode??0)}catch(n){console.error("init failed:",n.message),process.exit(1)}});ye.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 ls({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});ye.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await ds({}),await Bn(process.exitCode??0)}catch(e){console.error("configure failed:",e.message),process.exit(1)}});ye.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 _s({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});ye.command("resolve").description("Record your decision on one conflict `update` staged (the /resolve-conflicts skill runs this for you)").argument("[file]","The conflicted file, as named in .klaudius/conflicts.md").allowExcessArguments(!1).option("--keep-mine","Keep your version").option("--take-new","Use the new version (yours is backed up first)").option("--check-merge <draft>","Show what a merged draft keeps from each side, changing nothing").option("--merge <draft>","Use a merged draft (yours is backed up first)").option("--auto-merge","Merge automatically when your edits and the update's don't overlap (yours is backed up first)").option("--restore","Bring back a file you deleted, in its new version").option("--keep-deleted","Keep a file you deleted out for good").option("--delete","Delete a file the new version dropped (backed up first)").option("--finish","Clear the update staging once nothing is waiting").action(async(e,t)=>{try{process.exitCode=await bs(Ps(e,t))}catch(n){console.error("resolve failed:",n.message),process.exit(1)}});ye.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 Cs({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});ye.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 Fs({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});ye.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 xs({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ye.parse(process.argv);