klaudius 0.12.0 → 0.12.1

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