klaudius 0.14.0 → 0.15.0

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