klaudius 0.12.2 → 0.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -18,12 +18,12 @@ You can run the pipeline against more than one country from the same
|
|
|
18
18
|
install (\`/find Barcelona\` from a UK install works fine), but
|
|
19
19
|
starting with one market makes it easier to learn that market's
|
|
20
20
|
outreach rhythm. You can change this any time via
|
|
21
|
-
\`npx klaudius configure\`.`});let n="__other__",
|
|
21
|
+
\`npx klaudius configure\`.`});let n="__other__",r=[{value:"the United Kingdom",label:"United Kingdom"},{value:"the United States",label:"United States"},{value:"Italy",label:"Italy"},{value:"Spain",label:"Spain"},{value:"France",label:"France"},{value:"Germany",label:"Germany"},{value:"Ireland",label:"Ireland"},{value:"the Netherlands",label:"Netherlands"},{value:"Belgium",label:"Belgium"},{value:"Portugal",label:"Portugal"},{value:"Switzerland",label:"Switzerland"},{value:"Austria",label:"Austria"},{value:"Canada",label:"Canada"},{value:"Australia",label:"Australia"},{value:"New Zealand",label:"New Zealand"},{value:"Mexico",label:"Mexico"},{value:"Brazil",label:"Brazil"},{value:"Sweden",label:"Sweden"},{value:"Poland",label:"Poland"},{value:n,label:"Other (type it in)"}],s=e.country??"",o=r.some(b=>b.value===s),u=await a({type:"select",message:"Which country's businesses will Klaudius search for?",initialValue:o?s:s?n:"the United Kingdom",options:r}),i;u===n?i=await a({type:"text",message:"Type the country name (any common form is fine)",placeholder:"e.g. South Africa, Greece, Brazil",initialValue:o?"":s,validate:b=>b.trim().length===0?"Country is required":void 0,note:{title:"Free-form country",body:`We'll match what you type against our country lookup (covers all
|
|
22
22
|
ISO 3166 sovereign states + common territories like Hong Kong and
|
|
23
23
|
Puerto Rico). If we don't recognise the name, we'll ask you to type
|
|
24
24
|
the 2-letter ISO country code directly on the next prompt \u2014 the
|
|
25
25
|
same code Google Places uses for region biasing. Aliases like 'uk',
|
|
26
|
-
'usa', 'italia', 'maroc' all match.`}}):
|
|
26
|
+
'usa', 'italia', 'maroc' all match.`}}):i=u;let l=te(i),d;l?d=l.code:d=(await a({type:"text",message:`What's the 2-letter ISO country code for ${i}?`,placeholder:"e.g. ID for Indonesia, ZA for South Africa, JO for Jordan",initialValue:e.countryCode??"",validate:b=>{let O=b.trim().toUpperCase();if(!/^[A-Z]{2}$/.test(O))return"Must be exactly 2 letters (ISO 3166-1 alpha-2 format)"},note:{title:`ISO code for ${i}`,body:`We didn't recognise "${i}" in our country lookup, so we need the
|
|
27
27
|
2-letter ISO 3166-1 alpha-2 code directly. Google Places uses this
|
|
28
28
|
for region biasing on every search.
|
|
29
29
|
|
|
@@ -32,8 +32,8 @@ Full list: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
|
|
|
32
32
|
Quick reference for less common markets:
|
|
33
33
|
Indonesia \u2192 ID Vietnam \u2192 VN Thailand \u2192 TH Egypt \u2192 EG
|
|
34
34
|
Kenya \u2192 KE Nigeria \u2192 NG Pakistan \u2192 PK Iran \u2192 IR
|
|
35
|
-
Saudi Arabia \u2192 SA Russia \u2192 RU Ukraine \u2192 UA Israel \u2192 IL`}})).trim().toUpperCase();let
|
|
36
|
-
for ${
|
|
35
|
+
Saudi Arabia \u2192 SA Russia \u2192 RU Ukraine \u2192 UA Israel \u2192 IL`}})).trim().toUpperCase();let w=e.language??l?.language??"English",f=await a({type:"text",message:"What language should outreach + websites be written in?",placeholder:"e.g. Italian, Spanish, English",initialValue:w,validate:b=>b.trim().length===0?"Language is required":void 0,note:{title:"Outreach + website language",body:l?`Defaulting to ${w} (the usual operator-facing language
|
|
36
|
+
for ${i}). Edit this if you'd rather write in something else \u2014
|
|
37
37
|
e.g. an English-speaking operator running on Spain might pick "Spanish"
|
|
38
38
|
to localise everything, or might pick "English" to keep their own voice.
|
|
39
39
|
Klaudius will use this language for every outreach message it sends and
|
|
@@ -47,15 +47,15 @@ site.
|
|
|
47
47
|
Most languages have a 2-letter ISO 639-1 code. A few (Filipino \u2192
|
|
48
48
|
"fil") use the 3-letter ISO 639-3 / BCP 47 code instead.
|
|
49
49
|
|
|
50
|
-
Full list: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes`}})).trim().toLowerCase(),{country:
|
|
50
|
+
Full list: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes`}})).trim().toLowerCase(),{country:l?l.country:i.trim(),countryCode:d,language:A?A.language:f.trim(),languageCode:I}}},Me={id:"pricing",title:"Pricing",isApplicable:()=>!0,execute:async(e,{prompt:a})=>{let t=e.pricingTerms===ie,n=t?"":e.pricing??"$999",r=e.pricingMonthly??(t?e.pricing??"":""),s=await a({type:"text",message:"What's the upfront fee you'll charge clients per site?",placeholder:"e.g. $999, \xA3799, \u20AC899 \u2014 or 0 for monthly-only billing",initialValue:n,note:{title:"Upfront fee",body:`The one-time amount charged when a client signs up. Type 0 (or
|
|
51
51
|
leave blank) if you only want to charge a monthly fee. You can
|
|
52
52
|
also add a recurring monthly fee on the next prompt \u2014 combining
|
|
53
53
|
the two is fine (e.g. $499 upfront + $49/month).
|
|
54
54
|
|
|
55
55
|
Use the currency that matches your clients' region. Klaudius
|
|
56
|
-
uses this string verbatim throughout outreach.`}}),o=await a({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:
|
|
56
|
+
uses this string verbatim throughout outreach.`}}),o=await a({type:"text",message:"What's the monthly fee? (optional \u2014 leave blank for one-off only)",placeholder:"e.g. $49, \xA339, \u20AC45 \u2014 or blank for none",initialValue:r,validate:w=>{if(U(s)&&U(w))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
|
|
57
57
|
a recurring monthly fee \u2014 either on its own (if upfront was 0)
|
|
58
|
-
or alongside the upfront fee.`}}),c=U(s),u=U(o),l,
|
|
58
|
+
or alongside the upfront fee.`}}),c=U(s),u=U(o),i,l,d;return c&&!u?(i=o.trim(),l=ie,d=o.trim()):!c&&u?(i=s.trim(),l=Ee,d=void 0):(i=s.trim(),l=`upfront, then ${o.trim()}/month`,d=o.trim()),{pricing:i,pricingTerms:l,pricingMonthly:d}}},Oe={id:"outreach-enabled",title:"Automated outreach",isApplicable:()=>!0,execute:async(e,{prompt:a})=>({outreachEnabled:await a({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
|
|
59
59
|
run outreach to them automatically (email and/or SMS).
|
|
60
60
|
If you'd rather handle outreach manually, you can skip this here.`}})})},Be={id:"operator-name",title:"Sign-off name",isApplicable:e=>e.outreachEnabled===!0,execute:async(e,{prompt:a,info:t})=>(t({title:"Sign-off name",body:`Outreach messages need a sender. Klaudius signs every email, SMS,
|
|
61
61
|
and WhatsApp it sends with this name \u2014 so the businesses you pitch
|
|
@@ -82,9 +82,9 @@ candidate \u2014 so opting into multiple channels also gives you fallback covera
|
|
|
82
82
|
when one channel doesn't work.
|
|
83
83
|
|
|
84
84
|
You'll be asked to pick your first-choice channel now, then optionally a
|
|
85
|
-
second and third. The order matters: it's the order Klaudius tries.`});let n={email:"Email",sms:"SMS (iMessage or Twilio, configured next)",whatsapp:"WhatsApp (Baileys / phone-linked device)"},
|
|
85
|
+
second and third. The order matters: it's the order Klaudius tries.`});let n={email:"Email",sms:"SMS (iMessage or Twilio, configured next)",whatsapp:"WhatsApp (Baileys / phone-linked device)"},r=["email","sms","whatsapp"],s=e.outreachPriority??[],o=[],c=await a({type:"select",message:"Which channel should Klaudius try FIRST for each candidate?",initialValue:s[0]??"email",options:r.map(u=>({value:u,label:n[u]}))});for(o.push(c);o.length<r.length;){let u=r.filter(f=>!o.includes(f)),i=o.length===1?"second":"third",l=o[o.length-1],d=n[l].replace(/\s*\(.*\)$/,"").toLowerCase(),w=await a({type:"select",message:`Should Klaudius use another channel as ${i} priority (for candidates where ${d} isn't viable or fails)?`,initialValue:s[o.length]??"no",options:[...u.map(f=>({value:f,label:`Yes \u2014 also use ${n[f]}`})),{value:"no",label:"No, that's all"}]});if(w==="no")break;o.push(w)}return{outreachChannels:o,outreachPriority:o}}},Re={id:"email",title:"Email setup",isApplicable:e=>e.outreachChannels?.includes("email")===!0,execute:async(e,{prompt:a,info:t})=>{t({title:"Email setup",body:`Klaudius needs an email account to send outreach FROM. This is the
|
|
86
86
|
address candidates will see as the sender. Use a domain you control
|
|
87
|
-
(your own, your business's) \u2014 not your personal address.`});let n=await a({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)"}]}),
|
|
87
|
+
(your own, your business's) \u2014 not your personal address.`});let n=await a({type:"select",message:"Who hosts the email account you'll send outreach from?",initialValue:e.emailProvider??"gmail",options:[{value:"gmail",label:"Gmail"},{value:"fastmail",label:"Fastmail"},{value:"outlook",label:"Outlook / Office 365"},{value:"zoho",label:"Zoho Mail"},{value:"ionos",label:"IONOS"},{value:"custom",label:"Custom / other (enter SMTP/IMAP details manually)"}]}),r=n!=="custom"?ae[n]:void 0,s=await a({type:"text",message:"Email address to send outreach from",placeholder:"you@yourbusiness.com",initialValue:e.emailAddress??"",validate:Te}),o=r?.appPasswordHelp??ne,c=await a({type:"password",message:"Paste the app password",initialValue:e.emailPassword??"",validate:N("App password"),note:{title:"App password",body:`An app password is a separate, single-purpose password that your
|
|
88
88
|
email provider issues for third-party apps like Klaudius. It is NOT
|
|
89
89
|
your normal account login password.
|
|
90
90
|
|
|
@@ -92,7 +92,7 @@ your normal account login password.
|
|
|
92
92
|
|
|
93
93
|
Once generated, it's stored locally in this project's .env file.
|
|
94
94
|
It is never sent to Klaudius's servers \u2014 only to your email
|
|
95
|
-
provider when sending outreach.`}}),u,l,
|
|
95
|
+
provider when sending outreach.`}}),u,i,l,d,w,f;if(n==="custom"){u=await a({type:"text",message:"SMTP host (the server Klaudius connects to for sending)",placeholder:"e.g. smtp.yourprovider.com",initialValue:e.emailSmtpHost??"",validate:N("SMTP host")});let A=await a({type:"text",message:"SMTP port (usually 587 for STARTTLS or 465 for SSL)",initialValue:String(e.emailSmtpPort??587),validate:b=>/^\d+$/.test(b)?void 0:"Must be a number"});i=parseInt(A,10),l=await a({type:"text",message:"IMAP host (the server Klaudius connects to for reading replies)",placeholder:"e.g. imap.yourprovider.com",initialValue:e.emailImapHost??"",validate:N("IMAP host")});let I=await a({type:"text",message:"IMAP port (usually 993 for SSL)",initialValue:String(e.emailImapPort??993),validate:b=>/^\d+$/.test(b)?void 0:"Must be a number"});d=parseInt(I,10),w=await a({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"}),f=await a({type:"text",message:"Inbox folder name (almost always INBOX)",initialValue:e.emailInboxFolder??"INBOX"})}else u=r.smtpHost,i=r.smtpPort,l=r.imapHost,d=r.imapPort,w=r.sentFolder,f=r.inboxFolder;return{emailProvider:n,emailAddress:s,emailPassword:c,emailFromName:e.name,emailSmtpHost:u,emailSmtpPort:i,emailImapHost:l,emailImapPort:d,emailSentFolder:w,emailInboxFolder:f}}},Ke={id:"sms",title:"SMS setup",isApplicable:e=>e.outreachChannels?.includes("sms")===!0,execute:async(e,{prompt:a,info:t})=>{t({title:"SMS setup",body:`Klaudius can send SMS one of two ways:
|
|
96
96
|
|
|
97
97
|
\u2022 macOS iMessage \u2014 free, uses Messages.app on your Mac.
|
|
98
98
|
Reaches other Apple users as iMessage for free. To reach
|
|
@@ -108,7 +108,7 @@ provider when sending outreach.`}}),u,l,r,d,S,f;if(n==="custom"){u=await a({type
|
|
|
108
108
|
|
|
109
109
|
\u2022 Twilio \u2014 cross-platform, ~$0.01 per SMS. Sender is a phone
|
|
110
110
|
number you buy from Twilio. Works on any OS, reaches any
|
|
111
|
-
phone, no iPhone required. Recommended for consistent delivery.`});let n=await a({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)"}]}),
|
|
111
|
+
phone, no iPhone required. Recommended for consistent delivery.`});let n=await a({type:"select",message:"Which SMS provider?",initialValue:e.smsProvider??(process.platform==="darwin"?"imessage":"twilio"),options:[{value:"imessage",label:"macOS iMessage (free, Mac only)"},{value:"twilio",label:"Twilio (cross-platform, paid per-message \u2014 recommended)"}]}),r=await a({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:se}),s={smsProvider:n,testPhone:r};return n==="twilio"&&(s.twilioAccountSid=await a({type:"text",message:"Twilio Account SID (starts with AC...)",initialValue:e.twilioAccountSid??"",validate:o=>/^AC[a-zA-Z0-9]+$/.test(o)?void 0:"Should start with 'AC'"}),s.twilioAuthToken=await a({type:"password",message:"Twilio Auth Token",initialValue:e.twilioAuthToken??"",validate:N("Twilio Auth Token")}),s.twilioPhoneNumber=await a({type:"text",message:"Twilio phone number (the number outreach will be sent FROM)",placeholder:"+15551234567",initialValue:e.twilioPhoneNumber??"",validate:se})),s}},Le={id:"whatsapp",title:"WhatsApp setup",isApplicable:e=>e.outreachPriority?.includes("whatsapp")===!0,execute:async(e,{prompt:a,info:t})=>{t({title:"WhatsApp setup",body:`Klaudius connects to WhatsApp as a linked device on your phone \u2014 same way
|
|
112
112
|
WhatsApp Web works. Setup is a one-time QR scan from the WhatsApp app on
|
|
113
113
|
the phone whose number you want to use. Klaudius will guide you through
|
|
114
114
|
that AFTER this wizard, once npm dependencies are installed.
|
|
@@ -126,7 +126,7 @@ number unless you're comfortable with that.
|
|
|
126
126
|
|
|
127
127
|
You'll be asked how many accounts to link and a short label for each
|
|
128
128
|
(used only locally \u2014 appears in logs, in the .env file, and in this
|
|
129
|
-
project's per-account directory under ~/.klaudius/whatsapp/).`});let n=await a({type:"select",message:"How many WhatsApp numbers do you want to link?",initialValue:String(e.whatsappAccounts?.length??1),options:[{value:"1",label:"1 number (recommended starting point)"},{value:"2",label:"2 numbers (spread load across two)"},{value:"3",label:"3 numbers"},{value:"4",label:"4 numbers"},{value:"5",label:"5 numbers (maximum)"}]}),
|
|
129
|
+
project's per-account directory under ~/.klaudius/whatsapp/).`});let n=await a({type:"select",message:"How many WhatsApp numbers do you want to link?",initialValue:String(e.whatsappAccounts?.length??1),options:[{value:"1",label:"1 number (recommended starting point)"},{value:"2",label:"2 numbers (spread load across two)"},{value:"3",label:"3 numbers"},{value:"4",label:"4 numbers"},{value:"5",label:"5 numbers (maximum)"}]}),r=parseInt(n,10),s=["primary","secondary","tertiary","quaternary","quinary"],o=[];for(let c=0;c<r;c++){let u=await a({type:"text",message:r===1?"Label for this WhatsApp account (used only locally \u2014 'primary' is fine)":`Label for WhatsApp account ${c+1} of ${r} (e.g. 'primary', 'uk-1', 'us-east')`,initialValue:e.whatsappAccounts?.[c]??s[c],validate:i=>{let l=i.trim();if(!l)return"Required";if(l.length>30)return"Too long (max 30 characters)";if(l.startsWith("-")||l.endsWith("-"))return"Can't start or end with a hyphen";if(!/^[A-Za-z0-9_-]+$/.test(l))return"Letters, digits, underscore, hyphen only (no spaces)";if(o.includes(l))return"Duplicate label"}});o.push(u.trim())}return{whatsappAccounts:o}}},Fe={id:"vercel",title:"Vercel deployment",isApplicable:()=>!0,execute:async(e,{prompt:a})=>({vercelToken:await a({type:"password",message:"Paste your Vercel API token",initialValue:e.vercelToken??"",validate:n=>n.trim().length===0?"Required \u2014 without this Klaudius can't deploy generated sites":void 0,note:{title:"Vercel deployment",body:`Klaudius deploys every generated client site to Vercel. We use a
|
|
130
130
|
Vercel API token to do this without an interactive login.
|
|
131
131
|
|
|
132
132
|
How to get one (one-time, ~30 seconds):
|
|
@@ -183,19 +183,23 @@ in another tab/app and paste this prompt verbatim:
|
|
|
183
183
|
The wizard is asking for: (1) project URL, (2) the secret/service-
|
|
184
184
|
role key, (3) a personal access token. Walk me through where to
|
|
185
185
|
find each one in the current Supabase dashboard UI, including the
|
|
186
|
-
exact menu paths and any caveats for newer vs. legacy projects."`});let
|
|
186
|
+
exact menu paths and any caveats for newer vs. legacy projects."`});let r=(await a({type:"text",message:"Paste your Supabase API URL",placeholder:"https://YOUR_REF.supabase.co",initialValue:e.supabaseUrl??"",validate:u=>/^https:\/\/[a-z0-9]+\.supabase\.co(\/rest\/v1\/?)?$/i.test(u.trim())?void 0:"Should look like https://xxxx.supabase.co (with or without /rest/v1/)",note:{title:"API URL",body:`In your Supabase dashboard, open your project, then go to:
|
|
187
187
|
Settings \u2192 Data API \u2192 'API URL'
|
|
188
188
|
|
|
189
189
|
It looks like https://xxxx.supabase.co. Click to copy and paste
|
|
190
|
-
below.`}})).trim().replace(/\/rest\/v1\/?$/i,"").replace(/\/$/,""),s=
|
|
190
|
+
below.`}})).trim().replace(/\/rest\/v1\/?$/i,"").replace(/\/$/,""),s=r.match(/^https:\/\/([a-z0-9]+)\.supabase\.co/i)?.[1]??"",o=await a({type:"password",message:"Paste the Supabase secret key (sb_secret_\u2026)",initialValue:e.supabaseServiceKey??"",validate:u=>{let i=u.trim();if(i.length<20)return"Looks too short";if(i.startsWith("sb_publishable_"))return"That's the publishable key. Klaudius needs the 'sb_secret_\u2026' key on the same page (different row, below the publishable one).";if(!i.startsWith("sb_secret_")&&!i.startsWith("eyJ"))return"Doesn't look like a Supabase secret key. Expected 'sb_secret_\u2026' (or a legacy JWT starting with 'eyJ\u2026' on older projects)."},note:{title:"Secret key",body:`Open this exact page:
|
|
191
191
|
https://supabase.com/dashboard/project/${s}/settings/api-keys
|
|
192
192
|
|
|
193
193
|
Under 'Secret keys', find the row whose value starts with
|
|
194
194
|
'sb_secret_'. Click to copy the full value.
|
|
195
195
|
|
|
196
196
|
NEVER use the 'anon' / 'public' / 'sb_publishable_' key (those
|
|
197
|
-
are client-side keys with no write permissions)
|
|
198
|
-
|
|
197
|
+
are client-side keys with no write permissions).
|
|
198
|
+
|
|
199
|
+
Don't confuse this page with 'Edge Functions \u2192 Secrets' in the
|
|
200
|
+
left sidebar \u2014 that's an unrelated feature (env vars for Edge
|
|
201
|
+
Functions). The page you want is Settings (gear icon, bottom
|
|
202
|
+
of the left sidebar) \u2192 API Keys.`}}),c=await a({type:"password",message:"Paste the Supabase personal access token",initialValue:e.supabasePat??"",validate:u=>u.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
|
|
199
203
|
ACCOUNT-wide token (not project-scoped) used by the Supabase MCP and
|
|
200
204
|
by Klaudius's schema migration.
|
|
201
205
|
|
|
@@ -205,7 +209,7 @@ Open this exact page:
|
|
|
205
209
|
Click 'Generate new token', name it 'Klaudius', and set the
|
|
206
210
|
expiration to 'Never' (recommended \u2014 saves you having to rotate
|
|
207
211
|
it later). Copy the value (starts with 'sbp_') and paste it
|
|
208
|
-
below.`}});return{supabaseUrl:
|
|
212
|
+
below.`}});return{supabaseUrl:r,supabaseServiceKey:o,supabasePat:c,supabaseProjectRef:s}}},ze={id:"google-places",title:"Google Places API",isApplicable:()=>!0,execute:async(e,{prompt:a})=>({googlePlacesApiKey:await a({type:"password",message:"Paste your Google Places API key",placeholder:"AIzaSy\u2026",initialValue:e.googlePlacesApiKey??"",validate:n=>n.trim().length===0?"Required \u2014 without this Klaudius can't find candidates":void 0,note:{title:"Google Places API key",body:`Klaudius's /find skill queries Google's Places API to discover businesses
|
|
209
213
|
without websites in your target region. Without a key, the pipeline has
|
|
210
214
|
no source of leads \u2014 so this is required.
|
|
211
215
|
|
|
@@ -260,7 +264,7 @@ How to create one:
|
|
|
260
264
|
'KlaudiusNotifierBot'). Each username has to be globally
|
|
261
265
|
unique, so add a personal suffix if it's taken.
|
|
262
266
|
6. BotFather replies with a token like
|
|
263
|
-
'1234567890:AAEhBP_yourtokenhere\u2026'. Copy it and paste below.`}}),
|
|
267
|
+
'1234567890:AAEhBP_yourtokenhere\u2026'. Copy it and paste below.`}}),r=null,s=0,o=null,c=null;for(;r===null;){s++;let u=s>1,i=c==="network"?`${o}
|
|
264
268
|
|
|
265
269
|
This is usually a network problem on your end (corporate WiFi or VPN
|
|
266
270
|
blocking Telegram, ISP DNS issue, a momentary drop). Check your
|
|
@@ -269,7 +273,7 @@ to retry.`:`${o}
|
|
|
269
273
|
|
|
270
274
|
Make sure you sent a regular text message (e.g. 'hi'), not
|
|
271
275
|
just a /start tap \u2014 /start alone doesn't always register.
|
|
272
|
-
Then press Enter to retry.`;await a({type:"text",message:u?c==="network"?"Check your network, then press Enter to retry":"Send another message to the bot, then press Enter to retry":"Send a message to your bot, then press Enter to detect chat ID",initialValue:"",placeholder:"(press Enter when you've sent the message)",validate:()=>{},note:{title:u?"Detect chat ID \u2014 retry":"Detect chat ID",body:u?
|
|
276
|
+
Then press Enter to retry.`;await a({type:"text",message:u?c==="network"?"Check your network, then press Enter to retry":"Send another message to the bot, then press Enter to retry":"Send a message to your bot, then press Enter to detect chat ID",initialValue:"",placeholder:"(press Enter when you've sent the message)",validate:()=>{},note:{title:u?"Detect chat ID \u2014 retry":"Detect chat ID",body:u?i:`Klaudius will auto-detect your chat ID by asking Telegram for
|
|
273
277
|
any messages your bot has received. To make that work:
|
|
274
278
|
|
|
275
279
|
1. In the Telegram app, search for the bot you just created
|
|
@@ -278,5 +282,5 @@ any messages your bot has received. To make that work:
|
|
|
278
282
|
If the chat starts with a 'Start' button, tap that first,
|
|
279
283
|
THEN send 'hi'. /start alone doesn't always show up.
|
|
280
284
|
3. Press Enter below \u2014 Klaudius will detect the chat ID for
|
|
281
|
-
you.`}});let
|
|
282
|
-
`);return Xe(be,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[J(Ce,{color:"cyan",bold:!0,children:e}),J(be,{flexDirection:"column",marginTop:0,children:t.map((n,
|
|
285
|
+
you.`}});let l=await ee({botToken:n});if(l.ok&&l.chatId)r=l.chatId;else if(l.reason==="no_messages")o="No messages from you to your bot have been picked up yet.",c="no_messages";else if(l.reason==="network")o=l.message??"Could not reach Telegram.",c="network";else throw new Error(`Telegram chat ID auto-detect failed: ${l.message??"unknown error"}`)}return{telegramBotToken:n,telegramChatId:r}}},x=[xe,Me,Oe,Be,Ne,Re,Ke,Le,Fe,Ge,ze,Ve];import{Box as re,Text as Ue}from"ink";import{jsx as le,jsxs as We}from"react/jsx-runtime";var He={pending:"\u25CB",current:"\u25C9",done:"\u2713",skipped:"\xB7"},De={pending:void 0,current:"cyan",done:"green",skipped:void 0};function ue({items:e}){return le(re,{flexDirection:"column",width:28,flexShrink:0,children:e.map(a=>{let t=a.status==="skipped"||a.status==="pending";return le(re,{children:We(Ue,{color:De[a.status],bold:a.status==="current",dimColor:t&&a.status!=="current",children:[He[a.status]," ",a.title]})},a.id)})})}import{useEffect as _e,useState as ce}from"react";import{Box as j,Text as D,useInput as $e}from"ink";import je from"ink-text-input";import{jsx as F,jsxs as q}from"react/jsx-runtime";function de({spec:e,masked:a,onSubmit:t,onBack:n}){let[r,s]=ce(typeof e.initialValue=="string"?e.initialValue:""),[o,c]=ce(null);_e(()=>(y("TextPromptUI:mount",{masked:a,message:e.message.slice(0,60),initial:typeof e.initialValue=="string"?e.initialValue.slice(0,30):null}),()=>{y("TextPromptUI:unmount")}),[a,e.message,e.initialValue]),$e((i,l)=>{y("TextPromptUI:useInput fired",{input:i,ctrl:l.ctrl,escape:l.escape,return:l.return}),l.escape&&n()});let u=i=>{y("TextPromptUI:handleSubmit",{raw:i.slice(0,30)});let l=i;if(e.validate){let d=e.validate(l);if(d){y("TextPromptUI:validate failed",{err:d}),c(d);return}}c(null),t(l)};return q(j,{flexDirection:"column",children:[q(D,{children:[F(D,{color:"cyan",children:"?"})," ",e.message]}),q(j,{children:[F(D,{color:"green",children:"\u203A "}),F(je,{value:r,onChange:s,onSubmit:u,placeholder:e.placeholder,mask:a?"\u2022":void 0})]}),o&&F(j,{marginTop:0,children:F(D,{color:"red",children:o})})]})}import{useState as qe}from"react";import{Box as ge,Text as Z,useInput as Ze}from"ink";import{jsx as pe,jsxs as Y}from"react/jsx-runtime";function he({spec:e,onSubmit:a,onBack:t}){let n=e.options??[],r=typeof e.initialValue=="string"?Math.max(0,n.findIndex(c=>c.value===e.initialValue)):0,[s,o]=qe(r===-1?0:r);return Ze((c,u)=>{if(u.escape)t();else if(u.upArrow)o(i=>(i-1+n.length)%n.length);else if(u.downArrow)o(i=>(i+1)%n.length);else if(u.return){let i=n[s];i&&a(i.value)}}),Y(ge,{flexDirection:"column",children:[Y(Z,{children:[pe(Z,{color:"cyan",children:"?"})," ",e.message]}),pe(ge,{flexDirection:"column",marginTop:0,children:n.map((c,u)=>{let i=u===s;return Y(Z,{color:i?"cyan":void 0,bold:i,children:[i?"\u25CF ":"\u25CB ",c.label]},c.value)})})]})}import{useState as Ye}from"react";import{Box as me,Text as G,useInput as Je}from"ink";import{jsx as ye,jsxs as z}from"react/jsx-runtime";function fe({spec:e,onSubmit:a,onBack:t}){let[n,r]=Ye(typeof e.initialValue=="boolean"?e.initialValue:!0);return Je((s,o)=>{o.escape?t():o.leftArrow||o.rightArrow?r(c=>!c):s==="y"||s==="Y"?r(!0):s==="n"||s==="N"?r(!1):o.return&&a(n)}),z(me,{flexDirection:"column",children:[z(G,{children:[ye(G,{color:"cyan",children:"?"})," ",e.message]}),z(me,{marginTop:0,children:[z(G,{color:n?"cyan":void 0,bold:n,children:[n?"\u25CF ":"\u25CB ","Yes"]}),ye(G,{children:" "}),z(G,{color:n?void 0:"cyan",bold:!n,children:[n?"\u25CB ":"\u25CF ","No"]})]})]})}import{Box as be,Text as Ce}from"ink";import{jsx as J,jsxs as Xe}from"react/jsx-runtime";function X({title:e,body:a}){let t=a.split(`
|
|
286
|
+
`);return Xe(be,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[J(Ce,{color:"cyan",bold:!0,children:e}),J(be,{flexDirection:"column",marginTop:0,children:t.map((n,r)=>J(Ce,{dimColor:!1,children:n.length===0?" ":n},r))})]})}import{jsx as p,jsxs as V}from"react/jsx-runtime";function Wa({defaults:e,onComplete:a,onlySection:t,banner:n}){let{exit:r}=aa(),s=Q({...e}),o=Q(new Map),[,c]=M(0),u=()=>c(h=>h+1),[i,l]=M(null),[d,w]=M(null),[f,A]=M([]),[I,b]=M(null),[O,we]=M(!1),[W,Se]=M({current:0,total:0}),R=()=>{let h=o.current;for(let C of x){let $=C.isApplicable(s.current),g=h.get(C.id);$?t&&C.id!==t?g!=="current"&&h.set(C.id,"done"):(g==="skipped"||!g)&&h.set(C.id,"pending"):h.set(C.id,"skipped")}};o.current.size===0&&R();let _=Q(!1);Qe(()=>{if(y("WizardApp:useEffect fired",{startedAlready:_.current}),_.current){y("WizardApp:useEffect returning early (startedRef true)");return}_.current=!0,y("WizardApp:orchestrator starting");let h=0,C=g=>{let v=++h;return y("orchestrator:promptFn called",{id:v,type:g.type,message:g.message.slice(0,60)}),b(null),new Promise((S,m)=>{w({id:v,spec:g,resolve:T=>{y("orchestrator:prompt resolved",{id:v,type:g.type,value:typeof T=="string"?T.slice(0,30):T}),S(T)},reject:T=>{y("orchestrator:prompt rejected",{id:v,reason:T.message}),m(T)}})})},$=g=>{A(v=>[...v,g])};return(async()=>{try{let g=t?x.filter(m=>m.id===t):x,v=()=>g.filter(m=>m.isApplicable(s.current)).length,S=0;for(;S<g.length;){let m=g[S];if(!m.isApplicable(s.current)){o.current.set(m.id,"skipped"),S++,R(),u();continue}A([]);for(let k of x)k.id===m.id?o.current.set(k.id,"current"):o.current.get(k.id)==="current"&&o.current.set(k.id,"pending");l(m.id);let T=g.slice(0,S+1).filter(k=>k.isApplicable(s.current)).length;Se({current:T,total:v()}),u();try{let k=await m.execute(s.current,{prompt:C,info:$});s.current={...s.current,...k},o.current.set(m.id,"done"),R(),S++}catch(k){if(k instanceof L){if(t&&m.clearOnSkip){for(let ve of m.clearOnSkip)s.current[ve]=void 0;o.current.set(m.id,"skipped"),R(),S++;continue}if(t)continue;o.current.set(m.id,"pending");let K=S-1;for(;K>=0&&!g[K].isApplicable(s.current);)K--;K<0||(S=K,o.current.set(g[S].id,"pending")),R(),u();continue}throw k}}y("orchestrator:all sections done, calling onComplete + exit"),we(!0),w(null),l(null),u(),await new Promise(m=>setTimeout(m,200)),a(s.current),r()}catch(g){y("orchestrator:caught error",{name:g?.name,message:g?.message}),g instanceof H&&(r(),process.exit(0));let v=g instanceof Error?g.message:String(g);b(`Setup error: ${v}`),u()}})(),()=>{y("WizardApp:useEffect cleanup ran (component unmounting)")}},[r,a]),na((h,C)=>{y("WizardApp:useInput fired",{input:h,ctrl:C.ctrl,escape:C.escape,return:C.return}),C.ctrl&&h==="c"&&(y("WizardApp:Ctrl+C \u2192 exiting"),r(),process.exit(0))});let ke=ea(()=>x.map(h=>({id:h.id,title:h.title,status:o.current.get(h.id)??"pending"})),[i,O,I]);return V(P,{flexDirection:"column",paddingY:1,children:[V(P,{marginBottom:1,children:[p(E,{bold:!0,color:"cyan",children:"Klaudius setup"}),p(E,{dimColor:!0,children:" \xB7 "}),p(E,{dimColor:!0,children:W.total>0?`Step ${W.current} of ${W.total}`:"Loading\u2026"})]}),V(P,{children:[p(ue,{items:ke}),V(P,{flexDirection:"column",flexGrow:1,marginLeft:2,children:[n&&V(P,{marginBottom:1,borderStyle:"round",borderColor:"red",paddingX:1,flexDirection:"column",children:[p(E,{color:"red",bold:!0,children:"\u26A0 Heads up"}),p(E,{children:n})]}),f.map((h,C)=>p(P,{marginBottom:1,children:p(X,{title:h.title,body:h.body})},C)),d?.spec.note&&p(P,{marginBottom:1,children:p(X,{title:d.spec.note.title,body:d.spec.note.body})}),d&&oa(d),I&&p(P,{marginTop:1,children:p(E,{color:"red",children:I})}),O&&p(P,{marginTop:1,children:p(E,{color:"green",bold:!0,children:"\u2713 Setup complete. Continuing\u2026"})})]})]}),p(P,{marginTop:1,children:p(E,{dimColor:!0,children:ta(t,i)})})]})}function ta(e,a){if(e){let t=x.find(n=>n.id===a);return t?.clearOnSkip&&t.clearOnSkip.length>0?"\u21B5 confirm esc skip this section ctrl-c cancel":"\u21B5 confirm ctrl-c cancel"}return"\u21B5 confirm esc back to previous section ctrl-c cancel"}function oa(e){let a=n=>e.resolve(n),t=()=>e.reject(new L);switch(e.spec.type){case"text":case"password":return p(de,{spec:e.spec,masked:e.spec.type==="password",onSubmit:a,onBack:t},e.id);case"select":return p(he,{spec:e.spec,onSubmit:a,onBack:t},e.id);case"confirm":return p(fe,{spec:e.spec,onSubmit:a,onBack:t},e.id)}}export{Wa as WizardApp};
|
package/dist/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as V,b as Ae,c as Se,d as v,f as _e,g as Te}from"./chunk-SZ4KCTSL.js";import{a as ne,e as Re}from"./chunk-47ODNABO.js";import{Command as Hn}from"commander";import{mkdir as Ze,readdir as nn,readFile as Je,stat as Xe,writeFile as Qe}from"fs/promises";import{spawnSync as et}from"child_process";import{resolve as sn,isAbsolute as on,join as Z,normalize as rn}from"path";import*as y from"@clack/prompts";import d from"picocolors";import wt from"react";import{render as kt}from"ink";async function _(e={},n={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:t}=await import("./WizardApp-
|
|
2
|
+
import{a as V,b as Ae,c as Se,d as v,f as _e,g as Te}from"./chunk-SZ4KCTSL.js";import{a as ne,e as Re}from"./chunk-47ODNABO.js";import{Command as Hn}from"commander";import{mkdir as Ze,readdir as nn,readFile as Je,stat as Xe,writeFile as Qe}from"fs/promises";import{spawnSync as et}from"child_process";import{resolve as sn,isAbsolute as on,join as Z,normalize as rn}from"path";import*as y from"@clack/prompts";import d from"picocolors";import wt from"react";import{render as kt}from"ink";async function _(e={},n={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:t}=await import("./WizardApp-UVH2T2G2.js"),i=null;V("runWizard:start",{onlySection:n.onlySection,hasDefaults:Object.keys(e).length>0}),Se(),await new Promise(o=>setImmediate(o)),await new Promise(o=>setTimeout(o,0)),V("runWizard:event loop drained, mounting Ink");let r=kt(wt.createElement(t,{defaults:e,onlySection:n.onlySection,banner:n.banner,onComplete:o=>{V("runWizard:onComplete called",{keys:Object.keys(o).length}),i=o}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(V("runWizard:render returned, awaiting exit"),await r.waitUntilExit(),V("runWizard:waitUntilExit resolved",{resultIsNull:i===null}),!i)throw new Error(`Wizard exited without completing. Diagnostic log: ${Ae}
|
|
3
3
|
Please share that file so we can trace what happened.`);return i}function se(e){let n=[],t=r=>{n.push(""),n.push("# "+"=".repeat(60)),n.push(`# ${r}`),n.push("# "+"=".repeat(60)),n.push("")},i=(r,o)=>{if(o==null||o===""){n.push(`# ${r}=`);return}let l=String(o);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(l)){let a=l.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");n.push(`${r}="${a}"`)}else n.push(`${r}=${l}`)};return n.push("# Klaudius configuration"),n.push("# Generated by `npx klaudius init`. Edit freely."),n.push("# NEVER commit this file. .gitignore already excludes it."),t("Klaudius licence"),i("KLAUDIUS_LICENSE_KEY",e.licenseKey),t("Operating country and language"),i("OPERATOR_COUNTRY",e.country),i("OPERATOR_COUNTRY_CODE",e.countryCode),i("OPERATOR_LANGUAGE",e.language),i("OPERATOR_LANGUAGE_CODE",e.languageCode),t("Pricing"),i("PRICING",e.pricing),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",e.pricingMonthly),t("Automated outreach features"),i("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),i("OPERATOR_NAME",e.name),i("SIGNATURE",e.signature),i("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),i("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),t("Email outreach"),i("EMAIL_ADDRESS",e.emailAddress),i("EMAIL_PASSWORD",e.emailPassword),i("EMAIL_FROM_NAME",e.emailFromName),i("EMAIL_SMTP_HOST",e.emailSmtpHost),i("EMAIL_SMTP_PORT",e.emailSmtpPort),i("EMAIL_IMAP_HOST",e.emailImapHost),i("EMAIL_IMAP_PORT",e.emailImapPort),i("EMAIL_SENT_FOLDER",e.emailSentFolder),i("EMAIL_INBOX_FOLDER",e.emailInboxFolder),t("SMS outreach"),i("SMS_PROVIDER",e.smsProvider),i("TEST_PHONE",e.testPhone),i("TWILIO_ACCOUNT_SID",e.twilioAccountSid),i("TWILIO_AUTH_TOKEN",e.twilioAuthToken),i("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),t("WhatsApp outreach"),i("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),t("Supabase (pipeline state)"),i("SUPABASE_URL",e.supabaseUrl),i("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),i("SUPABASE_PAT",e.supabasePat),i("SUPABASE_PROJECT_REF",e.supabaseProjectRef),t("Vercel (deployment)"),i("VERCEL_TOKEN",e.vercelToken),i("VERCEL_SCOPE",e.vercelScope??""),t("Search APIs"),i("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),i("SERPAPI_KEY",e.serpapiKey),t("Telegram notifications (optional)"),i("TELEGRAM_BOT_TOKEN",e.telegramBotToken),i("TELEGRAM_CHAT_ID",e.telegramChatId),t("Rate limiting (sensible defaults)"),i("REQUESTS_PER_MINUTE",10),i("REQUEST_DELAY",2),n.join(`
|
|
4
4
|
`)+`
|
|
5
5
|
`}function ie(e){let n={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(n,null,2)+`
|
|
@@ -8,15 +8,15 @@ Please share that file so we can trace what happened.`);return i}function se(e){
|
|
|
8
8
|
`,o=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let l of i)o.push(""),l.comment&&o.push(`# ${l.comment}`),o.push(Et(l.key,l.value));return e+r+o.join(`
|
|
9
9
|
`)+`
|
|
10
10
|
`}function Pt(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function x(e){let n={};for(let t of e.split(`
|
|
11
|
-
`)){let i=t.trim();if(!i||i.startsWith("#"))continue;let r=i.indexOf("=");if(r===-1)continue;let o=i.slice(0,r).trim(),l=Pt(i.slice(r+1).trim());n[o]=l}return n}function ve(e){let n=a=>{let p=e[a];if(!p)return;let f=parseInt(p,10);return isNaN(f)?void 0:f},t=e.SMS_PROVIDER,i=a=>a==="email"||a==="sms"||a==="whatsapp",r=e.OUTREACH_CHANNELS?.split(",").map(a=>a.trim()).filter(i),o=e.OUTREACH_PRIORITY?.split(",").map(a=>a.trim()).filter(i),l=e.WHATSAPP_ACCOUNTS?.split(",").map(a=>a.trim()).filter(a=>a.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:r&&r.length>0?r:void 0,outreachPriority:o&&o.length>0?o:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:n("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:n("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:t==="imessage"||t==="twilio"?t:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,emailPassword:e.EMAIL_PASSWORD,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function ge(e){let n=E=>{let U=e[E];if(!U)return;let O=parseInt(U,10);return isNaN(O)?void 0:O},t=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY,r=e.SUPABASE_PAT,o=e.SUPABASE_PROJECT_REF,l=e.PRICING,a=e.PRICING_TERMS||"one-off, no monthly fees",p=e.VERCEL_TOKEN;if(!l||!t||!i||!r||!o||!p)return null;let f=e.SMS_PROVIDER,c=E=>E==="email"||E==="sms"||E==="whatsapp",w=e.OUTREACH_CHANNELS?.split(",").map(E=>E.trim()).filter(c),P=e.OUTREACH_PRIORITY?.split(",").map(E=>E.trim()).filter(c),M=e.WHATSAPP_ACCOUNTS?.split(",").map(E=>E.trim()).filter(E=>E.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:l,pricingTerms:a,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:w&&w.length>0?w:void 0,outreachPriority:P&&P.length>0?P:void 0,whatsappAccounts:M&&M.length>0?M:void 0,emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:n("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:n("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:f==="imessage"||f==="twilio"?f:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,vercelToken:p,vercelScope:e.VERCEL_SCOPE||void 0,supabaseUrl:t,supabaseServiceKey:i,supabasePat:r,supabaseProjectRef:o,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{mkdir as bt,rm as At}from"fs/promises";import{Readable as St}from"stream";import*as Oe from"tar";var _t="https://klaudius.dev/api/template";function Tt(e){return St.fromWeb(e)}async function oe(e){let n=process.env.KLAUDIUS_TEMPLATE_URL??_t,t="0.12.
|
|
11
|
+
`)){let i=t.trim();if(!i||i.startsWith("#"))continue;let r=i.indexOf("=");if(r===-1)continue;let o=i.slice(0,r).trim(),l=Pt(i.slice(r+1).trim());n[o]=l}return n}function ve(e){let n=a=>{let p=e[a];if(!p)return;let f=parseInt(p,10);return isNaN(f)?void 0:f},t=e.SMS_PROVIDER,i=a=>a==="email"||a==="sms"||a==="whatsapp",r=e.OUTREACH_CHANNELS?.split(",").map(a=>a.trim()).filter(i),o=e.OUTREACH_PRIORITY?.split(",").map(a=>a.trim()).filter(i),l=e.WHATSAPP_ACCOUNTS?.split(",").map(a=>a.trim()).filter(a=>a.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:r&&r.length>0?r:void 0,outreachPriority:o&&o.length>0?o:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:n("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:n("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:t==="imessage"||t==="twilio"?t:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,emailPassword:e.EMAIL_PASSWORD,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function ge(e){let n=E=>{let U=e[E];if(!U)return;let O=parseInt(U,10);return isNaN(O)?void 0:O},t=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY,r=e.SUPABASE_PAT,o=e.SUPABASE_PROJECT_REF,l=e.PRICING,a=e.PRICING_TERMS||"one-off, no monthly fees",p=e.VERCEL_TOKEN;if(!l||!t||!i||!r||!o||!p)return null;let f=e.SMS_PROVIDER,c=E=>E==="email"||E==="sms"||E==="whatsapp",w=e.OUTREACH_CHANNELS?.split(",").map(E=>E.trim()).filter(c),P=e.OUTREACH_PRIORITY?.split(",").map(E=>E.trim()).filter(c),M=e.WHATSAPP_ACCOUNTS?.split(",").map(E=>E.trim()).filter(E=>E.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:l,pricingTerms:a,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:w&&w.length>0?w:void 0,outreachPriority:P&&P.length>0?P:void 0,whatsappAccounts:M&&M.length>0?M:void 0,emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:n("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:n("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:f==="imessage"||f==="twilio"?f:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,vercelToken:p,vercelScope:e.VERCEL_SCOPE||void 0,supabaseUrl:t,supabaseServiceKey:i,supabasePat:r,supabaseProjectRef:o,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{mkdir as bt,rm as At}from"fs/promises";import{Readable as St}from"stream";import*as Oe from"tar";var _t="https://klaudius.dev/api/template";function Tt(e){return St.fromWeb(e)}async function oe(e){let n=process.env.KLAUDIUS_TEMPLATE_URL??_t,t="0.12.3",i;try{i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:t})})}catch(l){throw new Error(`Could not reach klaudius.dev to download the template: ${v(l)}`)}if(!i.ok){let l="";try{let a=await i.json();l=a.reason?` (${a.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${i.status}${l}`)}if(!i.body)throw new Error("Template download succeeded but response had no body");let r=i.headers.get("x-klaudius-tier");await bt(e.destDir,{recursive:!0});let o=0;try{await new Promise((l,a)=>{let p=Oe.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{o++}});p.on("finish",l),p.on("error",a),Tt(i.body).on("error",a).pipe(p)})}catch(l){throw await At(e.destDir,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Failed to extract template archive: ${l.message}`)}return{filesExtracted:o,tier:r}}import{mkdir as Rt,readFile as It,writeFile as Ct,access as vt}from"fs/promises";import{dirname as Ot,join as $e}from"path";var $t=".klaudius",xe=`${$t}/manifest.json`;async function Ne(e){let n=$e(e,xe);try{await vt(n)}catch{return null}let t=await It(n,"utf-8");return JSON.parse(t)}async function re(e,n){let t=$e(e,xe);await Rt(Ot(t),{recursive:!0}),await Ct(t,JSON.stringify(n,null,2)+`
|
|
12
12
|
`,"utf-8")}function Le(e,n){let t=new Date().toISOString();return{version:1,templateVersion:e,installedAt:t,updatedAt:t,files:n}}import{createHash as xt}from"crypto";import{hostname as Me,userInfo as Nt,platform as Ue,arch as De}from"os";import D from"picocolors";var s={info:e=>console.log(D.cyan("\u2139"),e),success:e=>console.log(D.green("\u2713"),e),warn:e=>console.log(D.yellow("\u26A0"),e),error:e=>console.error(D.red("\u2717"),e),step:e=>console.log(D.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
13
|
-
`+D.bold(D.cyan(e))),detail:e=>console.log(D.dim(" "+e))};var Lt="https://klaudius.dev",Mt="/api/licenses/validate",Ut="0.12.
|
|
13
|
+
`+D.bold(D.cyan(e))),detail:e=>console.log(D.dim(" "+e))};var Lt="https://klaudius.dev",Mt="/api/licenses/validate",Ut="0.12.3";async function je(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let n=e.trim(),i=(process.env.KLAUDIUS_API_URL??Lt).replace(/\/$/,"")+Mt,r=X(),o;try{o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:n,machine_id:r,hostname:Me(),os:`${Ue()}-${De()}`,cli_version:Ut})})}catch(a){return{ok:!1,reason:`Could not reach the Klaudius license server (${v(a)}). Check your internet connection or try again later.`}}let l;try{l=await o.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${o.status}).`}}return l.ok?{ok:!0,tier:l.tier??"core"}:{ok:!1,reason:l.reason??`License rejected (HTTP ${o.status}).`}}function X(){let e=[Me(),Nt().username,Ue(),De()].join("|");return xt("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Dt}from"fs/promises";import{join as jt}from"path";async function B(e){try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:e.serviceKey,Authorization:`Bearer ${e.serviceKey}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${v(n)}`}}}async function Ke(e){let n;try{n=await Dt(jt(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(t){return{ok:!1,message:`Could not read scripts/schema.sql: ${t.message}`}}try{let t=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${e.pat}`,"Content-Type":"application/json"},body:JSON.stringify({query:n})});if(t.ok)return{ok:!0};let i=await t.text();return i.includes("already exists")||i.includes('relation "clients" already exists')||i.includes("duplicate")?(s.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${t.status}): ${i.slice(0,300)}`}}catch(t){return{ok:!1,message:`Schema apply failed: ${t.message}`}}}async function ae(e){try{let n=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(n.status===401||n.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${n.status}). The token is invalid, expired, or has been revoked.`};if(!n.ok)return{ok:!1,message:`Vercel API returned HTTP ${n.status}. Try again or check status.vercel.com.`};let t=await n.json();return{ok:!0,username:t.user?.username??t.user?.email}}catch(n){return{ok:!1,message:`Could not reach Vercel: ${v(n)}`}}}async function le(e){try{let n=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":e,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(n.ok)return{ok:!0};if(n.status===429)return{ok:!0};let t={};try{t=await n.json()}catch{}let i=t.error?.message??"",r=t.error?.status??"";return n.status===400&&(r==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(i))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:n.status===401||n.status===403?{ok:!1,message:i||`Google rejected the key (HTTP ${n.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`}:{ok:!1,message:`Google API returned HTTP ${n.status}${i?`: ${i}`:""}.`}}catch(n){return{ok:!1,message:`Could not reach Google: ${v(n)}`}}}import Kt from"nodemailer";import{ImapFlow as Ht}from"imapflow";async function Fe(e){let n=Kt.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await n.verify()}catch(i){return{ok:!1,failedAt:"smtp",message:He(i,"SMTP")}}finally{n.close()}let t=new Ht({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1});try{await t.connect(),await t.logout()}catch(i){try{await t.logout()}catch{}return{ok:!1,failedAt:"imap",message:He(i,"IMAP")}}return{ok:!0}}function He(e,n){let t=e instanceof Error?e.message:String(e),i=t.toLowerCase();return i.includes("invalid credentials")||i.includes("authentication failed")||i.includes("auth failed")||i.includes("login failed")?`${n} rejected the credentials. Most common causes:
|
|
14
14
|
\u2022 The app password is wrong, expired, or for a different provider.
|
|
15
15
|
\u2022 The email address doesn't match the account that issued the password.
|
|
16
16
|
\u2022 2FA is required but no app-specific password was generated.`:i.includes("etimedout")||i.includes("timeout")?`${n} server didn't respond in time. Check the host/port, or your network.`:i.includes("enotfound")||i.includes("getaddrinfo")?`${n} host could not be resolved. Check the host setting.`:`${n} check failed: ${t}`}async function Ve(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let n=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,t=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let i=await fetch(n,{headers:{Authorization:`Basic ${t}`}});if(i.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!i.ok)return{ok:!1,message:`Twilio API returned HTTP ${i.status}. Try again or check status.twilio.com.`};let r=await i.json();return r.status&&r.status!=="active"?{ok:!1,message:`Twilio account is in '${r.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:r.friendly_name}}catch(i){return{ok:!1,message:`Could not reach Twilio: ${v(i)}`}}}import{spawn as Ft}from"child_process";async function Be(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let t=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,i=await Vt(t);if(i.code===0)return{ok:!0};let r=i.stderr.toLowerCase();return r.includes("can't get application")||r.includes("isn't running")||r.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:r.includes("(-1728)")||r.includes("not found")||r.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:r.includes("(-1719)")||r.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${i.stderr.trim()||`exit code ${i.code}`}`}}function Vt(e){return new Promise(n=>{let t=Ft("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),i="";t.stderr.on("data",r=>{i+=r.toString()}),t.on("close",r=>n({code:r??1,stderr:i})),t.on("error",r=>n({code:1,stderr:r.message}))})}import{spawn as Ge}from"child_process";function Bt(){let e=process.env.NODE_OPTIONS?.trim(),n=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:n}}var G=2,We=2e3,Gt=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Ye(e,n){let t=e+`
|
|
17
17
|
`+n;return Gt.some(i=>i.test(t))}function ze(e){return new Promise(n=>setTimeout(n,e))}function Wt(e,n,t){return new Promise(i=>{let r=Ge(e,n,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:t.env??process.env}),o="",l="";r.stdout?.on("data",a=>{let p=a.toString();o+=p,process.stdout.write(p)}),r.stderr?.on("data",a=>{let p=a.toString();l+=p,process.stderr.write(p)}),r.on("close",a=>i({code:a??1,stdout:o,stderr:l})),r.on("error",a=>i({code:1,stdout:o,stderr:l+a.message}))})}async function ye(e,n,t){let i={code:0,stdout:"",stderr:""};for(let r=0;r<=G;r++){if(i=await Wt(e,n,{cwd:t.cwd,env:t.env}),i.code===0||!Ye(i.stderr,i.stdout))return i;r<G&&(s.detail(`${t.label} failed with a transient network error \u2014 retrying (${r+2}/${G+1})\u2026`),await ze(We))}return i}function we(e,n,t){return new Promise(i=>{let r=Ge(e,n,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),o="",l="";r.stdout?.on("data",a=>{o+=a.toString()}),r.stderr?.on("data",a=>{l+=a.toString()}),r.on("close",a=>i({code:a??1,stdout:o,stderr:l})),r.on("error",a=>i({code:1,stdout:o,stderr:l+a.message}))})}var Yt=[{pattern:/UNABLE_TO_VERIFY_LEAF_SIGNATURE|unable to verify the first certificate/i,hint:"TLS-handshake error \u2014 your machine appears to be intercepting HTTPS (antivirus, corporate proxy, or VPN re-signing traffic with its own root CA). We work around this with NODE_OPTIONS=--use-system-ca, which needs Node 22.15+. Run `node --version` to verify, upgrade if older, then re-run setup."},{pattern:/Microsoft Visual C\+\+ 14\.0 or greater is required/i,hint:"Python tried to compile a package from source and couldn't find the Microsoft C++ Build Tools. The latest Klaudius pins supabase<2.26 to skip the offending dependency entirely. Update with `npm install -g klaudius@latest` and re-run init \u2014 that should bypass the source build."}];function zt(e){let n=`${e.stderr??""}
|
|
18
18
|
${e.stdout??""}`;return Yt.find(i=>i.pattern.test(n))?.hint}async function qt(e){let n=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],t=["-m","pip","install","--quiet","--user"],i=null,r=async l=>{let a={code:0,stdout:"",stderr:""};for(let p=0;p<=G;p++){if(i===null&&(i=(await we("python3",["--version"],{cwd:e})).code===0?"python3":"python"),a=await we(i,l,{cwd:e}),a.code===0||/ENOENT|not recognized as an internal or external command/i.test(a.stderr)&&i==="python3"&&(i="python",a=await we(i,l,{cwd:e}),a.code===0)||!Ye(a.stderr,a.stdout))return a;p<G&&(s.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${G+1})\u2026`),await ze(We))}return a},o=await r([...t,"--break-system-packages",...n]);return o.code!==0&&/no such option:.*break-system-packages/i.test(o.stderr)&&(s.detail("Older pip detected; retrying without --break-system-packages"),o=await r([...t,...n])),o.code!==0&&(o.stderr.trim()&&process.stderr.write(o.stderr),o.stdout.trim()&&process.stdout.write(o.stdout)),o}async function ce(e){let n={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},t=Bt(),i=(p,f)=>{let c=zt(f);c&&((n.hints??={})[p]=c)};s.step("Running npm install (Next.js, Playwright JS, etc.)...");let r=await ye("npm",["install"],{cwd:e,label:"npm install",env:t});n.npm=r.code===0?"ok":"failed",r.code!==0&&i("npm",r),s.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let o=await qt(e);n.pip=o.code===0?"ok":"failed",o.code!==0&&i("pip",o),s.step("Installing Playwright browser (chromium ~200MB; one-time)...");let l=await ye("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:t});n.playwright=l.code===0?"ok":"failed",l.code!==0&&i("playwright",l),s.step("Installing Patchright browser (chromium ~200MB; one-time)...");let a=await ye("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:t});return n.patchright=a.code===0?"ok":"failed",a.code!==0&&i("patchright",a),n}import{spawn as Jt}from"child_process";var W=3,Q=10;function Xt(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}async function de(){let e=await Qt("python3",["--version"]),n=Xt();if(e.code!==0)return{ok:!1,message:`python3 is not installed (or not on PATH). Install Python ${W}.${Q} or newer from ${n}`};let t=(e.stdout+e.stderr).trim(),i=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(t);if(!i)return{ok:!1,message:`Could not parse the python3 version string ("${t}"). Install Python ${W}.${Q} or newer from ${n}`};let r=parseInt(i[1],10),o=parseInt(i[2],10),l=i[3]?`${r}.${o}.${i[3]}`:`${r}.${o}`;return r<W||r===W&&o<Q?{ok:!1,version:l,major:r,minor:o,message:`Your installed Python is ${l}. Klaudius needs Python ${W}.${Q} or newer (the pipeline depends on packages that only ship wheels for ${W}.${Q}+). Install a newer Python from ${n} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:l,major:r,minor:o}}function Qt(e,n){return new Promise(t=>{let i=Jt(e,n,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",o="";i.stdout?.on("data",l=>{r+=l.toString()}),i.stderr?.on("data",l=>{o+=l.toString()}),i.on("close",l=>t({code:l??1,stdout:r,stderr:o})),i.on("error",()=>t({code:1,stdout:r,stderr:o}))})}function Y(){let e=process.version,n=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let t=parseInt(n[1],10),i=parseInt(n[2],10),r=parseInt(n[3],10),o=`${t}.${i}.${r}`;return t<22||t===22&&i<15?{ok:!1,version:o,major:t,minor:i,message:`Your installed Node.js is ${o}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:o,major:t,minor:i}}import{mkdir as Zt,readFile as en,writeFile as tn}from"fs/promises";import{join as qe}from"path";async function ue(e,n){let t=qe(e,".claude");await Zt(t,{recursive:!0});let i=qe(t,"settings.json"),r={};try{let p=await en(i,"utf-8"),f=JSON.parse(p);f&&typeof f=="object"&&!Array.isArray(f)&&(r=f)}catch{}let o=r.enabledMcpjsonServers,l=Array.isArray(o)?o.filter(p=>typeof p=="string"):[];l.includes(n)||l.push(n);let a={...r,enabledMcpjsonServers:l};await tn(i,JSON.stringify(a,null,2)+`
|
|
19
|
-
`,"utf-8")}var an="0.12.
|
|
19
|
+
`,"utf-8")}var an="0.12.3",T=5;function z(e,n){s.blank(),s.error(`${e} validation failed ${T} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${n}`),s.blank(),s.detail("Your credentials are saved in `.env`. Two ways forward:"),s.detail(" \u2022 Open `.env` in any text editor, fix the value, re-run `klaudius init` and pick Resume."),s.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),s.blank(),process.exit(1)}async function tt(e){let n=e.target??".",t=on(n)?n:sn(process.cwd(),n),i=un(t);i&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${t}`),s.detail(`Reason: ${i}`),s.blank(),s.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),s.blank(),process.platform==="win32"?(s.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${d.cyan("cd $HOME\\Documents")}`),console.log(` ${d.cyan("npx klaudius init my-agency")}`)):(s.detail("For example:"),console.log(` ${d.cyan("cd ~/Documents")}`),console.log(` ${d.cyan("npx klaudius init my-agency")}`)),s.blank(),process.exit(1)),process.platform==="win32"&&pn()&&(s.warn("You appear to be running in an elevated (Administrator) PowerShell."),s.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run klaudius init."),s.blank());let r=await ln(t);if(r.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${d.bold(t)}.`),s.detail("(Your .env and project files are in place.)"),s.blank(),r.nodeModulesMissing?(s.detail("It looks like a previous setup didn't finish installing dependencies."),s.detail("To pick up where it left off, run:"),s.blank(),t!==process.cwd()&&console.log(` ${d.cyan(`cd ${n}`)}`),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Everything is scaffolded and dependencies look installed."),s.detail("Pick the action you wanted:"),s.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),s.blank()),s.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius init`."),s.blank();return}if(r.kind==="occupied"){let u=n===".";s.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),s.detail(`Path: ${t}`),s.detail(`Contains: ${r.entries.slice(0,5).join(", ")}${r.entries.length>5?`, \u2026 (+${r.entries.length-5} more)`:""}`),s.blank(),u?(s.detail("Two ways forward:"),s.blank(),s.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius init my-agency")}`),s.blank(),s.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius init")}`)):(s.detail(`The folder '${n}' already exists and isn't empty.`),s.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius init ${n}-2`)}`),s.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let o=await dn(e.license),l=y.spinner();l.start("Validating license");let a=await je(o);a.ok||(l.stop(`License invalid: ${a.reason??"unknown"}`,2),s.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),l.stop(`License valid (${a.tier??"core"} tier)`);let p=await de();p.ok||(s.error(p.message??"Python version check failed."),s.blank(),s.detail("Once you've installed Python 3.10+, re-run `klaudius init` in this folder."),process.exit(1));let f=Y();f.ok||(s.error(f.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `klaudius init` in this folder."),process.exit(1));let c,w=!1;if(r.kind==="partial")if(await cn(t)==="resume"){let h=await Je(r.envPath,"utf-8"),m=ge(x(h));m?(s.success("Resuming with values from your existing .env"),s.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),c=m,w=!0):(s.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),c=await _())}else{let h=await Je(r.envPath,"utf-8"),m=ge(x(h));c=await _(m??{})}else c=await _();c.licenseKey=o,await N(t,c),w||(s.success("Saved .env"),s.success("Saved .mcp.json")),s.blank();for(let u=1;;u++){let h=y.spinner();h.start("Validating Supabase credentials");let m=await B({url:c.supabaseUrl,serviceKey:c.supabaseServiceKey});if(m.ok){h.stop("Supabase credentials accepted");break}h.stop(m.message??"Supabase check failed",2),u>=T&&z("Supabase",m.message??"Supabase check failed");let k=m.message??"Supabase check failed";s.blank(),s.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${u+1} of ${T})`),s.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),s.blank(),c=await _(c,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
20
20
|
${k}
|
|
21
21
|
|
|
22
22
|
Re-enter the URL, secret key, or PAT below. Press Enter on any
|
|
@@ -48,7 +48,7 @@ Re-enter the bot token or chat_id below.
|
|
|
48
48
|
Press Enter on any field to keep its current value.`}),await N(t,c),!c.telegramBotToken||!c.telegramChatId)){s.success("Skipped Telegram. Setup will continue."),h=!0;break}}}s.blank();let P=y.spinner();P.start("Downloading Klaudius template");let M;try{M=(await oe({licenseKey:o,machineId:X(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,destDir:t})).filesExtracted,P.stop(`Downloaded ${M} files into ${d.bold(t)}`)}catch(u){P.stop(u.message,2),s.detail("Your .env / .mcp.json are saved. Re-run init once the issue is resolved to retry the download."),process.exit(1)}await Ze(Z(t,"clients"),{recursive:!0});let E=await Re(t);await re(t,Le(an,E)),s.success("Wrote .klaudius/manifest.json");let U=!1,O="";if(e.skipSchema)s.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),s.detail(`Apply manually later via the SQL editor: ${c.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+c.supabaseProjectRef+"/sql/new").replace(c.supabaseProjectRef+".supabase.co","")}`);else{s.blank();let u=y.spinner();u.start("Applying schema to Supabase");let h=await Ke({projectRoot:t,pat:c.supabasePat,projectRef:c.supabaseProjectRef});h.ok?u.stop("Schema applied (or already present)"):(u.stop(h.message??"Schema apply failed",2),U=!0,O=`https://supabase.com/dashboard/project/${c.supabaseProjectRef}/sql/new`)}let S=[],C={};if(e.skipInstall)s.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{s.blank(),s.heading("Installing dependencies");let u=await ce(t);s.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&S.push("npm"),u.pip==="failed"&&S.push("pip"),u.playwright==="failed"&&S.push("playwright"),u.patchright==="failed"&&S.push("patchright"),C=u.hints??{}}let g=c.outreachEnabled&&c.outreachPriority?.includes("whatsapp")&&(c.whatsappAccounts?.length??0)>0,$=!e.skipInstall&&!S.includes("npm");if(g&&$){s.blank(),s.heading("Linking WhatsApp accounts"),console.log(d.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
|
|
49
49
|
phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
|
|
50
50
|
Link a Device, and point it at the QR shown in this terminal.`)),s.blank();for(let u of c.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${u}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius pair-whatsapp --label ${u})`));let h=et(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:t,stdio:"inherit"});h.status===0?s.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${h.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))),s.blank()}}else if(g&&!$){s.blank(),console.log(d.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius install` completes successfully, pair via:"));for(let u of c.whatsappAccounts)console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))}s.blank();let K=[...S,...U?["schema"]:[]];if(K.length>0){y.outro(d.yellow(d.bold(`Setup paused \u2014 ${K.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),s.blank();for(let[k,fe]of Object.entries(C))console.log(d.yellow(`Likely cause of ${k} failure:`)),console.log(d.dim(` ${fe}`)),s.blank();let u=t!==process.cwd()?` ${d.cyan(`cd ${e.target}`)}
|
|
51
|
-
`:"";S.length>0&&(console.log(d.dim("Easiest fix \u2014 let Claude finish it for you:")),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("claude")} ${d.dim("# open Claude Code in this folder")}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${S.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius doctor."`)),s.blank(),console.log(d.dim(" (Don't have Claude Code yet? Install with: `npm install -g @anthropic-ai/claude-code`)")),s.blank(),console.log(d.dim("Or do it yourself:")),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify everything")}`),s.blank()),U&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(O)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),S.includes("pip")&&!C.pip&&(console.log(d.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(d.dim(`Python 3.10+. Install a newer one from ${mn()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),s.blank());let m=["npm","playwright","patchright"].filter(k=>S.includes(k)&&!C[k]);if(m.length>0){let k=m.length===1?"keeps":"keep";console.log(d.dim(`If ${m.join(" / ")} ${k} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius install`.")),s.blank()}console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}y.outro(d.green(d.bold("Project ready."))),console.log(d.dim("Next steps:")),t!==process.cwd()&&console.log(` ${d.cyan(`cd ${e.target}`)}`);let J=process.platform==="win32"?"start":process.platform==="linux"?"xdg-open":"open",yt=d.dim("# read this first \u2014 operator basics + commands");console.log(` ${d.cyan(`${J} DOCS.html`)}${" ".repeat(Math.max(1,17-J.length))}${yt}`),console.log(` ${d.cyan("claude")} ${d.dim("# open Claude Code in this project")}`),console.log(` ${d.dim("then ask Claude:")}`),console.log(` ${d.cyan(' "Run the pipeline."')}`),s.blank()}async function N(e,n){await Ze(e,{recursive:!0}),await Qe(Z(e,".env"),se(n),"utf-8"),await Qe(Z(e,".mcp.json"),ie(n),"utf-8"),await ue(e,"supabase")}async function ln(e){try{(await Xe(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let n=await nn(e),t=n.filter(a=>!a.startsWith(".DS_Store"));if(t.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude"]),r=t.every(a=>i.has(a)),o=t.includes(".env"),l=n.includes(".klaudius");if(r&&o&&!l)return{kind:"partial",envPath:Z(e,".env")};if(l&&o){let a=!0;try{a=!(await Xe(Z(e,"node_modules"))).isDirectory()}catch{a=!0}return{kind:"scaffolded",nodeModulesMissing:a}}return{kind:"occupied",entries:t}}async function cn(e){s.blank(),s.warn(`Found a partial setup at ${d.bold(e)}.`),s.detail(`A previous init wrote ${d.bold(".env")} but didn't finish scaffolding.`),s.blank();let n=await y.select({message:"How would you like to proceed?",initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return y.isCancel(n)&&(y.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),n}async function dn(e){if(e&&e.trim().length>0)return e;y.intro("Klaudius");let n=await y.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:t=>t.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return y.isCancel(n)&&(y.cancel("Setup cancelled. No files written."),process.exit(0)),n}function un(e){let n=rn(e);if(process.platform==="win32"){let t=n.toLowerCase();if(t.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(t.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(t.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(t.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let t=["/System/","/usr/","/bin/","/sbin/"];for(let i of t)if(n.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function pn(){if(process.platform!=="win32")return!1;try{return et("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function mn(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}import{access as fn}from"fs/promises";import{join as nt,resolve as hn}from"path";import R from"picocolors";async function it(e){let n=e.target?hn(process.cwd(),e.target):process.cwd(),t=await st(nt(n,".env")),i=await st(nt(n,"package.json"));(!t||!i)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${n}`),t||s.detail("Missing: .env"),i||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1)),s.heading("Installing dependencies");let r=await ce(n);s.blank(),s.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let o=[];if(r.npm==="failed"&&o.push("npm"),r.pip==="failed"&&o.push("pip"),r.playwright==="failed"&&o.push("playwright"),r.patchright==="failed"&&o.push("patchright"),o.length===0){s.blank(),console.log(R.green(R.bold("All dependencies installed."))),console.log(R.dim("Run `npx klaudius doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(R.yellow(R.bold(`${o.join(", ")} still failing.`))),s.blank();for(let[l,a]of Object.entries(r.hints??{}))console.log(R.yellow(`Likely cause of ${l} failure:`)),console.log(R.dim(` ${a}`)),s.blank();console.log(R.dim("Options:")),console.log(R.dim(" \u2022 Open Claude Code in this folder (`claude`) and paste:")),console.log(R.cyan(` "Finish my Klaudius install \u2014 ${o.join(", ")} failed. Debug the install output, retry, then run npx klaudius doctor."`)),console.log(R.dim(" (Don't have Claude Code yet? Install with: `npm install -g @anthropic-ai/claude-code`)")),console.log(R.dim(" \u2022 Or run `npx klaudius doctor` for a structured diagnostic.")),console.log(R.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function st(e){try{return await fn(e),!0}catch{return!1}}import{readFile as gn,writeFile as ot,access as yn}from"fs/promises";import{join as pe}from"path";import*as me from"@clack/prompts";import H from"picocolors";async function rt(e){let n=e.projectRoot??process.cwd(),t=pe(n,".env"),i=pe(n,".mcp.json"),r=await ke(pe(n,".klaudius","manifest.json")),o=await ke(t);!r&&!o&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius init` first."),process.exit(1));let l=Y();l.ok||(s.error(l.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `klaudius configure` in this folder."),process.exit(1));let a={};try{let c=await gn(t,"utf-8");a=x(c)}catch{s.warn("No .env found. Starting from an empty configuration.")}let p=ve(a);me.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let f=await _(p);if(f.supabaseUrl!==a.SUPABASE_URL||f.supabaseServiceKey!==a.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let c=await B({url:f.supabaseUrl,serviceKey:f.supabaseServiceKey});c.ok||(s.error(c.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}await ot(t,se(f),"utf-8"),s.success("Updated .env"),await ot(i,ie(f),"utf-8"),s.success("Updated .mcp.json"),await ue(n,"supabase"),s.blank(),me.outro(H.green("Configuration updated.")),await wn(n,r)}async function wn(e,n){let t=await ke(pe(e,"node_modules"));s.blank(),n?t||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${H.cyan("npx klaudius install")} ${H.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${H.cyan("npx klaudius doctor")} ${H.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${H.cyan("npx klaudius init")} ${H.dim("# pick Resume when prompted")}`),s.blank())}async function ke(e){try{return await yn(e),!0}catch{return!1}}import{copyFile as at,mkdir as lt,readdir as kn,readFile as En,rm as ee,writeFile as ct,access as dt}from"fs/promises";import{dirname as ut,join as I,relative as Pn}from"path";import{tmpdir as bn}from"os";import*as q from"@clack/prompts";import Ee from"picocolors";var Pe="0.12.2";async function pt(e){let n=e.projectRoot??process.cwd(),t=await Ne(n);t||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius init` first."),process.exit(1));let i,r=I(n,".env"),o,l;try{o=await En(r,"utf-8"),l=x(o)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=l.KLAUDIUS_LICENSE_KEY??"",i||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let a=Ce(o,l,Ie);a!==null&&(await ct(r,a,"utf-8"),s.detail("Backfilled new env keys")),q.intro(`Update from ${t.templateVersion} \u2192 ${Pe}`);let p=I(bn(),`klaudius-update-${process.pid}-${Date.now()}`),f;try{s.heading("Downloading the latest Klaudius template");let g=await oe({licenseKey:i,machineId:X(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,destDir:p});s.success(`Fetched ${g.filesExtracted} canonical files`),f=p}catch(g){s.error(g.message),s.detail("Update aborted. Your project is unchanged."),await ee(p,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let c=await An(f,n,t),w=c.filter(g=>g.state==="new"),P=c.filter(g=>g.state==="clean-update"),M=c.filter(g=>g.state==="user-only"),E=c.filter(g=>g.state==="conflict"),U=c.filter(g=>g.state==="no-change"),O=c.filter(g=>g.state==="removed-clean"),S=c.filter(g=>g.state==="removed-modified"),C=[...E,...S];if(s.blank(),s.heading("Change summary"),s.detail(`${L(U.length,"file")} unchanged`),s.detail(`${L(w.length,"new file")}`),s.detail(`${L(P.length,"file")} updated cleanly (no local edits)`),s.detail(`${L(M.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${L(O.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${L(E.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${L(S.length,"file")} removed upstream but edited locally (need your decision)`),w.length===0&&P.length===0&&O.length===0&&C.length===0){s.blank(),q.outro(Ee.green("Already up to date.")),await ee(p,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let g of[...w,...P]){let $=I(f,g.path),K=I(n,g.path);await lt(ut(K),{recursive:!0}),await at($,K),t.files[g.path]=g.canonicalHash}w.length+P.length>0&&s.success(`Wrote ${L(w.length+P.length,"file")}`);for(let g of O){let $=I(n,g.path);await ee($,{force:!0}),delete t.files[g.path]}if(O.length>0&&s.success(`Deleted ${L(O.length,"file")} removed upstream`),C.length>0){s.blank(),s.heading(`${C.length} conflict(s) need resolution`);let g=I(n,".klaudius","incoming");try{await ee(g,{recursive:!0,force:!0})}catch{}for(let $ of E){let K=I(f,$.path),J=I(g,$.path);await lt(ut(J),{recursive:!0}),await at(K,J)}await ct(I(n,".klaudius","conflicts.md"),Sn(C,t.templateVersion,Pe),"utf-8"),E.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}t.updatedAt=new Date().toISOString(),C.length===0&&(t.templateVersion=Pe),await re(n,t),s.blank(),C.length===0?q.outro(Ee.green("Update complete.")):q.outro(Ee.yellow(`${C.length} conflict(s) staged. Open Claude Code in this project and ask:
|
|
51
|
+
`:"";S.length>0&&(console.log(d.dim("Easiest fix \u2014 let Claude finish it for you:")),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("claude")} ${d.dim("# open Claude Code in this folder")}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${S.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius doctor."`)),s.blank(),console.log(d.dim(" (Don't have Claude Code yet? Install with: `npm install -g @anthropic-ai/claude-code`)")),s.blank(),console.log(d.dim("Or do it yourself:")),s.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify everything")}`),s.blank()),U&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(O)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),S.includes("pip")&&!C.pip&&(console.log(d.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(d.dim(`Python 3.10+. Install a newer one from ${mn()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),s.blank());let m=["npm","playwright","patchright"].filter(k=>S.includes(k)&&!C[k]);if(m.length>0){let k=m.length===1?"keeps":"keep";console.log(d.dim(`If ${m.join(" / ")} ${k} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius install`.")),s.blank()}console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}y.outro(d.green(d.bold("Project ready."))),console.log(d.dim("Next steps:")),t!==process.cwd()&&console.log(` ${d.cyan(`cd ${e.target}`)}`);let J=process.platform==="win32"?"start":process.platform==="linux"?"xdg-open":"open",yt=d.dim("# read this first \u2014 operator basics + commands");console.log(` ${d.cyan(`${J} DOCS.html`)}${" ".repeat(Math.max(1,17-J.length))}${yt}`),console.log(` ${d.cyan("claude")} ${d.dim("# open Claude Code in this project")}`),console.log(` ${d.dim("then ask Claude:")}`),console.log(` ${d.cyan(' "Run the pipeline."')}`),s.blank()}async function N(e,n){await Ze(e,{recursive:!0}),await Qe(Z(e,".env"),se(n),"utf-8"),await Qe(Z(e,".mcp.json"),ie(n),"utf-8"),await ue(e,"supabase")}async function ln(e){try{(await Xe(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let n=await nn(e),t=n.filter(a=>!a.startsWith(".DS_Store"));if(t.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude"]),r=t.every(a=>i.has(a)),o=t.includes(".env"),l=n.includes(".klaudius");if(r&&o&&!l)return{kind:"partial",envPath:Z(e,".env")};if(l&&o){let a=!0;try{a=!(await Xe(Z(e,"node_modules"))).isDirectory()}catch{a=!0}return{kind:"scaffolded",nodeModulesMissing:a}}return{kind:"occupied",entries:t}}async function cn(e){s.blank(),s.warn(`Found a partial setup at ${d.bold(e)}.`),s.detail(`A previous init wrote ${d.bold(".env")} but didn't finish scaffolding.`),s.blank();let n=await y.select({message:"How would you like to proceed?",initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return y.isCancel(n)&&(y.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),n}async function dn(e){if(e&&e.trim().length>0)return e;y.intro("Klaudius");let n=await y.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:t=>t.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return y.isCancel(n)&&(y.cancel("Setup cancelled. No files written."),process.exit(0)),n}function un(e){let n=rn(e);if(process.platform==="win32"){let t=n.toLowerCase();if(t.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(t.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(t.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(t.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let t=["/System/","/usr/","/bin/","/sbin/"];for(let i of t)if(n.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function pn(){if(process.platform!=="win32")return!1;try{return et("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function mn(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}import{access as fn}from"fs/promises";import{join as nt,resolve as hn}from"path";import R from"picocolors";async function it(e){let n=e.target?hn(process.cwd(),e.target):process.cwd(),t=await st(nt(n,".env")),i=await st(nt(n,"package.json"));(!t||!i)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${n}`),t||s.detail("Missing: .env"),i||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1)),s.heading("Installing dependencies");let r=await ce(n);s.blank(),s.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let o=[];if(r.npm==="failed"&&o.push("npm"),r.pip==="failed"&&o.push("pip"),r.playwright==="failed"&&o.push("playwright"),r.patchright==="failed"&&o.push("patchright"),o.length===0){s.blank(),console.log(R.green(R.bold("All dependencies installed."))),console.log(R.dim("Run `npx klaudius doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(R.yellow(R.bold(`${o.join(", ")} still failing.`))),s.blank();for(let[l,a]of Object.entries(r.hints??{}))console.log(R.yellow(`Likely cause of ${l} failure:`)),console.log(R.dim(` ${a}`)),s.blank();console.log(R.dim("Options:")),console.log(R.dim(" \u2022 Open Claude Code in this folder (`claude`) and paste:")),console.log(R.cyan(` "Finish my Klaudius install \u2014 ${o.join(", ")} failed. Debug the install output, retry, then run npx klaudius doctor."`)),console.log(R.dim(" (Don't have Claude Code yet? Install with: `npm install -g @anthropic-ai/claude-code`)")),console.log(R.dim(" \u2022 Or run `npx klaudius doctor` for a structured diagnostic.")),console.log(R.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function st(e){try{return await fn(e),!0}catch{return!1}}import{readFile as gn,writeFile as ot,access as yn}from"fs/promises";import{join as pe}from"path";import*as me from"@clack/prompts";import H from"picocolors";async function rt(e){let n=e.projectRoot??process.cwd(),t=pe(n,".env"),i=pe(n,".mcp.json"),r=await ke(pe(n,".klaudius","manifest.json")),o=await ke(t);!r&&!o&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius init` first."),process.exit(1));let l=Y();l.ok||(s.error(l.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `klaudius configure` in this folder."),process.exit(1));let a={};try{let c=await gn(t,"utf-8");a=x(c)}catch{s.warn("No .env found. Starting from an empty configuration.")}let p=ve(a);me.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let f=await _(p);if(f.supabaseUrl!==a.SUPABASE_URL||f.supabaseServiceKey!==a.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let c=await B({url:f.supabaseUrl,serviceKey:f.supabaseServiceKey});c.ok||(s.error(c.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}await ot(t,se(f),"utf-8"),s.success("Updated .env"),await ot(i,ie(f),"utf-8"),s.success("Updated .mcp.json"),await ue(n,"supabase"),s.blank(),me.outro(H.green("Configuration updated.")),await wn(n,r)}async function wn(e,n){let t=await ke(pe(e,"node_modules"));s.blank(),n?t||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${H.cyan("npx klaudius install")} ${H.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${H.cyan("npx klaudius doctor")} ${H.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${H.cyan("npx klaudius init")} ${H.dim("# pick Resume when prompted")}`),s.blank())}async function ke(e){try{return await yn(e),!0}catch{return!1}}import{copyFile as at,mkdir as lt,readdir as kn,readFile as En,rm as ee,writeFile as ct,access as dt}from"fs/promises";import{dirname as ut,join as I,relative as Pn}from"path";import{tmpdir as bn}from"os";import*as q from"@clack/prompts";import Ee from"picocolors";var Pe="0.12.3";async function pt(e){let n=e.projectRoot??process.cwd(),t=await Ne(n);t||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius init` first."),process.exit(1));let i,r=I(n,".env"),o,l;try{o=await En(r,"utf-8"),l=x(o)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=l.KLAUDIUS_LICENSE_KEY??"",i||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let a=Ce(o,l,Ie);a!==null&&(await ct(r,a,"utf-8"),s.detail("Backfilled new env keys")),q.intro(`Update from ${t.templateVersion} \u2192 ${Pe}`);let p=I(bn(),`klaudius-update-${process.pid}-${Date.now()}`),f;try{s.heading("Downloading the latest Klaudius template");let g=await oe({licenseKey:i,machineId:X(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,destDir:p});s.success(`Fetched ${g.filesExtracted} canonical files`),f=p}catch(g){s.error(g.message),s.detail("Update aborted. Your project is unchanged."),await ee(p,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let c=await An(f,n,t),w=c.filter(g=>g.state==="new"),P=c.filter(g=>g.state==="clean-update"),M=c.filter(g=>g.state==="user-only"),E=c.filter(g=>g.state==="conflict"),U=c.filter(g=>g.state==="no-change"),O=c.filter(g=>g.state==="removed-clean"),S=c.filter(g=>g.state==="removed-modified"),C=[...E,...S];if(s.blank(),s.heading("Change summary"),s.detail(`${L(U.length,"file")} unchanged`),s.detail(`${L(w.length,"new file")}`),s.detail(`${L(P.length,"file")} updated cleanly (no local edits)`),s.detail(`${L(M.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${L(O.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${L(E.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${L(S.length,"file")} removed upstream but edited locally (need your decision)`),w.length===0&&P.length===0&&O.length===0&&C.length===0){s.blank(),q.outro(Ee.green("Already up to date.")),await ee(p,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let g of[...w,...P]){let $=I(f,g.path),K=I(n,g.path);await lt(ut(K),{recursive:!0}),await at($,K),t.files[g.path]=g.canonicalHash}w.length+P.length>0&&s.success(`Wrote ${L(w.length+P.length,"file")}`);for(let g of O){let $=I(n,g.path);await ee($,{force:!0}),delete t.files[g.path]}if(O.length>0&&s.success(`Deleted ${L(O.length,"file")} removed upstream`),C.length>0){s.blank(),s.heading(`${C.length} conflict(s) need resolution`);let g=I(n,".klaudius","incoming");try{await ee(g,{recursive:!0,force:!0})}catch{}for(let $ of E){let K=I(f,$.path),J=I(g,$.path);await lt(ut(J),{recursive:!0}),await at(K,J)}await ct(I(n,".klaudius","conflicts.md"),Sn(C,t.templateVersion,Pe),"utf-8"),E.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}t.updatedAt=new Date().toISOString(),C.length===0&&(t.templateVersion=Pe),await re(n,t),s.blank(),C.length===0?q.outro(Ee.green("Update complete.")):q.outro(Ee.yellow(`${C.length} conflict(s) staged. Open Claude Code in this project and ask:
|
|
52
52
|
"Run /resolve-conflicts"`)),await ee(p,{recursive:!0,force:!0}).catch(()=>{})}async function An(e,n,t){let i=await mt(e),r=new Set(i),o=[];for(let l of i){let a=await ne(I(e,l)),p=t.files[l],f=I(n,l),c;try{await dt(f),c=await ne(f)}catch{o.push({path:l,state:"new",canonicalHash:a,manifestHash:p});continue}a===p?c===p?o.push({path:l,state:"no-change",canonicalHash:a,localHash:c,manifestHash:p}):o.push({path:l,state:"user-only",canonicalHash:a,localHash:c,manifestHash:p}):c===p?o.push({path:l,state:"clean-update",canonicalHash:a,localHash:c,manifestHash:p}):o.push({path:l,state:"conflict",canonicalHash:a,localHash:c,manifestHash:p})}for(let l of Object.keys(t.files)){if(r.has(l))continue;let a=t.files[l],p=I(n,l),f;try{await dt(p),f=await ne(p)}catch{delete t.files[l];continue}f===a?o.push({path:l,state:"removed-clean",localHash:f,manifestHash:a}):o.push({path:l,state:"removed-modified",localHash:f,manifestHash:a})}return o}function L(e,n){return`${e} ${n}${e===1?"":"s"}`}async function mt(e,n=e){let t=await kn(e,{withFileTypes:!0}),i=[];for(let r of t){let o=I(e,r.name);r.isDirectory()?i.push(...await mt(o,n)):r.isFile()&&i.push(Pn(n,o))}return i}function Sn(e,n,t){let i=e.filter(a=>a.state==="conflict").length,r=e.filter(a=>a.state==="removed-modified").length,o=[];o.push("# Update Conflicts"),o.push(""),o.push(`Generated by \`npx klaudius update\` on ${new Date().toISOString()}.`),o.push(`Updating from canonical version **${n}** to **${t}**.`),o.push("");let l=[];i>0&&l.push(`${i} file${i===1?"":"s"} ha${i===1?"s":"ve"} BOTH local edits AND upstream changes`),r>0&&l.push(`${r} file${r===1?"":"s"} ${r===1?"was":"were"} removed upstream but edited locally`),o.push(l.join(", and ")+"."),o.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),o.push(""),o.push("---"),o.push("");for(let a of e)o.push(`## ${a.path}`),o.push(""),a.state==="removed-modified"?(o.push("**Type:** Removed upstream"),o.push(""),o.push(`- Your local copy: \`${a.path}\``),o.push("- This file no longer exists in the canonical template."),o.push("- You've modified it locally since install."),o.push(`- Hash at last install/update: \`${(a.manifestHash??"(none)").slice(0,16)}\``),o.push(`- Your local hash now: \`${(a.localHash??"(missing)").slice(0,16)}\``),o.push(""),o.push("**Resolution options for the SKILL to walk through:**"),o.push(""),o.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),o.push("2. Delete \u2014 remove the file from disk and from the manifest")):(o.push("**Type:** Edit conflict"),o.push(""),o.push(`- Your version (with your local edits): \`${a.path}\``),o.push(`- New canonical version: \`.klaudius/incoming/${a.path}\``),o.push(`- Hash at last install/update: \`${(a.manifestHash??"(none)").slice(0,16)}\``),o.push(`- Your local hash now: \`${(a.localHash??"(missing)").slice(0,16)}\``),o.push(`- New canonical hash: \`${(a.canonicalHash??"(none)").slice(0,16)}\``),o.push(""),o.push("**Resolution options for the SKILL to walk through:**"),o.push(""),o.push("1. Keep mine \u2014 discard the new canonical changes"),o.push("2. Take canonical \u2014 overwrite my edits with the new version"),o.push("3. Merge \u2014 review both side-by-side and produce a combined version")),o.push(""),o.push("---"),o.push("");return o.join(`
|
|
53
53
|
`)}import{access as _n,readFile as Tn,stat as Rn}from"fs/promises";import{join as F}from"path";import b from"picocolors";import{spawn as In}from"child_process";async function ft(e){let n=e.projectRoot??process.cwd(),t=[];console.log(b.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
54
54
|
`)),t.push(await Cn()),t.push(await vn());let i=F(n,".env"),r=F(n,".klaudius","manifest.json"),o=F(n,".mcp.json"),l=await te(i),a=await te(r),p=await te(o);if(t.push({name:".env present",status:l?"ok":"fail",detail:l?i:"missing",nextAction:l?void 0:"Run `klaudius init` in this folder."}),t.push({name:"Template scaffolded (.klaudius/manifest.json)",status:a?"ok":"fail",detail:a?r:"missing",nextAction:a?void 0:l?"Init didn't finish \u2014 run `klaudius init` and pick Resume.":"Run `klaudius init`."}),t.push({name:".mcp.json present",status:p?"ok":"warn",detail:p?o:"missing",nextAction:p?void 0:"Run `klaudius configure` to regenerate."}),t.push(await On(n)),t.push(await $n(n)),t.push(await xn()),!l)t.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)t.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let w=await Tn(i,"utf-8"),P=x(w);await Nn(P,t)}console.log();for(let w of t){let P=w.status==="ok"?b.green("\u2713"):w.status==="warn"?b.yellow("\u26A0"):w.status==="skip"?b.dim("\xB7"):b.red("\u2717");console.log(` ${P} ${w.name}${w.detail?b.dim(` \u2014 ${w.detail}`):""}`),w.nextAction&&console.log(` ${b.dim("\u2192")} ${b.cyan(w.nextAction)}`)}let f=t.filter(w=>w.status==="fail").length,c=t.filter(w=>w.status==="warn").length;console.log(),f===0&&c===0?console.log(b.green(b.bold("Everything checks out. You're good to go."))):f===0?console.log(b.yellow(b.bold(`${c} warning${c===1?"":"s"} \u2014 review above.`))):(console.log(b.red(b.bold(`${f} failed check${f===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function te(e){try{return await _n(e),!0}catch{return!1}}async function Cn(){let e=await de();return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:"Install Python 3.10+ from https://www.python.org/downloads/"}}async function vn(){let e=process.version,n=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!n)return{name:"Node \u2265 22.15",status:"warn",detail:e};let t=parseInt(n[1],10),i=parseInt(n[2],10);return t<22||t===22&&i<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function On(e){let n=F(e,"node_modules");if(!await te(n))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius install` in this folder."};try{if(!(await Rn(n)).isDirectory())return{name:"node_modules installed",status:"warn",detail:"exists but isn't a directory"}}catch{}return{name:"node_modules installed",status:"ok"}}async function $n(e){let n=process.platform==="darwin"?F(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?F(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):F(process.env.HOME??"",".cache","ms-playwright");return await te(n)?{name:"Playwright browser installed",status:"ok",detail:n}:{name:"Playwright browser installed",status:"fail",detail:"no browser cache found",nextAction:"Run `npx playwright install chromium` in this folder."}}async function xn(){let e=["supabase","dotenv","requests","httpx","PIL"],n=`import sys
|
|
@@ -63,4 +63,4 @@ except Exception as e:
|
|
|
63
63
|
`));let o=Un(process.execPath,[t,"pair","--account",r],{cwd:n,stdio:"inherit"});if(o.status===0){console.log(A.green(`Paired '${r}'.`)),console.log(A.dim(`
|
|
64
64
|
If you haven't already, add '${r}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
65
65
|
WHATSAPP_ACCOUNTS=primary,${r}
|
|
66
|
-
(Skip this if '${r}' is already there or you set it via the init wizard.)`));return}o.error?console.error(A.red(`Pair failed: ${o.error.message}`)):(console.error(A.red(`Pair did not complete (exit ${o.status??"signalled"}). Common causes:`)),console.error(A.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(A.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(A.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${r}/daemon.log`))),process.exit(o.status??1)}import{spawnSync as Kn}from"child_process";var be="--use-system-ca";function gt(){let e=process.env.NODE_OPTIONS??"";if(e.includes(be)||!Y().ok)return;let t=e?`${e} ${be}`:be,i=Kn(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:t},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}gt();var Fn="0.12.
|
|
66
|
+
(Skip this if '${r}' is already there or you set it via the init wizard.)`));return}o.error?console.error(A.red(`Pair failed: ${o.error.message}`)):(console.error(A.red(`Pair did not complete (exit ${o.status??"signalled"}). Common causes:`)),console.error(A.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(A.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(A.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${r}/daemon.log`))),process.exit(o.status??1)}import{spawnSync as Kn}from"child_process";var be="--use-system-ca";function gt(){let e=process.env.NODE_OPTIONS??"";if(e.includes(be)||!Y().ok)return;let t=e?`${e} ${be}`:be,i=Kn(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:t},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}gt();var Fn="0.12.3",j=new Hn;j.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Fn);j.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").action(async(e,n)=>{try{await tt({target:e,license:n.license,skipInstall:!!n.skipInstall,skipSchema:!!n.skipSchema})}catch(t){console.error("init failed:",t.message),process.exit(1)}});j.command("install").description("Re-run dependency installers against an already-scaffolded project (npm, pip, playwright, patchright)").argument("[target]","Project directory (defaults to current directory)").action(async e=>{try{await it({target:e})}catch(n){console.error("install failed:",n.message),process.exit(1)}});j.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await rt({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});j.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await pt({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});j.command("doctor").description("Diagnose a broken install \u2014 env versions, files, installed deps, credentials").option("--offline","Skip credential validations that require network calls").action(async e=>{try{await ft({offline:!!e.offline})}catch(n){console.error("doctor failed:",n.message),process.exit(1)}});j.command("pair-whatsapp").description("Link a WhatsApp account to this project (or re-pair if it logged out)").option("--label <name>","Account label (default: primary). Should match a value in WHATSAPP_ACCOUNTS.","primary").action(async e=>{try{await ht({label:e.label})}catch(n){console.error("pair-whatsapp failed:",n.message),process.exit(1)}});j.parse(process.argv);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.3",
|
|
4
4
|
"description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code (find, build, deploy, outreach end-to-end).",
|
|
5
5
|
"homepage": "https://klaudius.dev",
|
|
6
6
|
"bugs": {
|