klaudius 0.21.3 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -1,101 +1,106 @@
1
1
  #!/usr/bin/env node
2
- import{a as oe,b as rt,c as lt,d as Ee,e as Ae,f as V,h as T,j as ct,k as dt,l as Pe,m as Te,o as z,p as ut,q as pt}from"./chunk-3PLSCSGS.js";import{Command as ys}from"commander";import{spawn as ht}from"child_process";import S from"picocolors";function q(){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),o=parseInt(t[2],10),a=parseInt(t[3],10),i=`${n}.${o}.${a}`;return n<22||n===22&&o<15?{ok:!1,version:i,major:n,minor:o,message:`Your installed Node.js is ${i}. 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:i,major:n,minor:o}}import{spawn as wn}from"child_process";import{existsSync as En}from"fs";import{homedir as An}from"os";import{delimiter as Pn,join as be}from"path";var Tn=new Set(["Restricted","AllSigned"]);function bn(e,t=En){for(let n of e.split(Pn)){let o=n.replace(/"/g,"");if(!o)continue;let a=be(o,"npx.ps1");if(t(a))return{path:a,isPs1:!0};for(let i of["npx.exe","npx.bat","npx.cmd"]){let l=be(o,i);if(t(l))return{path:l,isPs1:!1}}}return null}async function mt(){let e=bn(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Sn();if(!t)return{blocked:!1,shimPath:e.path};let n=be(An(),".local","node")+"\\";return{blocked:Tn.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Sn(){let e=be(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await ft(e)??await ft("powershell.exe")}function ft(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let o=wn(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),a="",i=setTimeout(()=>{o.kill(),n(null)},8e3);o.stdout.on("data",l=>{a+=l.toString()}),o.stderr?.resume(),o.on("close",l=>{clearTimeout(i),n(l===0&&a.trim()?a.trim():null)}),o.on("error",()=>{clearTimeout(i),n(null)})})}import{spawn as _n}from"child_process";var me=3,Se=10,In=[["python3"],["python"],["py","-3"]];async function he(){for(let e of In){let t=await Rn(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 o=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!o)continue;let a=parseInt(o[1],10),i=parseInt(o[2],10),l=o[3]?`${a}.${i}.${o[3]}`:`${a}.${i}`;return{command:[...e],version:l,major:a,minor:i}}return null}async function se(){let e=Cn(),t=await he();if(!t){let l=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 ${me}.${Se}+ is not installed (or not on PATH). Install it from ${e}.`+l}}let{command:n,version:o,major:a,minor:i}=t;return a<me||a===me&&i<Se?{ok:!1,version:o,major:a,minor:i,command:n,message:`Your installed Python is ${o}. Klaudius needs Python ${me}.${Se} or newer (the pipeline depends on packages that only ship wheels for ${me}.${Se}+). 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:o,major:a,minor:i,command:n}}function Cn(){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 Rn(e,t){return new Promise(n=>{let o=_n(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",i="";o.stdout?.on("data",l=>{a+=l.toString()}),o.stderr?.on("data",l=>{i+=l.toString()}),o.on("close",l=>n({code:l??1,stdout:a,stderr:i})),o.on("error",()=>n({code:1,stdout:a,stderr:i}))})}var gt=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function yt(e={}){console.log(S.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
- `));let t=[];t.push(On());let n=await se();if(t.push(xn(n)),t.push(await vn(n.command)),t.push(await Nn()),process.platform==="win32"){let a=await $n();a&&t.push(a)}t.push(await Ln());for(let a of t){let i=a.status==="ok"?S.green("\u2713"):S.red("\u2717");console.log(` ${i} ${a.name}${a.detail?S.dim(` \u2014 ${a.detail}`):""}`),a.nextAction&&console.log(` ${S.dim("\u2192")} ${S.cyan(a.nextAction)}`)}console.log();let o=t.filter(a=>a.status==="fail");if(o.length===0){Mn();return}console.log(S.red(S.bold(`${o.length} check${o.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(S.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(S.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function On(){let e=q();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 before re-running."}}function xn(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 vn(e){let t=e??["python3"],n=await Be(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 Nn(){let e=process.platform==="win32",t=await Be("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 Be("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 $n(){let e=await mt();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 Ln(){try{return await fetch(gt,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:gt}}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 Mn(){console.log(S.green(S.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(S.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 tab and run:"),console.log(),console.log(` ${S.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(S.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(S.dim(" run it in a new terminal.")),console.log()}function Be(e,t,n=!1){return new Promise(o=>{let a=n?ht([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ht(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",l="";a.stdout?.on("data",c=>{i+=c.toString()}),a.stderr?.on("data",c=>{l+=c.toString()}),a.on("close",c=>o({code:c??1,stdout:i,stderr:l})),a.on("error",()=>o({code:1,stdout:i,stderr:l}))})}import{mkdir as Ze,readdir as Zt,readFile as Jt,stat as et,writeFile as Qe}from"fs/promises";import{spawnSync as en}from"child_process";import{homedir as vo}from"os";import{resolve as No,isAbsolute as $o,join as F,normalize as Lo}from"path";import*as k from"@clack/prompts";import d from"picocolors";import Dn from"react";import{render as Un}from"ink";async function _(e={},t={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius@latest init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:n}=await import("./WizardApp-JNNSMLM7.js"),o=null;oe("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),lt(),await new Promise(i=>setImmediate(i)),await new Promise(i=>setTimeout(i,0)),oe("runWizard:event loop drained, mounting Ink");let a=Un(Dn.createElement(n,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:i=>{oe("runWizard:onComplete called",{keys:Object.keys(i).length}),o=i}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(oe("runWizard:render returned, awaiting exit"),await a.waitUntilExit(),oe("runWizard:waitUntilExit resolved",{resultIsNull:o===null}),!o)throw new Error(`Wizard exited without completing. Diagnostic log: ${rt}
5
- Please share that file so we can trace what happened.`);return o}var We="claude-code";function kt(e){if(e==="claude-code"||e==="codex")return e}var ze="vercel";function wt(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function Et(e){if(e==="telegram"||e==="email"||e==="sms")return e}function Hn(e){if(e==="custom"||e!==void 0&&Object.hasOwn(V,e))return e}function _e(e){let t=Hn(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[o,a]of Object.entries(V))if(a.smtpHost===n)return o;return"custom"}}function Ie(e){let t=[],n=i=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${i}`),t.push("# "+"=".repeat(60)),t.push("")},o=(i,l)=>{if(l==null||l===""){t.push(`# ${i}=`);return}let c=String(l);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(c)){let p=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${i}="${p}"`)}else t.push(`${i}=${c}`)};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"),o("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),o("AI_AGENT",e.aiAgent??We),n("Operating country and language"),o("OPERATOR_COUNTRY",e.country),o("OPERATOR_COUNTRY_CODE",e.countryCode),o("OPERATOR_LANGUAGE",e.language),o("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let a=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];return o("PIPELINE_MODES",[...new Set(["classic",...a])].join(",")),n("Pricing"),o("PRICING",e.pricing),o("PRICING_TERMS",e.pricingTerms),o("PRICING_MONTHLY",e.pricingMonthly),n("Automated outreach features"),o("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),o("OPERATOR_NAME",e.name),o("SIGNATURE",e.signature),o("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),o("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),o("EMAIL_PROVIDER",e.emailProvider),o("EMAIL_ADDRESS",e.emailAddress),o("EMAIL_PASSWORD",e.emailPassword),o("EMAIL_FROM_NAME",e.emailFromName),o("EMAIL_SMTP_HOST",e.emailSmtpHost),o("EMAIL_SMTP_PORT",e.emailSmtpPort),o("EMAIL_IMAP_HOST",e.emailImapHost),o("EMAIL_IMAP_PORT",e.emailImapPort),o("EMAIL_SENT_FOLDER",e.emailSentFolder),o("EMAIL_INBOX_FOLDER",e.emailInboxFolder),n("SMS outreach"),o("SMS_PROVIDER",e.smsProvider),o("TEST_PHONE",e.testPhone),o("TWILIO_ACCOUNT_SID",e.twilioAccountSid),o("TWILIO_AUTH_TOKEN",e.twilioAuthToken),o("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),o("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Supabase (pipeline state)"),o("SUPABASE_URL",e.supabaseUrl),o("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),o("SUPABASE_PAT",e.supabasePat),o("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),o("DEPLOY_PROVIDER",e.deployProvider??ze),o("VERCEL_TOKEN",e.vercelToken),o("VERCEL_SCOPE",e.vercelScope??""),o("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),o("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),o("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),o("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),o("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),o("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),o("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),o("NOTIFY_CHANNEL",e.notifyChannel),o("NOTIFY_TO",e.notifyTo),o("TELEGRAM_BOT_TOKEN",e.telegramBotToken),o("TELEGRAM_CHAT_ID",e.telegramChatId),t.join(`
2
+ import{a as le,b as ut,c as pt,d as ce,e as be,f as K,h as T,j as ft,k as mt,l as Se,m as _e,o as Z,p as ht,q as gt}from"./chunk-R2LC3ZRY.js";import{Command as _i}from"commander";import{spawn as wt}from"child_process";import _ from"picocolors";function ee(){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),a=`${n}.${i}.${s}`;return n<22||n===22&&i<15?{ok:!1,version:a,major:n,minor:i,message:`Your installed Node.js is ${a}. 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:a,major:n,minor:i}}import{spawn as Sn}from"child_process";import{existsSync as _n}from"fs";import{homedir as In}from"os";import{delimiter as Cn,join as Ie}from"path";var Rn=new Set(["Restricted","AllSigned"]);function xn(e,t=_n){for(let n of e.split(Cn)){let i=n.replace(/"/g,"");if(!i)continue;let s=Ie(i,"npx.ps1");if(t(s))return{path:s,isPs1:!0};for(let a of["npx.exe","npx.bat","npx.cmd"]){let l=Ie(i,a);if(t(l))return{path:l,isPs1:!1}}}return null}async function kt(){let e=xn(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await On();if(!t)return{blocked:!1,shimPath:e.path};let n=Ie(In(),".local","node")+"\\";return{blocked:Rn.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function On(){let e=Ie(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await yt(e)??await yt("powershell.exe")}function yt(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let i=Sn(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),s="",a=setTimeout(()=>{i.kill(),n(null)},8e3);i.stdout.on("data",l=>{s+=l.toString()}),i.stderr?.resume(),i.on("close",l=>{clearTimeout(a),n(l===0&&s.trim()?s.trim():null)}),i.on("error",()=>{clearTimeout(a),n(null)})})}import{spawn as vn}from"child_process";var Ee=3,Ce=10,Nn=[["python3"],["python"],["py","-3"]];async function B(){for(let e of Nn){let t=await Ln(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),a=parseInt(i[2],10),l=i[3]?`${s}.${a}.${i[3]}`:`${s}.${a}`;return{command:[...e],version:l,major:s,minor:a}}return null}async function de(){let e=$n(),t=await B();if(!t){let l=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 ${Ee}.${Ce}+ is not installed (or not on PATH). Install it from ${e}.`+l}}let{command:n,version:i,major:s,minor:a}=t;return s<Ee||s===Ee&&a<Ce?{ok:!1,version:i,major:s,minor:a,command:n,message:`Your installed Python is ${i}. Klaudius needs Python ${Ee}.${Ce} or newer (the pipeline depends on packages that only ship wheels for ${Ee}.${Ce}+). 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:a,command:n}}function $n(){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 Ln(e,t){return new Promise(n=>{let i=vn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),s="",a="";i.stdout?.on("data",l=>{s+=l.toString()}),i.stderr?.on("data",l=>{a+=l.toString()}),i.on("close",l=>n({code:l??1,stdout:s,stderr:a})),i.on("error",()=>n({code:1,stdout:s,stderr:a}))})}var Et=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function At(e={}){console.log(_.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
+ `));let t=[];t.push(Mn());let n=await de();if(t.push(Dn(n)),t.push(await Hn(n.command)),t.push(await Un()),process.platform==="win32"){let s=await jn();s&&t.push(s)}t.push(await Fn());for(let s of t){let a=s.status==="ok"?_.green("\u2713"):_.red("\u2717");console.log(` ${a} ${s.name}${s.detail?_.dim(` \u2014 ${s.detail}`):""}`),s.nextAction&&console.log(` ${_.dim("\u2192")} ${_.cyan(s.nextAction)}`)}console.log();let i=t.filter(s=>s.status==="fail");if(i.length===0){Kn();return}console.log(_.red(_.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(_.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(_.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Mn(){let e=ee();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 before re-running."}}function Dn(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 Hn(e){let t=e??["python3"],n=await ze(t[0],[...t.slice(1),"-m","pip","--version"]);return n.code===0?{name:"pip available",status:"ok",detail:(n.stdout||n.stderr).trim().split(`
4
+ `)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function Un(){let e=process.platform==="win32",t=await ze("npm",["--version"],e);return t.code!==0?{name:"npm / npx available",status:"fail",detail:"npm not found",nextAction:"npm ships with Node.js \u2014 reinstall Node from https://nodejs.org/."}:(await ze("npx",["--version"],e)).code!==0?{name:"npm / npx available",status:"fail",detail:`npm ${t.stdout.trim()} ok, npx missing`,nextAction:"npx ships with npm 5.2+ \u2014 reinstall Node from https://nodejs.org/."}:{name:"npm / npx available",status:"ok",detail:`npm ${t.stdout.trim()}`}}async function jn(){let e=await kt();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 Fn(){try{return await fetch(Et,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:Et}}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 Kn(){console.log(_.green(_.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(_.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 tab and run:"),console.log(),console.log(` ${_.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(_.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(_.dim(" run it in a new terminal.")),console.log()}function ze(e,t,n=!1){return new Promise(i=>{let s=n?wt([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):wt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";s.stdout?.on("data",c=>{a+=c.toString()}),s.stderr?.on("data",c=>{l+=c.toString()}),s.on("close",c=>i({code:c??1,stdout:a,stderr:l})),s.on("error",()=>i({code:1,stdout:a,stderr:l}))})}import{mkdir as tt,readdir as sn,readFile as tn,stat as nt,writeFile as et}from"fs/promises";import{spawnSync as ot}from"child_process";import{homedir as Ho}from"os";import{resolve as Uo,isAbsolute as jo,join as G,normalize as Fo}from"path";import*as w from"@clack/prompts";import d from"picocolors";import Gn from"react";import{render as Vn}from"ink";async function I(e={},t={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius@latest init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:n}=await import("./WizardApp-KO7MOXCQ.js"),i=null;le("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),pt(),await new Promise(a=>setImmediate(a)),await new Promise(a=>setTimeout(a,0)),le("runWizard:event loop drained, mounting Ink");let s=Vn(Gn.createElement(n,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:a=>{le("runWizard:onComplete called",{keys:Object.keys(a).length}),i=a}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(le("runWizard:render returned, awaiting exit"),await s.waitUntilExit(),le("runWizard:waitUntilExit resolved",{resultIsNull:i===null}),!i)throw new Error(`Wizard exited without completing. Diagnostic log: ${ut}
5
+ Please share that file so we can trace what happened.`);return i}var qe="claude-code";function Pt(e){if(e==="claude-code"||e==="codex")return e}var Je="vercel";function Tt(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function bt(e){if(e==="telegram"||e==="email"||e==="sms")return e}function St(e){if(e==="password"||e==="oauth-microsoft")return e}function Yn(e){if(e==="custom"||e!==void 0&&Object.hasOwn(K,e))return e}function Re(e){let t=Yn(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[i,s]of Object.entries(K))if(s.smtpHost===n)return i;return"custom"}}function xe(e){let t=[],n=a=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${a}`),t.push("# "+"=".repeat(60)),t.push("")},i=(a,l)=>{if(l==null||l===""){t.push(`# ${a}=`);return}let c=String(l);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(c)){let u=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${a}="${u}"`)}else t.push(`${a}=${c}`)};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??qe),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"];return i("PIPELINE_MODES",[...new Set(["classic",...s])].join(",")),n("Pricing"),i("PRICING",e.pricing),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",e.pricingMonthly),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),n("SMS outreach"),i("SMS_PROVIDER",e.smsProvider),i("TEST_PHONE",e.testPhone),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("Supabase (pipeline state)"),i("SUPABASE_URL",e.supabaseUrl),i("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),i("SUPABASE_PAT",e.supabasePat),i("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),i("DEPLOY_PROVIDER",e.deployProvider??Je),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),t.join(`
6
6
  `)+`
7
- `}function Ce(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)+`
8
- `}function Re(e){let t=e.supabaseProjectRef,n=jn(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.","","[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(`
9
- `)}function jn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var At=[{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. Pre-modes installs targeted no-website businesses only ('classic') \u2014 this records that explicitly. Change to 'classic,rescue' to ALSO target businesses whose existing website is verifiably dead or bad (Rescue mode), 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."}];function Fn(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function Pt(e,t,n){let o=n.filter(l=>!(l.key in t));if(o.length===0)return null;let a=e.endsWith(`
7
+ `}function Oe(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)+`
8
+ `}function ve(e){let t=e.supabaseProjectRef,n=Bn(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.","","[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(`
9
+ `)}function Bn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var _t=[{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. Pre-modes installs targeted no-website businesses only ('classic') \u2014 this records that explicitly. Change to 'classic,rescue' to ALSO target businesses whose existing website is verifiably dead or bad (Rescue mode), 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."}];function Wn(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function It(e,t,n){let i=n.filter(l=>!(l.key in t));if(i.length===0)return null;let s=e.endsWith(`
10
10
  `)?"":`
11
- `,i=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let l of o)i.push(""),l.comment&&i.push(`# ${l.comment}`),i.push(Fn(l.key,l.value));return e+a+i.join(`
11
+ `,a=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let l of i)a.push(""),l.comment&&a.push(`# ${l.comment}`),a.push(Wn(l.key,l.value));return e+s+a.join(`
12
12
  `)+`
13
- `}function Kn(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 U(e){let t={};for(let n of e.split(`
14
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let a=o.indexOf("=");if(a===-1)continue;let i=o.slice(0,a).trim(),l=Kn(o.slice(a+1).trim());t[i]=l}return t}function Tt(e){let t=c=>{let p=e[c];if(!p)return;let h=parseInt(p,10);return isNaN(h)?void 0:h},n=e.SMS_PROVIDER,o=c=>c==="email"||c==="sms"||c==="whatsapp",a=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(o),i=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(o),l=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:kt(e.AI_AGENT)??We,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:a&&a.length>0?a:void 0,outreachPriority:i&&i.length>0?i:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailProvider:_e(e),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,smsProvider:n==="imessage"||n==="twilio"?n:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:wt(e.DEPLOY_PROVIDER)??ze,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:Et(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function qe(e){let t=g=>{let L=e[g];if(!L)return;let u=parseInt(L,10);return isNaN(u)?void 0:u},n=e.SUPABASE_URL,o=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),a=e.SUPABASE_PAT?.replace(/\s+/g,""),i=e.SUPABASE_PROJECT_REF,l=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",p=wt(e.DEPLOY_PROVIDER)??ze,h=e.VERCEL_TOKEN,r=e.CLOUDFLARE_API_TOKEN,w=e.CLOUDFLARE_ACCOUNT_ID,y=e.NETLIFY_AUTH_TOKEN,A=e.SELFHOST_DEPLOY_TARGET,v=e.SELFHOST_URL_TEMPLATE;if(!l||!n||!o||!a||!i||!(p==="cloudflare"?!!r&&!!w:p==="netlify"?!!y:p==="selfhost"?!!A&&!!v:!!h))return null;let $=e.SMS_PROVIDER,Z=g=>g==="email"||g==="sms"||g==="whatsapp",P=e.OUTREACH_CHANNELS?.split(",").map(g=>g.trim()).filter(Z),j=e.OUTREACH_PRIORITY?.split(",").map(g=>g.trim()).filter(Z),O=e.WHATSAPP_ACCOUNTS?.split(",").map(g=>g.trim()).filter(g=>g.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:kt(e.AI_AGENT)??We,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(g=>g.trim().toLowerCase()).filter(Boolean):void 0,pricing:l,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:P&&P.length>0?P:void 0,outreachPriority:j&&j.length>0?j:void 0,whatsappAccounts:O&&O.length>0?O:void 0,emailProvider:_e(e),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,smsProvider:$==="imessage"||$==="twilio"?$:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:p,vercelToken:h,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:r||void 0,cloudflareAccountId:w||void 0,netlifyAuthToken:y||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:A||void 0,selfhostUrlTemplate:v||void 0,supabaseUrl:n,supabaseServiceKey:o,supabasePat:a,supabaseProjectRef:i,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:Et(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Bs,mkdir as Ws,readdir as Xn,stat as zs}from"fs/promises";import{dirname as Js,join as Ct,relative as Qn,sep as Zn}from"path";import{fileURLToPath as Qs}from"url";import{createHash as Gn}from"crypto";import{readFile as Vn}from"fs/promises";async function ie(e){let t=await Vn(e);return Gn("sha256").update(t).digest("hex")}import{mkdir as Yn,readFile as Bn,writeFile as Wn,access as zn}from"fs/promises";import{dirname as qn,join as bt}from"path";var Jn=".klaudius",St=`${Jn}/manifest.json`,Oe=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml"]);async function _t(e){let t=bt(e,St);try{await zn(t)}catch{return null}let n=await Bn(t,"utf-8"),o=JSON.parse(n),a={};for(let[i,l]of Object.entries(o.files??{}))a[i.split("\\").join("/")]=l;return o.files=a,o}async function xe(e,t){let n=bt(e,St);await Yn(qn(n),{recursive:!0}),await Wn(n,JSON.stringify(t,null,2)+`
15
- `,"utf-8")}function It(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function ae(e,t=e){let n=await Xn(e,{withFileTypes:!0}),o=[];for(let a of n){let i=Ct(e,a.name);a.isDirectory()?o.push(...await ae(i,t)):a.isFile()&&o.push(Qn(t,i).split(Zn).join("/"))}return o}async function Rt(e){let t=await ae(e),n={};for(let o of t)Oe.has(o)||(n[o]=await ie(Ct(e,o)));return n}import{copyFile as eo,mkdir as Ot,mkdtemp as to,readdir as xt,rm as vt}from"fs/promises";import{tmpdir as no}from"os";import{dirname as oo,join as ve}from"path";import{Readable as so}from"stream";import*as Nt from"tar";var io="https://klaudius.dev/api/template";function ao(e){return so.fromWeb(e)}async function Ne(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??io,n="0.21.3",o;try{o=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: ${T(c)}`)}if(!o.ok){let c="";try{let p=await o.json();c=p.reason?` (${p.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${o.status}${c}`)}if(!o.body)throw new Error("Template download succeeded but response had no body");let a=o.headers.get("x-klaudius-tier"),i=await to(ve(no(),"klaudius-template-")),l=0;try{try{await new Promise((h,r)=>{let w=Nt.extract({cwd:i,strict:!0});w.on("finish",h),w.on("error",r),ao(o.body).on("error",r).pipe(w)})}catch(h){throw new Error(`Failed to extract template archive: ${h.message}`)}await Ot(e.destDir,{recursive:!0});let c=new Set(await xt(e.destDir)),p=await ae(i);try{for(let h of p){let r=ve(e.destDir,h);await Ot(oo(r),{recursive:!0}),await eo(ve(i,h),r),l++}}catch(h){let r=await xt(e.destDir).catch(()=>[]);for(let w of r)c.has(w)||await vt(ve(e.destDir,w),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${h.message}`)}}finally{await vt(i,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:a}}import J from"picocolors";var s={info:e=>console.log(J.cyan("\u2139"),e),success:e=>console.log(J.green("\u2713"),e),warn:e=>console.log(J.yellow("\u26A0"),e),error:e=>console.error(J.red("\u2717"),e),step:e=>console.log(J.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
16
- `+J.bold(J.cyan(e))),detail:e=>console.log(J.dim(" "+e))};var ro="https://registry.npmjs.org/klaudius/latest";async function lo(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let o=await fetch(ro,{signal:t.signal,headers:{accept:"application/json"}});if(!o.ok)return null;let a=await o.json();return typeof a.version=="string"?a.version:null}catch{return null}finally{clearTimeout(n)}}function co(e,t){let n=i=>i.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),o=n(e),a=n(t);if(o.length<3||a.length<3)return!1;for(let i=0;i<3;i++){if(Number.isNaN(o[i])||Number.isNaN(a[i]))return!1;if(o[i]>a[i])return!0;if(o[i]<a[i])return!1}return!1}async function $e(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await lo();!n||!co(n,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(s.detail("Your project content is fetched fresh either way, so you're not missing any"),s.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),s.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),s.blank())}import{createHash as uo}from"crypto";import{hostname as $t,userInfo as po,platform as Lt,arch as Mt}from"os";var fo="https://klaudius.dev",mo="/api/licenses/validate",ho="0.21.3";async function Dt(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(),o=(process.env.KLAUDIUS_API_URL??fo).replace(/\/$/,"")+mo,a=ge(),i;try{i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:a,hostname:$t(),os:`${Lt()}-${Mt()}`,cli_version:ho})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${T(c)}). Check your internet connection or try again later.`}}let l;try{l=await i.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${i.status}).`}}return l.ok?{ok:!0,tier:l.tier??"core"}:{ok:!1,reason:l.reason??`License rejected (HTTP ${i.status}).`}}function ge(){let e=[$t(),po().username,Lt(),Mt()].join("|");return uo("sha256").update(e).digest("hex").slice(0,32)}import{readFile as go}from"fs/promises";import{join as yo}from"path";async function re(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${T(n)}`}}}async function Ut(e){let t;try{t=await go(yo(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(o){return{ok:!1,message:`Could not read scripts/schema.sql: ${o.message}`}}let n=e.pat.replace(/\s+/g,"");try{let o=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(o.ok)return{ok:!0};let a=await o.text();return a.includes("already exists")||a.includes('relation "clients" already exists')||a.includes("duplicate")?(s.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${o.status}): ${a.slice(0,300)}`}}catch(o){return{ok:!1,message:`Schema apply failed: ${o.message}`}}}async function Le(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${T(t)}`}}}var Ht="https://api.cloudflare.com/client/v4";function jt(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Me(e){let{token:t,accountId:n}=e,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let a=await fetch(`${Ht}/user/tokens/verify`,{headers:o});if(a.status===401||a.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${a.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} verifying the token. Try again or check cloudflarestatus.com.`};let i=await a.json(),l=i.result?.status;if(i.success===!1||l&&l!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${l?` (status: ${l})`:""}. ${jt(i)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${T(a)}`}}try{let a=await fetch(`${Ht}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:o});if(a.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(a.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(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let i=await a.json();return i.success===!1?{ok:!1,message:jt(i)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(i.result)?i.result.length:void 0}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${T(a)}`}}}var Ft="https://api.netlify.com/api/v1";async function De(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let o=await fetch(`${Ft}/user`,{headers:n});if(o.status===401||o.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${o.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(!o.ok)return{ok:!1,message:`Netlify API returned HTTP ${o.status} verifying the token. Try again or check netlifystatus.com.`}}catch(o){return{ok:!1,message:`Could not reach Netlify: ${T(o)}`}}try{let o=await fetch(`${Ft}/accounts`,{headers:n});if(!o.ok)return{ok:!1,message:`Netlify API returned HTTP ${o.status} listing your teams. Try again or check netlifystatus.com.`};let a=await o.json(),i=Array.isArray(a)?a:[];if(i.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 l=typeof i[0]?.slug=="string"?i[0].slug:void 0;return{ok:!0,accountCount:i.length,accountSlug:l}}catch(o){return{ok:!1,message:`Could not reach Netlify: ${T(o)}`}}}async function le(e){let t=ut(e);if(t)return{ok:!1,message:t};let n=z(e),o=n.value,a=i=>{let l=[i],c=pt(e);return c&&l.push(c),n.repairs.length>0&&l.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.`),l.join(`
17
- `)};try{let i=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":o,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(i.ok)return{ok:!0};if(i.status===429)return{ok:!0};let l={};try{l=await i.json()}catch{}let c=l.error?.message??"",p=l.error?.status??"";return i.status===400&&(p==="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 and enable 'Places API (New)' for the project this key belongs to, then try again."}:i.status===401||i.status===403?{ok:!1,message:a(c||`Google rejected the key (HTTP ${i.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`)}:{ok:!1,message:a(`Google API returned HTTP ${i.status}${c?`: ${c}`:""}.`)}}catch(i){return{ok:!1,message:`Could not reach Google: ${T(i)}`}}}import ko from"nodemailer";import{ImapFlow as wo}from"imapflow";function Kt(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 o=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")||o.includes("invalid login")?"auth":o.includes("etimedout")||o.includes("timeout")||o.includes("enotfound")||o.includes("getaddrinfo")||o.includes("econnrefused")||o.includes("econnreset")?"network":"other"}async function ce(e){let t=ko.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(o){return{ok:!1,failedAt:"smtp",message:Gt(o,"SMTP",e.usesAccountPassword),failureKind:Kt(o)}}finally{t.close()}let n=new wo({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await n.connect(),await n.logout()}catch(o){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Gt(o,"IMAP",e.usesAccountPassword),failureKind:Kt(o)}}return{ok:!0}}function Gt(e,t,n){let o=e instanceof Error?e.message:String(e),a=o.toLowerCase();return a.includes("invalid credentials")||a.includes("authentication failed")||a.includes("auth failed")||a.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
13
+ `}function zn(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 H(e){let t={};for(let n of e.split(`
14
+ `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.indexOf("=");if(s===-1)continue;let a=i.slice(0,s).trim(),l=zn(i.slice(s+1).trim());t[a]=l}return t}function Ct(e){let t=c=>{let u=e[c];if(!u)return;let m=parseInt(u,10);return isNaN(m)?void 0:m},n=e.SMS_PROVIDER,i=c=>c==="email"||c==="sms"||c==="whatsapp",s=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(i),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(i),l=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Pt(e.AI_AGENT)??qe,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:a&&a.length>0?a:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailProvider:Re(e),emailAuth:St(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,smsProvider:n==="imessage"||n==="twilio"?n:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:Tt(e.DEPLOY_PROVIDER)??Je,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:bt(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function Xe(e){let t=g=>{let L=e[g];if(!L)return;let Y=parseInt(L,10);return isNaN(Y)?void 0:Y},n=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),s=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,l=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",u=Tt(e.DEPLOY_PROVIDER)??Je,m=e.VERCEL_TOKEN,r=e.CLOUDFLARE_API_TOKEN,E=e.CLOUDFLARE_ACCOUNT_ID,y=e.NETLIFY_AUTH_TOKEN,k=e.SELFHOST_DEPLOY_TARGET,b=e.SELFHOST_URL_TEMPLATE;if(!l||!n||!i||!s||!a||!(u==="cloudflare"?!!r&&!!E:u==="netlify"?!!y:u==="selfhost"?!!k&&!!b:!!m))return null;let N=e.SMS_PROVIDER,ie=g=>g==="email"||g==="sms"||g==="whatsapp",P=e.OUTREACH_CHANNELS?.split(",").map(g=>g.trim()).filter(ie),F=e.OUTREACH_PRIORITY?.split(",").map(g=>g.trim()).filter(ie),O=e.WHATSAPP_ACCOUNTS?.split(",").map(g=>g.trim()).filter(g=>g.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Pt(e.AI_AGENT)??qe,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(g=>g.trim().toLowerCase()).filter(Boolean):void 0,pricing:l,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:P&&P.length>0?P:void 0,outreachPriority:F&&F.length>0?F:void 0,whatsappAccounts:O&&O.length>0?O:void 0,emailProvider:Re(e),emailAuth:St(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,smsProvider:N==="imessage"||N==="twilio"?N:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:u,vercelToken:m,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:r||void 0,cloudflareAccountId:E||void 0,netlifyAuthToken:y||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:k||void 0,selfhostUrlTemplate:b||void 0,supabaseUrl:n,supabaseServiceKey:i,supabasePat:s,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:bt(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as ts,mkdir as ns,readdir as oo,stat as os}from"fs/promises";import{dirname as ss,join as Nt,relative as io,sep as so}from"path";import{fileURLToPath as rs}from"url";import{createHash as qn}from"crypto";import{readFile as Jn}from"fs/promises";async function ue(e){let t=await Jn(e);return qn("sha256").update(t).digest("hex")}import{mkdir as Xn,readFile as Qn,writeFile as Zn,access as eo}from"fs/promises";import{dirname as to,join as Rt}from"path";var no=".klaudius",xt=`${no}/manifest.json`,Ne=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml",".ms-token.json"]);async function Ot(e){let t=Rt(e,xt);try{await eo(t)}catch{return null}let n=await Qn(t,"utf-8"),i=JSON.parse(n),s={};for(let[a,l]of Object.entries(i.files??{}))s[a.split("\\").join("/")]=l;return i.files=s,i}async function $e(e,t){let n=Rt(e,xt);await Xn(to(n),{recursive:!0}),await Zn(n,JSON.stringify(t,null,2)+`
15
+ `,"utf-8")}function vt(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function pe(e,t=e){let n=await oo(e,{withFileTypes:!0}),i=[];for(let s of n){let a=Nt(e,s.name);s.isDirectory()?i.push(...await pe(a,t)):s.isFile()&&i.push(io(t,a).split(so).join("/"))}return i}async function $t(e){let t=await pe(e),n={};for(let i of t)Ne.has(i)||(n[i]=await ue(Nt(e,i)));return n}import{copyFile as ao,mkdir as Lt,mkdtemp as ro,readdir as Mt,rm as Dt}from"fs/promises";import{tmpdir as lo}from"os";import{dirname as co,join as Le}from"path";import{Readable as uo}from"stream";import*as Ht from"tar";var po="https://klaudius.dev/api/template";function fo(e){return uo.fromWeb(e)}async function Me(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??po,n="0.22.2",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: ${T(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"),a=await ro(Le(lo(),"klaudius-template-")),l=0;try{try{await new Promise((m,r)=>{let E=Ht.extract({cwd:a,strict:!0});E.on("finish",m),E.on("error",r),fo(i.body).on("error",r).pipe(E)})}catch(m){throw new Error(`Failed to extract template archive: ${m.message}`)}await Lt(e.destDir,{recursive:!0});let c=new Set(await Mt(e.destDir)),u=await pe(a);try{for(let m of u){let r=Le(e.destDir,m);await Lt(co(r),{recursive:!0}),await ao(Le(a,m),r),l++}}catch(m){let r=await Mt(e.destDir).catch(()=>[]);for(let E of r)c.has(E)||await Dt(Le(e.destDir,E),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${m.message}`)}}finally{await Dt(a,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:s}}import te from"picocolors";var o={info:e=>console.log(te.cyan("\u2139"),e),success:e=>console.log(te.green("\u2713"),e),warn:e=>console.log(te.yellow("\u26A0"),e),error:e=>console.error(te.red("\u2717"),e),step:e=>console.log(te.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
16
+ `+te.bold(te.cyan(e))),detail:e=>console.log(te.dim(" "+e))};var mo="https://registry.npmjs.org/klaudius/latest";async function ho(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(mo,{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 go(e,t){let n=a=>a.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),i=n(e),s=n(t);if(i.length<3||s.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(i[a])||Number.isNaN(s[a]))return!1;if(i[a]>s[a])return!0;if(i[a]<s[a])return!1}return!1}async function De(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await ho();!n||!go(n,t)||(o.blank(),o.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(o.detail("Your project content is fetched fresh either way, so you're not missing any"),o.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),o.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),o.blank())}import{createHash as yo}from"crypto";import{hostname as Ut,userInfo as ko,platform as jt,arch as Ft}from"os";var wo="https://klaudius.dev",Eo="/api/licenses/validate",Ao="0.22.2";async function Kt(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??wo).replace(/\/$/,"")+Eo,s=Ae(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:s,hostname:Ut(),os:`${jt()}-${Ft()}`,cli_version:Ao})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${T(c)}). Check your internet connection or try again later.`}}let l;try{l=await a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return l.ok?{ok:!0,tier:l.tier??"core"}:{ok:!1,reason:l.reason??`License rejected (HTTP ${a.status}).`}}function Ae(){let e=[Ut(),ko().username,jt(),Ft()].join("|");return yo("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Po}from"fs/promises";import{join as To}from"path";async function fe(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${T(n)}`}}}async function Gt(e){let t;try{t=await Po(To(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 s.includes("already exists")||s.includes('relation "clients" already exists')||s.includes("duplicate")?(o.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${i.status}): ${s.slice(0,300)}`}}catch(i){return{ok:!1,message:`Schema apply failed: ${i.message}`}}}async function He(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${T(t)}`}}}var Vt="https://api.cloudflare.com/client/v4";function Yt(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Ue(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let s=await fetch(`${Vt}/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 a=await s.json(),l=a.result?.status;if(a.success===!1||l&&l!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${l?` (status: ${l})`:""}. ${Yt(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${T(s)}`}}try{let s=await fetch(`${Vt}/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 a=await s.json();return a.success===!1?{ok:!1,message:Yt(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${T(s)}`}}}var Bt="https://api.netlify.com/api/v1";async function je(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${Bt}/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: ${T(i)}`}}try{let i=await fetch(`${Bt}/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(),a=Array.isArray(s)?s:[];if(a.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 l=typeof a[0]?.slug=="string"?a[0].slug:void 0;return{ok:!0,accountCount:a.length,accountSlug:l}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${T(i)}`}}}async function me(e){let t=ht(e);if(t)return{ok:!1,message:t};let n=Z(e),i=n.value,s=a=>{let l=[a],c=gt(e);return c&&l.push(c),n.repairs.length>0&&l.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.`),l.join(`
17
+ `)};try{let a=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(a.ok)return{ok:!0};if(a.status===429)return{ok:!0};let l={};try{l=await a.json()}catch{}let c=l.error?.message??"",u=l.error?.status??"";return a.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 and enable 'Places API (New)' for the project this key belongs to, then try again."}:a.status===401||a.status===403?{ok:!1,message:s(c||`Google rejected the key (HTTP ${a.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`)}:{ok:!1,message:s(`Google API returned HTTP ${a.status}${c?`: ${c}`:""}.`)}}catch(a){return{ok:!1,message:`Could not reach Google: ${T(a)}`}}}import bo from"nodemailer";import{ImapFlow as So}from"imapflow";function Wt(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 ne(e){let t=bo.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(i){return{ok:!1,failedAt:"smtp",message:zt(i,"SMTP",e.usesAccountPassword),failureKind:Wt(i)}}finally{t.close()}let n=new So({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await n.connect(),await n.logout()}catch(i){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:zt(i,"IMAP",e.usesAccountPassword),failureKind:Wt(i)}}return{ok:!0}}function zt(e,t,n){let i=e instanceof Error?e.message:String(e),s=i.toLowerCase();return s.includes("invalid credentials")||s.includes("authentication failed")||s.includes("auth failed")||s.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
18
18
  \u2022 The mailbox password is wrong or mistyped.
19
19
  \u2022 The email address doesn't match this mailbox's login.
20
20
  \u2022 The provider is blocking third-party apps \u2014 check that third-party
21
21
  access is enabled and 2FA is off in your provider's settings.`:`${t} rejected the credentials. Most common causes:
22
22
  \u2022 The app password is wrong, expired, or for a different provider.
23
23
  \u2022 The email address doesn't match the account that issued the password.
24
- \u2022 2FA is required but no app-specific password was generated.`:a.includes("etimedout")||a.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:a.includes("enotfound")||a.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${o}`}async function Vt(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 o=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(o.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(!o.ok)return{ok:!1,message:`Twilio API returned HTTP ${o.status}. Try again or check status.twilio.com.`};let a=await o.json();return a.status&&a.status!=="active"?{ok:!1,message:`Twilio account is in '${a.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:a.friendly_name}}catch(o){return{ok:!1,message:`Could not reach Twilio: ${T(o)}`}}}import{spawn as Eo}from"child_process";async function Yt(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,"")}"`,o=await Ao(n);if(o.code===0)return{ok:!0};let a=o.stderr.toLowerCase();return a.includes("can't get application")||a.includes("isn't running")||a.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."}:a.includes("(-1728)")||a.includes("not found")||a.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.`}:a.includes("(-1719)")||a.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: ${o.stderr.trim()||`exit code ${o.code}`}`}}function Ao(e){return new Promise(t=>{let n=Eo("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),o="";n.stderr.on("data",a=>{o+=a.toString()}),n.on("close",a=>t({code:a??1,stderr:o})),n.on("error",a=>t({code:1,stderr:a.message}))})}import{spawn as Xe}from"child_process";function Po(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var de=2,Bt=2e3,To=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Wt(e,t){let n=e+`
25
- `+t;return To.some(o=>o.test(n))}function zt(e){return new Promise(t=>setTimeout(t,e))}function bo(e,t,n){return new Promise(o=>{let a=n.shell?Xe([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):Xe(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),i="",l="";a.stdout?.on("data",c=>{let p=c.toString();i+=p,process.stdout.write(p)}),a.stderr?.on("data",c=>{let p=c.toString();l+=p,process.stderr.write(p)}),a.on("close",c=>o({code:c??1,stdout:i,stderr:l})),a.on("error",c=>o({code:1,stdout:i,stderr:l+c.message}))})}async function Je(e,t,n){let o={code:0,stdout:"",stderr:""};for(let a=0;a<=de;a++){if(o=await bo(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),o.code===0||!Wt(o.stderr,o.stdout))return o;a<de&&(s.detail(`${n.label} failed with a transient network error \u2014 retrying (${a+2}/${de+1})\u2026`),await zt(Bt))}return o}function So(e,t,n){return new Promise(o=>{let a=Xe(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),i="",l="";a.stdout?.on("data",c=>{i+=c.toString()}),a.stderr?.on("data",c=>{l+=c.toString()}),a.on("close",c=>o({code:c??1,stdout:i,stderr:l})),a.on("error",c=>o({code:1,stdout:i,stderr:l+c.message}))})}var _o=[{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 Io(e){let t=`${e.stderr??""}
26
- ${e.stdout??""}`;return _o.find(o=>o.pattern.test(t))?.hint}async function Co(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],a=(await he())?.command??["python3"],i=async c=>{let p={code:0,stdout:"",stderr:""};for(let h=0;h<=de;h++){if(p=await So(a[0],[...a.slice(1),...c],{cwd:e}),p.code===0||!Wt(p.stderr,p.stdout))return p;h<de&&(s.detail(`pip install hit a transient network error \u2014 retrying (${h+2}/${de+1})\u2026`),await zt(Bt))}return p},l=await i([...n,"--break-system-packages",...t]);return l.code!==0&&/no such option:.*break-system-packages/i.test(l.stderr)&&(s.detail("Older pip detected; retrying without --break-system-packages"),l=await i([...n,...t])),l.code!==0&&(l.stderr.trim()&&process.stderr.write(l.stderr),l.stdout.trim()&&process.stdout.write(l.stdout)),l}async function Ue(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=Po(),o=process.platform==="win32",a=(h,r)=>{let w=Io(r);w&&((t.hints??={})[h]=w)};s.step("Running npm install (Next.js, Playwright JS, etc.)...");let i=await Je("npm",["install"],{cwd:e,label:"npm install",env:n,shell:o});t.npm=i.code===0?"ok":"failed",i.code!==0&&a("npm",i),s.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await Co(e);t.pip=l.code===0?"ok":"failed",l.code!==0&&a("pip",l),s.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Je("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:o});t.playwright=c.code===0?"ok":"failed",c.code!==0&&a("playwright",c),s.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await Je("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:o});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&a("patchright",p),t}import{mkdir as Ro,readFile as Oo,writeFile as xo}from"fs/promises";import{join as qt}from"path";async function He(e,t){let n=qt(e,".claude");await Ro(n,{recursive:!0});let o=qt(n,"settings.json"),a={};try{let p=await Oo(o,"utf-8"),h=JSON.parse(p);h&&typeof h=="object"&&!Array.isArray(h)&&(a=h)}catch{}let i=a.enabledMcpjsonServers,l=Array.isArray(i)?i.filter(p=>typeof p=="string"):[];l.includes(t)||l.push(t);let c={...a,enabledMcpjsonServers:l};await xo(o,JSON.stringify(c,null,2)+`
27
- `,"utf-8")}var Xt="0.21.3",b=5;function ne(e){return`npx klaudius@latest init ${je(ue(e))}`}function ue(e){if(process.platform==="win32")return e;let t=vo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Mo(e){let t=[];try{let o=(await Zt(e,{withFileTypes:!0})).filter(a=>a.isDirectory()&&!a.name.startsWith(".")).slice(0,200);for(let a of o){let i=F(e,a.name);if(!await Qt(F(i,".env")))continue;let l=await Qt(F(i,".klaudius","manifest.json"));if(t.push({path:i,finished:l}),t.length>=3)break}}catch{}return t}async function Qt(e){try{return await et(e),!0}catch{return!1}}function je(e){return/\s/.test(e)?`"${e}"`:e}function X(e,t,n){s.blank(),s.error(`${t} validation failed ${b} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${n}`),s.blank(),s.detail("Your credentials are saved in `.env`. Two ways forward:"),s.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),s.blank(),console.log(` ${d.cyan(ne(e))}`),s.blank(),s.detail(` (Your .env is at ${ue(F(e,".env"))} \u2014 open it in any text editor.)`),s.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),s.blank(),process.exit(1)}async function tn(e){let t=e.target??".",n=$o(t)?t:No(process.cwd(),t),o=jo(n);o&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${n}`),s.detail(`Reason: ${o}`),s.blank(),s.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),s.blank(),process.platform==="win32"?(s.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${d.cyan("cd $HOME\\Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)):(s.detail("For example:"),console.log(` ${d.cyan("cd ~/Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)),s.blank(),process.exit(1)),process.platform==="win32"&&Fo()&&(s.warn("You appear to be running in an elevated (Administrator) PowerShell."),s.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),s.blank()),await $e("init",Xt);let a=await Do(n);if(a.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${d.bold(n)}.`),s.detail("(Your .env and project files are in place.)"),s.blank(),a.nodeModulesMissing?(s.detail("It looks like a previous setup didn't finish installing dependencies."),s.detail("To pick up where it left off, run:"),s.blank(),n!==process.cwd()&&console.log(` ${d.cyan(`cd ${je(t)}`)}`),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Everything is scaffolded and dependencies look installed."),s.detail("Pick the action you wanted:"),s.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius@latest configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius@latest update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),s.blank()),s.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),s.blank();return}if(a.kind==="occupied"){let u=t===".",m=await Mo(n);if(m.length>0){s.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),s.detail(`You're in: ${ue(n)}`),s.blank();for(let f of m)s.detail(f.finished?`Found a finished project at ${ue(f.path)}. To work in it:`:`Found an unfinished setup at ${ue(f.path)}. To pick up where it left off:`),s.blank(),f.finished?(console.log(` ${d.cyan(`cd ${ue(f.path)}`)}`),console.log(` ${d.cyan("claude")} ${d.dim("# open Claude Code in the project")}`)):console.log(` ${d.cyan(ne(f.path))} ${d.dim("# then pick Resume")}`),s.blank();process.exit(1)}s.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),s.detail(`Path: ${n}`),s.detail(`Contains: ${a.entries.slice(0,5).join(", ")}${a.entries.length>5?`, \u2026 (+${a.entries.length-5} more)`:""}`),s.blank(),u?(s.detail("Two ways forward:"),s.blank(),s.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`),s.blank(),s.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(s.detail(`The folder '${t}' already exists and isn't empty.`),s.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius@latest init ${t}-2`)}`),s.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let i=await Ho(e.license),l=k.spinner();l.start("Validating license");let c=await Dt(i);c.ok||(l.stop(`License invalid: ${c.reason??"unknown"}`,2),s.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),l.stop(`License valid (${c.tier??"core"} tier)`);let p=await se();p.ok||(s.error(p.message??"Python version check failed."),s.blank(),s.detail(`Once you've installed Python 3.10+, re-run the same command: ${ne(n)}`),process.exit(1));let h=q();h.ok||(s.error(h.message??"Node.js version check failed."),s.blank(),s.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${ne(n)}`),process.exit(1));let r,w=!1;if(a.kind==="partial")if(await Uo(n)==="resume"){let m=await Jt(a.envPath,"utf-8"),f=qe(U(m));f?(s.success("Resuming with values from your existing .env"),s.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),r=f,w=!0):(s.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await _())}else{let m=await Jt(a.envPath,"utf-8"),f=qe(U(m));r=await _(f??{})}else r=await _();r.licenseKey=i,await C(n,r),w||(s.success("Saved .env"),s.success(r.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),s.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating Supabase credentials");let f=await re({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(f.ok){m.stop("Supabase credentials accepted");break}m.stop(f.message??"Supabase check failed",2),u>=b&&X(n,"Supabase",f.message??"Supabase check failed");let E=f.message??"Supabase check failed";s.blank(),s.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${u+1} of ${b})`),s.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await _(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
28
- ${E}
24
+ \u2022 2FA is required but no app-specific password was generated.`:s.includes("etimedout")||s.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:s.includes("enotfound")||s.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${i}`}async function qt(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: ${T(i)}`}}}import{spawn as _o}from"child_process";async function Jt(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,i=await Io(n);if(i.code===0)return{ok:!0};let 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 Io(e){return new Promise(t=>{let n=_o("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 Ze}from"child_process";function Co(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var he=2,Xt=2e3,Ro=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Qt(e,t){let n=e+`
25
+ `+t;return Ro.some(i=>i.test(n))}function Zt(e){return new Promise(t=>setTimeout(t,e))}function xo(e,t,n){return new Promise(i=>{let s=n.shell?Ze([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):Ze(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),a="",l="";s.stdout?.on("data",c=>{let u=c.toString();a+=u,process.stdout.write(u)}),s.stderr?.on("data",c=>{let u=c.toString();l+=u,process.stderr.write(u)}),s.on("close",c=>i({code:c??1,stdout:a,stderr:l})),s.on("error",c=>i({code:1,stdout:a,stderr:l+c.message}))})}async function Qe(e,t,n){let i={code:0,stdout:"",stderr:""};for(let s=0;s<=he;s++){if(i=await xo(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!Qt(i.stderr,i.stdout))return i;s<he&&(o.detail(`${n.label} failed with a transient network error \u2014 retrying (${s+2}/${he+1})\u2026`),await Zt(Xt))}return i}function Oo(e,t,n){return new Promise(i=>{let s=Ze(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";s.stdout?.on("data",c=>{a+=c.toString()}),s.stderr?.on("data",c=>{l+=c.toString()}),s.on("close",c=>i({code:c??1,stdout:a,stderr:l})),s.on("error",c=>i({code:1,stdout:a,stderr:l+c.message}))})}var vo=[{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 No(e){let t=`${e.stderr??""}
26
+ ${e.stdout??""}`;return vo.find(i=>i.pattern.test(t))?.hint}async function $o(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],s=(await B())?.command??["python3"],a=async c=>{let u={code:0,stdout:"",stderr:""};for(let m=0;m<=he;m++){if(u=await Oo(s[0],[...s.slice(1),...c],{cwd:e}),u.code===0||!Qt(u.stderr,u.stdout))return u;m<he&&(o.detail(`pip install hit a transient network error \u2014 retrying (${m+2}/${he+1})\u2026`),await Zt(Xt))}return u},l=await a([...n,"--break-system-packages",...t]);return l.code!==0&&/no such option:.*break-system-packages/i.test(l.stderr)&&(o.detail("Older pip detected; retrying without --break-system-packages"),l=await a([...n,...t])),l.code!==0&&(l.stderr.trim()&&process.stderr.write(l.stderr),l.stdout.trim()&&process.stdout.write(l.stdout)),l}async function Fe(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=Co(),i=process.platform==="win32",s=(m,r)=>{let E=No(r);E&&((t.hints??={})[m]=E)};o.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await Qe("npm",["install"],{cwd:e,label:"npm install",env:n,shell:i});t.npm=a.code===0?"ok":"failed",a.code!==0&&s("npm",a),o.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await $o(e);t.pip=l.code===0?"ok":"failed",l.code!==0&&s("pip",l),o.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Qe("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:i});t.playwright=c.code===0?"ok":"failed",c.code!==0&&s("playwright",c),o.step("Installing Patchright browser (chromium ~200MB; one-time)...");let u=await Qe("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:i});return t.patchright=u.code===0?"ok":"failed",u.code!==0&&s("patchright",u),t}import{mkdir as Lo,readFile as Mo,writeFile as Do}from"fs/promises";import{join as en}from"path";async function Ke(e,t){let n=en(e,".claude");await Lo(n,{recursive:!0});let i=en(n,"settings.json"),s={};try{let u=await Mo(i,"utf-8"),m=JSON.parse(u);m&&typeof m=="object"&&!Array.isArray(m)&&(s=m)}catch{}let a=s.enabledMcpjsonServers,l=Array.isArray(a)?a.filter(u=>typeof u=="string"):[];l.includes(t)||l.push(t);let c={...s,enabledMcpjsonServers:l};await Do(i,JSON.stringify(c,null,2)+`
27
+ `,"utf-8")}var nn="0.22.2",S=5;function re(e){return`npx klaudius@latest init ${Ge(ge(e))}`}function ge(e){if(process.platform==="win32")return e;let t=Ho();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Ko(e){let t=[];try{let i=(await sn(e,{withFileTypes:!0})).filter(s=>s.isDirectory()&&!s.name.startsWith(".")).slice(0,200);for(let s of i){let a=G(e,s.name);if(!await on(G(a,".env")))continue;let l=await on(G(a,".klaudius","manifest.json"));if(t.push({path:a,finished:l}),t.length>=3)break}}catch{}return t}async function on(e){try{return await nt(e),!0}catch{return!1}}function Ge(e){return/\s/.test(e)?`"${e}"`:e}function oe(e,t,n){o.blank(),o.error(`${t} validation failed ${S} times in a row. Pausing setup so you don't get stuck in a loop.`),o.detail(`Last error: ${n}`),o.blank(),o.detail("Your credentials are saved in `.env`. Two ways forward:"),o.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),o.blank(),console.log(` ${d.cyan(re(e))}`),o.blank(),o.detail(` (Your .env is at ${ge(G(e,".env"))} \u2014 open it in any text editor.)`),o.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),o.blank(),process.exit(1)}async function an(e){let t=e.target??".",n=jo(t)?t:Uo(process.cwd(),t),i=Bo(n);i&&(o.error("Klaudius can't be installed inside a protected system folder."),o.detail(`Path: ${n}`),o.detail(`Reason: ${i}`),o.blank(),o.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),o.blank(),process.platform==="win32"?(o.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${d.cyan("cd $HOME\\Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)):(o.detail("For example:"),console.log(` ${d.cyan("cd ~/Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)),o.blank(),process.exit(1)),process.platform==="win32"&&Wo()&&(o.warn("You appear to be running in an elevated (Administrator) PowerShell."),o.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."),o.blank()),await De("init",nn);let s=await Go(n);if(s.kind==="scaffolded"){o.blank(),o.warn(`Found an existing Klaudius project at ${d.bold(n)}.`),o.detail("(Your .env and project files are in place.)"),o.blank(),s.nodeModulesMissing?(o.detail("It looks like a previous setup didn't finish installing dependencies."),o.detail("To pick up where it left off, run:"),o.blank(),n!==process.cwd()&&console.log(` ${d.cyan(`cd ${Ge(t)}`)}`),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Everything is scaffolded and dependencies look installed."),o.detail("Pick the action you wanted:"),o.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius@latest configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius@latest update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),o.blank()),o.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),o.blank();return}if(s.kind==="occupied"){let p=t===".",h=await Ko(n);if(h.length>0){o.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),o.detail(`You're in: ${ge(n)}`),o.blank();for(let f of h)o.detail(f.finished?`Found a finished project at ${ge(f.path)}. To work in it:`:`Found an unfinished setup at ${ge(f.path)}. To pick up where it left off:`),o.blank(),f.finished?(console.log(` ${d.cyan(`cd ${ge(f.path)}`)}`),console.log(` ${d.cyan("claude")} ${d.dim("# open Claude Code in the project")}`)):console.log(` ${d.cyan(re(f.path))} ${d.dim("# then pick Resume")}`),o.blank();process.exit(1)}o.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),o.detail(`Path: ${n}`),o.detail(`Contains: ${s.entries.slice(0,5).join(", ")}${s.entries.length>5?`, \u2026 (+${s.entries.length-5} more)`:""}`),o.blank(),p?(o.detail("Two ways forward:"),o.blank(),o.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`),o.blank(),o.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(o.detail(`The folder '${t}' already exists and isn't empty.`),o.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius@latest init ${t}-2`)}`),o.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await Yo(e.license),l=w.spinner();l.start("Validating license");let c=await Kt(a);c.ok||(l.stop(`License invalid: ${c.reason??"unknown"}`,2),o.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),l.stop(`License valid (${c.tier??"core"} tier)`);let u=await de();u.ok||(o.error(u.message??"Python version check failed."),o.blank(),o.detail(`Once you've installed Python 3.10+, re-run the same command: ${re(n)}`),process.exit(1));let m=ee();m.ok||(o.error(m.message??"Node.js version check failed."),o.blank(),o.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${re(n)}`),process.exit(1));let r,E=!1;if(s.kind==="partial")if(await Vo(n)==="resume"){let h=await tn(s.envPath,"utf-8"),f=Xe(H(h));f?(o.success("Resuming with values from your existing .env"),o.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),r=f,E=!0):(o.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await I())}else{let h=await tn(s.envPath,"utf-8"),f=Xe(H(h));r=await I(f??{})}else r=await I();r.licenseKey=a,await R(n,r),E||(o.success("Saved .env"),o.success(r.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),o.blank();for(let p=1;;p++){let h=w.spinner();h.start("Validating Supabase credentials");let f=await fe({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(f.ok){h.stop("Supabase credentials accepted");break}h.stop(f.message??"Supabase check failed",2),p>=S&&oe(n,"Supabase",f.message??"Supabase check failed");let A=f.message??"Supabase check failed";o.blank(),o.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${p+1} of ${S})`),o.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await I(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
28
+ ${A}
29
29
 
30
30
  Re-enter the URL, secret key, or PAT below. Press Enter on any
31
- field to keep what's already there.`}),await C(n,r)}if(s.blank(),r.deployProvider==="cloudflare")for(let u=1;;u++){let m=k.spinner();m.start("Validating Cloudflare token + account");let f=await Me({token:r.cloudflareApiToken??"",accountId:r.cloudflareAccountId??""});if(f.ok){m.stop(`Cloudflare credentials accepted (${f.projectCount??0} existing Pages project${f.projectCount===1?"":"s"})`);break}m.stop(f.message??"Cloudflare check failed",2),u>=b&&X(n,"Cloudflare",f.message??"Cloudflare check failed");let E=f.message??"Cloudflare check failed";s.blank(),s.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${u+1} of ${b})`),s.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await _(r,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
32
- ${E}
31
+ field to keep what's already there.`}),await R(n,r)}if(o.blank(),r.deployProvider==="cloudflare")for(let p=1;;p++){let h=w.spinner();h.start("Validating Cloudflare token + account");let f=await Ue({token:r.cloudflareApiToken??"",accountId:r.cloudflareAccountId??""});if(f.ok){h.stop(`Cloudflare credentials accepted (${f.projectCount??0} existing Pages project${f.projectCount===1?"":"s"})`);break}h.stop(f.message??"Cloudflare check failed",2),p>=S&&oe(n,"Cloudflare",f.message??"Cloudflare check failed");let A=f.message??"Cloudflare check failed";o.blank(),o.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${p+1} of ${S})`),o.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await I(r,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
32
+ ${A}
33
33
 
34
34
  Re-enter the API token or Account ID below. The token needs the
35
35
  "Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
36
- the current value.`}),await C(n,r)}else if(r.deployProvider==="netlify")for(let u=1;;u++){let m=k.spinner();m.start("Validating Netlify token");let f=await De({token:r.netlifyAuthToken??""});if(f.ok){m.stop(f.accountSlug?`Netlify token accepted (team: ${f.accountSlug})`:"Netlify token accepted");break}m.stop(f.message??"Netlify check failed",2),u>=b&&X(n,"Netlify",f.message??"Netlify check failed");let E=f.message??"Netlify check failed";s.blank(),s.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${u+1} of ${b})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await _(r,{onlySection:"netlify",banner:`Netlify rejected the token:
37
- ${E}
36
+ the current value.`}),await R(n,r)}else if(r.deployProvider==="netlify")for(let p=1;;p++){let h=w.spinner();h.start("Validating Netlify token");let f=await je({token:r.netlifyAuthToken??""});if(f.ok){h.stop(f.accountSlug?`Netlify token accepted (team: ${f.accountSlug})`:"Netlify token accepted");break}h.stop(f.message??"Netlify check failed",2),p>=S&&oe(n,"Netlify",f.message??"Netlify check failed");let A=f.message??"Netlify check failed";o.blank(),o.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${p+1} of ${S})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await I(r,{onlySection:"netlify",banner:`Netlify rejected the token:
37
+ ${A}
38
38
 
39
39
  Generate a new token at
40
40
  https://app.netlify.com/user/applications#personal-access-tokens
41
- and paste it below. Press Enter to keep the current value.`}),await C(n,r)}else if(r.deployProvider==="selfhost")for(let u=1;;u++){let m=Pe(r.selfhostDeployTarget??""),f=Te(r.selfhostUrlTemplate??"");if(!m&&!f){s.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let E=[m&&`SELFHOST_DEPLOY_TARGET: ${m}`,f&&`SELFHOST_URL_TEMPLATE: ${f}`].filter(Boolean).join(`
42
- `);u>=b&&X(n,"Self-host",E),s.blank(),s.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${u+1} of ${b})`),s.blank(),r=await _(r,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
43
- ${E}
41
+ and paste it below. Press Enter to keep the current value.`}),await R(n,r)}else if(r.deployProvider==="selfhost")for(let p=1;;p++){let h=Se(r.selfhostDeployTarget??""),f=_e(r.selfhostUrlTemplate??"");if(!h&&!f){o.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let A=[h&&`SELFHOST_DEPLOY_TARGET: ${h}`,f&&`SELFHOST_URL_TEMPLATE: ${f}`].filter(Boolean).join(`
42
+ `);p>=S&&oe(n,"Self-host",A),o.blank(),o.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${p+1} of ${S})`),o.blank(),r=await I(r,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
43
+ ${A}
44
44
 
45
- Re-enter them below. Press Enter on a field to keep its current value.`}),await C(n,r)}else for(let u=1;;u++){let m=k.spinner();m.start("Validating Vercel token");let f=await Le(r.vercelToken??"");if(f.ok){m.stop(f.username?`Vercel token accepted (signed in as ${f.username})`:"Vercel token accepted");break}m.stop(f.message??"Vercel check failed",2),u>=b&&X(n,"Vercel",f.message??"Vercel check failed");let E=f.message??"Vercel check failed";s.blank(),s.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${u+1} of ${b})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await _(r,{onlySection:"vercel",banner:`Vercel rejected the token:
46
- ${E}
45
+ Re-enter them below. Press Enter on a field to keep its current value.`}),await R(n,r)}else for(let p=1;;p++){let h=w.spinner();h.start("Validating Vercel token");let f=await He(r.vercelToken??"");if(f.ok){h.stop(f.username?`Vercel token accepted (signed in as ${f.username})`:"Vercel token accepted");break}h.stop(f.message??"Vercel check failed",2),p>=S&&oe(n,"Vercel",f.message??"Vercel check failed");let A=f.message??"Vercel check failed";o.blank(),o.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${p+1} of ${S})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await I(r,{onlySection:"vercel",banner:`Vercel rejected the token:
46
+ ${A}
47
47
 
48
48
  Generate a new token at https://vercel.com/account/tokens and
49
- paste it below. Press Enter to keep the current value.`}),await C(n,r)}s.blank();for(let u=1;;u++){let m=z(r.googlePlacesApiKey??""),f=k.spinner();f.start("Validating Google Places API key");let E=await le(r.googlePlacesApiKey??"");if(E.ok){if(f.stop("Google Places API key accepted"),m.changed){if(m.repairs.length>0){s.blank(),s.warn("Corrected look-alike characters in your Google Places API key:");for(let I of m.repairs)s.detail(` ${I}`);s.detail("These come from keys that were transcribed rather than copied."),s.detail("Google accepted the corrected key, and .env now holds it.")}r.googlePlacesApiKey=m.value,await C(n,r)}break}f.stop(E.message??"Google Places check failed",2),u>=b&&X(n,"Google Places",E.message??"Google Places check failed");let G=E.message??"Google Places check failed";s.blank(),s.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${u+1} of ${b})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await _(r,{onlySection:"google-places",banner:`Google rejected the key:
50
- ${G}
49
+ paste it below. Press Enter to keep the current value.`}),await R(n,r)}o.blank();for(let p=1;;p++){let h=Z(r.googlePlacesApiKey??""),f=w.spinner();f.start("Validating Google Places API key");let A=await me(r.googlePlacesApiKey??"");if(A.ok){if(f.stop("Google Places API key accepted"),h.changed){if(h.repairs.length>0){o.blank(),o.warn("Corrected look-alike characters in your Google Places API key:");for(let C of h.repairs)o.detail(` ${C}`);o.detail("These come from keys that were transcribed rather than copied."),o.detail("Google accepted the corrected key, and .env now holds it.")}r.googlePlacesApiKey=h.value,await R(n,r)}break}f.stop(A.message??"Google Places check failed",2),p>=S&&oe(n,"Google Places",A.message??"Google Places check failed");let z=A.message??"Google Places check failed";o.blank(),o.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${p+1} of ${S})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await I(r,{onlySection:"google-places",banner:`Google rejected the key:
50
+ ${z}
51
51
 
52
52
  Generate (or fix) the key at https://console.cloud.google.com
53
- and paste it below. Press Enter to keep the current value.`}),await C(n,r)}let y=!1;if(r.outreachEnabled&&r.outreachChannels?.includes("email")&&r.emailAddress&&r.emailPassword&&r.emailSmtpHost&&r.emailSmtpPort&&r.emailImapHost&&r.emailImapPort){s.blank();let u=0,m=!1,f;for(;!m;){u++;let E=k.spinner();E.start("Validating email credentials (SMTP + IMAP)");let G=r.emailProvider&&r.emailProvider!=="custom"?r.emailProvider:Ee(r.emailSmtpHost),I=G?V[G]:void 0,M=await ce({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort,usesAccountPassword:I?.usesAccountPassword});if(M.ok){E.stop("Email credentials accepted (SMTP + IMAP)");break}E.stop(M.message??"Email check failed",2);let we=`${G}\0${r.emailAddress}\0${r.emailPassword}`;if(I&&M.failureKind!=="network"&&f!==we){f=we;let ee=Ae(G,r.emailSmtpHost,r.emailImapHost),te,at=0;if(ee.length>0){s.blank(),s.warn(`That server rejected the login. ${I.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let D of ee){let Ve=k.spinner();Ve.start(`Trying ${D.label} (${D.smtpHost})`);let Ye=await ce({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:D.smtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:D.imapHost,emailImapPort:r.emailImapPort});if(Ye.ok){Ve.stop(`${D.label}: your login works here (${D.smtpHost})`),te=D;break}Ye.failureKind!=="network"&&at++,Ve.stop(Ye.failureKind==="network"?`${D.label}: unreachable`:`${D.label}: rejected too`,2)}}if(te){s.blank(),s.success("Found it \u2014 your password was right all along; the server was the only problem.");let D=await k.confirm({message:`Use the ${te.label} servers (${te.smtpHost} / ${te.imapHost})?`,initialValue:!0});if(k.isCancel(D)&&(k.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
53
+ and paste it below. Press Enter to keep the current value.`}),await R(n,r)}let y=!1;if(r.outreachEnabled&&r.outreachChannels?.includes("email")&&r.emailAddress&&r.emailPassword&&r.emailSmtpHost&&r.emailSmtpPort&&r.emailImapHost&&r.emailImapPort){o.blank();let p=0,h=!1,f;for(;!h;){p++;let A=w.spinner();A.start("Validating email credentials (SMTP + IMAP)");let z=r.emailProvider&&r.emailProvider!=="custom"?r.emailProvider:ce(r.emailSmtpHost),C=z?K[z]:void 0,M=await ne({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort,usesAccountPassword:C?.usesAccountPassword});if(M.ok){A.stop("Email credentials accepted (SMTP + IMAP)");break}A.stop(M.message??"Email check failed",2);let Te=`${z}\0${r.emailAddress}\0${r.emailPassword}`;if(C&&M.failureKind!=="network"&&f!==Te){f=Te;let se=be(z,r.emailSmtpHost,r.emailImapHost),ae,dt=0;if(se.length>0){o.blank(),o.warn(`That server rejected the login. ${C.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let D of se){let Be=w.spinner();Be.start(`Trying ${D.label} (${D.smtpHost})`);let We=await ne({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:D.smtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:D.imapHost,emailImapPort:r.emailImapPort});if(We.ok){Be.stop(`${D.label}: your login works here (${D.smtpHost})`),ae=D;break}We.failureKind!=="network"&&dt++,Be.stop(We.failureKind==="network"?`${D.label}: unreachable`:`${D.label}: rejected too`,2)}}if(ae){o.blank(),o.success("Found it \u2014 your password was right all along; the server was the only problem.");let D=await w.confirm({message:`Use the ${ae.label} servers (${ae.smtpHost} / ${ae.imapHost})?`,initialValue:!0});if(w.isCancel(D)&&(w.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
54
54
 
55
- ${ne(n)}
56
- `),process.exit(0)),D){r.emailSmtpHost=te.smtpHost,r.emailImapHost=te.imapHost,await C(n,r);continue}}else ee.length>0&&(s.blank(),at===0?s.warn("Couldn't reach any of the alternate servers \u2014 this looks like a network problem, not a credential problem. Check your connection and retry."):I.noAltWorkedHint&&s.warn(I.noAltWorkedHint))}let kn=M.message??"Email check failed";s.blank(),s.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),s.detail("You can skip it now and wire it up later from inside the project."),s.blank();let Ge=await k.select({message:`What would you like to do? ${d.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:u>=3?"skip":u>=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(k.isCancel(Ge)&&(k.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
55
+ ${re(n)}
56
+ `),process.exit(0)),D){r.emailSmtpHost=ae.smtpHost,r.emailImapHost=ae.imapHost,await R(n,r);continue}}else se.length>0&&(o.blank(),dt===0?o.warn("Couldn't reach any of the alternate servers \u2014 this looks like a network problem, not a credential problem. Check your connection and retry."):C.noAltWorkedHint&&o.warn(C.noAltWorkedHint))}let bn=M.message??"Email check failed";o.blank(),o.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),o.detail("You can skip it now and wire it up later from inside the project."),o.blank();let Ye=await w.select({message:`What would you like to do? ${d.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:p>=3?"skip":p>=2?"edit":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my email details and retry"},{value:"skip",label:"Skip email for now (finish setup; wire email up later)"}]});if(w.isCancel(Ye)&&(w.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
57
57
 
58
- ${ne(n)}
59
- `),process.exit(0)),Ge==="skip"){r.outreachChannels=(r.outreachChannels??[]).filter(ee=>ee!=="email"),r.outreachPriority=(r.outreachPriority??[]).filter(ee=>ee!=="email"),r.outreachChannels.length===0&&(r.outreachEnabled=!1),await C(n,r),y=!0,s.success("Skipped email for now. Setup will continue."),r.outreachEnabled?s.detail("Outreach will use your other channel(s); email stays off until it's fixed."):s.detail("Automated outreach is off until email is fixed \u2014 everything else works."),m=!0;break}Ge==="edit"&&(s.blank(),r=await _(r,{onlySection:"email",banner:`${M.failedAt==="imap"?"IMAP":"SMTP"} check failed:
60
- ${kn}
58
+ ${re(n)}
59
+ `),process.exit(0)),Ye==="skip"){r.outreachChannels=(r.outreachChannels??[]).filter(se=>se!=="email"),r.outreachPriority=(r.outreachPriority??[]).filter(se=>se!=="email"),r.outreachChannels.length===0&&(r.outreachEnabled=!1),await R(n,r),y=!0,o.success("Skipped email for now. Setup will continue."),r.outreachEnabled?o.detail("Outreach will use your other channel(s); email stays off until it's fixed."):o.detail("Automated outreach is off until email is fixed \u2014 everything else works."),h=!0;break}Ye==="edit"&&(o.blank(),r=await I(r,{onlySection:"email",banner:`${M.failedAt==="imap"?"IMAP":"SMTP"} check failed:
60
+ ${bn}
61
61
 
62
62
  Re-enter the email address, app password, or server details below.
63
63
  Press Enter on any field to keep its current value.
64
64
 
65
65
  Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
66
- at the "Server settings" question.`}),await C(n,r))}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="twilio"&&r.twilioAccountSid&&r.twilioAuthToken){s.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating Twilio credentials");let f=await Vt({accountSid:r.twilioAccountSid,authToken:r.twilioAuthToken});if(f.ok){m.stop(f.friendlyName?`Twilio credentials accepted (${f.friendlyName})`:"Twilio credentials accepted");break}m.stop(f.message??"Twilio check failed",2),u>=b&&X(n,"Twilio",f.message??"Twilio check failed");let E=f.message??"Twilio check failed";s.blank(),s.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${b})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await _(r,{onlySection:"sms",banner:`Twilio rejected the credentials:
67
- ${E}
66
+ at the "Server settings" question.`}),await R(n,r))}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="twilio"&&r.twilioAccountSid&&r.twilioAuthToken){o.blank();for(let p=1;;p++){let h=w.spinner();h.start("Validating Twilio credentials");let f=await qt({accountSid:r.twilioAccountSid,authToken:r.twilioAuthToken});if(f.ok){h.stop(f.friendlyName?`Twilio credentials accepted (${f.friendlyName})`:"Twilio credentials accepted");break}h.stop(f.message??"Twilio check failed",2),p>=S&&oe(n,"Twilio",f.message??"Twilio check failed");let A=f.message??"Twilio check failed";o.blank(),o.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${p+1} of ${S})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await I(r,{onlySection:"sms",banner:`Twilio rejected the credentials:
67
+ ${A}
68
68
 
69
69
  Re-enter the Account SID or Auth Token below.
70
- Press Enter on any field to keep its current value.`}),await C(n,r)}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="imessage"&&r.testPhone){s.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating iMessage setup (sending a test ping)");let f=await Yt({testPhone:r.testPhone});if(f.ok){m.stop("iMessage dispatched (check your phone for the test ping)");break}m.stop(f.message??"iMessage check failed",2),u>=b&&X(n,"iMessage",f.message??"iMessage check failed");let E=f.message??"iMessage check failed";s.blank(),s.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${b})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await _(r,{onlySection:"sms",banner:`iMessage check failed:
71
- ${E}
70
+ Press Enter on any field to keep its current value.`}),await R(n,r)}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="imessage"&&r.testPhone){o.blank();for(let p=1;;p++){let h=w.spinner();h.start("Validating iMessage setup (sending a test ping)");let f=await Jt({testPhone:r.testPhone});if(f.ok){h.stop("iMessage dispatched (check your phone for the test ping)");break}h.stop(f.message??"iMessage check failed",2),p>=S&&oe(n,"iMessage",f.message??"iMessage check failed");let A=f.message??"iMessage check failed";o.blank(),o.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${p+1} of ${S})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await I(r,{onlySection:"sms",banner:`iMessage check failed:
71
+ ${A}
72
72
 
73
73
  Either fix the underlying issue (sign in to Messages.app, configure
74
74
  Text Message Forwarding) and press Enter through, or change SMS
75
- provider to Twilio.`}),await C(n,r)}}if((r.notifyChannel??"telegram")==="telegram"&&r.telegramBotToken&&r.telegramChatId){s.blank();let u=0,m=!1;for(;!m;){u++;let f=k.spinner();f.start("Validating Telegram bot + chat (sending a test ping)");let E=await dt({botToken:r.telegramBotToken,chatId:r.telegramChatId});if(E.ok){f.stop(E.botHandle?`Telegram bot ${E.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),m=!0;break}f.stop(E.message??"Telegram check failed",2);let G=E.message??"Telegram check failed";s.blank(),s.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),s.blank();let I=await k.select({message:`What would you like to do? ${d.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:u>=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(k.isCancel(I)&&(k.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
75
+ provider to Twilio.`}),await R(n,r)}}if((r.notifyChannel??"telegram")==="telegram"&&r.telegramBotToken&&r.telegramChatId){o.blank();let p=0,h=!1;for(;!h;){p++;let f=w.spinner();f.start("Validating Telegram bot + chat (sending a test ping)");let A=await mt({botToken:r.telegramBotToken,chatId:r.telegramChatId});if(A.ok){f.stop(A.botHandle?`Telegram bot ${A.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),h=!0;break}f.stop(A.message??"Telegram check failed",2);let z=A.message??"Telegram check failed";o.blank(),o.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),o.blank();let C=await w.select({message:`What would you like to do? ${d.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:p>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(w.isCancel(C)&&(w.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
76
76
 
77
- ${ne(n)}
78
- `),process.exit(0)),I==="skip"){r.telegramBotToken=void 0,r.telegramChatId=void 0,await C(n,r),s.success("Skipped Telegram. Setup will continue."),s.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),m=!0;break}if(I==="edit"&&(s.blank(),r=await _(r,{onlySection:"notifications",banner:`Telegram check failed:
79
- ${G}
77
+ ${re(n)}
78
+ `),process.exit(0)),C==="skip"){r.telegramBotToken=void 0,r.telegramChatId=void 0,await R(n,r),o.success("Skipped Telegram. Setup will continue."),o.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`."),h=!0;break}if(C==="edit"&&(o.blank(),r=await I(r,{onlySection:"notifications",banner:`Telegram check failed:
79
+ ${z}
80
80
 
81
81
  Re-enter the bot token or chat_id below.
82
- Press Enter on any field to keep its current value.`}),await C(n,r),(r.notifyChannel??"telegram")!=="telegram"||!r.telegramBotToken||!r.telegramChatId)){s.success("Skipped Telegram. Setup will continue."),m=!0;break}}}s.blank();let A=k.spinner();A.start("Downloading Klaudius template");let v;try{v=(await Ne({licenseKey:i,machineId:ge(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:r.aiAgent,destDir:n})).filesExtracted,A.stop(`Downloaded ${v} files into ${d.bold(n)}`)}catch(u){A.stop(u.message,2);let m=r.aiAgent==="codex"?".codex/config.toml":".mcp.json";s.detail(`Your .env / ${m} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await Ze(F(n,"clients"),{recursive:!0});let ke=await Rt(n);await xe(n,It(Xt,ke)),s.success("Wrote .klaudius/manifest.json");let $=!1,Z="";if(e.skipSchema)s.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),s.detail(`Apply manually later via the SQL editor: ${r.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+r.supabaseProjectRef+"/sql/new").replace(r.supabaseProjectRef+".supabase.co","")}`);else{s.blank();let u=k.spinner();u.start("Applying schema to Supabase");let m=await Ut({projectRoot:n,pat:r.supabasePat,projectRef:r.supabaseProjectRef});m.ok?u.stop("Schema applied (or already present)"):(u.stop(m.message??"Schema apply failed",2),$=!0,Z=`https://supabase.com/dashboard/project/${r.supabaseProjectRef}/sql/new`)}let P=[],j={};if(e.skipInstall)s.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{s.blank(),s.heading("Installing dependencies");let u=await Ue(n);s.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&P.push("npm"),u.pip==="failed"&&P.push("pip"),u.playwright==="failed"&&P.push("playwright"),u.patchright==="failed"&&P.push("patchright"),j=u.hints??{}}let O=r.outreachEnabled&&r.outreachPriority?.includes("whatsapp")&&(r.whatsappAccounts?.length??0)>0,g=!e.skipInstall&&!P.includes("npm");if(O&&g){s.blank(),s.heading("Linking WhatsApp accounts"),console.log(d.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
82
+ Press Enter on any field to keep its current value.`}),await R(n,r),(r.notifyChannel??"telegram")!=="telegram"||!r.telegramBotToken||!r.telegramChatId)){o.success("Skipped Telegram. Setup will continue."),h=!0;break}}}o.blank();let k=w.spinner();k.start("Downloading Klaudius template");let b;try{b=(await Me({licenseKey:a,machineId:Ae(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:r.aiAgent,destDir:n})).filesExtracted,k.stop(`Downloaded ${b} files into ${d.bold(n)}`)}catch(p){k.stop(p.message,2);let h=r.aiAgent==="codex"?".codex/config.toml":".mcp.json";o.detail(`Your .env / ${h} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await tt(G(n,"clients"),{recursive:!0});let j=await $t(n);await $e(n,vt(nn,j)),o.success("Wrote .klaudius/manifest.json");let N=!1,ie="";if(e.skipSchema)o.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),o.detail(`Apply manually later via the SQL editor: ${r.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+r.supabaseProjectRef+"/sql/new").replace(r.supabaseProjectRef+".supabase.co","")}`);else{o.blank();let p=w.spinner();p.start("Applying schema to Supabase");let h=await Gt({projectRoot:n,pat:r.supabasePat,projectRef:r.supabaseProjectRef});h.ok?p.stop("Schema applied (or already present)"):(p.stop(h.message??"Schema apply failed",2),N=!0,ie=`https://supabase.com/dashboard/project/${r.supabaseProjectRef}/sql/new`)}let P=[],F={};if(e.skipInstall)o.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{o.blank(),o.heading("Installing dependencies");let p=await Fe(n);o.detail(`npm: ${p.npm}, pip: ${p.pip}, playwright: ${p.playwright}, patchright: ${p.patchright}`),p.npm==="failed"&&P.push("npm"),p.pip==="failed"&&P.push("pip"),p.playwright==="failed"&&P.push("playwright"),p.patchright==="failed"&&P.push("patchright"),F=p.hints??{}}let O=r.outreachEnabled&&r.outreachPriority?.includes("whatsapp")&&(r.whatsappAccounts?.length??0)>0,g=!e.skipInstall&&!P.includes("npm");if(O&&g){o.blank(),o.heading("Linking WhatsApp accounts"),console.log(d.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
83
83
  phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
84
- Link a Device, and point it at the QR shown in this terminal.`)),s.blank();for(let u of r.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${u}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${u})`));let m=en(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:n,stdio:"inherit"});m.status===0?s.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${m.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${u}`))),s.blank()}}else if(O&&!g){s.blank(),console.log(d.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let u of r.whatsappAccounts)console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${u}`))}s.blank();let L=[...P,...$?["schema"]:[]];if(L.length>0){k.outro(d.yellow(d.bold(`Setup paused \u2014 ${L.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),s.blank();for(let[M,we]of Object.entries(j))console.log(d.yellow(`Likely cause of ${M} failure:`)),console.log(d.dim(` ${we}`)),s.blank();let u=n!==process.cwd()&&e.target?` ${d.cyan(`cd ${je(e.target)}`)}
85
- `:"",m=r.aiAgent==="codex"?"codex":"claude",f=r.aiAgent==="codex"?"Codex":"Claude Code",E=r.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";P.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan(m)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${P.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(d.dim(` (Don't have ${f} yet? Install with: \`${E}\`)`)),s.blank(),console.log(d.dim("Or do it yourself:")),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify everything")}`),s.blank()),$&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(Z)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),P.includes("pip")&&!j.pip&&(console.log(d.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(d.dim(`Python 3.10+. Install a newer one from ${Ko()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),s.blank());let I=["npm","playwright","patchright"].filter(M=>P.includes(M)&&!j[M]);if(I.length>0){let M=I.length===1?"keeps":"keep";console.log(d.dim(`If ${I.join(" / ")} ${M} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}y&&(console.log(d.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${f}`)),console.log(d.dim("to finish setting it up \u2014 your email details are saved in .env.")),s.blank()),console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}if(Go(r,n,e.target),y){let u=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(d.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(d.dim(`Your details are saved in .env. To finish it, ask ${u}:`)),console.log(d.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(d.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(d.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(d.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(d.cyan(' and send a test email to my own address to confirm."')),r.outreachEnabled&&(r.outreachChannels??[]).length>0&&(s.blank(),console.log(d.yellow(`Note: your other channel(s) \u2014 ${(r.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),s.blank()}}async function C(e,t){await Ze(e,{recursive:!0}),await Qe(F(e,".env"),Ie(t),"utf-8"),t.aiAgent==="codex"?(await Ze(F(e,".codex"),{recursive:!0}),await Qe(F(e,".codex","config.toml"),Re(t),"utf-8")):(await Qe(F(e,".mcp.json"),Ce(t),"utf-8"),await He(e,"supabase"))}async function Do(e){try{(await et(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Zt(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let o=new Set([".env",".mcp.json",".claude",".codex"]),a=n.every(c=>o.has(c)),i=n.includes(".env"),l=t.includes(".klaudius");if(a&&i&&!l)return{kind:"partial",envPath:F(e,".env")};if(l&&i){let c=!0;try{c=!(await et(F(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function Uo(e){s.blank(),s.warn(`Found a partial setup at ${d.bold(e)}.`),s.detail(`A previous init wrote ${d.bold(".env")} but didn't finish scaffolding.`),s.blank();let t=await k.select({message:`How would you like to proceed? ${d.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 k.isCancel(t)&&(k.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Ho(e){if(e&&e.trim().length>0)return e;k.intro("Klaudius");let t=await k.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 k.isCancel(t)&&(k.cancel("Setup cancelled. No files written."),process.exit(0)),t}function jo(e){let t=Lo(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 o of n)if(t.startsWith(o))return`Inside ${o.slice(0,-1)} (system-managed directory).`}}function Fo(){if(process.platform!=="win32")return!1;try{return en("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Ko(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Go(e,t,n){let o=e.aiAgent==="codex"?"codex":"claude",a=e.aiAgent==="codex"?"Codex":"Claude Code";if(k.outro(d.green(d.bold("Project ready."))),console.log(d.bold("Next steps:")),s.blank(),t!==process.cwd()&&n){let i=`cd ${je(n)}`;console.log(` ${d.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${d.dim("# go into your project folder")}`)}console.log(` ${d.cyan(o)}${" ".repeat(Math.max(1,27-o.length))}${d.dim(`# opens ${a} in this project`)}`),s.blank(),console.log(d.bold(`Some starter prompts for ${a}:`)),s.blank(),console.log(` ${d.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${d.cyan(`I know I'm ready to start using Klaudius."`)}`),s.blank(),console.log(` ${d.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),s.blank(),console.log(` ${d.cyan('"Run the pipeline for one client."')}`),console.log(d.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),s.blank(),e.aiAgent!=="codex"&&(console.log(d.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(d.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),s.blank())}import{access as Vo,readFile as Yo}from"fs/promises";import{join as tt,resolve as Bo}from"path";import N from"picocolors";async function on(e){let t=e.target?Bo(process.cwd(),e.target):process.cwd(),n=await nn(tt(t,".env")),o=await nn(tt(t,"package.json"));(!n||!o)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),n||s.detail("Missing: .env"),o||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let a="claude-code";try{U(await Yo(tt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(a="codex")}catch{}s.heading("Installing dependencies");let i=await Ue(t);s.blank(),s.detail(`npm: ${i.npm}, pip: ${i.pip}, playwright: ${i.playwright}, patchright: ${i.patchright}`);let l=[];if(i.npm==="failed"&&l.push("npm"),i.pip==="failed"&&l.push("pip"),i.playwright==="failed"&&l.push("playwright"),i.patchright==="failed"&&l.push("patchright"),l.length===0){s.blank(),console.log(N.green(N.bold("All dependencies installed."))),console.log(N.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(N.yellow(N.bold(`${l.join(", ")} still failing.`))),s.blank();for(let[r,w]of Object.entries(i.hints??{}))console.log(N.yellow(`Likely cause of ${r} failure:`)),console.log(N.dim(` ${w}`)),s.blank();let c=a==="codex"?"codex":"claude",p=a==="codex"?"Codex":"Claude Code",h=a==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(N.dim("Options:")),console.log(N.dim(` \u2022 Open ${p} in this folder (\`${c}\`) and paste:`)),console.log(N.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(N.dim(` (Don't have ${p} yet? Install with: \`${h}\`)`)),console.log(N.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(N.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function nn(e){try{return await Vo(e),!0}catch{return!1}}import{readFile as Wo,writeFile as nt,access as zo}from"fs/promises";import{join as pe}from"path";import*as Fe from"@clack/prompts";import Y from"picocolors";import{mkdir as qo}from"fs/promises";async function sn(e){let t=e.projectRoot??process.cwd(),n=pe(t,".env"),o=pe(t,".mcp.json"),a=pe(t,".codex","config.toml"),i=await ot(pe(t,".klaudius","manifest.json")),l=await ot(n);!i&&!l&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=q();c.ok||(s.error(c.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let p={};try{let A=await Wo(n,"utf-8");p=U(A)}catch{s.warn("No .env found. Starting from an empty configuration.")}let h=Tt(p);Object.keys(p).length>0&&(h.pipelineModes??=["classic"]),Fe.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let r=await _(h),w=h.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==w&&(s.error(`Switching AI coding agent (${w} \u2192 ${r.aiAgent}) isn't supported via configure.`),s.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),s.blank(),console.log(` ${Y.cyan("npx klaudius@latest init <new-folder>")} ${Y.dim("# pick the new agent in the wizard")}`),s.blank(),s.detail(".env is unchanged."),process.exit(1)),r.supabaseUrl!==p.SUPABASE_URL||r.supabaseServiceKey!==p.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let A=await re({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});A.ok||(s.error(A.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let y=z(r.googlePlacesApiKey??"");if(y.changed&&r.googlePlacesApiKey){s.heading("Checking your Google Places API key");let A=await le(r.googlePlacesApiKey);if(A.ok){if(y.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let v of y.repairs)s.detail(` ${v}`);s.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=y.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(A.message??"Google rejected the Google Places API key"),s.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),s.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}await nt(n,Ie(r),"utf-8"),s.success("Updated .env"),r.aiAgent==="codex"?(await qo(pe(t,".codex"),{recursive:!0}),await nt(a,Re(r),"utf-8"),s.success("Updated .codex/config.toml")):(await nt(o,Ce(r),"utf-8"),s.success("Updated .mcp.json"),await He(t,"supabase")),s.blank(),Fe.outro(Y.green("Configuration updated.")),await Jo(t,i)}async function Jo(e,t){let n=await ot(pe(e,"node_modules"));s.blank(),t?n||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${Y.cyan("npx klaudius@latest install")} ${Y.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${Y.cyan("npx klaudius@latest doctor")} ${Y.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${Y.cyan("npx klaudius@latest init")} ${Y.dim("# pick Resume when prompted")}`),s.blank())}async function ot(e){try{return await zo(e),!0}catch{return!1}}import{copyFile as an,mkdir as rn,readFile as Xo,rm as ye,writeFile as ln,access as cn}from"fs/promises";import{dirname as dn,join as H}from"path";import{tmpdir as Qo}from"os";import*as fe from"@clack/prompts";import st from"picocolors";var Ke="0.21.3";async function un(e){let t=e.projectRoot??process.cwd(),n=await _t(t);n||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let g of Oe)delete n.files[g];let o,a=H(t,".env"),i,l;try{i=await Xo(a,"utf-8"),l=U(i)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}o=l.KLAUDIUS_LICENSE_KEY??"",o||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius@latest init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=Pt(i,l,At);c!==null&&(await ln(a,c,"utf-8"),s.detail("Backfilled new env keys")),await $e("update",Ke),fe.intro(`Update from ${n.templateVersion} \u2192 ${Ke}`);let h=l.AI_AGENT==="codex"?"codex":"claude-code",r=H(Qo(),`klaudius-update-${process.pid}-${Date.now()}`),w;try{s.heading("Downloading the latest Klaudius template");let g=await Ne({licenseKey:o,machineId:ge(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:h,destDir:r});s.success(`Fetched ${g.filesExtracted} canonical files`),w=r}catch(g){s.error(g.message),s.detail("Update aborted. Your project is unchanged."),await ye(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let y=await Zo(w,t,n),A=y.filter(g=>g.state==="new"),v=y.filter(g=>g.state==="clean-update"),ke=y.filter(g=>g.state==="user-only"),$=y.filter(g=>g.state==="conflict"),Z=y.filter(g=>g.state==="no-change"),P=y.filter(g=>g.state==="removed-clean"),j=y.filter(g=>g.state==="removed-modified"),O=[...$,...j];if(s.blank(),s.heading("Change summary"),s.detail(`${B(Z.length,"file")} unchanged`),s.detail(`${B(A.length,"new file")}`),s.detail(`${B(v.length,"file")} updated cleanly (no local edits)`),s.detail(`${B(ke.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${B(P.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${B($.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${B(j.length,"file")} removed upstream but edited locally (need your decision)`),A.length===0&&v.length===0&&P.length===0&&O.length===0){s.blank(),fe.outro(st.green("Already up to date.")),await ye(r,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let g of[...A,...v]){let L=H(w,g.path),u=H(t,g.path);await rn(dn(u),{recursive:!0}),await an(L,u),n.files[g.path]=g.canonicalHash}A.length+v.length>0&&s.success(`Wrote ${B(A.length+v.length,"file")}`);for(let g of P){let L=H(t,g.path);await ye(L,{force:!0}),delete n.files[g.path]}if(P.length>0&&s.success(`Deleted ${B(P.length,"file")} removed upstream`),O.length>0){s.blank(),s.heading(`${O.length} conflict(s) need resolution`);let g=H(t,".klaudius","incoming");try{await ye(g,{recursive:!0,force:!0})}catch{}for(let L of $){let u=H(w,L.path),m=H(g,L.path);await rn(dn(m),{recursive:!0}),await an(u,m)}await ln(H(t,".klaudius","conflicts.md"),es(O,n.templateVersion,Ke),"utf-8"),$.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}if(n.updatedAt=new Date().toISOString(),O.length===0&&(n.templateVersion=Ke),await xe(t,n),s.blank(),O.length===0)fe.outro(st.green("Update complete."));else{let g=h==="codex"?"Codex":"Claude Code";fe.outro(st.yellow(`${O.length} conflict(s) staged. Open ${g} in this project and ask:
86
- "Run /resolve-conflicts"`))}await ye(r,{recursive:!0,force:!0}).catch(()=>{})}async function Zo(e,t,n){let o=await ae(e),a=new Set(o),i=[];for(let l of o){let c=await ie(H(e,l)),p=n.files[l],h=H(t,l),r;try{await cn(h),r=await ie(h)}catch{i.push({path:l,state:"new",canonicalHash:c,manifestHash:p});continue}c===p?r===p?i.push({path:l,state:"no-change",canonicalHash:c,localHash:r,manifestHash:p}):i.push({path:l,state:"user-only",canonicalHash:c,localHash:r,manifestHash:p}):r===p?i.push({path:l,state:"clean-update",canonicalHash:c,localHash:r,manifestHash:p}):i.push({path:l,state:"conflict",canonicalHash:c,localHash:r,manifestHash:p})}for(let l of Object.keys(n.files)){if(a.has(l))continue;let c=n.files[l],p=H(t,l),h;try{await cn(p),h=await ie(p)}catch{delete n.files[l];continue}h===c?i.push({path:l,state:"removed-clean",localHash:h,manifestHash:c}):i.push({path:l,state:"removed-modified",localHash:h,manifestHash:c})}return i}function B(e,t){return`${e} ${t}${e===1?"":"s"}`}function es(e,t,n){let o=e.filter(c=>c.state==="conflict").length,a=e.filter(c=>c.state==="removed-modified").length,i=[];i.push("# Update Conflicts"),i.push(""),i.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),i.push(`Updating from canonical version **${t}** to **${n}**.`),i.push("");let l=[];o>0&&l.push(`${o} file${o===1?"":"s"} ha${o===1?"s":"ve"} BOTH local edits AND upstream changes`),a>0&&l.push(`${a} file${a===1?"":"s"} ${a===1?"was":"were"} removed upstream but edited locally`),i.push(l.join(", and ")+"."),i.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."),i.push(""),i.push("---"),i.push("");for(let c of e)i.push(`## ${c.path}`),i.push(""),c.state==="removed-modified"?(i.push("**Type:** Removed upstream"),i.push(""),i.push(`- Your local copy: \`${c.path}\``),i.push("- This file no longer exists in the canonical template."),i.push("- You've modified it locally since install."),i.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),i.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),i.push(""),i.push("**Resolution options for the SKILL to walk through:**"),i.push(""),i.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),i.push("2. Delete \u2014 remove the file from disk and from the manifest")):(i.push("**Type:** Edit conflict"),i.push(""),i.push(`- Your version (with your local edits): \`${c.path}\``),i.push(`- New canonical version: \`.klaudius/incoming/${c.path}\``),i.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),i.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),i.push(`- New canonical hash: \`${(c.canonicalHash??"(none)").slice(0,16)}\``),i.push(""),i.push("**Resolution options for the SKILL to walk through:**"),i.push(""),i.push("1. Keep mine \u2014 discard the new canonical changes"),i.push("2. Take canonical \u2014 overwrite my edits with the new version"),i.push("3. Merge \u2014 review both side-by-side and produce a combined version")),i.push(""),i.push("---"),i.push("");return i.join(`
87
- `)}import{access as ts,readFile as pn,stat as ns}from"fs/promises";import{join as K}from"path";import R from"picocolors";import{spawn as fn}from"child_process";async function mn(e){let t=e.projectRoot??process.cwd(),n=[];console.log(R.bold(`Klaudius doctor \u2014 checking your project\u2026
88
- `)),n.push(await os()),n.push(await ss());let o=K(t,".env"),a=K(t,".klaudius","manifest.json"),i=K(t,".mcp.json"),l=K(t,".codex","config.toml"),c=await Q(o),p=await Q(a),h="claude-code";if(c)try{U(await pn(o,"utf-8")).AI_AGENT==="codex"&&(h="codex")}catch{}if(h==="claude-code"){let y=await Q(K(t,"AGENTS.md")),A=!await Q(K(t,".claude"));y&&A&&(h="codex")}if(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."}),n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?"ok":"fail",detail:p?a:"missing",nextAction:p?void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."}),h==="codex"){let y=await Q(l);n.push({name:".codex/config.toml present",status:y?"ok":"warn",detail:y?l:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let y=await Q(i);n.push({name:".mcp.json present",status:y?"ok":"warn",detail:y?i:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await us(h)),n.push(await is(t)),n.push(await as(t)),n.push(await rs()),!c)n.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)n.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let y=await pn(o,"utf-8"),A=U(y);await ls(A,n)}console.log();for(let y of n){let A=y.status==="ok"?R.green("\u2713"):y.status==="warn"?R.yellow("\u26A0"):y.status==="skip"?R.dim("\xB7"):R.red("\u2717");console.log(` ${A} ${y.name}${y.detail?R.dim(` \u2014 ${y.detail}`):""}`),y.nextAction&&console.log(` ${R.dim("\u2192")} ${R.cyan(y.nextAction)}`)}let r=n.filter(y=>y.status==="fail").length,w=n.filter(y=>y.status==="warn").length;console.log(),r===0&&w===0?console.log(R.green(R.bold("Everything checks out. You're good to go."))):r===0?console.log(R.yellow(R.bold(`${w} warning${w===1?"":"s"} \u2014 review above.`))):(console.log(R.red(R.bold(`${r} failed check${r===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function Q(e){try{return await ts(e),!0}catch{return!1}}async function os(){let e=await se();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 ss(){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),o=parseInt(t[2],10);return n<22||n===22&&o<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 is(e){let t=K(e,"node_modules");if(!await Q(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await ns(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 as(e){let t=process.platform==="darwin"?K(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?K(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):K(process.env.HOME??"",".cache","ms-playwright");return await Q(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 rs(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
84
+ Link a Device, and point it at the QR shown in this terminal.`)),o.blank();for(let p of r.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${p}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${p})`));let h=ot(process.execPath,["scripts/whatsapp.mjs","pair","--account",p],{cwd:n,stdio:"inherit"});h.status===0?o.detail(`Paired '${p}'.`):(console.log(d.yellow(`'${p}' did not pair (exit ${h.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))),o.blank()}}else if(O&&!g){o.blank(),console.log(d.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let p of r.whatsappAccounts)console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))}let L=r.emailAuth==="oauth-microsoft"&&r.outreachEnabled&&r.outreachChannels?.includes("email"),Y=!e.skipInstall&&!P.includes("pip"),we=p=>{console.log(d.dim("Connect it any time from the project folder with:")),console.log(d.cyan(` ${p?p.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(d.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(L&&Y){o.blank(),o.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(d.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
85
+ password. Your browser will open to Microsoft's sign-in page \u2014
86
+ sign in as `+(r.emailAddress??"your outreach mailbox")+` and approve.
87
+ (No browser on this machine? It falls back to a short code you can
88
+ enter from any device.)`)),o.blank();let p=await B();if(p){let[h,...f]=p.command,A=ot(h,[...f,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});A.status===0?o.success("Outlook mailbox connected."):(o.blank(),console.log(d.yellow(`The Microsoft sign-in didn't complete (exit ${A.status??"signalled"}). Setup continues without it.`)),we(p))}else console.log(d.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),we(null)}else L&&!Y&&(o.blank(),console.log(d.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(d.cyan(" python3 scripts/ms_oauth.py login")));o.blank();let ct=[...P,...N?["schema"]:[]];if(ct.length>0){w.outro(d.yellow(d.bold(`Setup paused \u2014 ${ct.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),o.blank();for(let[M,Te]of Object.entries(F))console.log(d.yellow(`Likely cause of ${M} failure:`)),console.log(d.dim(` ${Te}`)),o.blank();let p=n!==process.cwd()&&e.target?` ${d.cyan(`cd ${Ge(e.target)}`)}
89
+ `:"",h=r.aiAgent==="codex"?"codex":"claude",f=r.aiAgent==="codex"?"Codex":"Claude Code",A=r.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";P.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),o.blank(),p&&process.stdout.write(p),console.log(` ${d.cyan(h)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${P.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),o.blank(),console.log(d.dim(` (Don't have ${f} yet? Install with: \`${A}\`)`)),o.blank(),console.log(d.dim("Or do it yourself:")),o.blank(),p&&process.stdout.write(p),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify everything")}`),o.blank()),N&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(ie)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),o.blank()),P.includes("pip")&&!F.pip&&(console.log(d.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(d.dim(`Python 3.10+. Install a newer one from ${zo()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),o.blank());let C=["npm","playwright","patchright"].filter(M=>P.includes(M)&&!F[M]);if(C.length>0){let M=C.length===1?"keeps":"keep";console.log(d.dim(`If ${C.join(" / ")} ${M} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),o.blank()}y&&(console.log(d.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${f}`)),console.log(d.dim("to finish setting it up \u2014 your email details are saved in .env.")),o.blank()),console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),o.blank();return}if(qo(r,n,e.target),y){let p=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(d.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(d.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(d.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(d.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(d.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(d.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(d.cyan(' and send a test email to my own address to confirm."')),r.outreachEnabled&&(r.outreachChannels??[]).length>0&&(o.blank(),console.log(d.yellow(`Note: your other channel(s) \u2014 ${(r.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),o.blank()}}async function R(e,t){await tt(e,{recursive:!0}),await et(G(e,".env"),xe(t),"utf-8"),t.aiAgent==="codex"?(await tt(G(e,".codex"),{recursive:!0}),await et(G(e,".codex","config.toml"),ve(t),"utf-8")):(await et(G(e,".mcp.json"),Oe(t),"utf-8"),await Ke(e,"supabase"))}async function Go(e){try{(await nt(e)).isDirectory()||(o.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await sn(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)),a=n.includes(".env"),l=t.includes(".klaudius");if(s&&a&&!l)return{kind:"partial",envPath:G(e,".env")};if(l&&a){let c=!0;try{c=!(await nt(G(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function Vo(e){o.blank(),o.warn(`Found a partial setup at ${d.bold(e)}.`),o.detail(`A previous init wrote ${d.bold(".env")} but didn't finish scaffolding.`),o.blank();let t=await w.select({message:`How would you like to proceed? ${d.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 w.isCancel(t)&&(w.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Yo(e){if(e&&e.trim().length>0)return e;w.intro("Klaudius");let t=await w.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 w.isCancel(t)&&(w.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Bo(e){let t=Fo(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 Wo(){if(process.platform!=="win32")return!1;try{return ot("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function zo(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function qo(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",s=e.aiAgent==="codex"?"Codex":"Claude Code";if(w.outro(d.green(d.bold("Project ready."))),console.log(d.bold("Next steps:")),o.blank(),t!==process.cwd()&&n){let a=`cd ${Ge(n)}`;console.log(` ${d.cyan(a)}${" ".repeat(Math.max(1,27-a.length))}${d.dim("# go into your project folder")}`)}console.log(` ${d.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${d.dim(`# opens ${s} in this project`)}`),o.blank(),console.log(d.bold(`Some starter prompts for ${s}:`)),o.blank(),console.log(` ${d.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${d.cyan(`I know I'm ready to start using Klaudius."`)}`),o.blank(),console.log(` ${d.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),o.blank(),console.log(` ${d.cyan('"Run the pipeline for one client."')}`),console.log(d.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.")),o.blank(),e.aiAgent!=="codex"&&(console.log(d.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(d.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),o.blank())}import{access as Jo,readFile as Xo}from"fs/promises";import{join as it,resolve as Qo}from"path";import $ from"picocolors";async function ln(e){let t=e.target?Qo(process.cwd(),e.target):process.cwd(),n=await rn(it(t,".env")),i=await rn(it(t,"package.json"));(!n||!i)&&(o.error("This doesn't look like a Klaudius project."),o.detail(`Path: ${t}`),n||o.detail("Missing: .env"),i||o.detail("Missing: package.json"),o.blank(),o.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),o.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let s="claude-code";try{H(await Xo(it(t,".env"),"utf-8")).AI_AGENT==="codex"&&(s="codex")}catch{}o.heading("Installing dependencies");let a=await Fe(t);o.blank(),o.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let l=[];if(a.npm==="failed"&&l.push("npm"),a.pip==="failed"&&l.push("pip"),a.playwright==="failed"&&l.push("playwright"),a.patchright==="failed"&&l.push("patchright"),l.length===0){o.blank(),console.log($.green($.bold("All dependencies installed."))),console.log($.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),o.blank();return}o.blank(),console.log($.yellow($.bold(`${l.join(", ")} still failing.`))),o.blank();for(let[r,E]of Object.entries(a.hints??{}))console.log($.yellow(`Likely cause of ${r} failure:`)),console.log($.dim(` ${E}`)),o.blank();let c=s==="codex"?"codex":"claude",u=s==="codex"?"Codex":"Claude Code",m=s==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log($.dim("Options:")),console.log($.dim(` \u2022 Open ${u} in this folder (\`${c}\`) and paste:`)),console.log($.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log($.dim(` (Don't have ${u} yet? Install with: \`${m}\`)`)),console.log($.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log($.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),o.blank(),process.exitCode=1}async function rn(e){try{return await Jo(e),!0}catch{return!1}}import{readFile as Zo,writeFile as st,access as ei}from"fs/promises";import{join as ye}from"path";import*as W from"@clack/prompts";import q from"picocolors";import{mkdir as ti}from"fs/promises";import{spawnSync as cn}from"child_process";async function dn(e){let t=e.projectRoot??process.cwd(),n=ye(t,".env"),i=ye(t,".mcp.json"),s=ye(t,".codex","config.toml"),a=await at(ye(t,".klaudius","manifest.json")),l=await at(n);!a&&!l&&(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ee();c.ok||(o.error(c.message??"Node.js version check failed."),o.blank(),o.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 k=await Zo(n,"utf-8");u=H(k)}catch{o.warn("No .env found. Starting from an empty configuration.")}let m=Ct(u);Object.keys(u).length>0&&(m.pipelineModes??=["classic"]),W.intro("Reconfigure Klaudius"),o.detail("Press Enter on any prompt to keep its current value."),o.blank();let r=await I(m),E=m.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==E&&(o.error(`Switching AI coding agent (${E} \u2192 ${r.aiAgent}) isn't supported via configure.`),o.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),o.blank(),console.log(` ${q.cyan("npx klaudius@latest init <new-folder>")} ${q.dim("# pick the new agent in the wizard")}`),o.blank(),o.detail(".env is unchanged."),process.exit(1)),r.supabaseUrl!==u.SUPABASE_URL||r.supabaseServiceKey!==u.SUPABASE_SERVICE_KEY){o.heading("Re-validating Supabase credentials");let k=await fe({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});k.ok||(o.error(k.message??"Supabase check failed"),o.warn("Aborting. .env not modified."),process.exit(1)),o.success("Supabase credentials accepted")}let y=Z(r.googlePlacesApiKey??"");if(y.changed&&r.googlePlacesApiKey){o.heading("Checking your Google Places API key");let k=await me(r.googlePlacesApiKey);if(k.ok){if(y.repairs.length>0){o.warn("Corrected look-alike characters in your Google Places API key:");for(let b of y.repairs)o.detail(` ${b}`);o.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=y.value,o.success("Google accepted the key \u2014 writing the corrected value to .env")}else o.error(k.message??"Google rejected the Google Places API key"),o.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),o.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(ni(r,u)){let k=W.spinner();k.start("Validating email credentials (SMTP + IMAP)");let b=r.emailProvider&&r.emailProvider!=="custom"?r.emailProvider:ce(r.emailSmtpHost),j=await ne({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort,usesAccountPassword:b?K[b].usesAccountPassword:void 0});j.ok?k.stop("Email credentials accepted (SMTP + IMAP)"):(k.stop(j.message??"Email check failed",2),o.warn("Writing the email settings exactly as you entered them \u2014 not verified."),o.detail(j.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 st(n,xe(r),"utf-8"),o.success("Updated .env"),r.aiAgent==="codex"?(await ti(ye(t,".codex"),{recursive:!0}),await st(s,ve(r),"utf-8"),o.success("Updated .codex/config.toml")):(await st(i,Oe(r),"utf-8"),o.success("Updated .mcp.json"),await Ke(t,"supabase")),r.emailAuth==="oauth-microsoft"&&r.outreachEnabled&&r.outreachChannels?.includes("email")){let k=await B();if(!(k!==null&&cn(k.command[0],[...k.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(o.blank(),!k)o.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),o.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let j=await W.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});W.isCancel(j)||!j?o.detail(`Skipped. Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`):cn(k.command[0],[...k.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?o.success("Outlook mailbox connected."):(o.warn("The Microsoft sign-in didn't complete."),o.detail(`Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`))}}o.blank(),W.outro(q.green("Configuration updated.")),await oi(t,a)}function ni(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"]];return n.some(([i])=>i===void 0||i==="")?!1:n.some(([i,s])=>String(i)!==(t[s]??""))}async function oi(e,t){let n=await at(ye(e,"node_modules"));o.blank(),t?n||(o.detail("Your project files are in place but dependencies aren't installed yet."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${q.cyan("npx klaudius@latest install")} ${q.dim("# (re-)installs npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${q.cyan("npx klaudius@latest doctor")} ${q.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${q.cyan("npx klaudius@latest init")} ${q.dim("# pick Resume when prompted")}`),o.blank())}async function at(e){try{return await ei(e),!0}catch{return!1}}import{copyFile as un,mkdir as pn,readFile as ii,rm as Pe,writeFile as fn,access as mn}from"fs/promises";import{dirname as hn,join as U}from"path";import{tmpdir as si}from"os";import*as ke from"@clack/prompts";import rt from"picocolors";var Ve="0.22.2";async function gn(e){let t=e.projectRoot??process.cwd(),n=await Ot(t);n||(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let g of Ne)delete n.files[g];let i,s=U(t,".env"),a,l;try{a=await ii(s,"utf-8"),l=H(a)}catch{o.error("Couldn't read .env from this directory."),o.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=l.KLAUDIUS_LICENSE_KEY??"",i||(o.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),o.detail("This file is created by `npx klaudius@latest init`. If your project predates"),o.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),o.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=It(a,l,_t);c!==null&&(await fn(s,c,"utf-8"),o.detail("Backfilled new env keys")),await De("update",Ve),ke.intro(`Update from ${n.templateVersion} \u2192 ${Ve}`);let m=l.AI_AGENT==="codex"?"codex":"claude-code",r=U(si(),`klaudius-update-${process.pid}-${Date.now()}`),E;try{o.heading("Downloading the latest Klaudius template");let g=await Me({licenseKey:i,machineId:Ae(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:m,destDir:r});o.success(`Fetched ${g.filesExtracted} canonical files`),E=r}catch(g){o.error(g.message),o.detail("Update aborted. Your project is unchanged."),await Pe(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let y=await ai(E,t,n),k=y.filter(g=>g.state==="new"),b=y.filter(g=>g.state==="clean-update"),j=y.filter(g=>g.state==="user-only"),N=y.filter(g=>g.state==="conflict"),ie=y.filter(g=>g.state==="no-change"),P=y.filter(g=>g.state==="removed-clean"),F=y.filter(g=>g.state==="removed-modified"),O=[...N,...F];if(o.blank(),o.heading("Change summary"),o.detail(`${J(ie.length,"file")} unchanged`),o.detail(`${J(k.length,"new file")}`),o.detail(`${J(b.length,"file")} updated cleanly (no local edits)`),o.detail(`${J(j.length,"file")} you've edited (no upstream change \u2014 left alone)`),o.detail(`${J(P.length,"file")} removed upstream (deleted cleanly)`),o.detail(`${J(N.length,"file")} with conflicts (you edited AND we have a new version)`),o.detail(`${J(F.length,"file")} removed upstream but edited locally (need your decision)`),k.length===0&&b.length===0&&P.length===0&&O.length===0){o.blank(),ke.outro(rt.green("Already up to date.")),await Pe(r,{recursive:!0,force:!0}).catch(()=>{});return}o.blank(),o.heading("Applying clean updates");for(let g of[...k,...b]){let L=U(E,g.path),Y=U(t,g.path);await pn(hn(Y),{recursive:!0}),await un(L,Y),n.files[g.path]=g.canonicalHash}k.length+b.length>0&&o.success(`Wrote ${J(k.length+b.length,"file")}`);for(let g of P){let L=U(t,g.path);await Pe(L,{force:!0}),delete n.files[g.path]}if(P.length>0&&o.success(`Deleted ${J(P.length,"file")} removed upstream`),O.length>0){o.blank(),o.heading(`${O.length} conflict(s) need resolution`);let g=U(t,".klaudius","incoming");try{await Pe(g,{recursive:!0,force:!0})}catch{}for(let L of N){let Y=U(E,L.path),we=U(g,L.path);await pn(hn(we),{recursive:!0}),await un(Y,we)}await fn(U(t,".klaudius","conflicts.md"),ri(O,n.templateVersion,Ve),"utf-8"),N.length>0&&o.detail("Staged canonical versions to .klaudius/incoming/"),o.detail("Wrote conflict report to .klaudius/conflicts.md")}if(n.updatedAt=new Date().toISOString(),O.length===0&&(n.templateVersion=Ve),await $e(t,n),o.blank(),O.length===0)ke.outro(rt.green("Update complete."));else{let g=m==="codex"?"Codex":"Claude Code";ke.outro(rt.yellow(`${O.length} conflict(s) staged. Open ${g} in this project and ask:
90
+ "Run /resolve-conflicts"`))}await Pe(r,{recursive:!0,force:!0}).catch(()=>{})}async function ai(e,t,n){let i=await pe(e),s=new Set(i),a=[];for(let l of i){let c=await ue(U(e,l)),u=n.files[l],m=U(t,l),r;try{await mn(m),r=await ue(m)}catch{a.push({path:l,state:"new",canonicalHash:c,manifestHash:u});continue}c===u?r===u?a.push({path:l,state:"no-change",canonicalHash:c,localHash:r,manifestHash:u}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:r,manifestHash:u}):r===u?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:r,manifestHash:u}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:r,manifestHash:u})}for(let l of Object.keys(n.files)){if(s.has(l))continue;let c=n.files[l],u=U(t,l),m;try{await mn(u),m=await ue(u)}catch{delete n.files[l];continue}m===c?a.push({path:l,state:"removed-clean",localHash:m,manifestHash:c}):a.push({path:l,state:"removed-modified",localHash:m,manifestHash:c})}return a}function J(e,t){return`${e} ${t}${e===1?"":"s"}`}function ri(e,t,n){let i=e.filter(c=>c.state==="conflict").length,s=e.filter(c=>c.state==="removed-modified").length,a=[];a.push("# Update Conflicts"),a.push(""),a.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),a.push(`Updating from canonical version **${t}** to **${n}**.`),a.push("");let l=[];i>0&&l.push(`${i} file${i===1?"":"s"} ha${i===1?"s":"ve"} BOTH local edits AND upstream changes`),s>0&&l.push(`${s} file${s===1?"":"s"} ${s===1?"was":"were"} removed upstream but edited locally`),a.push(l.join(", and ")+"."),a.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."),a.push(""),a.push("---"),a.push("");for(let c of e)a.push(`## ${c.path}`),a.push(""),c.state==="removed-modified"?(a.push("**Type:** Removed upstream"),a.push(""),a.push(`- Your local copy: \`${c.path}\``),a.push("- This file no longer exists in the canonical template."),a.push("- You've modified it locally since install."),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),a.push("2. Delete \u2014 remove the file from disk and from the manifest")):(a.push("**Type:** Edit conflict"),a.push(""),a.push(`- Your version (with your local edits): \`${c.path}\``),a.push(`- New canonical version: \`.klaudius/incoming/${c.path}\``),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(`- New canonical hash: \`${(c.canonicalHash??"(none)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 discard the new canonical changes"),a.push("2. Take canonical \u2014 overwrite my edits with the new version"),a.push("3. Merge \u2014 review both side-by-side and produce a combined version")),a.push(""),a.push("---"),a.push("");return a.join(`
91
+ `)}import{access as li,readFile as yn,stat as ci}from"fs/promises";import{join as V}from"path";import x from"picocolors";import{spawn as kn,spawnSync as di}from"child_process";async function wn(e){let t=e.projectRoot??process.cwd(),n=[];console.log(x.bold(`Klaudius doctor \u2014 checking your project\u2026
92
+ `)),n.push(await ui()),n.push(await pi());let i=V(t,".env"),s=V(t,".klaudius","manifest.json"),a=V(t,".mcp.json"),l=V(t,".codex","config.toml"),c=await X(i),u=await X(s),m="claude-code";if(c)try{H(await yn(i,"utf-8")).AI_AGENT==="codex"&&(m="codex")}catch{}if(m==="claude-code"){let y=await X(V(t,"AGENTS.md")),k=!await X(V(t,".claude"));y&&k&&(m="codex")}if(n.push({name:".env present",status:c?"ok":"fail",detail:c?i:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."}),n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:u?"ok":"fail",detail:u?s:"missing",nextAction:u?void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."}),m==="codex"){let y=await X(l);n.push({name:".codex/config.toml present",status:y?"ok":"warn",detail:y?l:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let y=await X(a);n.push({name:".mcp.json present",status:y?"ok":"warn",detail:y?a:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await Ei(m)),n.push(await fi(t)),n.push(await mi(t)),n.push(await hi()),!c)n.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)n.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let y=await yn(i,"utf-8"),k=H(y);await gi(k,n,t)}console.log();for(let y of n){let k=y.status==="ok"?x.green("\u2713"):y.status==="warn"?x.yellow("\u26A0"):y.status==="skip"?x.dim("\xB7"):x.red("\u2717");console.log(` ${k} ${y.name}${y.detail?x.dim(` \u2014 ${y.detail}`):""}`),y.nextAction&&console.log(` ${x.dim("\u2192")} ${x.cyan(y.nextAction)}`)}let r=n.filter(y=>y.status==="fail").length,E=n.filter(y=>y.status==="warn").length;console.log(),r===0&&E===0?console.log(x.green(x.bold("Everything checks out. You're good to go."))):r===0?console.log(x.yellow(x.bold(`${E} warning${E===1?"":"s"} \u2014 review above.`))):(console.log(x.red(x.bold(`${r} failed check${r===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function X(e){try{return await li(e),!0}catch{return!1}}async function ui(){let e=await de();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 pi(){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 fi(e){let t=V(e,"node_modules");if(!await X(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await ci(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 mi(e){let t=process.platform==="darwin"?V(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?V(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):V(process.env.HOME??"",".cache","ms-playwright");return await X(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 hi(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
89
93
  try:
90
- ${e.map(i=>` import ${i}`).join(`
94
+ ${e.map(a=>` import ${a}`).join(`
91
95
  `)}
92
96
  except Exception as e:
93
97
  print(str(e))
94
98
  sys.exit(1)
95
- `,n=await he();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 o=n.command,a=await hn(o[0],[...o.slice(1),"-c",t]);return a.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(a.stdout||a.stderr).trim().split(`
96
- `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function ls(e,t){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let i=await re({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:i.ok?"ok":"fail",detail:i.ok?"connected":i.message,nextAction:i.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 n=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(n==="selfhost"){let i=e.SELFHOST_DEPLOY_TARGET??"",l=e.SELFHOST_URL_TEMPLATE??"",c=[],p=Pe(i);p&&c.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let h=Te(l);h&&c.push(`SELFHOST_URL_TEMPLATE: ${h}`),t.push({name:"Self-host deploy config",status:c.length===0?"ok":"fail",detail:c.length===0?`target ${i} (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(n==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let i=await Me({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:i.ok?"ok":"fail",detail:i.ok?`valid (${i.projectCount??0} Pages project${i.projectCount===1?"":"s"})`:i.message,nextAction:i.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(n==="netlify")if(e.NETLIFY_AUTH_TOKEN){let i=await De({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:i.ok?"ok":"fail",detail:i.ok?i.accountSlug?`valid (team: ${i.accountSlug})`:"valid":i.message,nextAction:i.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 i=await Le(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:i.ok?"ok":"fail",detail:i.ok?i.username??"valid":i.message,nextAction:i.ok?void 0:"Generate a new token at https://vercel.com/account/tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let i=await le(e.GOOGLE_PLACES_API_KEY),l=z(e.GOOGLE_PLACES_API_KEY);i.ok&&l.changed?t.push({name:"Google Places API key",status:"fail",detail:"The key works, but the copy stored in .env is not the key we had to send \u2014 "+(l.repairs.length>0?`it contains look-alike characters (${l.repairs.join("; ")}). `:"it contains invisible or stray characters. ")+"The pipeline's scripts read .env directly and will fail on it.",nextAction:"Run `npx klaudius@latest configure` and press Enter through the prompts \u2014 it rewrites .env with the corrected key."}):t.push({name:"Google Places API key",status:i.ok?"ok":"fail",detail:i.ok?"accepted":i.message,nextAction:i.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 ds(e));let o=(e.NOTIFY_CHANNEL??"").toLowerCase(),a=o==="email"||o==="sms"||o==="none"||o==="off"?o:"telegram";if(a==="none"||a==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(a==="email"){let i=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:i&&e.EMAIL_ADDRESS?"ok":"fail",detail:i&&e.EMAIL_ADDRESS?`alerts go to ${i}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:i&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(a==="sms"){let i=e.NOTIFY_TO||e.TEST_PHONE,l=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:i&&l?"ok":"fail",detail:i&&l?`alerts go to ${i} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:i?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:i&&l?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let i=await ct({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:i.ok?"ok":"fail",detail:i.ok?`bot ${i.botHandle??"ok"} (chat_id not tested)`:i.message,nextAction:i.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 cs(e){let t=i=>!!i&&/^\d+$/.test(i.trim()),n=!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),o=(e.OUTREACH_CHANNELS??"").split(",").map(i=>i.trim()),a=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&o.includes("email");return a&&n?"active":a?"incomplete":n?"parked":"unconfigured"}async function ds(e){let t="Email credentials (SMTP + IMAP)",n=cs(e);if(n==="unconfigured")return{name:t,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(n==="parked")return{name:t,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(n==="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:t,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=_e(e),a=o&&o!=="custom"?o:Ee(e.EMAIL_SMTP_HOST),i={emailAddress:e.EMAIL_ADDRESS,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:a?V[a].usesAccountPassword:void 0},l=await ce(i);if(l.ok)return{name:t,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`};if(l.failureKind==="network")return{name:t,status:"fail",detail:l.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(a){let c=Ae(a,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(R.dim(` (email login rejected \u2014 probing ${V[a].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let r of c){let w=await ce({...i,emailSmtpHost:r.smtpHost,emailImapHost:r.imapHost});if(!w.ok&&w.failureKind!=="network"&&p++,w.ok)return{name:t,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${r.label} (${r.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${r.smtpHost} and EMAIL_IMAP_HOST=${r.imapHost} in .env (or ask your AI agent to).`}}let h=(l.message??"login rejected").split(/\.\s|\n/)[0];return p===0?{name:t,status:"fail",detail:`${h} \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:t,status:"fail",detail:`${h} \u2014 tried all ${V[a].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:a==="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`.":a==="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:t,status:"fail",detail:l.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}async function us(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",o=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`.",a=await hn(t,["--version"],process.platform==="win32");return a.code===0?{name:n,status:"ok",detail:(a.stdout||a.stderr).trim().split(`
97
- `)[0]}:{name:n,status:"warn",detail:"not found",nextAction:o}}function hn(e,t,n=!1){return new Promise(o=>{let a=n?fn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):fn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",l="";a.stdout?.on("data",c=>{i+=c.toString()}),a.stderr?.on("data",c=>{l+=c.toString()}),a.on("close",c=>o({code:c??1,stdout:i,stderr:l})),a.on("error",()=>o({code:1,stdout:i,stderr:l}))})}import{existsSync as ps}from"fs";import{spawnSync as fs}from"child_process";import{join as ms,resolve as hs}from"path";import x from"picocolors";async function gn(e){let t=hs(e.projectRoot??process.cwd()),n=ms(t,"scripts","whatsapp.mjs");ps(n)||(console.error(x.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(x.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(x.dim(`Looked for: ${n}`)),process.exit(1));let o=(e.label??"primary").trim(),a=o.replace(/[^A-Za-z0-9_-]/g,"");a||(console.error(x.red(`Invalid label '${o}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),a!==o&&console.error(x.yellow(`Note: cleaned label '${o}' \u2192 '${a}' (filename-safe characters only).`)),console.log(x.cyan(`Pairing WhatsApp account '${a}'...`)),console.log(x.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.
98
- `));let i=fs(process.execPath,[n,"pair","--account",a],{cwd:t,stdio:"inherit"});if(i.status===0){console.log(x.green(`Paired '${a}'.`)),console.log(x.dim(`
99
- If you haven't already, add '${a}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
100
- WHATSAPP_ACCOUNTS=primary,${a}
101
- (Skip this if '${a}' is already there or you set it via the init wizard.)`));return}i.error?console.error(x.red(`Pair failed: ${i.error.message}`)):(console.error(x.red(`Pair did not complete (exit ${i.status??"signalled"}). Common causes:`)),console.error(x.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(x.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(x.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${a}/daemon.log`))),process.exit(i.status??1)}import{spawnSync as gs}from"child_process";var it="--use-system-ca";function yn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(it)||!q().ok)return;let n=e?`${e} ${it}`:it,o=gs(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});o.signal&&(process.kill(process.pid,o.signal),process.exit(1)),process.exit(o.status??1)}yn();var ks="0.21.3",W=new ys;W.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(ks);W.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 yt({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});W.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").action(async(e,t)=>{try{await tn({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});W.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 on({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});W.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await sn({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});W.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await un({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});W.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 mn({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});W.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 gn({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});W.parse(process.argv);
99
+ `,n=await B();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 An(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(`
100
+ `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function gi(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let l=await fe({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:l.ok?"ok":"fail",detail:l.ok?"connected":l.message,nextAction:l.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 l=e.SELFHOST_DEPLOY_TARGET??"",c=e.SELFHOST_URL_TEMPLATE??"",u=[],m=Se(l);m&&u.push(`SELFHOST_DEPLOY_TARGET: ${m}`);let r=_e(c);r&&u.push(`SELFHOST_URL_TEMPLATE: ${r}`),t.push({name:"Self-host deploy config",status:u.length===0?"ok":"fail",detail:u.length===0?`target ${l} (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 l=await Ue({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:l.ok?"ok":"fail",detail:l.ok?`valid (${l.projectCount??0} Pages project${l.projectCount===1?"":"s"})`:l.message,nextAction:l.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 l=await je({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:l.ok?"ok":"fail",detail:l.ok?l.accountSlug?`valid (team: ${l.accountSlug})`:"valid":l.message,nextAction:l.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 l=await He(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:l.ok?"ok":"fail",detail:l.ok?l.username??"valid":l.message,nextAction:l.ok?void 0:"Generate a new token at https://vercel.com/account/tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let l=await me(e.GOOGLE_PLACES_API_KEY),c=Z(e.GOOGLE_PLACES_API_KEY);l.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:l.ok?"ok":"fail",detail:l.ok?"accepted":l.message,nextAction:l.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 wi(e,n));let s=(e.NOTIFY_CHANNEL??"").toLowerCase(),a=s==="email"||s==="sms"||s==="none"||s==="off"?s:"telegram";if(a==="none"||a==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(a==="email"){let l=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:l&&e.EMAIL_ADDRESS?"ok":"fail",detail:l&&e.EMAIL_ADDRESS?`alerts go to ${l}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:l&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(a==="sms"){let l=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:l&&c?"ok":"fail",detail:l&&c?`alerts go to ${l} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:l?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:l&&c?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let l=await ft({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:l.ok?"ok":"fail",detail:l.ok?`bot ${l.botHandle??"ok"} (chat_id not tested)`:l.message,nextAction:l.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 yi(e){let t=a=>!!a&&/^\d+$/.test(a.trim()),n=En(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(a=>a.trim()),s=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&i.includes("email");return s&&n?"active":s?"incomplete":n?"parked":"unconfigured"}function En(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function ki(e){let t="Email account (Microsoft sign-in)",n=await B(),s=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[l,...c]=n.command,u=di(l,[...c,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),m=`${u.stdout??""}${u.stderr??""}`.trim();if(u.status===0){let r=/signed in as (\S+)/.exec(m)?.[1];return{name:t,status:"ok",detail:r?`signed in as ${r} (token refresh works)`:"signed in (token refresh works)"}}return{name:t,status:"fail",detail:m.split(`
101
+ `)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:s}}return await X(V(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 wi(e,t){let n="Email credentials (SMTP + IMAP)",i=yi(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(En(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."}:ki(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(m=>m.endsWith("_PORT")?!e[m]||!/^\d+$/.test(e[m].trim()):!e[m]);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=Re(e),a=s&&s!=="custom"?s:ce(e.EMAIL_SMTP_HOST),l={emailAddress:e.EMAIL_ADDRESS,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:a?K[a].usesAccountPassword:void 0},c=await ne(l);if(c.ok)return{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(a){let u=be(a,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(u.length>0){console.log(x.dim(` (email login rejected \u2014 probing ${K[a].label}'s other regional servers, up to ~10s each\u2026)`));let m=0;for(let E of u){let y=await ne({...l,emailSmtpHost:E.smtpHost,emailImapHost:E.imapHost});if(!y.ok&&y.failureKind!=="network"&&m++,y.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${E.label} (${E.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${E.smtpHost} and EMAIL_IMAP_HOST=${E.imapHost} in .env (or ask your AI agent to).`}}let r=(c.message??"login rejected").split(/\.\s|\n/)[0];return m===0?{name:n,status:"fail",detail:`${r} \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:`${r} \u2014 tried all ${K[a].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:a==="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`.":a==="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."}}async function Ei(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 An(t,["--version"],process.platform==="win32");return s.code===0?{name:n,status:"ok",detail:(s.stdout||s.stderr).trim().split(`
102
+ `)[0]}:{name:n,status:"warn",detail:"not found",nextAction:i}}function An(e,t,n=!1){return new Promise(i=>{let s=n?kn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):kn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";s.stdout?.on("data",c=>{a+=c.toString()}),s.stderr?.on("data",c=>{l+=c.toString()}),s.on("close",c=>i({code:c??1,stdout:a,stderr:l})),s.on("error",()=>i({code:1,stdout:a,stderr:l}))})}import{existsSync as Ai}from"fs";import{spawnSync as Pi}from"child_process";import{join as Ti,resolve as bi}from"path";import v from"picocolors";async function Pn(e){let t=bi(e.projectRoot??process.cwd()),n=Ti(t,"scripts","whatsapp.mjs");Ai(n)||(console.error(v.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(v.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(v.dim(`Looked for: ${n}`)),process.exit(1));let i=(e.label??"primary").trim(),s=i.replace(/[^A-Za-z0-9_-]/g,"");s||(console.error(v.red(`Invalid label '${i}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),s!==i&&console.error(v.yellow(`Note: cleaned label '${i}' \u2192 '${s}' (filename-safe characters only).`)),console.log(v.cyan(`Pairing WhatsApp account '${s}'...`)),console.log(v.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
103
+ `));let a=Pi(process.execPath,[n,"pair","--account",s],{cwd:t,stdio:"inherit"});if(a.status===0){console.log(v.green(`Paired '${s}'.`)),console.log(v.dim(`
104
+ If you haven't already, add '${s}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
105
+ WHATSAPP_ACCOUNTS=primary,${s}
106
+ (Skip this if '${s}' is already there or you set it via the init wizard.)`));return}a.error?console.error(v.red(`Pair failed: ${a.error.message}`)):(console.error(v.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(v.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(v.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(v.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${s}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as Si}from"child_process";var lt="--use-system-ca";function Tn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(lt)||!ee().ok)return;let n=e?`${e} ${lt}`:lt,i=Si(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)}Tn();var Ii="0.22.2",Q=new _i;Q.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Ii);Q.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 At({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});Q.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").action(async(e,t)=>{try{await an({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});Q.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 ln({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});Q.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await dn({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});Q.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await gn({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});Q.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 wn({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});Q.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 Pn({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});Q.parse(process.argv);