klaudius 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{a as f,e as Q}from"./chunk-SZ4KCTSL.js";import{useEffect as We,useMemo as je,useRef as Z,useState as T}from"react";import{Box as P,Text as k,useApp as qe,useInput as Ye}from"ink";var ee={gmail:{label:"Gmail",smtpHost:"smtp.gmail.com",smtpPort:587,imapHost:"imap.gmail.com",imapPort:993,sentFolder:"[Gmail]/Sent Mail",inboxFolder:"INBOX",appPasswordHelp:`Generate at https://myaccount.google.com/apppasswords
1
+ import{a as f,e as J}from"./chunk-SZ4KCTSL.js";import{useEffect as je,useMemo as qe,useRef as Z,useState as T}from"react";import{Box as k,Text as I,useApp as Ye,useInput as Xe}from"ink";var ee={gmail:{label:"Gmail",smtpHost:"smtp.gmail.com",smtpPort:587,imapHost:"imap.gmail.com",imapPort:993,sentFolder:"[Gmail]/Sent Mail",inboxFolder:"INBOX",appPasswordHelp:`Generate at https://myaccount.google.com/apppasswords
2
2
  (2-step verification must be enabled on your Google account first;
3
3
  Google won't accept your normal account password from third-party apps).`},outlook:{label:"Outlook / Office 365",smtpHost:"smtp-mail.outlook.com",smtpPort:587,imapHost:"outlook.office365.com",imapPort:993,sentFolder:"Sent Items",inboxFolder:"INBOX",appPasswordHelp:`Generate at https://account.microsoft.com/security \u2192 Advanced security options \u2192 App passwords
4
4
  (2-step verification must be enabled first).`},ionos:{label:"IONOS",smtpHost:"smtp.ionos.co.uk",smtpPort:587,imapHost:"imap.ionos.co.uk",imapPort:993,sentFolder:"Sent Items",inboxFolder:"INBOX",appPasswordHelp:`Use your normal IONOS mailbox password.
@@ -6,31 +6,41 @@ Google won't accept your normal account password from third-party apps).`},outlo
6
6
  (Fastmail requires app passwords for IMAP/SMTP regardless of 2FA setting.)`},zoho:{label:"Zoho Mail",smtpHost:"smtp.zoho.com",smtpPort:587,imapHost:"imap.zoho.com",imapPort:993,sentFolder:"Sent",inboxFolder:"INBOX",appPasswordHelp:`Generate at https://accounts.zoho.com/u/h#security/app_passwords
7
7
  (Zoho requires app passwords for IMAP/SMTP \u2014 your normal account password won't work.)`}},te=`Use the app-specific password your provider issues for SMTP/IMAP
8
8
  (check their security settings \u2014 most providers require a generated password
9
- rather than your normal account password).`;var R=class extends Error{constructor(){super("user pressed back"),this.name="BackSignal"}},U=class extends Error{constructor(){super("user cancelled"),this.name="CancelSignal"}},Pe="Include the country code with a + (e.g. +12025550123 for US, +447123456789 for UK)",oe=e=>/^\+\d{8,15}$/.test(e)?void 0:Pe,ve=e=>/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e)?void 0:"Enter a valid email",C=e=>t=>t.trim().length===0?`${e} is required`:void 0,xe="one-off, no monthly fees",ne="per month";function H(e){if(!e)return!0;let t=e.trim();if(t==="")return!0;let n=t.replace(/[^\d.]/g,"");if(n==="")return/^\s*free\s*$/i.test(t);let o=parseFloat(n);return!isNaN(o)&&o===0}var ke={id:"pricing",title:"Pricing",isApplicable:()=>!0,execute:async(e,{prompt:t})=>{let n=e.pricingTerms===ne,o=n?"":e.pricing??"$999",r=e.pricingMonthly??(n?e.pricing??"":""),a=await t({type:"text",message:"What's the upfront fee you'll charge clients per site?",placeholder:"e.g. $999, \xA3799, \u20AC899 \u2014 or 0 for monthly-only billing",initialValue:o,note:{title:"Upfront fee",body:`The one-time amount charged when a client signs up. Type 0 (or
9
+ rather than your normal account password).`;var N=class extends Error{constructor(){super("user pressed back"),this.name="BackSignal"}},L=class extends Error{constructor(){super("user cancelled"),this.name="CancelSignal"}},Pe="Include the country code with a + (e.g. +12025550123 for US, +447123456789 for UK)",ne=e=>/^\+\d{8,15}$/.test(e)?void 0:Pe,ve=e=>/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e)?void 0:"Enter a valid email",E=e=>t=>t.trim().length===0?`${e} is required`:void 0,ke="one-off, no monthly fees",oe="per month";function _(e){if(!e)return!0;let t=e.trim();if(t==="")return!0;let a=t.replace(/[^\d.]/g,"");if(a==="")return/^\s*free\s*$/i.test(t);let n=parseFloat(a);return!isNaN(n)&&n===0}var xe={id:"pricing",title:"Pricing",isApplicable:()=>!0,execute:async(e,{prompt:t})=>{let a=e.pricingTerms===oe,n=a?"":e.pricing??"$999",r=e.pricingMonthly??(a?e.pricing??"":""),s=await t({type:"text",message:"What's the upfront fee you'll charge clients per site?",placeholder:"e.g. $999, \xA3799, \u20AC899 \u2014 or 0 for monthly-only billing",initialValue:n,note:{title:"Upfront fee",body:`The one-time amount charged when a client signs up. Type 0 (or
10
10
  leave blank) if you only want to charge a monthly fee. You can
11
11
  also add a recurring monthly fee on the next prompt \u2014 combining
12
12
  the two is fine (e.g. $499 upfront + $49/month).
13
13
 
14
14
  Use the currency that matches your clients' region. Klaudius
15
- uses this string verbatim throughout outreach.`}}),s=await t({type:"text",message:"What's the monthly fee? (optional \u2014 leave blank for one-off only)",placeholder:"e.g. $49, \xA339, \u20AC45 \u2014 or blank for none",initialValue:r,validate:x=>{if(H(a)&&H(x))return"Set an upfront fee, a monthly fee, or both \u2014 they can't both be zero."},note:{title:"Monthly fee (optional)",body:`Leave blank to charge a one-off fee only. Fill it in to charge
15
+ uses this string verbatim throughout outreach.`}}),o=await t({type:"text",message:"What's the monthly fee? (optional \u2014 leave blank for one-off only)",placeholder:"e.g. $49, \xA339, \u20AC45 \u2014 or blank for none",initialValue:r,validate:b=>{if(_(s)&&_(b))return"Set an upfront fee, a monthly fee, or both \u2014 they can't both be zero."},note:{title:"Monthly fee (optional)",body:`Leave blank to charge a one-off fee only. Fill it in to charge
16
16
  a recurring monthly fee \u2014 either on its own (if upfront was 0)
17
- or alongside the upfront fee.`}}),u=H(a),i=H(s),l,c,m;return u&&!i?(l=s.trim(),c=ne,m=s.trim()):!u&&i?(l=a.trim(),c=xe,m=void 0):(l=a.trim(),c=`upfront, then ${s.trim()}/month`,m=s.trim()),{pricing:l,pricingTerms:c,pricingMonthly:m}}},Ie={id:"outreach-enabled",title:"Automated outreach",isApplicable:()=>!0,execute:async(e,{prompt:t})=>({outreachEnabled:await t({type:"confirm",message:"Use Klaudius's automated outreach features?",initialValue:e.outreachEnabled??!0,note:{title:"Automated outreach features",body:`After finding candidates and building websites for them, Klaudius can
17
+ or alongside the upfront fee.`}}),u=_(s),i=_(o),c,l,d;return u&&!i?(c=o.trim(),l=oe,d=o.trim()):!u&&i?(c=s.trim(),l=ke,d=void 0):(c=s.trim(),l=`upfront, then ${o.trim()}/month`,d=o.trim()),{pricing:c,pricingTerms:l,pricingMonthly:d}}},Ie={id:"outreach-enabled",title:"Automated outreach",isApplicable:()=>!0,execute:async(e,{prompt:t})=>({outreachEnabled:await t({type:"confirm",message:"Use Klaudius's automated outreach features?",initialValue:e.outreachEnabled??!0,note:{title:"Automated outreach features",body:`After finding candidates and building websites for them, Klaudius can
18
18
  run outreach to them automatically (email and/or SMS).
19
- If you'd rather handle outreach manually, you can skip this here.`}})})},Te={id:"operator-name",title:"Your name",isApplicable:e=>e.outreachEnabled===!0,execute:async(e,{prompt:t})=>{let n=await t({type:"text",message:"Your name as it should appear publicly in outreach",placeholder:"e.g. Mike Smith \u2014 or your business name if you'd rather",initialValue:e.name??e.emailFromName??"",validate:C("Name")}),o=n.trim().split(/\s+/)[0];return{name:n,signature:e.signature??`Thanks, ${o}`}}},Ae={id:"channels",title:"Outreach channels",isApplicable:e=>e.outreachEnabled===!0,execute:async(e,{prompt:t})=>{let n=e.outreachChannels&&e.outreachChannels.length>1?"both":e.outreachChannels?.[0]??"email",o=await t({type:"select",message:"Which channels can Klaudius use for outreach?",initialValue:n,options:[{value:"email",label:"Email only"},{value:"sms",label:"SMS only"},{value:"both",label:"Both (recommended for maximum reach)"}],note:{title:"Outreach channels",body:`Different businesses have different contact methods publicly available \u2014
20
- some list only an email, others only a phone number. Klaudius uses whichever
21
- channel is available for each candidate (it doesn't message the same candidate
22
- on both). Picking 'both' just means Klaudius can reach more of the
23
- businesses it finds.`}}),r=o==="both"?["email","sms"]:[o],a;return r.length>1&&(a=await t({type:"select",message:"When a candidate has both email and a phone number, which channel should Klaudius try first?",initialValue:e.outreachPriority??"email",options:[{value:"email",label:"Prefer email (better for B2B / professional services)"},{value:"sms",label:"Prefer SMS (better response rates for trades / local services)"}]})),{outreachChannels:r,outreachPriority:a}}},Ce={id:"email",title:"Email setup",isApplicable:e=>e.outreachChannels?.includes("email")===!0,execute:async(e,{prompt:t,info:n})=>{n({title:"Email setup",body:`Klaudius needs an email account to send outreach FROM. This is the
19
+ If you'd rather handle outreach manually, you can skip this here.`}})})},Ae={id:"operator-name",title:"Your name",isApplicable:e=>e.outreachEnabled===!0,execute:async(e,{prompt:t})=>{let a=await t({type:"text",message:"Your name as it should appear publicly in outreach",placeholder:"e.g. Mike Smith \u2014 or your business name if you'd rather",initialValue:e.name??e.emailFromName??"",validate:E("Name")}),n=a.trim().split(/\s+/)[0];return{name:a,signature:e.signature??`Thanks, ${n}`}}},Te={id:"channels",title:"Outreach channels & priority",isApplicable:e=>e.outreachEnabled===!0,execute:async(e,{prompt:t,info:a})=>{a({title:"Outreach channels & priority",body:`Different businesses have different contact methods publicly available \u2014 some
20
+ list only an email, others only a phone number, others use WhatsApp as their
21
+ primary channel. Klaudius lets you opt into multiple channels so it can reach
22
+ more candidates, and you set a priority order for when a candidate has
23
+ multiple contact methods available.
24
+
25
+ How it works: for each candidate, Klaudius walks your priority list in order
26
+ and picks the first channel that's viable for THAT candidate. If a channel's
27
+ send fails for a per-recipient reason (e.g. number not on WhatsApp, hard
28
+ email bounce), it cascades to your next-priority channel for that same
29
+ candidate \u2014 so opting into multiple channels also gives you fallback coverage
30
+ when one channel doesn't work.
31
+
32
+ You'll be asked to pick your first-choice channel now, then optionally a
33
+ second and third. The order matters: it's the order Klaudius tries.`});let n={email:"Email",sms:"SMS (iMessage or Twilio, configured next)",whatsapp:"WhatsApp (Baileys / phone-linked device)"},r=["email","sms","whatsapp"],s=e.outreachPriority??[],o=[],u=await t({type:"select",message:"Which channel should Klaudius try FIRST for each candidate?",initialValue:s[0]??"email",options:r.map(i=>({value:i,label:n[i]}))});for(o.push(u);o.length<r.length;){let i=r.filter(P=>!o.includes(P)),c=o.length===1?"second":"third",l=o[o.length-1],d=n[l].replace(/\s*\(.*\)$/,"").toLowerCase(),b=await t({type:"select",message:`Should Klaudius use another channel as ${c} priority (for candidates where ${d} isn't viable or fails)?`,initialValue:s[o.length]??"no",options:[...i.map(P=>({value:P,label:`Yes \u2014 also use ${n[P]}`})),{value:"no",label:"No, that's all"}]});if(b==="no")break;o.push(b)}return{outreachChannels:o,outreachPriority:o}}},Ce={id:"email",title:"Email setup",isApplicable:e=>e.outreachChannels?.includes("email")===!0,execute:async(e,{prompt:t,info:a})=>{a({title:"Email setup",body:`Klaudius needs an email account to send outreach FROM. This is the
24
34
  address candidates will see as the sender. Use a domain you control
25
- (your own, your business's) \u2014 not your personal address.`});let o=await t({type:"select",message:"Who hosts the email account you'll send outreach from?",initialValue:e.emailProvider??"gmail",options:[{value:"gmail",label:"Gmail"},{value:"fastmail",label:"Fastmail"},{value:"outlook",label:"Outlook / Office 365"},{value:"zoho",label:"Zoho Mail"},{value:"ionos",label:"IONOS"},{value:"custom",label:"Custom / other (enter SMTP/IMAP details manually)"}]}),r=o!=="custom"?ee[o]:void 0,a=await t({type:"text",message:"Email address to send outreach from",placeholder:"you@yourbusiness.com",initialValue:e.emailAddress??"",validate:ve}),s=r?.appPasswordHelp??te,u=await t({type:"password",message:"Paste the app password",initialValue:e.emailPassword??"",validate:C("App password"),note:{title:"App password",body:`An app password is a separate, single-purpose password that your
35
+ (your own, your business's) \u2014 not your personal address.`});let n=await t({type:"select",message:"Who hosts the email account you'll send outreach from?",initialValue:e.emailProvider??"gmail",options:[{value:"gmail",label:"Gmail"},{value:"fastmail",label:"Fastmail"},{value:"outlook",label:"Outlook / Office 365"},{value:"zoho",label:"Zoho Mail"},{value:"ionos",label:"IONOS"},{value:"custom",label:"Custom / other (enter SMTP/IMAP details manually)"}]}),r=n!=="custom"?ee[n]:void 0,s=await t({type:"text",message:"Email address to send outreach from",placeholder:"you@yourbusiness.com",initialValue:e.emailAddress??"",validate:ve}),o=r?.appPasswordHelp??te,u=await t({type:"password",message:"Paste the app password",initialValue:e.emailPassword??"",validate:E("App password"),note:{title:"App password",body:`An app password is a separate, single-purpose password that your
26
36
  email provider issues for third-party apps like Klaudius. It is NOT
27
37
  your normal account login password.
28
38
 
29
- `+s+`
39
+ `+o+`
30
40
 
31
41
  Once generated, it's stored locally in this project's .env file.
32
42
  It is never sent to Klaudius's servers \u2014 only to your email
33
- provider when sending outreach.`}}),i,l,c,m,x,E;if(o==="custom"){i=await t({type:"text",message:"SMTP host (the server Klaudius connects to for sending)",placeholder:"e.g. smtp.yourprovider.com",initialValue:e.emailSmtpHost??"",validate:C("SMTP host")});let _=await t({type:"text",message:"SMTP port (usually 587 for STARTTLS or 465 for SSL)",initialValue:String(e.emailSmtpPort??587),validate:A=>/^\d+$/.test(A)?void 0:"Must be a number"});l=parseInt(_,10),c=await t({type:"text",message:"IMAP host (the server Klaudius connects to for reading replies)",placeholder:"e.g. imap.yourprovider.com",initialValue:e.emailImapHost??"",validate:C("IMAP host")});let O=await t({type:"text",message:"IMAP port (usually 993 for SSL)",initialValue:String(e.emailImapPort??993),validate:A=>/^\d+$/.test(A)?void 0:"Must be a number"});m=parseInt(O,10),x=await t({type:"text",message:"Sent folder name (so SMTP-sent messages also appear in your email client's Sent folder)",placeholder:'e.g. "Sent", "Sent Items"',initialValue:e.emailSentFolder??"Sent"}),E=await t({type:"text",message:"Inbox folder name (almost always INBOX)",initialValue:e.emailInboxFolder??"INBOX"})}else i=r.smtpHost,l=r.smtpPort,c=r.imapHost,m=r.imapPort,x=r.sentFolder,E=r.inboxFolder;return{emailProvider:o,emailAddress:a,emailPassword:u,emailFromName:e.name,emailSmtpHost:i,emailSmtpPort:l,emailImapHost:c,emailImapPort:m,emailSentFolder:x,emailInboxFolder:E}}},Ee={id:"sms",title:"SMS setup",isApplicable:e=>e.outreachChannels?.includes("sms")===!0,execute:async(e,{prompt:t,info:n})=>{n({title:"SMS setup",body:`Klaudius can send SMS one of two ways:
43
+ provider when sending outreach.`}}),i,c,l,d,b,P;if(n==="custom"){i=await t({type:"text",message:"SMTP host (the server Klaudius connects to for sending)",placeholder:"e.g. smtp.yourprovider.com",initialValue:e.emailSmtpHost??"",validate:E("SMTP host")});let H=await t({type:"text",message:"SMTP port (usually 587 for STARTTLS or 465 for SSL)",initialValue:String(e.emailSmtpPort??587),validate:C=>/^\d+$/.test(C)?void 0:"Must be a number"});c=parseInt(H,10),l=await t({type:"text",message:"IMAP host (the server Klaudius connects to for reading replies)",placeholder:"e.g. imap.yourprovider.com",initialValue:e.emailImapHost??"",validate:E("IMAP host")});let O=await t({type:"text",message:"IMAP port (usually 993 for SSL)",initialValue:String(e.emailImapPort??993),validate:C=>/^\d+$/.test(C)?void 0:"Must be a number"});d=parseInt(O,10),b=await t({type:"text",message:"Sent folder name (so SMTP-sent messages also appear in your email client's Sent folder)",placeholder:'e.g. "Sent", "Sent Items"',initialValue:e.emailSentFolder??"Sent"}),P=await t({type:"text",message:"Inbox folder name (almost always INBOX)",initialValue:e.emailInboxFolder??"INBOX"})}else i=r.smtpHost,c=r.smtpPort,l=r.imapHost,d=r.imapPort,b=r.sentFolder,P=r.inboxFolder;return{emailProvider:n,emailAddress:s,emailPassword:u,emailFromName:e.name,emailSmtpHost:i,emailSmtpPort:c,emailImapHost:l,emailImapPort:d,emailSentFolder:b,emailInboxFolder:P}}},Ee={id:"sms",title:"SMS setup",isApplicable:e=>e.outreachChannels?.includes("sms")===!0,execute:async(e,{prompt:t,info:a})=>{a({title:"SMS setup",body:`Klaudius can send SMS one of two ways:
34
44
 
35
45
  \u2022 macOS iMessage \u2014 free, uses Messages.app on your Mac.
36
46
  Reaches other Apple users as iMessage for free. To reach
@@ -46,7 +56,25 @@ provider when sending outreach.`}}),i,l,c,m,x,E;if(o==="custom"){i=await t({type
46
56
 
47
57
  \u2022 Twilio \u2014 cross-platform, ~$0.01 per SMS. Sender is a phone
48
58
  number you buy from Twilio. Works on any OS, reaches any
49
- phone, no iPhone required. Recommended for consistent delivery.`});let o=await t({type:"select",message:"Which SMS provider?",initialValue:e.smsProvider??(process.platform==="darwin"?"imessage":"twilio"),options:[{value:"imessage",label:"macOS iMessage (free, Mac only)"},{value:"twilio",label:"Twilio (cross-platform, paid per-message \u2014 recommended)"}]}),r=await t({type:"text",message:"Your mobile number (used as a safe target for test sends so Klaudius doesn't accidentally message real candidates while you're testing)",placeholder:"+12025550123",initialValue:e.testPhone??"",validate:oe}),a={smsProvider:o,testPhone:r};return o==="twilio"&&(a.twilioAccountSid=await t({type:"text",message:"Twilio Account SID (starts with AC...)",initialValue:e.twilioAccountSid??"",validate:s=>/^AC[a-zA-Z0-9]+$/.test(s)?void 0:"Should start with 'AC'"}),a.twilioAuthToken=await t({type:"password",message:"Twilio Auth Token",initialValue:e.twilioAuthToken??"",validate:C("Twilio Auth Token")}),a.twilioPhoneNumber=await t({type:"text",message:"Twilio phone number (the number outreach will be sent FROM)",placeholder:"+15551234567",initialValue:e.twilioPhoneNumber??"",validate:oe})),a}},Oe={id:"vercel",title:"Vercel deployment",isApplicable:()=>!0,execute:async(e,{prompt:t})=>({vercelToken:await t({type:"password",message:"Paste your Vercel API token",initialValue:e.vercelToken??"",validate:o=>o.trim().length===0?"Required \u2014 without this Klaudius can't deploy generated sites":void 0,note:{title:"Vercel deployment",body:`Klaudius deploys every generated client site to Vercel. We use a
59
+ phone, no iPhone required. Recommended for consistent delivery.`});let n=await t({type:"select",message:"Which SMS provider?",initialValue:e.smsProvider??(process.platform==="darwin"?"imessage":"twilio"),options:[{value:"imessage",label:"macOS iMessage (free, Mac only)"},{value:"twilio",label:"Twilio (cross-platform, paid per-message \u2014 recommended)"}]}),r=await t({type:"text",message:"Your mobile number (used as a safe target for test sends so Klaudius doesn't accidentally message real candidates while you're testing)",placeholder:"+12025550123",initialValue:e.testPhone??"",validate:ne}),s={smsProvider:n,testPhone:r};return n==="twilio"&&(s.twilioAccountSid=await t({type:"text",message:"Twilio Account SID (starts with AC...)",initialValue:e.twilioAccountSid??"",validate:o=>/^AC[a-zA-Z0-9]+$/.test(o)?void 0:"Should start with 'AC'"}),s.twilioAuthToken=await t({type:"password",message:"Twilio Auth Token",initialValue:e.twilioAuthToken??"",validate:E("Twilio Auth Token")}),s.twilioPhoneNumber=await t({type:"text",message:"Twilio phone number (the number outreach will be sent FROM)",placeholder:"+15551234567",initialValue:e.twilioPhoneNumber??"",validate:ne})),s}},Oe={id:"whatsapp",title:"WhatsApp setup",isApplicable:e=>e.outreachPriority?.includes("whatsapp")===!0,execute:async(e,{prompt:t,info:a})=>{a({title:"WhatsApp setup",body:`Klaudius connects to WhatsApp as a linked device on your phone \u2014 same way
60
+ WhatsApp Web works. Setup is a one-time QR scan from the WhatsApp app on
61
+ the phone whose number you want to use. Klaudius will guide you through
62
+ that AFTER this wizard, once npm dependencies are installed.
63
+
64
+ Multiple numbers (advanced): if you plan to send at higher volume, you can
65
+ link 2-5 WhatsApp accounts. Klaudius round-robins across them for initial
66
+ outreach (spreading the load and the ban risk); follow-ups always use the
67
+ same account that started the thread. Each account is independent \u2014 one
68
+ getting banned doesn't affect the others. For multi-number you need a
69
+ separate phone number per account (they're tied to real SIMs).
70
+
71
+ IMPORTANT: WhatsApp may suspend numbers used for cold outbound. Start with
72
+ phone numbers you can afford to lose, and don't link your main personal
73
+ number unless you're comfortable with that.
74
+
75
+ You'll be asked how many accounts to link and a short label for each
76
+ (used only locally \u2014 appears in logs, in the .env file, and in this
77
+ project's per-account directory under ~/.klaudius/whatsapp/).`});let n=await t({type:"select",message:"How many WhatsApp numbers do you want to link?",initialValue:String(e.whatsappAccounts?.length??1),options:[{value:"1",label:"1 number (recommended starting point)"},{value:"2",label:"2 numbers (spread load across two)"},{value:"3",label:"3 numbers"},{value:"4",label:"4 numbers"},{value:"5",label:"5 numbers (maximum)"}]}),r=parseInt(n,10),s=["primary","secondary","tertiary","quaternary","quinary"],o=[];for(let u=0;u<r;u++){let i=await t({type:"text",message:r===1?"Label for this WhatsApp account (used only locally \u2014 'primary' is fine)":`Label for WhatsApp account ${u+1} of ${r} (e.g. 'primary', 'uk-1', 'us-east')`,initialValue:e.whatsappAccounts?.[u]??s[u],validate:c=>{let l=c.trim();if(!l)return"Required";if(l.length>30)return"Too long (max 30 characters)";if(l.startsWith("-")||l.endsWith("-"))return"Can't start or end with a hyphen";if(!/^[A-Za-z0-9_-]+$/.test(l))return"Letters, digits, underscore, hyphen only (no spaces)";if(o.includes(l))return"Duplicate label"}});o.push(i.trim())}return{whatsappAccounts:o}}},Me={id:"vercel",title:"Vercel deployment",isApplicable:()=>!0,execute:async(e,{prompt:t})=>({vercelToken:await t({type:"password",message:"Paste your Vercel API token",initialValue:e.vercelToken??"",validate:n=>n.trim().length===0?"Required \u2014 without this Klaudius can't deploy generated sites":void 0,note:{title:"Vercel deployment",body:`Klaudius deploys every generated client site to Vercel. We use a
50
78
  Vercel API token to do this without an interactive login.
51
79
 
52
80
  How to get one (one-time, ~30 seconds):
@@ -69,7 +97,7 @@ STUCK? Open Claude (or any LLM) in another tab/app and paste:
69
97
  "I need to create a personal Vercel API token for the
70
98
  Klaudius CLI tool. Walk me through generating one at
71
99
  vercel.com/account/tokens, including which scope and
72
- expiration to choose."`}})})},Me={id:"supabase",title:"Supabase",isApplicable:()=>!0,execute:async(e,{prompt:t,info:n})=>{n({title:"Supabase setup",body:`Supabase is your CRM. It's where Klaudius records every business it
100
+ expiration to choose."`}})})},Re={id:"supabase",title:"Supabase",isApplicable:()=>!0,execute:async(e,{prompt:t,info:a})=>{a({title:"Supabase setup",body:`Supabase is your CRM. It's where Klaudius records every business it
73
101
  finds, where each one sits in your funnel (gathered \u2192 built \u2192 deployed
74
102
  \u2192 outreach sent \u2192 responded), and the follow-up state for every lead.
75
103
  You can browse it at any time from the Supabase dashboard, or ask
@@ -107,8 +135,8 @@ in another tab/app and paste this prompt verbatim:
107
135
  Settings \u2192 Data API \u2192 'API URL'
108
136
 
109
137
  It looks like https://xxxx.supabase.co. Click to copy and paste
110
- below.`}})).trim().replace(/\/rest\/v1\/?$/i,"").replace(/\/$/,""),a=r.match(/^https:\/\/([a-z0-9]+)\.supabase\.co/i)?.[1]??"",s=await t({type:"password",message:"Paste the Supabase secret key (sb_secret_\u2026)",initialValue:e.supabaseServiceKey??"",validate:i=>i.length<20?"Looks too short":void 0,note:{title:"Secret key",body:a?`Open this exact page:
111
- https://supabase.com/dashboard/project/${a}/settings/api-keys
138
+ below.`}})).trim().replace(/\/rest\/v1\/?$/i,"").replace(/\/$/,""),s=r.match(/^https:\/\/([a-z0-9]+)\.supabase\.co/i)?.[1]??"",o=await t({type:"password",message:"Paste the Supabase secret key (sb_secret_\u2026)",initialValue:e.supabaseServiceKey??"",validate:i=>i.length<20?"Looks too short":void 0,note:{title:"Secret key",body:s?`Open this exact page:
139
+ https://supabase.com/dashboard/project/${s}/settings/api-keys
112
140
 
113
141
  Under 'Secret keys', find the row whose value starts with
114
142
  'sb_secret_'. Click to copy the full value.
@@ -125,7 +153,7 @@ Open this exact page:
125
153
  Click 'Generate new token', name it 'Klaudius', and set the
126
154
  expiration to 'Never' (recommended \u2014 saves you having to rotate
127
155
  it later). Copy the value (starts with 'sbp_') and paste it
128
- below.`}});return{supabaseUrl:r,supabaseServiceKey:s,supabasePat:u,supabaseProjectRef:a}}},Ne={id:"google-places",title:"Google Places API",isApplicable:()=>!0,execute:async(e,{prompt:t})=>({googlePlacesApiKey:await t({type:"password",message:"Paste your Google Places API key",placeholder:"AIzaSy\u2026",initialValue:e.googlePlacesApiKey??"",validate:o=>o.trim().length===0?"Required \u2014 without this Klaudius can't find candidates":void 0,note:{title:"Google Places API key",body:`Klaudius's /find skill queries Google's Places API to discover businesses
156
+ below.`}});return{supabaseUrl:r,supabaseServiceKey:o,supabasePat:u,supabaseProjectRef:s}}},Ne={id:"google-places",title:"Google Places API",isApplicable:()=>!0,execute:async(e,{prompt:t})=>({googlePlacesApiKey:await t({type:"password",message:"Paste your Google Places API key",placeholder:"AIzaSy\u2026",initialValue:e.googlePlacesApiKey??"",validate:n=>n.trim().length===0?"Required \u2014 without this Klaudius can't find candidates":void 0,note:{title:"Google Places API key",body:`Klaudius's /find skill queries Google's Places API to discover businesses
129
157
  without websites in your target region. Without a key, the pipeline has
130
158
  no source of leads \u2014 so this is required.
131
159
 
@@ -161,13 +189,13 @@ STUCK? Open Claude (or any LLM) in another tab/app and paste this prompt:
161
189
  "I need a Google Places API (New) key for a CLI tool called
162
190
  Klaudius. Walk me through claiming the $300 Google Cloud free trial
163
191
  and getting the API key Google auto-generates after enabling
164
- Places API (New), including any signup gotchas."`}})})},Re={id:"telegram",title:"Telegram (optional)",isApplicable:()=>!0,clearOnSkip:["telegramBotToken","telegramChatId"],execute:async(e,{prompt:t})=>{if(!await t({type:"confirm",message:"Set up Telegram notifications? (sends a ping when outreach lands)",initialValue:!!e.telegramBotToken,note:{title:"Telegram notifications (optional)",body:`Klaudius can ping a Telegram chat when outreach is sent or when a
192
+ Places API (New), including any signup gotchas."`}})})},Be={id:"telegram",title:"Telegram (optional)",isApplicable:()=>!0,clearOnSkip:["telegramBotToken","telegramChatId"],execute:async(e,{prompt:t})=>{if(!await t({type:"confirm",message:"Set up Telegram notifications? (sends a ping when outreach lands)",initialValue:!!e.telegramBotToken,note:{title:"Telegram notifications (optional)",body:`Klaudius can ping a Telegram chat when outreach is sent or when a
165
193
  candidate replies. This is OPTIONAL \u2014 skip it if you'd rather check
166
194
  the Supabase dashboard manually.
167
195
 
168
196
  If you say yes, you'll need a Telegram bot token (created via
169
197
  @BotFather, ~30 seconds) and your chat ID (your own user ID, for
170
- personal pings). The next two prompts walk you through both.`}}))return{telegramBotToken:void 0,telegramChatId:void 0};let o=await t({type:"password",message:"Paste your Telegram bot token",initialValue:e.telegramBotToken??"",validate:C("Bot token"),note:{title:"Bot token",body:`Telegram lets you create personal bots in ~30 seconds. Klaudius
198
+ personal pings). The next two prompts walk you through both.`}}))return{telegramBotToken:void 0,telegramChatId:void 0};let n=await t({type:"password",message:"Paste your Telegram bot token",initialValue:e.telegramBotToken??"",validate:E("Bot token"),note:{title:"Bot token",body:`Telegram lets you create personal bots in ~30 seconds. Klaudius
171
199
  uses a bot to send you private notifications.
172
200
 
173
201
  How to create one:
@@ -180,16 +208,16 @@ How to create one:
180
208
  'KlaudiusNotifierBot'). Each username has to be globally
181
209
  unique, so add a personal suffix if it's taken.
182
210
  6. BotFather replies with a token like
183
- '1234567890:AAEhBP_yourtokenhere\u2026'. Copy it and paste below.`}}),r=null,a=0,s=null,u=null;for(;r===null;){a++;let i=a>1,l=u==="network"?`${s}
211
+ '1234567890:AAEhBP_yourtokenhere\u2026'. Copy it and paste below.`}}),r=null,s=0,o=null,u=null;for(;r===null;){s++;let i=s>1,c=u==="network"?`${o}
184
212
 
185
213
  This is usually a network problem on your end (corporate WiFi or VPN
186
214
  blocking Telegram, ISP DNS issue, a momentary drop). Check your
187
215
  connection, try a different network if available, then press Enter
188
- to retry.`:`${s}
216
+ to retry.`:`${o}
189
217
 
190
218
  Make sure you sent a regular text message (e.g. 'hi'), not
191
219
  just a /start tap \u2014 /start alone doesn't always register.
192
- Then press Enter to retry.`;await t({type:"text",message:i?u==="network"?"Check your network, then press Enter to retry":"Send another message to the bot, then press Enter to retry":"Send a message to your bot, then press Enter to detect chat ID",initialValue:"",placeholder:"(press Enter when you've sent the message)",validate:()=>{},note:{title:i?"Detect chat ID \u2014 retry":"Detect chat ID",body:i?l:`Klaudius will auto-detect your chat ID by asking Telegram for
220
+ Then press Enter to retry.`;await t({type:"text",message:i?u==="network"?"Check your network, then press Enter to retry":"Send another message to the bot, then press Enter to retry":"Send a message to your bot, then press Enter to detect chat ID",initialValue:"",placeholder:"(press Enter when you've sent the message)",validate:()=>{},note:{title:i?"Detect chat ID \u2014 retry":"Detect chat ID",body:i?c:`Klaudius will auto-detect your chat ID by asking Telegram for
193
221
  any messages your bot has received. To make that work:
194
222
 
195
223
  1. In the Telegram app, search for the bot you just created
@@ -198,5 +226,5 @@ any messages your bot has received. To make that work:
198
226
  If the chat starts with a 'Start' button, tap that first,
199
227
  THEN send 'hi'. /start alone doesn't always show up.
200
228
  3. Press Enter below \u2014 Klaudius will detect the chat ID for
201
- you.`}});let c=await Q({botToken:o});if(c.ok&&c.chatId)r=c.chatId;else if(c.reason==="no_messages")s="No messages from you to your bot have been picked up yet.",u="no_messages";else if(c.reason==="network")s=c.message??"Could not reach Telegram.",u="network";else throw new Error(`Telegram chat ID auto-detect failed: ${c.message??"unknown error"}`)}return{telegramBotToken:o,telegramChatId:r}}},I=[ke,Ie,Te,Ae,Ce,Ee,Oe,Me,Ne,Re];import{Box as ae,Text as Be}from"ink";import{jsx as se,jsxs as Fe}from"react/jsx-runtime";var Ve={pending:"\u25CB",current:"\u25C9",done:"\u2713",skipped:"\xB7"},Ke={pending:void 0,current:"cyan",done:"green",skipped:void 0};function re({items:e}){return se(ae,{flexDirection:"column",width:28,flexShrink:0,children:e.map(t=>{let n=t.status==="skipped"||t.status==="pending";return se(ae,{children:Fe(Be,{color:Ke[t.status],bold:t.status==="current",dimColor:n&&t.status!=="current",children:[Ve[t.status]," ",t.title]})},t.id)})})}import{useEffect as _e,useState as ie}from"react";import{Box as z,Text as D,useInput as He}from"ink";import Ue from"ink-text-input";import{jsx as B,jsxs as W}from"react/jsx-runtime";function le({spec:e,masked:t,onSubmit:n,onBack:o}){let[r,a]=ie(typeof e.initialValue=="string"?e.initialValue:""),[s,u]=ie(null);_e(()=>(f("TextPromptUI:mount",{masked:t,message:e.message.slice(0,60),initial:typeof e.initialValue=="string"?e.initialValue.slice(0,30):null}),()=>{f("TextPromptUI:unmount")}),[t,e.message,e.initialValue]),He((l,c)=>{f("TextPromptUI:useInput fired",{input:l,ctrl:c.ctrl,escape:c.escape,return:c.return}),c.escape&&o()});let i=l=>{f("TextPromptUI:handleSubmit",{raw:l.slice(0,30)});let c=l;if(e.validate){let m=e.validate(c);if(m){f("TextPromptUI:validate failed",{err:m}),u(m);return}}u(null),n(c)};return W(z,{flexDirection:"column",children:[W(D,{children:[B(D,{color:"cyan",children:"?"})," ",e.message]}),W(z,{children:[B(D,{color:"green",children:"\u203A "}),B(Ue,{value:r,onChange:a,onSubmit:i,placeholder:e.placeholder,mask:t?"\u2022":void 0})]}),s&&B(z,{marginTop:0,children:B(D,{color:"red",children:s})})]})}import{useState as De}from"react";import{Box as ce,Text as j,useInput as Ge}from"ink";import{jsx as ue,jsxs as q}from"react/jsx-runtime";function pe({spec:e,onSubmit:t,onBack:n}){let o=e.options??[],r=typeof e.initialValue=="string"?Math.max(0,o.findIndex(u=>u.value===e.initialValue)):0,[a,s]=De(r===-1?0:r);return Ge((u,i)=>{if(i.escape)n();else if(i.upArrow)s(l=>(l-1+o.length)%o.length);else if(i.downArrow)s(l=>(l+1)%o.length);else if(i.return){let l=o[a];l&&t(l.value)}}),q(ce,{flexDirection:"column",children:[q(j,{children:[ue(j,{color:"cyan",children:"?"})," ",e.message]}),ue(ce,{flexDirection:"column",marginTop:0,children:o.map((u,i)=>{let l=i===a;return q(j,{color:l?"cyan":void 0,bold:l,children:[l?"\u25CF ":"\u25CB ",u.label]},u.value)})})]})}import{useState as Le}from"react";import{Box as de,Text as V,useInput as $e}from"ink";import{jsx as me,jsxs as K}from"react/jsx-runtime";function he({spec:e,onSubmit:t,onBack:n}){let[o,r]=Le(typeof e.initialValue=="boolean"?e.initialValue:!0);return $e((a,s)=>{s.escape?n():s.leftArrow||s.rightArrow?r(u=>!u):a==="y"||a==="Y"?r(!0):a==="n"||a==="N"?r(!1):s.return&&t(o)}),K(de,{flexDirection:"column",children:[K(V,{children:[me(V,{color:"cyan",children:"?"})," ",e.message]}),K(de,{marginTop:0,children:[K(V,{color:o?"cyan":void 0,bold:o,children:[o?"\u25CF ":"\u25CB ","Yes"]}),me(V,{children:" "}),K(V,{color:o?void 0:"cyan",bold:!o,children:[o?"\u25CB ":"\u25CF ","No"]})]})]})}import{Box as ge,Text as fe}from"ink";import{jsx as Y,jsxs as ze}from"react/jsx-runtime";function X({title:e,body:t}){let n=t.split(`
202
- `);return ze(ge,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[Y(fe,{color:"cyan",bold:!0,children:e}),Y(ge,{flexDirection:"column",marginTop:0,children:n.map((o,r)=>Y(fe,{dimColor:!1,children:o.length===0?" ":o},r))})]})}import{jsx as d,jsxs as F}from"react/jsx-runtime";function Vt({defaults:e,onComplete:t,onlySection:n,banner:o}){let{exit:r}=qe(),a=Z({...e}),s=Z(new Map),[,u]=T(0),i=()=>u(h=>h+1),[l,c]=T(null),[m,x]=T(null),[E,_]=T([]),[O,A]=T(null),[J,ye]=T(!1),[G,be]=T({current:0,total:0}),M=()=>{let h=s.current;for(let y of I){let $=y.isApplicable(a.current),p=h.get(y.id);$?n&&y.id!==n?p!=="current"&&h.set(y.id,"done"):(p==="skipped"||!p)&&h.set(y.id,"pending"):h.set(y.id,"skipped")}};s.current.size===0&&M();let L=Z(!1);We(()=>{if(f("WizardApp:useEffect fired",{startedAlready:L.current}),L.current){f("WizardApp:useEffect returning early (startedRef true)");return}L.current=!0,f("WizardApp:orchestrator starting");let h=0,y=p=>{let S=++h;return f("orchestrator:promptFn called",{id:S,type:p.type,message:p.message.slice(0,60)}),A(null),new Promise((b,g)=>{x({id:S,spec:p,resolve:v=>{f("orchestrator:prompt resolved",{id:S,type:p.type,value:typeof v=="string"?v.slice(0,30):v}),b(v)},reject:v=>{f("orchestrator:prompt rejected",{id:S,reason:v.message}),g(v)}})})},$=p=>{_(S=>[...S,p])};return(async()=>{try{let p=n?I.filter(g=>g.id===n):I,S=()=>p.filter(g=>g.isApplicable(a.current)).length,b=0;for(;b<p.length;){let g=p[b];if(!g.isApplicable(a.current)){s.current.set(g.id,"skipped"),b++,M(),i();continue}_([]);for(let w of I)w.id===g.id?s.current.set(w.id,"current"):s.current.get(w.id)==="current"&&s.current.set(w.id,"pending");c(g.id);let v=p.slice(0,b+1).filter(w=>w.isApplicable(a.current)).length;be({current:v,total:S()}),i();try{let w=await g.execute(a.current,{prompt:y,info:$});a.current={...a.current,...w},s.current.set(g.id,"done"),M(),b++}catch(w){if(w instanceof R){if(n&&g.clearOnSkip){for(let Se of g.clearOnSkip)a.current[Se]=void 0;s.current.set(g.id,"skipped"),M(),b++;continue}if(n)continue;s.current.set(g.id,"pending");let N=b-1;for(;N>=0&&!p[N].isApplicable(a.current);)N--;N<0||(b=N,s.current.set(p[b].id,"pending")),M(),i();continue}throw w}}f("orchestrator:all sections done, calling onComplete + exit"),ye(!0),x(null),c(null),i(),await new Promise(g=>setTimeout(g,200)),t(a.current),r()}catch(p){f("orchestrator:caught error",{name:p?.name,message:p?.message}),p instanceof U&&(r(),process.exit(0));let S=p instanceof Error?p.message:String(p);A(`Setup error: ${S}`),i()}})(),()=>{f("WizardApp:useEffect cleanup ran (component unmounting)")}},[r,t]),Ye((h,y)=>{f("WizardApp:useInput fired",{input:h,ctrl:y.ctrl,escape:y.escape,return:y.return}),y.ctrl&&h==="c"&&(f("WizardApp:Ctrl+C \u2192 exiting"),r(),process.exit(0))});let we=je(()=>I.map(h=>({id:h.id,title:h.title,status:s.current.get(h.id)??"pending"})),[l,J,O]);return F(P,{flexDirection:"column",paddingY:1,children:[F(P,{marginBottom:1,children:[d(k,{bold:!0,color:"cyan",children:"Klaudius setup"}),d(k,{dimColor:!0,children:" \xB7 "}),d(k,{dimColor:!0,children:G.total>0?`Step ${G.current} of ${G.total}`:"Loading\u2026"})]}),F(P,{children:[d(re,{items:we}),F(P,{flexDirection:"column",flexGrow:1,marginLeft:2,children:[o&&F(P,{marginBottom:1,borderStyle:"round",borderColor:"red",paddingX:1,flexDirection:"column",children:[d(k,{color:"red",bold:!0,children:"\u26A0 Heads up"}),d(k,{children:o})]}),E.map((h,y)=>d(P,{marginBottom:1,children:d(X,{title:h.title,body:h.body})},y)),m?.spec.note&&d(P,{marginBottom:1,children:d(X,{title:m.spec.note.title,body:m.spec.note.body})}),m&&Ze(m),O&&d(P,{marginTop:1,children:d(k,{color:"red",children:O})}),J&&d(P,{marginTop:1,children:d(k,{color:"green",bold:!0,children:"\u2713 Setup complete. Continuing\u2026"})})]})]}),d(P,{marginTop:1,children:d(k,{dimColor:!0,children:Xe(n,l)})})]})}function Xe(e,t){if(e){let n=I.find(o=>o.id===t);return n?.clearOnSkip&&n.clearOnSkip.length>0?"\u21B5 confirm esc skip this section ctrl-c cancel":"\u21B5 confirm ctrl-c cancel"}return"\u21B5 confirm esc back to previous section ctrl-c cancel"}function Ze(e){let t=o=>e.resolve(o),n=()=>e.reject(new R);switch(e.spec.type){case"text":case"password":return d(le,{spec:e.spec,masked:e.spec.type==="password",onSubmit:t,onBack:n},e.id);case"select":return d(pe,{spec:e.spec,onSubmit:t,onBack:n},e.id);case"confirm":return d(he,{spec:e.spec,onSubmit:t,onBack:n},e.id)}}export{Vt as WizardApp};
229
+ you.`}});let l=await J({botToken:n});if(l.ok&&l.chatId)r=l.chatId;else if(l.reason==="no_messages")o="No messages from you to your bot have been picked up yet.",u="no_messages";else if(l.reason==="network")o=l.message??"Could not reach Telegram.",u="network";else throw new Error(`Telegram chat ID auto-detect failed: ${l.message??"unknown error"}`)}return{telegramBotToken:n,telegramChatId:r}}},A=[xe,Ie,Ae,Te,Ce,Ee,Oe,Me,Re,Ne,Be];import{Box as ae,Text as Ve}from"ink";import{jsx as se,jsxs as He}from"react/jsx-runtime";var Ke={pending:"\u25CB",current:"\u25C9",done:"\u2713",skipped:"\xB7"},Fe={pending:void 0,current:"cyan",done:"green",skipped:void 0};function re({items:e}){return se(ae,{flexDirection:"column",width:28,flexShrink:0,children:e.map(t=>{let a=t.status==="skipped"||t.status==="pending";return se(ae,{children:He(Ve,{color:Fe[t.status],bold:t.status==="current",dimColor:a&&t.status!=="current",children:[Ke[t.status]," ",t.title]})},t.id)})})}import{useEffect as _e,useState as ie}from"react";import{Box as G,Text as W,useInput as Le}from"ink";import We from"ink-text-input";import{jsx as B,jsxs as z}from"react/jsx-runtime";function le({spec:e,masked:t,onSubmit:a,onBack:n}){let[r,s]=ie(typeof e.initialValue=="string"?e.initialValue:""),[o,u]=ie(null);_e(()=>(f("TextPromptUI:mount",{masked:t,message:e.message.slice(0,60),initial:typeof e.initialValue=="string"?e.initialValue.slice(0,30):null}),()=>{f("TextPromptUI:unmount")}),[t,e.message,e.initialValue]),Le((c,l)=>{f("TextPromptUI:useInput fired",{input:c,ctrl:l.ctrl,escape:l.escape,return:l.return}),l.escape&&n()});let i=c=>{f("TextPromptUI:handleSubmit",{raw:c.slice(0,30)});let l=c;if(e.validate){let d=e.validate(l);if(d){f("TextPromptUI:validate failed",{err:d}),u(d);return}}u(null),a(l)};return z(G,{flexDirection:"column",children:[z(W,{children:[B(W,{color:"cyan",children:"?"})," ",e.message]}),z(G,{children:[B(W,{color:"green",children:"\u203A "}),B(We,{value:r,onChange:s,onSubmit:i,placeholder:e.placeholder,mask:t?"\u2022":void 0})]}),o&&B(G,{marginTop:0,children:B(W,{color:"red",children:o})})]})}import{useState as De}from"react";import{Box as ce,Text as j,useInput as Ue}from"ink";import{jsx as ue,jsxs as q}from"react/jsx-runtime";function pe({spec:e,onSubmit:t,onBack:a}){let n=e.options??[],r=typeof e.initialValue=="string"?Math.max(0,n.findIndex(u=>u.value===e.initialValue)):0,[s,o]=De(r===-1?0:r);return Ue((u,i)=>{if(i.escape)a();else if(i.upArrow)o(c=>(c-1+n.length)%n.length);else if(i.downArrow)o(c=>(c+1)%n.length);else if(i.return){let c=n[s];c&&t(c.value)}}),q(ce,{flexDirection:"column",children:[q(j,{children:[ue(j,{color:"cyan",children:"?"})," ",e.message]}),ue(ce,{flexDirection:"column",marginTop:0,children:n.map((u,i)=>{let c=i===s;return q(j,{color:c?"cyan":void 0,bold:c,children:[c?"\u25CF ":"\u25CB ",u.label]},u.value)})})]})}import{useState as $e}from"react";import{Box as de,Text as V,useInput as Ge}from"ink";import{jsx as me,jsxs as K}from"react/jsx-runtime";function he({spec:e,onSubmit:t,onBack:a}){let[n,r]=$e(typeof e.initialValue=="boolean"?e.initialValue:!0);return Ge((s,o)=>{o.escape?a():o.leftArrow||o.rightArrow?r(u=>!u):s==="y"||s==="Y"?r(!0):s==="n"||s==="N"?r(!1):o.return&&t(n)}),K(de,{flexDirection:"column",children:[K(V,{children:[me(V,{color:"cyan",children:"?"})," ",e.message]}),K(de,{marginTop:0,children:[K(V,{color:n?"cyan":void 0,bold:n,children:[n?"\u25CF ":"\u25CB ","Yes"]}),me(V,{children:" "}),K(V,{color:n?void 0:"cyan",bold:!n,children:[n?"\u25CB ":"\u25CF ","No"]})]})]})}import{Box as ge,Text as fe}from"ink";import{jsx as Y,jsxs as ze}from"react/jsx-runtime";function X({title:e,body:t}){let a=t.split(`
230
+ `);return ze(ge,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[Y(fe,{color:"cyan",bold:!0,children:e}),Y(ge,{flexDirection:"column",marginTop:0,children:a.map((n,r)=>Y(fe,{dimColor:!1,children:n.length===0?" ":n},r))})]})}import{jsx as m,jsxs as F}from"react/jsx-runtime";function Kt({defaults:e,onComplete:t,onlySection:a,banner:n}){let{exit:r}=Ye(),s=Z({...e}),o=Z(new Map),[,u]=T(0),i=()=>u(h=>h+1),[c,l]=T(null),[d,b]=T(null),[P,H]=T([]),[O,C]=T(null),[Q,ye]=T(!1),[D,be]=T({current:0,total:0}),M=()=>{let h=o.current;for(let y of A){let $=y.isApplicable(s.current),p=h.get(y.id);$?a&&y.id!==a?p!=="current"&&h.set(y.id,"done"):(p==="skipped"||!p)&&h.set(y.id,"pending"):h.set(y.id,"skipped")}};o.current.size===0&&M();let U=Z(!1);je(()=>{if(f("WizardApp:useEffect fired",{startedAlready:U.current}),U.current){f("WizardApp:useEffect returning early (startedRef true)");return}U.current=!0,f("WizardApp:orchestrator starting");let h=0,y=p=>{let v=++h;return f("orchestrator:promptFn called",{id:v,type:p.type,message:p.message.slice(0,60)}),C(null),new Promise((w,g)=>{b({id:v,spec:p,resolve:x=>{f("orchestrator:prompt resolved",{id:v,type:p.type,value:typeof x=="string"?x.slice(0,30):x}),w(x)},reject:x=>{f("orchestrator:prompt rejected",{id:v,reason:x.message}),g(x)}})})},$=p=>{H(v=>[...v,p])};return(async()=>{try{let p=a?A.filter(g=>g.id===a):A,v=()=>p.filter(g=>g.isApplicable(s.current)).length,w=0;for(;w<p.length;){let g=p[w];if(!g.isApplicable(s.current)){o.current.set(g.id,"skipped"),w++,M(),i();continue}H([]);for(let S of A)S.id===g.id?o.current.set(S.id,"current"):o.current.get(S.id)==="current"&&o.current.set(S.id,"pending");l(g.id);let x=p.slice(0,w+1).filter(S=>S.isApplicable(s.current)).length;be({current:x,total:v()}),i();try{let S=await g.execute(s.current,{prompt:y,info:$});s.current={...s.current,...S},o.current.set(g.id,"done"),M(),w++}catch(S){if(S instanceof N){if(a&&g.clearOnSkip){for(let Se of g.clearOnSkip)s.current[Se]=void 0;o.current.set(g.id,"skipped"),M(),w++;continue}if(a)continue;o.current.set(g.id,"pending");let R=w-1;for(;R>=0&&!p[R].isApplicable(s.current);)R--;R<0||(w=R,o.current.set(p[w].id,"pending")),M(),i();continue}throw S}}f("orchestrator:all sections done, calling onComplete + exit"),ye(!0),b(null),l(null),i(),await new Promise(g=>setTimeout(g,200)),t(s.current),r()}catch(p){f("orchestrator:caught error",{name:p?.name,message:p?.message}),p instanceof L&&(r(),process.exit(0));let v=p instanceof Error?p.message:String(p);C(`Setup error: ${v}`),i()}})(),()=>{f("WizardApp:useEffect cleanup ran (component unmounting)")}},[r,t]),Xe((h,y)=>{f("WizardApp:useInput fired",{input:h,ctrl:y.ctrl,escape:y.escape,return:y.return}),y.ctrl&&h==="c"&&(f("WizardApp:Ctrl+C \u2192 exiting"),r(),process.exit(0))});let we=qe(()=>A.map(h=>({id:h.id,title:h.title,status:o.current.get(h.id)??"pending"})),[c,Q,O]);return F(k,{flexDirection:"column",paddingY:1,children:[F(k,{marginBottom:1,children:[m(I,{bold:!0,color:"cyan",children:"Klaudius setup"}),m(I,{dimColor:!0,children:" \xB7 "}),m(I,{dimColor:!0,children:D.total>0?`Step ${D.current} of ${D.total}`:"Loading\u2026"})]}),F(k,{children:[m(re,{items:we}),F(k,{flexDirection:"column",flexGrow:1,marginLeft:2,children:[n&&F(k,{marginBottom:1,borderStyle:"round",borderColor:"red",paddingX:1,flexDirection:"column",children:[m(I,{color:"red",bold:!0,children:"\u26A0 Heads up"}),m(I,{children:n})]}),P.map((h,y)=>m(k,{marginBottom:1,children:m(X,{title:h.title,body:h.body})},y)),d?.spec.note&&m(k,{marginBottom:1,children:m(X,{title:d.spec.note.title,body:d.spec.note.body})}),d&&Qe(d),O&&m(k,{marginTop:1,children:m(I,{color:"red",children:O})}),Q&&m(k,{marginTop:1,children:m(I,{color:"green",bold:!0,children:"\u2713 Setup complete. Continuing\u2026"})})]})]}),m(k,{marginTop:1,children:m(I,{dimColor:!0,children:Ze(a,c)})})]})}function Ze(e,t){if(e){let a=A.find(n=>n.id===t);return a?.clearOnSkip&&a.clearOnSkip.length>0?"\u21B5 confirm esc skip this section ctrl-c cancel":"\u21B5 confirm ctrl-c cancel"}return"\u21B5 confirm esc back to previous section ctrl-c cancel"}function Qe(e){let t=n=>e.resolve(n),a=()=>e.reject(new N);switch(e.spec.type){case"text":case"password":return m(le,{spec:e.spec,masked:e.spec.type==="password",onSubmit:t,onBack:a},e.id);case"select":return m(pe,{spec:e.spec,onSubmit:t,onBack:a},e.id);case"confirm":return m(he,{spec:e.spec,onSubmit:t,onBack:a},e.id)}}export{Kt as WizardApp};
package/dist/bin.js CHANGED
@@ -1,59 +1,65 @@
1
1
  #!/usr/bin/env node
2
- import{a as U,b as me,c as fe,d as R,f as he,g as ge}from"./chunk-SZ4KCTSL.js";import{a as W,e as ke}from"./chunk-47ODNABO.js";import{Command as ms}from"commander";import{mkdir as Be,readdir as jt,readFile as je,stat as He,writeFile as Ve}from"fs/promises";import{resolve as Ht,isAbsolute as Vt,join as G}from"path";import*as g from"@clack/prompts";import d from"picocolors";import st from"react";import{render as nt}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-B6HU5YMU.js"),n=null;U("runWizard:start",{onlySection:s.onlySection,hasDefaults:Object.keys(e).length>0}),fe(),await new Promise(o=>setImmediate(o)),await new Promise(o=>setTimeout(o,0)),U("runWizard:event loop drained, mounting Ink");let r=nt(st.createElement(t,{defaults:e,onlySection:s.onlySection,banner:s.banner,onComplete:o=>{U("runWizard:onComplete called",{keys:Object.keys(o).length}),n=o}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(U("runWizard:render returned, awaiting exit"),await r.waitUntilExit(),U("runWizard:waitUntilExit resolved",{resultIsNull:n===null}),!n)throw new Error(`Wizard exited without completing. Diagnostic log: ${me}
3
- Please share that file so we can trace what happened.`);return n}function z(e){let s=[],t=r=>{s.push(""),s.push("# "+"=".repeat(60)),s.push(`# ${r}`),s.push("# "+"=".repeat(60)),s.push("")},n=(r,o)=>{if(o==null||o===""){s.push(`# ${r}=`);return}let l=String(o);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(l)){let c=l.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");s.push(`${r}="${c}"`)}else s.push(`${r}=${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("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),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("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 j,b as ge,c as ke,d as C,f as we,g as ye}from"./chunk-SZ4KCTSL.js";import{a as q,e as Ee}from"./chunk-47ODNABO.js";import{Command as bs}from"commander";import{mkdir as We,readdir as Ft,readFile as Be,stat as Fe,writeFile as Ge}from"fs/promises";import{spawnSync as Gt}from"child_process";import{resolve as Wt,isAbsolute as Yt,join as Y}from"path";import*as g from"@clack/prompts";import d from"picocolors";import at from"react";import{render as rt}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-HGVYB3EE.js"),n=null;j("runWizard:start",{onlySection:s.onlySection,hasDefaults:Object.keys(e).length>0}),ke(),await new Promise(o=>setImmediate(o)),await new Promise(o=>setTimeout(o,0)),j("runWizard:event loop drained, mounting Ink");let a=rt(at.createElement(t,{defaults:e,onlySection:s.onlySection,banner:s.banner,onComplete:o=>{j("runWizard:onComplete called",{keys:Object.keys(o).length}),n=o}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(j("runWizard:render returned, awaiting exit"),await a.waitUntilExit(),j("runWizard:waitUntilExit resolved",{resultIsNull:n===null}),!n)throw new Error(`Wizard exited without completing. Diagnostic log: ${ge}
3
+ Please share that file so we can trace what happened.`);return n}function J(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 c=String(o);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(c)){let l=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");s.push(`${a}="${l}"`)}else s.push(`${a}=${c}`)};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("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(`
4
4
  `)+`
5
- `}function q(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
- `}function it(e,s){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(s)){let t=s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${t}"`}return`${e}=${s}`}function we(e,s,t){let n=t.filter(l=>!(l.key in s));if(n.length===0)return null;let r=e.endsWith(`
5
+ `}function X(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
+ `}function lt(e,s){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(s)){let t=s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${t}"`}return`${e}=${s}`}function Pe(e,s,t){let n=t.filter(c=>!(c.key in s));if(n.length===0)return null;let a=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(it(l.key,l.value));return e+r+o.join(`
8
+ `,o=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let c of n)o.push(""),c.comment&&o.push(`# ${c.comment}`),o.push(lt(c.key,c.value));return e+a+o.join(`
9
9
  `)+`
10
- `}function ot(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 O(e){let s={};for(let t of e.split(`
11
- `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(r===-1)continue;let o=n.slice(0,r).trim(),l=ot(n.slice(r+1).trim());s[o]=l}return s}function ye(e){let s=o=>{let l=e[o];if(!l)return;let c=parseInt(l,10);return isNaN(c)?void 0:c},t=e.SMS_PROVIDER,n=e.OUTREACH_CHANNELS?.split(",").map(o=>o.trim()).filter(o=>o==="email"||o==="sms"),r=e.OUTREACH_PRIORITY;return{licenseKey:e.KLAUDIUS_LICENSE_KEY,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:n&&n.length>0?n:void 0,outreachPriority:r==="email"||r==="sms"?r: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 ae(e){let s=P=>{let w=e[P];if(!w)return;let _=parseInt(w,10);return isNaN(_)?void 0:_},t=e.SUPABASE_URL,n=e.SUPABASE_SERVICE_KEY,r=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||!r||!o||!m)return null;let a=e.SMS_PROVIDER,k=e.OUTREACH_CHANNELS?.split(",").map(P=>P.trim()).filter(P=>P==="email"||P==="sms"),E=e.OUTREACH_PRIORITY;return{licenseKey:e.KLAUDIUS_LICENSE_KEY,pricing:l,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:k&&k.length>0?k:void 0,outreachPriority:E==="email"||E==="sms"?E: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:a==="imessage"||a==="twilio"?a: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: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 rt,rm as at}from"fs/promises";import{Readable as lt}from"stream";import*as Ee from"tar";var ct="https://klaudius.dev/api/template";function dt(e){return lt.fromWeb(e)}async function J(e){let s=process.env.KLAUDIUS_TEMPLATE_URL??ct,t="0.9.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: ${R(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 r=n.headers.get("x-klaudius-tier");await rt(e.destDir,{recursive:!0});let o=0;try{await new Promise((l,c)=>{let m=Ee.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{o++}});m.on("finish",l),m.on("error",c),dt(n.body).on("error",c).pipe(m)})}catch(l){throw await at(e.destDir,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Failed to extract template archive: ${l.message}`)}return{filesExtracted:o,tier:r}}import{mkdir as ut,readFile as pt,writeFile as mt,access as ft}from"fs/promises";import{dirname as ht,join as Pe}from"path";var gt=".klaudius",be=`${gt}/manifest.json`;async function Se(e){let s=Pe(e,be);try{await ft(s)}catch{return null}let t=await pt(s,"utf-8");return JSON.parse(t)}async function X(e,s){let t=Pe(e,be);await ut(ht(t),{recursive:!0}),await mt(t,JSON.stringify(s,null,2)+`
12
- `,"utf-8")}function _e(e,s){let t=new Date().toISOString();return{version:1,templateVersion:e,installedAt:t,updatedAt:t,files:s}}import{createHash as kt}from"crypto";import{hostname as Te,userInfo as wt,platform as Ae,arch as Ie}from"os";import x from"picocolors";var i={info:e=>console.log(x.cyan("\u2139"),e),success:e=>console.log(x.green("\u2713"),e),warn:e=>console.log(x.yellow("\u26A0"),e),error:e=>console.error(x.red("\u2717"),e),step:e=>console.log(x.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
13
- `+x.bold(x.cyan(e))),detail:e=>console.log(x.dim(" "+e))};var yt="https://klaudius.dev",Et="/api/licenses/validate",Pt="0.9.0";async function Re(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??yt).replace(/\/$/,"")+Et,r=F(),o;try{o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:s,machine_id:r,hostname:Te(),os:`${Ae()}-${Ie()}`,cli_version:Pt})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${R(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 F(){let e=[Te(),wt().username,Ae(),Ie()].join("|");return kt("sha256").update(e).digest("hex").slice(0,32)}import{readFile as bt}from"fs/promises";import{join as St}from"path";async function D(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: ${R(s)}`}}}async function ve(e){let s;try{s=await bt(St(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 Q(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: ${R(s)}`}}}async function Z(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??"",r=t.error?.status??"";return s.status===400&&(r==="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: ${R(s)}`}}}import _t from"nodemailer";import{ImapFlow as Tt}from"imapflow";async function Oe(e){let s=_t.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:Ce(n,"SMTP")}}finally{s.close()}let t=new Tt({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:Ce(n,"IMAP")}}return{ok:!0}}function Ce(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 ct(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 O(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(),c=ct(n.slice(a+1).trim());s[o]=c}return s}function be(e){let s=l=>{let m=e[l];if(!m)return;let r=parseInt(m,10);return isNaN(r)?void 0:r},t=e.SMS_PROVIDER,n=l=>l==="email"||l==="sms"||l==="whatsapp",a=e.OUTREACH_CHANNELS?.split(",").map(l=>l.trim()).filter(n),o=e.OUTREACH_PRIORITY?.split(",").map(l=>l.trim()).filter(n),c=e.WHATSAPP_ACCOUNTS?.split(",").map(l=>l.trim()).filter(l=>l.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,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:c&&c.length>0?c: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 ce(e){let s=y=>{let _=e[y];if(!_)return;let h=parseInt(_,10);return isNaN(h)?void 0:h},t=e.SUPABASE_URL,n=e.SUPABASE_SERVICE_KEY,a=e.SUPABASE_PAT,o=e.SUPABASE_PROJECT_REF,c=e.PRICING,l=e.PRICING_TERMS||"one-off, no monthly fees",m=e.VERCEL_TOKEN;if(!c||!t||!n||!a||!o||!m)return null;let r=e.SMS_PROVIDER,k=y=>y==="email"||y==="sms"||y==="whatsapp",P=e.OUTREACH_CHANNELS?.split(",").map(y=>y.trim()).filter(k),v=e.OUTREACH_PRIORITY?.split(",").map(y=>y.trim()).filter(k),w=e.WHATSAPP_ACCOUNTS?.split(",").map(y=>y.trim()).filter(y=>y.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,pricing:c,pricingTerms:l,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:v&&v.length>0?v: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 dt,rm as ut}from"fs/promises";import{Readable as pt}from"stream";import*as Se from"tar";var mt="https://klaudius.dev/api/template";function ht(e){return pt.fromWeb(e)}async function Q(e){let s=process.env.KLAUDIUS_TEMPLATE_URL??mt,t="0.10.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(c){throw new Error(`Could not reach klaudius.dev to download the template: ${C(c)}`)}if(!n.ok){let c="";try{let l=await n.json();c=l.reason?` (${l.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${n.status}${c}`)}if(!n.body)throw new Error("Template download succeeded but response had no body");let a=n.headers.get("x-klaudius-tier");await dt(e.destDir,{recursive:!0});let o=0;try{await new Promise((c,l)=>{let m=Se.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{o++}});m.on("finish",c),m.on("error",l),ht(n.body).on("error",l).pipe(m)})}catch(c){throw await ut(e.destDir,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Failed to extract template archive: ${c.message}`)}return{filesExtracted:o,tier:a}}import{mkdir as ft,readFile as gt,writeFile as kt,access as wt}from"fs/promises";import{dirname as yt,join as Ae}from"path";var Et=".klaudius",_e=`${Et}/manifest.json`;async function Te(e){let s=Ae(e,_e);try{await wt(s)}catch{return null}let t=await gt(s,"utf-8");return JSON.parse(t)}async function Z(e,s){let t=Ae(e,_e);await ft(yt(t),{recursive:!0}),await kt(t,JSON.stringify(s,null,2)+`
12
+ `,"utf-8")}function Ie(e,s){let t=new Date().toISOString();return{version:1,templateVersion:e,installedAt:t,updatedAt:t,files:s}}import{createHash as Pt}from"crypto";import{hostname as Re,userInfo as bt,platform as ve,arch as Ce}from"os";import M from"picocolors";var i={info:e=>console.log(M.cyan("\u2139"),e),success:e=>console.log(M.green("\u2713"),e),warn:e=>console.log(M.yellow("\u26A0"),e),error:e=>console.error(M.red("\u2717"),e),step:e=>console.log(M.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
13
+ `+M.bold(M.cyan(e))),detail:e=>console.log(M.dim(" "+e))};var St="https://klaudius.dev",At="/api/licenses/validate",_t="0.10.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??St).replace(/\/$/,"")+At,a=W(),o;try{o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:s,machine_id:a,hostname:Re(),os:`${ve()}-${Ce()}`,cli_version:_t})})}catch(l){return{ok:!1,reason:`Could not reach the Klaudius license server (${C(l)}). Check your internet connection or try again later.`}}let c;try{c=await o.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${o.status}).`}}return c.ok?{ok:!0,tier:c.tier??"core"}:{ok:!1,reason:c.reason??`License rejected (HTTP ${o.status}).`}}function W(){let e=[Re(),bt().username,ve(),Ce()].join("|");return Pt("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Tt}from"fs/promises";import{join as It}from"path";async function K(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 Oe(e){let s;try{s=await Tt(It(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 ee(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 te(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 Rt from"nodemailer";import{ImapFlow as vt}from"imapflow";async function xe(e){let s=Rt.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:Ne(n,"SMTP")}}finally{s.close()}let t=new vt({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:Ne(n,"IMAP")}}return{ok:!0}}function Ne(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:
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 $e(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 r=await n.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(n){return{ok:!1,message:`Could not reach Twilio: ${R(n)}`}}}import{spawn as At}from"child_process";async function Ne(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 It(t);if(n.code===0)return{ok:!0};let r=n.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: ${n.stderr.trim()||`exit code ${n.code}`}`}}function It(e){return new Promise(s=>{let t=At("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),n="";t.stderr.on("data",r=>{n+=r.toString()}),t.on("close",r=>s({code:r??1,stderr:n})),t.on("error",r=>s({code:1,stderr:r.message}))})}import{spawn as xe}from"child_process";function Rt(){let e=process.env.NODE_OPTIONS?.trim(),s=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:s}}var K=2,Me=2e3,vt=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Le(e,s){let t=e+`
17
- `+s;return vt.some(n=>n.test(t))}function Ue(e){return new Promise(s=>setTimeout(s,e))}function Ct(e,s,t){return new Promise(n=>{let r=xe(e,s,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:t.env??process.env}),o="",l="";r.stdout?.on("data",c=>{let m=c.toString();o+=m,process.stdout.write(m)}),r.stderr?.on("data",c=>{let m=c.toString();l+=m,process.stderr.write(m)}),r.on("close",c=>n({code:c??1,stdout:o,stderr:l})),r.on("error",c=>n({code:1,stdout:o,stderr:l+c.message}))})}async function le(e,s,t){let n={code:0,stdout:"",stderr:""};for(let r=0;r<=K;r++){if(n=await Ct(e,s,{cwd:t.cwd,env:t.env}),n.code===0||!Le(n.stderr,n.stdout))return n;r<K&&(i.detail(`${t.label} failed with a transient network error \u2014 retrying (${r+2}/${K+1})\u2026`),await Ue(Me))}return n}function Ot(e,s,t){return new Promise(n=>{let r=xe(e,s,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),o="",l="";r.stdout?.on("data",c=>{o+=c.toString()}),r.stderr?.on("data",c=>{l+=c.toString()}),r.on("close",c=>n({code:c??1,stdout:o,stderr:l})),r.on("error",c=>n({code:1,stdout:o,stderr:l+c.message}))})}var $t=[{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 Nt(e){let s=`${e.stderr??""}
18
- ${e.stdout??""}`;return $t.find(n=>n.pattern.test(s))?.hint}async function xt(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<=K;c++){if(l=await Ot("pip3",o,{cwd:e}),l.code===0||!Le(l.stderr,l.stdout))return l;c<K&&(i.detail(`pip install hit a transient network error \u2014 retrying (${c+2}/${K+1})\u2026`),await Ue(Me))}return l},r=await n([...t,"--break-system-packages",...s]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),r=await n([...t,...s])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function De(e){let s={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},t=Rt(),n=(m,a)=>{let k=Nt(a);k&&((s.hints??={})[m]=k)};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let r=await le("npm",["install"],{cwd:e,label:"npm install",env:t});s.npm=r.code===0?"ok":"failed",r.code!==0&&n("npm",r),i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let o=await xt(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 le("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 le("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 Mt}from"child_process";var ee=3,ce=10;async function te(){let e=await Lt("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),r=parseInt(t[2],10),o=t[3]?`${n}.${r}.${t[3]}`:`${n}.${r}`;return n<ee||n===ee&&r<ce?{ok:!1,version:o,major:n,minor:r,message:`Your installed Python is ${o}. Klaudius needs Python ${ee}.${ce} or newer (the pipeline depends on packages that only ship wheels for ${ee}.${ce}+). 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:r}}function Lt(e,s){return new Promise(t=>{let n=Mt(e,s,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",o="";n.stdout?.on("data",l=>{r+=l.toString()}),n.stderr?.on("data",l=>{o+=l.toString()}),n.on("close",l=>t({code:l??1,stdout:r,stderr:o})),n.on("error",()=>t({code:1,stdout:r,stderr:o}))})}function se(){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),r=parseInt(s[3],10),o=`${t}.${n}.${r}`;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 Ut,readFile as Dt,writeFile as Kt}from"fs/promises";import{join as Ke}from"path";async function ne(e,s){let t=Ke(e,".claude");await Ut(t,{recursive:!0});let n=Ke(t,"settings.json"),r={};try{let m=await Dt(n,"utf-8"),a=JSON.parse(m);a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{}let o=r.enabledMcpjsonServers,l=Array.isArray(o)?o.filter(m=>typeof m=="string"):[];l.includes(s)||l.push(s);let c={...r,enabledMcpjsonServers:l};await Kt(n,JSON.stringify(c,null,2)+`
19
- `,"utf-8")}var Bt="0.9.0",A=5;function j(e,s){i.blank(),i.error(`${e} validation failed ${A} 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 Fe(e){let s=e.target??".",t=Vt(s)?s:Ht(process.cwd(),s),n=await Ft(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 r=await Yt(e.license),o=g.spinner();o.start("Validating license");let l=await Re(r);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 te();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=se();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 a,k=!1;if(n.kind==="partial")if(await Gt(t)==="resume"){let h=await je(n.envPath,"utf-8"),p=ae(O(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.)"),a=p,k=!0):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),a=await T())}else{let h=await je(n.envPath,"utf-8"),p=ae(O(h));a=await T(p??{})}else a=await T();a.licenseKey=r,await $(t,a),k||(i.success("Saved .env"),i.success("Saved .mcp.json")),i.blank();for(let u=1;;u++){let h=g.spinner();h.start("Validating Supabase credentials");let p=await D({url:a.supabaseUrl,serviceKey:a.supabaseServiceKey});if(p.ok){h.stop("Supabase credentials accepted");break}h.stop(p.message??"Supabase check failed",2),u>=A&&j("Supabase",p.message??"Supabase check failed");let y=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 ${A})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await T(a,{onlySection:"supabase",banner:`Supabase rejected your credentials:
20
- ${y}
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 Me(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 Ct}from"child_process";async function Le(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 $t(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 $t(e){return new Promise(s=>{let t=Ct("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 Ue}from"child_process";function Ot(){let e=process.env.NODE_OPTIONS?.trim(),s=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:s}}var H=2,De=2e3,Nt=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function je(e,s){let t=e+`
17
+ `+s;return Nt.some(n=>n.test(t))}function Ke(e){return new Promise(s=>setTimeout(s,e))}function xt(e,s,t){return new Promise(n=>{let a=Ue(e,s,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:t.env??process.env}),o="",c="";a.stdout?.on("data",l=>{let m=l.toString();o+=m,process.stdout.write(m)}),a.stderr?.on("data",l=>{let m=l.toString();c+=m,process.stderr.write(m)}),a.on("close",l=>n({code:l??1,stdout:o,stderr:c})),a.on("error",l=>n({code:1,stdout:o,stderr:c+l.message}))})}async function de(e,s,t){let n={code:0,stdout:"",stderr:""};for(let a=0;a<=H;a++){if(n=await xt(e,s,{cwd:t.cwd,env:t.env}),n.code===0||!je(n.stderr,n.stdout))return n;a<H&&(i.detail(`${t.label} failed with a transient network error \u2014 retrying (${a+2}/${H+1})\u2026`),await Ke(De))}return n}function Mt(e,s,t){return new Promise(n=>{let a=Ue(e,s,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),o="",c="";a.stdout?.on("data",l=>{o+=l.toString()}),a.stderr?.on("data",l=>{c+=l.toString()}),a.on("close",l=>n({code:l??1,stdout:o,stderr:c})),a.on("error",l=>n({code:1,stdout:o,stderr:c+l.message}))})}var Lt=[{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 Ut(e){let s=`${e.stderr??""}
18
+ ${e.stdout??""}`;return Lt.find(n=>n.pattern.test(s))?.hint}async function Dt(e){let s=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],t=["install","--quiet","--user"],n=async o=>{let c={code:0,stdout:"",stderr:""};for(let l=0;l<=H;l++){if(c=await Mt("pip3",o,{cwd:e}),c.code===0||!je(c.stderr,c.stdout))return c;l<H&&(i.detail(`pip install hit a transient network error \u2014 retrying (${l+2}/${H+1})\u2026`),await Ke(De))}return c},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 He(e){let s={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},t=Ot(),n=(m,r)=>{let k=Ut(r);k&&((s.hints??={})[m]=k)};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await de("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 Dt(e);s.pip=o.code===0?"ok":"failed",o.code!==0&&n("pip",o),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await de("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:t});s.playwright=c.code===0?"ok":"failed",c.code!==0&&n("playwright",c),i.step("Installing Patchright browser (chromium ~200MB; one-time)...");let l=await de("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:t});return s.patchright=l.code===0?"ok":"failed",l.code!==0&&n("patchright",l),s}import{spawn as jt}from"child_process";var se=3,ue=10;async function ne(){let e=await Kt("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<se||n===se&&a<ue?{ok:!1,version:o,major:n,minor:a,message:`Your installed Python is ${o}. Klaudius needs Python ${se}.${ue} or newer (the pipeline depends on packages that only ship wheels for ${se}.${ue}+). 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 Kt(e,s){return new Promise(t=>{let n=jt(e,s,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",o="";n.stdout?.on("data",c=>{a+=c.toString()}),n.stderr?.on("data",c=>{o+=c.toString()}),n.on("close",c=>t({code:c??1,stdout:a,stderr:o})),n.on("error",()=>t({code:1,stdout:a,stderr:o}))})}function ie(){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 Ht,readFile as Vt,writeFile as Bt}from"fs/promises";import{join as Ve}from"path";async function oe(e,s){let t=Ve(e,".claude");await Ht(t,{recursive:!0});let n=Ve(t,"settings.json"),a={};try{let m=await Vt(n,"utf-8"),r=JSON.parse(m);r&&typeof r=="object"&&!Array.isArray(r)&&(a=r)}catch{}let o=a.enabledMcpjsonServers,c=Array.isArray(o)?o.filter(m=>typeof m=="string"):[];c.includes(s)||c.push(s);let l={...a,enabledMcpjsonServers:c};await Bt(n,JSON.stringify(l,null,2)+`
19
+ `,"utf-8")}var zt="0.10.0",I=5;function V(e,s){i.blank(),i.error(`${e} validation failed ${I} 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 Ye(e){let s=e.target??".",t=Yt(s)?s:Wt(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 Xt(e.license),o=g.spinner();o.start("Validating license");let c=await $e(a);c.ok||(o.stop(`License invalid: ${c.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 (${c.tier??"core"} tier)`);let l=await ne();l.ok||(i.error(l.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=ie();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,k=!1;if(n.kind==="partial")if(await Jt(t)==="resume"){let f=await Be(n.envPath,"utf-8"),p=ce(O(f));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,k=!0):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await T())}else{let f=await Be(n.envPath,"utf-8"),p=ce(O(f));r=await T(p??{})}else r=await T();r.licenseKey=a,await N(t,r),k||(i.success("Saved .env"),i.success("Saved .mcp.json")),i.blank();for(let u=1;;u++){let f=g.spinner();f.start("Validating Supabase credentials");let p=await K({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(p.ok){f.stop("Supabase credentials accepted");break}f.stop(p.message??"Supabase check failed",2),u>=I&&V("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 ${I})`),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}
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,a)}i.blank();for(let u=1;;u++){let h=g.spinner();h.start("Validating Vercel token");let p=await Q(a.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>=A&&j("Vercel",p.message??"Vercel check failed");let y=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 ${A})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await T(a,{onlySection:"vercel",banner:`Vercel rejected the token:
24
- ${y}
23
+ field to keep what's already there.`}),await N(t,r)}i.blank();for(let u=1;;u++){let f=g.spinner();f.start("Validating Vercel token");let p=await ee(r.vercelToken);if(p.ok){f.stop(p.username?`Vercel token accepted (signed in as ${p.username})`:"Vercel token accepted");break}f.stop(p.message??"Vercel check failed",2),u>=I&&V("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 ${I})`),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}
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,a)}i.blank();for(let u=1;;u++){let h=g.spinner();h.start("Validating Google Places API key");let p=await Z(a.googlePlacesApiKey??"");if(p.ok){h.stop("Google Places API key accepted");break}h.stop(p.message??"Google Places check failed",2),u>=A&&j("Google Places",p.message??"Google Places check failed");let y=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 ${A})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await T(a,{onlySection:"google-places",banner:`Google rejected the key:
28
- ${y}
27
+ paste it below. Press Enter to keep the current value.`}),await N(t,r)}i.blank();for(let u=1;;u++){let f=g.spinner();f.start("Validating Google Places API key");let p=await te(r.googlePlacesApiKey??"");if(p.ok){f.stop("Google Places API key accepted");break}f.stop(p.message??"Google Places check failed",2),u>=I&&V("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 ${I})`),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}
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,a)}if(a.outreachEnabled&&a.outreachChannels?.includes("email")&&a.emailAddress&&a.emailPassword&&a.emailSmtpHost&&a.emailSmtpPort&&a.emailImapHost&&a.emailImapPort){i.blank();for(let u=1;;u++){let h=g.spinner();h.start("Validating email credentials (SMTP + IMAP)");let p=await Oe({emailAddress:a.emailAddress,emailPassword:a.emailPassword,emailSmtpHost:a.emailSmtpHost,emailSmtpPort:a.emailSmtpPort,emailImapHost:a.emailImapHost,emailImapPort:a.emailImapPort});if(p.ok){h.stop("Email credentials accepted (SMTP + IMAP)");break}h.stop(p.message??"Email check failed",2),u>=A&&j("Email",p.message??"Email check failed");let y=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 ${A})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await T(a,{onlySection:"email",banner:`${p.failedAt==="imap"?"IMAP":"SMTP"} check failed:
32
- ${y}
31
+ and paste it below. Press Enter to keep the current value.`}),await N(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 f=g.spinner();f.start("Validating email credentials (SMTP + IMAP)");let p=await xe({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort});if(p.ok){f.stop("Email credentials accepted (SMTP + IMAP)");break}f.stop(p.message??"Email check failed",2),u>=I&&V("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 ${I})`),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}
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,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="twilio"&&a.twilioAccountSid&&a.twilioAuthToken){i.blank();for(let u=1;;u++){let h=g.spinner();h.start("Validating Twilio credentials");let p=await $e({accountSid:a.twilioAccountSid,authToken:a.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>=A&&j("Twilio",p.message??"Twilio check failed");let y=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 ${A})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await T(a,{onlySection:"sms",banner:`Twilio rejected the credentials:
36
- ${y}
35
+ Press Enter on any field to keep its current value.`}),await N(t,r)}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="twilio"&&r.twilioAccountSid&&r.twilioAuthToken){i.blank();for(let u=1;;u++){let f=g.spinner();f.start("Validating Twilio credentials");let p=await Me({accountSid:r.twilioAccountSid,authToken:r.twilioAuthToken});if(p.ok){f.stop(p.friendlyName?`Twilio credentials accepted (${p.friendlyName})`:"Twilio credentials accepted");break}f.stop(p.message??"Twilio check failed",2),u>=I&&V("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 ${I})`),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}
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,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="imessage"&&a.testPhone){i.blank();for(let u=1;;u++){let h=g.spinner();h.start("Validating iMessage setup (sending a test ping)");let p=await Ne({testPhone:a.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>=A&&j("iMessage",p.message??"iMessage check failed");let y=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 ${A})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await T(a,{onlySection:"sms",banner:`iMessage check failed:
40
- ${y}
39
+ Press Enter on any field to keep its current value.`}),await N(t,r)}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="imessage"&&r.testPhone){i.blank();for(let u=1;;u++){let f=g.spinner();f.start("Validating iMessage setup (sending a test ping)");let p=await Le({testPhone:r.testPhone});if(p.ok){f.stop("iMessage dispatched (check your phone for the test ping)");break}f.stop(p.message??"iMessage check failed",2),u>=I&&V("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 ${I})`),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}
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,a)}}if(a.telegramBotToken&&a.telegramChatId){i.blank();let u=0,h=!1;for(;!h;){u++;let p=g.spinner();p.start("Validating Telegram bot + chat (sending a test ping)");let y=await ge({botToken:a.telegramBotToken,chatId:a.telegramChatId});if(y.ok){p.stop(y.botHandle?`Telegram bot ${y.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),h=!0;break}p.stop(y.message??"Telegram check failed",2);let tt=y.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 re=await g.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(g.isCancel(re)&&(g.cancel("Setup cancelled. Your .env is saved \u2014 re-run `klaudius init` to resume."),process.exit(0)),re==="skip"){a.telegramBotToken=void 0,a.telegramChatId=void 0,await $(t,a),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(re==="edit"&&(i.blank(),a=await T(a,{onlySection:"telegram",banner:`Telegram check failed:
45
- ${tt}
44
+ provider to Twilio.`}),await N(t,r)}}if(r.telegramBotToken&&r.telegramChatId){i.blank();let u=0,f=!1;for(;!f;){u++;let p=g.spinner();p.start("Validating Telegram bot + chat (sending a test ping)");let E=await ye({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"),f=!0;break}p.stop(E.message??"Telegram check failed",2);let ot=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 le=await g.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(g.isCancel(le)&&(g.cancel("Setup cancelled. Your .env is saved \u2014 re-run `klaudius init` to resume."),process.exit(0)),le==="skip"){r.telegramBotToken=void 0,r.telegramChatId=void 0,await N(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`."),f=!0;break}if(le==="edit"&&(i.blank(),r=await T(r,{onlySection:"telegram",banner:`Telegram check failed:
45
+ ${ot}
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,a),!a.telegramBotToken||!a.telegramChatId)){i.success("Skipped Telegram. Setup will continue."),h=!0;break}}}i.blank();let E=g.spinner();E.start("Downloading Klaudius template");let P;try{P=(await J({licenseKey:r,machineId:F(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,destDir:t})).filesExtracted,E.stop(`Downloaded ${P} files into ${d.bold(t)}`)}catch(u){E.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 Be(G(t,"clients"),{recursive:!0});let w=await ke(t);await X(t,_e(Bt,w)),i.success("Wrote .klaudius/manifest.json");let _=!1,v="";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: ${a.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+a.supabaseProjectRef+"/sql/new").replace(a.supabaseProjectRef+".supabase.co","")}`);else{i.blank();let u=g.spinner();u.start("Applying schema to Supabase");let h=await ve({projectRoot:t,pat:a.supabasePat,projectRef:a.supabaseProjectRef});h.ok?u.stop("Schema applied (or already present)"):(u.stop(h.message??"Schema apply failed",2),_=!0,v=`https://supabase.com/dashboard/project/${a.supabaseProjectRef}/sql/new`)}let f=[],b={};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 De(t);i.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&f.push("npm"),u.pip==="failed"&&f.push("pip"),u.playwright==="failed"&&f.push("playwright"),u.patchright==="failed"&&f.push("patchright"),b=u.hints??{}}i.blank();let C=[...f,..._?["schema"]:[]];if(C.length>0){g.outro(d.yellow(d.bold(`Setup paused \u2014 ${C.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),i.blank();for(let[p,y]of Object.entries(b))console.log(d.yellow(`Likely cause of ${p} failure:`)),console.log(d.dim(` ${y}`)),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}`)}`),f.length>0&&console.log(` ${d.cyan("bash setup.sh")} ${d.dim("# retry the failing installers")}`),_&&(console.log(d.dim(" Apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(v)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run."))),i.blank(),f.includes("pip")&&!b.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=>f.includes(p)&&!b[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}g.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("# 30-second tour (open in any browser)")}`),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 Be(e,{recursive:!0}),await Ve(G(e,".env"),z(s),"utf-8"),await Ve(G(e,".mcp.json"),q(s),"utf-8"),await ne(e,"supabase")}async function Ft(e){try{(await He(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let s=await jt(e),t=s.filter(c=>!c.startsWith(".DS_Store"));if(t.length===0)return{kind:"fresh"};let n=new Set([".env",".mcp.json",".claude"]),r=t.every(c=>n.has(c)),o=t.includes(".env"),l=s.includes(".klaudius");if(r&&o&&!l)return{kind:"partial",envPath:G(e,".env")};if(l&&o){let c=!0;try{c=!(await He(G(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:t}}async function Gt(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 g.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 g.isCancel(s)&&(g.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),s}async function Yt(e){if(e&&e.trim().length>0)return e;g.intro("Klaudius");let s=await g.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 g.isCancel(s)&&(g.cancel("Setup cancelled. No files written."),process.exit(0)),s}import{readFile as Wt,writeFile as Ge,access as zt}from"fs/promises";import{join as ie}from"path";import*as oe from"@clack/prompts";import L from"picocolors";async function Ye(e){let s=e.projectRoot??process.cwd(),t=ie(s,".env"),n=ie(s,".mcp.json"),r=await de(ie(s,".klaudius","manifest.json")),o=await de(t);!r&&!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=se();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 k=await Wt(t,"utf-8");c=O(k)}catch{i.warn("No .env found. Starting from an empty configuration.")}let m=ye(c);oe.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let a=await T(m);if(a.supabaseUrl!==c.SUPABASE_URL||a.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let k=await D({url:a.supabaseUrl,serviceKey:a.supabaseServiceKey});k.ok||(i.error(k.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}await Ge(t,z(a),"utf-8"),i.success("Updated .env"),await Ge(n,q(a),"utf-8"),i.success("Updated .mcp.json"),await ne(s,"supabase"),i.blank(),oe.outro(L.green("Configuration updated.")),await qt(s,r)}async function qt(e,s){let t=await de(ie(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(` ${L.cyan("bash setup.sh")} ${L.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${L.cyan("npx klaudius doctor")} ${L.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(` ${L.cyan("npx klaudius init")} ${L.dim("# pick Resume when prompted")}`),i.blank())}async function de(e){try{return await zt(e),!0}catch{return!1}}import{copyFile as We,mkdir as ze,readdir as Jt,readFile as Xt,rm as Y,writeFile as qe,access as Je}from"fs/promises";import{dirname as Xe,join as I,relative as Qt}from"path";import{tmpdir as Zt}from"os";import*as H from"@clack/prompts";import ue from"picocolors";var pe="0.9.0";async function Qe(e){let s=e.projectRoot??process.cwd(),t=await Se(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,r=I(s,".env");try{let f=await Xt(r,"utf-8"),b=O(f);n=b.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=we(f,b,[{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)."}]);C!==null&&(await qe(r,C,"utf-8"),i.detail("Backfilled new env keys"))}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)}H.intro(`Update from ${t.templateVersion} \u2192 ${pe}`);let o=I(Zt(),`klaudius-update-${process.pid}-${Date.now()}`),l;try{i.heading("Downloading the latest Klaudius template");let f=await J({licenseKey:n,machineId:F(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,destDir:o});i.success(`Fetched ${f.filesExtracted} canonical files`),l=o}catch(f){i.error(f.message),i.detail("Update aborted. Your project is unchanged."),await Y(o,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let c=await es(l,s,t),m=c.filter(f=>f.state==="new"),a=c.filter(f=>f.state==="clean-update"),k=c.filter(f=>f.state==="user-only"),E=c.filter(f=>f.state==="conflict"),P=c.filter(f=>f.state==="no-change"),w=c.filter(f=>f.state==="removed-clean"),_=c.filter(f=>f.state==="removed-modified"),v=[...E,..._];if(i.blank(),i.heading("Change summary"),i.detail(`${N(P.length,"file")} unchanged`),i.detail(`${N(m.length,"new file")}`),i.detail(`${N(a.length,"file")} updated cleanly (no local edits)`),i.detail(`${N(k.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${N(w.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${N(E.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${N(_.length,"file")} removed upstream but edited locally (need your decision)`),m.length===0&&a.length===0&&w.length===0&&v.length===0){i.blank(),H.outro(ue.green("Already up to date.")),await Y(o,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let f of[...m,...a]){let b=I(l,f.path),C=I(s,f.path);await ze(Xe(C),{recursive:!0}),await We(b,C),t.files[f.path]=f.canonicalHash}m.length+a.length>0&&i.success(`Wrote ${N(m.length+a.length,"file")}`);for(let f of w){let b=I(s,f.path);await Y(b,{force:!0}),delete t.files[f.path]}if(w.length>0&&i.success(`Deleted ${N(w.length,"file")} removed upstream`),v.length>0){i.blank(),i.heading(`${v.length} conflict(s) need resolution`);let f=I(s,".klaudius","incoming");try{await Y(f,{recursive:!0,force:!0})}catch{}for(let b of E){let C=I(l,b.path),u=I(f,b.path);await ze(Xe(u),{recursive:!0}),await We(C,u)}await qe(I(s,".klaudius","conflicts.md"),ts(v,t.templateVersion,pe),"utf-8"),E.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=pe),await X(s,t),i.blank(),v.length===0?H.outro(ue.green("Update complete.")):H.outro(ue.yellow(`${v.length} conflict(s) staged. Open Claude Code in this project and ask:
49
- "Run /resolve-conflicts"`)),await Y(o,{recursive:!0,force:!0}).catch(()=>{})}async function es(e,s,t){let n=await Ze(e),r=new Set(n),o=[];for(let l of n){let c=await W(I(e,l)),m=t.files[l],a=I(s,l),k;try{await Je(a),k=await W(a)}catch{o.push({path:l,state:"new",canonicalHash:c,manifestHash:m});continue}c===m?k===m?o.push({path:l,state:"no-change",canonicalHash:c,localHash:k,manifestHash:m}):o.push({path:l,state:"user-only",canonicalHash:c,localHash:k,manifestHash:m}):k===m?o.push({path:l,state:"clean-update",canonicalHash:c,localHash:k,manifestHash:m}):o.push({path:l,state:"conflict",canonicalHash:c,localHash:k,manifestHash:m})}for(let l of Object.keys(t.files)){if(r.has(l))continue;let c=t.files[l],m=I(s,l),a;try{await Je(m),a=await W(m)}catch{delete t.files[l];continue}a===c?o.push({path:l,state:"removed-clean",localHash:a,manifestHash:c}):o.push({path:l,state:"removed-modified",localHash:a,manifestHash:c})}return o}function N(e,s){return`${e} ${s}${e===1?"":"s"}`}async function Ze(e,s=e){let t=await Jt(e,{withFileTypes:!0}),n=[];for(let r of t){let o=I(e,r.name);r.isDirectory()?n.push(...await Ze(o,s)):r.isFile()&&n.push(Qt(s,o))}return n}function ts(e,s,t){let n=e.filter(c=>c.state==="conflict").length,r=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`),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 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(`
50
- `)}import{access as ss,readFile as ns,stat as is}from"fs/promises";import{join as M}from"path";import S from"picocolors";import{spawn as os}from"child_process";async function et(e){let s=e.projectRoot??process.cwd(),t=[];console.log(S.bold(`Klaudius doctor \u2014 checking your project\u2026
51
- `)),t.push(await rs()),t.push(await as());let n=M(s,".env"),r=M(s,".klaudius","manifest.json"),o=M(s,".mcp.json"),l=M(s,"setup.sh"),c=await V(n),m=await V(r),a=await V(o),k=await V(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?r:"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:a?"ok":"warn",detail:a?o:"missing",nextAction:a?void 0:"Run `klaudius configure` to regenerate."}),t.push({name:"setup.sh present",status:k?"ok":"warn",detail:k?l:"missing \u2014 re-run init"}),t.push(await ls(s)),t.push(await cs(s)),t.push(await ds()),!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 ns(n,"utf-8"),_=O(w);await us(_,t)}console.log();for(let w of t){let _=w.status==="ok"?S.green("\u2713"):w.status==="warn"?S.yellow("\u26A0"):w.status==="skip"?S.dim("\xB7"):S.red("\u2717");console.log(` ${_} ${w.name}${w.detail?S.dim(` \u2014 ${w.detail}`):""}`),w.nextAction&&console.log(` ${S.dim("\u2192")} ${S.cyan(w.nextAction)}`)}let E=t.filter(w=>w.status==="fail").length,P=t.filter(w=>w.status==="warn").length;console.log(),E===0&&P===0?console.log(S.green(S.bold("Everything checks out. You're good to go."))):E===0?console.log(S.yellow(S.bold(`${P} warning${P===1?"":"s"} \u2014 review above.`))):(console.log(S.red(S.bold(`${E} failed check${E===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function V(e){try{return await ss(e),!0}catch{return!1}}async function rs(){let e=await te();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 as(){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 ls(e){let s=M(e,"node_modules");if(!await V(s))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `bash setup.sh` (or `npm install`) in this folder."};try{if(!(await is(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 cs(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 V(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 ds(){let e=["supabase","dotenv","requests","httpx","PIL"],s=`import sys
48
+ Press Enter on any field to keep its current value.`}),await N(t,r),!r.telegramBotToken||!r.telegramChatId)){i.success("Skipped Telegram. Setup will continue."),f=!0;break}}}i.blank();let P=g.spinner();P.start("Downloading Klaudius template");let v;try{v=(await Q({licenseKey:a,machineId:W(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,destDir:t})).filesExtracted,P.stop(`Downloaded ${v} 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 We(Y(t,"clients"),{recursive:!0});let w=await Ee(t);await Z(t,Ie(zt,w)),i.success("Wrote .klaudius/manifest.json");let y=!1,_="";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=g.spinner();u.start("Applying schema to Supabase");let f=await Oe({projectRoot:t,pat:r.supabasePat,projectRef:r.supabaseProjectRef});f.ok?u.stop("Schema applied (or already present)"):(u.stop(f.message??"Schema apply failed",2),y=!0,_=`https://supabase.com/dashboard/project/${r.supabaseProjectRef}/sql/new`)}let h=[],b={};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 He(t);i.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&h.push("npm"),u.pip==="failed"&&h.push("pip"),u.playwright==="failed"&&h.push("playwright"),u.patchright==="failed"&&h.push("patchright"),b=u.hints??{}}let $=r.outreachEnabled&&r.outreachPriority?.includes("whatsapp")&&(r.whatsappAccounts?.length??0)>0,G=!e.skipInstall&&!h.includes("npm");if($&&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
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 f=Gt(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:t,stdio:"inherit"});f.status===0?i.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${f.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))),i.blank()}}else if($&&!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 fe=[...h,...y?["schema"]:[]];if(fe.length>0){g.outro(d.yellow(d.bold(`Setup paused \u2014 ${fe.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),i.blank();for(let[p,E]of Object.entries(b))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}`)}`),h.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(_)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run."))),i.blank(),h.includes("pip")&&!b.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 f=["npm","playwright","patchright"].filter(p=>h.includes(p)&&!b[p]);if(f.length>0){let p=f.length===1?"keeps":"keep";console.log(d.dim(`If ${f.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}g.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 N(e,s){await We(e,{recursive:!0}),await Ge(Y(e,".env"),J(s),"utf-8"),await Ge(Y(e,".mcp.json"),X(s),"utf-8"),await oe(e,"supabase")}async function qt(e){try{(await Fe(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let s=await Ft(e),t=s.filter(l=>!l.startsWith(".DS_Store"));if(t.length===0)return{kind:"fresh"};let n=new Set([".env",".mcp.json",".claude"]),a=t.every(l=>n.has(l)),o=t.includes(".env"),c=s.includes(".klaudius");if(a&&o&&!c)return{kind:"partial",envPath:Y(e,".env")};if(c&&o){let l=!0;try{l=!(await Fe(Y(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:t}}async function Jt(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 g.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 g.isCancel(s)&&(g.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),s}async function Xt(e){if(e&&e.trim().length>0)return e;g.intro("Klaudius");let s=await g.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 g.isCancel(s)&&(g.cancel("Setup cancelled. No files written."),process.exit(0)),s}import{readFile as Qt,writeFile as ze,access as Zt}from"fs/promises";import{join as ae}from"path";import*as re from"@clack/prompts";import U from"picocolors";async function qe(e){let s=e.projectRoot??process.cwd(),t=ae(s,".env"),n=ae(s,".mcp.json"),a=await pe(ae(s,".klaudius","manifest.json")),o=await pe(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 c=ie();c.ok||(i.error(c.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 l={};try{let k=await Qt(t,"utf-8");l=O(k)}catch{i.warn("No .env found. Starting from an empty configuration.")}let m=be(l);re.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!==l.SUPABASE_URL||r.supabaseServiceKey!==l.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let k=await K({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});k.ok||(i.error(k.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}await ze(t,J(r),"utf-8"),i.success("Updated .env"),await ze(n,X(r),"utf-8"),i.success("Updated .mcp.json"),await oe(s,"supabase"),i.blank(),re.outro(U.green("Configuration updated.")),await es(s,a)}async function es(e,s){let t=await pe(ae(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(` ${U.cyan("bash setup.sh")} ${U.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${U.cyan("npx klaudius doctor")} ${U.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(` ${U.cyan("npx klaudius init")} ${U.dim("# pick Resume when prompted")}`),i.blank())}async function pe(e){try{return await Zt(e),!0}catch{return!1}}import{copyFile as Je,mkdir as Xe,readdir as ts,readFile as ss,rm as z,writeFile as Qe,access as Ze}from"fs/promises";import{dirname as et,join as R,relative as ns}from"path";import{tmpdir as is}from"os";import*as B from"@clack/prompts";import me from"picocolors";var he="0.10.0";async function tt(e){let s=e.projectRoot??process.cwd(),t=await Te(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=R(s,".env");try{let h=await ss(a,"utf-8"),b=O(h);n=b.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 $=Pe(h,b,[{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)."}]);$!==null&&(await Qe(a,$,"utf-8"),i.detail("Backfilled new env keys"))}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)}B.intro(`Update from ${t.templateVersion} \u2192 ${he}`);let o=R(is(),`klaudius-update-${process.pid}-${Date.now()}`),c;try{i.heading("Downloading the latest Klaudius template");let h=await Q({licenseKey:n,machineId:W(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,destDir:o});i.success(`Fetched ${h.filesExtracted} canonical files`),c=o}catch(h){i.error(h.message),i.detail("Update aborted. Your project is unchanged."),await z(o,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let l=await os(c,s,t),m=l.filter(h=>h.state==="new"),r=l.filter(h=>h.state==="clean-update"),k=l.filter(h=>h.state==="user-only"),P=l.filter(h=>h.state==="conflict"),v=l.filter(h=>h.state==="no-change"),w=l.filter(h=>h.state==="removed-clean"),y=l.filter(h=>h.state==="removed-modified"),_=[...P,...y];if(i.blank(),i.heading("Change summary"),i.detail(`${x(v.length,"file")} unchanged`),i.detail(`${x(m.length,"new file")}`),i.detail(`${x(r.length,"file")} updated cleanly (no local edits)`),i.detail(`${x(k.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${x(w.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${x(P.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${x(y.length,"file")} removed upstream but edited locally (need your decision)`),m.length===0&&r.length===0&&w.length===0&&_.length===0){i.blank(),B.outro(me.green("Already up to date.")),await z(o,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let h of[...m,...r]){let b=R(c,h.path),$=R(s,h.path);await Xe(et($),{recursive:!0}),await Je(b,$),t.files[h.path]=h.canonicalHash}m.length+r.length>0&&i.success(`Wrote ${x(m.length+r.length,"file")}`);for(let h of w){let b=R(s,h.path);await z(b,{force:!0}),delete t.files[h.path]}if(w.length>0&&i.success(`Deleted ${x(w.length,"file")} removed upstream`),_.length>0){i.blank(),i.heading(`${_.length} conflict(s) need resolution`);let h=R(s,".klaudius","incoming");try{await z(h,{recursive:!0,force:!0})}catch{}for(let b of P){let $=R(c,b.path),G=R(h,b.path);await Xe(et(G),{recursive:!0}),await Je($,G)}await Qe(R(s,".klaudius","conflicts.md"),as(_,t.templateVersion,he),"utf-8"),P.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}t.updatedAt=new Date().toISOString(),_.length===0&&(t.templateVersion=he),await Z(s,t),i.blank(),_.length===0?B.outro(me.green("Update complete.")):B.outro(me.yellow(`${_.length} conflict(s) staged. Open Claude Code in this project and ask:
51
+ "Run /resolve-conflicts"`)),await z(o,{recursive:!0,force:!0}).catch(()=>{})}async function os(e,s,t){let n=await st(e),a=new Set(n),o=[];for(let c of n){let l=await q(R(e,c)),m=t.files[c],r=R(s,c),k;try{await Ze(r),k=await q(r)}catch{o.push({path:c,state:"new",canonicalHash:l,manifestHash:m});continue}l===m?k===m?o.push({path:c,state:"no-change",canonicalHash:l,localHash:k,manifestHash:m}):o.push({path:c,state:"user-only",canonicalHash:l,localHash:k,manifestHash:m}):k===m?o.push({path:c,state:"clean-update",canonicalHash:l,localHash:k,manifestHash:m}):o.push({path:c,state:"conflict",canonicalHash:l,localHash:k,manifestHash:m})}for(let c of Object.keys(t.files)){if(a.has(c))continue;let l=t.files[c],m=R(s,c),r;try{await Ze(m),r=await q(m)}catch{delete t.files[c];continue}r===l?o.push({path:c,state:"removed-clean",localHash:r,manifestHash:l}):o.push({path:c,state:"removed-modified",localHash:r,manifestHash:l})}return o}function x(e,s){return`${e} ${s}${e===1?"":"s"}`}async function st(e,s=e){let t=await ts(e,{withFileTypes:!0}),n=[];for(let a of t){let o=R(e,a.name);a.isDirectory()?n.push(...await st(o,s)):a.isFile()&&n.push(ns(s,o))}return n}function as(e,s,t){let n=e.filter(l=>l.state==="conflict").length,a=e.filter(l=>l.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 c=[];n>0&&c.push(`${n} file${n===1?"":"s"} ha${n===1?"s":"ve"} BOTH local edits AND upstream changes`),a>0&&c.push(`${a} file${a===1?"":"s"} ${a===1?"was":"were"} removed upstream but edited locally`),o.push(c.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 l of e)o.push(`## ${l.path}`),o.push(""),l.state==="removed-modified"?(o.push("**Type:** Removed upstream"),o.push(""),o.push(`- Your local copy: \`${l.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: \`${(l.manifestHash??"(none)").slice(0,16)}\``),o.push(`- Your local hash now: \`${(l.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): \`${l.path}\``),o.push(`- New canonical version: \`.klaudius/incoming/${l.path}\``),o.push(`- Hash at last install/update: \`${(l.manifestHash??"(none)").slice(0,16)}\``),o.push(`- Your local hash now: \`${(l.localHash??"(missing)").slice(0,16)}\``),o.push(`- New canonical hash: \`${(l.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 rs,readFile as ls,stat as cs}from"fs/promises";import{join as L}from"path";import S from"picocolors";import{spawn as ds}from"child_process";async function nt(e){let s=e.projectRoot??process.cwd(),t=[];console.log(S.bold(`Klaudius doctor \u2014 checking your project\u2026
53
+ `)),t.push(await us()),t.push(await ps());let n=L(s,".env"),a=L(s,".klaudius","manifest.json"),o=L(s,".mcp.json"),c=L(s,"setup.sh"),l=await F(n),m=await F(a),r=await F(o),k=await F(c);if(t.push({name:".env present",status:l?"ok":"fail",detail:l?n:"missing",nextAction:l?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:l?"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:k?"ok":"warn",detail:k?c:"missing \u2014 re-run init"}),t.push(await ms(s)),t.push(await hs(s)),t.push(await fs()),!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 ls(n,"utf-8"),y=O(w);await gs(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,v=t.filter(w=>w.status==="warn").length;console.log(),P===0&&v===0?console.log(S.green(S.bold("Everything checks out. You're good to go."))):P===0?console.log(S.yellow(S.bold(`${v} warning${v===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 F(e){try{return await rs(e),!0}catch{return!1}}async function us(){let e=await ne();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 ps(){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 ms(e){let s=L(e,"node_modules");if(!await F(s))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `bash setup.sh` (or `npm install`) in this folder."};try{if(!(await cs(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 hs(e){let s=process.platform==="darwin"?L(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?L(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):L(process.env.HOME??"",".cache","ms-playwright");return await F(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 fs(){let e=["supabase","dotenv","requests","httpx","PIL"],s=`import sys
52
54
  try:
53
55
  ${e.map(n=>` import ${n}`).join(`
54
56
  `)}
55
57
  except Exception as e:
56
58
  print(str(e))
57
59
  sys.exit(1)
58
- `,t=await ps("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(`
59
- `).pop()??"import failed",nextAction:"Run `bash setup.sh` in this folder."}}async function us(e,s){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let t=await D({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 Q(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 Z(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 he({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 ps(e,s){return new Promise(t=>{let n=os(e,s,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",o="";n.stdout?.on("data",l=>{r+=l.toString()}),n.stderr?.on("data",l=>{o+=l.toString()}),n.on("close",l=>t({code:l??1,stdout:r,stderr:o})),n.on("error",()=>t({code:1,stdout:r,stderr:o}))})}var fs="0.9.0",B=new ms;B.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(fs);B.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").action(async(e,s)=>{try{await Fe({target:e,license:s.license,skipInstall:!!s.skipInstall,skipSchema:!!s.skipSchema})}catch(t){console.error("init failed:",t.message),process.exit(1)}});B.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await Ye({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});B.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await Qe({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});B.command("doctor").description("Diagnose a broken install \u2014 env versions, files, installed deps, credentials").option("--offline","Skip credential validations that require network calls").action(async e=>{try{await et({offline:!!e.offline})}catch(s){console.error("doctor failed:",s.message),process.exit(1)}});B.parse(process.argv);
60
+ `,t=await ks("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 gs(e,s){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let t=await K({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 ee(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 te(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 ks(e,s){return new Promise(t=>{let n=ds(e,s,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",o="";n.stdout?.on("data",c=>{a+=c.toString()}),n.stderr?.on("data",c=>{o+=c.toString()}),n.on("close",c=>t({code:c??1,stdout:a,stderr:o})),n.on("error",()=>t({code:1,stdout:a,stderr:o}))})}import{existsSync as ws}from"fs";import{spawnSync as ys}from"child_process";import{join as Es,resolve as Ps}from"path";import A from"picocolors";async function it(e){let s=Ps(e.projectRoot??process.cwd()),t=Es(s,"scripts","whatsapp.mjs");ws(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 n=(e.label??"primary").trim(),a=n.replace(/[^A-Za-z0-9_-]/g,"");a||(console.error(A.red(`Invalid label '${n}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),a!==n&&console.error(A.yellow(`Note: cleaned label '${n}' \u2192 '${a}' (filename-safe characters only).`)),console.log(A.cyan(`Pairing WhatsApp account '${a}'...`)),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.
62
+ `));let o=ys(process.execPath,[t,"pair","--account",a],{cwd:s,stdio:"inherit"});if(o.status===0){console.log(A.green(`Paired '${a}'.`)),console.log(A.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(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/${a}/daemon.log`))),process.exit(o.status??1)}var Ss="0.10.0",D=new bs;D.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Ss);D.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 Ye({target:e,license:s.license,skipInstall:!!s.skipInstall,skipSchema:!!s.skipSchema})}catch(t){console.error("init failed:",t.message),process.exit(1)}});D.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await qe({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});D.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await tt({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});D.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 nt({offline:!!e.offline})}catch(s){console.error("doctor failed:",s.message),process.exit(1)}});D.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 it({label:e.label})}catch(s){console.error("pair-whatsapp failed:",s.message),process.exit(1)}});D.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klaudius",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code (find, build, deploy, outreach end-to-end).",
5
5
  "homepage": "https://klaudius.dev",
6
6
  "bugs": {