klaudius 0.21.0 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -113,14 +113,9 @@ that AFTER this wizard, once npm dependencies are installed.
113
113
 
114
114
  Multiple numbers (advanced): if you plan to send at higher volume, you can
115
115
  link 2-5 WhatsApp accounts. Klaudius round-robins across them for initial
116
- outreach (spreading the load and the ban risk); follow-ups always use the
117
- same account that started the thread. Each account is independent \u2014 one
118
- getting banned doesn't affect the others. For multi-number you need a
119
- separate phone number per account (they're tied to real SIMs).
120
-
121
- IMPORTANT: WhatsApp may suspend numbers used for cold outbound. Start with
122
- phone numbers you can afford to lose, and don't link your main personal
123
- number unless you're comfortable with that.
116
+ outreach (spreading the load); follow-ups always use the same account that
117
+ started the thread. Each account is independent. For multi-number you need
118
+ a separate phone number per account (they're tied to real SIMs).
124
119
 
125
120
  You'll be asked how many accounts to link and a short label for each
126
121
  (used only locally \u2014 appears in logs, in the .env file, and in this
package/dist/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import{a as oe,b as at,c as rt,d as Ee,e as W,g as T,i as lt,j as ct,k as Ae,l as Pe,n as z,o as dt,p as ut}from"./chunk-73JSE77U.js";import{Command as gs}from"commander";import{spawn as mt}from"child_process";import S from"picocolors";function q(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),o=parseInt(t[2],10),a=parseInt(t[3],10),i=`${n}.${o}.${a}`;return n<22||n===22&&o<15?{ok:!1,version:i,major:n,minor:o,message:`Your installed Node.js is ${i}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:i,major:n,minor:o}}import{spawn as kn}from"child_process";import{existsSync as wn}from"fs";import{homedir as En}from"os";import{delimiter as An,join as Te}from"path";var Pn=new Set(["Restricted","AllSigned"]);function Tn(e,t=wn){for(let n of e.split(An)){let o=n.replace(/"/g,"");if(!o)continue;let a=Te(o,"npx.ps1");if(t(a))return{path:a,isPs1:!0};for(let i of["npx.exe","npx.bat","npx.cmd"]){let l=Te(o,i);if(t(l))return{path:l,isPs1:!1}}}return null}async function ft(){let e=Tn(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await bn();if(!t)return{blocked:!1,shimPath:e.path};let n=Te(En(),".local","node")+"\\";return{blocked:Pn.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function bn(){let e=Te(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await pt(e)??await pt("powershell.exe")}function pt(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let o=kn(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),a="",i=setTimeout(()=>{o.kill(),n(null)},8e3);o.stdout.on("data",l=>{a+=l.toString()}),o.stderr?.resume(),o.on("close",l=>{clearTimeout(i),n(l===0&&a.trim()?a.trim():null)}),o.on("error",()=>{clearTimeout(i),n(null)})})}import{spawn as Sn}from"child_process";var me=3,be=10,_n=[["python3"],["python"],["py","-3"]];async function he(){for(let e of _n){let t=await Cn(e[0],[...e.slice(1),"--version"]),n=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(n)||t.code!==0)continue;let o=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!o)continue;let a=parseInt(o[1],10),i=parseInt(o[2],10),l=o[3]?`${a}.${i}.${o[3]}`:`${a}.${i}`;return{command:[...e],version:l,major:a,minor:i}}return null}async function se(){let e=In(),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}.${be}+ is not installed (or not on PATH). Install it from ${e}.`+l}}let{command:n,version:o,major:a,minor:i}=t;return a<me||a===me&&i<be?{ok:!1,version:o,major:a,minor:i,command:n,message:`Your installed Python is ${o}. Klaudius needs Python ${me}.${be} or newer (the pipeline depends on packages that only ship wheels for ${me}.${be}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:o,major:a,minor:i,command:n}}function In(){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 Cn(e,t){return new Promise(n=>{let o=Sn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",i="";o.stdout?.on("data",l=>{a+=l.toString()}),o.stderr?.on("data",l=>{i+=l.toString()}),o.on("close",l=>n({code:l??1,stdout:a,stderr:i})),o.on("error",()=>n({code:1,stdout:a,stderr:i}))})}var ht=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function gt(e={}){console.log(S.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
3
  `));let t=[];t.push(Rn());let n=await se();if(t.push(On(n)),t.push(await xn(n.command)),t.push(await vn()),process.platform==="win32"){let a=await Nn();a&&t.push(a)}t.push(await $n());for(let a of t){let i=a.status==="ok"?S.green("\u2713"):S.red("\u2717");console.log(` ${i} ${a.name}${a.detail?S.dim(` \u2014 ${a.detail}`):""}`),a.nextAction&&console.log(` ${S.dim("\u2192")} ${S.cyan(a.nextAction)}`)}console.log();let o=t.filter(a=>a.status==="fail");if(o.length===0){Ln();return}console.log(S.red(S.bold(`${o.length} check${o.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(S.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(S.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Rn(){let e=q();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal before re-running."}}function On(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 xn(e){let t=e??["python3"],n=await Ye(t[0],[...t.slice(1),"-m","pip","--version"]);return n.code===0?{name:"pip available",status:"ok",detail:(n.stdout||n.stderr).trim().split(`
4
- `)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function vn(){let e=process.platform==="win32",t=await Ye("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 Ye("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 Nn(){let e=await ft();if(e.npxMissing)return null;let t="npx runs in PowerShell";if(!e.blocked){let n="resolves to a policy-immune shim";return e.shimPath&&(n=e.policy?`ExecutionPolicy ${e.policy} allows the npx.ps1 shim`:"npx.ps1 shim present but ExecutionPolicy unreadable \u2014 assuming it runs"),{name:t,status:"ok",detail:n}}return{name:t,status:"fail",detail:`ExecutionPolicy ${e.policy} blocks ${e.shimPath}, which PowerShell prefers over npx.cmd`,nextAction:e.ownInstall?`In PowerShell run: Remove-Item "$env:USERPROFILE\\.local\\node\\np*.ps1" \u2014 it deletes only the PowerShell shims from Klaudius's own Node install (npx falls back to npx.cmd). It prints nothing back; that means it worked. Then re-run this preflight.`:"In Windows PowerShell (the classic blue one, not PowerShell 7) run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned \u2014 printing nothing back means it worked; confirm with Get-ExecutionPolicy (should say RemoteSigned), then re-run this preflight. If it prints an error instead, your organisation manages this setting \u2014 ask IT."}}async function $n(){try{return await fetch(ht,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:ht}}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 Ln(){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 Ye(e,t,n=!1){return new Promise(o=>{let a=n?mt([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):mt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",l="";a.stdout?.on("data",c=>{i+=c.toString()}),a.stderr?.on("data",c=>{l+=c.toString()}),a.on("close",c=>o({code:c??1,stdout:i,stderr:l})),a.on("error",()=>o({code:1,stdout:i,stderr:l}))})}import{mkdir as Qe,readdir as Qt,readFile as qt,stat as Ze,writeFile as Xe}from"fs/promises";import{spawnSync as Zt}from"child_process";import{homedir as xo}from"os";import{resolve as vo,isAbsolute as No,join as F,normalize as $o}from"path";import*as k from"@clack/prompts";import d from"picocolors";import Mn from"react";import{render as Dn}from"ink";async function _(e={},t={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius@latest init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:n}=await import("./WizardApp-AEM5AKTF.js"),o=null;oe("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),rt(),await new Promise(i=>setImmediate(i)),await new Promise(i=>setTimeout(i,0)),oe("runWizard:event loop drained, mounting Ink");let a=Dn(Mn.createElement(n,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:i=>{oe("runWizard:onComplete called",{keys:Object.keys(i).length}),o=i}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(oe("runWizard:render returned, awaiting exit"),await a.waitUntilExit(),oe("runWizard:waitUntilExit resolved",{resultIsNull:o===null}),!o)throw new Error(`Wizard exited without completing. Diagnostic log: ${at}
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 vn(){let e=process.platform==="win32",t=await Ye("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 Ye("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 Nn(){let e=await ft();if(e.npxMissing)return null;let t="npx runs in PowerShell";if(!e.blocked){let n="resolves to a policy-immune shim";return e.shimPath&&(n=e.policy?`ExecutionPolicy ${e.policy} allows the npx.ps1 shim`:"npx.ps1 shim present but ExecutionPolicy unreadable \u2014 assuming it runs"),{name:t,status:"ok",detail:n}}return{name:t,status:"fail",detail:`ExecutionPolicy ${e.policy} blocks ${e.shimPath}, which PowerShell prefers over npx.cmd`,nextAction:e.ownInstall?`In PowerShell run: Remove-Item "$env:USERPROFILE\\.local\\node\\np*.ps1" \u2014 it deletes only the PowerShell shims from Klaudius's own Node install (npx falls back to npx.cmd). It prints nothing back; that means it worked. Then re-run this preflight.`:"In Windows PowerShell (the classic blue one, not PowerShell 7) run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned \u2014 printing nothing back means it worked; confirm with Get-ExecutionPolicy (should say RemoteSigned), then re-run this preflight. If it prints an error instead, your organisation manages this setting \u2014 ask IT."}}async function $n(){try{return await fetch(ht,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:ht}}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 Ln(){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 Ye(e,t,n=!1){return new Promise(o=>{let a=n?mt([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):mt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",l="";a.stdout?.on("data",c=>{i+=c.toString()}),a.stderr?.on("data",c=>{l+=c.toString()}),a.on("close",c=>o({code:c??1,stdout:i,stderr:l})),a.on("error",()=>o({code:1,stdout:i,stderr:l}))})}import{mkdir as Qe,readdir as Qt,readFile as qt,stat as Ze,writeFile as Xe}from"fs/promises";import{spawnSync as Zt}from"child_process";import{homedir as xo}from"os";import{resolve as vo,isAbsolute as No,join as F,normalize as $o}from"path";import*as k from"@clack/prompts";import d from"picocolors";import Mn from"react";import{render as Dn}from"ink";async function _(e={},t={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius@latest init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:n}=await import("./WizardApp-ETSJS77F.js"),o=null;oe("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),rt(),await new Promise(i=>setImmediate(i)),await new Promise(i=>setTimeout(i,0)),oe("runWizard:event loop drained, mounting Ink");let a=Dn(Mn.createElement(n,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:i=>{oe("runWizard:onComplete called",{keys:Object.keys(i).length}),o=i}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(oe("runWizard:render returned, awaiting exit"),await a.waitUntilExit(),oe("runWizard:waitUntilExit resolved",{resultIsNull:o===null}),!o)throw new Error(`Wizard exited without completing. Diagnostic log: ${at}
5
5
  Please share that file so we can trace what happened.`);return o}var Be="claude-code";function yt(e){if(e==="claude-code"||e==="codex")return e}var We="vercel";function kt(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function wt(e){if(e==="telegram"||e==="email"||e==="sms")return e}function Un(e){if(e==="custom"||e!==void 0&&Object.hasOwn(W,e))return e}function Se(e){let t=Un(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[o,a]of Object.entries(W))if(a.smtpHost===n)return o;return"custom"}}function _e(e){let t=[],n=i=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${i}`),t.push("# "+"=".repeat(60)),t.push("")},o=(i,l)=>{if(l==null||l===""){t.push(`# ${i}=`);return}let c=String(l);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(c)){let p=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${i}="${p}"`)}else t.push(`${i}=${c}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),o("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),o("AI_AGENT",e.aiAgent??Be),n("Operating country and language"),o("OPERATOR_COUNTRY",e.country),o("OPERATOR_COUNTRY_CODE",e.countryCode),o("OPERATOR_LANGUAGE",e.language),o("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let a=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];return o("PIPELINE_MODES",[...new Set(["classic",...a])].join(",")),n("Pricing"),o("PRICING",e.pricing),o("PRICING_TERMS",e.pricingTerms),o("PRICING_MONTHLY",e.pricingMonthly),n("Automated outreach features"),o("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),o("OPERATOR_NAME",e.name),o("SIGNATURE",e.signature),o("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),o("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),o("EMAIL_PROVIDER",e.emailProvider),o("EMAIL_ADDRESS",e.emailAddress),o("EMAIL_PASSWORD",e.emailPassword),o("EMAIL_FROM_NAME",e.emailFromName),o("EMAIL_SMTP_HOST",e.emailSmtpHost),o("EMAIL_SMTP_PORT",e.emailSmtpPort),o("EMAIL_IMAP_HOST",e.emailImapHost),o("EMAIL_IMAP_PORT",e.emailImapPort),o("EMAIL_SENT_FOLDER",e.emailSentFolder),o("EMAIL_INBOX_FOLDER",e.emailInboxFolder),n("SMS outreach"),o("SMS_PROVIDER",e.smsProvider),o("TEST_PHONE",e.testPhone),o("TWILIO_ACCOUNT_SID",e.twilioAccountSid),o("TWILIO_AUTH_TOKEN",e.twilioAuthToken),o("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),o("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Supabase (pipeline state)"),o("SUPABASE_URL",e.supabaseUrl),o("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),o("SUPABASE_PAT",e.supabasePat),o("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),o("DEPLOY_PROVIDER",e.deployProvider??We),o("VERCEL_TOKEN",e.vercelToken),o("VERCEL_SCOPE",e.vercelScope??""),o("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),o("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),o("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),o("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),o("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),o("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),o("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),o("NOTIFY_CHANNEL",e.notifyChannel),o("NOTIFY_TO",e.notifyTo),o("TELEGRAM_BOT_TOKEN",e.telegramBotToken),o("TELEGRAM_CHAT_ID",e.telegramChatId),t.join(`
6
6
  `)+`
7
7
  `}function Ie(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)+`
@@ -12,15 +12,15 @@ Please share that file so we can trace what happened.`);return o}var Be="claude-
12
12
  `)+`
13
13
  `}function Fn(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 n of e.split(`
14
14
  `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let a=o.indexOf("=");if(a===-1)continue;let i=o.slice(0,a).trim(),l=Fn(o.slice(a+1).trim());t[i]=l}return t}function Pt(e){let t=c=>{let p=e[c];if(!p)return;let m=parseInt(p,10);return isNaN(m)?void 0:m},n=e.SMS_PROVIDER,o=c=>c==="email"||c==="sms"||c==="whatsapp",a=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(o),i=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(o),l=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:yt(e.AI_AGENT)??Be,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(c=>c.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:a&&a.length>0?a:void 0,outreachPriority:i&&i.length>0?i:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailProvider:Se(e),emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:n==="imessage"||n==="twilio"?n:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:kt(e.DEPLOY_PROVIDER)??We,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN||void 0,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID||void 0,netlifyAuthToken:e.NETLIFY_AUTH_TOKEN||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:e.SELFHOST_DEPLOY_TARGET||void 0,selfhostUrlTemplate:e.SELFHOST_URL_TEMPLATE||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,emailPassword:e.EMAIL_PASSWORD,notifyChannel:wt(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function ze(e){let t=g=>{let L=e[g];if(!L)return;let u=parseInt(L,10);return isNaN(u)?void 0:u},n=e.SUPABASE_URL,o=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),a=e.SUPABASE_PAT?.replace(/\s+/g,""),i=e.SUPABASE_PROJECT_REF,l=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",p=kt(e.DEPLOY_PROVIDER)??We,m=e.VERCEL_TOKEN,r=e.CLOUDFLARE_API_TOKEN,E=e.CLOUDFLARE_ACCOUNT_ID,y=e.NETLIFY_AUTH_TOKEN,A=e.SELFHOST_DEPLOY_TARGET,v=e.SELFHOST_URL_TEMPLATE;if(!l||!n||!o||!a||!i||!(p==="cloudflare"?!!r&&!!E:p==="netlify"?!!y:p==="selfhost"?!!A&&!!v:!!m))return null;let $=e.SMS_PROVIDER,Z=g=>g==="email"||g==="sms"||g==="whatsapp",P=e.OUTREACH_CHANNELS?.split(",").map(g=>g.trim()).filter(Z),j=e.OUTREACH_PRIORITY?.split(",").map(g=>g.trim()).filter(Z),O=e.WHATSAPP_ACCOUNTS?.split(",").map(g=>g.trim()).filter(g=>g.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:yt(e.AI_AGENT)??Be,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(g=>g.trim().toLowerCase()).filter(Boolean):void 0,pricing:l,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:P&&P.length>0?P:void 0,outreachPriority:j&&j.length>0?j:void 0,whatsappAccounts:O&&O.length>0?O:void 0,emailProvider:Se(e),emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:$==="imessage"||$==="twilio"?$:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:p,vercelToken:m,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:r||void 0,cloudflareAccountId:E||void 0,netlifyAuthToken:y||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:A||void 0,selfhostUrlTemplate:v||void 0,supabaseUrl:n,supabaseServiceKey:o,supabasePat:a,supabaseProjectRef:i,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:wt(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Ys,mkdir as Bs,readdir as Jn,stat as Ws}from"fs/promises";import{dirname as qs,join as It,relative as Xn,sep as Qn}from"path";import{fileURLToPath as Xs}from"url";import{createHash as Kn}from"crypto";import{readFile as Gn}from"fs/promises";async function ie(e){let t=await Gn(e);return Kn("sha256").update(t).digest("hex")}import{mkdir as Vn,readFile as Yn,writeFile as Bn,access as Wn}from"fs/promises";import{dirname as zn,join as Tt}from"path";var qn=".klaudius",bt=`${qn}/manifest.json`,Re=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml"]);async function St(e){let t=Tt(e,bt);try{await Wn(t)}catch{return null}let n=await Yn(t,"utf-8"),o=JSON.parse(n),a={};for(let[i,l]of Object.entries(o.files??{}))a[i.split("\\").join("/")]=l;return o.files=a,o}async function Oe(e,t){let n=Tt(e,bt);await Vn(zn(n),{recursive:!0}),await Bn(n,JSON.stringify(t,null,2)+`
15
- `,"utf-8")}function _t(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function ae(e,t=e){let n=await Jn(e,{withFileTypes:!0}),o=[];for(let a of n){let i=It(e,a.name);a.isDirectory()?o.push(...await ae(i,t)):a.isFile()&&o.push(Xn(t,i).split(Qn).join("/"))}return o}async function Ct(e){let t=await ae(e),n={};for(let o of t)Re.has(o)||(n[o]=await ie(It(e,o)));return n}import{copyFile as Zn,mkdir as Rt,mkdtemp as eo,readdir as Ot,rm as xt}from"fs/promises";import{tmpdir as to}from"os";import{dirname as no,join as xe}from"path";import{Readable as oo}from"stream";import*as vt from"tar";var so="https://klaudius.dev/api/template";function io(e){return oo.fromWeb(e)}async function ve(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??so,n="0.21.0",o;try{o=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${T(c)}`)}if(!o.ok){let c="";try{let p=await o.json();c=p.reason?` (${p.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${o.status}${c}`)}if(!o.body)throw new Error("Template download succeeded but response had no body");let a=o.headers.get("x-klaudius-tier"),i=await eo(xe(to(),"klaudius-template-")),l=0;try{try{await new Promise((m,r)=>{let E=vt.extract({cwd:i,strict:!0});E.on("finish",m),E.on("error",r),io(o.body).on("error",r).pipe(E)})}catch(m){throw new Error(`Failed to extract template archive: ${m.message}`)}await Rt(e.destDir,{recursive:!0});let c=new Set(await Ot(e.destDir)),p=await ae(i);try{for(let m of p){let r=xe(e.destDir,m);await Rt(no(r),{recursive:!0}),await Zn(xe(i,m),r),l++}}catch(m){let r=await Ot(e.destDir).catch(()=>[]);for(let E of r)c.has(E)||await xt(xe(e.destDir,E),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${m.message}`)}}finally{await xt(i,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:a}}import J from"picocolors";var s={info:e=>console.log(J.cyan("\u2139"),e),success:e=>console.log(J.green("\u2713"),e),warn:e=>console.log(J.yellow("\u26A0"),e),error:e=>console.error(J.red("\u2717"),e),step:e=>console.log(J.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
16
- `+J.bold(J.cyan(e))),detail:e=>console.log(J.dim(" "+e))};var ao="https://registry.npmjs.org/klaudius/latest";async function ro(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let o=await fetch(ao,{signal:t.signal,headers:{accept:"application/json"}});if(!o.ok)return null;let a=await o.json();return typeof a.version=="string"?a.version:null}catch{return null}finally{clearTimeout(n)}}function lo(e,t){let n=i=>i.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),o=n(e),a=n(t);if(o.length<3||a.length<3)return!1;for(let i=0;i<3;i++){if(Number.isNaN(o[i])||Number.isNaN(a[i]))return!1;if(o[i]>a[i])return!0;if(o[i]<a[i])return!1}return!1}async function Ne(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await ro();!n||!lo(n,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(s.detail("Your project content is fetched fresh either way, so you're not missing any"),s.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),s.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),s.blank())}import{createHash as co}from"crypto";import{hostname as Nt,userInfo as uo,platform as $t,arch as Lt}from"os";var po="https://klaudius.dev",fo="/api/licenses/validate",mo="0.21.0";async function Mt(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),o=(process.env.KLAUDIUS_API_URL??po).replace(/\/$/,"")+fo,a=ge(),i;try{i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:a,hostname:Nt(),os:`${$t()}-${Lt()}`,cli_version:mo})})}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=[Nt(),uo().username,$t(),Lt()].join("|");return co("sha256").update(e).digest("hex").slice(0,32)}import{readFile as ho}from"fs/promises";import{join as go}from"path";async function re(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${T(n)}`}}}async function Dt(e){let t;try{t=await ho(go(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(o){return{ok:!1,message:`Could not read scripts/schema.sql: ${o.message}`}}let n=e.pat.replace(/\s+/g,"");try{let o=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(o.ok)return{ok:!0};let a=await o.text();return a.includes("already exists")||a.includes('relation "clients" already exists')||a.includes("duplicate")?(s.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${o.status}): ${a.slice(0,300)}`}}catch(o){return{ok:!1,message:`Schema apply failed: ${o.message}`}}}async function $e(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${T(t)}`}}}var Ut="https://api.cloudflare.com/client/v4";function jt(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Le(e){let{token:t,accountId:n}=e,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let a=await fetch(`${Ut}/user/tokens/verify`,{headers:o});if(a.status===401||a.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${a.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} verifying the token. Try again or check cloudflarestatus.com.`};let i=await a.json(),l=i.result?.status;if(i.success===!1||l&&l!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${l?` (status: ${l})`:""}. ${jt(i)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${T(a)}`}}try{let a=await fetch(`${Ut}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:o});if(a.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(a.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let i=await a.json();return i.success===!1?{ok:!1,message:jt(i)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(i.result)?i.result.length:void 0}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${T(a)}`}}}var Ht="https://api.netlify.com/api/v1";async function Me(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let o=await fetch(`${Ht}/user`,{headers:n});if(o.status===401||o.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!o.ok)return{ok:!1,message:`Netlify API returned HTTP ${o.status} verifying the token. Try again or check netlifystatus.com.`}}catch(o){return{ok:!1,message:`Could not reach Netlify: ${T(o)}`}}try{let o=await fetch(`${Ht}/accounts`,{headers:n});if(!o.ok)return{ok:!1,message:`Netlify API returned HTTP ${o.status} listing your teams. Try again or check netlifystatus.com.`};let a=await o.json(),i=Array.isArray(a)?a:[];if(i.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let l=typeof i[0]?.slug=="string"?i[0].slug:void 0;return{ok:!0,accountCount:i.length,accountSlug:l}}catch(o){return{ok:!1,message:`Could not reach Netlify: ${T(o)}`}}}async function le(e){let t=dt(e);if(t)return{ok:!1,message:t};let n=z(e),o=n.value,a=i=>{let l=[i],c=ut(e);return c&&l.push(c),n.repairs.length>0&&l.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),l.join(`
15
+ `,"utf-8")}function _t(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function ae(e,t=e){let n=await Jn(e,{withFileTypes:!0}),o=[];for(let a of n){let i=It(e,a.name);a.isDirectory()?o.push(...await ae(i,t)):a.isFile()&&o.push(Xn(t,i).split(Qn).join("/"))}return o}async function Ct(e){let t=await ae(e),n={};for(let o of t)Re.has(o)||(n[o]=await ie(It(e,o)));return n}import{copyFile as Zn,mkdir as Rt,mkdtemp as eo,readdir as Ot,rm as xt}from"fs/promises";import{tmpdir as to}from"os";import{dirname as no,join as xe}from"path";import{Readable as oo}from"stream";import*as vt from"tar";var so="https://klaudius.dev/api/template";function io(e){return oo.fromWeb(e)}async function ve(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??so,n="0.21.2",o;try{o=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${T(c)}`)}if(!o.ok){let c="";try{let p=await o.json();c=p.reason?` (${p.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${o.status}${c}`)}if(!o.body)throw new Error("Template download succeeded but response had no body");let a=o.headers.get("x-klaudius-tier"),i=await eo(xe(to(),"klaudius-template-")),l=0;try{try{await new Promise((m,r)=>{let E=vt.extract({cwd:i,strict:!0});E.on("finish",m),E.on("error",r),io(o.body).on("error",r).pipe(E)})}catch(m){throw new Error(`Failed to extract template archive: ${m.message}`)}await Rt(e.destDir,{recursive:!0});let c=new Set(await Ot(e.destDir)),p=await ae(i);try{for(let m of p){let r=xe(e.destDir,m);await Rt(no(r),{recursive:!0}),await Zn(xe(i,m),r),l++}}catch(m){let r=await Ot(e.destDir).catch(()=>[]);for(let E of r)c.has(E)||await xt(xe(e.destDir,E),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${m.message}`)}}finally{await xt(i,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:a}}import J from"picocolors";var s={info:e=>console.log(J.cyan("\u2139"),e),success:e=>console.log(J.green("\u2713"),e),warn:e=>console.log(J.yellow("\u26A0"),e),error:e=>console.error(J.red("\u2717"),e),step:e=>console.log(J.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
16
+ `+J.bold(J.cyan(e))),detail:e=>console.log(J.dim(" "+e))};var ao="https://registry.npmjs.org/klaudius/latest";async function ro(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let o=await fetch(ao,{signal:t.signal,headers:{accept:"application/json"}});if(!o.ok)return null;let a=await o.json();return typeof a.version=="string"?a.version:null}catch{return null}finally{clearTimeout(n)}}function lo(e,t){let n=i=>i.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),o=n(e),a=n(t);if(o.length<3||a.length<3)return!1;for(let i=0;i<3;i++){if(Number.isNaN(o[i])||Number.isNaN(a[i]))return!1;if(o[i]>a[i])return!0;if(o[i]<a[i])return!1}return!1}async function Ne(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await ro();!n||!lo(n,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(s.detail("Your project content is fetched fresh either way, so you're not missing any"),s.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),s.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),s.blank())}import{createHash as co}from"crypto";import{hostname as Nt,userInfo as uo,platform as $t,arch as Lt}from"os";var po="https://klaudius.dev",fo="/api/licenses/validate",mo="0.21.2";async function Mt(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),o=(process.env.KLAUDIUS_API_URL??po).replace(/\/$/,"")+fo,a=ge(),i;try{i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:a,hostname:Nt(),os:`${$t()}-${Lt()}`,cli_version:mo})})}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=[Nt(),uo().username,$t(),Lt()].join("|");return co("sha256").update(e).digest("hex").slice(0,32)}import{readFile as ho}from"fs/promises";import{join as go}from"path";async function re(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${T(n)}`}}}async function Dt(e){let t;try{t=await ho(go(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(o){return{ok:!1,message:`Could not read scripts/schema.sql: ${o.message}`}}let n=e.pat.replace(/\s+/g,"");try{let o=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(o.ok)return{ok:!0};let a=await o.text();return a.includes("already exists")||a.includes('relation "clients" already exists')||a.includes("duplicate")?(s.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${o.status}): ${a.slice(0,300)}`}}catch(o){return{ok:!1,message:`Schema apply failed: ${o.message}`}}}async function $e(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${T(t)}`}}}var Ut="https://api.cloudflare.com/client/v4";function jt(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Le(e){let{token:t,accountId:n}=e,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let a=await fetch(`${Ut}/user/tokens/verify`,{headers:o});if(a.status===401||a.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${a.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} verifying the token. Try again or check cloudflarestatus.com.`};let i=await a.json(),l=i.result?.status;if(i.success===!1||l&&l!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${l?` (status: ${l})`:""}. ${jt(i)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${T(a)}`}}try{let a=await fetch(`${Ut}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:o});if(a.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(a.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let i=await a.json();return i.success===!1?{ok:!1,message:jt(i)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(i.result)?i.result.length:void 0}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${T(a)}`}}}var Ht="https://api.netlify.com/api/v1";async function Me(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let o=await fetch(`${Ht}/user`,{headers:n});if(o.status===401||o.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!o.ok)return{ok:!1,message:`Netlify API returned HTTP ${o.status} verifying the token. Try again or check netlifystatus.com.`}}catch(o){return{ok:!1,message:`Could not reach Netlify: ${T(o)}`}}try{let o=await fetch(`${Ht}/accounts`,{headers:n});if(!o.ok)return{ok:!1,message:`Netlify API returned HTTP ${o.status} listing your teams. Try again or check netlifystatus.com.`};let a=await o.json(),i=Array.isArray(a)?a:[];if(i.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let l=typeof i[0]?.slug=="string"?i[0].slug:void 0;return{ok:!0,accountCount:i.length,accountSlug:l}}catch(o){return{ok:!1,message:`Could not reach Netlify: ${T(o)}`}}}async function le(e){let t=dt(e);if(t)return{ok:!1,message:t};let n=z(e),o=n.value,a=i=>{let l=[i],c=ut(e);return c&&l.push(c),n.repairs.length>0&&l.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),l.join(`
17
17
  `)};try{let i=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":o,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(i.ok)return{ok:!0};if(i.status===429)return{ok:!0};let l={};try{l=await i.json()}catch{}let c=l.error?.message??"",p=l.error?.status??"";return i.status===400&&(p==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(c))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:i.status===401||i.status===403?{ok:!1,message:a(c||`Google rejected the key (HTTP ${i.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`)}:{ok:!1,message:a(`Google API returned HTTP ${i.status}${c?`: ${c}`:""}.`)}}catch(i){return{ok:!1,message:`Could not reach Google: ${T(i)}`}}}import yo from"nodemailer";import{ImapFlow as ko}from"imapflow";function Ft(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let o=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")||o.includes("invalid login")?"auth":o.includes("etimedout")||o.includes("timeout")||o.includes("enotfound")||o.includes("getaddrinfo")||o.includes("econnrefused")||o.includes("econnreset")?"network":"other"}async function ce(e){let t=yo.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(o){return{ok:!1,failedAt:"smtp",message:Kt(o,"SMTP"),failureKind:Ft(o)}}finally{t.close()}let n=new ko({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await n.connect(),await n.logout()}catch(o){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Kt(o,"IMAP"),failureKind:Ft(o)}}return{ok:!0}}function Kt(e,t){let n=e instanceof Error?e.message:String(e),o=n.toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.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
20
  \u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${n}`}async function Gt(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let o=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(o.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!o.ok)return{ok:!1,message:`Twilio API returned HTTP ${o.status}. Try again or check status.twilio.com.`};let a=await o.json();return a.status&&a.status!=="active"?{ok:!1,message:`Twilio account is in '${a.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:a.friendly_name}}catch(o){return{ok:!1,message:`Could not reach Twilio: ${T(o)}`}}}import{spawn as wo}from"child_process";async function Vt(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,o=await Eo(n);if(o.code===0)return{ok:!0};let a=o.stderr.toLowerCase();return a.includes("can't get application")||a.includes("isn't running")||a.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:a.includes("(-1728)")||a.includes("not found")||a.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:a.includes("(-1719)")||a.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${o.stderr.trim()||`exit code ${o.code}`}`}}function Eo(e){return new Promise(t=>{let n=wo("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),o="";n.stderr.on("data",a=>{o+=a.toString()}),n.on("close",a=>t({code:a??1,stderr:o})),n.on("error",a=>t({code:1,stderr:a.message}))})}import{spawn as Je}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,Yt=2e3,Po=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Bt(e,t){let n=e+`
21
21
  `+t;return Po.some(o=>o.test(n))}function Wt(e){return new Promise(t=>setTimeout(t,e))}function To(e,t,n){return new Promise(o=>{let a=n.shell?Je([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):Je(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),i="",l="";a.stdout?.on("data",c=>{let p=c.toString();i+=p,process.stdout.write(p)}),a.stderr?.on("data",c=>{let p=c.toString();l+=p,process.stderr.write(p)}),a.on("close",c=>o({code:c??1,stdout:i,stderr:l})),a.on("error",c=>o({code:1,stdout:i,stderr:l+c.message}))})}async function qe(e,t,n){let o={code:0,stdout:"",stderr:""};for(let a=0;a<=de;a++){if(o=await To(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),o.code===0||!Bt(o.stderr,o.stdout))return o;a<de&&(s.detail(`${n.label} failed with a transient network error \u2014 retrying (${a+2}/${de+1})\u2026`),await Wt(Yt))}return o}function bo(e,t,n){return new Promise(o=>{let a=Je(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),i="",l="";a.stdout?.on("data",c=>{i+=c.toString()}),a.stderr?.on("data",c=>{l+=c.toString()}),a.on("close",c=>o({code:c??1,stdout:i,stderr:l})),a.on("error",c=>o({code:1,stdout:i,stderr:l+c.message}))})}var So=[{pattern:/UNABLE_TO_VERIFY_LEAF_SIGNATURE|unable to verify the first certificate/i,hint:"TLS-handshake error \u2014 your machine appears to be intercepting HTTPS (antivirus, corporate proxy, or VPN re-signing traffic with its own root CA). We work around this with NODE_OPTIONS=--use-system-ca, which needs Node 22.15+. Run `node --version` to verify, upgrade if older, then re-run setup."},{pattern:/Microsoft Visual C\+\+ 14\.0 or greater is required/i,hint:"Python tried to compile a package from source and couldn't find the Microsoft C++ Build Tools. The latest Klaudius pins supabase<2.26 to skip the offending dependency entirely. Re-run with `npx klaudius@latest init` (pulls the latest) \u2014 that should bypass the source build."}];function _o(e){let t=`${e.stderr??""}
22
22
  ${e.stdout??""}`;return So.find(o=>o.pattern.test(t))?.hint}async function Io(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],a=(await he())?.command??["python3"],i=async c=>{let p={code:0,stdout:"",stderr:""};for(let m=0;m<=de;m++){if(p=await bo(a[0],[...a.slice(1),...c],{cwd:e}),p.code===0||!Bt(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 Wt(Yt))}return p},l=await i([...n,"--break-system-packages",...t]);return l.code!==0&&/no such option:.*break-system-packages/i.test(l.stderr)&&(s.detail("Older pip detected; retrying without --break-system-packages"),l=await i([...n,...t])),l.code!==0&&(l.stderr.trim()&&process.stderr.write(l.stderr),l.stdout.trim()&&process.stdout.write(l.stdout)),l}async function De(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=Ao(),o=process.platform==="win32",a=(m,r)=>{let E=_o(r);E&&((t.hints??={})[m]=E)};s.step("Running npm install (Next.js, Playwright JS, etc.)...");let i=await qe("npm",["install"],{cwd:e,label:"npm install",env:n,shell:o});t.npm=i.code===0?"ok":"failed",i.code!==0&&a("npm",i),s.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await Io(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 qe("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:o});t.playwright=c.code===0?"ok":"failed",c.code!==0&&a("playwright",c),s.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await qe("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:o});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&a("patchright",p),t}import{mkdir as Co,readFile as Ro,writeFile as Oo}from"fs/promises";import{join as zt}from"path";async function Ue(e,t){let n=zt(e,".claude");await Co(n,{recursive:!0});let o=zt(n,"settings.json"),a={};try{let p=await Ro(o,"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 Oo(o,JSON.stringify(c,null,2)+`
23
- `,"utf-8")}var Jt="0.21.0",b=5;function ne(e){return`npx klaudius@latest init ${je(ue(e))}`}function ue(e){if(process.platform==="win32")return e;let t=xo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Lo(e){let t=[];try{let o=(await Qt(e,{withFileTypes:!0})).filter(a=>a.isDirectory()&&!a.name.startsWith(".")).slice(0,200);for(let a of o){let i=F(e,a.name);if(!await Xt(F(i,".env")))continue;let l=await Xt(F(i,".klaudius","manifest.json"));if(t.push({path:i,finished:l}),t.length>=3)break}}catch{}return t}async function Xt(e){try{return await Ze(e),!0}catch{return!1}}function je(e){return/\s/.test(e)?`"${e}"`:e}function X(e,t,n){s.blank(),s.error(`${t} validation failed ${b} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${n}`),s.blank(),s.detail("Your credentials are saved in `.env`. Two ways forward:"),s.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),s.blank(),console.log(` ${d.cyan(ne(e))}`),s.blank(),s.detail(` (Your .env is at ${ue(F(e,".env"))} \u2014 open it in any text editor.)`),s.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),s.blank(),process.exit(1)}async function en(e){let t=e.target??".",n=No(t)?t:vo(process.cwd(),t),o=jo(n);o&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${n}`),s.detail(`Reason: ${o}`),s.blank(),s.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),s.blank(),process.platform==="win32"?(s.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${d.cyan("cd $HOME\\Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)):(s.detail("For example:"),console.log(` ${d.cyan("cd ~/Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)),s.blank(),process.exit(1)),process.platform==="win32"&&Ho()&&(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 Ne("init",Jt);let a=await Mo(n);if(a.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${d.bold(n)}.`),s.detail("(Your .env and project files are in place.)"),s.blank(),a.nodeModulesMissing?(s.detail("It looks like a previous setup didn't finish installing dependencies."),s.detail("To pick up where it left off, run:"),s.blank(),n!==process.cwd()&&console.log(` ${d.cyan(`cd ${je(t)}`)}`),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Everything is scaffolded and dependencies look installed."),s.detail("Pick the action you wanted:"),s.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius@latest configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius@latest update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),s.blank()),s.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),s.blank();return}if(a.kind==="occupied"){let u=t===".",h=await Lo(n);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(n)}`),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: ${n}`),s.detail(`Contains: ${a.entries.slice(0,5).join(", ")}${a.entries.length>5?`, \u2026 (+${a.entries.length-5} more)`:""}`),s.blank(),u?(s.detail("Two ways forward:"),s.blank(),s.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`),s.blank(),s.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(s.detail(`The folder '${t}' already exists and isn't empty.`),s.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius@latest init ${t}-2`)}`),s.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let i=await Uo(e.license),l=k.spinner();l.start("Validating license");let c=await Mt(i);c.ok||(l.stop(`License invalid: ${c.reason??"unknown"}`,2),s.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),l.stop(`License valid (${c.tier??"core"} tier)`);let p=await se();p.ok||(s.error(p.message??"Python version check failed."),s.blank(),s.detail(`Once you've installed Python 3.10+, re-run the same command: ${ne(n)}`),process.exit(1));let m=q();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(n)}`),process.exit(1));let r,E=!1;if(a.kind==="partial")if(await Do(n)==="resume"){let h=await qt(a.envPath,"utf-8"),f=ze(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,E=!0):(s.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await _())}else{let h=await qt(a.envPath,"utf-8"),f=ze(D(h));r=await _(f??{})}else r=await _();r.licenseKey=i,await C(n,r),E||(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=k.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>=b&&X(n,"Supabase",f.message??"Supabase check failed");let w=f.message??"Supabase check failed";s.blank(),s.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${u+1} of ${b})`),s.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await _(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
23
+ `,"utf-8")}var Jt="0.21.2",b=5;function ne(e){return`npx klaudius@latest init ${je(ue(e))}`}function ue(e){if(process.platform==="win32")return e;let t=xo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Lo(e){let t=[];try{let o=(await Qt(e,{withFileTypes:!0})).filter(a=>a.isDirectory()&&!a.name.startsWith(".")).slice(0,200);for(let a of o){let i=F(e,a.name);if(!await Xt(F(i,".env")))continue;let l=await Xt(F(i,".klaudius","manifest.json"));if(t.push({path:i,finished:l}),t.length>=3)break}}catch{}return t}async function Xt(e){try{return await Ze(e),!0}catch{return!1}}function je(e){return/\s/.test(e)?`"${e}"`:e}function X(e,t,n){s.blank(),s.error(`${t} validation failed ${b} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${n}`),s.blank(),s.detail("Your credentials are saved in `.env`. Two ways forward:"),s.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),s.blank(),console.log(` ${d.cyan(ne(e))}`),s.blank(),s.detail(` (Your .env is at ${ue(F(e,".env"))} \u2014 open it in any text editor.)`),s.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),s.blank(),process.exit(1)}async function en(e){let t=e.target??".",n=No(t)?t:vo(process.cwd(),t),o=jo(n);o&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${n}`),s.detail(`Reason: ${o}`),s.blank(),s.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),s.blank(),process.platform==="win32"?(s.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${d.cyan("cd $HOME\\Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)):(s.detail("For example:"),console.log(` ${d.cyan("cd ~/Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)),s.blank(),process.exit(1)),process.platform==="win32"&&Ho()&&(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 Ne("init",Jt);let a=await Mo(n);if(a.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${d.bold(n)}.`),s.detail("(Your .env and project files are in place.)"),s.blank(),a.nodeModulesMissing?(s.detail("It looks like a previous setup didn't finish installing dependencies."),s.detail("To pick up where it left off, run:"),s.blank(),n!==process.cwd()&&console.log(` ${d.cyan(`cd ${je(t)}`)}`),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Everything is scaffolded and dependencies look installed."),s.detail("Pick the action you wanted:"),s.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius@latest configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius@latest update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),s.blank()),s.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),s.blank();return}if(a.kind==="occupied"){let u=t===".",h=await Lo(n);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(n)}`),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: ${n}`),s.detail(`Contains: ${a.entries.slice(0,5).join(", ")}${a.entries.length>5?`, \u2026 (+${a.entries.length-5} more)`:""}`),s.blank(),u?(s.detail("Two ways forward:"),s.blank(),s.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`),s.blank(),s.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(s.detail(`The folder '${t}' already exists and isn't empty.`),s.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius@latest init ${t}-2`)}`),s.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let i=await Uo(e.license),l=k.spinner();l.start("Validating license");let c=await Mt(i);c.ok||(l.stop(`License invalid: ${c.reason??"unknown"}`,2),s.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),l.stop(`License valid (${c.tier??"core"} tier)`);let p=await se();p.ok||(s.error(p.message??"Python version check failed."),s.blank(),s.detail(`Once you've installed Python 3.10+, re-run the same command: ${ne(n)}`),process.exit(1));let m=q();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(n)}`),process.exit(1));let r,E=!1;if(a.kind==="partial")if(await Do(n)==="resume"){let h=await qt(a.envPath,"utf-8"),f=ze(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,E=!0):(s.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await _())}else{let h=await qt(a.envPath,"utf-8"),f=ze(D(h));r=await _(f??{})}else r=await _();r.licenseKey=i,await C(n,r),E||(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=k.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>=b&&X(n,"Supabase",f.message??"Supabase check failed");let w=f.message??"Supabase check failed";s.blank(),s.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${u+1} of ${b})`),s.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),s.blank(),r=await _(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
24
24
  ${w}
25
25
 
26
26
  Re-enter the URL, secret key, or PAT below. Press Enter on any
@@ -78,7 +78,7 @@ Re-enter the bot token or chat_id below.
78
78
  Press Enter on any field to keep its current value.`}),await C(n,r),(r.notifyChannel??"telegram")!=="telegram"||!r.telegramBotToken||!r.telegramChatId)){s.success("Skipped Telegram. Setup will continue."),h=!0;break}}}s.blank();let A=k.spinner();A.start("Downloading Klaudius template");let v;try{v=(await ve({licenseKey:i,machineId:ge(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:r.aiAgent,destDir:n})).filesExtracted,A.stop(`Downloaded ${v} files into ${d.bold(n)}`)}catch(u){A.stop(u.message,2);let 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(F(n,"clients"),{recursive:!0});let ke=await Ct(n);await Oe(n,_t(Jt,ke)),s.success("Wrote .klaudius/manifest.json");let $=!1,Z="";if(e.skipSchema)s.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),s.detail(`Apply manually later via the SQL editor: ${r.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+r.supabaseProjectRef+"/sql/new").replace(r.supabaseProjectRef+".supabase.co","")}`);else{s.blank();let u=k.spinner();u.start("Applying schema to Supabase");let h=await Dt({projectRoot:n,pat:r.supabasePat,projectRef:r.supabaseProjectRef});h.ok?u.stop("Schema applied (or already present)"):(u.stop(h.message??"Schema apply failed",2),$=!0,Z=`https://supabase.com/dashboard/project/${r.supabaseProjectRef}/sql/new`)}let P=[],j={};if(e.skipInstall)s.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{s.blank(),s.heading("Installing dependencies");let u=await De(n);s.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&P.push("npm"),u.pip==="failed"&&P.push("pip"),u.playwright==="failed"&&P.push("playwright"),u.patchright==="failed"&&P.push("patchright"),j=u.hints??{}}let O=r.outreachEnabled&&r.outreachPriority?.includes("whatsapp")&&(r.whatsappAccounts?.length??0)>0,g=!e.skipInstall&&!P.includes("npm");if(O&&g){s.blank(),s.heading("Linking WhatsApp accounts"),console.log(d.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
79
79
  phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
80
80
  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=Zt(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:n,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(O&&!g){s.blank(),console.log(d.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let u of r.whatsappAccounts)console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${u}`))}s.blank();let L=[...P,...$?["schema"]:[]];if(L.length>0){k.outro(d.yellow(d.bold(`Setup paused \u2014 ${L.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),s.blank();for(let[H,we]of Object.entries(j))console.log(d.yellow(`Likely cause of ${H} failure:`)),console.log(d.dim(` ${we}`)),s.blank();let u=n!==process.cwd()&&e.target?` ${d.cyan(`cd ${je(e.target)}`)}
81
- `:"",h=r.aiAgent==="codex"?"codex":"claude",f=r.aiAgent==="codex"?"Codex":"Claude Code",w=r.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";P.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan(h)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${P.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(d.dim(` (Don't have ${f} yet? Install with: \`${w}\`)`)),s.blank(),console.log(d.dim("Or do it yourself:")),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify everything")}`),s.blank()),$&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(Z)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),P.includes("pip")&&!j.pip&&(console.log(d.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(d.dim(`Python 3.10+. Install a newer one from ${Fo()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),s.blank());let I=["npm","playwright","patchright"].filter(H=>P.includes(H)&&!j[H]);if(I.length>0){let H=I.length===1?"keeps":"keep";console.log(d.dim(`If ${I.join(" / ")} ${H} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}y&&(console.log(d.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${f}`)),console.log(d.dim("to finish setting it up \u2014 your email details are saved in .env.")),s.blank()),console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}if(Ko(r,n,e.target),y){let u=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(d.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(d.dim(`Your details are saved in .env. To finish it, ask ${u}:`)),console.log(d.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(d.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(d.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(d.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(d.cyan(' and send a test email to my own address to confirm."')),r.outreachEnabled&&(r.outreachChannels??[]).length>0&&(s.blank(),console.log(d.yellow(`Note: your other channel(s) \u2014 ${(r.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),s.blank()}}async function C(e,t){await Qe(e,{recursive:!0}),await Xe(F(e,".env"),_e(t),"utf-8"),t.aiAgent==="codex"?(await Qe(F(e,".codex"),{recursive:!0}),await Xe(F(e,".codex","config.toml"),Ce(t),"utf-8")):(await Xe(F(e,".mcp.json"),Ie(t),"utf-8"),await Ue(e,"supabase"))}async function Mo(e){try{(await Ze(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Qt(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let o=new Set([".env",".mcp.json",".claude",".codex"]),a=n.every(c=>o.has(c)),i=n.includes(".env"),l=t.includes(".klaudius");if(a&&i&&!l)return{kind:"partial",envPath:F(e,".env")};if(l&&i){let c=!0;try{c=!(await Ze(F(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function Do(e){s.blank(),s.warn(`Found a partial setup at ${d.bold(e)}.`),s.detail(`A previous init wrote ${d.bold(".env")} but didn't finish scaffolding.`),s.blank();let t=await k.select({message:`How would you like to proceed? ${d.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return k.isCancel(t)&&(k.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Uo(e){if(e&&e.trim().length>0)return e;k.intro("Klaudius");let t=await k.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return k.isCancel(t)&&(k.cancel("Setup cancelled. No files written."),process.exit(0)),t}function jo(e){let t=$o(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let o of n)if(t.startsWith(o))return`Inside ${o.slice(0,-1)} (system-managed directory).`}}function Ho(){if(process.platform!=="win32")return!1;try{return Zt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Fo(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Ko(e,t,n){let o=e.aiAgent==="codex"?"codex":"claude",a=e.aiAgent==="codex"?"Codex":"Claude Code";if(k.outro(d.green(d.bold("Project ready."))),console.log(d.bold("Next steps:")),s.blank(),t!==process.cwd()&&n){let i=`cd ${je(n)}`;console.log(` ${d.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${d.dim("# go into your project folder")}`)}console.log(` ${d.cyan(o)}${" ".repeat(Math.max(1,27-o.length))}${d.dim(`# opens ${a} in this project`)}`),s.blank(),console.log(d.bold(`Some starter prompts for ${a}:`)),s.blank(),console.log(` ${d.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${d.cyan(`I know I'm ready to start using Klaudius."`)}`),s.blank(),console.log(` ${d.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),s.blank(),console.log(` ${d.cyan('"Run the pipeline for one client."')}`),console.log(d.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),s.blank(),e.aiAgent!=="codex"&&(console.log(d.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(d.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),s.blank())}import{access as Go,readFile as Vo}from"fs/promises";import{join as et,resolve as Yo}from"path";import N from"picocolors";async function nn(e){let t=e.target?Yo(process.cwd(),e.target):process.cwd(),n=await tn(et(t,".env")),o=await tn(et(t,"package.json"));(!n||!o)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),n||s.detail("Missing: .env"),o||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let a="claude-code";try{D(await Vo(et(t,".env"),"utf-8")).AI_AGENT==="codex"&&(a="codex")}catch{}s.heading("Installing dependencies");let i=await De(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,E]of Object.entries(i.hints??{}))console.log(N.yellow(`Likely cause of ${r} failure:`)),console.log(N.dim(` ${E}`)),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 tn(e){try{return await Go(e),!0}catch{return!1}}import{readFile as Bo,writeFile as tt,access as Wo}from"fs/promises";import{join as pe}from"path";import*as He from"@clack/prompts";import V from"picocolors";import{mkdir as zo}from"fs/promises";async function on(e){let t=e.projectRoot??process.cwd(),n=pe(t,".env"),o=pe(t,".mcp.json"),a=pe(t,".codex","config.toml"),i=await nt(pe(t,".klaudius","manifest.json")),l=await nt(n);!i&&!l&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=q();c.ok||(s.error(c.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let p={};try{let A=await Bo(n,"utf-8");p=D(A)}catch{s.warn("No .env found. Starting from an empty configuration.")}let m=Pt(p);Object.keys(p).length>0&&(m.pipelineModes??=["classic"]),He.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let r=await _(m),E=m.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==E&&(s.error(`Switching AI coding agent (${E} \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 A=await re({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});A.ok||(s.error(A.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let y=z(r.googlePlacesApiKey??"");if(y.changed&&r.googlePlacesApiKey){s.heading("Checking your Google Places API key");let A=await le(r.googlePlacesApiKey);if(A.ok){if(y.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let v of y.repairs)s.detail(` ${v}`);s.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=y.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(A.message??"Google rejected the Google Places API key"),s.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),s.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}await tt(n,_e(r),"utf-8"),s.success("Updated .env"),r.aiAgent==="codex"?(await zo(pe(t,".codex"),{recursive:!0}),await tt(a,Ce(r),"utf-8"),s.success("Updated .codex/config.toml")):(await tt(o,Ie(r),"utf-8"),s.success("Updated .mcp.json"),await Ue(t,"supabase")),s.blank(),He.outro(V.green("Configuration updated.")),await qo(t,i)}async function qo(e,t){let n=await nt(pe(e,"node_modules"));s.blank(),t?n||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${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 nt(e){try{return await Wo(e),!0}catch{return!1}}import{copyFile as sn,mkdir as an,readFile as Jo,rm as ye,writeFile as rn,access as ln}from"fs/promises";import{dirname as cn,join as U}from"path";import{tmpdir as Xo}from"os";import*as fe from"@clack/prompts";import ot from"picocolors";var Fe="0.21.0";async function dn(e){let t=e.projectRoot??process.cwd(),n=await St(t);n||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let g of Re)delete n.files[g];let o,a=U(t,".env"),i,l;try{i=await Jo(a,"utf-8"),l=D(i)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}o=l.KLAUDIUS_LICENSE_KEY??"",o||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius@latest init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=At(i,l,Et);c!==null&&(await rn(a,c,"utf-8"),s.detail("Backfilled new env keys")),await Ne("update",Fe),fe.intro(`Update from ${n.templateVersion} \u2192 ${Fe}`);let m=l.AI_AGENT==="codex"?"codex":"claude-code",r=U(Xo(),`klaudius-update-${process.pid}-${Date.now()}`),E;try{s.heading("Downloading the latest Klaudius template");let g=await ve({licenseKey:o,machineId:ge(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:m,destDir:r});s.success(`Fetched ${g.filesExtracted} canonical files`),E=r}catch(g){s.error(g.message),s.detail("Update aborted. Your project is unchanged."),await ye(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let y=await Qo(E,t,n),A=y.filter(g=>g.state==="new"),v=y.filter(g=>g.state==="clean-update"),ke=y.filter(g=>g.state==="user-only"),$=y.filter(g=>g.state==="conflict"),Z=y.filter(g=>g.state==="no-change"),P=y.filter(g=>g.state==="removed-clean"),j=y.filter(g=>g.state==="removed-modified"),O=[...$,...j];if(s.blank(),s.heading("Change summary"),s.detail(`${Y(Z.length,"file")} unchanged`),s.detail(`${Y(A.length,"new file")}`),s.detail(`${Y(v.length,"file")} updated cleanly (no local edits)`),s.detail(`${Y(ke.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${Y(P.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${Y($.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${Y(j.length,"file")} removed upstream but edited locally (need your decision)`),A.length===0&&v.length===0&&P.length===0&&O.length===0){s.blank(),fe.outro(ot.green("Already up to date.")),await ye(r,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let g of[...A,...v]){let L=U(E,g.path),u=U(t,g.path);await an(cn(u),{recursive:!0}),await sn(L,u),n.files[g.path]=g.canonicalHash}A.length+v.length>0&&s.success(`Wrote ${Y(A.length+v.length,"file")}`);for(let g of P){let L=U(t,g.path);await ye(L,{force:!0}),delete n.files[g.path]}if(P.length>0&&s.success(`Deleted ${Y(P.length,"file")} removed upstream`),O.length>0){s.blank(),s.heading(`${O.length} conflict(s) need resolution`);let g=U(t,".klaudius","incoming");try{await ye(g,{recursive:!0,force:!0})}catch{}for(let L of $){let u=U(E,L.path),h=U(g,L.path);await an(cn(h),{recursive:!0}),await sn(u,h)}await rn(U(t,".klaudius","conflicts.md"),Zo(O,n.templateVersion,Fe),"utf-8"),$.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}if(n.updatedAt=new Date().toISOString(),O.length===0&&(n.templateVersion=Fe),await Oe(t,n),s.blank(),O.length===0)fe.outro(ot.green("Update complete."));else{let g=m==="codex"?"Codex":"Claude Code";fe.outro(ot.yellow(`${O.length} conflict(s) staged. Open ${g} in this project and ask:
81
+ `:"",h=r.aiAgent==="codex"?"codex":"claude",f=r.aiAgent==="codex"?"Codex":"Claude Code",w=r.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";P.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan(h)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${P.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(d.dim(` (Don't have ${f} yet? Install with: \`${w}\`)`)),s.blank(),console.log(d.dim("Or do it yourself:")),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify everything")}`),s.blank()),$&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(Z)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),P.includes("pip")&&!j.pip&&(console.log(d.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(d.dim(`Python 3.10+. Install a newer one from ${Fo()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),s.blank());let I=["npm","playwright","patchright"].filter(H=>P.includes(H)&&!j[H]);if(I.length>0){let H=I.length===1?"keeps":"keep";console.log(d.dim(`If ${I.join(" / ")} ${H} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}y&&(console.log(d.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${f}`)),console.log(d.dim("to finish setting it up \u2014 your email details are saved in .env.")),s.blank()),console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}if(Ko(r,n,e.target),y){let u=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(d.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(d.dim(`Your details are saved in .env. To finish it, ask ${u}:`)),console.log(d.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(d.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(d.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(d.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(d.cyan(' and send a test email to my own address to confirm."')),r.outreachEnabled&&(r.outreachChannels??[]).length>0&&(s.blank(),console.log(d.yellow(`Note: your other channel(s) \u2014 ${(r.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),s.blank()}}async function C(e,t){await Qe(e,{recursive:!0}),await Xe(F(e,".env"),_e(t),"utf-8"),t.aiAgent==="codex"?(await Qe(F(e,".codex"),{recursive:!0}),await Xe(F(e,".codex","config.toml"),Ce(t),"utf-8")):(await Xe(F(e,".mcp.json"),Ie(t),"utf-8"),await Ue(e,"supabase"))}async function Mo(e){try{(await Ze(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Qt(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let o=new Set([".env",".mcp.json",".claude",".codex"]),a=n.every(c=>o.has(c)),i=n.includes(".env"),l=t.includes(".klaudius");if(a&&i&&!l)return{kind:"partial",envPath:F(e,".env")};if(l&&i){let c=!0;try{c=!(await Ze(F(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function Do(e){s.blank(),s.warn(`Found a partial setup at ${d.bold(e)}.`),s.detail(`A previous init wrote ${d.bold(".env")} but didn't finish scaffolding.`),s.blank();let t=await k.select({message:`How would you like to proceed? ${d.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return k.isCancel(t)&&(k.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Uo(e){if(e&&e.trim().length>0)return e;k.intro("Klaudius");let t=await k.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return k.isCancel(t)&&(k.cancel("Setup cancelled. No files written."),process.exit(0)),t}function jo(e){let t=$o(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let o of n)if(t.startsWith(o))return`Inside ${o.slice(0,-1)} (system-managed directory).`}}function Ho(){if(process.platform!=="win32")return!1;try{return Zt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Fo(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Ko(e,t,n){let o=e.aiAgent==="codex"?"codex":"claude",a=e.aiAgent==="codex"?"Codex":"Claude Code";if(k.outro(d.green(d.bold("Project ready."))),console.log(d.bold("Next steps:")),s.blank(),t!==process.cwd()&&n){let i=`cd ${je(n)}`;console.log(` ${d.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${d.dim("# go into your project folder")}`)}console.log(` ${d.cyan(o)}${" ".repeat(Math.max(1,27-o.length))}${d.dim(`# opens ${a} in this project`)}`),s.blank(),console.log(d.bold(`Some starter prompts for ${a}:`)),s.blank(),console.log(` ${d.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${d.cyan(`I know I'm ready to start using Klaudius."`)}`),s.blank(),console.log(` ${d.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),s.blank(),console.log(` ${d.cyan('"Run the pipeline for one client."')}`),console.log(d.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),s.blank(),e.aiAgent!=="codex"&&(console.log(d.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(d.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),s.blank())}import{access as Go,readFile as Vo}from"fs/promises";import{join as et,resolve as Yo}from"path";import N from"picocolors";async function nn(e){let t=e.target?Yo(process.cwd(),e.target):process.cwd(),n=await tn(et(t,".env")),o=await tn(et(t,"package.json"));(!n||!o)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),n||s.detail("Missing: .env"),o||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let a="claude-code";try{D(await Vo(et(t,".env"),"utf-8")).AI_AGENT==="codex"&&(a="codex")}catch{}s.heading("Installing dependencies");let i=await De(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,E]of Object.entries(i.hints??{}))console.log(N.yellow(`Likely cause of ${r} failure:`)),console.log(N.dim(` ${E}`)),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 tn(e){try{return await Go(e),!0}catch{return!1}}import{readFile as Bo,writeFile as tt,access as Wo}from"fs/promises";import{join as pe}from"path";import*as He from"@clack/prompts";import V from"picocolors";import{mkdir as zo}from"fs/promises";async function on(e){let t=e.projectRoot??process.cwd(),n=pe(t,".env"),o=pe(t,".mcp.json"),a=pe(t,".codex","config.toml"),i=await nt(pe(t,".klaudius","manifest.json")),l=await nt(n);!i&&!l&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=q();c.ok||(s.error(c.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let p={};try{let A=await Bo(n,"utf-8");p=D(A)}catch{s.warn("No .env found. Starting from an empty configuration.")}let m=Pt(p);Object.keys(p).length>0&&(m.pipelineModes??=["classic"]),He.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let r=await _(m),E=m.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==E&&(s.error(`Switching AI coding agent (${E} \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 A=await re({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});A.ok||(s.error(A.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let y=z(r.googlePlacesApiKey??"");if(y.changed&&r.googlePlacesApiKey){s.heading("Checking your Google Places API key");let A=await le(r.googlePlacesApiKey);if(A.ok){if(y.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let v of y.repairs)s.detail(` ${v}`);s.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=y.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(A.message??"Google rejected the Google Places API key"),s.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),s.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}await tt(n,_e(r),"utf-8"),s.success("Updated .env"),r.aiAgent==="codex"?(await zo(pe(t,".codex"),{recursive:!0}),await tt(a,Ce(r),"utf-8"),s.success("Updated .codex/config.toml")):(await tt(o,Ie(r),"utf-8"),s.success("Updated .mcp.json"),await Ue(t,"supabase")),s.blank(),He.outro(V.green("Configuration updated.")),await qo(t,i)}async function qo(e,t){let n=await nt(pe(e,"node_modules"));s.blank(),t?n||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${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 nt(e){try{return await Wo(e),!0}catch{return!1}}import{copyFile as sn,mkdir as an,readFile as Jo,rm as ye,writeFile as rn,access as ln}from"fs/promises";import{dirname as cn,join as U}from"path";import{tmpdir as Xo}from"os";import*as fe from"@clack/prompts";import ot from"picocolors";var Fe="0.21.2";async function dn(e){let t=e.projectRoot??process.cwd(),n=await St(t);n||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let g of Re)delete n.files[g];let o,a=U(t,".env"),i,l;try{i=await Jo(a,"utf-8"),l=D(i)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}o=l.KLAUDIUS_LICENSE_KEY??"",o||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius@latest init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=At(i,l,Et);c!==null&&(await rn(a,c,"utf-8"),s.detail("Backfilled new env keys")),await Ne("update",Fe),fe.intro(`Update from ${n.templateVersion} \u2192 ${Fe}`);let m=l.AI_AGENT==="codex"?"codex":"claude-code",r=U(Xo(),`klaudius-update-${process.pid}-${Date.now()}`),E;try{s.heading("Downloading the latest Klaudius template");let g=await ve({licenseKey:o,machineId:ge(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:m,destDir:r});s.success(`Fetched ${g.filesExtracted} canonical files`),E=r}catch(g){s.error(g.message),s.detail("Update aborted. Your project is unchanged."),await ye(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let y=await Qo(E,t,n),A=y.filter(g=>g.state==="new"),v=y.filter(g=>g.state==="clean-update"),ke=y.filter(g=>g.state==="user-only"),$=y.filter(g=>g.state==="conflict"),Z=y.filter(g=>g.state==="no-change"),P=y.filter(g=>g.state==="removed-clean"),j=y.filter(g=>g.state==="removed-modified"),O=[...$,...j];if(s.blank(),s.heading("Change summary"),s.detail(`${Y(Z.length,"file")} unchanged`),s.detail(`${Y(A.length,"new file")}`),s.detail(`${Y(v.length,"file")} updated cleanly (no local edits)`),s.detail(`${Y(ke.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${Y(P.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${Y($.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${Y(j.length,"file")} removed upstream but edited locally (need your decision)`),A.length===0&&v.length===0&&P.length===0&&O.length===0){s.blank(),fe.outro(ot.green("Already up to date.")),await ye(r,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let g of[...A,...v]){let L=U(E,g.path),u=U(t,g.path);await an(cn(u),{recursive:!0}),await sn(L,u),n.files[g.path]=g.canonicalHash}A.length+v.length>0&&s.success(`Wrote ${Y(A.length+v.length,"file")}`);for(let g of P){let L=U(t,g.path);await ye(L,{force:!0}),delete n.files[g.path]}if(P.length>0&&s.success(`Deleted ${Y(P.length,"file")} removed upstream`),O.length>0){s.blank(),s.heading(`${O.length} conflict(s) need resolution`);let g=U(t,".klaudius","incoming");try{await ye(g,{recursive:!0,force:!0})}catch{}for(let L of $){let u=U(E,L.path),h=U(g,L.path);await an(cn(h),{recursive:!0}),await sn(u,h)}await rn(U(t,".klaudius","conflicts.md"),Zo(O,n.templateVersion,Fe),"utf-8"),$.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}if(n.updatedAt=new Date().toISOString(),O.length===0&&(n.templateVersion=Fe),await Oe(t,n),s.blank(),O.length===0)fe.outro(ot.green("Update complete."));else{let g=m==="codex"?"Codex":"Claude Code";fe.outro(ot.yellow(`${O.length} conflict(s) staged. Open ${g} in this project and ask:
82
82
  "Run /resolve-conflicts"`))}await ye(r,{recursive:!0,force:!0}).catch(()=>{})}async function Qo(e,t,n){let o=await ae(e),a=new Set(o),i=[];for(let l of o){let c=await ie(U(e,l)),p=n.files[l],m=U(t,l),r;try{await ln(m),r=await ie(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(n.files)){if(a.has(l))continue;let c=n.files[l],p=U(t,l),m;try{await ln(p),m=await ie(p)}catch{delete n.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 Y(e,t){return`${e} ${t}${e===1?"":"s"}`}function Zo(e,t,n){let o=e.filter(c=>c.state==="conflict").length,a=e.filter(c=>c.state==="removed-modified").length,i=[];i.push("# Update Conflicts"),i.push(""),i.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),i.push(`Updating from canonical version **${t}** to **${n}**.`),i.push("");let l=[];o>0&&l.push(`${o} file${o===1?"":"s"} ha${o===1?"s":"ve"} BOTH local edits AND upstream changes`),a>0&&l.push(`${a} file${a===1?"":"s"} ${a===1?"was":"were"} removed upstream but edited locally`),i.push(l.join(", and ")+"."),i.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),i.push(""),i.push("---"),i.push("");for(let c of e)i.push(`## ${c.path}`),i.push(""),c.state==="removed-modified"?(i.push("**Type:** Removed upstream"),i.push(""),i.push(`- Your local copy: \`${c.path}\``),i.push("- This file no longer exists in the canonical template."),i.push("- You've modified it locally since install."),i.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),i.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),i.push(""),i.push("**Resolution options for the SKILL to walk through:**"),i.push(""),i.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),i.push("2. Delete \u2014 remove the file from disk and from the manifest")):(i.push("**Type:** Edit conflict"),i.push(""),i.push(`- Your version (with your local edits): \`${c.path}\``),i.push(`- New canonical version: \`.klaudius/incoming/${c.path}\``),i.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),i.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),i.push(`- New canonical hash: \`${(c.canonicalHash??"(none)").slice(0,16)}\``),i.push(""),i.push("**Resolution options for the SKILL to walk through:**"),i.push(""),i.push("1. Keep mine \u2014 discard the new canonical changes"),i.push("2. Take canonical \u2014 overwrite my edits with the new version"),i.push("3. Merge \u2014 review both side-by-side and produce a combined version")),i.push(""),i.push("---"),i.push("");return i.join(`
83
83
  `)}import{access as es,readFile as un,stat as ts}from"fs/promises";import{join as G}from"path";import R from"picocolors";import{spawn as pn}from"child_process";async function fn(e){let t=e.projectRoot??process.cwd(),n=[];console.log(R.bold(`Klaudius doctor \u2014 checking your project\u2026
84
84
  `)),n.push(await ns()),n.push(await os());let o=G(t,".env"),a=G(t,".klaudius","manifest.json"),i=G(t,".mcp.json"),l=G(t,".codex","config.toml"),c=await Q(o),p=await Q(a),m="claude-code";if(c)try{D(await un(o,"utf-8")).AI_AGENT==="codex"&&(m="codex")}catch{}if(m==="claude-code"){let y=await Q(G(t,"AGENTS.md")),A=!await Q(G(t,".claude"));y&&A&&(m="codex")}if(n.push({name:".env present",status:c?"ok":"fail",detail:c?o:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."}),n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?"ok":"fail",detail:p?a:"missing",nextAction:p?void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."}),m==="codex"){let y=await Q(l);n.push({name:".codex/config.toml present",status:y?"ok":"warn",detail:y?l:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let y=await Q(i);n.push({name:".mcp.json present",status:y?"ok":"warn",detail:y?i:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await ds(m)),n.push(await ss(t)),n.push(await is(t)),n.push(await as()),!c)n.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)n.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let y=await un(o,"utf-8"),A=D(y);await rs(A,n)}console.log();for(let y of n){let A=y.status==="ok"?R.green("\u2713"):y.status==="warn"?R.yellow("\u26A0"):y.status==="skip"?R.dim("\xB7"):R.red("\u2717");console.log(` ${A} ${y.name}${y.detail?R.dim(` \u2014 ${y.detail}`):""}`),y.nextAction&&console.log(` ${R.dim("\u2192")} ${R.cyan(y.nextAction)}`)}let r=n.filter(y=>y.status==="fail").length,E=n.filter(y=>y.status==="warn").length;console.log(),r===0&&E===0?console.log(R.green(R.bold("Everything checks out. You're good to go."))):r===0?console.log(R.yellow(R.bold(`${E} warning${E===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 es(e),!0}catch{return!1}}async function ns(){let e=await se();return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:"Install Python 3.10+ from https://www.python.org/downloads/"}}async function os(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let n=parseInt(t[1],10),o=parseInt(t[2],10);return n<22||n===22&&o<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function ss(e){let t=G(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 ts(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 is(e){let t=process.platform==="darwin"?G(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?G(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):G(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 as(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
@@ -94,4 +94,4 @@ except Exception as e:
94
94
  `));let i=ps(process.execPath,[n,"pair","--account",a],{cwd:t,stdio:"inherit"});if(i.status===0){console.log(x.green(`Paired '${a}'.`)),console.log(x.dim(`
95
95
  If you haven't already, add '${a}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
96
96
  WHATSAPP_ACCOUNTS=primary,${a}
97
- (Skip this if '${a}' is already there or you set it via the init wizard.)`));return}i.error?console.error(x.red(`Pair failed: ${i.error.message}`)):(console.error(x.red(`Pair did not complete (exit ${i.status??"signalled"}). Common causes:`)),console.error(x.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(x.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(x.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${a}/daemon.log`))),process.exit(i.status??1)}import{spawnSync as hs}from"child_process";var st="--use-system-ca";function gn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(st)||!q().ok)return;let n=e?`${e} ${st}`:st,o=hs(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});o.signal&&(process.kill(process.pid,o.signal),process.exit(1)),process.exit(o.status??1)}gn();var ys="0.21.0",B=new gs;B.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(ys);B.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 gt({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});B.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 en({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});B.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 nn({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});B.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await on({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});B.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await dn({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});B.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 fn({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});B.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 hn({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});B.parse(process.argv);
97
+ (Skip this if '${a}' is already there or you set it via the init wizard.)`));return}i.error?console.error(x.red(`Pair failed: ${i.error.message}`)):(console.error(x.red(`Pair did not complete (exit ${i.status??"signalled"}). Common causes:`)),console.error(x.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(x.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(x.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${a}/daemon.log`))),process.exit(i.status??1)}import{spawnSync as hs}from"child_process";var st="--use-system-ca";function gn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(st)||!q().ok)return;let n=e?`${e} ${st}`:st,o=hs(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});o.signal&&(process.kill(process.pid,o.signal),process.exit(1)),process.exit(o.status??1)}gn();var ys="0.21.2",B=new gs;B.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(ys);B.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 gt({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});B.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 en({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});B.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 nn({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});B.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await on({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});B.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await dn({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});B.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 fn({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});B.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 hn({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});B.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klaudius",
3
- "version": "0.21.0",
3
+ "version": "0.21.2",
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": {
@@ -26,7 +26,7 @@
26
26
  "scripts": {
27
27
  "build": "tsup",
28
28
  "dev": "tsx src/bin.ts",
29
- "test": "npm run build && tsx test/lib-tests.ts && tsx test/masked-prefill-pty-test.ts && tsx test/configure-outro-test.ts && tsx test/init-scaffolded-test.ts",
29
+ "test": "npm run build && tsx test/lib-tests.ts && tsx test/deliverability-tests.ts && tsx test/masked-prefill-pty-test.ts && tsx test/configure-outro-test.ts && tsx test/init-scaffolded-test.ts",
30
30
  "prepublishOnly": "npm run build"
31
31
  },
32
32
  "engines": {