klaudius 0.15.2 → 0.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +18 -18
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -5,57 +5,57 @@ import{a as Q,b as Me,c as Ue,d as _,f as je,g as Ke}from"./chunk-SZ4KCTSL.js";i
5
5
  Please share that file so we can trace what happened.`);return t}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 n=[],s=i=>{n.push(""),n.push("# "+"=".repeat(60)),n.push(`# ${i}`),n.push("# "+"=".repeat(60)),n.push("")},t=(i,a)=>{if(a==null||a===""){n.push(`# ${i}=`);return}let r=String(a);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(r)){let c=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");n.push(`${i}="${c}"`)}else n.push(`${i}=${r}`)};return n.push("# Klaudius configuration"),n.push("# Generated by `npx klaudius init`. Edit freely."),n.push("# NEVER commit this file. .gitignore already excludes it."),s("Klaudius licence"),t("KLAUDIUS_LICENSE_KEY",e.licenseKey),s("AI coding agent"),t("AI_AGENT",e.aiAgent??be),s("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),s("Pricing"),t("PRICING",e.pricing),t("PRICING_TERMS",e.pricingTerms),t("PRICING_MONTHLY",e.pricingMonthly),s("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(",")),s("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),s("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),s("WhatsApp outreach"),t("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),s("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),s("Deployment"),t("DEPLOY_PROVIDER",e.deployProvider??Te),t("VERCEL_TOKEN",e.vercelToken),t("VERCEL_SCOPE",e.vercelScope??""),t("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),t("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("Search APIs"),t("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),t("SERPAPI_KEY",e.serpapiKey),s("Telegram notifications (optional)"),t("TELEGRAM_BOT_TOKEN",e.telegramBotToken),t("TELEGRAM_CHAT_ID",e.telegramChatId),s("Rate limiting (sensible defaults)"),t("REQUESTS_PER_MINUTE",10),t("REQUEST_DELAY",2),n.join(`
6
6
  `)+`
7
7
  `}function pe(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)+`
8
- `}function me(e){let n=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=${n}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${s}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
8
+ `}function fe(e){let n=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=${n}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${s}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
9
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 `npx klaudius configure` (adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID)."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'}];function qt(e,n){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(n)){let s=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${s}"`}return`${e}=${n}`}function Xe(e,n,s){let t=s.filter(r=>!(r.key in n));if(t.length===0)return null;let i=e.endsWith(`
10
10
  `)?"":`
11
11
  `,a=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let r of t)a.push(""),r.comment&&a.push(`# ${r.comment}`),a.push(qt(r.key,r.value));return e+i+a.join(`
12
12
  `)+`
13
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 n={};for(let s of e.split(`
14
- `)){let t=s.trim();if(!t||t.startsWith("#"))continue;let i=t.indexOf("=");if(i===-1)continue;let a=t.slice(0,i).trim(),r=Xt(t.slice(i+1).trim());n[a]=r}return n}function Je(e){let n=c=>{let p=e[c];if(!p)return;let g=parseInt(p,10);return isNaN(g)?void 0:g},s=e.SMS_PROVIDER,t=c=>c==="email"||c==="sms"||c==="whatsapp",i=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(t),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(t),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:i&&i.length>0?i:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort: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: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 n=w=>{let V=e[w];if(!V)return;let x=parseInt(V,10);return isNaN(x)?void 0:x},s=e.SUPABASE_URL,t=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),i=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,r=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",p=ze(e.DEPLOY_PROVIDER)??Te,g=e.VERCEL_TOKEN,l=e.CLOUDFLARE_API_TOKEN,A=e.CLOUDFLARE_ACCOUNT_ID;if(!r||!s||!t||!i||!a||!(p==="cloudflare"?!!l&&!!A:!!g))return null;let P=e.SMS_PROVIDER,L=w=>w==="email"||w==="sms"||w==="whatsapp",U=e.OUTREACH_CHANNELS?.split(",").map(w=>w.trim()).filter(L),N=e.OUTREACH_PRIORITY?.split(",").map(w=>w.trim()).filter(L),b=e.WHATSAPP_ACCOUNTS?.split(",").map(w=>w.trim()).filter(w=>w.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent: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: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:l||void 0,cloudflareAccountId:A||void 0,supabaseUrl:s,supabaseServiceKey:t,supabasePat:i,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{mkdir as 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 n=process.env.KLAUDIUS_TEMPLATE_URL??en,s="0.15.2",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:s,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(r){throw new Error(`Could not reach klaudius.dev to download the template: ${_(r)}`)}if(!t.ok){let r="";try{let c=await t.json();r=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${t.status}${r}`)}if(!t.body)throw new Error("Template download succeeded but response had no body");let i=t.headers.get("x-klaudius-tier");await Jt(e.destDir,{recursive:!0});let a=0;try{await new Promise((r,c)=>{let p=Qe.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{a++}});p.on("finish",r),p.on("error",c),tn(t.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:a,tier:i}}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.2";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 n=e.trim(),t=(process.env.KLAUDIUS_API_URL??sn).replace(/\/$/,"")+an,i=ie(),a;try{a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:n,machine_id:i,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 a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${a.status}).`}}function ie(){let e=[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){let n=e.serviceKey.replace(/\s+/g,"");try{let s=await fetch(e.url+"/rest/v1/",{headers:{apikey:n,Authorization:`Bearer ${n}`}});return s.status===401||s.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${s.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(s){return{ok:!1,message:`Could not reach Supabase: ${_(s)}`}}}async function ot(e){let n;try{n=await ln(cn(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(t){return{ok:!1,message:`Could not read scripts/schema.sql: ${t.message}`}}let s=e.pat.replace(/\s+/g,"");try{let t=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({query:n})});if(t.ok)return{ok:!0};let i=await t.text();return i.includes("already exists")||i.includes('relation "clients" already exists')||i.includes("duplicate")?(o.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${t.status}): ${i.slice(0,300)}`}}catch(t){return{ok:!1,message:`Schema apply failed: ${t.message}`}}}async function he(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 s=await n.json();return{ok:!0,username:s.user?.username??s.user?.email}}catch(n){return{ok:!1,message:`Could not reach Vercel: ${_(n)}`}}}var st="https://api.cloudflare.com/client/v4";function it(e){let n=e?.errors?.[0];if(n)return n.message?`${n.message}${n.code?` (code ${n.code})`:""}`:void 0}async function ge(e){let{token:n,accountId:s}=e,t={Authorization:`Bearer ${n}`,"Content-Type":"application/json"};try{let i=await fetch(`${st}/user/tokens/verify`,{headers:t});if(i.status===401||i.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await i.json(),r=a.result?.status;if(a.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${it(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}try{let i=await fetch(`${st}/accounts/${encodeURIComponent(s)}/pages/projects`,{headers:t});if(i.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${s} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(i.status===404)return{ok:!1,message:`Account ${s} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await i.json();return a.success===!1?{ok:!1,message:it(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}}async function ke(e){try{let 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 s={};try{s=await n.json()}catch{}let t=s.error?.message??"",i=s.error?.status??"";return n.status===400&&(i==="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: ${_(n)}`}}}import dn from"nodemailer";import{ImapFlow as un}from"imapflow";async function rt(e){let n=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 n.verify()}catch(t){return{ok:!1,failedAt:"smtp",message:at(t,"SMTP")}}finally{n.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(t){try{await s.logout()}catch{}return{ok:!1,failedAt:"imap",message:at(t,"IMAP")}}return{ok:!0}}function at(e,n){let s=e instanceof Error?e.message:String(e),t=s.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:
14
+ `)){let t=s.trim();if(!t||t.startsWith("#"))continue;let i=t.indexOf("=");if(i===-1)continue;let a=t.slice(0,i).trim(),r=Xt(t.slice(i+1).trim());n[a]=r}return n}function Je(e){let n=c=>{let p=e[c];if(!p)return;let g=parseInt(p,10);return isNaN(g)?void 0:g},s=e.SMS_PROVIDER,t=c=>c==="email"||c==="sms"||c==="whatsapp",i=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(t),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(t),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:i&&i.length>0?i:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort: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: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 n=w=>{let V=e[w];if(!V)return;let x=parseInt(V,10);return isNaN(x)?void 0:x},s=e.SUPABASE_URL,t=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),i=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,r=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",p=ze(e.DEPLOY_PROVIDER)??Te,g=e.VERCEL_TOKEN,l=e.CLOUDFLARE_API_TOKEN,A=e.CLOUDFLARE_ACCOUNT_ID;if(!r||!s||!t||!i||!a||!(p==="cloudflare"?!!l&&!!A:!!g))return null;let P=e.SMS_PROVIDER,L=w=>w==="email"||w==="sms"||w==="whatsapp",U=e.OUTREACH_CHANNELS?.split(",").map(w=>w.trim()).filter(L),N=e.OUTREACH_PRIORITY?.split(",").map(w=>w.trim()).filter(L),b=e.WHATSAPP_ACCOUNTS?.split(",").map(w=>w.trim()).filter(w=>w.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent: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: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:l||void 0,cloudflareAccountId:A||void 0,supabaseUrl:s,supabaseServiceKey:t,supabasePat:i,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{mkdir as 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 me(e){let n=process.env.KLAUDIUS_TEMPLATE_URL??en,s="0.15.3",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:s,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(r){throw new Error(`Could not reach klaudius.dev to download the template: ${_(r)}`)}if(!t.ok){let r="";try{let c=await t.json();r=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${t.status}${r}`)}if(!t.body)throw new Error("Template download succeeded but response had no body");let i=t.headers.get("x-klaudius-tier");await Jt(e.destDir,{recursive:!0});let a=0;try{await new Promise((r,c)=>{let p=Qe.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{a++}});p.on("finish",r),p.on("error",c),tn(t.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:a,tier:i}}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.3";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 n=e.trim(),t=(process.env.KLAUDIUS_API_URL??sn).replace(/\/$/,"")+an,i=ie(),a;try{a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:n,machine_id:i,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 a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${a.status}).`}}function ie(){let e=[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){let n=e.serviceKey.replace(/\s+/g,"");try{let s=await fetch(e.url+"/rest/v1/",{headers:{apikey:n,Authorization:`Bearer ${n}`}});return s.status===401||s.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${s.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(s){return{ok:!1,message:`Could not reach Supabase: ${_(s)}`}}}async function ot(e){let n;try{n=await ln(cn(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(t){return{ok:!1,message:`Could not read scripts/schema.sql: ${t.message}`}}let s=e.pat.replace(/\s+/g,"");try{let t=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({query:n})});if(t.ok)return{ok:!0};let i=await t.text();return i.includes("already exists")||i.includes('relation "clients" already exists')||i.includes("duplicate")?(o.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${t.status}): ${i.slice(0,300)}`}}catch(t){return{ok:!1,message:`Schema apply failed: ${t.message}`}}}async function he(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 s=await n.json();return{ok:!0,username:s.user?.username??s.user?.email}}catch(n){return{ok:!1,message:`Could not reach Vercel: ${_(n)}`}}}var st="https://api.cloudflare.com/client/v4";function it(e){let n=e?.errors?.[0];if(n)return n.message?`${n.message}${n.code?` (code ${n.code})`:""}`:void 0}async function ge(e){let{token:n,accountId:s}=e,t={Authorization:`Bearer ${n}`,"Content-Type":"application/json"};try{let i=await fetch(`${st}/user/tokens/verify`,{headers:t});if(i.status===401||i.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await i.json(),r=a.result?.status;if(a.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${it(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}try{let i=await fetch(`${st}/accounts/${encodeURIComponent(s)}/pages/projects`,{headers:t});if(i.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${s} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(i.status===404)return{ok:!1,message:`Account ${s} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await i.json();return a.success===!1?{ok:!1,message:it(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}}async function ke(e){try{let 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 s={};try{s=await n.json()}catch{}let t=s.error?.message??"",i=s.error?.status??"";return n.status===400&&(i==="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: ${_(n)}`}}}import dn from"nodemailer";import{ImapFlow as un}from"imapflow";async function rt(e){let n=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 n.verify()}catch(t){return{ok:!1,failedAt:"smtp",message:at(t,"SMTP")}}finally{n.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(t){try{await s.logout()}catch{}return{ok:!1,failedAt:"imap",message:at(t,"IMAP")}}return{ok:!0}}function at(e,n){let s=e instanceof Error?e.message:String(e),t=s.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:
16
16
  \u2022 The app password is wrong, expired, or for a different provider.
17
17
  \u2022 The email address doesn't match the account that issued the password.
18
- \u2022 2FA is required but no app-specific password was generated.`: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: ${s}`}async function lt(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`,s=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let t=await fetch(n,{headers:{Authorization:`Basic ${s}`}});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 i=await t.json();return i.status&&i.status!=="active"?{ok:!1,message:`Twilio account is in '${i.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:i.friendly_name}}catch(t){return{ok:!1,message:`Could not reach Twilio: ${_(t)}`}}}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,"")}"`,t=await mn(s);if(t.code===0)return{ok:!0};let i=t.stderr.toLowerCase();return i.includes("can't get application")||i.includes("isn't running")||i.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:i.includes("(-1728)")||i.includes("not found")||i.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:i.includes("(-1719)")||i.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${t.stderr.trim()||`exit code ${t.code}`}`}}function mn(e){return new Promise(n=>{let s=pn("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),t="";s.stderr.on("data",i=>{t+=i.toString()}),s.on("close",i=>n({code:i??1,stderr:t})),s.on("error",i=>n({code:1,stderr:i.message}))})}import{spawn as dt}from"child_process";function fn(){let e=process.env.NODE_OPTIONS?.trim(),n=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:n}}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,n){let s=e+`
19
- `+n;return hn.some(t=>t.test(s))}function mt(e){return new Promise(n=>setTimeout(n,e))}function gn(e,n,s){return new Promise(t=>{let i=dt(e,n,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:s.env??process.env}),a="",r="";i.stdout?.on("data",c=>{let p=c.toString();a+=p,process.stdout.write(p)}),i.stderr?.on("data",c=>{let p=c.toString();r+=p,process.stderr.write(p)}),i.on("close",c=>t({code:c??1,stdout:a,stderr:r})),i.on("error",c=>t({code:1,stdout:a,stderr:r+c.message}))})}async function Ce(e,n,s){let t={code:0,stdout:"",stderr:""};for(let i=0;i<=te;i++){if(t=await gn(e,n,{cwd:s.cwd,env:s.env}),t.code===0||!pt(t.stderr,t.stdout))return t;i<te&&(o.detail(`${s.label} failed with a transient network error \u2014 retrying (${i+2}/${te+1})\u2026`),await mt(ut))}return t}function kn(e,n,s){return new Promise(t=>{let i=dt(e,n,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",r="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{r+=c.toString()}),i.on("close",c=>t({code:c??1,stdout:a,stderr:r})),i.on("error",c=>t({code:1,stdout:a,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 n=`${e.stderr??""}
20
- ${e.stdout??""}`;return yn.find(t=>t.pattern.test(n))?.hint}async function En(e){let n=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],s=["-m","pip","install","--quiet","--user"],i=(await Ae())?.command??["python3"],a=async c=>{let p={code:0,stdout:"",stderr:""};for(let g=0;g<=te;g++){if(p=await kn(i[0],[...i.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 a([...s,"--break-system-packages",...n]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(o.detail("Older pip detected; retrying without --break-system-packages"),r=await a([...s,...n])),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 n={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},s=fn(),t=(p,g)=>{let l=wn(g);l&&((n.hints??={})[p]=l)};o.step("Running npm install (Next.js, Playwright JS, etc.)...");let i=await Ce("npm",["install"],{cwd:e,label:"npm install",env:s});n.npm=i.code===0?"ok":"failed",i.code!==0&&t("npm",i),o.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let a=await En(e);n.pip=a.code===0?"ok":"failed",a.code!==0&&t("pip",a),o.step("Installing Playwright browser (chromium ~200MB; one-time)...");let r=await Ce("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:s});n.playwright=r.code===0?"ok":"failed",r.code!==0&&t("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 n.patchright=c.code===0?"ok":"failed",c.code!==0&&t("patchright",c),n}import{mkdir as An,readFile as Pn,writeFile as bn}from"fs/promises";import{join as ft}from"path";async function we(e,n){let s=ft(e,".claude");await An(s,{recursive:!0});let t=ft(s,"settings.json"),i={};try{let p=await Pn(t,"utf-8"),g=JSON.parse(p);g&&typeof g=="object"&&!Array.isArray(g)&&(i=g)}catch{}let a=i.enabledMcpjsonServers,r=Array.isArray(a)?a.filter(p=>typeof p=="string"):[];r.includes(n)||r.push(n);let c={...i,enabledMcpjsonServers:r};await bn(t,JSON.stringify(c,null,2)+`
21
- `,"utf-8")}var Sn="0.15.2",C=5;function z(e,n){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: ${n}`),o.blank(),o.detail("Your credentials are saved in `.env`. Two ways forward:"),o.detail(" \u2022 Open `.env` in any text editor, fix the value, re-run `npx klaudius init` and pick Resume."),o.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),o.blank(),process.exit(1)}async function yt(e){let n=e.target??".",s=Cn(n)?n:_n(process.cwd(),n),t=On(s);t&&(o.error("Klaudius can't be installed inside a protected system folder."),o.detail(`Path: ${s}`),o.detail(`Reason: ${t}`),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 npx klaudius init."),o.blank());let i=await Rn(s);if(i.kind==="scaffolded"){o.blank(),o.warn(`Found an existing Klaudius project at ${d.bold(s)}.`),o.detail("(Your .env and project files are in place.)"),o.blank(),i.nodeModulesMissing?(o.detail("It looks like a previous setup didn't finish installing dependencies."),o.detail("To pick up where it left off, run:"),o.blank(),s!==process.cwd()&&console.log(` ${d.cyan(`cd ${n}`)}`),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Everything is scaffolded and dependencies look installed."),o.detail("Pick the action you wanted:"),o.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),o.blank()),o.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius init`."),o.blank();return}if(i.kind==="occupied"){let u=n===".";o.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),o.detail(`Path: ${s}`),o.detail(`Contains: ${i.entries.slice(0,5).join(", ")}${i.entries.length>5?`, \u2026 (+${i.entries.length-5} more)`:""}`),o.blank(),u?(o.detail("Two ways forward:"),o.blank(),o.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius init my-agency")}`),o.blank(),o.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius init")}`)):(o.detail(`The folder '${n}' already exists and isn't empty.`),o.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius init ${n}-2`)}`),o.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await vn(e.license),r=y.spinner();r.start("Validating license");let c=await nt(a);c.ok||(r.stop(`License invalid: ${c.reason??"unknown"}`,2),o.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),r.stop(`License valid (${c.tier??"core"} tier)`);let p=await Z();p.ok||(o.error(p.message??"Python version check failed."),o.blank(),o.detail("Once you've installed Python 3.10+, re-run `npx klaudius init` in this folder."),process.exit(1));let g=G();g.ok||(o.error(g.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius init` in this folder."),process.exit(1));let l,A=!1;if(i.kind==="partial")if(await xn(s)==="resume"){let f=await ht(i.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(i.envPath,"utf-8"),m=_e($(f));l=await I(m??{})}else l=await I();l.licenseKey=a,await D(s,l),A||(o.success("Saved .env"),o.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),o.blank();for(let u=1;;u++){let 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:
18
+ \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: ${s}`}async function lt(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`,s=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let t=await fetch(n,{headers:{Authorization:`Basic ${s}`}});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 i=await t.json();return i.status&&i.status!=="active"?{ok:!1,message:`Twilio account is in '${i.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:i.friendly_name}}catch(t){return{ok:!1,message:`Could not reach Twilio: ${_(t)}`}}}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,"")}"`,t=await fn(s);if(t.code===0)return{ok:!0};let i=t.stderr.toLowerCase();return i.includes("can't get application")||i.includes("isn't running")||i.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:i.includes("(-1728)")||i.includes("not found")||i.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:i.includes("(-1719)")||i.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${t.stderr.trim()||`exit code ${t.code}`}`}}function fn(e){return new Promise(n=>{let s=pn("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),t="";s.stderr.on("data",i=>{t+=i.toString()}),s.on("close",i=>n({code:i??1,stderr:t})),s.on("error",i=>n({code:1,stderr:i.message}))})}import{spawn as dt}from"child_process";function mn(){let e=process.env.NODE_OPTIONS?.trim(),n=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:n}}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,n){let s=e+`
19
+ `+n;return hn.some(t=>t.test(s))}function ft(e){return new Promise(n=>setTimeout(n,e))}function gn(e,n,s){return new Promise(t=>{let i=dt(e,n,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:s.env??process.env}),a="",r="";i.stdout?.on("data",c=>{let p=c.toString();a+=p,process.stdout.write(p)}),i.stderr?.on("data",c=>{let p=c.toString();r+=p,process.stderr.write(p)}),i.on("close",c=>t({code:c??1,stdout:a,stderr:r})),i.on("error",c=>t({code:1,stdout:a,stderr:r+c.message}))})}async function Ce(e,n,s){let t={code:0,stdout:"",stderr:""};for(let i=0;i<=te;i++){if(t=await gn(e,n,{cwd:s.cwd,env:s.env}),t.code===0||!pt(t.stderr,t.stdout))return t;i<te&&(o.detail(`${s.label} failed with a transient network error \u2014 retrying (${i+2}/${te+1})\u2026`),await ft(ut))}return t}function kn(e,n,s){return new Promise(t=>{let i=dt(e,n,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",r="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{r+=c.toString()}),i.on("close",c=>t({code:c??1,stdout:a,stderr:r})),i.on("error",c=>t({code:1,stdout:a,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. Re-run with `npx klaudius@latest init` (pulls the latest) \u2014 that should bypass the source build."}];function wn(e){let n=`${e.stderr??""}
20
+ ${e.stdout??""}`;return yn.find(t=>t.pattern.test(n))?.hint}async function En(e){let n=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],s=["-m","pip","install","--quiet","--user"],i=(await Ae())?.command??["python3"],a=async c=>{let p={code:0,stdout:"",stderr:""};for(let g=0;g<=te;g++){if(p=await kn(i[0],[...i.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 ft(ut))}return p},r=await a([...s,"--break-system-packages",...n]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(o.detail("Older pip detected; retrying without --break-system-packages"),r=await a([...s,...n])),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 n={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},s=mn(),t=(p,g)=>{let l=wn(g);l&&((n.hints??={})[p]=l)};o.step("Running npm install (Next.js, Playwright JS, etc.)...");let i=await Ce("npm",["install"],{cwd:e,label:"npm install",env:s});n.npm=i.code===0?"ok":"failed",i.code!==0&&t("npm",i),o.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let a=await En(e);n.pip=a.code===0?"ok":"failed",a.code!==0&&t("pip",a),o.step("Installing Playwright browser (chromium ~200MB; one-time)...");let r=await Ce("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:s});n.playwright=r.code===0?"ok":"failed",r.code!==0&&t("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 n.patchright=c.code===0?"ok":"failed",c.code!==0&&t("patchright",c),n}import{mkdir as An,readFile as Pn,writeFile as bn}from"fs/promises";import{join as mt}from"path";async function we(e,n){let s=mt(e,".claude");await An(s,{recursive:!0});let t=mt(s,"settings.json"),i={};try{let p=await Pn(t,"utf-8"),g=JSON.parse(p);g&&typeof g=="object"&&!Array.isArray(g)&&(i=g)}catch{}let a=i.enabledMcpjsonServers,r=Array.isArray(a)?a.filter(p=>typeof p=="string"):[];r.includes(n)||r.push(n);let c={...i,enabledMcpjsonServers:r};await bn(t,JSON.stringify(c,null,2)+`
21
+ `,"utf-8")}var Sn="0.15.3",C=5;function z(e,n){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: ${n}`),o.blank(),o.detail("Your credentials are saved in `.env`. Two ways forward:"),o.detail(" \u2022 Open `.env` in any text editor, fix the value, re-run `npx klaudius init` and pick Resume."),o.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),o.blank(),process.exit(1)}async function yt(e){let n=e.target??".",s=Cn(n)?n:_n(process.cwd(),n),t=On(s);t&&(o.error("Klaudius can't be installed inside a protected system folder."),o.detail(`Path: ${s}`),o.detail(`Reason: ${t}`),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 npx klaudius init."),o.blank());let i=await Rn(s);if(i.kind==="scaffolded"){o.blank(),o.warn(`Found an existing Klaudius project at ${d.bold(s)}.`),o.detail("(Your .env and project files are in place.)"),o.blank(),i.nodeModulesMissing?(o.detail("It looks like a previous setup didn't finish installing dependencies."),o.detail("To pick up where it left off, run:"),o.blank(),s!==process.cwd()&&console.log(` ${d.cyan(`cd ${n}`)}`),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Everything is scaffolded and dependencies look installed."),o.detail("Pick the action you wanted:"),o.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),o.blank()),o.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius init`."),o.blank();return}if(i.kind==="occupied"){let u=n===".";o.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),o.detail(`Path: ${s}`),o.detail(`Contains: ${i.entries.slice(0,5).join(", ")}${i.entries.length>5?`, \u2026 (+${i.entries.length-5} more)`:""}`),o.blank(),u?(o.detail("Two ways forward:"),o.blank(),o.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius init my-agency")}`),o.blank(),o.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius init")}`)):(o.detail(`The folder '${n}' already exists and isn't empty.`),o.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius init ${n}-2`)}`),o.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await vn(e.license),r=y.spinner();r.start("Validating license");let c=await nt(a);c.ok||(r.stop(`License invalid: ${c.reason??"unknown"}`,2),o.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),r.stop(`License valid (${c.tier??"core"} tier)`);let p=await Z();p.ok||(o.error(p.message??"Python version check failed."),o.blank(),o.detail("Once you've installed Python 3.10+, re-run `npx klaudius init` in this folder."),process.exit(1));let g=G();g.ok||(o.error(g.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius init` in this folder."),process.exit(1));let l,A=!1;if(i.kind==="partial")if(await xn(s)==="resume"){let m=await ht(i.envPath,"utf-8"),f=_e($(m));f?(o.success("Resuming with values from your existing .env"),o.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=f,A=!0):(o.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await I())}else{let m=await ht(i.envPath,"utf-8"),f=_e($(m));l=await I(f??{})}else l=await I();l.licenseKey=a,await D(s,l),A||(o.success("Saved .env"),o.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),o.blank();for(let u=1;;u++){let m=y.spinner();m.start("Validating Supabase credentials");let f=await ee({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(f.ok){m.stop("Supabase credentials accepted");break}m.stop(f.message??"Supabase check failed",2),u>=C&&z("Supabase",f.message??"Supabase check failed");let E=f.message??"Supabase check failed";o.blank(),o.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
22
22
  ${E}
23
23
 
24
24
  Re-enter the URL, secret key, or PAT below. Press Enter on any
25
- field to keep what's already there.`}),await D(s,l)}if(o.blank(),l.deployProvider==="cloudflare")for(let u=1;;u++){let 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:
25
+ field to keep what's already there.`}),await D(s,l)}if(o.blank(),l.deployProvider==="cloudflare")for(let u=1;;u++){let m=y.spinner();m.start("Validating Cloudflare token + account");let f=await ge({token:l.cloudflareApiToken??"",accountId:l.cloudflareAccountId??""});if(f.ok){m.stop(`Cloudflare credentials accepted (${f.projectCount??0} existing Pages project${f.projectCount===1?"":"s"})`);break}m.stop(f.message??"Cloudflare check failed",2),u>=C&&z("Cloudflare",f.message??"Cloudflare check failed");let E=f.message??"Cloudflare check failed";o.blank(),o.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
26
26
  ${E}
27
27
 
28
28
  Re-enter the API token or Account ID below. The token needs the
29
29
  "Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
30
- the current value.`}),await D(s,l)}else for(let u=1;;u++){let 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:
30
+ the current value.`}),await D(s,l)}else for(let u=1;;u++){let m=y.spinner();m.start("Validating Vercel token");let f=await he(l.vercelToken??"");if(f.ok){m.stop(f.username?`Vercel token accepted (signed in as ${f.username})`:"Vercel token accepted");break}m.stop(f.message??"Vercel check failed",2),u>=C&&z("Vercel",f.message??"Vercel check failed");let E=f.message??"Vercel check failed";o.blank(),o.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"vercel",banner:`Vercel rejected the token:
31
31
  ${E}
32
32
 
33
33
  Generate a new token at https://vercel.com/account/tokens and
34
- paste it below. Press Enter to keep the current value.`}),await D(s,l)}o.blank();for(let u=1;;u++){let 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:
34
+ paste it below. Press Enter to keep the current value.`}),await D(s,l)}o.blank();for(let u=1;;u++){let m=y.spinner();m.start("Validating Google Places API key");let f=await ke(l.googlePlacesApiKey??"");if(f.ok){m.stop("Google Places API key accepted");break}m.stop(f.message??"Google Places check failed",2),u>=C&&z("Google Places",f.message??"Google Places check failed");let E=f.message??"Google Places check failed";o.blank(),o.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"google-places",banner:`Google rejected the key:
35
35
  ${E}
36
36
 
37
37
  Generate (or fix) the key at https://console.cloud.google.com
38
- and paste it below. Press Enter to keep the current value.`}),await D(s,l)}if(l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAddress&&l.emailPassword&&l.emailSmtpHost&&l.emailSmtpPort&&l.emailImapHost&&l.emailImapPort){o.blank();for(let u=1;;u++){let 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:
38
+ and paste it below. Press Enter to keep the current value.`}),await D(s,l)}if(l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAddress&&l.emailPassword&&l.emailSmtpHost&&l.emailSmtpPort&&l.emailImapHost&&l.emailImapPort){o.blank();for(let u=1;;u++){let m=y.spinner();m.start("Validating email credentials (SMTP + IMAP)");let f=await rt({emailAddress:l.emailAddress,emailPassword:l.emailPassword,emailSmtpHost:l.emailSmtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:l.emailImapHost,emailImapPort:l.emailImapPort});if(f.ok){m.stop("Email credentials accepted (SMTP + IMAP)");break}m.stop(f.message??"Email check failed",2),u>=C&&z("Email",f.message??"Email check failed");let E=f.message??"Email check failed";o.blank(),o.warn(`Bouncing you back into the email section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"email",banner:`${f.failedAt==="imap"?"IMAP":"SMTP"} check failed:
39
39
  ${E}
40
40
 
41
41
  Re-enter the email address, app password, or host details below.
42
- Press Enter on any field to keep its current value.`}),await D(s,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="twilio"&&l.twilioAccountSid&&l.twilioAuthToken){o.blank();for(let u=1;;u++){let 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:
42
+ Press Enter on any field to keep its current value.`}),await D(s,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="twilio"&&l.twilioAccountSid&&l.twilioAuthToken){o.blank();for(let u=1;;u++){let m=y.spinner();m.start("Validating Twilio credentials");let f=await lt({accountSid:l.twilioAccountSid,authToken:l.twilioAuthToken});if(f.ok){m.stop(f.friendlyName?`Twilio credentials accepted (${f.friendlyName})`:"Twilio credentials accepted");break}m.stop(f.message??"Twilio check failed",2),u>=C&&z("Twilio",f.message??"Twilio check failed");let E=f.message??"Twilio check failed";o.blank(),o.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"sms",banner:`Twilio rejected the credentials:
43
43
  ${E}
44
44
 
45
45
  Re-enter the Account SID or Auth Token below.
46
- Press Enter on any field to keep its current value.`}),await D(s,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="imessage"&&l.testPhone){o.blank();for(let u=1;;u++){let 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:
46
+ Press Enter on any field to keep its current value.`}),await D(s,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="imessage"&&l.testPhone){o.blank();for(let u=1;;u++){let m=y.spinner();m.start("Validating iMessage setup (sending a test ping)");let f=await ct({testPhone:l.testPhone});if(f.ok){m.stop("iMessage dispatched (check your phone for the test ping)");break}m.stop(f.message??"iMessage check failed",2),u>=C&&z("iMessage",f.message??"iMessage check failed");let E=f.message??"iMessage check failed";o.blank(),o.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"sms",banner:`iMessage check failed:
47
47
  ${E}
48
48
 
49
49
  Either fix the underlying issue (sign in to Messages.app, configure
50
50
  Text Message Forwarding) and press Enter through, or change SMS
51
- provider to Twilio.`}),await D(s,l)}}if(l.telegramBotToken&&l.telegramChatId){o.blank();let u=0,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 `npx klaudius init` to resume."),process.exit(0)),Y==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await D(s,l),o.success("Skipped Telegram. Setup will continue."),o.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),f=!0;break}if(Y==="edit"&&(o.blank(),l=await I(l,{onlySection:"telegram",banner:`Telegram check failed:
51
+ provider to Twilio.`}),await D(s,l)}}if(l.telegramBotToken&&l.telegramChatId){o.blank();let u=0,m=!1;for(;!m;){u++;let f=y.spinner();f.start("Validating Telegram bot + chat (sending a test ping)");let E=await Ke({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(E.ok){f.stop(E.botHandle?`Telegram bot ${E.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),m=!0;break}f.stop(E.message??"Telegram check failed",2);let 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 `npx klaudius init` to resume."),process.exit(0)),Y==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await D(s,l),o.success("Skipped Telegram. Setup will continue."),o.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),m=!0;break}if(Y==="edit"&&(o.blank(),l=await I(l,{onlySection:"telegram",banner:`Telegram check failed:
52
52
  ${De}
53
53
 
54
54
  Re-enter the bot token or chat_id below.
55
- Press Enter on any field to keep its current value.`}),await D(s,l),!l.telegramBotToken||!l.telegramChatId)){o.success("Skipped Telegram. Setup will continue."),f=!0;break}}}o.blank();let h=y.spinner();h.start("Downloading Klaudius template");let P;try{P=(await fe({licenseKey:a,machineId:ie(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:s})).filesExtracted,h.stop(`Downloaded ${P} files into ${d.bold(s)}`)}catch(u){h.stop(u.message,2);let 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,x=!e.skipInstall&&!b.includes("npm");if(V&&x){o.blank(),o.heading("Linking WhatsApp accounts"),console.log(d.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
55
+ Press Enter on any field to keep its current value.`}),await D(s,l),!l.telegramBotToken||!l.telegramChatId)){o.success("Skipped Telegram. Setup will continue."),m=!0;break}}}o.blank();let h=y.spinner();h.start("Downloading Klaudius template");let P;try{P=(await me({licenseKey:a,machineId:ie(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:s})).filesExtracted,h.stop(`Downloaded ${P} files into ${d.bold(s)}`)}catch(u){h.stop(u.message,2);let m=l.aiAgent==="codex"?".codex/config.toml":".mcp.json";o.detail(`Your .env / ${m} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await 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 m=await ot({projectRoot:s,pat:l.supabasePat,projectRef:l.supabaseProjectRef});m.ok?u.stop("Schema applied (or already present)"):(u.stop(m.message??"Schema apply failed",2),U=!0,N=`https://supabase.com/dashboard/project/${l.supabaseProjectRef}/sql/new`)}let b=[],w={};if(e.skipInstall)o.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{o.blank(),o.heading("Installing dependencies");let u=await 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,x=!e.skipInstall&&!b.includes("npm");if(V&&x){o.blank(),o.heading("Linking WhatsApp accounts"),console.log(d.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
56
56
  phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
57
- Link a Device, and point it at the QR shown in this terminal.`)),o.blank();for(let u of l.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${u}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius pair-whatsapp --label ${u})`));let 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&&!x){o.blank(),console.log(d.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius install` completes successfully, pair via:"));for(let u of l.whatsappAccounts)console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))}o.blank();let 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,n){await Se(e,{recursive:!0}),await Ie(q(e,".env"),ue(n),"utf-8"),n.aiAgent==="codex"?(await Se(q(e,".codex"),{recursive:!0}),await Ie(q(e,".codex","config.toml"),me(n),"utf-8")):(await Ie(q(e,".mcp.json"),pe(n),"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 n=await Tn(e),s=n.filter(c=>!c.startsWith(".DS_Store"));if(s.length===0)return{kind:"fresh"};let t=new Set([".env",".mcp.json",".claude",".codex"]),i=s.every(c=>t.has(c)),a=s.includes(".env"),r=n.includes(".klaudius");if(i&&a&&!r)return{kind:"partial",envPath:q(e,".env")};if(r&&a){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 xn(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 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 vn(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:s=>s.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 On(e){let n=In(e);if(process.platform==="win32"){let s=n.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 t of s)if(n.startsWith(t))return`Inside ${t.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 v from"picocolors";async function Et(e){let n=e.target?Mn(process.cwd(),e.target):process.cwd(),s=await wt(Re(n,".env")),t=await wt(Re(n,"package.json"));(!s||!t)&&(o.error("This doesn't look like a Klaudius project."),o.detail(`Path: ${n}`),s||o.detail("Missing: .env"),t||o.detail("Missing: package.json"),o.blank(),o.detail("Run `npx klaudius init` to scaffold a new project first,"),o.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let i="claude-code";try{$(await Dn(Re(n,".env"),"utf-8")).AI_AGENT==="codex"&&(i="codex")}catch{}o.heading("Installing dependencies");let a=await ye(n);o.blank(),o.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let r=[];if(a.npm==="failed"&&r.push("npm"),a.pip==="failed"&&r.push("pip"),a.playwright==="failed"&&r.push("playwright"),a.patchright==="failed"&&r.push("patchright"),r.length===0){o.blank(),console.log(v.green(v.bold("All dependencies installed."))),console.log(v.dim("Run `npx klaudius doctor` to verify everything else (credentials, files).")),o.blank();return}o.blank(),console.log(v.yellow(v.bold(`${r.join(", ")} still failing.`))),o.blank();for(let[l,A]of Object.entries(a.hints??{}))console.log(v.yellow(`Likely cause of ${l} failure:`)),console.log(v.dim(` ${A}`)),o.blank();let c=i==="codex"?"codex":"claude",p=i==="codex"?"Codex":"Claude Code",g=i==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(v.dim("Options:")),console.log(v.dim(` \u2022 Open ${p} in this folder (\`${c}\`) and paste:`)),console.log(v.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius doctor."`)),console.log(v.dim(` (Don't have ${p} yet? Install with: \`${g}\`)`)),console.log(v.dim(" \u2022 Or run `npx klaudius doctor` for a structured diagnostic.")),console.log(v.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),o.blank(),process.exitCode=1}async function wt(e){try{return await Ln(e),!0}catch{return!1}}import{readFile as Un,writeFile as xe,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 n=e.projectRoot??process.cwd(),s=ne(n,".env"),t=ne(n,".mcp.json"),i=ne(n,".codex","config.toml"),a=await ve(ne(n,".klaudius","manifest.json")),r=await ve(s);!a&&!r&&(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius init` first."),process.exit(1));let c=G();c.ok||(o.error(c.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius configure` in this folder."),process.exit(1));let p={};try{let h=await 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 xe(s,ue(l),"utf-8"),o.success("Updated .env"),l.aiAgent==="codex"?(await Kn(ne(n,".codex"),{recursive:!0}),await xe(i,me(l),"utf-8"),o.success("Updated .codex/config.toml")):(await xe(t,pe(l),"utf-8"),o.success("Updated .mcp.json"),await we(n,"supabase")),o.blank(),Ee.outro(K.green("Configuration updated.")),await Hn(n,a)}async function Hn(e,n){let s=await ve(ne(e,"node_modules"));o.blank(),n?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 ve(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.2";async function It(e){let n=e.projectRoot??process.cwd(),s=await Fe(n);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 t,i=O(n,".env"),a,r;try{a=await Vn(i,"utf-8"),r=$(a)}catch{o.error("Couldn't read .env from this directory."),o.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}t=r.KLAUDIUS_LICENSE_KEY??"",t||(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(a,r,qe);c!==null&&(await Tt(i,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:t,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,n,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"),x=[...N,...V];if(o.blank(),o.heading("Change summary"),o.detail(`${H(b.length,"file")} unchanged`),o.detail(`${H(P.length,"new file")}`),o.detail(`${H(L.length,"file")} updated cleanly (no local edits)`),o.detail(`${H(U.length,"file")} you've edited (no upstream change \u2014 left alone)`),o.detail(`${H(w.length,"file")} removed upstream (deleted cleanly)`),o.detail(`${H(N.length,"file")} with conflicts (you edited AND we have a new version)`),o.detail(`${H(V.length,"file")} removed upstream but edited locally (need your decision)`),P.length===0&&L.length===0&&w.length===0&&x.length===0){o.blank(),oe.outro(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(n,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(n,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`),x.length>0){o.blank(),o.heading(`${x.length} conflict(s) need resolution`);let k=O(n,".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(n,".klaudius","conflicts.md"),Yn(x,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(),x.length===0&&(s.templateVersion=$e),await ce(n,s),o.blank(),x.length===0)oe.outro(Oe.green("Update complete."));else{let k=g==="codex"?"Codex":"Claude Code";oe.outro(Oe.yellow(`${x.length} conflict(s) staged. Open ${k} in this project and ask:
57
+ Link a Device, and point it at the QR shown in this terminal.`)),o.blank();for(let u of l.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${u}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius pair-whatsapp --label ${u})`));let m=kt(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:s,stdio:"inherit"});m.status===0?o.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${m.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))),o.blank()}}else if(V&&!x){o.blank(),console.log(d.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius install` completes successfully, pair via:"));for(let u of l.whatsappAccounts)console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))}o.blank();let 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
+ `:"",m=l.aiAgent==="codex"?"codex":"claude",f=l.aiAgent==="codex"?"Codex":"Claude Code",E=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";b.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),o.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan(m)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${b.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius doctor."`)),o.blank(),console.log(d.dim(` (Don't have ${f} yet? Install with: \`${E}\`)`)),o.blank(),console.log(d.dim("Or do it yourself:")),o.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify everything")}`),o.blank()),U&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(N)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),o.blank()),b.includes("pip")&&!w.pip&&(console.log(d.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(d.dim(`Python 3.10+. Install a newer one from ${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,n){await Se(e,{recursive:!0}),await Ie(q(e,".env"),ue(n),"utf-8"),n.aiAgent==="codex"?(await Se(q(e,".codex"),{recursive:!0}),await Ie(q(e,".codex","config.toml"),fe(n),"utf-8")):(await Ie(q(e,".mcp.json"),pe(n),"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 n=await Tn(e),s=n.filter(c=>!c.startsWith(".DS_Store"));if(s.length===0)return{kind:"fresh"};let t=new Set([".env",".mcp.json",".claude",".codex"]),i=s.every(c=>t.has(c)),a=s.includes(".env"),r=n.includes(".klaudius");if(i&&a&&!r)return{kind:"partial",envPath:q(e,".env")};if(r&&a){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 xn(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 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 vn(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:s=>s.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 On(e){let n=In(e);if(process.platform==="win32"){let s=n.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 t of s)if(n.startsWith(t))return`Inside ${t.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 v from"picocolors";async function Et(e){let n=e.target?Mn(process.cwd(),e.target):process.cwd(),s=await wt(Re(n,".env")),t=await wt(Re(n,"package.json"));(!s||!t)&&(o.error("This doesn't look like a Klaudius project."),o.detail(`Path: ${n}`),s||o.detail("Missing: .env"),t||o.detail("Missing: package.json"),o.blank(),o.detail("Run `npx klaudius init` to scaffold a new project first,"),o.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let i="claude-code";try{$(await Dn(Re(n,".env"),"utf-8")).AI_AGENT==="codex"&&(i="codex")}catch{}o.heading("Installing dependencies");let a=await ye(n);o.blank(),o.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let r=[];if(a.npm==="failed"&&r.push("npm"),a.pip==="failed"&&r.push("pip"),a.playwright==="failed"&&r.push("playwright"),a.patchright==="failed"&&r.push("patchright"),r.length===0){o.blank(),console.log(v.green(v.bold("All dependencies installed."))),console.log(v.dim("Run `npx klaudius doctor` to verify everything else (credentials, files).")),o.blank();return}o.blank(),console.log(v.yellow(v.bold(`${r.join(", ")} still failing.`))),o.blank();for(let[l,A]of Object.entries(a.hints??{}))console.log(v.yellow(`Likely cause of ${l} failure:`)),console.log(v.dim(` ${A}`)),o.blank();let c=i==="codex"?"codex":"claude",p=i==="codex"?"Codex":"Claude Code",g=i==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(v.dim("Options:")),console.log(v.dim(` \u2022 Open ${p} in this folder (\`${c}\`) and paste:`)),console.log(v.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius doctor."`)),console.log(v.dim(` (Don't have ${p} yet? Install with: \`${g}\`)`)),console.log(v.dim(" \u2022 Or run `npx klaudius doctor` for a structured diagnostic.")),console.log(v.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),o.blank(),process.exitCode=1}async function wt(e){try{return await Ln(e),!0}catch{return!1}}import{readFile as Un,writeFile as xe,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 n=e.projectRoot??process.cwd(),s=ne(n,".env"),t=ne(n,".mcp.json"),i=ne(n,".codex","config.toml"),a=await ve(ne(n,".klaudius","manifest.json")),r=await ve(s);!a&&!r&&(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius init` first."),process.exit(1));let c=G();c.ok||(o.error(c.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius configure` in this folder."),process.exit(1));let p={};try{let h=await 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 xe(s,ue(l),"utf-8"),o.success("Updated .env"),l.aiAgent==="codex"?(await Kn(ne(n,".codex"),{recursive:!0}),await xe(i,fe(l),"utf-8"),o.success("Updated .codex/config.toml")):(await xe(t,pe(l),"utf-8"),o.success("Updated .mcp.json"),await we(n,"supabase")),o.blank(),Ee.outro(K.green("Configuration updated.")),await Hn(n,a)}async function Hn(e,n){let s=await ve(ne(e,"node_modules"));o.blank(),n?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 ve(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.3";async function It(e){let n=e.projectRoot??process.cwd(),s=await Fe(n);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 t,i=O(n,".env"),a,r;try{a=await Vn(i,"utf-8"),r=$(a)}catch{o.error("Couldn't read .env from this directory."),o.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}t=r.KLAUDIUS_LICENSE_KEY??"",t||(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(a,r,qe);c!==null&&(await Tt(i,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 me({licenseKey:t,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,n,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"),x=[...N,...V];if(o.blank(),o.heading("Change summary"),o.detail(`${H(b.length,"file")} unchanged`),o.detail(`${H(P.length,"new file")}`),o.detail(`${H(L.length,"file")} updated cleanly (no local edits)`),o.detail(`${H(U.length,"file")} you've edited (no upstream change \u2014 left alone)`),o.detail(`${H(w.length,"file")} removed upstream (deleted cleanly)`),o.detail(`${H(N.length,"file")} with conflicts (you edited AND we have a new version)`),o.detail(`${H(V.length,"file")} removed upstream but edited locally (need your decision)`),P.length===0&&L.length===0&&w.length===0&&x.length===0){o.blank(),oe.outro(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(n,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(n,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`),x.length>0){o.blank(),o.heading(`${x.length} conflict(s) need resolution`);let k=O(n,".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(n,".klaudius","conflicts.md"),Yn(x,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(),x.length===0&&(s.templateVersion=$e),await ce(n,s),o.blank(),x.length===0)oe.outro(Oe.green("Update complete."));else{let k=g==="codex"?"Codex":"Claude Code";oe.outro(Oe.yellow(`${x.length} conflict(s) staged. Open ${k} in this project and ask:
59
59
  "Run /resolve-conflicts"`))}await ae(l,{recursive:!0,force:!0}).catch(()=>{})}async function Wn(e,n,s){let t=await St(e),i=new Set(t),a=[];for(let r of t){let c=await le(O(e,r)),p=s.files[r],g=O(n,r),l;try{await _t(g),l=await le(g)}catch{a.push({path:r,state:"new",canonicalHash:c,manifestHash:p});continue}c===p?l===p?a.push({path:r,state:"no-change",canonicalHash:c,localHash:l,manifestHash:p}):a.push({path:r,state:"user-only",canonicalHash:c,localHash:l,manifestHash:p}):l===p?a.push({path:r,state:"clean-update",canonicalHash:c,localHash:l,manifestHash:p}):a.push({path:r,state:"conflict",canonicalHash:c,localHash:l,manifestHash:p})}for(let r of Object.keys(s.files)){if(i.has(r))continue;let c=s.files[r],p=O(n,r),g;try{await _t(p),g=await le(p)}catch{delete s.files[r];continue}g===c?a.push({path:r,state:"removed-clean",localHash:g,manifestHash:c}):a.push({path:r,state:"removed-modified",localHash:g,manifestHash:c})}return a}function H(e,n){return`${e} ${n}${e===1?"":"s"}`}async function St(e,n=e){let s=await Fn(e,{withFileTypes:!0}),t=[];for(let i of s){let a=O(e,i.name);i.isDirectory()?t.push(...await St(a,n)):i.isFile()&&t.push(Gn(n,a))}return t}function Yn(e,n,s){let t=e.filter(c=>c.state==="conflict").length,i=e.filter(c=>c.state==="removed-modified").length,a=[];a.push("# Update Conflicts"),a.push(""),a.push(`Generated by \`npx klaudius update\` on ${new Date().toISOString()}.`),a.push(`Updating from canonical version **${n}** to **${s}**.`),a.push("");let r=[];t>0&&r.push(`${t} file${t===1?"":"s"} ha${t===1?"s":"ve"} BOTH local edits AND upstream changes`),i>0&&r.push(`${i} file${i===1?"":"s"} ${i===1?"was":"were"} removed upstream but edited locally`),a.push(r.join(", and ")+"."),a.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),a.push(""),a.push("---"),a.push("");for(let c of e)a.push(`## ${c.path}`),a.push(""),c.state==="removed-modified"?(a.push("**Type:** Removed upstream"),a.push(""),a.push(`- Your local copy: \`${c.path}\``),a.push("- This file no longer exists in the canonical template."),a.push("- You've modified it locally since install."),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),a.push("2. Delete \u2014 remove the file from disk and from the manifest")):(a.push("**Type:** Edit conflict"),a.push(""),a.push(`- Your version (with your local edits): \`${c.path}\``),a.push(`- New canonical version: \`.klaudius/incoming/${c.path}\``),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(`- New canonical hash: \`${(c.canonicalHash??"(none)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 discard the new canonical changes"),a.push("2. Take canonical \u2014 overwrite my edits with the new version"),a.push("3. Merge \u2014 review both side-by-side and produce a combined version")),a.push(""),a.push("---"),a.push("");return a.join(`
60
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 xt(e){let n=e.projectRoot??process.cwd(),s=[];console.log(S.bold(`Klaudius doctor \u2014 checking your project\u2026
61
61
  `)),s.push(await Jn()),s.push(await Qn());let t=M(n,".env"),i=M(n,".klaudius","manifest.json"),a=M(n,".mcp.json"),r=M(n,".codex","config.toml"),c=await W(t),p=await W(i),g="claude-code";if(c)try{$(await Rt(t,"utf-8")).AI_AGENT==="codex"&&(g="codex")}catch{}if(g==="claude-code"){let h=await W(M(n,"AGENTS.md")),P=!await W(M(n,".claude"));h&&P&&(g="codex")}if(s.push({name:".env present",status:c?"ok":"fail",detail:c?t:"missing",nextAction:c?void 0:"Run `npx klaudius init` in this folder."}),s.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?"ok":"fail",detail:p?i:"missing",nextAction:p?void 0:c?"Init didn't finish \u2014 run `npx klaudius init` and pick Resume.":"Run `npx klaudius init`."}),g==="codex"){let h=await W(r);s.push({name:".codex/config.toml present",status:h?"ok":"warn",detail:h?r:"missing",nextAction:h?void 0:"Run `npx klaudius configure` to regenerate."})}else{let h=await W(a);s.push({name:".mcp.json present",status:h?"ok":"warn",detail:h?a:"missing",nextAction:h?void 0:"Run `npx klaudius configure` to regenerate."})}if(s.push(await oo(g)),s.push(await Zn(n)),s.push(await eo(n)),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(t,"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,n=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!n)return{name:"Node \u2265 22.15",status:"warn",detail:e};let s=parseInt(n[1],10),t=parseInt(n[2],10);return s<22||s===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 Zn(e){let n=M(e,"node_modules");if(!await W(n))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius install` in this folder."};try{if(!(await qn(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 eo(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 W(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 to(){let e=["supabase","dotenv","requests","httpx","PIL"],n=`import sys
@@ -71,4 +71,4 @@ except Exception as e:
71
71
  `));let a=io(process.execPath,[s,"pair","--account",i],{cwd:n,stdio:"inherit"});if(a.status===0){console.log(R.green(`Paired '${i}'.`)),console.log(R.dim(`
72
72
  If you haven't already, add '${i}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
73
73
  WHATSAPP_ACCOUNTS=primary,${i}
74
- (Skip this if '${i}' is already there or you set it via the init wizard.)`));return}a.error?console.error(R.red(`Pair failed: ${a.error.message}`)):(console.error(R.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(R.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(R.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(R.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${i}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as 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,t=lo(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:s},stdio:"inherit"});t.signal&&(process.kill(process.pid,t.signal),process.exit(1)),process.exit(t.status??1)}$t();var uo="0.15.2",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,n)=>{try{await yt({target:e,license:n.license,skipInstall:!!n.skipInstall,skipSchema:!!n.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(n){console.error("install failed:",n.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 xt({offline:!!e.offline})}catch(n){console.error("doctor failed:",n.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(n){console.error("pair-whatsapp failed:",n.message),process.exit(1)}});F.parse(process.argv);
74
+ (Skip this if '${i}' is already there or you set it via the init wizard.)`));return}a.error?console.error(R.red(`Pair failed: ${a.error.message}`)):(console.error(R.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(R.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(R.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(R.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${i}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as 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,t=lo(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:s},stdio:"inherit"});t.signal&&(process.kill(process.pid,t.signal),process.exit(1)),process.exit(t.status??1)}$t();var uo="0.15.3",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,n)=>{try{await yt({target:e,license:n.license,skipInstall:!!n.skipInstall,skipSchema:!!n.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(n){console.error("install failed:",n.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 xt({offline:!!e.offline})}catch(n){console.error("doctor failed:",n.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(n){console.error("pair-whatsapp failed:",n.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.15.2",
3
+ "version": "0.15.3",
4
4
  "description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code (find, build, deploy, outreach end-to-end).",
5
5
  "homepage": "https://klaudius.dev",
6
6
  "bugs": {