klaudius 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,4 +55,4 @@ Email [hello@klaudius.dev](mailto:hello@klaudius.dev).
55
55
 
56
56
  ## About
57
57
 
58
- Klaudius is operated by Cloudbot Limited, a company registered in England and Wales. More at [klaudius.dev](https://klaudius.dev).
58
+ More at [klaudius.dev](https://klaudius.dev).
@@ -1,26 +1,28 @@
1
- import{a as m,d as ee}from"./chunk-GI7NTKNT.js";import{useEffect as $e,useMemo as ze,useRef as J,useState as T}from"react";import{Box as S,Text as x,useApp as je,useInput as We}from"ink";var te={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 g,d as Q}from"./chunk-GI7NTKNT.js";import{useEffect as $e,useMemo as je,useRef as Z,useState as T}from"react";import{Box as P,Text as I,useApp as We,useInput as qe}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.
5
5
  (IONOS doesn't require app passwords for IMAP/SMTP unless you've enabled 2FA.)`},fastmail:{label:"Fastmail",smtpHost:"smtp.fastmail.com",smtpPort:587,imapHost:"imap.fastmail.com",imapPort:993,sentFolder:"Sent",inboxFolder:"INBOX",appPasswordHelp:`Generate at https://app.fastmail.com/settings/security/integrations
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
- (Zoho requires app passwords for IMAP/SMTP \u2014 your normal account password won't work.)`}},oe=`Use the app-specific password your provider issues for SMTP/IMAP
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 B=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)",ae=e=>/^\+\d{8,15}$/.test(e)?void 0:Pe,Se=e=>/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e)?void 0:"Enter a valid email",I=e=>t=>t.trim().length===0?`${e} is required`:void 0,z="one-off, no monthly fees",R="per month",ve={id:"pricing",title:"Pricing",isApplicable:()=>!0,execute:async(e,{prompt:t})=>{let a=e.pricingTerms&&e.pricingTerms!==z&&e.pricingTerms!==R?e.pricingTerms:void 0,o=a||(e.pricingTerms===R?R:z),s=[{value:z,label:"One-off payment (single fee)"},{value:R,label:"Monthly (recurring fee)"}];a&&s.unshift({value:a,label:`Keep current wording: "${a}"`});let n=await t({type:"select",message:"How will you charge clients?",initialValue:o,options:s,note:{title:"Billing model",body:`Klaudius bakes this into outreach copy verbatim \u2014 e.g. '$999
10
- one-off, no monthly fees' vs. '$99 per month'. Pick whichever
11
- model matches how you want to bill clients. You can switch later
12
- by re-running \`npx klaudius configure\`, or hand-edit PRICING_TERMS
13
- in .env to bespoke wording (e.g. 'per month, no minimum term').`}}),i=n===R,c=e.pricing??(i?"$99":"$999");return{pricing:await t({type:"text",message:i?"What's the monthly price you'll charge clients?":"What price will you charge clients per finished site?",placeholder:i?"e.g. $99, \xA379, \u20AC89":"e.g. $999, \xA3799, \u20AC899",initialValue:c,validate:I("Price"),note:{title:"Pricing",body:`Use the currency that matches the region of clients you'll be reaching
14
- out to (e.g. $ for US clients, \xA3 for the UK, \u20AC for the EU). Klaudius
15
- uses this exact string verbatim throughout outreach.`}}),pricingTerms:n}}},xe={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
9
+ rather than your normal account password).`;var N=class extends Error{constructor(){super("user pressed back"),this.name="BackSignal"}},U=class extends Error{constructor(){super("user cancelled"),this.name="CancelSignal"}},Se="Include the country code with a + (e.g. +12025550123 for US, +447123456789 for UK)",oe=e=>/^\+\d{8,15}$/.test(e)?void 0:Se,Pe=e=>/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e)?void 0:"Enter a valid email",A=e=>t=>t.trim().length===0?`${e} is required`:void 0,xe="one-off, no monthly fees",ae="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 ve={id:"pricing",title:"Pricing",isApplicable:()=>!0,execute:async(e,{prompt:t})=>{let n=e.pricingTerms===ae,o=n?"":e.pricing??"$999",s=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
10
+ leave blank) if you only want to charge a monthly fee. You can
11
+ also add a recurring monthly fee on the next prompt \u2014 combining
12
+ the two is fine (e.g. $499 upfront + $49/month).
13
+
14
+ Use the currency that matches your clients' region. Klaudius
15
+ uses this string verbatim throughout outreach.`}}),i=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:s,validate:v=>{if(H(a)&&H(v))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
+ a recurring monthly fee \u2014 either on its own (if upfront was 0)
17
+ or alongside the upfront fee.`}}),u=H(a),r=H(i),l,p,m;return u&&!r?(l=i.trim(),p=ae,m=i.trim()):!u&&r?(l=a.trim(),p=xe,m=void 0):(l=a.trim(),p=`upfront, then ${i.trim()}/month`,m=i.trim()),{pricing:l,pricingTerms:p,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
16
18
  run outreach to them automatically (email and/or SMS).
17
- If you'd rather handle outreach manually, you can skip this here.`}})})},Ie={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:I("Name")}),o=a.trim().split(/\s+/)[0];return{name:a,signature:e.signature??`Thanks, ${o}`}}},Te={id:"channels",title:"Outreach channels",isApplicable:e=>e.outreachEnabled===!0,execute:async(e,{prompt:t})=>{let a=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:a,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
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:A("Name")}),o=n.trim().split(/\s+/)[0];return{name:n,signature:e.signature??`Thanks, ${o}`}}},ke={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
18
20
  some list only an email, others only a phone number. Klaudius uses whichever
19
21
  channel is available for each candidate (it doesn't message the same candidate
20
22
  on both). Picking 'both' just means Klaudius can reach more of the
21
- businesses it finds.`}}),s=o==="both"?["email","sms"]:[o],n;return s.length>1&&(n=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:s,outreachPriority:n}}},ke={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
23
+ businesses it finds.`}}),s=o==="both"?["email","sms"]:[o],a;return s.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:s,outreachPriority:a}}},Ae={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
22
24
  address candidates will see as the sender. Use a domain you control
23
- (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)"}]}),s=o!=="custom"?te[o]:void 0,n=await t({type:"text",message:"Email address to send outreach from",placeholder:"you@yourbusiness.com",initialValue:e.emailAddress??"",validate:Se}),i=s?.appPasswordHelp??oe,c=await t({type:"password",message:"Paste the app password",initialValue:e.emailPassword??"",validate:I("App password"),note:{title:"App password",body:`An app password is a separate, single-purpose password that your
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)"}]}),s=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:Pe}),i=s?.appPasswordHelp??te,u=await t({type:"password",message:"Paste the app password",initialValue:e.emailPassword??"",validate:A("App password"),note:{title:"App password",body:`An app password is a separate, single-purpose password that your
24
26
  email provider issues for third-party apps like Klaudius. It is NOT
25
27
  your normal account login password.
26
28
 
@@ -28,7 +30,7 @@ your normal account login password.
28
30
 
29
31
  Once generated, it's stored locally in this project's .env file.
30
32
  It is never sent to Klaudius's servers \u2014 only to your email
31
- provider when sending outreach.`}}),r,u,f,y,k,E;if(o==="custom"){r=await t({type:"text",message:"SMTP host (the server Klaudius connects to for sending)",placeholder:"e.g. smtp.yourprovider.com",initialValue:e.emailSmtpHost??"",validate:I("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"});u=parseInt(_,10),f=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:I("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"});y=parseInt(O,10),k=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 r=s.smtpHost,u=s.smtpPort,f=s.imapHost,y=s.imapPort,k=s.sentFolder,E=s.inboxFolder;return{emailProvider:o,emailAddress:n,emailPassword:c,emailFromName:e.name,emailSmtpHost:r,emailSmtpPort:u,emailImapHost:f,emailImapPort:y,emailSentFolder:k,emailInboxFolder:E}}},Ae={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:
33
+ provider when sending outreach.`}}),r,l,p,m,v,E;if(o==="custom"){r=await t({type:"text",message:"SMTP host (the server Klaudius connects to for sending)",placeholder:"e.g. smtp.yourprovider.com",initialValue:e.emailSmtpHost??"",validate:A("SMTP host")});let F=await t({type:"text",message:"SMTP port (usually 587 for STARTTLS or 465 for SSL)",initialValue:String(e.emailSmtpPort??587),validate:k=>/^\d+$/.test(k)?void 0:"Must be a number"});l=parseInt(F,10),p=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:A("IMAP host")});let O=await t({type:"text",message:"IMAP port (usually 993 for SSL)",initialValue:String(e.emailImapPort??993),validate:k=>/^\d+$/.test(k)?void 0:"Must be a number"});m=parseInt(O,10),v=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 r=s.smtpHost,l=s.smtpPort,p=s.imapHost,m=s.imapPort,v=s.sentFolder,E=s.inboxFolder;return{emailProvider:o,emailAddress:a,emailPassword:u,emailFromName:e.name,emailSmtpHost:r,emailSmtpPort:l,emailImapHost:p,emailImapPort:m,emailSentFolder:v,emailInboxFolder:E}}},Ce={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:
32
34
 
33
35
  \u2022 macOS iMessage \u2014 free, uses Messages.app on your Mac.
34
36
  Reaches other Apple users as iMessage for free. To reach
@@ -44,7 +46,7 @@ provider when sending outreach.`}}),r,u,f,y,k,E;if(o==="custom"){r=await t({type
44
46
 
45
47
  \u2022 Twilio \u2014 cross-platform, ~$0.01 per SMS. Sender is a phone
46
48
  number you buy from Twilio. Works on any OS, reaches any
47
- 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)"}]}),s=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:ae}),n={smsProvider:o,testPhone:s};return o==="twilio"&&(n.twilioAccountSid=await t({type:"text",message:"Twilio Account SID (starts with AC...)",initialValue:e.twilioAccountSid??"",validate:i=>/^AC[a-zA-Z0-9]+$/.test(i)?void 0:"Should start with 'AC'"}),n.twilioAuthToken=await t({type:"password",message:"Twilio Auth Token",initialValue:e.twilioAuthToken??"",validate:I("Twilio Auth Token")}),n.twilioPhoneNumber=await t({type:"text",message:"Twilio phone number (the number outreach will be sent FROM)",placeholder:"+15551234567",initialValue:e.twilioPhoneNumber??"",validate:ae})),n}},Ce={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
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)"}]}),s=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:s};return o==="twilio"&&(a.twilioAccountSid=await t({type:"text",message:"Twilio Account SID (starts with AC...)",initialValue:e.twilioAccountSid??"",validate:i=>/^AC[a-zA-Z0-9]+$/.test(i)?void 0:"Should start with 'AC'"}),a.twilioAuthToken=await t({type:"password",message:"Twilio Auth Token",initialValue:e.twilioAuthToken??"",validate:A("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}},Ee={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
48
50
  Vercel API token to do this without an interactive login.
49
51
 
50
52
  How to get one (one-time, ~30 seconds):
@@ -67,7 +69,7 @@ STUCK? Open Claude (or any LLM) in another tab/app and paste:
67
69
  "I need to create a personal Vercel API token for the
68
70
  Klaudius CLI tool. Walk me through generating one at
69
71
  vercel.com/account/tokens, including which scope and
70
- expiration to choose."`}})})},Ee={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
72
+ expiration to choose."`}})})},Oe={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
71
73
  finds, where each one sits in your funnel (gathered \u2192 built \u2192 deployed
72
74
  \u2192 outreach sent \u2192 responded), and the follow-up state for every lead.
73
75
  You can browse it at any time from the Supabase dashboard, or ask
@@ -105,15 +107,15 @@ in another tab/app and paste this prompt verbatim:
105
107
  Settings \u2192 Data API \u2192 'API URL'
106
108
 
107
109
  It looks like https://xxxx.supabase.co. Click to copy and paste
108
- below.`}})).trim().replace(/\/rest\/v1\/?$/i,"").replace(/\/$/,""),n=s.match(/^https:\/\/([a-z0-9]+)\.supabase\.co/i)?.[1]??"",i=await t({type:"password",message:"Paste the Supabase secret key (sb_secret_\u2026)",initialValue:e.supabaseServiceKey??"",validate:r=>r.length<20?"Looks too short":void 0,note:{title:"Secret key",body:n?`Open this exact page:
109
- https://supabase.com/dashboard/project/${n}/settings/api-keys
110
+ below.`}})).trim().replace(/\/rest\/v1\/?$/i,"").replace(/\/$/,""),a=s.match(/^https:\/\/([a-z0-9]+)\.supabase\.co/i)?.[1]??"",i=await t({type:"password",message:"Paste the Supabase secret key (sb_secret_\u2026)",initialValue:e.supabaseServiceKey??"",validate:r=>r.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
110
112
 
111
113
  Under 'Secret keys', find the row whose value starts with
112
114
  'sb_secret_'. Click to copy the full value.
113
115
 
114
116
  NEVER use the 'anon' / 'public' / 'sb_publishable_' key (those
115
117
  are client-side keys with no write permissions).`:`Open Settings \u2192 API Keys in your Supabase project. Copy the
116
- secret key (starts with 'sb_secret_').`}}),c=await t({type:"password",message:"Paste the Supabase personal access token",initialValue:e.supabasePat??"",validate:r=>r.startsWith("sbp_")?void 0:"Should start with 'sbp_'",note:{title:"Personal access token",body:`This is a separate credential from the secret key above \u2014 it's an
118
+ secret key (starts with 'sb_secret_').`}}),u=await t({type:"password",message:"Paste the Supabase personal access token",initialValue:e.supabasePat??"",validate:r=>r.startsWith("sbp_")?void 0:"Should start with 'sbp_'",note:{title:"Personal access token",body:`This is a separate credential from the secret key above \u2014 it's an
117
119
  ACCOUNT-wide token (not project-scoped) used by the Supabase MCP and
118
120
  by Klaudius's schema migration.
119
121
 
@@ -123,7 +125,7 @@ Open this exact page:
123
125
  Click 'Generate new token', name it 'Klaudius', and set the
124
126
  expiration to 'Never' (recommended \u2014 saves you having to rotate
125
127
  it later). Copy the value (starts with 'sbp_') and paste it
126
- below.`}});return{supabaseUrl:s,supabaseServiceKey:i,supabasePat:c,supabaseProjectRef:n}}},Oe={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
128
+ below.`}});return{supabaseUrl:s,supabaseServiceKey:i,supabasePat:u,supabaseProjectRef:a}}},Me={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
127
129
  without websites in your target region. Without a key, the pipeline has
128
130
  no source of leads \u2014 so this is required.
129
131
 
@@ -159,13 +161,13 @@ STUCK? Open Claude (or any LLM) in another tab/app and paste this prompt:
159
161
  "I need a Google Places API (New) key for a CLI tool called
160
162
  Klaudius. Walk me through claiming the $300 Google Cloud free trial
161
163
  and getting the API key Google auto-generates after enabling
162
- Places API (New), including any signup gotchas."`}})})},Me={id:"telegram",title:"Telegram (optional)",isApplicable:()=>!0,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
164
+ Places API (New), including any signup gotchas."`}})})},Ne={id:"telegram",title:"Telegram (optional)",isApplicable:()=>!0,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
163
165
  candidate replies. This is OPTIONAL \u2014 skip it if you'd rather check
164
166
  the Supabase dashboard manually.
165
167
 
166
168
  If you say yes, you'll need a Telegram bot token (created via
167
169
  @BotFather, ~30 seconds) and your chat ID (your own user ID, for
168
- personal pings). The next two prompts walk you through both.`}}))return{};let o=await t({type:"password",message:"Paste your Telegram bot token",initialValue:e.telegramBotToken??"",validate:I("Bot token"),note:{title:"Bot token",body:`Telegram lets you create personal bots in ~30 seconds. Klaudius
170
+ personal pings). The next two prompts walk you through both.`}}))return{};let o=await t({type:"password",message:"Paste your Telegram bot token",initialValue:e.telegramBotToken??"",validate:A("Bot token"),note:{title:"Bot token",body:`Telegram lets you create personal bots in ~30 seconds. Klaudius
169
171
  uses a bot to send you private notifications.
170
172
 
171
173
  How to create one:
@@ -178,7 +180,7 @@ How to create one:
178
180
  'KlaudiusNotifierBot'). Each username has to be globally
179
181
  unique, so add a personal suffix if it's taken.
180
182
  6. BotFather replies with a token like
181
- '1234567890:AAEhBP_yourtokenhere\u2026'. Copy it and paste below.`}}),s=null,n=0,i=null;for(;s===null;){n++;let c=n>1;await t({type:"text",message:c?"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:c?"Detect chat ID \u2014 retry":"Detect chat ID",body:c?`${i}
183
+ '1234567890:AAEhBP_yourtokenhere\u2026'. Copy it and paste below.`}}),s=null,a=0,i=null;for(;s===null;){a++;let u=a>1;await t({type:"text",message:u?"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:u?"Detect chat ID \u2014 retry":"Detect chat ID",body:u?`${i}
182
184
 
183
185
  Make sure you sent a regular text message (e.g. 'hi'), not
184
186
  just a /start tap \u2014 /start alone doesn't always register.
@@ -191,5 +193,5 @@ any messages your bot has received. To make that work:
191
193
  If the chat starts with a 'Start' button, tap that first,
192
194
  THEN send 'hi'. /start alone doesn't always show up.
193
195
  3. Press Enter below \u2014 Klaudius will detect the chat ID for
194
- you.`}});let r=await ee({botToken:o});if(r.ok&&r.chatId)s=r.chatId;else if(r.reason==="no_messages")i="No messages from you to your bot have been picked up yet.";else throw new Error(`Telegram chat ID auto-detect failed: ${r.message??"unknown error"}`)}return{telegramBotToken:o,telegramChatId:s}}},C=[ve,xe,Ie,Te,ke,Ae,Ce,Ee,Oe,Me];import{Box as ne,Text as Re}from"ink";import{jsx as se,jsxs as Ke}from"react/jsx-runtime";var Be={pending:"\u25CB",current:"\u25C9",done:"\u2713",skipped:"\xB7"},Ne={pending:void 0,current:"cyan",done:"green",skipped:void 0};function ie({items:e}){return se(ne,{flexDirection:"column",width:28,flexShrink:0,children:e.map(t=>{let a=t.status==="skipped"||t.status==="pending";return se(ne,{children:Ke(Re,{color:Ne[t.status],bold:t.status==="current",dimColor:a&&t.status!=="current",children:[Be[t.status]," ",t.title]})},t.id)})})}import{useEffect as Ve,useState as re}from"react";import{Box as j,Text as D,useInput as Fe}from"ink";import _e from"ink-text-input";import{jsx as N,jsxs as W}from"react/jsx-runtime";function le({spec:e,masked:t,onSubmit:a,onBack:o}){let[s,n]=re(typeof e.initialValue=="string"?e.initialValue:""),[i,c]=re(null);Ve(()=>(m("TextPromptUI:mount",{masked:t,message:e.message.slice(0,60),initial:typeof e.initialValue=="string"?e.initialValue.slice(0,30):null}),()=>{m("TextPromptUI:unmount")}),[t,e.message,e.initialValue]),Fe((u,f)=>{m("TextPromptUI:useInput fired",{input:u,ctrl:f.ctrl,escape:f.escape,return:f.return}),f.escape&&o()});let r=u=>{m("TextPromptUI:handleSubmit",{raw:u.slice(0,30)});let f=u;if(e.validate){let y=e.validate(f);if(y){m("TextPromptUI:validate failed",{err:y}),c(y);return}}c(null),a(f)};return W(j,{flexDirection:"column",children:[W(D,{children:[N(D,{color:"cyan",children:"?"})," ",e.message]}),W(j,{children:[N(D,{color:"green",children:"\u203A "}),N(_e,{value:s,onChange:n,onSubmit:r,placeholder:e.placeholder,mask:t?"\u2022":void 0})]}),i&&N(j,{marginTop:0,children:N(D,{color:"red",children:i})})]})}import{useState as He}from"react";import{Box as ce,Text as q,useInput as Ue}from"ink";import{jsx as ue,jsxs as Y}from"react/jsx-runtime";function pe({spec:e,onSubmit:t,onBack:a}){let o=e.options??[],s=typeof e.initialValue=="string"?Math.max(0,o.findIndex(c=>c.value===e.initialValue)):0,[n,i]=He(s===-1?0:s);return Ue((c,r)=>{if(r.escape)a();else if(r.upArrow)i(u=>(u-1+o.length)%o.length);else if(r.downArrow)i(u=>(u+1)%o.length);else if(r.return){let u=o[n];u&&t(u.value)}}),Y(ce,{flexDirection:"column",children:[Y(q,{children:[ue(q,{color:"cyan",children:"?"})," ",e.message]}),ue(ce,{flexDirection:"column",marginTop:0,children:o.map((c,r)=>{let u=r===n;return Y(q,{color:u?"cyan":void 0,bold:u,children:[u?"\u25CF ":"\u25CB ",c.label]},c.value)})})]})}import{useState as De}from"react";import{Box as de,Text as K,useInput as Ge}from"ink";import{jsx as me,jsxs as V}from"react/jsx-runtime";function he({spec:e,onSubmit:t,onBack:a}){let[o,s]=De(typeof e.initialValue=="boolean"?e.initialValue:!0);return Ge((n,i)=>{i.escape?a():i.leftArrow||i.rightArrow?s(c=>!c):n==="y"||n==="Y"?s(!0):n==="n"||n==="N"?s(!1):i.return&&t(o)}),V(de,{flexDirection:"column",children:[V(K,{children:[me(K,{color:"cyan",children:"?"})," ",e.message]}),V(de,{marginTop:0,children:[V(K,{color:o?"cyan":void 0,bold:o,children:[o?"\u25CF ":"\u25CB ","Yes"]}),me(K,{children:" "}),V(K,{color:o?void 0:"cyan",bold:!o,children:[o?"\u25CB ":"\u25CF ","No"]})]})]})}import{Box as ge,Text as fe}from"ink";import{jsx as X,jsxs as Le}from"react/jsx-runtime";function Z({title:e,body:t}){let a=t.split(`
195
- `);return Le(ge,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[X(fe,{color:"cyan",bold:!0,children:e}),X(ge,{flexDirection:"column",marginTop:0,children:a.map((o,s)=>X(fe,{dimColor:!1,children:o.length===0?" ":o},s))})]})}import{jsx as p,jsxs as F}from"react/jsx-runtime";function Rt({defaults:e,onComplete:t,onlySection:a,banner:o}){let{exit:s}=je(),n=J({...e}),i=J(new Map),[,c]=T(0),r=()=>c(d=>d+1),[u,f]=T(null),[y,k]=T(null),[E,_]=T([]),[O,A]=T(null),[Q,ye]=T(!1),[G,be]=T({current:0,total:0}),H=()=>{let d=i.current;for(let h of C){let $=h.isApplicable(n.current),l=d.get(h.id);$?a&&h.id!==a?l!=="current"&&d.set(h.id,"done"):(l==="skipped"||!l)&&d.set(h.id,"pending"):d.set(h.id,"skipped")}};i.current.size===0&&H();let L=J(!1);$e(()=>{if(m("WizardApp:useEffect fired",{startedAlready:L.current}),L.current){m("WizardApp:useEffect returning early (startedRef true)");return}L.current=!0,m("WizardApp:orchestrator starting");let d=0,h=l=>{let w=++d;return m("orchestrator:promptFn called",{id:w,type:l.type,message:l.message.slice(0,60)}),A(null),new Promise((P,g)=>{k({id:w,spec:l,resolve:v=>{m("orchestrator:prompt resolved",{id:w,type:l.type,value:typeof v=="string"?v.slice(0,30):v}),P(v)},reject:v=>{m("orchestrator:prompt rejected",{id:w,reason:v.message}),g(v)}})})},$=l=>{_(w=>[...w,l])};return(async()=>{try{let l=a?C.filter(g=>g.id===a):C,w=()=>l.filter(g=>g.isApplicable(n.current)).length,P=0;for(;P<l.length;){let g=l[P];if(!g.isApplicable(n.current)){i.current.set(g.id,"skipped"),P++,H(),r();continue}_([]);for(let b of C)b.id===g.id?i.current.set(b.id,"current"):i.current.get(b.id)==="current"&&i.current.set(b.id,"pending");f(g.id);let v=l.slice(0,P+1).filter(b=>b.isApplicable(n.current)).length;be({current:v,total:w()}),r();try{let b=await g.execute(n.current,{prompt:h,info:$});n.current={...n.current,...b},i.current.set(g.id,"done"),H(),P++}catch(b){if(b instanceof B){i.current.set(g.id,"pending");let M=P-1;for(;M>=0&&!l[M].isApplicable(n.current);)M--;M<0||(P=M,i.current.set(l[P].id,"pending")),H(),r();continue}throw b}}m("orchestrator:all sections done, calling onComplete + exit"),ye(!0),k(null),f(null),r(),await new Promise(g=>setTimeout(g,200)),t(n.current),s()}catch(l){m("orchestrator:caught error",{name:l?.name,message:l?.message}),l instanceof U&&(s(),process.exit(0));let w=l instanceof Error?l.message:String(l);A(`Setup error: ${w}`),r()}})(),()=>{m("WizardApp:useEffect cleanup ran (component unmounting)")}},[s,t]),We((d,h)=>{m("WizardApp:useInput fired",{input:d,ctrl:h.ctrl,escape:h.escape,return:h.return}),h.ctrl&&d==="c"&&(m("WizardApp:Ctrl+C \u2192 exiting"),s(),process.exit(0))});let we=ze(()=>C.map(d=>({id:d.id,title:d.title,status:i.current.get(d.id)??"pending"})),[u,Q,O]);return F(S,{flexDirection:"column",paddingY:1,children:[F(S,{marginBottom:1,children:[p(x,{bold:!0,color:"cyan",children:"Klaudius setup"}),p(x,{dimColor:!0,children:" \xB7 "}),p(x,{dimColor:!0,children:G.total>0?`Step ${G.current} of ${G.total}`:"Loading\u2026"})]}),F(S,{children:[p(ie,{items:we}),F(S,{flexDirection:"column",flexGrow:1,marginLeft:2,children:[o&&F(S,{marginBottom:1,borderStyle:"round",borderColor:"red",paddingX:1,flexDirection:"column",children:[p(x,{color:"red",bold:!0,children:"\u26A0 Heads up"}),p(x,{children:o})]}),E.map((d,h)=>p(S,{marginBottom:1,children:p(Z,{title:d.title,body:d.body})},h)),y?.spec.note&&p(S,{marginBottom:1,children:p(Z,{title:y.spec.note.title,body:y.spec.note.body})}),y&&qe(y),O&&p(S,{marginTop:1,children:p(x,{color:"red",children:O})}),Q&&p(S,{marginTop:1,children:p(x,{color:"green",bold:!0,children:"\u2713 Setup complete. Continuing\u2026"})})]})]}),p(S,{marginTop:1,children:p(x,{dimColor:!0,children:"\u21B5 confirm esc back to previous section ctrl-c cancel"})})]})}function qe(e){let t=o=>e.resolve(o),a=()=>e.reject(new B);switch(e.spec.type){case"text":case"password":return p(le,{spec:e.spec,masked:e.spec.type==="password",onSubmit:t,onBack:a},e.id);case"select":return p(pe,{spec:e.spec,onSubmit:t,onBack:a},e.id);case"confirm":return p(he,{spec:e.spec,onSubmit:t,onBack:a},e.id)}}export{Rt as WizardApp};
196
+ you.`}});let r=await Q({botToken:o});if(r.ok&&r.chatId)s=r.chatId;else if(r.reason==="no_messages")i="No messages from you to your bot have been picked up yet.";else throw new Error(`Telegram chat ID auto-detect failed: ${r.message??"unknown error"}`)}return{telegramBotToken:o,telegramChatId:s}}},C=[ve,Ie,Te,ke,Ae,Ce,Ee,Oe,Me,Ne];import{Box as ne,Text as Re}from"ink";import{jsx as se,jsxs as Ke}from"react/jsx-runtime";var Be={pending:"\u25CB",current:"\u25C9",done:"\u2713",skipped:"\xB7"},Ve={pending:void 0,current:"cyan",done:"green",skipped:void 0};function ie({items:e}){return se(ne,{flexDirection:"column",width:28,flexShrink:0,children:e.map(t=>{let n=t.status==="skipped"||t.status==="pending";return se(ne,{children:Ke(Re,{color:Ve[t.status],bold:t.status==="current",dimColor:n&&t.status!=="current",children:[Be[t.status]," ",t.title]})},t.id)})})}import{useEffect as Fe,useState as re}from"react";import{Box as $,Text as D,useInput as _e}from"ink";import He from"ink-text-input";import{jsx as R,jsxs as j}from"react/jsx-runtime";function le({spec:e,masked:t,onSubmit:n,onBack:o}){let[s,a]=re(typeof e.initialValue=="string"?e.initialValue:""),[i,u]=re(null);Fe(()=>(g("TextPromptUI:mount",{masked:t,message:e.message.slice(0,60),initial:typeof e.initialValue=="string"?e.initialValue.slice(0,30):null}),()=>{g("TextPromptUI:unmount")}),[t,e.message,e.initialValue]),_e((l,p)=>{g("TextPromptUI:useInput fired",{input:l,ctrl:p.ctrl,escape:p.escape,return:p.return}),p.escape&&o()});let r=l=>{g("TextPromptUI:handleSubmit",{raw:l.slice(0,30)});let p=l;if(e.validate){let m=e.validate(p);if(m){g("TextPromptUI:validate failed",{err:m}),u(m);return}}u(null),n(p)};return j($,{flexDirection:"column",children:[j(D,{children:[R(D,{color:"cyan",children:"?"})," ",e.message]}),j($,{children:[R(D,{color:"green",children:"\u203A "}),R(He,{value:s,onChange:a,onSubmit:r,placeholder:e.placeholder,mask:t?"\u2022":void 0})]}),i&&R($,{marginTop:0,children:R(D,{color:"red",children:i})})]})}import{useState as Ue}from"react";import{Box as ce,Text as W,useInput as De}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??[],s=typeof e.initialValue=="string"?Math.max(0,o.findIndex(u=>u.value===e.initialValue)):0,[a,i]=Ue(s===-1?0:s);return De((u,r)=>{if(r.escape)n();else if(r.upArrow)i(l=>(l-1+o.length)%o.length);else if(r.downArrow)i(l=>(l+1)%o.length);else if(r.return){let l=o[a];l&&t(l.value)}}),q(ce,{flexDirection:"column",children:[q(W,{children:[ue(W,{color:"cyan",children:"?"})," ",e.message]}),ue(ce,{flexDirection:"column",marginTop:0,children:o.map((u,r)=>{let l=r===a;return q(W,{color:l?"cyan":void 0,bold:l,children:[l?"\u25CF ":"\u25CB ",u.label]},u.value)})})]})}import{useState as Ge}from"react";import{Box as de,Text as B,useInput as Le}from"ink";import{jsx as me,jsxs as V}from"react/jsx-runtime";function he({spec:e,onSubmit:t,onBack:n}){let[o,s]=Ge(typeof e.initialValue=="boolean"?e.initialValue:!0);return Le((a,i)=>{i.escape?n():i.leftArrow||i.rightArrow?s(u=>!u):a==="y"||a==="Y"?s(!0):a==="n"||a==="N"?s(!1):i.return&&t(o)}),V(de,{flexDirection:"column",children:[V(B,{children:[me(B,{color:"cyan",children:"?"})," ",e.message]}),V(de,{marginTop:0,children:[V(B,{color:o?"cyan":void 0,bold:o,children:[o?"\u25CF ":"\u25CB ","Yes"]}),me(B,{children:" "}),V(B,{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(`
197
+ `);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,s)=>Y(fe,{dimColor:!1,children:o.length===0?" ":o},s))})]})}import{jsx as d,jsxs as K}from"react/jsx-runtime";function Rt({defaults:e,onComplete:t,onlySection:n,banner:o}){let{exit:s}=We(),a=Z({...e}),i=Z(new Map),[,u]=T(0),r=()=>u(h=>h+1),[l,p]=T(null),[m,v]=T(null),[E,F]=T([]),[O,k]=T(null),[J,ye]=T(!1),[G,be]=T({current:0,total:0}),_=()=>{let h=i.current;for(let f of C){let z=f.isApplicable(a.current),c=h.get(f.id);z?n&&f.id!==n?c!=="current"&&h.set(f.id,"done"):(c==="skipped"||!c)&&h.set(f.id,"pending"):h.set(f.id,"skipped")}};i.current.size===0&&_();let L=Z(!1);$e(()=>{if(g("WizardApp:useEffect fired",{startedAlready:L.current}),L.current){g("WizardApp:useEffect returning early (startedRef true)");return}L.current=!0,g("WizardApp:orchestrator starting");let h=0,f=c=>{let w=++h;return g("orchestrator:promptFn called",{id:w,type:c.type,message:c.message.slice(0,60)}),k(null),new Promise((S,y)=>{v({id:w,spec:c,resolve:x=>{g("orchestrator:prompt resolved",{id:w,type:c.type,value:typeof x=="string"?x.slice(0,30):x}),S(x)},reject:x=>{g("orchestrator:prompt rejected",{id:w,reason:x.message}),y(x)}})})},z=c=>{F(w=>[...w,c])};return(async()=>{try{let c=n?C.filter(y=>y.id===n):C,w=()=>c.filter(y=>y.isApplicable(a.current)).length,S=0;for(;S<c.length;){let y=c[S];if(!y.isApplicable(a.current)){i.current.set(y.id,"skipped"),S++,_(),r();continue}F([]);for(let b of C)b.id===y.id?i.current.set(b.id,"current"):i.current.get(b.id)==="current"&&i.current.set(b.id,"pending");p(y.id);let x=c.slice(0,S+1).filter(b=>b.isApplicable(a.current)).length;be({current:x,total:w()}),r();try{let b=await y.execute(a.current,{prompt:f,info:z});a.current={...a.current,...b},i.current.set(y.id,"done"),_(),S++}catch(b){if(b instanceof N){i.current.set(y.id,"pending");let M=S-1;for(;M>=0&&!c[M].isApplicable(a.current);)M--;M<0||(S=M,i.current.set(c[S].id,"pending")),_(),r();continue}throw b}}g("orchestrator:all sections done, calling onComplete + exit"),ye(!0),v(null),p(null),r(),await new Promise(y=>setTimeout(y,200)),t(a.current),s()}catch(c){g("orchestrator:caught error",{name:c?.name,message:c?.message}),c instanceof U&&(s(),process.exit(0));let w=c instanceof Error?c.message:String(c);k(`Setup error: ${w}`),r()}})(),()=>{g("WizardApp:useEffect cleanup ran (component unmounting)")}},[s,t]),qe((h,f)=>{g("WizardApp:useInput fired",{input:h,ctrl:f.ctrl,escape:f.escape,return:f.return}),f.ctrl&&h==="c"&&(g("WizardApp:Ctrl+C \u2192 exiting"),s(),process.exit(0))});let we=je(()=>C.map(h=>({id:h.id,title:h.title,status:i.current.get(h.id)??"pending"})),[l,J,O]);return K(P,{flexDirection:"column",paddingY:1,children:[K(P,{marginBottom:1,children:[d(I,{bold:!0,color:"cyan",children:"Klaudius setup"}),d(I,{dimColor:!0,children:" \xB7 "}),d(I,{dimColor:!0,children:G.total>0?`Step ${G.current} of ${G.total}`:"Loading\u2026"})]}),K(P,{children:[d(ie,{items:we}),K(P,{flexDirection:"column",flexGrow:1,marginLeft:2,children:[o&&K(P,{marginBottom:1,borderStyle:"round",borderColor:"red",paddingX:1,flexDirection:"column",children:[d(I,{color:"red",bold:!0,children:"\u26A0 Heads up"}),d(I,{children:o})]}),E.map((h,f)=>d(P,{marginBottom:1,children:d(X,{title:h.title,body:h.body})},f)),m?.spec.note&&d(P,{marginBottom:1,children:d(X,{title:m.spec.note.title,body:m.spec.note.body})}),m&&Ye(m),O&&d(P,{marginTop:1,children:d(I,{color:"red",children:O})}),J&&d(P,{marginTop:1,children:d(I,{color:"green",bold:!0,children:"\u2713 Setup complete. Continuing\u2026"})})]})]}),d(P,{marginTop:1,children:d(I,{dimColor:!0,children:"\u21B5 confirm esc back to previous section ctrl-c cancel"})})]})}function Ye(e){let t=o=>e.resolve(o),n=()=>e.reject(new N);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{Rt as WizardApp};
package/dist/bin.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{a as _,b as F,c as V,e as G}from"./chunk-GI7NTKNT.js";import{a as U,e as W}from"./chunk-47ODNABO.js";import{Command as wt}from"commander";import{mkdir as we,readdir as et,readFile as he,stat as tt,writeFile as ge}from"fs/promises";import{resolve as st,isAbsolute as it,join as x}from"path";import*as d from"@clack/prompts";import m from"picocolors";import be from"react";import{render as Re}from"ink";async function w(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:n}=await import("./WizardApp-G654OP5R.js"),t=null;_("runWizard:start",{onlySection:s.onlySection,hasDefaults:Object.keys(e).length>0}),V(),await new Promise(l=>setImmediate(l)),await new Promise(l=>setTimeout(l,0)),_("runWizard:event loop drained, mounting Ink");let a=Re(be.createElement(n,{defaults:e,onlySection:s.onlySection,banner:s.banner,onComplete:l=>{_("runWizard:onComplete called",{keys:Object.keys(l).length}),t=l}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(_("runWizard:render returned, awaiting exit"),await a.waitUntilExit(),_("runWizard:waitUntilExit resolved",{resultIsNull:t===null}),!t)throw new Error(`Wizard exited without completing. Diagnostic log: ${F}
3
- Please share that file so we can trace what happened.`);return t}function C(e){let s=[],n=a=>{s.push(""),s.push("# "+"=".repeat(60)),s.push(`# ${a}`),s.push("# "+"=".repeat(60)),s.push("")},t=(a,l)=>{if(l==null||l===""){s.push(`# ${a}=`);return}let c=String(l);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(c)){let r=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");s.push(`${a}="${r}"`)}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."),n("Klaudius licence"),t("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("Pricing"),t("PRICING",e.pricing),t("PRICING_TERMS",e.pricingTerms),n("Automated outreach features"),t("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),t("OPERATOR_NAME",e.name),t("SIGNATURE",e.signature),t("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),t("OUTREACH_PRIORITY",e.outreachPriority),n("Email outreach"),t("EMAIL_ADDRESS",e.emailAddress),t("EMAIL_PASSWORD",e.emailPassword),t("EMAIL_FROM_NAME",e.emailFromName),t("EMAIL_SMTP_HOST",e.emailSmtpHost),t("EMAIL_SMTP_PORT",e.emailSmtpPort),t("EMAIL_IMAP_HOST",e.emailImapHost),t("EMAIL_IMAP_PORT",e.emailImapPort),t("EMAIL_SENT_FOLDER",e.emailSentFolder),t("EMAIL_INBOX_FOLDER",e.emailInboxFolder),n("SMS outreach"),t("SMS_PROVIDER",e.smsProvider),t("TEST_PHONE",e.testPhone),t("TWILIO_ACCOUNT_SID",e.twilioAccountSid),t("TWILIO_AUTH_TOKEN",e.twilioAuthToken),t("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("Supabase (pipeline state)"),t("SUPABASE_URL",e.supabaseUrl),t("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),t("SUPABASE_PAT",e.supabasePat),t("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Vercel (deployment)"),t("VERCEL_TOKEN",e.vercelToken),n("Search APIs"),t("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),t("SERPAPI_KEY",e.serpapiKey),n("Telegram notifications (optional)"),t("TELEGRAM_BOT_TOKEN",e.telegramBotToken),t("TELEGRAM_CHAT_ID",e.telegramChatId),n("Rate limiting (sensible defaults)"),t("REQUESTS_PER_MINUTE",10),t("REQUEST_DELAY",2),s.join(`
2
+ import{a as _,b as F,c as V,e as G}from"./chunk-GI7NTKNT.js";import{a as U,e as W}from"./chunk-47ODNABO.js";import{Command as yt}from"commander";import{mkdir as ye,readdir as et,readFile as he,stat as tt,writeFile as ge}from"fs/promises";import{resolve as st,isAbsolute as it,join as x}from"path";import*as d from"@clack/prompts";import m from"picocolors";import be from"react";import{render as Re}from"ink";async function y(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:n}=await import("./WizardApp-ETYSKVKU.js"),t=null;_("runWizard:start",{onlySection:s.onlySection,hasDefaults:Object.keys(e).length>0}),V(),await new Promise(l=>setImmediate(l)),await new Promise(l=>setTimeout(l,0)),_("runWizard:event loop drained, mounting Ink");let a=Re(be.createElement(n,{defaults:e,onlySection:s.onlySection,banner:s.banner,onComplete:l=>{_("runWizard:onComplete called",{keys:Object.keys(l).length}),t=l}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(_("runWizard:render returned, awaiting exit"),await a.waitUntilExit(),_("runWizard:waitUntilExit resolved",{resultIsNull:t===null}),!t)throw new Error(`Wizard exited without completing. Diagnostic log: ${F}
3
+ Please share that file so we can trace what happened.`);return t}function C(e){let s=[],n=a=>{s.push(""),s.push("# "+"=".repeat(60)),s.push(`# ${a}`),s.push("# "+"=".repeat(60)),s.push("")},t=(a,l)=>{if(l==null||l===""){s.push(`# ${a}=`);return}let c=String(l);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(c)){let r=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");s.push(`${a}="${r}"`)}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."),n("Klaudius licence"),t("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("Pricing"),t("PRICING",e.pricing),t("PRICING_TERMS",e.pricingTerms),t("PRICING_MONTHLY",e.pricingMonthly),n("Automated outreach features"),t("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),t("OPERATOR_NAME",e.name),t("SIGNATURE",e.signature),t("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),t("OUTREACH_PRIORITY",e.outreachPriority),n("Email outreach"),t("EMAIL_ADDRESS",e.emailAddress),t("EMAIL_PASSWORD",e.emailPassword),t("EMAIL_FROM_NAME",e.emailFromName),t("EMAIL_SMTP_HOST",e.emailSmtpHost),t("EMAIL_SMTP_PORT",e.emailSmtpPort),t("EMAIL_IMAP_HOST",e.emailImapHost),t("EMAIL_IMAP_PORT",e.emailImapPort),t("EMAIL_SENT_FOLDER",e.emailSentFolder),t("EMAIL_INBOX_FOLDER",e.emailInboxFolder),n("SMS outreach"),t("SMS_PROVIDER",e.smsProvider),t("TEST_PHONE",e.testPhone),t("TWILIO_ACCOUNT_SID",e.twilioAccountSid),t("TWILIO_AUTH_TOKEN",e.twilioAuthToken),t("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("Supabase (pipeline state)"),t("SUPABASE_URL",e.supabaseUrl),t("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),t("SUPABASE_PAT",e.supabasePat),t("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Vercel (deployment)"),t("VERCEL_TOKEN",e.vercelToken),n("Search APIs"),t("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),t("SERPAPI_KEY",e.serpapiKey),n("Telegram notifications (optional)"),t("TELEGRAM_BOT_TOKEN",e.telegramBotToken),t("TELEGRAM_CHAT_ID",e.telegramChatId),n("Rate limiting (sensible defaults)"),t("REQUESTS_PER_MINUTE",10),t("REQUEST_DELAY",2),s.join(`
4
4
  `)+`
5
5
  `}function v(e){let s={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat}}}};return JSON.stringify(s,null,2)+`
6
6
  `}function Ce(e,s){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(s)){let n=s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${s}`}function Y(e,s,n){let t=n.filter(c=>!(c.key in s));if(t.length===0)return null;let a=e.endsWith(`
@@ -8,40 +8,40 @@ Please share that file so we can trace what happened.`);return t}function C(e){l
8
8
  `,l=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let c of t)l.push(""),c.comment&&l.push(`# ${c.comment}`),l.push(Ce(c.key,c.value));return e+a+l.join(`
9
9
  `)+`
10
10
  `}function ve(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 A(e){let s={};for(let n of e.split(`
11
- `)){let t=n.trim();if(!t||t.startsWith("#"))continue;let a=t.indexOf("=");if(a===-1)continue;let l=t.slice(0,a).trim(),c=ve(t.slice(a+1).trim());s[l]=c}return s}function z(e){let s=l=>{let c=e[l];if(!c)return;let r=parseInt(c,10);return isNaN(r)?void 0:r},n=e.SMS_PROVIDER,t=e.OUTREACH_CHANNELS?.split(",").map(l=>l.trim()).filter(l=>l==="email"||l==="sms"),a=e.OUTREACH_PRIORITY;return{licenseKey:e.KLAUDIUS_LICENSE_KEY,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:t&&t.length>0?t:void 0,outreachPriority:a==="email"||a==="sms"?a: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:n==="imessage"||n==="twilio"?n: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,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 K(e){let s=u=>{let o=e[u];if(!o)return;let p=parseInt(o,10);return isNaN(p)?void 0:p},n=e.SUPABASE_URL,t=e.SUPABASE_SERVICE_KEY,a=e.SUPABASE_PAT,l=e.SUPABASE_PROJECT_REF,c=e.PRICING,r=e.PRICING_TERMS||"one-off, no monthly fees",h=e.VERCEL_TOKEN;if(!c||!n||!t||!a||!l||!h)return null;let f=e.SMS_PROVIDER,k=e.OUTREACH_CHANNELS?.split(",").map(u=>u.trim()).filter(u=>u==="email"||u==="sms"),g=e.OUTREACH_PRIORITY;return{licenseKey:e.KLAUDIUS_LICENSE_KEY,pricing:c,pricingTerms:r,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:k&&k.length>0?k:void 0,outreachPriority:g==="email"||g==="sms"?g: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:f==="imessage"||f==="twilio"?f:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,vercelToken:h,supabaseUrl:n,supabaseServiceKey:t,supabasePat:a,supabaseProjectRef:l,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{mkdir as Oe,rm as Le}from"fs/promises";import{Readable as Me}from"stream";import*as X from"tar";var xe="https://klaudius.dev/api/template";function $e(e){return Me.fromWeb(e)}async function O(e){let s=process.env.KLAUDIUS_TEMPLATE_URL??xe,n="0.4.0",t;try{t=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:n})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${c.message}`)}if(!t.ok){let c="";try{let r=await t.json();c=r.reason?` (${r.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${t.status}${c}`)}if(!t.body)throw new Error("Template download succeeded but response had no body");let a=t.headers.get("x-klaudius-tier");await Oe(e.destDir,{recursive:!0});let l=0;try{await new Promise((c,r)=>{let h=X.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{l++}});h.on("finish",c),h.on("error",r),$e(t.body).on("error",r).pipe(h)})}catch(c){throw await Le(e.destDir,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Failed to extract template archive: ${c.message}`)}return{filesExtracted:l,tier:a}}import{mkdir as Ne,readFile as Ue,writeFile as Ke,access as De}from"fs/promises";import{dirname as He,join as q}from"path";var je=".klaudius",J=`${je}/manifest.json`;async function Q(e){let s=q(e,J);try{await De(s)}catch{return null}let n=await Ue(s,"utf-8");return JSON.parse(n)}async function L(e,s){let n=q(e,J);await Ne(He(n),{recursive:!0}),await Ke(n,JSON.stringify(s,null,2)+`
11
+ `)){let t=n.trim();if(!t||t.startsWith("#"))continue;let a=t.indexOf("=");if(a===-1)continue;let l=t.slice(0,a).trim(),c=ve(t.slice(a+1).trim());s[l]=c}return s}function z(e){let s=l=>{let c=e[l];if(!c)return;let r=parseInt(c,10);return isNaN(r)?void 0:r},n=e.SMS_PROVIDER,t=e.OUTREACH_CHANNELS?.split(",").map(l=>l.trim()).filter(l=>l==="email"||l==="sms"),a=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:t&&t.length>0?t:void 0,outreachPriority:a==="email"||a==="sms"?a: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:n==="imessage"||n==="twilio"?n: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,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 K(e){let s=u=>{let o=e[u];if(!o)return;let p=parseInt(o,10);return isNaN(p)?void 0:p},n=e.SUPABASE_URL,t=e.SUPABASE_SERVICE_KEY,a=e.SUPABASE_PAT,l=e.SUPABASE_PROJECT_REF,c=e.PRICING,r=e.PRICING_TERMS||"one-off, no monthly fees",h=e.VERCEL_TOKEN;if(!c||!n||!t||!a||!l||!h)return null;let f=e.SMS_PROVIDER,k=e.OUTREACH_CHANNELS?.split(",").map(u=>u.trim()).filter(u=>u==="email"||u==="sms"),g=e.OUTREACH_PRIORITY;return{licenseKey:e.KLAUDIUS_LICENSE_KEY,pricing:c,pricingTerms:r,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:g==="email"||g==="sms"?g: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:f==="imessage"||f==="twilio"?f:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,vercelToken:h,supabaseUrl:n,supabaseServiceKey:t,supabasePat:a,supabaseProjectRef:l,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{mkdir as Oe,rm as Le}from"fs/promises";import{Readable as Me}from"stream";import*as X from"tar";var xe="https://klaudius.dev/api/template";function $e(e){return Me.fromWeb(e)}async function O(e){let s=process.env.KLAUDIUS_TEMPLATE_URL??xe,n="0.5.1",t;try{t=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:n})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${c.message}`)}if(!t.ok){let c="";try{let r=await t.json();c=r.reason?` (${r.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${t.status}${c}`)}if(!t.body)throw new Error("Template download succeeded but response had no body");let a=t.headers.get("x-klaudius-tier");await Oe(e.destDir,{recursive:!0});let l=0;try{await new Promise((c,r)=>{let h=X.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{l++}});h.on("finish",c),h.on("error",r),$e(t.body).on("error",r).pipe(h)})}catch(c){throw await Le(e.destDir,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Failed to extract template archive: ${c.message}`)}return{filesExtracted:l,tier:a}}import{mkdir as Ne,readFile as Ue,writeFile as Ke,access as De}from"fs/promises";import{dirname as He,join as q}from"path";var je=".klaudius",J=`${je}/manifest.json`;async function Q(e){let s=q(e,J);try{await De(s)}catch{return null}let n=await Ue(s,"utf-8");return JSON.parse(n)}async function L(e,s){let n=q(e,J);await Ne(He(n),{recursive:!0}),await Ke(n,JSON.stringify(s,null,2)+`
12
12
  `,"utf-8")}function Z(e,s){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:s}}import{createHash as Be}from"crypto";import{hostname as ee,userInfo as Fe,platform as te,arch as se}from"os";import E from"picocolors";var i={info:e=>console.log(E.cyan("\u2139"),e),success:e=>console.log(E.green("\u2713"),e),warn:e=>console.log(E.yellow("\u26A0"),e),error:e=>console.error(E.red("\u2717"),e),step:e=>console.log(E.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
13
- `+E.bold(E.cyan(e))),detail:e=>console.log(E.dim(" "+e))};var Ve="https://klaudius.dev",Ge="/api/licenses/validate",We="0.4.0";async function ie(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(),t=(process.env.KLAUDIUS_API_URL??Ve).replace(/\/$/,"")+Ge,a=b(),l;try{l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:s,machine_id:a,hostname:ee(),os:`${te()}-${se()}`,cli_version:We})})}catch(r){return{ok:!1,reason:`Could not reach the Klaudius license server (${r instanceof Error?r.message:"unknown"}). Check your internet connection or try again later.`}}let c;try{c=await l.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${l.status}).`}}return c.ok?{ok:!0,tier:c.tier??"core"}:{ok:!1,reason:c.reason??`License rejected (HTTP ${l.status}).`}}function b(){let e=[ee(),Fe().username,te(),se()].join("|");return Be("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Ye}from"fs/promises";import{join as ze}from"path";async function M(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: ${s.message}`}}}async function ne(e){let s;try{s=await Ye(ze(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(n){return{ok:!1,message:`Could not read scripts/schema.sql: ${n.message}`}}try{let n=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(n.ok)return{ok:!0};let t=await n.text();return t.includes("already exists")||t.includes('relation "clients" already exists')||t.includes("duplicate")?(i.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${n.status}): ${t.slice(0,300)}`}}catch(n){return{ok:!1,message:`Schema apply failed: ${n.message}`}}}async function re(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 n=await s.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(s){return{ok:!1,message:`Could not reach Vercel: ${s.message}`}}}async function ae(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 n={};try{n=await s.json()}catch{}let t=n.error?.message??"",a=n.error?.status??"";return s.status===400&&(a==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(t))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:s.status===401||s.status===403?{ok:!1,message:t||`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}${t?`: ${t}`:""}.`}}catch(s){return{ok:!1,message:`Could not reach Google: ${s.message}`}}}import Xe from"nodemailer";import{ImapFlow as qe}from"imapflow";async function le(e){let s=Xe.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(t){return{ok:!1,failedAt:"smtp",message:oe(t,"SMTP")}}finally{s.close()}let n=new qe({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1});try{await n.connect(),await n.logout()}catch(t){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:oe(t,"IMAP")}}return{ok:!0}}function oe(e,s){let n=e instanceof Error?e.message:String(e),t=n.toLowerCase();return t.includes("invalid credentials")||t.includes("authentication failed")||t.includes("auth failed")||t.includes("login failed")?`${s} rejected the credentials. Most common causes:
13
+ `+E.bold(E.cyan(e))),detail:e=>console.log(E.dim(" "+e))};var Ve="https://klaudius.dev",Ge="/api/licenses/validate",We="0.5.1";async function ie(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(),t=(process.env.KLAUDIUS_API_URL??Ve).replace(/\/$/,"")+Ge,a=b(),l;try{l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:s,machine_id:a,hostname:ee(),os:`${te()}-${se()}`,cli_version:We})})}catch(r){return{ok:!1,reason:`Could not reach the Klaudius license server (${r instanceof Error?r.message:"unknown"}). Check your internet connection or try again later.`}}let c;try{c=await l.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${l.status}).`}}return c.ok?{ok:!0,tier:c.tier??"core"}:{ok:!1,reason:c.reason??`License rejected (HTTP ${l.status}).`}}function b(){let e=[ee(),Fe().username,te(),se()].join("|");return Be("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Ye}from"fs/promises";import{join as ze}from"path";async function M(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: ${s.message}`}}}async function ne(e){let s;try{s=await Ye(ze(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(n){return{ok:!1,message:`Could not read scripts/schema.sql: ${n.message}`}}try{let n=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(n.ok)return{ok:!0};let t=await n.text();return t.includes("already exists")||t.includes('relation "clients" already exists')||t.includes("duplicate")?(i.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${n.status}): ${t.slice(0,300)}`}}catch(n){return{ok:!1,message:`Schema apply failed: ${n.message}`}}}async function re(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 n=await s.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(s){return{ok:!1,message:`Could not reach Vercel: ${s.message}`}}}async function ae(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 n={};try{n=await s.json()}catch{}let t=n.error?.message??"",a=n.error?.status??"";return s.status===400&&(a==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(t))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:s.status===401||s.status===403?{ok:!1,message:t||`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}${t?`: ${t}`:""}.`}}catch(s){return{ok:!1,message:`Could not reach Google: ${s.message}`}}}import Xe from"nodemailer";import{ImapFlow as qe}from"imapflow";async function le(e){let s=Xe.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(t){return{ok:!1,failedAt:"smtp",message:oe(t,"SMTP")}}finally{s.close()}let n=new qe({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1});try{await n.connect(),await n.logout()}catch(t){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:oe(t,"IMAP")}}return{ok:!0}}function oe(e,s){let n=e instanceof Error?e.message:String(e),t=n.toLowerCase();return t.includes("invalid credentials")||t.includes("authentication failed")||t.includes("auth failed")||t.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.`:t.includes("etimedout")||t.includes("timeout")?`${s} server didn't respond in time. Check the host/port, or your network.`:t.includes("enotfound")||t.includes("getaddrinfo")?`${s} host could not be resolved. Check the host setting.`:`${s} check failed: ${n}`}async function ce(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`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let t=await fetch(s,{headers:{Authorization:`Basic ${n}`}});if(t.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!t.ok)return{ok:!1,message:`Twilio API returned HTTP ${t.status}. Try again or check status.twilio.com.`};let a=await t.json();return a.status&&a.status!=="active"?{ok:!1,message:`Twilio account is in '${a.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:a.friendly_name}}catch(t){return{ok:!1,message:`Could not reach Twilio: ${t.message}`}}}import{spawn as Je}from"child_process";async function ue(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 n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,t=await Qe(n);if(t.code===0)return{ok:!0};let a=t.stderr.toLowerCase();return a.includes("can't get application")||a.includes("isn't running")||a.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:a.includes("(-1728)")||a.includes("not found")||a.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:a.includes("(-1719)")||a.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${t.stderr.trim()||`exit code ${t.code}`}`}}function Qe(e){return new Promise(s=>{let n=Je("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),t="";n.stderr.on("data",a=>{t+=a.toString()}),n.on("close",a=>s({code:a??1,stderr:t})),n.on("error",a=>s({code:1,stderr:a.message}))})}import{spawn as me}from"child_process";function pe(e,s,n){return new Promise(t=>{let a=me(e,s,{cwd:n.cwd,stdio:n.inherit!==!1?"inherit":"pipe",shell:!1});a.on("close",l=>t(l??1)),a.on("error",()=>t(1))})}function de(e,s,n){return new Promise(t=>{let a=me(e,s,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),l="",c="";a.stdout?.on("data",r=>{l+=r.toString()}),a.stderr?.on("data",r=>{c+=r.toString()}),a.on("close",r=>t({code:r??1,stdout:l,stderr:c})),a.on("error",r=>t({code:1,stdout:l,stderr:c+r.message}))})}async function Ze(e){let s=["supabase","python-dotenv","requests","httpx","Pillow"],n=["install","--quiet","--user"],t=await de("pip3",[...n,"--break-system-packages",...s],{cwd:e});return t.code!==0&&/no such option:.*break-system-packages/i.test(t.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),t=await de("pip3",[...n,...s],{cwd:e})),t.code!==0?(t.stderr.trim()&&process.stderr.write(t.stderr),t.stdout.trim()&&process.stdout.write(t.stdout),"failed"):"ok"}async function fe(e){let s={npm:"skipped",pip:"skipped",playwright:"skipped"};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let n=await pe("npm",["install"],{cwd:e});s.npm=n===0?"ok":"failed",i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)..."),s.pip=await Ze(e),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let t=await pe("npx",["playwright","install","chromium"],{cwd:e});return s.playwright=t===0?"ok":"failed",s}async function ye(e){let s=e.target??".",n=it(s)?s:st(process.cwd(),s),t=await nt(n);if(t.kind==="occupied"){let u=s===".";i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${t.entries.slice(0,5).join(", ")}${t.entries.length>5?`, \u2026 (+${t.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(` ${m.cyan("npx klaudius init my-agency")}`),i.blank(),i.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${m.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(` ${m.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 at(e.license),l=d.spinner();l.start("Validating license");let c=await ie(a);c.ok||(l.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)),l.stop(`License valid (${c.tier??"core"} tier)`);let r,h=!1;if(t.kind==="partial")if(await rt(n)==="resume"){let o=await he(t.envPath,"utf-8"),p=K(A(o));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,h=!0):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await w())}else{let o=await he(t.envPath,"utf-8"),p=K(A(o));r=await w(p??{})}else r=await w();for(r.licenseKey=a,await S(n,r),h||(i.success("Saved .env"),i.success("Saved .mcp.json")),i.blank();;){let u=d.spinner();u.start("Validating Supabase credentials");let o=await M({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(o.ok){u.stop("Supabase credentials accepted");break}u.stop(o.message??"Supabase check failed",2);let p=o.message??"Supabase check failed";i.blank(),i.warn("Bouncing you back into the Supabase section so you can fix it in place."),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await w(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
16
+ \u2022 2FA is required but no app-specific password was generated.`:t.includes("etimedout")||t.includes("timeout")?`${s} server didn't respond in time. Check the host/port, or your network.`:t.includes("enotfound")||t.includes("getaddrinfo")?`${s} host could not be resolved. Check the host setting.`:`${s} check failed: ${n}`}async function ce(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`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let t=await fetch(s,{headers:{Authorization:`Basic ${n}`}});if(t.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!t.ok)return{ok:!1,message:`Twilio API returned HTTP ${t.status}. Try again or check status.twilio.com.`};let a=await t.json();return a.status&&a.status!=="active"?{ok:!1,message:`Twilio account is in '${a.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:a.friendly_name}}catch(t){return{ok:!1,message:`Could not reach Twilio: ${t.message}`}}}import{spawn as Je}from"child_process";async function ue(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 n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,t=await Qe(n);if(t.code===0)return{ok:!0};let a=t.stderr.toLowerCase();return a.includes("can't get application")||a.includes("isn't running")||a.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:a.includes("(-1728)")||a.includes("not found")||a.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:a.includes("(-1719)")||a.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${t.stderr.trim()||`exit code ${t.code}`}`}}function Qe(e){return new Promise(s=>{let n=Je("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),t="";n.stderr.on("data",a=>{t+=a.toString()}),n.on("close",a=>s({code:a??1,stderr:t})),n.on("error",a=>s({code:1,stderr:a.message}))})}import{spawn as me}from"child_process";function pe(e,s,n){return new Promise(t=>{let a=me(e,s,{cwd:n.cwd,stdio:n.inherit!==!1?"inherit":"pipe",shell:!1});a.on("close",l=>t(l??1)),a.on("error",()=>t(1))})}function de(e,s,n){return new Promise(t=>{let a=me(e,s,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),l="",c="";a.stdout?.on("data",r=>{l+=r.toString()}),a.stderr?.on("data",r=>{c+=r.toString()}),a.on("close",r=>t({code:r??1,stdout:l,stderr:c})),a.on("error",r=>t({code:1,stdout:l,stderr:c+r.message}))})}async function Ze(e){let s=["supabase","python-dotenv","requests","httpx","Pillow"],n=["install","--quiet","--user"],t=await de("pip3",[...n,"--break-system-packages",...s],{cwd:e});return t.code!==0&&/no such option:.*break-system-packages/i.test(t.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),t=await de("pip3",[...n,...s],{cwd:e})),t.code!==0?(t.stderr.trim()&&process.stderr.write(t.stderr),t.stdout.trim()&&process.stdout.write(t.stdout),"failed"):"ok"}async function fe(e){let s={npm:"skipped",pip:"skipped",playwright:"skipped"};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let n=await pe("npm",["install"],{cwd:e});s.npm=n===0?"ok":"failed",i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)..."),s.pip=await Ze(e),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let t=await pe("npx",["playwright","install","chromium"],{cwd:e});return s.playwright=t===0?"ok":"failed",s}async function we(e){let s=e.target??".",n=it(s)?s:st(process.cwd(),s),t=await nt(n);if(t.kind==="occupied"){let u=s===".";i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${t.entries.slice(0,5).join(", ")}${t.entries.length>5?`, \u2026 (+${t.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(` ${m.cyan("npx klaudius init my-agency")}`),i.blank(),i.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${m.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(` ${m.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 at(e.license),l=d.spinner();l.start("Validating license");let c=await ie(a);c.ok||(l.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)),l.stop(`License valid (${c.tier??"core"} tier)`);let r,h=!1;if(t.kind==="partial")if(await rt(n)==="resume"){let o=await he(t.envPath,"utf-8"),p=K(A(o));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,h=!0):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await y())}else{let o=await he(t.envPath,"utf-8"),p=K(A(o));r=await y(p??{})}else r=await y();for(r.licenseKey=a,await S(n,r),h||(i.success("Saved .env"),i.success("Saved .mcp.json")),i.blank();;){let u=d.spinner();u.start("Validating Supabase credentials");let o=await M({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(o.ok){u.stop("Supabase credentials accepted");break}u.stop(o.message??"Supabase check failed",2);let p=o.message??"Supabase check failed";i.blank(),i.warn("Bouncing you back into the Supabase section so you can fix it in place."),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await y(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
17
17
  ${p}
18
18
 
19
19
  Re-enter the URL, secret key, or PAT below. Press Enter on any
20
- field to keep what's already there.`}),await S(n,r)}for(i.blank();;){let u=d.spinner();u.start("Validating Vercel token");let o=await re(r.vercelToken);if(o.ok){u.stop(o.username?`Vercel token accepted (signed in as ${o.username})`:"Vercel token accepted");break}u.stop(o.message??"Vercel check failed",2);let p=o.message??"Vercel check failed";i.blank(),i.warn("Bouncing you back into the Vercel section so you can fix it in place."),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await w(r,{onlySection:"vercel",banner:`Vercel rejected the token:
20
+ field to keep what's already there.`}),await S(n,r)}for(i.blank();;){let u=d.spinner();u.start("Validating Vercel token");let o=await re(r.vercelToken);if(o.ok){u.stop(o.username?`Vercel token accepted (signed in as ${o.username})`:"Vercel token accepted");break}u.stop(o.message??"Vercel check failed",2);let p=o.message??"Vercel check failed";i.blank(),i.warn("Bouncing you back into the Vercel section so you can fix it in place."),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await y(r,{onlySection:"vercel",banner:`Vercel rejected the token:
21
21
  ${p}
22
22
 
23
23
  Generate a new token at https://vercel.com/account/tokens and
24
- paste it below. Press Enter to keep the current value.`}),await S(n,r)}for(i.blank();;){let u=d.spinner();u.start("Validating Google Places API key");let o=await ae(r.googlePlacesApiKey??"");if(o.ok){u.stop("Google Places API key accepted");break}u.stop(o.message??"Google Places check failed",2);let p=o.message??"Google Places check failed";i.blank(),i.warn("Bouncing you back into the Google Places section so you can fix it in place."),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await w(r,{onlySection:"google-places",banner:`Google rejected the key:
24
+ paste it below. Press Enter to keep the current value.`}),await S(n,r)}for(i.blank();;){let u=d.spinner();u.start("Validating Google Places API key");let o=await ae(r.googlePlacesApiKey??"");if(o.ok){u.stop("Google Places API key accepted");break}u.stop(o.message??"Google Places check failed",2);let p=o.message??"Google Places check failed";i.blank(),i.warn("Bouncing you back into the Google Places section so you can fix it in place."),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await y(r,{onlySection:"google-places",banner:`Google rejected the key:
25
25
  ${p}
26
26
 
27
27
  Generate (or fix) the key at https://console.cloud.google.com
28
- and paste it below. Press Enter to keep the current value.`}),await S(n,r)}if(r.outreachEnabled&&r.outreachChannels?.includes("email")&&r.emailAddress&&r.emailPassword&&r.emailSmtpHost&&r.emailSmtpPort&&r.emailImapHost&&r.emailImapPort)for(i.blank();;){let u=d.spinner();u.start("Validating email credentials (SMTP + IMAP)");let o=await le({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort});if(o.ok){u.stop("Email credentials accepted (SMTP + IMAP)");break}u.stop(o.message??"Email check failed",2);let p=o.message??"Email check failed";i.blank(),i.warn("Bouncing you back into the email section so you can fix it in place."),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await w(r,{onlySection:"email",banner:`${o.failedAt==="imap"?"IMAP":"SMTP"} check failed:
28
+ and paste it below. Press Enter to keep the current value.`}),await S(n,r)}if(r.outreachEnabled&&r.outreachChannels?.includes("email")&&r.emailAddress&&r.emailPassword&&r.emailSmtpHost&&r.emailSmtpPort&&r.emailImapHost&&r.emailImapPort)for(i.blank();;){let u=d.spinner();u.start("Validating email credentials (SMTP + IMAP)");let o=await le({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort});if(o.ok){u.stop("Email credentials accepted (SMTP + IMAP)");break}u.stop(o.message??"Email check failed",2);let p=o.message??"Email check failed";i.blank(),i.warn("Bouncing you back into the email section so you can fix it in place."),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await y(r,{onlySection:"email",banner:`${o.failedAt==="imap"?"IMAP":"SMTP"} check failed:
29
29
  ${p}
30
30
 
31
31
  Re-enter the email address, app password, or host details below.
32
- Press Enter on any field to keep its current value.`}),await S(n,r)}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="twilio"&&r.twilioAccountSid&&r.twilioAuthToken)for(i.blank();;){let u=d.spinner();u.start("Validating Twilio credentials");let o=await ce({accountSid:r.twilioAccountSid,authToken:r.twilioAuthToken});if(o.ok){u.stop(o.friendlyName?`Twilio credentials accepted (${o.friendlyName})`:"Twilio credentials accepted");break}u.stop(o.message??"Twilio check failed",2);let p=o.message??"Twilio check failed";i.blank(),i.warn("Bouncing you back into the SMS section so you can fix it in place."),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await w(r,{onlySection:"sms",banner:`Twilio rejected the credentials:
32
+ Press Enter on any field to keep its current value.`}),await S(n,r)}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="twilio"&&r.twilioAccountSid&&r.twilioAuthToken)for(i.blank();;){let u=d.spinner();u.start("Validating Twilio credentials");let o=await ce({accountSid:r.twilioAccountSid,authToken:r.twilioAuthToken});if(o.ok){u.stop(o.friendlyName?`Twilio credentials accepted (${o.friendlyName})`:"Twilio credentials accepted");break}u.stop(o.message??"Twilio check failed",2);let p=o.message??"Twilio check failed";i.blank(),i.warn("Bouncing you back into the SMS section so you can fix it in place."),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await y(r,{onlySection:"sms",banner:`Twilio rejected the credentials:
33
33
  ${p}
34
34
 
35
35
  Re-enter the Account SID or Auth Token below.
36
- Press Enter on any field to keep its current value.`}),await S(n,r)}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="imessage"&&r.testPhone)for(i.blank();;){let u=d.spinner();u.start("Validating iMessage setup (sending a test ping)");let o=await ue({testPhone:r.testPhone});if(o.ok){u.stop("iMessage dispatched (check your phone for the test ping)");break}u.stop(o.message??"iMessage check failed",2);let p=o.message??"iMessage check failed";i.blank(),i.warn("Bouncing you back into the SMS section so you can fix it in place."),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await w(r,{onlySection:"sms",banner:`iMessage check failed:
36
+ Press Enter on any field to keep its current value.`}),await S(n,r)}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="imessage"&&r.testPhone)for(i.blank();;){let u=d.spinner();u.start("Validating iMessage setup (sending a test ping)");let o=await ue({testPhone:r.testPhone});if(o.ok){u.stop("iMessage dispatched (check your phone for the test ping)");break}u.stop(o.message??"iMessage check failed",2);let p=o.message??"iMessage check failed";i.blank(),i.warn("Bouncing you back into the SMS section so you can fix it in place."),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await y(r,{onlySection:"sms",banner:`iMessage check failed:
37
37
  ${p}
38
38
 
39
39
  Either fix the underlying issue (sign in to Messages.app, configure
40
40
  Text Message Forwarding) and press Enter through, or change SMS
41
- provider to Twilio.`}),await S(n,r)}if(r.telegramBotToken&&r.telegramChatId)for(i.blank();;){let u=d.spinner();u.start("Validating Telegram bot + chat (sending a test ping)");let o=await G({botToken:r.telegramBotToken,chatId:r.telegramChatId});if(o.ok){u.stop(o.botHandle?`Telegram bot ${o.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered");break}u.stop(o.message??"Telegram check failed",2);let p=o.message??"Telegram check failed";i.blank(),i.warn("Bouncing you back into the Telegram section so you can fix it in place."),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await w(r,{onlySection:"telegram",banner:`Telegram check failed:
41
+ provider to Twilio.`}),await S(n,r)}if(r.telegramBotToken&&r.telegramChatId)for(i.blank();;){let u=d.spinner();u.start("Validating Telegram bot + chat (sending a test ping)");let o=await G({botToken:r.telegramBotToken,chatId:r.telegramChatId});if(o.ok){u.stop(o.botHandle?`Telegram bot ${o.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered");break}u.stop(o.message??"Telegram check failed",2);let p=o.message??"Telegram check failed";i.blank(),i.warn("Bouncing you back into the Telegram section so you can fix it in place."),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await y(r,{onlySection:"telegram",banner:`Telegram check failed:
42
42
  ${p}
43
43
 
44
44
  Re-enter the bot token or chat_id below.
45
- Press Enter on any field to keep its current value.`}),await S(n,r)}i.blank();let f=d.spinner();f.start("Downloading Klaudius template");let k;try{k=(await O({licenseKey:a,machineId:b(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,destDir:n})).filesExtracted,f.stop(`Downloaded ${k} files into ${m.bold(n)}`)}catch(u){f.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(x(n,"clients"),{recursive:!0});let g=await W(n);if(await L(n,Z("0.1.0",g)),i.success("Wrote .klaudius/manifest.json"),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=d.spinner();u.start("Applying schema to Supabase");let o=await ne({projectRoot:n,pat:r.supabasePat,projectRef:r.supabaseProjectRef});o.ok?u.stop("Schema applied (or already present)"):(u.stop(o.message??"Schema apply failed",2),i.warn("Apply scripts/schema.sql manually in your Supabase SQL editor before running the pipeline."))}if(e.skipInstall)i.warn("--skip-install set; you'll need to run npm install + pip install + playwright install yourself.");else{i.blank(),i.heading("Installing dependencies");let u=await fe(n);i.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}`),(u.npm==="failed"||u.pip==="failed"||u.playwright==="failed")&&i.warn("Some installers failed. You can re-run them manually with `bash setup.sh`.")}i.blank(),d.outro(m.green(m.bold("Project ready."))),console.log(m.dim("Next steps:")),n!==process.cwd()&&console.log(` ${m.cyan(`cd ${e.target}`)}`),console.log(` ${m.cyan("claude")} ${m.dim("# open Claude Code in this project")}`),console.log(` ${m.dim("then ask Claude:")}`),console.log(` ${m.cyan(' "Run the pipeline."')}`),i.blank(),console.log(m.dim("Klaudius ships with sensible defaults for tone, follow-up cadence, pitch")),console.log(m.dim("and more \u2014 but you don't have to live with them. Customise by talking to")),console.log(m.dim("Claude inside this project. Examples you can ask:")),console.log(m.dim(' "Make the outreach more casual."')),console.log(m.dim(' "Change the follow-up cadence to weekly."')),console.log(m.dim(` "Don't pitch businesses with fewer than 5 reviews."`)),console.log(m.dim(' "Use a different opening hook for restaurants."')),console.log(m.dim("Claude knows where to make the change \u2014 no config files to edit by hand.")),i.blank()}async function S(e,s){await we(e,{recursive:!0}),await ge(x(e,".env"),C(s),"utf-8"),await ge(x(e,".mcp.json"),v(s),"utf-8")}async function nt(e){try{(await tt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let s=await et(e),n=s.filter(r=>!r.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let t=new Set([".env",".mcp.json"]),a=n.every(r=>t.has(r)),l=n.includes(".env"),c=s.includes(".klaudius");return a&&l&&!c?{kind:"partial",envPath:x(e,".env")}:{kind:"occupied",entries:n}}async function rt(e){i.blank(),i.warn(`Found a partial setup at ${m.bold(e)}.`),i.detail(`A previous init wrote ${m.bold(".env")} but didn't finish scaffolding.`),i.blank();let s=await d.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 d.isCancel(s)&&(d.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),s}async function at(e){if(e&&e.trim().length>0)return e;d.intro("Klaudius");let s=await d.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return d.isCancel(s)&&(d.cancel("Setup cancelled. No files written."),process.exit(0)),s}import{readFile as ot,writeFile as ke,access as lt}from"fs/promises";import{join as D}from"path";import*as $ from"@clack/prompts";import ct from"picocolors";async function Ee(e){let s=e.projectRoot??process.cwd(),n=D(s,".env"),t=D(s,".mcp.json");try{await lt(D(s,".klaudius","manifest.json"))}catch{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 a={};try{let r=await ot(n,"utf-8");a=A(r)}catch{i.warn("No .env found. Starting from an empty configuration.")}let l=z(a);$.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let c=await w(l);if(c.supabaseUrl!==a.SUPABASE_URL||c.supabaseServiceKey!==a.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let r=await M({url:c.supabaseUrl,serviceKey:c.supabaseServiceKey});r.ok||(i.error(r.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}await ke(n,C(c),"utf-8"),i.success("Updated .env"),await ke(t,v(c),"utf-8"),i.success("Updated .mcp.json"),i.blank(),$.outro(ct.green("Configuration updated."))}import{copyFile as Se,mkdir as Pe,readdir as ut,readFile as pt,rm as N,writeFile as Ae,access as dt}from"fs/promises";import{dirname as _e,join as y,relative as mt}from"path";import{tmpdir as ft}from"os";import*as I from"@clack/prompts";import H from"picocolors";var j="0.4.0";async function Te(e){let s=e.projectRoot??process.cwd(),n=await Q(s);n||(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 t,a=y(s,".env");try{let o=await pt(a,"utf-8"),p=A(o);t=p.KLAUDIUS_LICENSE_KEY??"",t||(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 P=Y(o,p,[{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."}]);P!==null&&(await Ae(a,P,"utf-8"),i.detail("Backfilled new env keys: PRICING_TERMS"))}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)}I.intro(`Update from ${n.templateVersion} \u2192 ${j}`);let l=y(ft(),`klaudius-update-${process.pid}-${Date.now()}`),c;try{i.heading("Downloading the latest Klaudius template");let o=await O({licenseKey:t,machineId:b(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,destDir:l});i.success(`Fetched ${o.filesExtracted} canonical files`),c=l}catch(o){i.error(o.message),i.detail("Update aborted. Your project is unchanged."),await N(l,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let r=await ht(c,s,n),h=r.filter(o=>o.state==="new"),f=r.filter(o=>o.state==="clean-update"),k=r.filter(o=>o.state==="user-only"),g=r.filter(o=>o.state==="conflict"),u=r.filter(o=>o.state==="no-change");if(i.blank(),i.heading("Change summary"),i.detail(`${T(u.length,"file")} unchanged`),i.detail(`${T(h.length,"new file")}`),i.detail(`${T(f.length,"file")} updated cleanly (no local edits)`),i.detail(`${T(k.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${T(g.length,"file")} with conflicts (you edited AND we have a new version)`),f.length===0&&h.length===0&&g.length===0){i.blank(),I.outro(H.green("Already up to date.")),await N(l,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let o of[...h,...f]){let p=y(c,o.path),P=y(s,o.path);await Pe(_e(P),{recursive:!0}),await Se(p,P),n.files[o.path]=o.canonicalHash}if(i.success(`Wrote ${T(h.length+f.length,"file")}`),g.length>0){i.blank(),i.heading(`${g.length} conflict(s) need resolution`);let o=y(s,".klaudius","incoming");try{await N(o,{recursive:!0,force:!0})}catch{}for(let p of g){let P=y(c,p.path),B=y(o,p.path);await Pe(_e(B),{recursive:!0}),await Se(P,B)}await Ae(y(s,".klaudius","conflicts.md"),gt(g,n.templateVersion,j),"utf-8"),i.detail("Staged canonical versions to .klaudius/incoming/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),g.length===0&&(n.templateVersion=j),await L(s,n),i.blank(),g.length===0?I.outro(H.green("Update complete.")):I.outro(H.yellow(`${g.length} conflict(s) staged. Open Claude Code in this project and ask:
46
- "Run /resolve-conflicts"`)),await N(l,{recursive:!0,force:!0}).catch(()=>{})}async function ht(e,s,n){let t=await Ie(e),a=[];for(let l of t){let c=await U(y(e,l)),r=n.files[l],h=y(s,l),f;try{await dt(h),f=await U(h)}catch{a.push({path:l,state:"new",canonicalHash:c,manifestHash:r});continue}c===r?f===r?a.push({path:l,state:"no-change",canonicalHash:c,localHash:f,manifestHash:r}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:f,manifestHash:r}):f===r?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:f,manifestHash:r}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:f,manifestHash:r})}return a}function T(e,s){return`${e} ${s}${e===1?"":"s"}`}async function Ie(e,s=e){let n=await ut(e,{withFileTypes:!0}),t=[];for(let a of n){let l=y(e,a.name);a.isDirectory()?t.push(...await Ie(l,s)):a.isFile()&&t.push(mt(s,l))}return t}function gt(e,s,n){let t=[];t.push("# Update Conflicts"),t.push(""),t.push(`Generated by \`npx klaudius update\` on ${new Date().toISOString()}.`),t.push(`Updating from canonical version **${s}** to **${n}**.`),t.push(""),t.push(`${e.length} file${e.length===1?"":"s"} ha${e.length===1?"s":"ve"} BOTH local edits AND upstream changes.`),t.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, or merge."),t.push(""),t.push("---"),t.push("");for(let a of e)t.push(`## ${a.path}`),t.push(""),t.push(`- Your version (with your local edits): \`${a.path}\``),t.push(`- New canonical version: \`.klaudius/incoming/${a.path}\``),t.push(`- Hash at last install/update: \`${(a.manifestHash??"(none)").slice(0,16)}\``),t.push(`- Your local hash now: \`${(a.localHash??"(missing)").slice(0,16)}\``),t.push(`- New canonical hash: \`${a.canonicalHash.slice(0,16)}\``),t.push(""),t.push("**Resolution options for the SKILL to walk through:**"),t.push(""),t.push("1. Keep mine \u2014 discard the new canonical changes"),t.push("2. Take canonical \u2014 overwrite my edits with the new version"),t.push("3. Merge \u2014 review both side-by-side and produce a combined version"),t.push(""),t.push("---"),t.push("");return t.join(`
47
- `)}var yt="0.4.0",R=new wt;R.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(yt);R.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(n){console.error("init failed:",n.message),process.exit(1)}});R.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await Ee({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});R.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await Te({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});R.parse(process.argv);
45
+ Press Enter on any field to keep its current value.`}),await S(n,r)}i.blank();let f=d.spinner();f.start("Downloading Klaudius template");let k;try{k=(await O({licenseKey:a,machineId:b(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,destDir:n})).filesExtracted,f.stop(`Downloaded ${k} files into ${m.bold(n)}`)}catch(u){f.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 ye(x(n,"clients"),{recursive:!0});let g=await W(n);if(await L(n,Z("0.1.0",g)),i.success("Wrote .klaudius/manifest.json"),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=d.spinner();u.start("Applying schema to Supabase");let o=await ne({projectRoot:n,pat:r.supabasePat,projectRef:r.supabaseProjectRef});o.ok?u.stop("Schema applied (or already present)"):(u.stop(o.message??"Schema apply failed",2),i.warn("Apply scripts/schema.sql manually in your Supabase SQL editor before running the pipeline."))}if(e.skipInstall)i.warn("--skip-install set; you'll need to run npm install + pip install + playwright install yourself.");else{i.blank(),i.heading("Installing dependencies");let u=await fe(n);i.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}`),(u.npm==="failed"||u.pip==="failed"||u.playwright==="failed")&&i.warn("Some installers failed. You can re-run them manually with `bash setup.sh`.")}i.blank(),d.outro(m.green(m.bold("Project ready."))),console.log(m.dim("Next steps:")),n!==process.cwd()&&console.log(` ${m.cyan(`cd ${e.target}`)}`),console.log(` ${m.cyan("claude")} ${m.dim("# open Claude Code in this project")}`),console.log(` ${m.dim("then ask Claude:")}`),console.log(` ${m.cyan(' "Run the pipeline."')}`),i.blank(),console.log(m.dim("Klaudius ships with sensible defaults for tone, follow-up cadence, pitch")),console.log(m.dim("and more \u2014 but you don't have to live with them. Customise by talking to")),console.log(m.dim("Claude inside this project. Examples you can ask:")),console.log(m.dim(' "Make the outreach more casual."')),console.log(m.dim(' "Change the follow-up cadence to weekly."')),console.log(m.dim(` "Don't pitch businesses with fewer than 5 reviews."`)),console.log(m.dim(' "Use a different opening hook for restaurants."')),console.log(m.dim("Claude knows where to make the change \u2014 no config files to edit by hand.")),i.blank()}async function S(e,s){await ye(e,{recursive:!0}),await ge(x(e,".env"),C(s),"utf-8"),await ge(x(e,".mcp.json"),v(s),"utf-8")}async function nt(e){try{(await tt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let s=await et(e),n=s.filter(r=>!r.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let t=new Set([".env",".mcp.json"]),a=n.every(r=>t.has(r)),l=n.includes(".env"),c=s.includes(".klaudius");return a&&l&&!c?{kind:"partial",envPath:x(e,".env")}:{kind:"occupied",entries:n}}async function rt(e){i.blank(),i.warn(`Found a partial setup at ${m.bold(e)}.`),i.detail(`A previous init wrote ${m.bold(".env")} but didn't finish scaffolding.`),i.blank();let s=await d.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 d.isCancel(s)&&(d.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),s}async function at(e){if(e&&e.trim().length>0)return e;d.intro("Klaudius");let s=await d.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return d.isCancel(s)&&(d.cancel("Setup cancelled. No files written."),process.exit(0)),s}import{readFile as ot,writeFile as ke,access as lt}from"fs/promises";import{join as D}from"path";import*as $ from"@clack/prompts";import ct from"picocolors";async function Ee(e){let s=e.projectRoot??process.cwd(),n=D(s,".env"),t=D(s,".mcp.json");try{await lt(D(s,".klaudius","manifest.json"))}catch{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 a={};try{let r=await ot(n,"utf-8");a=A(r)}catch{i.warn("No .env found. Starting from an empty configuration.")}let l=z(a);$.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let c=await y(l);if(c.supabaseUrl!==a.SUPABASE_URL||c.supabaseServiceKey!==a.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let r=await M({url:c.supabaseUrl,serviceKey:c.supabaseServiceKey});r.ok||(i.error(r.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}await ke(n,C(c),"utf-8"),i.success("Updated .env"),await ke(t,v(c),"utf-8"),i.success("Updated .mcp.json"),i.blank(),$.outro(ct.green("Configuration updated."))}import{copyFile as Se,mkdir as Pe,readdir as ut,readFile as pt,rm as N,writeFile as Ae,access as dt}from"fs/promises";import{dirname as _e,join as w,relative as mt}from"path";import{tmpdir as ft}from"os";import*as T from"@clack/prompts";import H from"picocolors";var j="0.5.1";async function Ie(e){let s=e.projectRoot??process.cwd(),n=await Q(s);n||(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 t,a=w(s,".env");try{let o=await pt(a,"utf-8"),p=A(o);t=p.KLAUDIUS_LICENSE_KEY??"",t||(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 P=Y(o,p,[{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."}]);P!==null&&(await Ae(a,P,"utf-8"),i.detail("Backfilled new env keys: PRICING_TERMS"))}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)}T.intro(`Update from ${n.templateVersion} \u2192 ${j}`);let l=w(ft(),`klaudius-update-${process.pid}-${Date.now()}`),c;try{i.heading("Downloading the latest Klaudius template");let o=await O({licenseKey:t,machineId:b(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,destDir:l});i.success(`Fetched ${o.filesExtracted} canonical files`),c=l}catch(o){i.error(o.message),i.detail("Update aborted. Your project is unchanged."),await N(l,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let r=await ht(c,s,n),h=r.filter(o=>o.state==="new"),f=r.filter(o=>o.state==="clean-update"),k=r.filter(o=>o.state==="user-only"),g=r.filter(o=>o.state==="conflict"),u=r.filter(o=>o.state==="no-change");if(i.blank(),i.heading("Change summary"),i.detail(`${I(u.length,"file")} unchanged`),i.detail(`${I(h.length,"new file")}`),i.detail(`${I(f.length,"file")} updated cleanly (no local edits)`),i.detail(`${I(k.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${I(g.length,"file")} with conflicts (you edited AND we have a new version)`),f.length===0&&h.length===0&&g.length===0){i.blank(),T.outro(H.green("Already up to date.")),await N(l,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let o of[...h,...f]){let p=w(c,o.path),P=w(s,o.path);await Pe(_e(P),{recursive:!0}),await Se(p,P),n.files[o.path]=o.canonicalHash}if(i.success(`Wrote ${I(h.length+f.length,"file")}`),g.length>0){i.blank(),i.heading(`${g.length} conflict(s) need resolution`);let o=w(s,".klaudius","incoming");try{await N(o,{recursive:!0,force:!0})}catch{}for(let p of g){let P=w(c,p.path),B=w(o,p.path);await Pe(_e(B),{recursive:!0}),await Se(P,B)}await Ae(w(s,".klaudius","conflicts.md"),gt(g,n.templateVersion,j),"utf-8"),i.detail("Staged canonical versions to .klaudius/incoming/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),g.length===0&&(n.templateVersion=j),await L(s,n),i.blank(),g.length===0?T.outro(H.green("Update complete.")):T.outro(H.yellow(`${g.length} conflict(s) staged. Open Claude Code in this project and ask:
46
+ "Run /resolve-conflicts"`)),await N(l,{recursive:!0,force:!0}).catch(()=>{})}async function ht(e,s,n){let t=await Te(e),a=[];for(let l of t){let c=await U(w(e,l)),r=n.files[l],h=w(s,l),f;try{await dt(h),f=await U(h)}catch{a.push({path:l,state:"new",canonicalHash:c,manifestHash:r});continue}c===r?f===r?a.push({path:l,state:"no-change",canonicalHash:c,localHash:f,manifestHash:r}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:f,manifestHash:r}):f===r?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:f,manifestHash:r}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:f,manifestHash:r})}return a}function I(e,s){return`${e} ${s}${e===1?"":"s"}`}async function Te(e,s=e){let n=await ut(e,{withFileTypes:!0}),t=[];for(let a of n){let l=w(e,a.name);a.isDirectory()?t.push(...await Te(l,s)):a.isFile()&&t.push(mt(s,l))}return t}function gt(e,s,n){let t=[];t.push("# Update Conflicts"),t.push(""),t.push(`Generated by \`npx klaudius update\` on ${new Date().toISOString()}.`),t.push(`Updating from canonical version **${s}** to **${n}**.`),t.push(""),t.push(`${e.length} file${e.length===1?"":"s"} ha${e.length===1?"s":"ve"} BOTH local edits AND upstream changes.`),t.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, or merge."),t.push(""),t.push("---"),t.push("");for(let a of e)t.push(`## ${a.path}`),t.push(""),t.push(`- Your version (with your local edits): \`${a.path}\``),t.push(`- New canonical version: \`.klaudius/incoming/${a.path}\``),t.push(`- Hash at last install/update: \`${(a.manifestHash??"(none)").slice(0,16)}\``),t.push(`- Your local hash now: \`${(a.localHash??"(missing)").slice(0,16)}\``),t.push(`- New canonical hash: \`${a.canonicalHash.slice(0,16)}\``),t.push(""),t.push("**Resolution options for the SKILL to walk through:**"),t.push(""),t.push("1. Keep mine \u2014 discard the new canonical changes"),t.push("2. Take canonical \u2014 overwrite my edits with the new version"),t.push("3. Merge \u2014 review both side-by-side and produce a combined version"),t.push(""),t.push("---"),t.push("");return t.join(`
47
+ `)}var wt="0.5.1",R=new yt;R.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(wt);R.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 we({target:e,license:s.license,skipInstall:!!s.skipInstall,skipSchema:!!s.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});R.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await Ee({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});R.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await Ie({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});R.parse(process.argv);
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "klaudius",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code (find, build, deploy, outreach end-to-end).",
5
5
  "homepage": "https://klaudius.dev",
6
6
  "bugs": {
7
7
  "email": "hello@klaudius.dev"
8
8
  },
9
- "author": "Cloudbot Limited",
9
+ "author": "Klaudius",
10
10
  "license": "UNLICENSED",
11
11
  "type": "module",
12
12
  "bin": {