klaudius 0.16.0 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +31 -31
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -1,74 +1,74 @@
1
1
  #!/usr/bin/env node
2
- import{a as Q,b as Ue,c as je,d as _,f as Ke,g as He}from"./chunk-SZ4KCTSL.js";import{a as le,b as Fe,c as Ve,d as ce,e as Ge,i as Be}from"./chunk-ZTT5HVYU.js";import{Command as mo}from"commander";import{spawn as Ht}from"child_process";import T from"picocolors";function G(){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 s=parseInt(t[1],10),n=parseInt(t[2],10),i=parseInt(t[3],10),a=`${s}.${n}.${i}`;return s<22||s===22&&n<15?{ok:!1,version:a,major:s,minor:n,message:`Your installed Node.js is ${a}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:a,major:s,minor:n}}import{spawn as Mt}from"child_process";var se=3,de=10,Ut=[["python3"],["python"],["py","-3"]];async function be(){for(let e of Ut){let t=await Kt(e[0],[...e.slice(1),"--version"]),s=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(s)||t.code!==0)continue;let n=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(s);if(!n)continue;let i=parseInt(n[1],10),a=parseInt(n[2],10),r=n[3]?`${i}.${a}.${n[3]}`:`${i}.${a}`;return{command:[...e],version:r,major:i,minor:a}}return null}async function Z(){let e=jt(),t=await be();if(!t){let r=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${se}.${de}+ is not installed (or not on PATH). Install it from ${e}.`+r}}let{command:s,version:n,major:i,minor:a}=t;return i<se||i===se&&a<de?{ok:!1,version:n,major:i,minor:a,command:s,message:`Your installed Python is ${n}. Klaudius needs Python ${se}.${de} or newer (the pipeline depends on packages that only ship wheels for ${se}.${de}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:n,major:i,minor:a,command:s}}function jt(){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 Kt(e,t){return new Promise(s=>{let n=Mt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";n.stdout?.on("data",r=>{i+=r.toString()}),n.stderr?.on("data",r=>{a+=r.toString()}),n.on("close",r=>s({code:r??1,stdout:i,stderr:a})),n.on("error",()=>s({code:1,stdout:i,stderr:a}))})}var We=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function Ye(e={}){console.log(T.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
- `));let t=[];t.push(Ft());let s=await Z();t.push(Vt(s)),t.push(await Gt(s.command)),t.push(await Bt()),t.push(await Wt());for(let i of t){let a=i.status==="ok"?T.green("\u2713"):T.red("\u2717");console.log(` ${a} ${i.name}${i.detail?T.dim(` \u2014 ${i.detail}`):""}`),i.nextAction&&console.log(` ${T.dim("\u2192")} ${T.cyan(i.nextAction)}`)}console.log();let n=t.filter(i=>i.status==="fail");if(n.length===0){Yt();return}console.log(T.red(T.bold(`${n.length} check${n.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius preflight\`.`))),console.log(),console.log(T.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(T.dim(" user, then re-run `npx klaudius preflight` until every check passes.")),console.log(),process.exitCode=1}function Ft(){let e=G();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 Vt(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 Gt(e){let t=e??["python3"],s=await Te(t[0],[...t.slice(1),"-m","pip","--version"]);return s.code===0?{name:"pip available",status:"ok",detail:(s.stdout||s.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 Bt(){let e=await Te("npm",["--version"]);return e.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 Te("npx",["--version"])).code!==0?{name:"npm / npx available",status:"fail",detail:`npm ${e.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 ${e.stdout.trim()}`}}async function Wt(){try{return await fetch(We,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:We}}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 Yt(){console.log(T.green(T.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(T.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(` ${T.cyan("npx klaudius init my-agency")}`),console.log(),console.log(T.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(T.dim(" run it in a new terminal.")),console.log()}function Te(e,t){return new Promise(s=>{let n=Ht(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";n.stdout?.on("data",r=>{i+=r.toString()}),n.stderr?.on("data",r=>{a+=r.toString()}),n.on("close",r=>s({code:r??1,stdout:i,stderr:a})),n.on("error",()=>s({code:1,stdout:i,stderr:a}))})}import{mkdir as xe,readdir as Rn,readFile as gt,stat as yt,writeFile as Re}from"fs/promises";import{spawnSync as wt}from"child_process";import{resolve as xn,isAbsolute as vn,join as q,normalize as On}from"path";import*as k from"@clack/prompts";import d from"picocolors";import zt from"react";import{render as qt}from"ink";async function I(e={},t={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:s}=await import("./WizardApp-XPK4JB6T.js"),n=null;Q("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),je(),await new Promise(a=>setImmediate(a)),await new Promise(a=>setTimeout(a,0)),Q("runWizard:event loop drained, mounting Ink");let i=qt(zt.createElement(s,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:a=>{Q("runWizard:onComplete called",{keys:Object.keys(a).length}),n=a}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(Q("runWizard:render returned, awaiting exit"),await i.waitUntilExit(),Q("runWizard:waitUntilExit resolved",{resultIsNull:n===null}),!n)throw new Error(`Wizard exited without completing. Diagnostic log: ${Ue}
5
- Please share that file so we can trace what happened.`);return n}var _e="claude-code";function ze(e){if(e==="claude-code"||e==="codex")return e}var Ce="vercel";function qe(e){if(e==="vercel"||e==="cloudflare")return e}function ue(e){let t=[],s=i=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${i}`),t.push("# "+"=".repeat(60)),t.push("")},n=(i,a)=>{if(a==null||a===""){t.push(`# ${i}=`);return}let r=String(a);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(r)){let c=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${i}="${c}"`)}else t.push(`${i}=${r}`)};return t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),s("Klaudius licence"),n("KLAUDIUS_LICENSE_KEY",e.licenseKey),s("AI coding agent"),n("AI_AGENT",e.aiAgent??_e),s("Operating country and language"),n("OPERATOR_COUNTRY",e.country),n("OPERATOR_COUNTRY_CODE",e.countryCode),n("OPERATOR_LANGUAGE",e.language),n("OPERATOR_LANGUAGE_CODE",e.languageCode),s("Pricing"),n("PRICING",e.pricing),n("PRICING_TERMS",e.pricingTerms),n("PRICING_MONTHLY",e.pricingMonthly),s("Automated outreach features"),n("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),n("OPERATOR_NAME",e.name),n("SIGNATURE",e.signature),n("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),n("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),s("Email outreach"),n("EMAIL_ADDRESS",e.emailAddress),n("EMAIL_PASSWORD",e.emailPassword),n("EMAIL_FROM_NAME",e.emailFromName),n("EMAIL_SMTP_HOST",e.emailSmtpHost),n("EMAIL_SMTP_PORT",e.emailSmtpPort),n("EMAIL_IMAP_HOST",e.emailImapHost),n("EMAIL_IMAP_PORT",e.emailImapPort),n("EMAIL_SENT_FOLDER",e.emailSentFolder),n("EMAIL_INBOX_FOLDER",e.emailInboxFolder),s("SMS outreach"),n("SMS_PROVIDER",e.smsProvider),n("TEST_PHONE",e.testPhone),n("TWILIO_ACCOUNT_SID",e.twilioAccountSid),n("TWILIO_AUTH_TOKEN",e.twilioAuthToken),n("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),s("WhatsApp outreach"),n("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),s("Supabase (pipeline state)"),n("SUPABASE_URL",e.supabaseUrl),n("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),n("SUPABASE_PAT",e.supabasePat),n("SUPABASE_PROJECT_REF",e.supabaseProjectRef),s("Deployment"),n("DEPLOY_PROVIDER",e.deployProvider??Ce),n("VERCEL_TOKEN",e.vercelToken),n("VERCEL_SCOPE",e.vercelScope??""),n("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),n("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("Search APIs"),n("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("SERPAPI_KEY",e.serpapiKey),s("Telegram notifications (optional)"),n("TELEGRAM_BOT_TOKEN",e.telegramBotToken),n("TELEGRAM_CHAT_ID",e.telegramChatId),s("Rate limiting (sensible defaults)"),n("REQUESTS_PER_MINUTE",10),n("REQUEST_DELAY",2),t.join(`
2
+ import{a as Q,b as Ue,c as je,d as _,f as Ke,g as He}from"./chunk-SZ4KCTSL.js";import{a as le,b as Fe,c as Ve,d as ce,e as Ge,i as Be}from"./chunk-ZTT5HVYU.js";import{Command as fs}from"commander";import{spawn as Ht}from"child_process";import T from"picocolors";function G(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let o=parseInt(t[1],10),n=parseInt(t[2],10),i=parseInt(t[3],10),a=`${o}.${n}.${i}`;return o<22||o===22&&n<15?{ok:!1,version:a,major:o,minor:n,message:`Your installed Node.js is ${a}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:a,major:o,minor:n}}import{spawn as Mt}from"child_process";var oe=3,de=10,Ut=[["python3"],["python"],["py","-3"]];async function be(){for(let e of Ut){let t=await Kt(e[0],[...e.slice(1),"--version"]),o=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(o)||t.code!==0)continue;let n=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(o);if(!n)continue;let i=parseInt(n[1],10),a=parseInt(n[2],10),r=n[3]?`${i}.${a}.${n[3]}`:`${i}.${a}`;return{command:[...e],version:r,major:i,minor:a}}return null}async function Z(){let e=jt(),t=await be();if(!t){let r=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${oe}.${de}+ is not installed (or not on PATH). Install it from ${e}.`+r}}let{command:o,version:n,major:i,minor:a}=t;return i<oe||i===oe&&a<de?{ok:!1,version:n,major:i,minor:a,command:o,message:`Your installed Python is ${n}. Klaudius needs Python ${oe}.${de} or newer (the pipeline depends on packages that only ship wheels for ${oe}.${de}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:n,major:i,minor:a,command:o}}function jt(){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 Kt(e,t){return new Promise(o=>{let n=Mt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";n.stdout?.on("data",r=>{i+=r.toString()}),n.stderr?.on("data",r=>{a+=r.toString()}),n.on("close",r=>o({code:r??1,stdout:i,stderr:a})),n.on("error",()=>o({code:1,stdout:i,stderr:a}))})}var We=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function Ye(e={}){console.log(T.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
+ `));let t=[];t.push(Ft());let o=await Z();t.push(Vt(o)),t.push(await Gt(o.command)),t.push(await Bt()),t.push(await Wt());for(let i of t){let a=i.status==="ok"?T.green("\u2713"):T.red("\u2717");console.log(` ${a} ${i.name}${i.detail?T.dim(` \u2014 ${i.detail}`):""}`),i.nextAction&&console.log(` ${T.dim("\u2192")} ${T.cyan(i.nextAction)}`)}console.log();let n=t.filter(i=>i.status==="fail");if(n.length===0){Yt();return}console.log(T.red(T.bold(`${n.length} check${n.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(T.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(T.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Ft(){let e=G();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 Vt(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 Gt(e){let t=e??["python3"],o=await Te(t[0],[...t.slice(1),"-m","pip","--version"]);return o.code===0?{name:"pip available",status:"ok",detail:(o.stdout||o.stderr).trim().split(`
4
+ `)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function Bt(){let e=await Te("npm",["--version"]);return e.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 Te("npx",["--version"])).code!==0?{name:"npm / npx available",status:"fail",detail:`npm ${e.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 ${e.stdout.trim()}`}}async function Wt(){try{return await fetch(We,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:We}}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 Yt(){console.log(T.green(T.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(T.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(` ${T.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(T.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(T.dim(" run it in a new terminal.")),console.log()}function Te(e,t){return new Promise(o=>{let n=Ht(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";n.stdout?.on("data",r=>{i+=r.toString()}),n.stderr?.on("data",r=>{a+=r.toString()}),n.on("close",r=>o({code:r??1,stdout:i,stderr:a})),n.on("error",()=>o({code:1,stdout:i,stderr:a}))})}import{mkdir as xe,readdir as Rn,readFile as gt,stat as yt,writeFile as Re}from"fs/promises";import{spawnSync as wt}from"child_process";import{resolve as xn,isAbsolute as vn,join as q,normalize as On}from"path";import*as k from"@clack/prompts";import d from"picocolors";import zt from"react";import{render as qt}from"ink";async function I(e={},t={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius@latest init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:o}=await import("./WizardApp-XPK4JB6T.js"),n=null;Q("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),je(),await new Promise(a=>setImmediate(a)),await new Promise(a=>setTimeout(a,0)),Q("runWizard:event loop drained, mounting Ink");let i=qt(zt.createElement(o,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:a=>{Q("runWizard:onComplete called",{keys:Object.keys(a).length}),n=a}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(Q("runWizard:render returned, awaiting exit"),await i.waitUntilExit(),Q("runWizard:waitUntilExit resolved",{resultIsNull:n===null}),!n)throw new Error(`Wizard exited without completing. Diagnostic log: ${Ue}
5
+ Please share that file so we can trace what happened.`);return n}var _e="claude-code";function ze(e){if(e==="claude-code"||e==="codex")return e}var Ce="vercel";function qe(e){if(e==="vercel"||e==="cloudflare")return e}function ue(e){let t=[],o=i=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${i}`),t.push("# "+"=".repeat(60)),t.push("")},n=(i,a)=>{if(a==null||a===""){t.push(`# ${i}=`);return}let r=String(a);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(r)){let c=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${i}="${c}"`)}else t.push(`${i}=${r}`)};return t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),o("Klaudius licence"),n("KLAUDIUS_LICENSE_KEY",e.licenseKey),o("AI coding agent"),n("AI_AGENT",e.aiAgent??_e),o("Operating country and language"),n("OPERATOR_COUNTRY",e.country),n("OPERATOR_COUNTRY_CODE",e.countryCode),n("OPERATOR_LANGUAGE",e.language),n("OPERATOR_LANGUAGE_CODE",e.languageCode),o("Pricing"),n("PRICING",e.pricing),n("PRICING_TERMS",e.pricingTerms),n("PRICING_MONTHLY",e.pricingMonthly),o("Automated outreach features"),n("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),n("OPERATOR_NAME",e.name),n("SIGNATURE",e.signature),n("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),n("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),o("Email outreach"),n("EMAIL_ADDRESS",e.emailAddress),n("EMAIL_PASSWORD",e.emailPassword),n("EMAIL_FROM_NAME",e.emailFromName),n("EMAIL_SMTP_HOST",e.emailSmtpHost),n("EMAIL_SMTP_PORT",e.emailSmtpPort),n("EMAIL_IMAP_HOST",e.emailImapHost),n("EMAIL_IMAP_PORT",e.emailImapPort),n("EMAIL_SENT_FOLDER",e.emailSentFolder),n("EMAIL_INBOX_FOLDER",e.emailInboxFolder),o("SMS outreach"),n("SMS_PROVIDER",e.smsProvider),n("TEST_PHONE",e.testPhone),n("TWILIO_ACCOUNT_SID",e.twilioAccountSid),n("TWILIO_AUTH_TOKEN",e.twilioAuthToken),n("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),o("WhatsApp outreach"),n("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),o("Supabase (pipeline state)"),n("SUPABASE_URL",e.supabaseUrl),n("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),n("SUPABASE_PAT",e.supabasePat),n("SUPABASE_PROJECT_REF",e.supabaseProjectRef),o("Deployment"),n("DEPLOY_PROVIDER",e.deployProvider??Ce),n("VERCEL_TOKEN",e.vercelToken),n("VERCEL_SCOPE",e.vercelScope??""),n("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),n("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),o("Search APIs"),n("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("SERPAPI_KEY",e.serpapiKey),o("Telegram notifications (optional)"),n("TELEGRAM_BOT_TOKEN",e.telegramBotToken),n("TELEGRAM_CHAT_ID",e.telegramChatId),o("Rate limiting (sensible defaults)"),n("REQUESTS_PER_MINUTE",10),n("REQUEST_DELAY",2),t.join(`
6
6
  `)+`
7
7
  `}function pe(e){let t={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(t,null,2)+`
8
- `}function fe(e){let t=e.supabaseProjectRef,s=Xt(e.supabasePat);return["# Codex MCP config \u2014 generated by `npx klaudius init` / `configure`.","# Edit freely. NEVER commit this file \u2014 .gitignore already excludes it.","# See `.codex/config.toml.example` for the documented format.","","[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${t}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${s}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
9
- `)}function Xt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Xe=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel' or 'cloudflare'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch to Cloudflare Pages, run `npx klaudius configure` (adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID)."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'}];function Jt(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let s=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${s}"`}return`${e}=${t}`}function Je(e,t,s){let n=s.filter(r=>!(r.key in t));if(n.length===0)return null;let i=e.endsWith(`
8
+ `}function fe(e){let t=e.supabaseProjectRef,o=Xt(e.supabasePat);return["# Codex MCP config \u2014 generated by `npx klaudius init` / `configure`.","# Edit freely. NEVER commit this file \u2014 .gitignore already excludes it.","# See `.codex/config.toml.example` for the documented format.","","[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${t}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${o}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
9
+ `)}function Xt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Xe=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel' or 'cloudflare'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch to Cloudflare Pages, run `npx klaudius@latest configure` (adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID)."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'}];function Jt(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let o=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${o}"`}return`${e}=${t}`}function Je(e,t,o){let n=o.filter(r=>!(r.key in t));if(n.length===0)return null;let i=e.endsWith(`
10
10
  `)?"":`
11
11
  `,a=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let r of n)a.push(""),r.comment&&a.push(`# ${r.comment}`),a.push(Jt(r.key,r.value));return e+i+a.join(`
12
12
  `)+`
13
- `}function Qt(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 $(e){let t={};for(let s of e.split(`
14
- `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i===-1)continue;let a=n.slice(0,i).trim(),r=Qt(n.slice(i+1).trim());t[a]=r}return t}function Qe(e){let t=c=>{let p=e[c];if(!p)return;let g=parseInt(p,10);return isNaN(g)?void 0:g},s=e.SMS_PROVIDER,n=c=>c==="email"||c==="sms"||c==="whatsapp",i=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(n),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(n),r=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:ze(e.AI_AGENT)??_e,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:i&&i.length>0?i:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:r&&r.length>0?r:void 0,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:s==="imessage"||s==="twilio"?s: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:qe(e.DEPLOY_PROVIDER)??Ce,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN||void 0,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,emailPassword:e.EMAIL_PASSWORD,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function Ie(e){let t=w=>{let V=e[w];if(!V)return;let x=parseInt(V,10);return isNaN(x)?void 0:x},s=e.SUPABASE_URL,n=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),i=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,r=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",p=qe(e.DEPLOY_PROVIDER)??Ce,g=e.VERCEL_TOKEN,l=e.CLOUDFLARE_API_TOKEN,A=e.CLOUDFLARE_ACCOUNT_ID;if(!r||!s||!n||!i||!a||!(p==="cloudflare"?!!l&&!!A:!!g))return null;let P=e.SMS_PROVIDER,L=w=>w==="email"||w==="sms"||w==="whatsapp",U=e.OUTREACH_CHANNELS?.split(",").map(w=>w.trim()).filter(L),N=e.OUTREACH_PRIORITY?.split(",").map(w=>w.trim()).filter(L),b=e.WHATSAPP_ACCOUNTS?.split(",").map(w=>w.trim()).filter(w=>w.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:ze(e.AI_AGENT)??_e,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:r,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:U&&U.length>0?U:void 0,outreachPriority:N&&N.length>0?N:void 0,whatsappAccounts:b&&b.length>0?b:void 0,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:P==="imessage"||P==="twilio"?P:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:p,vercelToken:g,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:l||void 0,cloudflareAccountId:A||void 0,supabaseUrl:s,supabaseServiceKey:n,supabasePat:i,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{mkdir as Zt,rm as en}from"fs/promises";import{Readable as tn}from"stream";import*as Ze from"tar";var nn="https://klaudius.dev/api/template";function on(e){return tn.fromWeb(e)}async function me(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??nn,s="0.16.0",n;try{n=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:s,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(r){throw new Error(`Could not reach klaudius.dev to download the template: ${_(r)}`)}if(!n.ok){let r="";try{let c=await n.json();r=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${n.status}${r}`)}if(!n.body)throw new Error("Template download succeeded but response had no body");let i=n.headers.get("x-klaudius-tier");await Zt(e.destDir,{recursive:!0});let a=0;try{await new Promise((r,c)=>{let p=Ze.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{a++}});p.on("finish",r),p.on("error",c),on(n.body).on("error",c).pipe(p)})}catch(r){throw await en(e.destDir,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Failed to extract template archive: ${r.message}`)}return{filesExtracted:a,tier:i}}import B from"picocolors";var o={info:e=>console.log(B.cyan("\u2139"),e),success:e=>console.log(B.green("\u2713"),e),warn:e=>console.log(B.yellow("\u26A0"),e),error:e=>console.error(B.red("\u2717"),e),step:e=>console.log(B.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
15
- `+B.bold(B.cyan(e))),detail:e=>console.log(B.dim(" "+e))};var sn="https://registry.npmjs.org/klaudius/latest";async function an(e=1500){let t=new AbortController,s=setTimeout(()=>t.abort(),e);try{let n=await fetch(sn,{signal:t.signal,headers:{accept:"application/json"}});if(!n.ok)return null;let i=await n.json();return typeof i.version=="string"?i.version:null}catch{return null}finally{clearTimeout(s)}}function rn(e,t){let s=a=>a.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),n=s(e),i=s(t);if(n.length<3||i.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(n[a])||Number.isNaN(i[a]))return!1;if(n[a]>i[a])return!0;if(n[a]<i[a])return!1}return!1}async function he(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let s=await an();!s||!rn(s,t)||(o.blank(),o.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${s}.`),e==="update"&&(o.detail("Your project content is fetched fresh either way, so you're not missing any"),o.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),o.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),o.blank())}import{createHash as ln}from"crypto";import{hostname as et,userInfo as cn,platform as tt,arch as nt}from"os";var dn="https://klaudius.dev",un="/api/licenses/validate",pn="0.16.0";async function ot(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),n=(process.env.KLAUDIUS_API_URL??dn).replace(/\/$/,"")+un,i=ie(),a;try{a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:i,hostname:et(),os:`${tt()}-${nt()}`,cli_version:pn})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${_(c)}). Check your internet connection or try again later.`}}let r;try{r=await a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${a.status}).`}}function ie(){let e=[et(),cn().username,tt(),nt()].join("|");return ln("sha256").update(e).digest("hex").slice(0,32)}import{readFile as fn}from"fs/promises";import{join as mn}from"path";async function ee(e){let t=e.serviceKey.replace(/\s+/g,"");try{let s=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return s.status===401||s.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${s.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(s){return{ok:!1,message:`Could not reach Supabase: ${_(s)}`}}}async function st(e){let t;try{t=await fn(mn(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(n){return{ok:!1,message:`Could not read scripts/schema.sql: ${n.message}`}}let s=e.pat.replace(/\s+/g,"");try{let n=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(n.ok)return{ok:!0};let i=await n.text();return i.includes("already exists")||i.includes('relation "clients" already exists')||i.includes("duplicate")?(o.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${n.status}): ${i.slice(0,300)}`}}catch(n){return{ok:!1,message:`Schema apply failed: ${n.message}`}}}async function ge(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 s=await t.json();return{ok:!0,username:s.user?.username??s.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${_(t)}`}}}var it="https://api.cloudflare.com/client/v4";function at(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ye(e){let{token:t,accountId:s}=e,n={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let i=await fetch(`${it}/user/tokens/verify`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await i.json(),r=a.result?.status;if(a.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${at(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}try{let i=await fetch(`${it}/accounts/${encodeURIComponent(s)}/pages/projects`,{headers:n});if(i.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${s} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(i.status===404)return{ok:!1,message:`Account ${s} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await i.json();return a.success===!1?{ok:!1,message:at(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}}async function ke(e){try{let t=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":e,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(t.ok)return{ok:!0};if(t.status===429)return{ok:!0};let s={};try{s=await t.json()}catch{}let n=s.error?.message??"",i=s.error?.status??"";return t.status===400&&(i==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(n))?{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."}:t.status===401||t.status===403?{ok:!1,message:n||`Google rejected the key (HTTP ${t.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`}:{ok:!1,message:`Google API returned HTTP ${t.status}${n?`: ${n}`:""}.`}}catch(t){return{ok:!1,message:`Could not reach Google: ${_(t)}`}}}import hn from"nodemailer";import{ImapFlow as gn}from"imapflow";async function lt(e){let t=hn.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(n){return{ok:!1,failedAt:"smtp",message:rt(n,"SMTP")}}finally{t.close()}let s=new gn({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1});try{await s.connect(),await s.logout()}catch(n){try{await s.logout()}catch{}return{ok:!1,failedAt:"imap",message:rt(n,"IMAP")}}return{ok:!0}}function rt(e,t){let s=e instanceof Error?e.message:String(e),n=s.toLowerCase();return n.includes("invalid credentials")||n.includes("authentication failed")||n.includes("auth failed")||n.includes("login failed")?`${t} rejected the credentials. Most common causes:
13
+ `}function Qt(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 $(e){let t={};for(let o of e.split(`
14
+ `)){let n=o.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i===-1)continue;let a=n.slice(0,i).trim(),r=Qt(n.slice(i+1).trim());t[a]=r}return t}function Qe(e){let t=c=>{let p=e[c];if(!p)return;let g=parseInt(p,10);return isNaN(g)?void 0:g},o=e.SMS_PROVIDER,n=c=>c==="email"||c==="sms"||c==="whatsapp",i=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(n),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(n),r=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:ze(e.AI_AGENT)??_e,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:i&&i.length>0?i:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:o==="imessage"||o==="twilio"?o:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:qe(e.DEPLOY_PROVIDER)??Ce,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN||void 0,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,emailPassword:e.EMAIL_PASSWORD,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function Ie(e){let t=w=>{let V=e[w];if(!V)return;let x=parseInt(V,10);return isNaN(x)?void 0:x},o=e.SUPABASE_URL,n=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),i=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,r=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",p=qe(e.DEPLOY_PROVIDER)??Ce,g=e.VERCEL_TOKEN,l=e.CLOUDFLARE_API_TOKEN,A=e.CLOUDFLARE_ACCOUNT_ID;if(!r||!o||!n||!i||!a||!(p==="cloudflare"?!!l&&!!A:!!g))return null;let P=e.SMS_PROVIDER,L=w=>w==="email"||w==="sms"||w==="whatsapp",U=e.OUTREACH_CHANNELS?.split(",").map(w=>w.trim()).filter(L),N=e.OUTREACH_PRIORITY?.split(",").map(w=>w.trim()).filter(L),b=e.WHATSAPP_ACCOUNTS?.split(",").map(w=>w.trim()).filter(w=>w.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:ze(e.AI_AGENT)??_e,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:r,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:U&&U.length>0?U:void 0,outreachPriority:N&&N.length>0?N:void 0,whatsappAccounts:b&&b.length>0?b:void 0,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:P==="imessage"||P==="twilio"?P:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:p,vercelToken:g,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:l||void 0,cloudflareAccountId:A||void 0,supabaseUrl:o,supabaseServiceKey:n,supabasePat:i,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{mkdir as Zt,rm as en}from"fs/promises";import{Readable as tn}from"stream";import*as Ze from"tar";var nn="https://klaudius.dev/api/template";function sn(e){return tn.fromWeb(e)}async function me(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??nn,o="0.16.1",n;try{n=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:o,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(r){throw new Error(`Could not reach klaudius.dev to download the template: ${_(r)}`)}if(!n.ok){let r="";try{let c=await n.json();r=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${n.status}${r}`)}if(!n.body)throw new Error("Template download succeeded but response had no body");let i=n.headers.get("x-klaudius-tier");await Zt(e.destDir,{recursive:!0});let a=0;try{await new Promise((r,c)=>{let p=Ze.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{a++}});p.on("finish",r),p.on("error",c),sn(n.body).on("error",c).pipe(p)})}catch(r){throw await en(e.destDir,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Failed to extract template archive: ${r.message}`)}return{filesExtracted:a,tier:i}}import B from"picocolors";var s={info:e=>console.log(B.cyan("\u2139"),e),success:e=>console.log(B.green("\u2713"),e),warn:e=>console.log(B.yellow("\u26A0"),e),error:e=>console.error(B.red("\u2717"),e),step:e=>console.log(B.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
15
+ `+B.bold(B.cyan(e))),detail:e=>console.log(B.dim(" "+e))};var on="https://registry.npmjs.org/klaudius/latest";async function an(e=1500){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{let n=await fetch(on,{signal:t.signal,headers:{accept:"application/json"}});if(!n.ok)return null;let i=await n.json();return typeof i.version=="string"?i.version:null}catch{return null}finally{clearTimeout(o)}}function rn(e,t){let o=a=>a.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),n=o(e),i=o(t);if(n.length<3||i.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(n[a])||Number.isNaN(i[a]))return!1;if(n[a]>i[a])return!0;if(n[a]<i[a])return!1}return!1}async function he(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let o=await an();!o||!rn(o,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${o}.`),e==="update"&&(s.detail("Your project content is fetched fresh either way, so you're not missing any"),s.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),s.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),s.blank())}import{createHash as ln}from"crypto";import{hostname as et,userInfo as cn,platform as tt,arch as nt}from"os";var dn="https://klaudius.dev",un="/api/licenses/validate",pn="0.16.1";async function st(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),n=(process.env.KLAUDIUS_API_URL??dn).replace(/\/$/,"")+un,i=ie(),a;try{a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:i,hostname:et(),os:`${tt()}-${nt()}`,cli_version:pn})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${_(c)}). Check your internet connection or try again later.`}}let r;try{r=await a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${a.status}).`}}function ie(){let e=[et(),cn().username,tt(),nt()].join("|");return ln("sha256").update(e).digest("hex").slice(0,32)}import{readFile as fn}from"fs/promises";import{join as mn}from"path";async function ee(e){let t=e.serviceKey.replace(/\s+/g,"");try{let o=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return o.status===401||o.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${o.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(o){return{ok:!1,message:`Could not reach Supabase: ${_(o)}`}}}async function ot(e){let t;try{t=await fn(mn(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(n){return{ok:!1,message:`Could not read scripts/schema.sql: ${n.message}`}}let o=e.pat.replace(/\s+/g,"");try{let n=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(n.ok)return{ok:!0};let i=await n.text();return i.includes("already exists")||i.includes('relation "clients" already exists')||i.includes("duplicate")?(s.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${n.status}): ${i.slice(0,300)}`}}catch(n){return{ok:!1,message:`Schema apply failed: ${n.message}`}}}async function ge(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let o=await t.json();return{ok:!0,username:o.user?.username??o.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${_(t)}`}}}var it="https://api.cloudflare.com/client/v4";function at(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ye(e){let{token:t,accountId:o}=e,n={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let i=await fetch(`${it}/user/tokens/verify`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await i.json(),r=a.result?.status;if(a.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${at(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}try{let i=await fetch(`${it}/accounts/${encodeURIComponent(o)}/pages/projects`,{headers:n});if(i.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${o} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(i.status===404)return{ok:!1,message:`Account ${o} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await i.json();return a.success===!1?{ok:!1,message:at(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}}async function ke(e){try{let t=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":e,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(t.ok)return{ok:!0};if(t.status===429)return{ok:!0};let o={};try{o=await t.json()}catch{}let n=o.error?.message??"",i=o.error?.status??"";return t.status===400&&(i==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(n))?{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."}:t.status===401||t.status===403?{ok:!1,message:n||`Google rejected the key (HTTP ${t.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`}:{ok:!1,message:`Google API returned HTTP ${t.status}${n?`: ${n}`:""}.`}}catch(t){return{ok:!1,message:`Could not reach Google: ${_(t)}`}}}import hn from"nodemailer";import{ImapFlow as gn}from"imapflow";async function lt(e){let t=hn.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(n){return{ok:!1,failedAt:"smtp",message:rt(n,"SMTP")}}finally{t.close()}let o=new gn({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1});try{await o.connect(),await o.logout()}catch(n){try{await o.logout()}catch{}return{ok:!1,failedAt:"imap",message:rt(n,"IMAP")}}return{ok:!0}}function rt(e,t){let o=e instanceof Error?e.message:String(e),n=o.toLowerCase();return n.includes("invalid credentials")||n.includes("authentication failed")||n.includes("auth failed")||n.includes("login failed")?`${t} rejected the credentials. Most common causes:
16
16
  \u2022 The app password is wrong, expired, or for a different provider.
17
17
  \u2022 The email address doesn't match the account that issued the password.
18
- \u2022 2FA is required but no app-specific password was generated.`:n.includes("etimedout")||n.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:n.includes("enotfound")||n.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}async function ct(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`,s=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let n=await fetch(t,{headers:{Authorization:`Basic ${s}`}});if(n.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!n.ok)return{ok:!1,message:`Twilio API returned HTTP ${n.status}. Try again or check status.twilio.com.`};let i=await n.json();return i.status&&i.status!=="active"?{ok:!1,message:`Twilio account is in '${i.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:i.friendly_name}}catch(n){return{ok:!1,message:`Could not reach Twilio: ${_(n)}`}}}import{spawn as yn}from"child_process";async function dt(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 s=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,n=await kn(s);if(n.code===0)return{ok:!0};let i=n.stderr.toLowerCase();return i.includes("can't get application")||i.includes("isn't running")||i.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:i.includes("(-1728)")||i.includes("not found")||i.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:i.includes("(-1719)")||i.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${n.stderr.trim()||`exit code ${n.code}`}`}}function kn(e){return new Promise(t=>{let s=yn("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),n="";s.stderr.on("data",i=>{n+=i.toString()}),s.on("close",i=>t({code:i??1,stderr:n})),s.on("error",i=>t({code:1,stderr:i.message}))})}import{spawn as ut}from"child_process";function wn(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var te=2,pt=2e3,En=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function ft(e,t){let s=e+`
19
- `+t;return En.some(n=>n.test(s))}function mt(e){return new Promise(t=>setTimeout(t,e))}function An(e,t,s){return new Promise(n=>{let i=ut(e,t,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:s.env??process.env}),a="",r="";i.stdout?.on("data",c=>{let p=c.toString();a+=p,process.stdout.write(p)}),i.stderr?.on("data",c=>{let p=c.toString();r+=p,process.stderr.write(p)}),i.on("close",c=>n({code:c??1,stdout:a,stderr:r})),i.on("error",c=>n({code:1,stdout:a,stderr:r+c.message}))})}async function Se(e,t,s){let n={code:0,stdout:"",stderr:""};for(let i=0;i<=te;i++){if(n=await An(e,t,{cwd:s.cwd,env:s.env}),n.code===0||!ft(n.stderr,n.stdout))return n;i<te&&(o.detail(`${s.label} failed with a transient network error \u2014 retrying (${i+2}/${te+1})\u2026`),await mt(pt))}return n}function Pn(e,t,s){return new Promise(n=>{let i=ut(e,t,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",r="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{r+=c.toString()}),i.on("close",c=>n({code:c??1,stdout:a,stderr:r})),i.on("error",c=>n({code:1,stdout:a,stderr:r+c.message}))})}var bn=[{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 Tn(e){let t=`${e.stderr??""}
20
- ${e.stdout??""}`;return bn.find(n=>n.pattern.test(t))?.hint}async function _n(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],s=["-m","pip","install","--quiet","--user"],i=(await be())?.command??["python3"],a=async c=>{let p={code:0,stdout:"",stderr:""};for(let g=0;g<=te;g++){if(p=await Pn(i[0],[...i.slice(1),...c],{cwd:e}),p.code===0||!ft(p.stderr,p.stdout))return p;g<te&&(o.detail(`pip install hit a transient network error \u2014 retrying (${g+2}/${te+1})\u2026`),await mt(pt))}return p},r=await a([...s,"--break-system-packages",...t]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(o.detail("Older pip detected; retrying without --break-system-packages"),r=await a([...s,...t])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function we(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},s=wn(),n=(p,g)=>{let l=Tn(g);l&&((t.hints??={})[p]=l)};o.step("Running npm install (Next.js, Playwright JS, etc.)...");let i=await Se("npm",["install"],{cwd:e,label:"npm install",env:s});t.npm=i.code===0?"ok":"failed",i.code!==0&&n("npm",i),o.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let a=await _n(e);t.pip=a.code===0?"ok":"failed",a.code!==0&&n("pip",a),o.step("Installing Playwright browser (chromium ~200MB; one-time)...");let r=await Se("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:s});t.playwright=r.code===0?"ok":"failed",r.code!==0&&n("playwright",r),o.step("Installing Patchright browser (chromium ~200MB; one-time)...");let c=await Se("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:s});return t.patchright=c.code===0?"ok":"failed",c.code!==0&&n("patchright",c),t}import{mkdir as Cn,readFile as In,writeFile as Sn}from"fs/promises";import{join as ht}from"path";async function Ee(e,t){let s=ht(e,".claude");await Cn(s,{recursive:!0});let n=ht(s,"settings.json"),i={};try{let p=await In(n,"utf-8"),g=JSON.parse(p);g&&typeof g=="object"&&!Array.isArray(g)&&(i=g)}catch{}let a=i.enabledMcpjsonServers,r=Array.isArray(a)?a.filter(p=>typeof p=="string"):[];r.includes(t)||r.push(t);let c={...i,enabledMcpjsonServers:r};await Sn(n,JSON.stringify(c,null,2)+`
21
- `,"utf-8")}var kt="0.16.0",C=5;function z(e,t){o.blank(),o.error(`${e} validation failed ${C} times in a row. Pausing setup so you don't get stuck in a loop.`),o.detail(`Last error: ${t}`),o.blank(),o.detail("Your credentials are saved in `.env`. Two ways forward:"),o.detail(" \u2022 Open `.env` in any text editor, fix the value, re-run `npx klaudius init` and pick Resume."),o.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),o.blank(),process.exit(1)}async function Et(e){let t=e.target??".",s=vn(t)?t:xn(process.cwd(),t),n=Dn(s);n&&(o.error("Klaudius can't be installed inside a protected system folder."),o.detail(`Path: ${s}`),o.detail(`Reason: ${n}`),o.blank(),o.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),o.blank(),process.platform==="win32"?(o.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${d.cyan("cd $HOME\\Documents")}`),console.log(` ${d.cyan("npx klaudius init my-agency")}`)):(o.detail("For example:"),console.log(` ${d.cyan("cd ~/Documents")}`),console.log(` ${d.cyan("npx klaudius init my-agency")}`)),o.blank(),process.exit(1)),process.platform==="win32"&&Mn()&&(o.warn("You appear to be running in an elevated (Administrator) PowerShell."),o.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius init."),o.blank()),await he("init",kt);let i=await $n(s);if(i.kind==="scaffolded"){o.blank(),o.warn(`Found an existing Klaudius project at ${d.bold(s)}.`),o.detail("(Your .env and project files are in place.)"),o.blank(),i.nodeModulesMissing?(o.detail("It looks like a previous setup didn't finish installing dependencies."),o.detail("To pick up where it left off, run:"),o.blank(),s!==process.cwd()&&console.log(` ${d.cyan(`cd ${t}`)}`),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Everything is scaffolded and dependencies look installed."),o.detail("Pick the action you wanted:"),o.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),o.blank()),o.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius init`."),o.blank();return}if(i.kind==="occupied"){let u=t===".";o.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),o.detail(`Path: ${s}`),o.detail(`Contains: ${i.entries.slice(0,5).join(", ")}${i.entries.length>5?`, \u2026 (+${i.entries.length-5} more)`:""}`),o.blank(),u?(o.detail("Two ways forward:"),o.blank(),o.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius init my-agency")}`),o.blank(),o.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius init")}`)):(o.detail(`The folder '${t}' already exists and isn't empty.`),o.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius init ${t}-2`)}`),o.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await Ln(e.license),r=k.spinner();r.start("Validating license");let c=await ot(a);c.ok||(r.stop(`License invalid: ${c.reason??"unknown"}`,2),o.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),r.stop(`License valid (${c.tier??"core"} tier)`);let p=await Z();p.ok||(o.error(p.message??"Python version check failed."),o.blank(),o.detail("Once you've installed Python 3.10+, re-run `npx klaudius init` in this folder."),process.exit(1));let g=G();g.ok||(o.error(g.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius init` in this folder."),process.exit(1));let l,A=!1;if(i.kind==="partial")if(await Nn(s)==="resume"){let m=await gt(i.envPath,"utf-8"),f=Ie($(m));f?(o.success("Resuming with values from your existing .env"),o.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=f,A=!0):(o.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await I())}else{let m=await gt(i.envPath,"utf-8"),f=Ie($(m));l=await I(f??{})}else l=await I();l.licenseKey=a,await D(s,l),A||(o.success("Saved .env"),o.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),o.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating Supabase credentials");let f=await ee({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(f.ok){m.stop("Supabase credentials accepted");break}m.stop(f.message??"Supabase check failed",2),u>=C&&z("Supabase",f.message??"Supabase check failed");let E=f.message??"Supabase check failed";o.blank(),o.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
18
+ \u2022 2FA is required but no app-specific password was generated.`:n.includes("etimedout")||n.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:n.includes("enotfound")||n.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${o}`}async function ct(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,o=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let n=await fetch(t,{headers:{Authorization:`Basic ${o}`}});if(n.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!n.ok)return{ok:!1,message:`Twilio API returned HTTP ${n.status}. Try again or check status.twilio.com.`};let i=await n.json();return i.status&&i.status!=="active"?{ok:!1,message:`Twilio account is in '${i.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:i.friendly_name}}catch(n){return{ok:!1,message:`Could not reach Twilio: ${_(n)}`}}}import{spawn as yn}from"child_process";async function dt(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let o=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,n=await kn(o);if(n.code===0)return{ok:!0};let i=n.stderr.toLowerCase();return i.includes("can't get application")||i.includes("isn't running")||i.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:i.includes("(-1728)")||i.includes("not found")||i.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:i.includes("(-1719)")||i.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${n.stderr.trim()||`exit code ${n.code}`}`}}function kn(e){return new Promise(t=>{let o=yn("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),n="";o.stderr.on("data",i=>{n+=i.toString()}),o.on("close",i=>t({code:i??1,stderr:n})),o.on("error",i=>t({code:1,stderr:i.message}))})}import{spawn as ut}from"child_process";function wn(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var te=2,pt=2e3,En=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function ft(e,t){let o=e+`
19
+ `+t;return En.some(n=>n.test(o))}function mt(e){return new Promise(t=>setTimeout(t,e))}function An(e,t,o){return new Promise(n=>{let i=ut(e,t,{cwd:o.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:o.env??process.env}),a="",r="";i.stdout?.on("data",c=>{let p=c.toString();a+=p,process.stdout.write(p)}),i.stderr?.on("data",c=>{let p=c.toString();r+=p,process.stderr.write(p)}),i.on("close",c=>n({code:c??1,stdout:a,stderr:r})),i.on("error",c=>n({code:1,stdout:a,stderr:r+c.message}))})}async function Se(e,t,o){let n={code:0,stdout:"",stderr:""};for(let i=0;i<=te;i++){if(n=await An(e,t,{cwd:o.cwd,env:o.env}),n.code===0||!ft(n.stderr,n.stdout))return n;i<te&&(s.detail(`${o.label} failed with a transient network error \u2014 retrying (${i+2}/${te+1})\u2026`),await mt(pt))}return n}function Pn(e,t,o){return new Promise(n=>{let i=ut(e,t,{cwd:o.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",r="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{r+=c.toString()}),i.on("close",c=>n({code:c??1,stdout:a,stderr:r})),i.on("error",c=>n({code:1,stdout:a,stderr:r+c.message}))})}var bn=[{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 Tn(e){let t=`${e.stderr??""}
20
+ ${e.stdout??""}`;return bn.find(n=>n.pattern.test(t))?.hint}async function _n(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],o=["-m","pip","install","--quiet","--user"],i=(await be())?.command??["python3"],a=async c=>{let p={code:0,stdout:"",stderr:""};for(let g=0;g<=te;g++){if(p=await Pn(i[0],[...i.slice(1),...c],{cwd:e}),p.code===0||!ft(p.stderr,p.stdout))return p;g<te&&(s.detail(`pip install hit a transient network error \u2014 retrying (${g+2}/${te+1})\u2026`),await mt(pt))}return p},r=await a([...o,"--break-system-packages",...t]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(s.detail("Older pip detected; retrying without --break-system-packages"),r=await a([...o,...t])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function we(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},o=wn(),n=(p,g)=>{let l=Tn(g);l&&((t.hints??={})[p]=l)};s.step("Running npm install (Next.js, Playwright JS, etc.)...");let i=await Se("npm",["install"],{cwd:e,label:"npm install",env:o});t.npm=i.code===0?"ok":"failed",i.code!==0&&n("npm",i),s.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let a=await _n(e);t.pip=a.code===0?"ok":"failed",a.code!==0&&n("pip",a),s.step("Installing Playwright browser (chromium ~200MB; one-time)...");let r=await Se("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:o});t.playwright=r.code===0?"ok":"failed",r.code!==0&&n("playwright",r),s.step("Installing Patchright browser (chromium ~200MB; one-time)...");let c=await Se("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:o});return t.patchright=c.code===0?"ok":"failed",c.code!==0&&n("patchright",c),t}import{mkdir as Cn,readFile as In,writeFile as Sn}from"fs/promises";import{join as ht}from"path";async function Ee(e,t){let o=ht(e,".claude");await Cn(o,{recursive:!0});let n=ht(o,"settings.json"),i={};try{let p=await In(n,"utf-8"),g=JSON.parse(p);g&&typeof g=="object"&&!Array.isArray(g)&&(i=g)}catch{}let a=i.enabledMcpjsonServers,r=Array.isArray(a)?a.filter(p=>typeof p=="string"):[];r.includes(t)||r.push(t);let c={...i,enabledMcpjsonServers:r};await Sn(n,JSON.stringify(c,null,2)+`
21
+ `,"utf-8")}var kt="0.16.1",C=5;function z(e,t){s.blank(),s.error(`${e} validation failed ${C} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${t}`),s.blank(),s.detail("Your credentials are saved in `.env`. Two ways forward:"),s.detail(" \u2022 Open `.env` in any text editor, fix the value, re-run `npx klaudius@latest init` and pick Resume."),s.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),s.blank(),process.exit(1)}async function Et(e){let t=e.target??".",o=vn(t)?t:xn(process.cwd(),t),n=Dn(o);n&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${o}`),s.detail(`Reason: ${n}`),s.blank(),s.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),s.blank(),process.platform==="win32"?(s.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${d.cyan("cd $HOME\\Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)):(s.detail("For example:"),console.log(` ${d.cyan("cd ~/Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)),s.blank(),process.exit(1)),process.platform==="win32"&&Mn()&&(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 he("init",kt);let i=await $n(o);if(i.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${d.bold(o)}.`),s.detail("(Your .env and project files are in place.)"),s.blank(),i.nodeModulesMissing?(s.detail("It looks like a previous setup didn't finish installing dependencies."),s.detail("To pick up where it left off, run:"),s.blank(),o!==process.cwd()&&console.log(` ${d.cyan(`cd ${t}`)}`),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Everything is scaffolded and dependencies look installed."),s.detail("Pick the action you wanted:"),s.blank(),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius@latest configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius@latest update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),s.blank()),s.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),s.blank();return}if(i.kind==="occupied"){let u=t===".";s.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),s.detail(`Path: ${o}`),s.detail(`Contains: ${i.entries.slice(0,5).join(", ")}${i.entries.length>5?`, \u2026 (+${i.entries.length-5} more)`:""}`),s.blank(),u?(s.detail("Two ways forward:"),s.blank(),s.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`),s.blank(),s.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(s.detail(`The folder '${t}' already exists and isn't empty.`),s.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius@latest init ${t}-2`)}`),s.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await Ln(e.license),r=k.spinner();r.start("Validating license");let c=await st(a);c.ok||(r.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)),r.stop(`License valid (${c.tier??"core"} tier)`);let p=await Z();p.ok||(s.error(p.message??"Python version check failed."),s.blank(),s.detail("Once you've installed Python 3.10+, re-run `npx klaudius@latest init` in this folder."),process.exit(1));let g=G();g.ok||(s.error(g.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest init` in this folder."),process.exit(1));let l,A=!1;if(i.kind==="partial")if(await Nn(o)==="resume"){let m=await gt(i.envPath,"utf-8"),f=Ie($(m));f?(s.success("Resuming with values from your existing .env"),s.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=f,A=!0):(s.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await I())}else{let m=await gt(i.envPath,"utf-8"),f=Ie($(m));l=await I(f??{})}else l=await I();l.licenseKey=a,await D(o,l),A||(s.success("Saved .env"),s.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),s.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating Supabase credentials");let f=await ee({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(f.ok){m.stop("Supabase credentials accepted");break}m.stop(f.message??"Supabase check failed",2),u>=C&&z("Supabase",f.message??"Supabase check failed");let E=f.message??"Supabase check failed";s.blank(),s.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${u+1} of ${C})`),s.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),s.blank(),l=await I(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
22
22
  ${E}
23
23
 
24
24
  Re-enter the URL, secret key, or PAT below. Press Enter on any
25
- field to keep what's already there.`}),await D(s,l)}if(o.blank(),l.deployProvider==="cloudflare")for(let u=1;;u++){let m=k.spinner();m.start("Validating Cloudflare token + account");let f=await ye({token:l.cloudflareApiToken??"",accountId:l.cloudflareAccountId??""});if(f.ok){m.stop(`Cloudflare credentials accepted (${f.projectCount??0} existing Pages project${f.projectCount===1?"":"s"})`);break}m.stop(f.message??"Cloudflare check failed",2),u>=C&&z("Cloudflare",f.message??"Cloudflare check failed");let E=f.message??"Cloudflare check failed";o.blank(),o.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
25
+ field to keep what's already there.`}),await D(o,l)}if(s.blank(),l.deployProvider==="cloudflare")for(let u=1;;u++){let m=k.spinner();m.start("Validating Cloudflare token + account");let f=await ye({token:l.cloudflareApiToken??"",accountId:l.cloudflareAccountId??""});if(f.ok){m.stop(`Cloudflare credentials accepted (${f.projectCount??0} existing Pages project${f.projectCount===1?"":"s"})`);break}m.stop(f.message??"Cloudflare check failed",2),u>=C&&z("Cloudflare",f.message??"Cloudflare check failed");let E=f.message??"Cloudflare check failed";s.blank(),s.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${u+1} of ${C})`),s.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),s.blank(),l=await I(l,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
26
26
  ${E}
27
27
 
28
28
  Re-enter the API token or Account ID below. The token needs the
29
29
  "Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
30
- the current value.`}),await D(s,l)}else for(let u=1;;u++){let m=k.spinner();m.start("Validating Vercel token");let f=await ge(l.vercelToken??"");if(f.ok){m.stop(f.username?`Vercel token accepted (signed in as ${f.username})`:"Vercel token accepted");break}m.stop(f.message??"Vercel check failed",2),u>=C&&z("Vercel",f.message??"Vercel check failed");let E=f.message??"Vercel check failed";o.blank(),o.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"vercel",banner:`Vercel rejected the token:
30
+ the current value.`}),await D(o,l)}else for(let u=1;;u++){let m=k.spinner();m.start("Validating Vercel token");let f=await ge(l.vercelToken??"");if(f.ok){m.stop(f.username?`Vercel token accepted (signed in as ${f.username})`:"Vercel token accepted");break}m.stop(f.message??"Vercel check failed",2),u>=C&&z("Vercel",f.message??"Vercel check failed");let E=f.message??"Vercel check failed";s.blank(),s.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${u+1} of ${C})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),l=await I(l,{onlySection:"vercel",banner:`Vercel rejected the token:
31
31
  ${E}
32
32
 
33
33
  Generate a new token at https://vercel.com/account/tokens and
34
- paste it below. Press Enter to keep the current value.`}),await D(s,l)}o.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating Google Places API key");let f=await ke(l.googlePlacesApiKey??"");if(f.ok){m.stop("Google Places API key accepted");break}m.stop(f.message??"Google Places check failed",2),u>=C&&z("Google Places",f.message??"Google Places check failed");let E=f.message??"Google Places check failed";o.blank(),o.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"google-places",banner:`Google rejected the key:
34
+ paste it below. Press Enter to keep the current value.`}),await D(o,l)}s.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating Google Places API key");let f=await ke(l.googlePlacesApiKey??"");if(f.ok){m.stop("Google Places API key accepted");break}m.stop(f.message??"Google Places check failed",2),u>=C&&z("Google Places",f.message??"Google Places check failed");let E=f.message??"Google Places check failed";s.blank(),s.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${u+1} of ${C})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),l=await I(l,{onlySection:"google-places",banner:`Google rejected the key:
35
35
  ${E}
36
36
 
37
37
  Generate (or fix) the key at https://console.cloud.google.com
38
- and paste it below. Press Enter to keep the current value.`}),await D(s,l)}if(l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAddress&&l.emailPassword&&l.emailSmtpHost&&l.emailSmtpPort&&l.emailImapHost&&l.emailImapPort){o.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating email credentials (SMTP + IMAP)");let f=await lt({emailAddress:l.emailAddress,emailPassword:l.emailPassword,emailSmtpHost:l.emailSmtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:l.emailImapHost,emailImapPort:l.emailImapPort});if(f.ok){m.stop("Email credentials accepted (SMTP + IMAP)");break}m.stop(f.message??"Email check failed",2),u>=C&&z("Email",f.message??"Email check failed");let E=f.message??"Email check failed";o.blank(),o.warn(`Bouncing you back into the email section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"email",banner:`${f.failedAt==="imap"?"IMAP":"SMTP"} check failed:
38
+ and paste it below. Press Enter to keep the current value.`}),await D(o,l)}if(l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAddress&&l.emailPassword&&l.emailSmtpHost&&l.emailSmtpPort&&l.emailImapHost&&l.emailImapPort){s.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating email credentials (SMTP + IMAP)");let f=await lt({emailAddress:l.emailAddress,emailPassword:l.emailPassword,emailSmtpHost:l.emailSmtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:l.emailImapHost,emailImapPort:l.emailImapPort});if(f.ok){m.stop("Email credentials accepted (SMTP + IMAP)");break}m.stop(f.message??"Email check failed",2),u>=C&&z("Email",f.message??"Email check failed");let E=f.message??"Email check failed";s.blank(),s.warn(`Bouncing you back into the email section so you can fix it in place. (attempt ${u+1} of ${C})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),l=await I(l,{onlySection:"email",banner:`${f.failedAt==="imap"?"IMAP":"SMTP"} check failed:
39
39
  ${E}
40
40
 
41
41
  Re-enter the email address, app password, or host details below.
42
- Press Enter on any field to keep its current value.`}),await D(s,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="twilio"&&l.twilioAccountSid&&l.twilioAuthToken){o.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating Twilio credentials");let f=await ct({accountSid:l.twilioAccountSid,authToken:l.twilioAuthToken});if(f.ok){m.stop(f.friendlyName?`Twilio credentials accepted (${f.friendlyName})`:"Twilio credentials accepted");break}m.stop(f.message??"Twilio check failed",2),u>=C&&z("Twilio",f.message??"Twilio check failed");let E=f.message??"Twilio check failed";o.blank(),o.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"sms",banner:`Twilio rejected the credentials:
42
+ Press Enter on any field to keep its current value.`}),await D(o,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="twilio"&&l.twilioAccountSid&&l.twilioAuthToken){s.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating Twilio credentials");let f=await ct({accountSid:l.twilioAccountSid,authToken:l.twilioAuthToken});if(f.ok){m.stop(f.friendlyName?`Twilio credentials accepted (${f.friendlyName})`:"Twilio credentials accepted");break}m.stop(f.message??"Twilio check failed",2),u>=C&&z("Twilio",f.message??"Twilio check failed");let E=f.message??"Twilio check failed";s.blank(),s.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${C})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),l=await I(l,{onlySection:"sms",banner:`Twilio rejected the credentials:
43
43
  ${E}
44
44
 
45
45
  Re-enter the Account SID or Auth Token below.
46
- Press Enter on any field to keep its current value.`}),await D(s,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="imessage"&&l.testPhone){o.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating iMessage setup (sending a test ping)");let f=await dt({testPhone:l.testPhone});if(f.ok){m.stop("iMessage dispatched (check your phone for the test ping)");break}m.stop(f.message??"iMessage check failed",2),u>=C&&z("iMessage",f.message??"iMessage check failed");let E=f.message??"iMessage check failed";o.blank(),o.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"sms",banner:`iMessage check failed:
46
+ Press Enter on any field to keep its current value.`}),await D(o,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="imessage"&&l.testPhone){s.blank();for(let u=1;;u++){let m=k.spinner();m.start("Validating iMessage setup (sending a test ping)");let f=await dt({testPhone:l.testPhone});if(f.ok){m.stop("iMessage dispatched (check your phone for the test ping)");break}m.stop(f.message??"iMessage check failed",2),u>=C&&z("iMessage",f.message??"iMessage check failed");let E=f.message??"iMessage check failed";s.blank(),s.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${C})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),l=await I(l,{onlySection:"sms",banner:`iMessage check failed:
47
47
  ${E}
48
48
 
49
49
  Either fix the underlying issue (sign in to Messages.app, configure
50
50
  Text Message Forwarding) and press Enter through, or change SMS
51
- provider to Twilio.`}),await D(s,l)}}if(l.telegramBotToken&&l.telegramChatId){o.blank();let u=0,m=!1;for(;!m;){u++;let f=k.spinner();f.start("Validating Telegram bot + chat (sending a test ping)");let E=await He({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(E.ok){f.stop(E.botHandle?`Telegram bot ${E.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),m=!0;break}f.stop(E.message??"Telegram check failed",2);let Me=E.message??"Telegram check failed";o.blank(),o.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),o.blank();let Y=await k.select({message:"What would you like to do?",initialValue:u>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(k.isCancel(Y)&&(k.cancel("Setup cancelled. Your .env is saved \u2014 re-run `npx klaudius init` to resume."),process.exit(0)),Y==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await D(s,l),o.success("Skipped Telegram. Setup will continue."),o.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),m=!0;break}if(Y==="edit"&&(o.blank(),l=await I(l,{onlySection:"telegram",banner:`Telegram check failed:
51
+ provider to Twilio.`}),await D(o,l)}}if(l.telegramBotToken&&l.telegramChatId){s.blank();let u=0,m=!1;for(;!m;){u++;let f=k.spinner();f.start("Validating Telegram bot + chat (sending a test ping)");let E=await He({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(E.ok){f.stop(E.botHandle?`Telegram bot ${E.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),m=!0;break}f.stop(E.message??"Telegram check failed",2);let Me=E.message??"Telegram check failed";s.blank(),s.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),s.blank();let Y=await k.select({message:"What would you like to do?",initialValue:u>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(k.isCancel(Y)&&(k.cancel("Setup cancelled. Your .env is saved \u2014 re-run `npx klaudius@latest init` to resume."),process.exit(0)),Y==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await D(o,l),s.success("Skipped Telegram. Setup will continue."),s.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),m=!0;break}if(Y==="edit"&&(s.blank(),l=await I(l,{onlySection:"telegram",banner:`Telegram check failed:
52
52
  ${Me}
53
53
 
54
54
  Re-enter the bot token or chat_id below.
55
- Press Enter on any field to keep its current value.`}),await D(s,l),!l.telegramBotToken||!l.telegramChatId)){o.success("Skipped Telegram. Setup will continue."),m=!0;break}}}o.blank();let h=k.spinner();h.start("Downloading Klaudius template");let P;try{P=(await me({licenseKey:a,machineId:ie(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:s})).filesExtracted,h.stop(`Downloaded ${P} files into ${d.bold(s)}`)}catch(u){h.stop(u.message,2);let m=l.aiAgent==="codex"?".codex/config.toml":".mcp.json";o.detail(`Your .env / ${m} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await xe(q(s,"clients"),{recursive:!0});let L=await Be(s);await ce(s,Ge(kt,L)),o.success("Wrote .klaudius/manifest.json");let U=!1,N="";if(e.skipSchema)o.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),o.detail(`Apply manually later via the SQL editor: ${l.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+l.supabaseProjectRef+"/sql/new").replace(l.supabaseProjectRef+".supabase.co","")}`);else{o.blank();let u=k.spinner();u.start("Applying schema to Supabase");let m=await st({projectRoot:s,pat:l.supabasePat,projectRef:l.supabaseProjectRef});m.ok?u.stop("Schema applied (or already present)"):(u.stop(m.message??"Schema apply failed",2),U=!0,N=`https://supabase.com/dashboard/project/${l.supabaseProjectRef}/sql/new`)}let b=[],w={};if(e.skipInstall)o.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{o.blank(),o.heading("Installing dependencies");let u=await we(s);o.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&b.push("npm"),u.pip==="failed"&&b.push("pip"),u.playwright==="failed"&&b.push("playwright"),u.patchright==="failed"&&b.push("patchright"),w=u.hints??{}}let V=l.outreachEnabled&&l.outreachPriority?.includes("whatsapp")&&(l.whatsappAccounts?.length??0)>0,x=!e.skipInstall&&!b.includes("npm");if(V&&x){o.blank(),o.heading("Linking WhatsApp accounts"),console.log(d.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
55
+ Press Enter on any field to keep its current value.`}),await D(o,l),!l.telegramBotToken||!l.telegramChatId)){s.success("Skipped Telegram. Setup will continue."),m=!0;break}}}s.blank();let h=k.spinner();h.start("Downloading Klaudius template");let P;try{P=(await me({licenseKey:a,machineId:ie(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:o})).filesExtracted,h.stop(`Downloaded ${P} files into ${d.bold(o)}`)}catch(u){h.stop(u.message,2);let m=l.aiAgent==="codex"?".codex/config.toml":".mcp.json";s.detail(`Your .env / ${m} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await xe(q(o,"clients"),{recursive:!0});let L=await Be(o);await ce(o,Ge(kt,L)),s.success("Wrote .klaudius/manifest.json");let U=!1,N="";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: ${l.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+l.supabaseProjectRef+"/sql/new").replace(l.supabaseProjectRef+".supabase.co","")}`);else{s.blank();let u=k.spinner();u.start("Applying schema to Supabase");let m=await ot({projectRoot:o,pat:l.supabasePat,projectRef:l.supabaseProjectRef});m.ok?u.stop("Schema applied (or already present)"):(u.stop(m.message??"Schema apply failed",2),U=!0,N=`https://supabase.com/dashboard/project/${l.supabaseProjectRef}/sql/new`)}let b=[],w={};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 we(o);s.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&b.push("npm"),u.pip==="failed"&&b.push("pip"),u.playwright==="failed"&&b.push("playwright"),u.patchright==="failed"&&b.push("patchright"),w=u.hints??{}}let V=l.outreachEnabled&&l.outreachPriority?.includes("whatsapp")&&(l.whatsappAccounts?.length??0)>0,x=!e.skipInstall&&!b.includes("npm");if(V&&x){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
56
56
  phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
57
- Link a Device, and point it at the QR shown in this terminal.`)),o.blank();for(let u of l.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 pair-whatsapp --label ${u})`));let m=wt(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:s,stdio:"inherit"});m.status===0?o.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${m.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))),o.blank()}}else if(V&&!x){o.blank(),console.log(d.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius install` completes successfully, pair via:"));for(let u of l.whatsappAccounts)console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))}o.blank();let y=[...b,...U?["schema"]:[]];if(y.length>0){k.outro(d.yellow(d.bold(`Setup paused \u2014 ${y.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),o.blank();for(let[J,Dt]of Object.entries(w))console.log(d.yellow(`Likely cause of ${J} failure:`)),console.log(d.dim(` ${Dt}`)),o.blank();let u=s!==process.cwd()?` ${d.cyan(`cd ${e.target}`)}
58
- `:"",m=l.aiAgent==="codex"?"codex":"claude",f=l.aiAgent==="codex"?"Codex":"Claude Code",E=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";b.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),o.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan(m)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${b.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius doctor."`)),o.blank(),console.log(d.dim(` (Don't have ${f} yet? Install with: \`${E}\`)`)),o.blank(),console.log(d.dim("Or do it yourself:")),o.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify everything")}`),o.blank()),U&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(N)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),o.blank()),b.includes("pip")&&!w.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 ${Un()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),o.blank());let Y=["npm","playwright","patchright"].filter(J=>b.includes(J)&&!w[J]);if(Y.length>0){let J=Y.length===1?"keeps":"keep";console.log(d.dim(`If ${Y.join(" / ")} ${J} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius install`.")),o.blank()}console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),o.blank();return}k.outro(d.green(d.bold("Project ready."))),console.log(d.dim("Next steps:")),s!==process.cwd()&&console.log(` ${d.cyan(`cd ${e.target}`)}`);let j=process.platform==="win32"?"start":process.platform==="linux"?"xdg-open":"open",X=d.dim("# read this first \u2014 operator basics + commands");console.log(` ${d.cyan(`${j} DOCS.html`)}${" ".repeat(Math.max(1,17-j.length))}${X}`);let re=l.aiAgent==="codex"?"codex":"claude",De=l.aiAgent==="codex"?"Codex":"Claude Code";console.log(` ${d.cyan(re)} ${d.dim(`# open ${De} in this project`)}`),console.log(` ${d.dim(`then ask ${De}:`)}`),console.log(` ${d.cyan(' "Run the pipeline."')}`),o.blank()}async function D(e,t){await xe(e,{recursive:!0}),await Re(q(e,".env"),ue(t),"utf-8"),t.aiAgent==="codex"?(await xe(q(e,".codex"),{recursive:!0}),await Re(q(e,".codex","config.toml"),fe(t),"utf-8")):(await Re(q(e,".mcp.json"),pe(t),"utf-8"),await Ee(e,"supabase"))}async function $n(e){try{(await yt(e)).isDirectory()||(o.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Rn(e),s=t.filter(c=>!c.startsWith(".DS_Store"));if(s.length===0)return{kind:"fresh"};let n=new Set([".env",".mcp.json",".claude",".codex"]),i=s.every(c=>n.has(c)),a=s.includes(".env"),r=t.includes(".klaudius");if(i&&a&&!r)return{kind:"partial",envPath:q(e,".env")};if(r&&a){let c=!0;try{c=!(await yt(q(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:s}}async function Nn(e){o.blank(),o.warn(`Found a partial setup at ${d.bold(e)}.`),o.detail(`A previous init wrote ${d.bold(".env")} but didn't finish scaffolding.`),o.blank();let t=await k.select({message:"How would you like to proceed?",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 Ln(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:s=>s.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 Dn(e){let t=On(e);if(process.platform==="win32"){let s=t.toLowerCase();if(s.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(s.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(s.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(s.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let s=["/System/","/usr/","/bin/","/sbin/"];for(let n of s)if(t.startsWith(n))return`Inside ${n.slice(0,-1)} (system-managed directory).`}}function Mn(){if(process.platform!=="win32")return!1;try{return wt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Un(){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/"}}import{access as jn,readFile as Kn}from"fs/promises";import{join as ve,resolve as Hn}from"path";import v from"picocolors";async function Pt(e){let t=e.target?Hn(process.cwd(),e.target):process.cwd(),s=await At(ve(t,".env")),n=await At(ve(t,"package.json"));(!s||!n)&&(o.error("This doesn't look like a Klaudius project."),o.detail(`Path: ${t}`),s||o.detail("Missing: .env"),n||o.detail("Missing: package.json"),o.blank(),o.detail("Run `npx klaudius init` to scaffold a new project first,"),o.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let i="claude-code";try{$(await Kn(ve(t,".env"),"utf-8")).AI_AGENT==="codex"&&(i="codex")}catch{}o.heading("Installing dependencies");let a=await we(t);o.blank(),o.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let r=[];if(a.npm==="failed"&&r.push("npm"),a.pip==="failed"&&r.push("pip"),a.playwright==="failed"&&r.push("playwright"),a.patchright==="failed"&&r.push("patchright"),r.length===0){o.blank(),console.log(v.green(v.bold("All dependencies installed."))),console.log(v.dim("Run `npx klaudius doctor` to verify everything else (credentials, files).")),o.blank();return}o.blank(),console.log(v.yellow(v.bold(`${r.join(", ")} still failing.`))),o.blank();for(let[l,A]of Object.entries(a.hints??{}))console.log(v.yellow(`Likely cause of ${l} failure:`)),console.log(v.dim(` ${A}`)),o.blank();let c=i==="codex"?"codex":"claude",p=i==="codex"?"Codex":"Claude Code",g=i==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(v.dim("Options:")),console.log(v.dim(` \u2022 Open ${p} in this folder (\`${c}\`) and paste:`)),console.log(v.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius doctor."`)),console.log(v.dim(` (Don't have ${p} yet? Install with: \`${g}\`)`)),console.log(v.dim(" \u2022 Or run `npx klaudius doctor` for a structured diagnostic.")),console.log(v.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),o.blank(),process.exitCode=1}async function At(e){try{return await jn(e),!0}catch{return!1}}import{readFile as Fn,writeFile as Oe,access as Vn}from"fs/promises";import{join as ne}from"path";import*as Ae from"@clack/prompts";import K from"picocolors";import{mkdir as Gn}from"fs/promises";async function bt(e){let t=e.projectRoot??process.cwd(),s=ne(t,".env"),n=ne(t,".mcp.json"),i=ne(t,".codex","config.toml"),a=await $e(ne(t,".klaudius","manifest.json")),r=await $e(s);!a&&!r&&(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius init` first."),process.exit(1));let c=G();c.ok||(o.error(c.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius configure` in this folder."),process.exit(1));let p={};try{let h=await Fn(s,"utf-8");p=$(h)}catch{o.warn("No .env found. Starting from an empty configuration.")}let g=Qe(p);Ae.intro("Reconfigure Klaudius"),o.detail("Press Enter on any prompt to keep its current value."),o.blank();let l=await I(g),A=g.aiAgent??"claude-code";if(l.aiAgent&&l.aiAgent!==A&&(o.error(`Switching AI coding agent (${A} \u2192 ${l.aiAgent}) isn't supported via configure.`),o.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius init <new-folder>")} ${K.dim("# pick the new agent in the wizard")}`),o.blank(),o.detail(".env is unchanged."),process.exit(1)),l.supabaseUrl!==p.SUPABASE_URL||l.supabaseServiceKey!==p.SUPABASE_SERVICE_KEY){o.heading("Re-validating Supabase credentials");let h=await ee({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});h.ok||(o.error(h.message??"Supabase check failed"),o.warn("Aborting. .env not modified."),process.exit(1)),o.success("Supabase credentials accepted")}await Oe(s,ue(l),"utf-8"),o.success("Updated .env"),l.aiAgent==="codex"?(await Gn(ne(t,".codex"),{recursive:!0}),await Oe(i,fe(l),"utf-8"),o.success("Updated .codex/config.toml")):(await Oe(n,pe(l),"utf-8"),o.success("Updated .mcp.json"),await Ee(t,"supabase")),o.blank(),Ae.outro(K.green("Configuration updated.")),await Bn(t,a)}async function Bn(e,t){let s=await $e(ne(e,"node_modules"));o.blank(),t?s||(o.detail("Your project files are in place but dependencies aren't installed yet."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius install")} ${K.dim("# (re-)installs npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${K.cyan("npx klaudius doctor")} ${K.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius init")} ${K.dim("# pick Resume when prompted")}`),o.blank())}async function $e(e){try{return await Vn(e),!0}catch{return!1}}import{copyFile as Tt,mkdir as _t,readdir as Wn,readFile as Yn,rm as ae,writeFile as Ct,access as It}from"fs/promises";import{dirname as St,join as O,relative as zn}from"path";import{tmpdir as qn}from"os";import*as oe from"@clack/prompts";import Ne from"picocolors";var Pe="0.16.0";async function Rt(e){let t=e.projectRoot??process.cwd(),s=await Ve(t);s||(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius init` first."),process.exit(1));for(let y of Fe)delete s.files[y];let n,i=O(t,".env"),a,r;try{a=await Yn(i,"utf-8"),r=$(a)}catch{o.error("Couldn't read .env from this directory."),o.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}n=r.KLAUDIUS_LICENSE_KEY??"",n||(o.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),o.detail("This file is created by `npx klaudius init`. If your project predates"),o.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius init`"),o.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=Je(a,r,Xe);c!==null&&(await Ct(i,c,"utf-8"),o.detail("Backfilled new env keys")),await he("update",Pe),oe.intro(`Update from ${s.templateVersion} \u2192 ${Pe}`);let g=r.AI_AGENT==="codex"?"codex":"claude-code",l=O(qn(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{o.heading("Downloading the latest Klaudius template");let y=await me({licenseKey:n,machineId:ie(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:g,destDir:l});o.success(`Fetched ${y.filesExtracted} canonical files`),A=l}catch(y){o.error(y.message),o.detail("Update aborted. Your project is unchanged."),await ae(l,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let h=await Xn(A,t,s),P=h.filter(y=>y.state==="new"),L=h.filter(y=>y.state==="clean-update"),U=h.filter(y=>y.state==="user-only"),N=h.filter(y=>y.state==="conflict"),b=h.filter(y=>y.state==="no-change"),w=h.filter(y=>y.state==="removed-clean"),V=h.filter(y=>y.state==="removed-modified"),x=[...N,...V];if(o.blank(),o.heading("Change summary"),o.detail(`${H(b.length,"file")} unchanged`),o.detail(`${H(P.length,"new file")}`),o.detail(`${H(L.length,"file")} updated cleanly (no local edits)`),o.detail(`${H(U.length,"file")} you've edited (no upstream change \u2014 left alone)`),o.detail(`${H(w.length,"file")} removed upstream (deleted cleanly)`),o.detail(`${H(N.length,"file")} with conflicts (you edited AND we have a new version)`),o.detail(`${H(V.length,"file")} removed upstream but edited locally (need your decision)`),P.length===0&&L.length===0&&w.length===0&&x.length===0){o.blank(),oe.outro(Ne.green("Already up to date.")),await ae(l,{recursive:!0,force:!0}).catch(()=>{});return}o.blank(),o.heading("Applying clean updates");for(let y of[...P,...L]){let j=O(A,y.path),X=O(t,y.path);await _t(St(X),{recursive:!0}),await Tt(j,X),s.files[y.path]=y.canonicalHash}P.length+L.length>0&&o.success(`Wrote ${H(P.length+L.length,"file")}`);for(let y of w){let j=O(t,y.path);await ae(j,{force:!0}),delete s.files[y.path]}if(w.length>0&&o.success(`Deleted ${H(w.length,"file")} removed upstream`),x.length>0){o.blank(),o.heading(`${x.length} conflict(s) need resolution`);let y=O(t,".klaudius","incoming");try{await ae(y,{recursive:!0,force:!0})}catch{}for(let j of N){let X=O(A,j.path),re=O(y,j.path);await _t(St(re),{recursive:!0}),await Tt(X,re)}await Ct(O(t,".klaudius","conflicts.md"),Jn(x,s.templateVersion,Pe),"utf-8"),N.length>0&&o.detail("Staged canonical versions to .klaudius/incoming/"),o.detail("Wrote conflict report to .klaudius/conflicts.md")}if(s.updatedAt=new Date().toISOString(),x.length===0&&(s.templateVersion=Pe),await ce(t,s),o.blank(),x.length===0)oe.outro(Ne.green("Update complete."));else{let y=g==="codex"?"Codex":"Claude Code";oe.outro(Ne.yellow(`${x.length} conflict(s) staged. Open ${y} in this project and ask:
59
- "Run /resolve-conflicts"`))}await ae(l,{recursive:!0,force:!0}).catch(()=>{})}async function Xn(e,t,s){let n=await xt(e),i=new Set(n),a=[];for(let r of n){let c=await le(O(e,r)),p=s.files[r],g=O(t,r),l;try{await It(g),l=await le(g)}catch{a.push({path:r,state:"new",canonicalHash:c,manifestHash:p});continue}c===p?l===p?a.push({path:r,state:"no-change",canonicalHash:c,localHash:l,manifestHash:p}):a.push({path:r,state:"user-only",canonicalHash:c,localHash:l,manifestHash:p}):l===p?a.push({path:r,state:"clean-update",canonicalHash:c,localHash:l,manifestHash:p}):a.push({path:r,state:"conflict",canonicalHash:c,localHash:l,manifestHash:p})}for(let r of Object.keys(s.files)){if(i.has(r))continue;let c=s.files[r],p=O(t,r),g;try{await It(p),g=await le(p)}catch{delete s.files[r];continue}g===c?a.push({path:r,state:"removed-clean",localHash:g,manifestHash:c}):a.push({path:r,state:"removed-modified",localHash:g,manifestHash:c})}return a}function H(e,t){return`${e} ${t}${e===1?"":"s"}`}async function xt(e,t=e){let s=await Wn(e,{withFileTypes:!0}),n=[];for(let i of s){let a=O(e,i.name);i.isDirectory()?n.push(...await xt(a,t)):i.isFile()&&n.push(zn(t,a))}return n}function Jn(e,t,s){let n=e.filter(c=>c.state==="conflict").length,i=e.filter(c=>c.state==="removed-modified").length,a=[];a.push("# Update Conflicts"),a.push(""),a.push(`Generated by \`npx klaudius update\` on ${new Date().toISOString()}.`),a.push(`Updating from canonical version **${t}** to **${s}**.`),a.push("");let r=[];n>0&&r.push(`${n} file${n===1?"":"s"} ha${n===1?"s":"ve"} BOTH local edits AND upstream changes`),i>0&&r.push(`${i} file${i===1?"":"s"} ${i===1?"was":"were"} removed upstream but edited locally`),a.push(r.join(", and ")+"."),a.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),a.push(""),a.push("---"),a.push("");for(let c of e)a.push(`## ${c.path}`),a.push(""),c.state==="removed-modified"?(a.push("**Type:** Removed upstream"),a.push(""),a.push(`- Your local copy: \`${c.path}\``),a.push("- This file no longer exists in the canonical template."),a.push("- You've modified it locally since install."),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),a.push("2. Delete \u2014 remove the file from disk and from the manifest")):(a.push("**Type:** Edit conflict"),a.push(""),a.push(`- Your version (with your local edits): \`${c.path}\``),a.push(`- New canonical version: \`.klaudius/incoming/${c.path}\``),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(`- New canonical hash: \`${(c.canonicalHash??"(none)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 discard the new canonical changes"),a.push("2. Take canonical \u2014 overwrite my edits with the new version"),a.push("3. Merge \u2014 review both side-by-side and produce a combined version")),a.push(""),a.push("---"),a.push("");return a.join(`
60
- `)}import{access as Qn,readFile as vt,stat as Zn}from"fs/promises";import{join as M}from"path";import S from"picocolors";import{spawn as eo}from"child_process";async function Ot(e){let t=e.projectRoot??process.cwd(),s=[];console.log(S.bold(`Klaudius doctor \u2014 checking your project\u2026
61
- `)),s.push(await to()),s.push(await no());let n=M(t,".env"),i=M(t,".klaudius","manifest.json"),a=M(t,".mcp.json"),r=M(t,".codex","config.toml"),c=await W(n),p=await W(i),g="claude-code";if(c)try{$(await vt(n,"utf-8")).AI_AGENT==="codex"&&(g="codex")}catch{}if(g==="claude-code"){let h=await W(M(t,"AGENTS.md")),P=!await W(M(t,".claude"));h&&P&&(g="codex")}if(s.push({name:".env present",status:c?"ok":"fail",detail:c?n:"missing",nextAction:c?void 0:"Run `npx klaudius init` in this folder."}),s.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?"ok":"fail",detail:p?i:"missing",nextAction:p?void 0:c?"Init didn't finish \u2014 run `npx klaudius init` and pick Resume.":"Run `npx klaudius init`."}),g==="codex"){let h=await W(r);s.push({name:".codex/config.toml present",status:h?"ok":"warn",detail:h?r:"missing",nextAction:h?void 0:"Run `npx klaudius configure` to regenerate."})}else{let h=await W(a);s.push({name:".mcp.json present",status:h?"ok":"warn",detail:h?a:"missing",nextAction:h?void 0:"Run `npx klaudius configure` to regenerate."})}if(s.push(await ro(g)),s.push(await oo(t)),s.push(await so(t)),s.push(await io()),!c)s.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)s.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let h=await vt(n,"utf-8"),P=$(h);await ao(P,s)}console.log();for(let h of s){let P=h.status==="ok"?S.green("\u2713"):h.status==="warn"?S.yellow("\u26A0"):h.status==="skip"?S.dim("\xB7"):S.red("\u2717");console.log(` ${P} ${h.name}${h.detail?S.dim(` \u2014 ${h.detail}`):""}`),h.nextAction&&console.log(` ${S.dim("\u2192")} ${S.cyan(h.nextAction)}`)}let l=s.filter(h=>h.status==="fail").length,A=s.filter(h=>h.status==="warn").length;console.log(),l===0&&A===0?console.log(S.green(S.bold("Everything checks out. You're good to go."))):l===0?console.log(S.yellow(S.bold(`${A} warning${A===1?"":"s"} \u2014 review above.`))):(console.log(S.red(S.bold(`${l} failed check${l===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function W(e){try{return await Qn(e),!0}catch{return!1}}async function to(){let e=await Z();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 no(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let s=parseInt(t[1],10),n=parseInt(t[2],10);return s<22||s===22&&n<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function oo(e){let t=M(e,"node_modules");if(!await W(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius install` in this folder."};try{if(!(await Zn(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 so(e){let t=process.platform==="darwin"?M(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?M(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):M(process.env.HOME??"",".cache","ms-playwright");return await W(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 io(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
57
+ Link a Device, and point it at the QR shown in this terminal.`)),s.blank();for(let u of l.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${u}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${u})`));let m=wt(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:o,stdio:"inherit"});m.status===0?s.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${m.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${u}`))),s.blank()}}else if(V&&!x){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 l.whatsappAccounts)console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${u}`))}s.blank();let y=[...b,...U?["schema"]:[]];if(y.length>0){k.outro(d.yellow(d.bold(`Setup paused \u2014 ${y.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),s.blank();for(let[J,Dt]of Object.entries(w))console.log(d.yellow(`Likely cause of ${J} failure:`)),console.log(d.dim(` ${Dt}`)),s.blank();let u=o!==process.cwd()?` ${d.cyan(`cd ${e.target}`)}
58
+ `:"",m=l.aiAgent==="codex"?"codex":"claude",f=l.aiAgent==="codex"?"Codex":"Claude Code",E=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";b.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan(m)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${b.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(d.dim(` (Don't have ${f} yet? Install with: \`${E}\`)`)),s.blank(),console.log(d.dim("Or do it yourself:")),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify everything")}`),s.blank()),U&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(N)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),b.includes("pip")&&!w.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 ${Un()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),s.blank());let Y=["npm","playwright","patchright"].filter(J=>b.includes(J)&&!w[J]);if(Y.length>0){let J=Y.length===1?"keeps":"keep";console.log(d.dim(`If ${Y.join(" / ")} ${J} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}k.outro(d.green(d.bold("Project ready."))),console.log(d.dim("Next steps:")),o!==process.cwd()&&console.log(` ${d.cyan(`cd ${e.target}`)}`);let j=process.platform==="win32"?"start":process.platform==="linux"?"xdg-open":"open",X=d.dim("# read this first \u2014 operator basics + commands");console.log(` ${d.cyan(`${j} DOCS.html`)}${" ".repeat(Math.max(1,17-j.length))}${X}`);let re=l.aiAgent==="codex"?"codex":"claude",De=l.aiAgent==="codex"?"Codex":"Claude Code";console.log(` ${d.cyan(re)} ${d.dim(`# open ${De} in this project`)}`),console.log(` ${d.dim(`then ask ${De}:`)}`),console.log(` ${d.cyan(' "Run the pipeline."')}`),s.blank()}async function D(e,t){await xe(e,{recursive:!0}),await Re(q(e,".env"),ue(t),"utf-8"),t.aiAgent==="codex"?(await xe(q(e,".codex"),{recursive:!0}),await Re(q(e,".codex","config.toml"),fe(t),"utf-8")):(await Re(q(e,".mcp.json"),pe(t),"utf-8"),await Ee(e,"supabase"))}async function $n(e){try{(await yt(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Rn(e),o=t.filter(c=>!c.startsWith(".DS_Store"));if(o.length===0)return{kind:"fresh"};let n=new Set([".env",".mcp.json",".claude",".codex"]),i=o.every(c=>n.has(c)),a=o.includes(".env"),r=t.includes(".klaudius");if(i&&a&&!r)return{kind:"partial",envPath:q(e,".env")};if(r&&a){let c=!0;try{c=!(await yt(q(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:o}}async function Nn(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?",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 Ln(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:o=>o.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 Dn(e){let t=On(e);if(process.platform==="win32"){let o=t.toLowerCase();if(o.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(o.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(o.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(o.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let o=["/System/","/usr/","/bin/","/sbin/"];for(let n of o)if(t.startsWith(n))return`Inside ${n.slice(0,-1)} (system-managed directory).`}}function Mn(){if(process.platform!=="win32")return!1;try{return wt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Un(){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/"}}import{access as jn,readFile as Kn}from"fs/promises";import{join as ve,resolve as Hn}from"path";import v from"picocolors";async function Pt(e){let t=e.target?Hn(process.cwd(),e.target):process.cwd(),o=await At(ve(t,".env")),n=await At(ve(t,"package.json"));(!o||!n)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),o||s.detail("Missing: .env"),n||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let i="claude-code";try{$(await Kn(ve(t,".env"),"utf-8")).AI_AGENT==="codex"&&(i="codex")}catch{}s.heading("Installing dependencies");let a=await we(t);s.blank(),s.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let r=[];if(a.npm==="failed"&&r.push("npm"),a.pip==="failed"&&r.push("pip"),a.playwright==="failed"&&r.push("playwright"),a.patchright==="failed"&&r.push("patchright"),r.length===0){s.blank(),console.log(v.green(v.bold("All dependencies installed."))),console.log(v.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(v.yellow(v.bold(`${r.join(", ")} still failing.`))),s.blank();for(let[l,A]of Object.entries(a.hints??{}))console.log(v.yellow(`Likely cause of ${l} failure:`)),console.log(v.dim(` ${A}`)),s.blank();let c=i==="codex"?"codex":"claude",p=i==="codex"?"Codex":"Claude Code",g=i==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(v.dim("Options:")),console.log(v.dim(` \u2022 Open ${p} in this folder (\`${c}\`) and paste:`)),console.log(v.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(v.dim(` (Don't have ${p} yet? Install with: \`${g}\`)`)),console.log(v.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(v.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function At(e){try{return await jn(e),!0}catch{return!1}}import{readFile as Fn,writeFile as Oe,access as Vn}from"fs/promises";import{join as ne}from"path";import*as Ae from"@clack/prompts";import K from"picocolors";import{mkdir as Gn}from"fs/promises";async function bt(e){let t=e.projectRoot??process.cwd(),o=ne(t,".env"),n=ne(t,".mcp.json"),i=ne(t,".codex","config.toml"),a=await $e(ne(t,".klaudius","manifest.json")),r=await $e(o);!a&&!r&&(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=G();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 h=await Fn(o,"utf-8");p=$(h)}catch{s.warn("No .env found. Starting from an empty configuration.")}let g=Qe(p);Ae.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let l=await I(g),A=g.aiAgent??"claude-code";if(l.aiAgent&&l.aiAgent!==A&&(s.error(`Switching AI coding agent (${A} \u2192 ${l.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(` ${K.cyan("npx klaudius@latest init <new-folder>")} ${K.dim("# pick the new agent in the wizard")}`),s.blank(),s.detail(".env is unchanged."),process.exit(1)),l.supabaseUrl!==p.SUPABASE_URL||l.supabaseServiceKey!==p.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let h=await ee({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});h.ok||(s.error(h.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}await Oe(o,ue(l),"utf-8"),s.success("Updated .env"),l.aiAgent==="codex"?(await Gn(ne(t,".codex"),{recursive:!0}),await Oe(i,fe(l),"utf-8"),s.success("Updated .codex/config.toml")):(await Oe(n,pe(l),"utf-8"),s.success("Updated .mcp.json"),await Ee(t,"supabase")),s.blank(),Ae.outro(K.green("Configuration updated.")),await Bn(t,a)}async function Bn(e,t){let o=await $e(ne(e,"node_modules"));s.blank(),t?o||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${K.cyan("npx klaudius@latest install")} ${K.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${K.cyan("npx klaudius@latest doctor")} ${K.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(` ${K.cyan("npx klaudius@latest init")} ${K.dim("# pick Resume when prompted")}`),s.blank())}async function $e(e){try{return await Vn(e),!0}catch{return!1}}import{copyFile as Tt,mkdir as _t,readdir as Wn,readFile as Yn,rm as ae,writeFile as Ct,access as It}from"fs/promises";import{dirname as St,join as O,relative as zn}from"path";import{tmpdir as qn}from"os";import*as se from"@clack/prompts";import Ne from"picocolors";var Pe="0.16.1";async function Rt(e){let t=e.projectRoot??process.cwd(),o=await Ve(t);o||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let y of Fe)delete o.files[y];let n,i=O(t,".env"),a,r;try{a=await Yn(i,"utf-8"),r=$(a)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}n=r.KLAUDIUS_LICENSE_KEY??"",n||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius@latest init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=Je(a,r,Xe);c!==null&&(await Ct(i,c,"utf-8"),s.detail("Backfilled new env keys")),await he("update",Pe),se.intro(`Update from ${o.templateVersion} \u2192 ${Pe}`);let g=r.AI_AGENT==="codex"?"codex":"claude-code",l=O(qn(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{s.heading("Downloading the latest Klaudius template");let y=await me({licenseKey:n,machineId:ie(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:g,destDir:l});s.success(`Fetched ${y.filesExtracted} canonical files`),A=l}catch(y){s.error(y.message),s.detail("Update aborted. Your project is unchanged."),await ae(l,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let h=await Xn(A,t,o),P=h.filter(y=>y.state==="new"),L=h.filter(y=>y.state==="clean-update"),U=h.filter(y=>y.state==="user-only"),N=h.filter(y=>y.state==="conflict"),b=h.filter(y=>y.state==="no-change"),w=h.filter(y=>y.state==="removed-clean"),V=h.filter(y=>y.state==="removed-modified"),x=[...N,...V];if(s.blank(),s.heading("Change summary"),s.detail(`${H(b.length,"file")} unchanged`),s.detail(`${H(P.length,"new file")}`),s.detail(`${H(L.length,"file")} updated cleanly (no local edits)`),s.detail(`${H(U.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${H(w.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${H(N.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${H(V.length,"file")} removed upstream but edited locally (need your decision)`),P.length===0&&L.length===0&&w.length===0&&x.length===0){s.blank(),se.outro(Ne.green("Already up to date.")),await ae(l,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let y of[...P,...L]){let j=O(A,y.path),X=O(t,y.path);await _t(St(X),{recursive:!0}),await Tt(j,X),o.files[y.path]=y.canonicalHash}P.length+L.length>0&&s.success(`Wrote ${H(P.length+L.length,"file")}`);for(let y of w){let j=O(t,y.path);await ae(j,{force:!0}),delete o.files[y.path]}if(w.length>0&&s.success(`Deleted ${H(w.length,"file")} removed upstream`),x.length>0){s.blank(),s.heading(`${x.length} conflict(s) need resolution`);let y=O(t,".klaudius","incoming");try{await ae(y,{recursive:!0,force:!0})}catch{}for(let j of N){let X=O(A,j.path),re=O(y,j.path);await _t(St(re),{recursive:!0}),await Tt(X,re)}await Ct(O(t,".klaudius","conflicts.md"),Jn(x,o.templateVersion,Pe),"utf-8"),N.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}if(o.updatedAt=new Date().toISOString(),x.length===0&&(o.templateVersion=Pe),await ce(t,o),s.blank(),x.length===0)se.outro(Ne.green("Update complete."));else{let y=g==="codex"?"Codex":"Claude Code";se.outro(Ne.yellow(`${x.length} conflict(s) staged. Open ${y} in this project and ask:
59
+ "Run /resolve-conflicts"`))}await ae(l,{recursive:!0,force:!0}).catch(()=>{})}async function Xn(e,t,o){let n=await xt(e),i=new Set(n),a=[];for(let r of n){let c=await le(O(e,r)),p=o.files[r],g=O(t,r),l;try{await It(g),l=await le(g)}catch{a.push({path:r,state:"new",canonicalHash:c,manifestHash:p});continue}c===p?l===p?a.push({path:r,state:"no-change",canonicalHash:c,localHash:l,manifestHash:p}):a.push({path:r,state:"user-only",canonicalHash:c,localHash:l,manifestHash:p}):l===p?a.push({path:r,state:"clean-update",canonicalHash:c,localHash:l,manifestHash:p}):a.push({path:r,state:"conflict",canonicalHash:c,localHash:l,manifestHash:p})}for(let r of Object.keys(o.files)){if(i.has(r))continue;let c=o.files[r],p=O(t,r),g;try{await It(p),g=await le(p)}catch{delete o.files[r];continue}g===c?a.push({path:r,state:"removed-clean",localHash:g,manifestHash:c}):a.push({path:r,state:"removed-modified",localHash:g,manifestHash:c})}return a}function H(e,t){return`${e} ${t}${e===1?"":"s"}`}async function xt(e,t=e){let o=await Wn(e,{withFileTypes:!0}),n=[];for(let i of o){let a=O(e,i.name);i.isDirectory()?n.push(...await xt(a,t)):i.isFile()&&n.push(zn(t,a))}return n}function Jn(e,t,o){let n=e.filter(c=>c.state==="conflict").length,i=e.filter(c=>c.state==="removed-modified").length,a=[];a.push("# Update Conflicts"),a.push(""),a.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),a.push(`Updating from canonical version **${t}** to **${o}**.`),a.push("");let r=[];n>0&&r.push(`${n} file${n===1?"":"s"} ha${n===1?"s":"ve"} BOTH local edits AND upstream changes`),i>0&&r.push(`${i} file${i===1?"":"s"} ${i===1?"was":"were"} removed upstream but edited locally`),a.push(r.join(", and ")+"."),a.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),a.push(""),a.push("---"),a.push("");for(let c of e)a.push(`## ${c.path}`),a.push(""),c.state==="removed-modified"?(a.push("**Type:** Removed upstream"),a.push(""),a.push(`- Your local copy: \`${c.path}\``),a.push("- This file no longer exists in the canonical template."),a.push("- You've modified it locally since install."),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),a.push("2. Delete \u2014 remove the file from disk and from the manifest")):(a.push("**Type:** Edit conflict"),a.push(""),a.push(`- Your version (with your local edits): \`${c.path}\``),a.push(`- New canonical version: \`.klaudius/incoming/${c.path}\``),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(`- New canonical hash: \`${(c.canonicalHash??"(none)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 discard the new canonical changes"),a.push("2. Take canonical \u2014 overwrite my edits with the new version"),a.push("3. Merge \u2014 review both side-by-side and produce a combined version")),a.push(""),a.push("---"),a.push("");return a.join(`
60
+ `)}import{access as Qn,readFile as vt,stat as Zn}from"fs/promises";import{join as M}from"path";import S from"picocolors";import{spawn as es}from"child_process";async function Ot(e){let t=e.projectRoot??process.cwd(),o=[];console.log(S.bold(`Klaudius doctor \u2014 checking your project\u2026
61
+ `)),o.push(await ts()),o.push(await ns());let n=M(t,".env"),i=M(t,".klaudius","manifest.json"),a=M(t,".mcp.json"),r=M(t,".codex","config.toml"),c=await W(n),p=await W(i),g="claude-code";if(c)try{$(await vt(n,"utf-8")).AI_AGENT==="codex"&&(g="codex")}catch{}if(g==="claude-code"){let h=await W(M(t,"AGENTS.md")),P=!await W(M(t,".claude"));h&&P&&(g="codex")}if(o.push({name:".env present",status:c?"ok":"fail",detail:c?n:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."}),o.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?"ok":"fail",detail:p?i:"missing",nextAction:p?void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."}),g==="codex"){let h=await W(r);o.push({name:".codex/config.toml present",status:h?"ok":"warn",detail:h?r:"missing",nextAction:h?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let h=await W(a);o.push({name:".mcp.json present",status:h?"ok":"warn",detail:h?a:"missing",nextAction:h?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(o.push(await rs(g)),o.push(await ss(t)),o.push(await os(t)),o.push(await is()),!c)o.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)o.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let h=await vt(n,"utf-8"),P=$(h);await as(P,o)}console.log();for(let h of o){let P=h.status==="ok"?S.green("\u2713"):h.status==="warn"?S.yellow("\u26A0"):h.status==="skip"?S.dim("\xB7"):S.red("\u2717");console.log(` ${P} ${h.name}${h.detail?S.dim(` \u2014 ${h.detail}`):""}`),h.nextAction&&console.log(` ${S.dim("\u2192")} ${S.cyan(h.nextAction)}`)}let l=o.filter(h=>h.status==="fail").length,A=o.filter(h=>h.status==="warn").length;console.log(),l===0&&A===0?console.log(S.green(S.bold("Everything checks out. You're good to go."))):l===0?console.log(S.yellow(S.bold(`${A} warning${A===1?"":"s"} \u2014 review above.`))):(console.log(S.red(S.bold(`${l} failed check${l===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function W(e){try{return await Qn(e),!0}catch{return!1}}async function ts(){let e=await Z();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 ns(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let o=parseInt(t[1],10),n=parseInt(t[2],10);return o<22||o===22&&n<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function ss(e){let t=M(e,"node_modules");if(!await W(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await Zn(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 os(e){let t=process.platform==="darwin"?M(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?M(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):M(process.env.HOME??"",".cache","ms-playwright");return await W(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 is(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
62
62
  try:
63
63
  ${e.map(n=>` import ${n}`).join(`
64
64
  `)}
65
65
  except Exception as e:
66
66
  print(str(e))
67
67
  sys.exit(1)
68
- `,s=await $t("python3",["-c",t]);return s.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(s.stdout||s.stderr).trim().split(`
69
- `).pop()??"import failed",nextAction:"Run `npx klaudius install` in this folder."}}async function ao(e,t){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let n=await ee({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:n.ok?"ok":"fail",detail:n.ok?"connected":n.message,nextAction:n.ok?void 0:"Run `npx klaudius configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});if((e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":"vercel")==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let n=await ye({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:n.ok?"ok":"fail",detail:n.ok?`valid (${n.projectCount??0} Pages project${n.projectCount===1?"":"s"})`:n.message,nextAction:n.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius configure`."})}else t.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius configure` and pick Cloudflare."});else if(e.VERCEL_TOKEN){let n=await ge(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:n.ok?"ok":"fail",detail:n.ok?n.username??"valid":n.message,nextAction:n.ok?void 0:"Generate a new token at https://vercel.com/account/tokens, then `npx klaudius configure`."})}else t.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let n=await ke(e.GOOGLE_PLACES_API_KEY);t.push({name:"Google Places API key",status:n.ok?"ok":"fail",detail:n.ok?"accepted":n.message,nextAction:n.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius configure`."})}else t.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let n=await Ke({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:n.ok?"ok":"fail",detail:n.ok?`bot ${n.botHandle??"ok"} (chat_id not tested)`:n.message,nextAction:n.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?t.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):t.push({name:"Telegram credentials",status:"skip",detail:"not configured (optional)"})}async function ro(e){let t=e==="codex"?"codex":"claude",s=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",n=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",i=await $t(t,["--version"]);return i.code===0?{name:s,status:"ok",detail:(i.stdout||i.stderr).trim().split(`
70
- `)[0]}:{name:s,status:"warn",detail:"not found",nextAction:n}}function $t(e,t){return new Promise(s=>{let n=eo(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";n.stdout?.on("data",r=>{i+=r.toString()}),n.stderr?.on("data",r=>{a+=r.toString()}),n.on("close",r=>s({code:r??1,stdout:i,stderr:a})),n.on("error",()=>s({code:1,stdout:i,stderr:a}))})}import{existsSync as lo}from"fs";import{spawnSync as co}from"child_process";import{join as uo,resolve as po}from"path";import R from"picocolors";async function Nt(e){let t=po(e.projectRoot??process.cwd()),s=uo(t,"scripts","whatsapp.mjs");lo(s)||(console.error(R.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(R.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius init`).")),console.error(R.dim(`Looked for: ${s}`)),process.exit(1));let n=(e.label??"primary").trim(),i=n.replace(/[^A-Za-z0-9_-]/g,"");i||(console.error(R.red(`Invalid label '${n}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),i!==n&&console.error(R.yellow(`Note: cleaned label '${n}' \u2192 '${i}' (filename-safe characters only).`)),console.log(R.cyan(`Pairing WhatsApp account '${i}'...`)),console.log(R.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
71
- `));let a=co(process.execPath,[s,"pair","--account",i],{cwd:t,stdio:"inherit"});if(a.status===0){console.log(R.green(`Paired '${i}'.`)),console.log(R.dim(`
68
+ `,o=await $t("python3",["-c",t]);return o.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(o.stdout||o.stderr).trim().split(`
69
+ `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function as(e,t){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let n=await ee({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:n.ok?"ok":"fail",detail:n.ok?"connected":n.message,nextAction:n.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});if((e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":"vercel")==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let n=await ye({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:n.ok?"ok":"fail",detail:n.ok?`valid (${n.projectCount??0} Pages project${n.projectCount===1?"":"s"})`:n.message,nextAction:n.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Cloudflare."});else if(e.VERCEL_TOKEN){let n=await ge(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:n.ok?"ok":"fail",detail:n.ok?n.username??"valid":n.message,nextAction:n.ok?void 0:"Generate a new token at https://vercel.com/account/tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let n=await ke(e.GOOGLE_PLACES_API_KEY);t.push({name:"Google Places API key",status:n.ok?"ok":"fail",detail:n.ok?"accepted":n.message,nextAction:n.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius@latest configure`."})}else t.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let n=await Ke({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:n.ok?"ok":"fail",detail:n.ok?`bot ${n.botHandle??"ok"} (chat_id not tested)`:n.message,nextAction:n.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?t.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):t.push({name:"Telegram credentials",status:"skip",detail:"not configured (optional)"})}async function rs(e){let t=e==="codex"?"codex":"claude",o=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",n=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",i=await $t(t,["--version"]);return i.code===0?{name:o,status:"ok",detail:(i.stdout||i.stderr).trim().split(`
70
+ `)[0]}:{name:o,status:"warn",detail:"not found",nextAction:n}}function $t(e,t){return new Promise(o=>{let n=es(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";n.stdout?.on("data",r=>{i+=r.toString()}),n.stderr?.on("data",r=>{a+=r.toString()}),n.on("close",r=>o({code:r??1,stdout:i,stderr:a})),n.on("error",()=>o({code:1,stdout:i,stderr:a}))})}import{existsSync as ls}from"fs";import{spawnSync as cs}from"child_process";import{join as ds,resolve as us}from"path";import R from"picocolors";async function Nt(e){let t=us(e.projectRoot??process.cwd()),o=ds(t,"scripts","whatsapp.mjs");ls(o)||(console.error(R.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(R.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(R.dim(`Looked for: ${o}`)),process.exit(1));let n=(e.label??"primary").trim(),i=n.replace(/[^A-Za-z0-9_-]/g,"");i||(console.error(R.red(`Invalid label '${n}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),i!==n&&console.error(R.yellow(`Note: cleaned label '${n}' \u2192 '${i}' (filename-safe characters only).`)),console.log(R.cyan(`Pairing WhatsApp account '${i}'...`)),console.log(R.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
71
+ `));let a=cs(process.execPath,[o,"pair","--account",i],{cwd:t,stdio:"inherit"});if(a.status===0){console.log(R.green(`Paired '${i}'.`)),console.log(R.dim(`
72
72
  If you haven't already, add '${i}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
73
73
  WHATSAPP_ACCOUNTS=primary,${i}
74
- (Skip this if '${i}' is already there or you set it via the init wizard.)`));return}a.error?console.error(R.red(`Pair failed: ${a.error.message}`)):(console.error(R.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(R.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(R.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(R.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${i}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as fo}from"child_process";var Le="--use-system-ca";function Lt(){let e=process.env.NODE_OPTIONS??"";if(e.includes(Le)||!G().ok)return;let s=e?`${e} ${Le}`:Le,n=fo(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:s},stdio:"inherit"});n.signal&&(process.kill(process.pid,n.signal),process.exit(1)),process.exit(n.status??1)}Lt();var ho="0.16.0",F=new mo;F.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(ho);F.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 Ye({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});F.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 Et({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(s){console.error("init failed:",s.message),process.exit(1)}});F.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 Pt({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});F.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await bt({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});F.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await Rt({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});F.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 Ot({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});F.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 Nt({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});F.parse(process.argv);
74
+ (Skip this if '${i}' is already there or you set it via the init wizard.)`));return}a.error?console.error(R.red(`Pair failed: ${a.error.message}`)):(console.error(R.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(R.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(R.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(R.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${i}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as ps}from"child_process";var Le="--use-system-ca";function Lt(){let e=process.env.NODE_OPTIONS??"";if(e.includes(Le)||!G().ok)return;let o=e?`${e} ${Le}`:Le,n=ps(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:o},stdio:"inherit"});n.signal&&(process.kill(process.pid,n.signal),process.exit(1)),process.exit(n.status??1)}Lt();var ms="0.16.1",F=new fs;F.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(ms);F.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 Ye({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});F.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 Et({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(o){console.error("init failed:",o.message),process.exit(1)}});F.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 Pt({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});F.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await bt({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});F.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await Rt({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});F.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 Ot({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});F.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 Nt({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});F.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klaudius",
3
- "version": "0.16.0",
3
+ "version": "0.16.1",
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": {