klaudius 0.19.1 → 0.19.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/bin.js +43 -43
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -29,7 +29,7 @@ The setup command installs Node and Python into your user space (no admin passwo
29
29
  ## Commands
30
30
 
31
31
  ```bash
32
- npx klaudius preflight # Re-check this machine is ready (Node, Python, pip, npm, network)
32
+ npx klaudius preflight # Re-check this machine is ready (Node, Python, pip, npm, network; on Windows also that PowerShell can run npx)
33
33
  npx klaudius init [target] # Scaffold a fresh project
34
34
  npx klaudius configure # Re-run the setup wizard against an existing project
35
35
  npx klaudius update # Pull latest template; conflicts staged for resolution
package/dist/bin.js CHANGED
@@ -1,93 +1,93 @@
1
1
  #!/usr/bin/env node
2
- import{a as se,b as ot,c as st,d as we,e as z,g as T,i as it,j as at,l as q,m as rt,n as lt}from"./chunk-H6TMU6MK.js";import{Command as ss}from"commander";import{spawn as ct}from"child_process";import _ from"picocolors";function J(){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 o=parseInt(t[1],10),n=parseInt(t[2],10),a=parseInt(t[3],10),i=`${o}.${n}.${a}`;return o<22||o===22&&n<15?{ok:!1,version:i,major:o,minor:n,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:o,minor:n}}import{spawn as fn}from"child_process";var me=3,Ae=10,mn=[["python3"],["python"],["py","-3"]];async function he(){for(let e of mn){let t=await gn(e[0],[...e.slice(1),"--version"]),o=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(o)||t.code!==0)continue;let n=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(o);if(!n)continue;let a=parseInt(n[1],10),i=parseInt(n[2],10),l=n[3]?`${a}.${i}.${n[3]}`:`${a}.${i}`;return{command:[...e],version:l,major:a,minor:i}}return null}async function ie(){let e=hn(),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}.${Ae}+ is not installed (or not on PATH). Install it from ${e}.`+l}}let{command:o,version:n,major:a,minor:i}=t;return a<me||a===me&&i<Ae?{ok:!1,version:n,major:a,minor:i,command:o,message:`Your installed Python is ${n}. Klaudius needs Python ${me}.${Ae} or newer (the pipeline depends on packages that only ship wheels for ${me}.${Ae}+). 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:n,major:a,minor:i,command:o}}function hn(){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 gn(e,t){return new Promise(o=>{let n=fn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",i="";n.stdout?.on("data",l=>{a+=l.toString()}),n.stderr?.on("data",l=>{i+=l.toString()}),n.on("close",l=>o({code:l??1,stdout:a,stderr:i})),n.on("error",()=>o({code:1,stdout:a,stderr:i}))})}var dt=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function ut(e={}){console.log(_.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
- `));let t=[];t.push(yn());let o=await ie();t.push(kn(o)),t.push(await wn(o.command)),t.push(await An()),t.push(await En());for(let a of t){let i=a.status==="ok"?_.green("\u2713"):_.red("\u2717");console.log(` ${i} ${a.name}${a.detail?_.dim(` \u2014 ${a.detail}`):""}`),a.nextAction&&console.log(` ${_.dim("\u2192")} ${_.cyan(a.nextAction)}`)}console.log();let n=t.filter(a=>a.status==="fail");if(n.length===0){Pn();return}console.log(_.red(_.bold(`${n.length} check${n.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 yn(){let e=J();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 kn(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 wn(e){let t=e??["python3"],o=await Fe(t[0],[...t.slice(1),"-m","pip","--version"]);return o.code===0?{name:"pip available",status:"ok",detail:(o.stdout||o.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 An(){let e=process.platform==="win32",t=await Fe("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 Fe("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 En(){try{return await fetch(dt,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:dt}}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 Pn(){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 Fe(e,t,o=!1){return new Promise(n=>{let a=o?ct([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ct(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=>n({code:c??1,stdout:i,stderr:l})),a.on("error",()=>n({code:1,stdout:i,stderr:l}))})}import{mkdir as qe,readdir as Wt,readFile as Gt,stat as Je,writeFile as ze}from"fs/promises";import{spawnSync as Yt}from"child_process";import{homedir as yo}from"os";import{resolve as ko,isAbsolute as wo,join as H,normalize as Ao}from"path";import*as y from"@clack/prompts";import d from"picocolors";import bn from"react";import{render as Tn}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:o}=await import("./WizardApp-RUIFVZWE.js"),n=null;se("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),st(),await new Promise(i=>setImmediate(i)),await new Promise(i=>setTimeout(i,0)),se("runWizard:event loop drained, mounting Ink");let a=Tn(bn.createElement(o,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:i=>{se("runWizard:onComplete called",{keys:Object.keys(i).length}),n=i}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(se("runWizard:render returned, awaiting exit"),await a.waitUntilExit(),se("runWizard:waitUntilExit resolved",{resultIsNull:n===null}),!n)throw new Error(`Wizard exited without completing. Diagnostic log: ${ot}
5
- Please share that file so we can trace what happened.`);return n}var Ge="claude-code";function pt(e){if(e==="claude-code"||e==="codex")return e}var Ve="vercel";function ft(e){if(e==="vercel"||e==="cloudflare"||e==="netlify")return e}function _n(e){if(e==="custom"||e!==void 0&&Object.hasOwn(z,e))return e}function Ee(e){let t=_n(e.EMAIL_PROVIDER);if(t)return t;let o=e.EMAIL_SMTP_HOST;if(o){for(let[n,a]of Object.entries(z))if(a.smtpHost===o)return n;return"custom"}}function Pe(e){let t=[],o=a=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${a}`),t.push("# "+"=".repeat(60)),t.push("")},n=(a,i)=>{if(i==null||i===""){t.push(`# ${a}=`);return}let l=String(i);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(l)){let c=l.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${a}="${c}"`)}else t.push(`${a}=${l}`)};return t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),o("Klaudius licence"),n("KLAUDIUS_LICENSE_KEY",e.licenseKey),o("AI coding agent"),n("AI_AGENT",e.aiAgent??Ge),o("Operating country and language"),n("OPERATOR_COUNTRY",e.country),n("OPERATOR_COUNTRY_CODE",e.countryCode),n("OPERATOR_LANGUAGE",e.language),n("OPERATOR_LANGUAGE_CODE",e.languageCode),o("Pricing"),n("PRICING",e.pricing),n("PRICING_TERMS",e.pricingTerms),n("PRICING_MONTHLY",e.pricingMonthly),o("Automated outreach features"),n("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),n("OPERATOR_NAME",e.name),n("SIGNATURE",e.signature),n("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),n("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),o("Email outreach"),n("EMAIL_PROVIDER",e.emailProvider),n("EMAIL_ADDRESS",e.emailAddress),n("EMAIL_PASSWORD",e.emailPassword),n("EMAIL_FROM_NAME",e.emailFromName),n("EMAIL_SMTP_HOST",e.emailSmtpHost),n("EMAIL_SMTP_PORT",e.emailSmtpPort),n("EMAIL_IMAP_HOST",e.emailImapHost),n("EMAIL_IMAP_PORT",e.emailImapPort),n("EMAIL_SENT_FOLDER",e.emailSentFolder),n("EMAIL_INBOX_FOLDER",e.emailInboxFolder),o("SMS outreach"),n("SMS_PROVIDER",e.smsProvider),n("TEST_PHONE",e.testPhone),n("TWILIO_ACCOUNT_SID",e.twilioAccountSid),n("TWILIO_AUTH_TOKEN",e.twilioAuthToken),n("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),o("WhatsApp outreach"),n("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),o("Supabase (pipeline state)"),n("SUPABASE_URL",e.supabaseUrl),n("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),n("SUPABASE_PAT",e.supabasePat),n("SUPABASE_PROJECT_REF",e.supabaseProjectRef),o("Deployment"),n("DEPLOY_PROVIDER",e.deployProvider??Ve),n("VERCEL_TOKEN",e.vercelToken),n("VERCEL_SCOPE",e.vercelScope??""),n("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),n("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),n("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),n("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),o("Search APIs"),n("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),o("Telegram notifications (optional)"),n("TELEGRAM_BOT_TOKEN",e.telegramBotToken),n("TELEGRAM_CHAT_ID",e.telegramChatId),t.join(`
2
+ import{a as se,b as st,c as it,d as Ae,e as z,g as T,i as at,j as rt,l as q,m as lt,n as ct}from"./chunk-H6TMU6MK.js";import{Command as fs}from"commander";import{spawn as pt}from"child_process";import S from"picocolors";function J(){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 o=parseInt(t[1],10),n=parseInt(t[2],10),i=parseInt(t[3],10),a=`${o}.${n}.${i}`;return o<22||o===22&&n<15?{ok:!1,version:a,major:o,minor:n,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:o,minor:n}}import{spawn as hn}from"child_process";import{existsSync as gn}from"fs";import{homedir as yn}from"os";import{delimiter as kn,join as Ee}from"path";var wn=new Set(["Restricted","AllSigned"]);function An(e,t=gn){for(let o of e.split(kn)){let n=o.replace(/"/g,"");if(!n)continue;let i=Ee(n,"npx.ps1");if(t(i))return{path:i,isPs1:!0};for(let a of["npx.exe","npx.bat","npx.cmd"]){let l=Ee(n,a);if(t(l))return{path:l,isPs1:!1}}}return null}async function ut(){let e=An(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await En();if(!t)return{blocked:!1,shimPath:e.path};let o=Ee(yn(),".local","node")+"\\";return{blocked:wn.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(o.toLowerCase())}}async function En(){let e=Ee(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await dt(e)??await dt("powershell.exe")}function dt(e){let t={...process.env};for(let o of Object.keys(t))o.toLowerCase()==="psmodulepath"&&delete t[o];return new Promise(o=>{let n=hn(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),i="",a=setTimeout(()=>{n.kill(),o(null)},8e3);n.stdout.on("data",l=>{i+=l.toString()}),n.stderr?.resume(),n.on("close",l=>{clearTimeout(a),o(l===0&&i.trim()?i.trim():null)}),n.on("error",()=>{clearTimeout(a),o(null)})})}import{spawn as Pn}from"child_process";var he=3,Pe=10,bn=[["python3"],["python"],["py","-3"]];async function ge(){for(let e of bn){let t=await Sn(e[0],[...e.slice(1),"--version"]),o=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(o)||t.code!==0)continue;let n=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(o);if(!n)continue;let i=parseInt(n[1],10),a=parseInt(n[2],10),l=n[3]?`${i}.${a}.${n[3]}`:`${i}.${a}`;return{command:[...e],version:l,major:i,minor:a}}return null}async function ie(){let e=Tn(),t=await ge();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 ${he}.${Pe}+ is not installed (or not on PATH). Install it from ${e}.`+l}}let{command:o,version:n,major:i,minor:a}=t;return i<he||i===he&&a<Pe?{ok:!1,version:n,major:i,minor:a,command:o,message:`Your installed Python is ${n}. Klaudius needs Python ${he}.${Pe} or newer (the pipeline depends on packages that only ship wheels for ${he}.${Pe}+). 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:n,major:i,minor:a,command:o}}function Tn(){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 Sn(e,t){return new Promise(o=>{let n=Pn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";n.stdout?.on("data",l=>{i+=l.toString()}),n.stderr?.on("data",l=>{a+=l.toString()}),n.on("close",l=>o({code:l??1,stdout:i,stderr:a})),n.on("error",()=>o({code:1,stdout:i,stderr:a}))})}var ft=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function mt(e={}){console.log(S.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
+ `));let t=[];t.push(In());let o=await ie();if(t.push(_n(o)),t.push(await Cn(o.command)),t.push(await Rn()),process.platform==="win32"){let i=await xn();i&&t.push(i)}t.push(await vn());for(let i of t){let a=i.status==="ok"?S.green("\u2713"):S.red("\u2717");console.log(` ${a} ${i.name}${i.detail?S.dim(` \u2014 ${i.detail}`):""}`),i.nextAction&&console.log(` ${S.dim("\u2192")} ${S.cyan(i.nextAction)}`)}console.log();let n=t.filter(i=>i.status==="fail");if(n.length===0){On();return}console.log(S.red(S.bold(`${n.length} check${n.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 In(){let e=J();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 _n(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 Cn(e){let t=e??["python3"],o=await Ge(t[0],[...t.slice(1),"-m","pip","--version"]);return o.code===0?{name:"pip available",status:"ok",detail:(o.stdout||o.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 Rn(){let e=process.platform==="win32",t=await Ge("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 Ge("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 xn(){let e=await ut();if(e.npxMissing)return null;let t="npx runs in PowerShell";if(!e.blocked){let o="resolves to a policy-immune shim";return e.shimPath&&(o=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:o}}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 vn(){try{return await fetch(ft,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:ft}}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 On(){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 Ge(e,t,o=!1){return new Promise(n=>{let i=o?pt([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):pt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{l+=c.toString()}),i.on("close",c=>n({code:c??1,stdout:a,stderr:l})),i.on("error",()=>n({code:1,stdout:a,stderr:l}))})}import{mkdir as Je,readdir as qt,readFile as Wt,stat as Xe,writeFile as qe}from"fs/promises";import{spawnSync as Jt}from"child_process";import{homedir as Co}from"os";import{resolve as Ro,isAbsolute as xo,join as H,normalize as vo}from"path";import*as y from"@clack/prompts";import d from"picocolors";import $n from"react";import{render as Nn}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:o}=await import("./WizardApp-RUIFVZWE.js"),n=null;se("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),it(),await new Promise(a=>setImmediate(a)),await new Promise(a=>setTimeout(a,0)),se("runWizard:event loop drained, mounting Ink");let i=Nn($n.createElement(o,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:a=>{se("runWizard:onComplete called",{keys:Object.keys(a).length}),n=a}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(se("runWizard:render returned, awaiting exit"),await i.waitUntilExit(),se("runWizard:waitUntilExit resolved",{resultIsNull:n===null}),!n)throw new Error(`Wizard exited without completing. Diagnostic log: ${st}
5
+ Please share that file so we can trace what happened.`);return n}var Ve="claude-code";function ht(e){if(e==="claude-code"||e==="codex")return e}var Be="vercel";function gt(e){if(e==="vercel"||e==="cloudflare"||e==="netlify")return e}function Ln(e){if(e==="custom"||e!==void 0&&Object.hasOwn(z,e))return e}function be(e){let t=Ln(e.EMAIL_PROVIDER);if(t)return t;let o=e.EMAIL_SMTP_HOST;if(o){for(let[n,i]of Object.entries(z))if(i.smtpHost===o)return n;return"custom"}}function Te(e){let t=[],o=i=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${i}`),t.push("# "+"=".repeat(60)),t.push("")},n=(i,a)=>{if(a==null||a===""){t.push(`# ${i}=`);return}let l=String(a);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(l)){let c=l.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${i}="${c}"`)}else t.push(`${i}=${l}`)};return t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),o("Klaudius licence"),n("KLAUDIUS_LICENSE_KEY",e.licenseKey),o("AI coding agent"),n("AI_AGENT",e.aiAgent??Ve),o("Operating country and language"),n("OPERATOR_COUNTRY",e.country),n("OPERATOR_COUNTRY_CODE",e.countryCode),n("OPERATOR_LANGUAGE",e.language),n("OPERATOR_LANGUAGE_CODE",e.languageCode),o("Pricing"),n("PRICING",e.pricing),n("PRICING_TERMS",e.pricingTerms),n("PRICING_MONTHLY",e.pricingMonthly),o("Automated outreach features"),n("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),n("OPERATOR_NAME",e.name),n("SIGNATURE",e.signature),n("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),n("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),o("Email outreach"),n("EMAIL_PROVIDER",e.emailProvider),n("EMAIL_ADDRESS",e.emailAddress),n("EMAIL_PASSWORD",e.emailPassword),n("EMAIL_FROM_NAME",e.emailFromName),n("EMAIL_SMTP_HOST",e.emailSmtpHost),n("EMAIL_SMTP_PORT",e.emailSmtpPort),n("EMAIL_IMAP_HOST",e.emailImapHost),n("EMAIL_IMAP_PORT",e.emailImapPort),n("EMAIL_SENT_FOLDER",e.emailSentFolder),n("EMAIL_INBOX_FOLDER",e.emailInboxFolder),o("SMS outreach"),n("SMS_PROVIDER",e.smsProvider),n("TEST_PHONE",e.testPhone),n("TWILIO_ACCOUNT_SID",e.twilioAccountSid),n("TWILIO_AUTH_TOKEN",e.twilioAuthToken),n("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),o("WhatsApp outreach"),n("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),o("Supabase (pipeline state)"),n("SUPABASE_URL",e.supabaseUrl),n("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),n("SUPABASE_PAT",e.supabasePat),n("SUPABASE_PROJECT_REF",e.supabaseProjectRef),o("Deployment"),n("DEPLOY_PROVIDER",e.deployProvider??Be),n("VERCEL_TOKEN",e.vercelToken),n("VERCEL_SCOPE",e.vercelScope??""),n("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),n("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),n("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),n("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),o("Search APIs"),n("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),o("Telegram notifications (optional)"),n("TELEGRAM_BOT_TOKEN",e.telegramBotToken),n("TELEGRAM_CHAT_ID",e.telegramChatId),t.join(`
6
6
  `)+`
7
- `}function be(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 Te(e){let t=e.supabaseProjectRef,o=Sn(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 = "${o}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
9
- `)}function Sn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var mt=[{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:"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.'}];function In(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let o=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${o}"`}return`${e}=${t}`}function ht(e,t,o){let n=o.filter(l=>!(l.key in t));if(n.length===0)return null;let a=e.endsWith(`
7
+ `}function Se(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 Ie(e){let t=e.supabaseProjectRef,o=Mn(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 = "${o}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
9
+ `)}function Mn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var yt=[{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:"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.'}];function Dn(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let o=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${o}"`}return`${e}=${t}`}function kt(e,t,o){let n=o.filter(l=>!(l.key in t));if(n.length===0)return null;let i=e.endsWith(`
10
10
  `)?"":`
11
- `,i=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let l of n)i.push(""),l.comment&&i.push(`# ${l.comment}`),i.push(In(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 n)a.push(""),l.comment&&a.push(`# ${l.comment}`),a.push(Dn(l.key,l.value));return e+i+a.join(`
12
12
  `)+`
13
- `}function Cn(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 o of e.split(`
14
- `)){let n=o.trim();if(!n||n.startsWith("#"))continue;let a=n.indexOf("=");if(a===-1)continue;let i=n.slice(0,a).trim(),l=Cn(n.slice(a+1).trim());t[i]=l}return t}function gt(e){let t=c=>{let p=e[c];if(!p)return;let m=parseInt(p,10);return isNaN(m)?void 0:m},o=e.SMS_PROVIDER,n=c=>c==="email"||c==="sms"||c==="whatsapp",a=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(n),i=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(n),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)??Ge,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,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:Ee(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:o==="imessage"||o==="twilio"?o: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:ft(e.DEPLOY_PROVIDER)??Ve,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,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,emailPassword:e.EMAIL_PASSWORD,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function Be(e){let t=P=>{let $=e[P];if(!$)return;let k=parseInt($,10);return isNaN(k)?void 0:k},o=e.SUPABASE_URL,n=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=ft(e.DEPLOY_PROVIDER)??Ve,m=e.VERCEL_TOKEN,r=e.CLOUDFLARE_API_TOKEN,w=e.CLOUDFLARE_ACCOUNT_ID,g=e.NETLIFY_AUTH_TOKEN;if(!l||!o||!n||!a||!i||!(p==="cloudflare"?!!r&&!!w:p==="netlify"?!!g:!!m))return null;let v=e.SMS_PROVIDER,oe=P=>P==="email"||P==="sms"||P==="whatsapp",M=e.OUTREACH_CHANNELS?.split(",").map(P=>P.trim()).filter(oe),Y=e.OUTREACH_PRIORITY?.split(",").map(P=>P.trim()).filter(oe),b=e.WHATSAPP_ACCOUNTS?.split(",").map(P=>P.trim()).filter(P=>P.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:pt(e.AI_AGENT)??Ge,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,pricing:l,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:M&&M.length>0?M:void 0,outreachPriority:Y&&Y.length>0?Y:void 0,whatsappAccounts:b&&b.length>0?b:void 0,emailProvider:Ee(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:v==="imessage"||v==="twilio"?v:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:p,vercelToken:m,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:r||void 0,cloudflareAccountId:w||void 0,netlifyAuthToken:g||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,supabaseUrl:o,supabaseServiceKey:n,supabasePat:a,supabaseProjectRef:i,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Is,mkdir as Cs,readdir as Dn,stat as Rs}from"fs/promises";import{dirname as xs,join as Et,relative as Un}from"path";import{fileURLToPath as $s}from"url";import{createHash as Rn}from"crypto";import{readFile as vn}from"fs/promises";async function ae(e){let t=await vn(e);return Rn("sha256").update(t).digest("hex")}import{mkdir as xn,readFile as On,writeFile as $n,access as Nn}from"fs/promises";import{dirname as Ln,join as yt}from"path";var Mn=".klaudius",kt=`${Mn}/manifest.json`,_e=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml"]);async function wt(e){let t=yt(e,kt);try{await Nn(t)}catch{return null}let o=await On(t,"utf-8");return JSON.parse(o)}async function Se(e,t){let o=yt(e,kt);await xn(Ln(o),{recursive:!0}),await $n(o,JSON.stringify(t,null,2)+`
15
- `,"utf-8")}function At(e,t){let o=new Date().toISOString();return{version:1,templateVersion:e,installedAt:o,updatedAt:o,files:t}}async function Ie(e,t=e){let o=await Dn(e,{withFileTypes:!0}),n=[];for(let a of o){let i=Et(e,a.name);a.isDirectory()?n.push(...await Ie(i,t)):a.isFile()&&n.push(Un(t,i))}return n}async function Pt(e){let t=await Ie(e),o={};for(let n of t)_e.has(n)||(o[n]=await ae(Et(e,n)));return o}import{copyFile as jn,mkdir as bt,mkdtemp as Hn,readdir as Tt,rm as _t}from"fs/promises";import{tmpdir as Kn}from"os";import{dirname as Fn,join as Ce}from"path";import{Readable as Gn}from"stream";import*as St from"tar";var Vn="https://klaudius.dev/api/template";function Bn(e){return Gn.fromWeb(e)}async function Re(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Vn,o="0.19.1",n;try{n=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:o,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${T(c)}`)}if(!n.ok){let c="";try{let p=await n.json();c=p.reason?` (${p.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${n.status}${c}`)}if(!n.body)throw new Error("Template download succeeded but response had no body");let a=n.headers.get("x-klaudius-tier"),i=await Hn(Ce(Kn(),"klaudius-template-")),l=0;try{try{await new Promise((m,r)=>{let w=St.extract({cwd:i,strict:!0});w.on("finish",m),w.on("error",r),Bn(n.body).on("error",r).pipe(w)})}catch(m){throw new Error(`Failed to extract template archive: ${m.message}`)}await bt(e.destDir,{recursive:!0});let c=new Set(await Tt(e.destDir)),p=await Ie(i);try{for(let m of p){let r=Ce(e.destDir,m);await bt(Fn(r),{recursive:!0}),await jn(Ce(i,m),r),l++}}catch(m){let r=await Tt(e.destDir).catch(()=>[]);for(let w of r)c.has(w)||await _t(Ce(e.destDir,w),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${m.message}`)}}finally{await _t(i,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:a}}import X from"picocolors";var s={info:e=>console.log(X.cyan("\u2139"),e),success:e=>console.log(X.green("\u2713"),e),warn:e=>console.log(X.yellow("\u26A0"),e),error:e=>console.error(X.red("\u2717"),e),step:e=>console.log(X.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
16
- `+X.bold(X.cyan(e))),detail:e=>console.log(X.dim(" "+e))};var Wn="https://registry.npmjs.org/klaudius/latest";async function Yn(e=1500){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{let n=await fetch(Wn,{signal:t.signal,headers:{accept:"application/json"}});if(!n.ok)return null;let a=await n.json();return typeof a.version=="string"?a.version:null}catch{return null}finally{clearTimeout(o)}}function zn(e,t){let o=i=>i.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),n=o(e),a=o(t);if(n.length<3||a.length<3)return!1;for(let i=0;i<3;i++){if(Number.isNaN(n[i])||Number.isNaN(a[i]))return!1;if(n[i]>a[i])return!0;if(n[i]<a[i])return!1}return!1}async function ve(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let o=await Yn();!o||!zn(o,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${o}.`),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 qn}from"crypto";import{hostname as It,userInfo as Jn,platform as Ct,arch as Rt}from"os";var Xn="https://klaudius.dev",Qn="/api/licenses/validate",Zn="0.19.1";async function vt(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(),n=(process.env.KLAUDIUS_API_URL??Xn).replace(/\/$/,"")+Qn,a=ge(),i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:a,hostname:It(),os:`${Ct()}-${Rt()}`,cli_version:Zn})})}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=[It(),Jn().username,Ct(),Rt()].join("|");return qn("sha256").update(e).digest("hex").slice(0,32)}import{readFile as eo}from"fs/promises";import{join as to}from"path";async function re(e){let t=e.serviceKey.replace(/\s+/g,"");try{let o=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return o.status===401||o.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${o.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(o){return{ok:!1,message:`Could not reach Supabase: ${T(o)}`}}}async function xt(e){let t;try{t=await eo(to(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(n){return{ok:!1,message:`Could not read scripts/schema.sql: ${n.message}`}}let o=e.pat.replace(/\s+/g,"");try{let n=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(n.ok)return{ok:!0};let a=await n.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 ${n.status}): ${a.slice(0,300)}`}}catch(n){return{ok:!1,message:`Schema apply failed: ${n.message}`}}}async function xe(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 o=await t.json();return{ok:!0,username:o.user?.username??o.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${T(t)}`}}}var Ot="https://api.cloudflare.com/client/v4";function $t(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Oe(e){let{token:t,accountId:o}=e,n={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let a=await fetch(`${Ot}/user/tokens/verify`,{headers:n});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})`:""}. ${$t(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(`${Ot}/accounts/${encodeURIComponent(o)}/pages/projects`,{headers:n});if(a.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${o} (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 ${o} 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:$t(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 Nt="https://api.netlify.com/api/v1";async function $e(e){let{token:t}=e,o={Authorization:`Bearer ${t}`};try{let n=await fetch(`${Nt}/user`,{headers:o});if(n.status===401||n.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${n.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(!n.ok)return{ok:!1,message:`Netlify API returned HTTP ${n.status} verifying the token. Try again or check netlifystatus.com.`}}catch(n){return{ok:!1,message:`Could not reach Netlify: ${T(n)}`}}try{let n=await fetch(`${Nt}/accounts`,{headers:o});if(!n.ok)return{ok:!1,message:`Netlify API returned HTTP ${n.status} listing your teams. Try again or check netlifystatus.com.`};let a=await n.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(n){return{ok:!1,message:`Could not reach Netlify: ${T(n)}`}}}async function le(e){let t=rt(e);if(t)return{ok:!1,message:t};let o=q(e),n=o.value,a=i=>{let l=[i],c=lt(e);return c&&l.push(c),o.repairs.length>0&&l.push(`Note: we corrected ${o.repairs.length} look-alike character(s) in this key before sending it (${o.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":n,"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 no from"nodemailer";import{ImapFlow as oo}from"imapflow";function Lt(e){let t=e;if(t?.authenticationFailed)return"auth";let o=typeof t?.code=="string"?t.code.toUpperCase():"";if(o==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(o))return"network";let n=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return n.includes("invalid credentials")||n.includes("authentication failed")||n.includes("auth failed")||n.includes("login failed")||n.includes("invalid login")?"auth":n.includes("etimedout")||n.includes("timeout")||n.includes("enotfound")||n.includes("getaddrinfo")||n.includes("econnrefused")||n.includes("econnreset")?"network":"other"}async function ce(e){let t=no.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(n){return{ok:!1,failedAt:"smtp",message:Mt(n,"SMTP"),failureKind:Lt(n)}}finally{t.close()}let o=new oo({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 o.connect(),await o.logout()}catch(n){try{await o.logout()}catch{}return{ok:!1,failedAt:"imap",message:Mt(n,"IMAP"),failureKind:Lt(n)}}return{ok:!0}}function Mt(e,t){let o=e instanceof Error?e.message:String(e),n=o.toLowerCase();return n.includes("invalid credentials")||n.includes("authentication failed")||n.includes("auth failed")||n.includes("login failed")?`${t} rejected the credentials. Most common causes:
13
+ `}function Un(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 D(e){let t={};for(let o of e.split(`
14
+ `)){let n=o.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i===-1)continue;let a=n.slice(0,i).trim(),l=Un(n.slice(i+1).trim());t[a]=l}return t}function wt(e){let t=c=>{let p=e[c];if(!p)return;let m=parseInt(p,10);return isNaN(m)?void 0:m},o=e.SMS_PROVIDER,n=c=>c==="email"||c==="sms"||c==="whatsapp",i=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(n),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(n),l=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:ht(e.AI_AGENT)??Ve,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,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:i&&i.length>0?i:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailProvider:be(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:o==="imessage"||o==="twilio"?o: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:gt(e.DEPLOY_PROVIDER)??Be,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,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,emailPassword:e.EMAIL_PASSWORD,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function We(e){let t=P=>{let $=e[P];if(!$)return;let k=parseInt($,10);return isNaN(k)?void 0:k},o=e.SUPABASE_URL,n=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),i=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,l=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",p=gt(e.DEPLOY_PROVIDER)??Be,m=e.VERCEL_TOKEN,r=e.CLOUDFLARE_API_TOKEN,w=e.CLOUDFLARE_ACCOUNT_ID,g=e.NETLIFY_AUTH_TOKEN;if(!l||!o||!n||!i||!a||!(p==="cloudflare"?!!r&&!!w:p==="netlify"?!!g:!!m))return null;let x=e.SMS_PROVIDER,oe=P=>P==="email"||P==="sms"||P==="whatsapp",L=e.OUTREACH_CHANNELS?.split(",").map(P=>P.trim()).filter(oe),Y=e.OUTREACH_PRIORITY?.split(",").map(P=>P.trim()).filter(oe),b=e.WHATSAPP_ACCOUNTS?.split(",").map(P=>P.trim()).filter(P=>P.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:ht(e.AI_AGENT)??Ve,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,pricing:l,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:L&&L.length>0?L:void 0,outreachPriority:Y&&Y.length>0?Y:void 0,whatsappAccounts:b&&b.length>0?b:void 0,emailProvider:be(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:x==="imessage"||x==="twilio"?x:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:p,vercelToken:m,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:r||void 0,cloudflareAccountId:w||void 0,netlifyAuthToken:g||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,supabaseUrl:o,supabaseServiceKey:n,supabasePat:i,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Fs,mkdir as Gs,readdir as Yn,stat as Vs}from"fs/promises";import{dirname as Ws,join as Tt,relative as zn,sep as qn}from"path";import{fileURLToPath as zs}from"url";import{createHash as jn}from"crypto";import{readFile as Hn}from"fs/promises";async function ae(e){let t=await Hn(e);return jn("sha256").update(t).digest("hex")}import{mkdir as Kn,readFile as Fn,writeFile as Gn,access as Vn}from"fs/promises";import{dirname as Bn,join as At}from"path";var Wn=".klaudius",Et=`${Wn}/manifest.json`,_e=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml"]);async function Pt(e){let t=At(e,Et);try{await Vn(t)}catch{return null}let o=await Fn(t,"utf-8"),n=JSON.parse(o),i={};for(let[a,l]of Object.entries(n.files??{}))i[a.split("\\").join("/")]=l;return n.files=i,n}async function Ce(e,t){let o=At(e,Et);await Kn(Bn(o),{recursive:!0}),await Gn(o,JSON.stringify(t,null,2)+`
15
+ `,"utf-8")}function bt(e,t){let o=new Date().toISOString();return{version:1,templateVersion:e,installedAt:o,updatedAt:o,files:t}}async function re(e,t=e){let o=await Yn(e,{withFileTypes:!0}),n=[];for(let i of o){let a=Tt(e,i.name);i.isDirectory()?n.push(...await re(a,t)):i.isFile()&&n.push(zn(t,a).split(qn).join("/"))}return n}async function St(e){let t=await re(e),o={};for(let n of t)_e.has(n)||(o[n]=await ae(Tt(e,n)));return o}import{copyFile as Jn,mkdir as It,mkdtemp as Xn,readdir as _t,rm as Ct}from"fs/promises";import{tmpdir as Qn}from"os";import{dirname as Zn,join as Re}from"path";import{Readable as eo}from"stream";import*as Rt from"tar";var to="https://klaudius.dev/api/template";function no(e){return eo.fromWeb(e)}async function xe(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??to,o="0.19.3",n;try{n=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:o,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${T(c)}`)}if(!n.ok){let c="";try{let p=await n.json();c=p.reason?` (${p.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${n.status}${c}`)}if(!n.body)throw new Error("Template download succeeded but response had no body");let i=n.headers.get("x-klaudius-tier"),a=await Xn(Re(Qn(),"klaudius-template-")),l=0;try{try{await new Promise((m,r)=>{let w=Rt.extract({cwd:a,strict:!0});w.on("finish",m),w.on("error",r),no(n.body).on("error",r).pipe(w)})}catch(m){throw new Error(`Failed to extract template archive: ${m.message}`)}await It(e.destDir,{recursive:!0});let c=new Set(await _t(e.destDir)),p=await re(a);try{for(let m of p){let r=Re(e.destDir,m);await It(Zn(r),{recursive:!0}),await Jn(Re(a,m),r),l++}}catch(m){let r=await _t(e.destDir).catch(()=>[]);for(let w of r)c.has(w)||await Ct(Re(e.destDir,w),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${m.message}`)}}finally{await Ct(a,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:i}}import X from"picocolors";var s={info:e=>console.log(X.cyan("\u2139"),e),success:e=>console.log(X.green("\u2713"),e),warn:e=>console.log(X.yellow("\u26A0"),e),error:e=>console.error(X.red("\u2717"),e),step:e=>console.log(X.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
16
+ `+X.bold(X.cyan(e))),detail:e=>console.log(X.dim(" "+e))};var oo="https://registry.npmjs.org/klaudius/latest";async function so(e=1500){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{let n=await fetch(oo,{signal:t.signal,headers:{accept:"application/json"}});if(!n.ok)return null;let i=await n.json();return typeof i.version=="string"?i.version:null}catch{return null}finally{clearTimeout(o)}}function io(e,t){let o=a=>a.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),n=o(e),i=o(t);if(n.length<3||i.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(n[a])||Number.isNaN(i[a]))return!1;if(n[a]>i[a])return!0;if(n[a]<i[a])return!1}return!1}async function ve(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let o=await so();!o||!io(o,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${o}.`),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 ao}from"crypto";import{hostname as xt,userInfo as ro,platform as vt,arch as Ot}from"os";var lo="https://klaudius.dev",co="/api/licenses/validate",uo="0.19.3";async function $t(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(),n=(process.env.KLAUDIUS_API_URL??lo).replace(/\/$/,"")+co,i=ye(),a;try{a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:i,hostname:xt(),os:`${vt()}-${Ot()}`,cli_version:uo})})}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 ye(){let e=[xt(),ro().username,vt(),Ot()].join("|");return ao("sha256").update(e).digest("hex").slice(0,32)}import{readFile as po}from"fs/promises";import{join as fo}from"path";async function le(e){let t=e.serviceKey.replace(/\s+/g,"");try{let o=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return o.status===401||o.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${o.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(o){return{ok:!1,message:`Could not reach Supabase: ${T(o)}`}}}async function Nt(e){let t;try{t=await po(fo(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(n){return{ok:!1,message:`Could not read scripts/schema.sql: ${n.message}`}}let o=e.pat.replace(/\s+/g,"");try{let n=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(n.ok)return{ok:!0};let i=await n.text();return i.includes("already exists")||i.includes('relation "clients" already exists')||i.includes("duplicate")?(s.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${n.status}): ${i.slice(0,300)}`}}catch(n){return{ok:!1,message:`Schema apply failed: ${n.message}`}}}async function Oe(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 o=await t.json();return{ok:!0,username:o.user?.username??o.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${T(t)}`}}}var Lt="https://api.cloudflare.com/client/v4";function Mt(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function $e(e){let{token:t,accountId:o}=e,n={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let i=await fetch(`${Lt}/user/tokens/verify`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await i.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})`:""}. ${Mt(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${T(i)}`}}try{let i=await fetch(`${Lt}/accounts/${encodeURIComponent(o)}/pages/projects`,{headers:n});if(i.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${o} (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(i.status===404)return{ok:!1,message:`Account ${o} 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(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await i.json();return a.success===!1?{ok:!1,message:Mt(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${T(i)}`}}}var Dt="https://api.netlify.com/api/v1";async function Ne(e){let{token:t}=e,o={Authorization:`Bearer ${t}`};try{let n=await fetch(`${Dt}/user`,{headers:o});if(n.status===401||n.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${n.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(!n.ok)return{ok:!1,message:`Netlify API returned HTTP ${n.status} verifying the token. Try again or check netlifystatus.com.`}}catch(n){return{ok:!1,message:`Could not reach Netlify: ${T(n)}`}}try{let n=await fetch(`${Dt}/accounts`,{headers:o});if(!n.ok)return{ok:!1,message:`Netlify API returned HTTP ${n.status} listing your teams. Try again or check netlifystatus.com.`};let i=await n.json(),a=Array.isArray(i)?i:[];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(n){return{ok:!1,message:`Could not reach Netlify: ${T(n)}`}}}async function ce(e){let t=lt(e);if(t)return{ok:!1,message:t};let o=q(e),n=o.value,i=a=>{let l=[a],c=ct(e);return c&&l.push(c),o.repairs.length>0&&l.push(`Note: we corrected ${o.repairs.length} look-alike character(s) in this key before sending it (${o.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":n,"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??"",p=l.error?.status??"";return a.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."}:a.status===401||a.status===403?{ok:!1,message:i(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:i(`Google API returned HTTP ${a.status}${c?`: ${c}`:""}.`)}}catch(a){return{ok:!1,message:`Could not reach Google: ${T(a)}`}}}import mo from"nodemailer";import{ImapFlow as ho}from"imapflow";function Ut(e){let t=e;if(t?.authenticationFailed)return"auth";let o=typeof t?.code=="string"?t.code.toUpperCase():"";if(o==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(o))return"network";let n=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return n.includes("invalid credentials")||n.includes("authentication failed")||n.includes("auth failed")||n.includes("login failed")||n.includes("invalid login")?"auth":n.includes("etimedout")||n.includes("timeout")||n.includes("enotfound")||n.includes("getaddrinfo")||n.includes("econnrefused")||n.includes("econnreset")?"network":"other"}async function de(e){let t=mo.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(n){return{ok:!1,failedAt:"smtp",message:jt(n,"SMTP"),failureKind:Ut(n)}}finally{t.close()}let o=new ho({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 o.connect(),await o.logout()}catch(n){try{await o.logout()}catch{}return{ok:!1,failedAt:"imap",message:jt(n,"IMAP"),failureKind:Ut(n)}}return{ok:!0}}function jt(e,t){let o=e instanceof Error?e.message:String(e),n=o.toLowerCase();return n.includes("invalid credentials")||n.includes("authentication failed")||n.includes("auth failed")||n.includes("login failed")?`${t} rejected the credentials. Most common causes:
18
18
  \u2022 The app password is wrong, expired, or for a different provider.
19
19
  \u2022 The email address doesn't match the account that issued the password.
20
- \u2022 2FA is required but no app-specific password was generated.`:n.includes("etimedout")||n.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:n.includes("enotfound")||n.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${o}`}async function Dt(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`,o=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let n=await fetch(t,{headers:{Authorization:`Basic ${o}`}});if(n.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(!n.ok)return{ok:!1,message:`Twilio API returned HTTP ${n.status}. Try again or check status.twilio.com.`};let a=await n.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(n){return{ok:!1,message:`Could not reach Twilio: ${T(n)}`}}}import{spawn as so}from"child_process";async function Ut(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 o=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,n=await io(o);if(n.code===0)return{ok:!0};let a=n.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: ${n.stderr.trim()||`exit code ${n.code}`}`}}function io(e){return new Promise(t=>{let o=so("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),n="";o.stderr.on("data",a=>{n+=a.toString()}),o.on("close",a=>t({code:a??1,stderr:n})),o.on("error",a=>t({code:1,stderr:a.message}))})}import{spawn as Ye}from"child_process";function ao(){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,jt=2e3,ro=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Ht(e,t){let o=e+`
21
- `+t;return ro.some(n=>n.test(o))}function Kt(e){return new Promise(t=>setTimeout(t,e))}function lo(e,t,o){return new Promise(n=>{let a=o.shell?Ye([e,...t].join(" "),{cwd:o.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:o.env??process.env}):Ye(e,t,{cwd:o.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:o.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=>n({code:c??1,stdout:i,stderr:l})),a.on("error",c=>n({code:1,stdout:i,stderr:l+c.message}))})}async function We(e,t,o){let n={code:0,stdout:"",stderr:""};for(let a=0;a<=de;a++){if(n=await lo(e,t,{cwd:o.cwd,env:o.env,shell:o.shell}),n.code===0||!Ht(n.stderr,n.stdout))return n;a<de&&(s.detail(`${o.label} failed with a transient network error \u2014 retrying (${a+2}/${de+1})\u2026`),await Kt(jt))}return n}function co(e,t,o){return new Promise(n=>{let a=Ye(e,t,{cwd:o.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=>n({code:c??1,stdout:i,stderr:l})),a.on("error",c=>n({code:1,stdout:i,stderr:l+c.message}))})}var uo=[{pattern:/UNABLE_TO_VERIFY_LEAF_SIGNATURE|unable to verify the first certificate/i,hint:"TLS-handshake error \u2014 your machine appears to be intercepting HTTPS (antivirus, corporate proxy, or VPN re-signing traffic with its own root CA). We work around this with NODE_OPTIONS=--use-system-ca, which needs Node 22.15+. Run `node --version` to verify, upgrade if older, then re-run setup."},{pattern:/Microsoft Visual C\+\+ 14\.0 or greater is required/i,hint:"Python tried to compile a package from source and couldn't find the Microsoft C++ Build Tools. The latest Klaudius pins supabase<2.26 to skip the offending dependency entirely. Re-run with `npx klaudius@latest init` (pulls the latest) \u2014 that should bypass the source build."}];function po(e){let t=`${e.stderr??""}
22
- ${e.stdout??""}`;return uo.find(n=>n.pattern.test(t))?.hint}async function fo(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],o=["-m","pip","install","--quiet","--user","--prefer-binary"],a=(await he())?.command??["python3"],i=async c=>{let p={code:0,stdout:"",stderr:""};for(let m=0;m<=de;m++){if(p=await co(a[0],[...a.slice(1),...c],{cwd:e}),p.code===0||!Ht(p.stderr,p.stdout))return p;m<de&&(s.detail(`pip install hit a transient network error \u2014 retrying (${m+2}/${de+1})\u2026`),await Kt(jt))}return p},l=await i([...o,"--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([...o,...t])),l.code!==0&&(l.stderr.trim()&&process.stderr.write(l.stderr),l.stdout.trim()&&process.stdout.write(l.stdout)),l}async function Ne(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},o=ao(),n=process.platform==="win32",a=(m,r)=>{let w=po(r);w&&((t.hints??={})[m]=w)};s.step("Running npm install (Next.js, Playwright JS, etc.)...");let i=await We("npm",["install"],{cwd:e,label:"npm install",env:o,shell:n});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 fo(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 We("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:o,shell:n});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 We("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:o,shell:n});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&a("patchright",p),t}import{mkdir as mo,readFile as ho,writeFile as go}from"fs/promises";import{join as Ft}from"path";async function Le(e,t){let o=Ft(e,".claude");await mo(o,{recursive:!0});let n=Ft(o,"settings.json"),a={};try{let p=await ho(n,"utf-8"),m=JSON.parse(p);m&&typeof m=="object"&&!Array.isArray(m)&&(a=m)}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 go(n,JSON.stringify(c,null,2)+`
23
- `,"utf-8")}var Vt="0.19.1",C=5;function ne(e){return`npx klaudius@latest init ${Me(ue(e))}`}function ue(e){if(process.platform==="win32")return e;let t=yo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Eo(e){let t=[];try{let n=(await Wt(e,{withFileTypes:!0})).filter(a=>a.isDirectory()&&!a.name.startsWith(".")).slice(0,200);for(let a of n){let i=H(e,a.name);if(!await Bt(H(i,".env")))continue;let l=await Bt(H(i,".klaudius","manifest.json"));if(t.push({path:i,finished:l}),t.length>=3)break}}catch{}return t}async function Bt(e){try{return await Je(e),!0}catch{return!1}}function Me(e){return/\s/.test(e)?`"${e}"`:e}function te(e,t,o){s.blank(),s.error(`${t} validation failed ${C} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${o}`),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(H(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 zt(e){let t=e.target??".",o=wo(t)?t:ko(process.cwd(),t),n=_o(o);n&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${o}`),s.detail(`Reason: ${n}`),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"&&So()&&(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 ve("init",Vt);let a=await Po(o);if(a.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${d.bold(o)}.`),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(),o!==process.cwd()&&console.log(` ${d.cyan(`cd ${Me(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===".",h=await Eo(o);if(h.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(o)}`),s.blank();for(let f of h)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: ${o}`),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 To(e.license),l=y.spinner();l.start("Validating license");let c=await vt(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 ie();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(o)}`),process.exit(1));let m=J();m.ok||(s.error(m.message??"Node.js version check failed."),s.blank(),s.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${ne(o)}`),process.exit(1));let r,w=!1;if(a.kind==="partial")if(await bo(o)==="resume"){let h=await Gt(a.envPath,"utf-8"),f=Be(U(h));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 I())}else{let h=await Gt(a.envPath,"utf-8"),f=Be(U(h));r=await I(f??{})}else r=await I();r.licenseKey=i,await x(o,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 h=y.spinner();h.start("Validating Supabase credentials");let f=await re({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(f.ok){h.stop("Supabase credentials accepted");break}h.stop(f.message??"Supabase check failed",2),u>=C&&te(o,"Supabase",f.message??"Supabase check failed");let A=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 ${C})`),s.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await I(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
20
+ \u2022 2FA is required but no app-specific password was generated.`:n.includes("etimedout")||n.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:n.includes("enotfound")||n.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${o}`}async function Ht(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`,o=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let n=await fetch(t,{headers:{Authorization:`Basic ${o}`}});if(n.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(!n.ok)return{ok:!1,message:`Twilio API returned HTTP ${n.status}. Try again or check status.twilio.com.`};let i=await n.json();return i.status&&i.status!=="active"?{ok:!1,message:`Twilio account is in '${i.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:i.friendly_name}}catch(n){return{ok:!1,message:`Could not reach Twilio: ${T(n)}`}}}import{spawn as go}from"child_process";async function Kt(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 o=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,n=await yo(o);if(n.code===0)return{ok:!0};let i=n.stderr.toLowerCase();return i.includes("can't get application")||i.includes("isn't running")||i.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."}:i.includes("(-1728)")||i.includes("not found")||i.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.`}:i.includes("(-1719)")||i.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: ${n.stderr.trim()||`exit code ${n.code}`}`}}function yo(e){return new Promise(t=>{let o=go("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),n="";o.stderr.on("data",i=>{n+=i.toString()}),o.on("close",i=>t({code:i??1,stderr:n})),o.on("error",i=>t({code:1,stderr:i.message}))})}import{spawn as ze}from"child_process";function ko(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var ue=2,Ft=2e3,wo=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Gt(e,t){let o=e+`
21
+ `+t;return wo.some(n=>n.test(o))}function Vt(e){return new Promise(t=>setTimeout(t,e))}function Ao(e,t,o){return new Promise(n=>{let i=o.shell?ze([e,...t].join(" "),{cwd:o.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:o.env??process.env}):ze(e,t,{cwd:o.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:o.env??process.env}),a="",l="";i.stdout?.on("data",c=>{let p=c.toString();a+=p,process.stdout.write(p)}),i.stderr?.on("data",c=>{let p=c.toString();l+=p,process.stderr.write(p)}),i.on("close",c=>n({code:c??1,stdout:a,stderr:l})),i.on("error",c=>n({code:1,stdout:a,stderr:l+c.message}))})}async function Ye(e,t,o){let n={code:0,stdout:"",stderr:""};for(let i=0;i<=ue;i++){if(n=await Ao(e,t,{cwd:o.cwd,env:o.env,shell:o.shell}),n.code===0||!Gt(n.stderr,n.stdout))return n;i<ue&&(s.detail(`${o.label} failed with a transient network error \u2014 retrying (${i+2}/${ue+1})\u2026`),await Vt(Ft))}return n}function Eo(e,t,o){return new Promise(n=>{let i=ze(e,t,{cwd:o.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{l+=c.toString()}),i.on("close",c=>n({code:c??1,stdout:a,stderr:l})),i.on("error",c=>n({code:1,stdout:a,stderr:l+c.message}))})}var Po=[{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 bo(e){let t=`${e.stderr??""}
22
+ ${e.stdout??""}`;return Po.find(n=>n.pattern.test(t))?.hint}async function To(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],o=["-m","pip","install","--quiet","--user","--prefer-binary"],i=(await ge())?.command??["python3"],a=async c=>{let p={code:0,stdout:"",stderr:""};for(let m=0;m<=ue;m++){if(p=await Eo(i[0],[...i.slice(1),...c],{cwd:e}),p.code===0||!Gt(p.stderr,p.stdout))return p;m<ue&&(s.detail(`pip install hit a transient network error \u2014 retrying (${m+2}/${ue+1})\u2026`),await Vt(Ft))}return p},l=await a([...o,"--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 a([...o,...t])),l.code!==0&&(l.stderr.trim()&&process.stderr.write(l.stderr),l.stdout.trim()&&process.stdout.write(l.stdout)),l}async function Le(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},o=ko(),n=process.platform==="win32",i=(m,r)=>{let w=bo(r);w&&((t.hints??={})[m]=w)};s.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await Ye("npm",["install"],{cwd:e,label:"npm install",env:o,shell:n});t.npm=a.code===0?"ok":"failed",a.code!==0&&i("npm",a),s.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await To(e);t.pip=l.code===0?"ok":"failed",l.code!==0&&i("pip",l),s.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Ye("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:o,shell:n});t.playwright=c.code===0?"ok":"failed",c.code!==0&&i("playwright",c),s.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await Ye("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:o,shell:n});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&i("patchright",p),t}import{mkdir as So,readFile as Io,writeFile as _o}from"fs/promises";import{join as Bt}from"path";async function Me(e,t){let o=Bt(e,".claude");await So(o,{recursive:!0});let n=Bt(o,"settings.json"),i={};try{let p=await Io(n,"utf-8"),m=JSON.parse(p);m&&typeof m=="object"&&!Array.isArray(m)&&(i=m)}catch{}let a=i.enabledMcpjsonServers,l=Array.isArray(a)?a.filter(p=>typeof p=="string"):[];l.includes(t)||l.push(t);let c={...i,enabledMcpjsonServers:l};await _o(n,JSON.stringify(c,null,2)+`
23
+ `,"utf-8")}var Yt="0.19.3",C=5;function ne(e){return`npx klaudius@latest init ${De(pe(e))}`}function pe(e){if(process.platform==="win32")return e;let t=Co();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Oo(e){let t=[];try{let n=(await qt(e,{withFileTypes:!0})).filter(i=>i.isDirectory()&&!i.name.startsWith(".")).slice(0,200);for(let i of n){let a=H(e,i.name);if(!await zt(H(a,".env")))continue;let l=await zt(H(a,".klaudius","manifest.json"));if(t.push({path:a,finished:l}),t.length>=3)break}}catch{}return t}async function zt(e){try{return await Xe(e),!0}catch{return!1}}function De(e){return/\s/.test(e)?`"${e}"`:e}function te(e,t,o){s.blank(),s.error(`${t} validation failed ${C} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${o}`),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 ${pe(H(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 Xt(e){let t=e.target??".",o=xo(t)?t:Ro(process.cwd(),t),n=Mo(o);n&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${o}`),s.detail(`Reason: ${n}`),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"&&Do()&&(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 ve("init",Yt);let i=await $o(o);if(i.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${d.bold(o)}.`),s.detail("(Your .env and project files are in place.)"),s.blank(),i.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(),o!==process.cwd()&&console.log(` ${d.cyan(`cd ${De(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(i.kind==="occupied"){let u=t===".",h=await Oo(o);if(h.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: ${pe(o)}`),s.blank();for(let f of h)s.detail(f.finished?`Found a finished project at ${pe(f.path)}. To work in it:`:`Found an unfinished setup at ${pe(f.path)}. To pick up where it left off:`),s.blank(),f.finished?(console.log(` ${d.cyan(`cd ${pe(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: ${o}`),s.detail(`Contains: ${i.entries.slice(0,5).join(", ")}${i.entries.length>5?`, \u2026 (+${i.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 a=await Lo(e.license),l=y.spinner();l.start("Validating license");let c=await $t(a);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 ie();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(o)}`),process.exit(1));let m=J();m.ok||(s.error(m.message??"Node.js version check failed."),s.blank(),s.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${ne(o)}`),process.exit(1));let r,w=!1;if(i.kind==="partial")if(await No(o)==="resume"){let h=await Wt(i.envPath,"utf-8"),f=We(D(h));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 h=await Wt(i.envPath,"utf-8"),f=We(D(h));r=await _(f??{})}else r=await _();r.licenseKey=a,await v(o,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 h=y.spinner();h.start("Validating Supabase credentials");let f=await le({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(f.ok){h.stop("Supabase credentials accepted");break}h.stop(f.message??"Supabase check failed",2),u>=C&&te(o,"Supabase",f.message??"Supabase check failed");let A=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 ${C})`),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:
24
24
  ${A}
25
25
 
26
26
  Re-enter the URL, secret key, or PAT below. Press Enter on any
27
- field to keep what's already there.`}),await x(o,r)}if(s.blank(),r.deployProvider==="cloudflare")for(let u=1;;u++){let h=y.spinner();h.start("Validating Cloudflare token + account");let f=await Oe({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),u>=C&&te(o,"Cloudflare",f.message??"Cloudflare check failed");let A=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 ${C})`),s.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await I(r,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
27
+ field to keep what's already there.`}),await v(o,r)}if(s.blank(),r.deployProvider==="cloudflare")for(let u=1;;u++){let h=y.spinner();h.start("Validating Cloudflare token + account");let f=await $e({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),u>=C&&te(o,"Cloudflare",f.message??"Cloudflare check failed");let A=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 ${C})`),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:
28
28
  ${A}
29
29
 
30
30
  Re-enter the API token or Account ID below. The token needs the
31
31
  "Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
32
- the current value.`}),await x(o,r)}else if(r.deployProvider==="netlify")for(let u=1;;u++){let h=y.spinner();h.start("Validating Netlify token");let f=await $e({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),u>=C&&te(o,"Netlify",f.message??"Netlify check failed");let A=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 ${C})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await I(r,{onlySection:"netlify",banner:`Netlify rejected the token:
32
+ the current value.`}),await v(o,r)}else if(r.deployProvider==="netlify")for(let u=1;;u++){let h=y.spinner();h.start("Validating Netlify token");let f=await Ne({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),u>=C&&te(o,"Netlify",f.message??"Netlify check failed");let A=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 ${C})`),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:
33
33
  ${A}
34
34
 
35
35
  Generate a new token at
36
36
  https://app.netlify.com/user/applications#personal-access-tokens
37
- and paste it below. Press Enter to keep the current value.`}),await x(o,r)}else for(let u=1;;u++){let h=y.spinner();h.start("Validating Vercel token");let f=await xe(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),u>=C&&te(o,"Vercel",f.message??"Vercel check failed");let A=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 ${C})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await I(r,{onlySection:"vercel",banner:`Vercel rejected the token:
37
+ and paste it below. Press Enter to keep the current value.`}),await v(o,r)}else for(let u=1;;u++){let h=y.spinner();h.start("Validating Vercel token");let f=await Oe(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),u>=C&&te(o,"Vercel",f.message??"Vercel check failed");let A=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 ${C})`),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:
38
38
  ${A}
39
39
 
40
40
  Generate a new token at https://vercel.com/account/tokens and
41
- paste it below. Press Enter to keep the current value.`}),await x(o,r)}s.blank();for(let u=1;;u++){let h=q(r.googlePlacesApiKey??""),f=y.spinner();f.start("Validating Google Places API key");let A=await le(r.googlePlacesApiKey??"");if(A.ok){if(f.stop("Google Places API key accepted"),h.changed){if(h.repairs.length>0){s.blank(),s.warn("Corrected look-alike characters in your Google Places API key:");for(let S of h.repairs)s.detail(` ${S}`);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=h.value,await x(o,r)}break}f.stop(A.message??"Google Places check failed",2),u>=C&&te(o,"Google Places",A.message??"Google Places check failed");let K=A.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 ${C})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await I(r,{onlySection:"google-places",banner:`Google rejected the key:
41
+ paste it below. Press Enter to keep the current value.`}),await v(o,r)}s.blank();for(let u=1;;u++){let h=q(r.googlePlacesApiKey??""),f=y.spinner();f.start("Validating Google Places API key");let A=await ce(r.googlePlacesApiKey??"");if(A.ok){if(f.stop("Google Places API key accepted"),h.changed){if(h.repairs.length>0){s.blank(),s.warn("Corrected look-alike characters in your Google Places API key:");for(let I of h.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=h.value,await v(o,r)}break}f.stop(A.message??"Google Places check failed",2),u>=C&&te(o,"Google Places",A.message??"Google Places check failed");let K=A.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 ${C})`),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:
42
42
  ${K}
43
43
 
44
44
  Generate (or fix) the key at https://console.cloud.google.com
45
- and paste it below. Press Enter to keep the current value.`}),await x(o,r)}let g=!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,h=!1,f;for(;!h;){u++;let A=y.spinner();A.start("Validating email credentials (SMTP + IMAP)");let K=await ce({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort});if(K.ok){A.stop("Email credentials accepted (SMTP + IMAP)");break}A.stop(K.message??"Email check failed",2);let S=r.emailProvider,j=S&&S!=="custom"?z[S]:void 0,ke=`${S}\0${r.emailAddress}\0${r.emailPassword}`;if(j&&K.failureKind!=="network"&&f!==ke){f=ke;let Z=we(S,r.emailSmtpHost,r.emailImapHost),ee,nt=0;if(Z.length>0){s.blank(),s.warn(`That server rejected the login. ${j.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let D of Z){let He=y.spinner();He.start(`Trying ${D.label} (${D.smtpHost})`);let Ke=await ce({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:D.smtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:D.imapHost,emailImapPort:r.emailImapPort});if(Ke.ok){He.stop(`${D.label}: your login works here (${D.smtpHost})`),ee=D;break}Ke.failureKind!=="network"&&nt++,He.stop(Ke.failureKind==="network"?`${D.label}: unreachable`:`${D.label}: rejected too`,2)}}if(ee){s.blank(),s.success("Found it \u2014 your password was right all along; the server was the only problem.");let D=await y.confirm({message:`Use the ${ee.label} servers (${ee.smtpHost} / ${ee.imapHost})?`,initialValue:!0});if(y.isCancel(D)&&(y.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
45
+ and paste it below. Press Enter to keep the current value.`}),await v(o,r)}let g=!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,h=!1,f;for(;!h;){u++;let A=y.spinner();A.start("Validating email credentials (SMTP + IMAP)");let K=await de({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort});if(K.ok){A.stop("Email credentials accepted (SMTP + IMAP)");break}A.stop(K.message??"Email check failed",2);let I=r.emailProvider,j=I&&I!=="custom"?z[I]:void 0,we=`${I}\0${r.emailAddress}\0${r.emailPassword}`;if(j&&K.failureKind!=="network"&&f!==we){f=we;let Z=Ae(I,r.emailSmtpHost,r.emailImapHost),ee,ot=0;if(Z.length>0){s.blank(),s.warn(`That server rejected the login. ${j.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let M of Z){let Ke=y.spinner();Ke.start(`Trying ${M.label} (${M.smtpHost})`);let Fe=await de({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:M.smtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:M.imapHost,emailImapPort:r.emailImapPort});if(Fe.ok){Ke.stop(`${M.label}: your login works here (${M.smtpHost})`),ee=M;break}Fe.failureKind!=="network"&&ot++,Ke.stop(Fe.failureKind==="network"?`${M.label}: unreachable`:`${M.label}: rejected too`,2)}}if(ee){s.blank(),s.success("Found it \u2014 your password was right all along; the server was the only problem.");let M=await y.confirm({message:`Use the ${ee.label} servers (${ee.smtpHost} / ${ee.imapHost})?`,initialValue:!0});if(y.isCancel(M)&&(y.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
46
46
 
47
47
  ${ne(o)}
48
- `),process.exit(0)),D){r.emailSmtpHost=ee.smtpHost,r.emailImapHost=ee.imapHost,await x(o,r);continue}}else Z.length>0&&(s.blank(),nt===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."):j.noAltWorkedHint&&s.warn(j.noAltWorkedHint))}let pn=K.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 je=await y.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(y.isCancel(je)&&(y.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
48
+ `),process.exit(0)),M){r.emailSmtpHost=ee.smtpHost,r.emailImapHost=ee.imapHost,await v(o,r);continue}}else Z.length>0&&(s.blank(),ot===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."):j.noAltWorkedHint&&s.warn(j.noAltWorkedHint))}let mn=K.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 He=await y.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(y.isCancel(He)&&(y.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
49
49
 
50
50
  ${ne(o)}
51
- `),process.exit(0)),je==="skip"){r.outreachChannels=(r.outreachChannels??[]).filter(Z=>Z!=="email"),r.outreachPriority=(r.outreachPriority??[]).filter(Z=>Z!=="email"),r.outreachChannels.length===0&&(r.outreachEnabled=!1),await x(o,r),g=!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."),h=!0;break}je==="edit"&&(s.blank(),r=await I(r,{onlySection:"email",banner:`${K.failedAt==="imap"?"IMAP":"SMTP"} check failed:
52
- ${pn}
51
+ `),process.exit(0)),He==="skip"){r.outreachChannels=(r.outreachChannels??[]).filter(Z=>Z!=="email"),r.outreachPriority=(r.outreachPriority??[]).filter(Z=>Z!=="email"),r.outreachChannels.length===0&&(r.outreachEnabled=!1),await v(o,r),g=!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."),h=!0;break}He==="edit"&&(s.blank(),r=await _(r,{onlySection:"email",banner:`${K.failedAt==="imap"?"IMAP":"SMTP"} check failed:
52
+ ${mn}
53
53
 
54
54
  Re-enter the email address, app password, or server details below.
55
55
  Press Enter on any field to keep its current value.
56
56
 
57
57
  Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
58
- at the "Server settings" question.`}),await x(o,r))}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="twilio"&&r.twilioAccountSid&&r.twilioAuthToken){s.blank();for(let u=1;;u++){let h=y.spinner();h.start("Validating Twilio credentials");let f=await Dt({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),u>=C&&te(o,"Twilio",f.message??"Twilio check failed");let A=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 ${C})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await I(r,{onlySection:"sms",banner:`Twilio rejected the credentials:
58
+ at the "Server settings" question.`}),await v(o,r))}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="twilio"&&r.twilioAccountSid&&r.twilioAuthToken){s.blank();for(let u=1;;u++){let h=y.spinner();h.start("Validating Twilio credentials");let f=await Ht({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),u>=C&&te(o,"Twilio",f.message??"Twilio check failed");let A=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 ${C})`),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:
59
59
  ${A}
60
60
 
61
61
  Re-enter the Account SID or Auth Token below.
62
- Press Enter on any field to keep its current value.`}),await x(o,r)}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="imessage"&&r.testPhone){s.blank();for(let u=1;;u++){let h=y.spinner();h.start("Validating iMessage setup (sending a test ping)");let f=await Ut({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),u>=C&&te(o,"iMessage",f.message??"iMessage check failed");let A=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 ${C})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await I(r,{onlySection:"sms",banner:`iMessage check failed:
62
+ Press Enter on any field to keep its current value.`}),await v(o,r)}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="imessage"&&r.testPhone){s.blank();for(let u=1;;u++){let h=y.spinner();h.start("Validating iMessage setup (sending a test ping)");let f=await Kt({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),u>=C&&te(o,"iMessage",f.message??"iMessage check failed");let A=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 ${C})`),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:
63
63
  ${A}
64
64
 
65
65
  Either fix the underlying issue (sign in to Messages.app, configure
66
66
  Text Message Forwarding) and press Enter through, or change SMS
67
- provider to Twilio.`}),await x(o,r)}}if(r.telegramBotToken&&r.telegramChatId){s.blank();let u=0,h=!1;for(;!h;){u++;let f=y.spinner();f.start("Validating Telegram bot + chat (sending a test ping)");let A=await at({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 K=A.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 S=await y.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(y.isCancel(S)&&(y.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
67
+ provider to Twilio.`}),await v(o,r)}}if(r.telegramBotToken&&r.telegramChatId){s.blank();let u=0,h=!1;for(;!h;){u++;let f=y.spinner();f.start("Validating Telegram bot + chat (sending a test ping)");let A=await rt({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 K=A.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 y.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(y.isCancel(I)&&(y.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
68
68
 
69
69
  ${ne(o)}
70
- `),process.exit(0)),S==="skip"){r.telegramBotToken=void 0,r.telegramChatId=void 0,await x(o,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`."),h=!0;break}if(S==="edit"&&(s.blank(),r=await I(r,{onlySection:"telegram",banner:`Telegram check failed:
70
+ `),process.exit(0)),I==="skip"){r.telegramBotToken=void 0,r.telegramChatId=void 0,await v(o,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`."),h=!0;break}if(I==="edit"&&(s.blank(),r=await _(r,{onlySection:"telegram",banner:`Telegram check failed:
71
71
  ${K}
72
72
 
73
73
  Re-enter the bot token or chat_id below.
74
- Press Enter on any field to keep its current value.`}),await x(o,r),!r.telegramBotToken||!r.telegramChatId)){s.success("Skipped Telegram. Setup will continue."),h=!0;break}}}s.blank();let E=y.spinner();E.start("Downloading Klaudius template");let v;try{v=(await Re({licenseKey:i,machineId:ge(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:r.aiAgent,destDir:o})).filesExtracted,E.stop(`Downloaded ${v} files into ${d.bold(o)}`)}catch(u){E.stop(u.message,2);let h=r.aiAgent==="codex"?".codex/config.toml":".mcp.json";s.detail(`Your .env / ${h} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await qe(H(o,"clients"),{recursive:!0});let oe=await Pt(o);await Se(o,At(Vt,oe)),s.success("Wrote .klaudius/manifest.json");let M=!1,Y="";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=y.spinner();u.start("Applying schema to Supabase");let h=await xt({projectRoot:o,pat:r.supabasePat,projectRef:r.supabaseProjectRef});h.ok?u.stop("Schema applied (or already present)"):(u.stop(h.message??"Schema apply failed",2),M=!0,Y=`https://supabase.com/dashboard/project/${r.supabaseProjectRef}/sql/new`)}let b=[],P={};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 Ne(o);s.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&b.push("npm"),u.pip==="failed"&&b.push("pip"),u.playwright==="failed"&&b.push("playwright"),u.patchright==="failed"&&b.push("patchright"),P=u.hints??{}}let $=r.outreachEnabled&&r.outreachPriority?.includes("whatsapp")&&(r.whatsappAccounts?.length??0)>0,k=!e.skipInstall&&!b.includes("npm");if($&&k){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
74
+ Press Enter on any field to keep its current value.`}),await v(o,r),!r.telegramBotToken||!r.telegramChatId)){s.success("Skipped Telegram. Setup will continue."),h=!0;break}}}s.blank();let E=y.spinner();E.start("Downloading Klaudius template");let x;try{x=(await xe({licenseKey:a,machineId:ye(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:r.aiAgent,destDir:o})).filesExtracted,E.stop(`Downloaded ${x} files into ${d.bold(o)}`)}catch(u){E.stop(u.message,2);let h=r.aiAgent==="codex"?".codex/config.toml":".mcp.json";s.detail(`Your .env / ${h} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await Je(H(o,"clients"),{recursive:!0});let oe=await St(o);await Ce(o,bt(Yt,oe)),s.success("Wrote .klaudius/manifest.json");let L=!1,Y="";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=y.spinner();u.start("Applying schema to Supabase");let h=await Nt({projectRoot:o,pat:r.supabasePat,projectRef:r.supabaseProjectRef});h.ok?u.stop("Schema applied (or already present)"):(u.stop(h.message??"Schema apply failed",2),L=!0,Y=`https://supabase.com/dashboard/project/${r.supabaseProjectRef}/sql/new`)}let b=[],P={};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 Le(o);s.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&b.push("npm"),u.pip==="failed"&&b.push("pip"),u.playwright==="failed"&&b.push("playwright"),u.patchright==="failed"&&b.push("patchright"),P=u.hints??{}}let $=r.outreachEnabled&&r.outreachPriority?.includes("whatsapp")&&(r.whatsappAccounts?.length??0)>0,k=!e.skipInstall&&!b.includes("npm");if($&&k){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
75
75
  phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
76
- 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 h=Yt(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:o,stdio:"inherit"});h.status===0?s.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${h.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${u}`))),s.blank()}}else if($&&!k){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 G=[...b,...M?["schema"]:[]];if(G.length>0){y.outro(d.yellow(d.bold(`Setup paused \u2014 ${G.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),s.blank();for(let[j,ke]of Object.entries(P))console.log(d.yellow(`Likely cause of ${j} failure:`)),console.log(d.dim(` ${ke}`)),s.blank();let u=o!==process.cwd()&&e.target?` ${d.cyan(`cd ${Me(e.target)}`)}
77
- `:"",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";b.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(h)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${b.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: \`${A}\`)`)),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()),M&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(Y)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),b.includes("pip")&&!P.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 ${Io()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),s.blank());let S=["npm","playwright","patchright"].filter(j=>b.includes(j)&&!P[j]);if(S.length>0){let j=S.length===1?"keeps":"keep";console.log(d.dim(`If ${S.join(" / ")} ${j} 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()}g&&(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(Co(r,o,e.target),g){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 x(e,t){await qe(e,{recursive:!0}),await ze(H(e,".env"),Pe(t),"utf-8"),t.aiAgent==="codex"?(await qe(H(e,".codex"),{recursive:!0}),await ze(H(e,".codex","config.toml"),Te(t),"utf-8")):(await ze(H(e,".mcp.json"),be(t),"utf-8"),await Le(e,"supabase"))}async function Po(e){try{(await Je(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Wt(e),o=t.filter(c=>!c.startsWith(".DS_Store"));if(o.length===0)return{kind:"fresh"};let n=new Set([".env",".mcp.json",".claude",".codex"]),a=o.every(c=>n.has(c)),i=o.includes(".env"),l=t.includes(".klaudius");if(a&&i&&!l)return{kind:"partial",envPath:H(e,".env")};if(l&&i){let c=!0;try{c=!(await Je(H(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:o}}async function bo(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 y.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 y.isCancel(t)&&(y.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function To(e){if(e&&e.trim().length>0)return e;y.intro("Klaudius");let t=await y.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:o=>o.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return y.isCancel(t)&&(y.cancel("Setup cancelled. No files written."),process.exit(0)),t}function _o(e){let t=Ao(e);if(process.platform==="win32"){let o=t.toLowerCase();if(o.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(o.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(o.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(o.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let o=["/System/","/usr/","/bin/","/sbin/"];for(let n of o)if(t.startsWith(n))return`Inside ${n.slice(0,-1)} (system-managed directory).`}}function So(){if(process.platform!=="win32")return!1;try{return Yt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Io(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Co(e,t,o){let n=e.aiAgent==="codex"?"codex":"claude",a=e.aiAgent==="codex"?"Codex":"Claude Code";if(y.outro(d.green(d.bold("Project ready."))),console.log(d.bold("Next steps:")),s.blank(),t!==process.cwd()&&o){let i=`cd ${Me(o)}`;console.log(` ${d.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${d.dim("# go into your project folder")}`)}console.log(` ${d.cyan(n)}${" ".repeat(Math.max(1,27-n.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 Ro,readFile as vo}from"fs/promises";import{join as Xe,resolve as xo}from"path";import N from"picocolors";async function Jt(e){let t=e.target?xo(process.cwd(),e.target):process.cwd(),o=await qt(Xe(t,".env")),n=await qt(Xe(t,"package.json"));(!o||!n)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),o||s.detail("Missing: .env"),n||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 vo(Xe(t,".env"),"utf-8")).AI_AGENT==="codex"&&(a="codex")}catch{}s.heading("Installing dependencies");let i=await Ne(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",m=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: \`${m}\`)`)),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 qt(e){try{return await Ro(e),!0}catch{return!1}}import{readFile as Oo,writeFile as Qe,access as $o}from"fs/promises";import{join as pe}from"path";import*as De from"@clack/prompts";import V from"picocolors";import{mkdir as No}from"fs/promises";async function Xt(e){let t=e.projectRoot??process.cwd(),o=pe(t,".env"),n=pe(t,".mcp.json"),a=pe(t,".codex","config.toml"),i=await Ze(pe(t,".klaudius","manifest.json")),l=await Ze(o);!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=J();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 E=await Oo(o,"utf-8");p=U(E)}catch{s.warn("No .env found. Starting from an empty configuration.")}let m=gt(p);De.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let r=await I(m),w=m.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(` ${V.cyan("npx klaudius@latest init <new-folder>")} ${V.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 E=await re({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});E.ok||(s.error(E.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let g=q(r.googlePlacesApiKey??"");if(g.changed&&r.googlePlacesApiKey){s.heading("Checking your Google Places API key");let E=await le(r.googlePlacesApiKey);if(E.ok){if(g.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let v of g.repairs)s.detail(` ${v}`);s.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=g.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(E.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 Qe(o,Pe(r),"utf-8"),s.success("Updated .env"),r.aiAgent==="codex"?(await No(pe(t,".codex"),{recursive:!0}),await Qe(a,Te(r),"utf-8"),s.success("Updated .codex/config.toml")):(await Qe(n,be(r),"utf-8"),s.success("Updated .mcp.json"),await Le(t,"supabase")),s.blank(),De.outro(V.green("Configuration updated.")),await Lo(t,i)}async function Lo(e,t){let o=await Ze(pe(e,"node_modules"));s.blank(),t?o||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${V.cyan("npx klaudius@latest install")} ${V.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${V.cyan("npx klaudius@latest doctor")} ${V.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(` ${V.cyan("npx klaudius@latest init")} ${V.dim("# pick Resume when prompted")}`),s.blank())}async function Ze(e){try{return await $o(e),!0}catch{return!1}}import{copyFile as Qt,mkdir as Zt,readdir as Mo,readFile as Do,rm as ye,writeFile as en,access as tn}from"fs/promises";import{dirname as nn,join as L,relative as Uo}from"path";import{tmpdir as jo}from"os";import*as fe from"@clack/prompts";import et from"picocolors";var Ue="0.19.1";async function on(e){let t=e.projectRoot??process.cwd(),o=await wt(t);o||(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 k of _e)delete o.files[k];let n,a=L(t,".env"),i,l;try{i=await Do(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)}n=l.KLAUDIUS_LICENSE_KEY??"",n||(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=ht(i,l,mt);c!==null&&(await en(a,c,"utf-8"),s.detail("Backfilled new env keys")),await ve("update",Ue),fe.intro(`Update from ${o.templateVersion} \u2192 ${Ue}`);let m=l.AI_AGENT==="codex"?"codex":"claude-code",r=L(jo(),`klaudius-update-${process.pid}-${Date.now()}`),w;try{s.heading("Downloading the latest Klaudius template");let k=await Re({licenseKey:n,machineId:ge(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:m,destDir:r});s.success(`Fetched ${k.filesExtracted} canonical files`),w=r}catch(k){s.error(k.message),s.detail("Update aborted. Your project is unchanged."),await ye(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let g=await Ho(w,t,o),E=g.filter(k=>k.state==="new"),v=g.filter(k=>k.state==="clean-update"),oe=g.filter(k=>k.state==="user-only"),M=g.filter(k=>k.state==="conflict"),Y=g.filter(k=>k.state==="no-change"),b=g.filter(k=>k.state==="removed-clean"),P=g.filter(k=>k.state==="removed-modified"),$=[...M,...P];if(s.blank(),s.heading("Change summary"),s.detail(`${B(Y.length,"file")} unchanged`),s.detail(`${B(E.length,"new file")}`),s.detail(`${B(v.length,"file")} updated cleanly (no local edits)`),s.detail(`${B(oe.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${B(b.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${B(M.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${B(P.length,"file")} removed upstream but edited locally (need your decision)`),E.length===0&&v.length===0&&b.length===0&&$.length===0){s.blank(),fe.outro(et.green("Already up to date.")),await ye(r,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let k of[...E,...v]){let G=L(w,k.path),u=L(t,k.path);await Zt(nn(u),{recursive:!0}),await Qt(G,u),o.files[k.path]=k.canonicalHash}E.length+v.length>0&&s.success(`Wrote ${B(E.length+v.length,"file")}`);for(let k of b){let G=L(t,k.path);await ye(G,{force:!0}),delete o.files[k.path]}if(b.length>0&&s.success(`Deleted ${B(b.length,"file")} removed upstream`),$.length>0){s.blank(),s.heading(`${$.length} conflict(s) need resolution`);let k=L(t,".klaudius","incoming");try{await ye(k,{recursive:!0,force:!0})}catch{}for(let G of M){let u=L(w,G.path),h=L(k,G.path);await Zt(nn(h),{recursive:!0}),await Qt(u,h)}await en(L(t,".klaudius","conflicts.md"),Ko($,o.templateVersion,Ue),"utf-8"),M.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}if(o.updatedAt=new Date().toISOString(),$.length===0&&(o.templateVersion=Ue),await Se(t,o),s.blank(),$.length===0)fe.outro(et.green("Update complete."));else{let k=m==="codex"?"Codex":"Claude Code";fe.outro(et.yellow(`${$.length} conflict(s) staged. Open ${k} in this project and ask:
78
- "Run /resolve-conflicts"`))}await ye(r,{recursive:!0,force:!0}).catch(()=>{})}async function Ho(e,t,o){let n=await sn(e),a=new Set(n),i=[];for(let l of n){let c=await ae(L(e,l)),p=o.files[l],m=L(t,l),r;try{await tn(m),r=await ae(m)}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(o.files)){if(a.has(l))continue;let c=o.files[l],p=L(t,l),m;try{await tn(p),m=await ae(p)}catch{delete o.files[l];continue}m===c?i.push({path:l,state:"removed-clean",localHash:m,manifestHash:c}):i.push({path:l,state:"removed-modified",localHash:m,manifestHash:c})}return i}function B(e,t){return`${e} ${t}${e===1?"":"s"}`}async function sn(e,t=e){let o=await Mo(e,{withFileTypes:!0}),n=[];for(let a of o){let i=L(e,a.name);a.isDirectory()?n.push(...await sn(i,t)):a.isFile()&&n.push(Uo(t,i))}return n}function Ko(e,t,o){let n=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 **${o}**.`),i.push("");let l=[];n>0&&l.push(`${n} file${n===1?"":"s"} ha${n===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(`
79
- `)}import{access as Fo,readFile as an,stat as Go}from"fs/promises";import{join as F}from"path";import R from"picocolors";import{spawn as rn}from"child_process";async function ln(e){let t=e.projectRoot??process.cwd(),o=[];console.log(R.bold(`Klaudius doctor \u2014 checking your project\u2026
80
- `)),o.push(await Vo()),o.push(await Bo());let n=F(t,".env"),a=F(t,".klaudius","manifest.json"),i=F(t,".mcp.json"),l=F(t,".codex","config.toml"),c=await Q(n),p=await Q(a),m="claude-code";if(c)try{U(await an(n,"utf-8")).AI_AGENT==="codex"&&(m="codex")}catch{}if(m==="claude-code"){let g=await Q(F(t,"AGENTS.md")),E=!await Q(F(t,".claude"));g&&E&&(m="codex")}if(o.push({name:".env present",status:c?"ok":"fail",detail:c?n:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."}),o.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`."}),m==="codex"){let g=await Q(l);o.push({name:".codex/config.toml present",status:g?"ok":"warn",detail:g?l:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let g=await Q(i);o.push({name:".mcp.json present",status:g?"ok":"warn",detail:g?i:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(o.push(await Qo(m)),o.push(await Wo(t)),o.push(await Yo(t)),o.push(await zo()),!c)o.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)o.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let g=await an(n,"utf-8"),E=U(g);await qo(E,o)}console.log();for(let g of o){let E=g.status==="ok"?R.green("\u2713"):g.status==="warn"?R.yellow("\u26A0"):g.status==="skip"?R.dim("\xB7"):R.red("\u2717");console.log(` ${E} ${g.name}${g.detail?R.dim(` \u2014 ${g.detail}`):""}`),g.nextAction&&console.log(` ${R.dim("\u2192")} ${R.cyan(g.nextAction)}`)}let r=o.filter(g=>g.status==="fail").length,w=o.filter(g=>g.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 Fo(e),!0}catch{return!1}}async function Vo(){let e=await ie();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 Bo(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let o=parseInt(t[1],10),n=parseInt(t[2],10);return o<22||o===22&&n<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 Wo(e){let t=F(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 Go(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 Yo(e){let t=process.platform==="darwin"?F(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?F(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):F(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 zo(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
76
+ 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 h=Jt(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:o,stdio:"inherit"});h.status===0?s.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${h.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${u}`))),s.blank()}}else if($&&!k){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 G=[...b,...L?["schema"]:[]];if(G.length>0){y.outro(d.yellow(d.bold(`Setup paused \u2014 ${G.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),s.blank();for(let[j,we]of Object.entries(P))console.log(d.yellow(`Likely cause of ${j} failure:`)),console.log(d.dim(` ${we}`)),s.blank();let u=o!==process.cwd()&&e.target?` ${d.cyan(`cd ${De(e.target)}`)}
77
+ `:"",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";b.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(h)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${b.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: \`${A}\`)`)),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()),L&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(Y)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),b.includes("pip")&&!P.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 ${Uo()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),s.blank());let I=["npm","playwright","patchright"].filter(j=>b.includes(j)&&!P[j]);if(I.length>0){let j=I.length===1?"keeps":"keep";console.log(d.dim(`If ${I.join(" / ")} ${j} 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()}g&&(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(jo(r,o,e.target),g){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 v(e,t){await Je(e,{recursive:!0}),await qe(H(e,".env"),Te(t),"utf-8"),t.aiAgent==="codex"?(await Je(H(e,".codex"),{recursive:!0}),await qe(H(e,".codex","config.toml"),Ie(t),"utf-8")):(await qe(H(e,".mcp.json"),Se(t),"utf-8"),await Me(e,"supabase"))}async function $o(e){try{(await Xe(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await qt(e),o=t.filter(c=>!c.startsWith(".DS_Store"));if(o.length===0)return{kind:"fresh"};let n=new Set([".env",".mcp.json",".claude",".codex"]),i=o.every(c=>n.has(c)),a=o.includes(".env"),l=t.includes(".klaudius");if(i&&a&&!l)return{kind:"partial",envPath:H(e,".env")};if(l&&a){let c=!0;try{c=!(await Xe(H(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:o}}async function No(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 y.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 y.isCancel(t)&&(y.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Lo(e){if(e&&e.trim().length>0)return e;y.intro("Klaudius");let t=await y.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:o=>o.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return y.isCancel(t)&&(y.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Mo(e){let t=vo(e);if(process.platform==="win32"){let o=t.toLowerCase();if(o.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(o.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(o.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(o.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let o=["/System/","/usr/","/bin/","/sbin/"];for(let n of o)if(t.startsWith(n))return`Inside ${n.slice(0,-1)} (system-managed directory).`}}function Do(){if(process.platform!=="win32")return!1;try{return Jt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Uo(){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 jo(e,t,o){let n=e.aiAgent==="codex"?"codex":"claude",i=e.aiAgent==="codex"?"Codex":"Claude Code";if(y.outro(d.green(d.bold("Project ready."))),console.log(d.bold("Next steps:")),s.blank(),t!==process.cwd()&&o){let a=`cd ${De(o)}`;console.log(` ${d.cyan(a)}${" ".repeat(Math.max(1,27-a.length))}${d.dim("# go into your project folder")}`)}console.log(` ${d.cyan(n)}${" ".repeat(Math.max(1,27-n.length))}${d.dim(`# opens ${i} in this project`)}`),s.blank(),console.log(d.bold(`Some starter prompts for ${i}:`)),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 Ho,readFile as Ko}from"fs/promises";import{join as Qe,resolve as Fo}from"path";import N from"picocolors";async function Zt(e){let t=e.target?Fo(process.cwd(),e.target):process.cwd(),o=await Qt(Qe(t,".env")),n=await Qt(Qe(t,"package.json"));(!o||!n)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),o||s.detail("Missing: .env"),n||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 i="claude-code";try{D(await Ko(Qe(t,".env"),"utf-8")).AI_AGENT==="codex"&&(i="codex")}catch{}s.heading("Installing dependencies");let a=await Le(t);s.blank(),s.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){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(a.hints??{}))console.log(N.yellow(`Likely cause of ${r} failure:`)),console.log(N.dim(` ${w}`)),s.blank();let c=i==="codex"?"codex":"claude",p=i==="codex"?"Codex":"Claude Code",m=i==="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: \`${m}\`)`)),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 Qt(e){try{return await Ho(e),!0}catch{return!1}}import{readFile as Go,writeFile as Ze,access as Vo}from"fs/promises";import{join as fe}from"path";import*as Ue from"@clack/prompts";import V from"picocolors";import{mkdir as Bo}from"fs/promises";async function en(e){let t=e.projectRoot??process.cwd(),o=fe(t,".env"),n=fe(t,".mcp.json"),i=fe(t,".codex","config.toml"),a=await et(fe(t,".klaudius","manifest.json")),l=await et(o);!a&&!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=J();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 E=await Go(o,"utf-8");p=D(E)}catch{s.warn("No .env found. Starting from an empty configuration.")}let m=wt(p);Ue.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let r=await _(m),w=m.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(` ${V.cyan("npx klaudius@latest init <new-folder>")} ${V.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 E=await le({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});E.ok||(s.error(E.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let g=q(r.googlePlacesApiKey??"");if(g.changed&&r.googlePlacesApiKey){s.heading("Checking your Google Places API key");let E=await ce(r.googlePlacesApiKey);if(E.ok){if(g.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let x of g.repairs)s.detail(` ${x}`);s.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=g.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(E.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 Ze(o,Te(r),"utf-8"),s.success("Updated .env"),r.aiAgent==="codex"?(await Bo(fe(t,".codex"),{recursive:!0}),await Ze(i,Ie(r),"utf-8"),s.success("Updated .codex/config.toml")):(await Ze(n,Se(r),"utf-8"),s.success("Updated .mcp.json"),await Me(t,"supabase")),s.blank(),Ue.outro(V.green("Configuration updated.")),await Wo(t,a)}async function Wo(e,t){let o=await et(fe(e,"node_modules"));s.blank(),t?o||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${V.cyan("npx klaudius@latest install")} ${V.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${V.cyan("npx klaudius@latest doctor")} ${V.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(` ${V.cyan("npx klaudius@latest init")} ${V.dim("# pick Resume when prompted")}`),s.blank())}async function et(e){try{return await Vo(e),!0}catch{return!1}}import{copyFile as tn,mkdir as nn,readFile as Yo,rm as ke,writeFile as on,access as sn}from"fs/promises";import{dirname as an,join as U}from"path";import{tmpdir as zo}from"os";import*as me from"@clack/prompts";import tt from"picocolors";var je="0.19.3";async function rn(e){let t=e.projectRoot??process.cwd(),o=await Pt(t);o||(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 k of _e)delete o.files[k];let n,i=U(t,".env"),a,l;try{a=await Yo(i,"utf-8"),l=D(a)}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)}n=l.KLAUDIUS_LICENSE_KEY??"",n||(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=kt(a,l,yt);c!==null&&(await on(i,c,"utf-8"),s.detail("Backfilled new env keys")),await ve("update",je),me.intro(`Update from ${o.templateVersion} \u2192 ${je}`);let m=l.AI_AGENT==="codex"?"codex":"claude-code",r=U(zo(),`klaudius-update-${process.pid}-${Date.now()}`),w;try{s.heading("Downloading the latest Klaudius template");let k=await xe({licenseKey:n,machineId:ye(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:m,destDir:r});s.success(`Fetched ${k.filesExtracted} canonical files`),w=r}catch(k){s.error(k.message),s.detail("Update aborted. Your project is unchanged."),await ke(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let g=await qo(w,t,o),E=g.filter(k=>k.state==="new"),x=g.filter(k=>k.state==="clean-update"),oe=g.filter(k=>k.state==="user-only"),L=g.filter(k=>k.state==="conflict"),Y=g.filter(k=>k.state==="no-change"),b=g.filter(k=>k.state==="removed-clean"),P=g.filter(k=>k.state==="removed-modified"),$=[...L,...P];if(s.blank(),s.heading("Change summary"),s.detail(`${B(Y.length,"file")} unchanged`),s.detail(`${B(E.length,"new file")}`),s.detail(`${B(x.length,"file")} updated cleanly (no local edits)`),s.detail(`${B(oe.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${B(b.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${B(L.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${B(P.length,"file")} removed upstream but edited locally (need your decision)`),E.length===0&&x.length===0&&b.length===0&&$.length===0){s.blank(),me.outro(tt.green("Already up to date.")),await ke(r,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let k of[...E,...x]){let G=U(w,k.path),u=U(t,k.path);await nn(an(u),{recursive:!0}),await tn(G,u),o.files[k.path]=k.canonicalHash}E.length+x.length>0&&s.success(`Wrote ${B(E.length+x.length,"file")}`);for(let k of b){let G=U(t,k.path);await ke(G,{force:!0}),delete o.files[k.path]}if(b.length>0&&s.success(`Deleted ${B(b.length,"file")} removed upstream`),$.length>0){s.blank(),s.heading(`${$.length} conflict(s) need resolution`);let k=U(t,".klaudius","incoming");try{await ke(k,{recursive:!0,force:!0})}catch{}for(let G of L){let u=U(w,G.path),h=U(k,G.path);await nn(an(h),{recursive:!0}),await tn(u,h)}await on(U(t,".klaudius","conflicts.md"),Jo($,o.templateVersion,je),"utf-8"),L.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}if(o.updatedAt=new Date().toISOString(),$.length===0&&(o.templateVersion=je),await Ce(t,o),s.blank(),$.length===0)me.outro(tt.green("Update complete."));else{let k=m==="codex"?"Codex":"Claude Code";me.outro(tt.yellow(`${$.length} conflict(s) staged. Open ${k} in this project and ask:
78
+ "Run /resolve-conflicts"`))}await ke(r,{recursive:!0,force:!0}).catch(()=>{})}async function qo(e,t,o){let n=await re(e),i=new Set(n),a=[];for(let l of n){let c=await ae(U(e,l)),p=o.files[l],m=U(t,l),r;try{await sn(m),r=await ae(m)}catch{a.push({path:l,state:"new",canonicalHash:c,manifestHash:p});continue}c===p?r===p?a.push({path:l,state:"no-change",canonicalHash:c,localHash:r,manifestHash:p}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:r,manifestHash:p}):r===p?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:r,manifestHash:p}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:r,manifestHash:p})}for(let l of Object.keys(o.files)){if(i.has(l))continue;let c=o.files[l],p=U(t,l),m;try{await sn(p),m=await ae(p)}catch{delete o.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 B(e,t){return`${e} ${t}${e===1?"":"s"}`}function Jo(e,t,o){let n=e.filter(c=>c.state==="conflict").length,i=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 **${o}**.`),a.push("");let l=[];n>0&&l.push(`${n} file${n===1?"":"s"} ha${n===1?"s":"ve"} BOTH local edits AND upstream changes`),i>0&&l.push(`${i} file${i===1?"":"s"} ${i===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(`
79
+ `)}import{access as Xo,readFile as ln,stat as Qo}from"fs/promises";import{join as F}from"path";import R from"picocolors";import{spawn as cn}from"child_process";async function dn(e){let t=e.projectRoot??process.cwd(),o=[];console.log(R.bold(`Klaudius doctor \u2014 checking your project\u2026
80
+ `)),o.push(await Zo()),o.push(await es());let n=F(t,".env"),i=F(t,".klaudius","manifest.json"),a=F(t,".mcp.json"),l=F(t,".codex","config.toml"),c=await Q(n),p=await Q(i),m="claude-code";if(c)try{D(await ln(n,"utf-8")).AI_AGENT==="codex"&&(m="codex")}catch{}if(m==="claude-code"){let g=await Q(F(t,"AGENTS.md")),E=!await Q(F(t,".claude"));g&&E&&(m="codex")}if(o.push({name:".env present",status:c?"ok":"fail",detail:c?n:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."}),o.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?"ok":"fail",detail:p?i:"missing",nextAction:p?void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."}),m==="codex"){let g=await Q(l);o.push({name:".codex/config.toml present",status:g?"ok":"warn",detail:g?l:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let g=await Q(a);o.push({name:".mcp.json present",status:g?"ok":"warn",detail:g?a:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(o.push(await rs(m)),o.push(await ts(t)),o.push(await ns(t)),o.push(await os()),!c)o.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)o.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let g=await ln(n,"utf-8"),E=D(g);await ss(E,o)}console.log();for(let g of o){let E=g.status==="ok"?R.green("\u2713"):g.status==="warn"?R.yellow("\u26A0"):g.status==="skip"?R.dim("\xB7"):R.red("\u2717");console.log(` ${E} ${g.name}${g.detail?R.dim(` \u2014 ${g.detail}`):""}`),g.nextAction&&console.log(` ${R.dim("\u2192")} ${R.cyan(g.nextAction)}`)}let r=o.filter(g=>g.status==="fail").length,w=o.filter(g=>g.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 Xo(e),!0}catch{return!1}}async function Zo(){let e=await ie();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 es(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let o=parseInt(t[1],10),n=parseInt(t[2],10);return o<22||o===22&&n<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 ts(e){let t=F(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 Qo(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 ns(e){let t=process.platform==="darwin"?F(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?F(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):F(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 os(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
81
81
  try:
82
- ${e.map(i=>` import ${i}`).join(`
82
+ ${e.map(a=>` import ${a}`).join(`
83
83
  `)}
84
84
  except Exception as e:
85
85
  print(str(e))
86
86
  sys.exit(1)
87
- `,o=await he();if(!o)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 n=o.command,a=await cn(n[0],[...n.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(`
88
- `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function qo(e,t){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let n=await re({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:n.ok?"ok":"fail",detail:n.ok?"connected":n.message,nextAction:n.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 o=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":"vercel";if(o==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let n=await Oe({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:n.ok?"ok":"fail",detail:n.ok?`valid (${n.projectCount??0} Pages project${n.projectCount===1?"":"s"})`:n.message,nextAction:n.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(o==="netlify")if(e.NETLIFY_AUTH_TOKEN){let n=await $e({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:n.ok?"ok":"fail",detail:n.ok?n.accountSlug?`valid (team: ${n.accountSlug})`:"valid":n.message,nextAction:n.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 n=await xe(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:n.ok?"ok":"fail",detail:n.ok?n.username??"valid":n.message,nextAction:n.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 n=await le(e.GOOGLE_PLACES_API_KEY),a=q(e.GOOGLE_PLACES_API_KEY);n.ok&&a.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 "+(a.repairs.length>0?`it contains look-alike characters (${a.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:n.ok?"ok":"fail",detail:n.ok?"accepted":n.message,nextAction:n.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)"});if(t.push(await Xo(e)),e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let n=await it({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:n.ok?"ok":"fail",detail:n.ok?`bot ${n.botHandle??"ok"} (chat_id not tested)`:n.message,nextAction:n.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:"Telegram credentials",status:"skip",detail:"not configured (optional)"})}function Jo(e){let t=i=>!!i&&/^\d+$/.test(i.trim()),o=!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),n=(e.OUTREACH_CHANNELS??"").split(",").map(i=>i.trim()),a=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&n.includes("email");return a&&o?"active":a?"incomplete":o?"parked":"unconfigured"}async function Xo(e){let t="Email credentials (SMTP + IMAP)",o=Jo(e);if(o==="unconfigured")return{name:t,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(o==="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(o==="incomplete"){let l=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(c=>c.endsWith("_PORT")?!e[c]||!/^\d+$/.test(e[c].trim()):!e[c]);return{name:t,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${l.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let n={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)},a=await ce(n);if(a.ok)return{name:t,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`};if(a.failureKind==="network")return{name:t,status:"fail",detail:a.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."};let i=Ee(e);if(i&&i!=="custom"){let l=we(i,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(l.length>0){console.log(R.dim(` (email login rejected \u2014 probing ${z[i].label}'s other regional servers, up to ~10s each\u2026)`));let c=0;for(let m of l){let r=await ce({...n,emailSmtpHost:m.smtpHost,emailImapHost:m.imapHost});if(!r.ok&&r.failureKind!=="network"&&c++,r.ok)return{name:t,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${m.label} (${m.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${m.smtpHost} and EMAIL_IMAP_HOST=${m.imapHost} in .env (or ask your AI agent to).`}}let p=(a.message??"login rejected").split(/\.\s|\n/)[0];return c===0?{name:t,status:"fail",detail:`${p} \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:`${p} \u2014 tried all ${z[i].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:i==="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`.":"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:t,status:"fail",detail:a.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}async function Qo(e){let t=e==="codex"?"codex":"claude",o=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",n=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 cn(t,["--version"],process.platform==="win32");return a.code===0?{name:o,status:"ok",detail:(a.stdout||a.stderr).trim().split(`
89
- `)[0]}:{name:o,status:"warn",detail:"not found",nextAction:n}}function cn(e,t,o=!1){return new Promise(n=>{let a=o?rn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):rn(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=>n({code:c??1,stdout:i,stderr:l})),a.on("error",()=>n({code:1,stdout:i,stderr:l}))})}import{existsSync as Zo}from"fs";import{spawnSync as es}from"child_process";import{join as ts,resolve as ns}from"path";import O from"picocolors";async function dn(e){let t=ns(e.projectRoot??process.cwd()),o=ts(t,"scripts","whatsapp.mjs");Zo(o)||(console.error(O.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(O.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(O.dim(`Looked for: ${o}`)),process.exit(1));let n=(e.label??"primary").trim(),a=n.replace(/[^A-Za-z0-9_-]/g,"");a||(console.error(O.red(`Invalid label '${n}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),a!==n&&console.error(O.yellow(`Note: cleaned label '${n}' \u2192 '${a}' (filename-safe characters only).`)),console.log(O.cyan(`Pairing WhatsApp account '${a}'...`)),console.log(O.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.
90
- `));let i=es(process.execPath,[o,"pair","--account",a],{cwd:t,stdio:"inherit"});if(i.status===0){console.log(O.green(`Paired '${a}'.`)),console.log(O.dim(`
91
- If you haven't already, add '${a}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
92
- WHATSAPP_ACCOUNTS=primary,${a}
93
- (Skip this if '${a}' is already there or you set it via the init wizard.)`));return}i.error?console.error(O.red(`Pair failed: ${i.error.message}`)):(console.error(O.red(`Pair did not complete (exit ${i.status??"signalled"}). Common causes:`)),console.error(O.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(O.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(O.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${a}/daemon.log`))),process.exit(i.status??1)}import{spawnSync as os}from"child_process";var tt="--use-system-ca";function un(){let e=process.env.NODE_OPTIONS??"";if(e.includes(tt)||!J().ok)return;let o=e?`${e} ${tt}`:tt,n=os(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:o},stdio:"inherit"});n.signal&&(process.kill(process.pid,n.signal),process.exit(1)),process.exit(n.status??1)}un();var is="0.19.1",W=new ss;W.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(is);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 ut({})}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 zt({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(o){console.error("init failed:",o.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 Jt({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 Xt({})}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 on({})}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 ln({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 dn({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});W.parse(process.argv);
87
+ `,o=await ge();if(!o)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 n=o.command,i=await un(n[0],[...n.slice(1),"-c",t]);return i.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(i.stdout||i.stderr).trim().split(`
88
+ `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function ss(e,t){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let n=await le({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:n.ok?"ok":"fail",detail:n.ok?"connected":n.message,nextAction:n.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 o=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":"vercel";if(o==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let n=await $e({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:n.ok?"ok":"fail",detail:n.ok?`valid (${n.projectCount??0} Pages project${n.projectCount===1?"":"s"})`:n.message,nextAction:n.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(o==="netlify")if(e.NETLIFY_AUTH_TOKEN){let n=await Ne({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:n.ok?"ok":"fail",detail:n.ok?n.accountSlug?`valid (team: ${n.accountSlug})`:"valid":n.message,nextAction:n.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 n=await Oe(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:n.ok?"ok":"fail",detail:n.ok?n.username??"valid":n.message,nextAction:n.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 n=await ce(e.GOOGLE_PLACES_API_KEY),i=q(e.GOOGLE_PLACES_API_KEY);n.ok&&i.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 "+(i.repairs.length>0?`it contains look-alike characters (${i.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:n.ok?"ok":"fail",detail:n.ok?"accepted":n.message,nextAction:n.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)"});if(t.push(await as(e)),e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let n=await at({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:n.ok?"ok":"fail",detail:n.ok?`bot ${n.botHandle??"ok"} (chat_id not tested)`:n.message,nextAction:n.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:"Telegram credentials",status:"skip",detail:"not configured (optional)"})}function is(e){let t=a=>!!a&&/^\d+$/.test(a.trim()),o=!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),n=(e.OUTREACH_CHANNELS??"").split(",").map(a=>a.trim()),i=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&n.includes("email");return i&&o?"active":i?"incomplete":o?"parked":"unconfigured"}async function as(e){let t="Email credentials (SMTP + IMAP)",o=is(e);if(o==="unconfigured")return{name:t,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(o==="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(o==="incomplete"){let l=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(c=>c.endsWith("_PORT")?!e[c]||!/^\d+$/.test(e[c].trim()):!e[c]);return{name:t,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${l.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let n={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)},i=await de(n);if(i.ok)return{name:t,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`};if(i.failureKind==="network")return{name:t,status:"fail",detail:i.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."};let a=be(e);if(a&&a!=="custom"){let l=Ae(a,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(l.length>0){console.log(R.dim(` (email login rejected \u2014 probing ${z[a].label}'s other regional servers, up to ~10s each\u2026)`));let c=0;for(let m of l){let r=await de({...n,emailSmtpHost:m.smtpHost,emailImapHost:m.imapHost});if(!r.ok&&r.failureKind!=="network"&&c++,r.ok)return{name:t,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${m.label} (${m.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${m.smtpHost} and EMAIL_IMAP_HOST=${m.imapHost} in .env (or ask your AI agent to).`}}let p=(i.message??"login rejected").split(/\.\s|\n/)[0];return c===0?{name:t,status:"fail",detail:`${p} \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:`${p} \u2014 tried all ${z[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`.":"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:t,status:"fail",detail:i.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}async function rs(e){let t=e==="codex"?"codex":"claude",o=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",n=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`.",i=await un(t,["--version"],process.platform==="win32");return i.code===0?{name:o,status:"ok",detail:(i.stdout||i.stderr).trim().split(`
89
+ `)[0]}:{name:o,status:"warn",detail:"not found",nextAction:n}}function un(e,t,o=!1){return new Promise(n=>{let i=o?cn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):cn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{l+=c.toString()}),i.on("close",c=>n({code:c??1,stdout:a,stderr:l})),i.on("error",()=>n({code:1,stdout:a,stderr:l}))})}import{existsSync as ls}from"fs";import{spawnSync as cs}from"child_process";import{join as ds,resolve as us}from"path";import O from"picocolors";async function pn(e){let t=us(e.projectRoot??process.cwd()),o=ds(t,"scripts","whatsapp.mjs");ls(o)||(console.error(O.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(O.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(O.dim(`Looked for: ${o}`)),process.exit(1));let n=(e.label??"primary").trim(),i=n.replace(/[^A-Za-z0-9_-]/g,"");i||(console.error(O.red(`Invalid label '${n}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),i!==n&&console.error(O.yellow(`Note: cleaned label '${n}' \u2192 '${i}' (filename-safe characters only).`)),console.log(O.cyan(`Pairing WhatsApp account '${i}'...`)),console.log(O.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.
90
+ `));let a=cs(process.execPath,[o,"pair","--account",i],{cwd:t,stdio:"inherit"});if(a.status===0){console.log(O.green(`Paired '${i}'.`)),console.log(O.dim(`
91
+ If you haven't already, add '${i}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
92
+ WHATSAPP_ACCOUNTS=primary,${i}
93
+ (Skip this if '${i}' is already there or you set it via the init wizard.)`));return}a.error?console.error(O.red(`Pair failed: ${a.error.message}`)):(console.error(O.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(O.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(O.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(O.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${i}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as ps}from"child_process";var nt="--use-system-ca";function fn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(nt)||!J().ok)return;let o=e?`${e} ${nt}`:nt,n=ps(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:o},stdio:"inherit"});n.signal&&(process.kill(process.pid,n.signal),process.exit(1)),process.exit(n.status??1)}fn();var ms="0.19.3",W=new fs;W.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(ms);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 mt({})}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 Xt({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(o){console.error("init failed:",o.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 Zt({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 en({})}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 rn({})}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 dn({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 pn({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});W.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klaudius",
3
- "version": "0.19.1",
3
+ "version": "0.19.3",
4
4
  "description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code (find, build, deploy, outreach end-to-end).",
5
5
  "homepage": "https://klaudius.dev",
6
6
  "bugs": {