klaudius 0.15.0 → 0.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as y,e as ee}from"./chunk-SZ4KCTSL.js";import{useEffect as na,useMemo as ta,useRef as Q,useState as M}from"react";import{Box as
|
|
1
|
+
import{a as y,e as ee}from"./chunk-SZ4KCTSL.js";import{useEffect as na,useMemo as ta,useRef as Q,useState as M}from"react";import{Box as v,Text as E,useApp as oa,useInput as ia}from"ink";var ae={gmail:{label:"Gmail",smtpHost:"smtp.gmail.com",smtpPort:587,imapHost:"imap.gmail.com",imapPort:993,sentFolder:"[Gmail]/Sent Mail",inboxFolder:"INBOX",appPasswordHelp:`Generate at https://myaccount.google.com/apppasswords
|
|
2
2
|
(2-step verification must be enabled on your Google account first;
|
|
3
3
|
Google won't accept your normal account password from third-party apps).`},outlook:{label:"Outlook / Office 365",smtpHost:"smtp-mail.outlook.com",smtpPort:587,imapHost:"outlook.office365.com",imapPort:993,sentFolder:"Sent Items",inboxFolder:"INBOX",appPasswordHelp:`Generate at https://account.microsoft.com/security \u2192 Advanced security options \u2192 App passwords
|
|
4
4
|
(2-step verification must be enabled first).`},ionos:{label:"IONOS",smtpHost:"smtp.ionos.co.uk",smtpPort:587,imapHost:"imap.ionos.co.uk",imapPort:993,sentFolder:"Sent Items",inboxFolder:"INBOX",appPasswordHelp:`Use your normal IONOS mailbox password.
|
|
@@ -22,13 +22,12 @@ businesses, pick United Kingdom here.
|
|
|
22
22
|
You can run the pipeline against more than one country from the same
|
|
23
23
|
install (\`/find Barcelona\` from a UK install works fine), but
|
|
24
24
|
starting with one market makes it easier to learn that market's
|
|
25
|
-
outreach rhythm.
|
|
26
|
-
\`npx klaudius configure\`.`});let n="__other__",s=[{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)"}],i=e.country??"",o=s.some(b=>b.value===i),u=await a({type:"select",message:"Which country's businesses will Klaudius search for?",initialValue:o?i:i?n:"the United Kingdom",options:s}),r;u===n?r=await a({type:"text",message:"Type the country name (any common form is fine)",placeholder:"e.g. South Africa, Greece, Brazil",initialValue:o?"":i,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
|
|
25
|
+
outreach rhythm.`});let n="__other__",s=[{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)"}],i=e.country??"",o=s.some(b=>b.value===i),u=await a({type:"select",message:"Which country's businesses will Klaudius search for?",initialValue:o?i:i?n:"the United Kingdom",options:s}),l;u===n?l=await a({type:"text",message:"Type the country name (any common form is fine)",placeholder:"e.g. South Africa, Greece, Brazil",initialValue:o?"":i,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
|
|
27
26
|
ISO 3166 sovereign states + common territories like Hong Kong and
|
|
28
27
|
Puerto Rico). If we don't recognise the name, we'll ask you to type
|
|
29
28
|
the 2-letter ISO country code directly on the next prompt \u2014 the
|
|
30
29
|
same code Google Places uses for region biasing. Aliases like 'uk',
|
|
31
|
-
'usa', 'italia', 'maroc' all match.`}}):
|
|
30
|
+
'usa', 'italia', 'maroc' all match.`}}):l=u;let r=te(l),d;r?d=r.code:d=(await a({type:"text",message:`What's the 2-letter ISO country code for ${l}?`,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 ${l}`,body:`We didn't recognise "${l}" in our country lookup, so we need the
|
|
32
31
|
2-letter ISO 3166-1 alpha-2 code directly. Google Places uses this
|
|
33
32
|
for region biasing on every search.
|
|
34
33
|
|
|
@@ -37,8 +36,8 @@ Full list: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
|
|
|
37
36
|
Quick reference for less common markets:
|
|
38
37
|
Indonesia \u2192 ID Vietnam \u2192 VN Thailand \u2192 TH Egypt \u2192 EG
|
|
39
38
|
Kenya \u2192 KE Nigeria \u2192 NG Pakistan \u2192 PK Iran \u2192 IR
|
|
40
|
-
Saudi Arabia \u2192 SA Russia \u2192 RU Ukraine \u2192 UA Israel \u2192 IL`}})).trim().toUpperCase();let w=e.language??
|
|
41
|
-
for ${
|
|
39
|
+
Saudi Arabia \u2192 SA Russia \u2192 RU Ukraine \u2192 UA Israel \u2192 IL`}})).trim().toUpperCase();let w=e.language??r?.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:r?`Defaulting to ${w} (the usual operator-facing language
|
|
40
|
+
for ${l}). Edit this if you'd rather write in something else \u2014
|
|
42
41
|
e.g. an English-speaking operator running on Spain might pick "Spanish"
|
|
43
42
|
to localise everything, or might pick "English" to keep their own voice.
|
|
44
43
|
Klaudius will use this language for every outreach message it sends and
|
|
@@ -52,7 +51,7 @@ site.
|
|
|
52
51
|
Most languages have a 2-letter ISO 639-1 code. A few (Filipino \u2192
|
|
53
52
|
"fil") use the 3-letter ISO 639-3 / BCP 47 code instead.
|
|
54
53
|
|
|
55
|
-
Full list: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes`}})).trim().toLowerCase(),{country:
|
|
54
|
+
Full list: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes`}})).trim().toLowerCase(),{country:r?r.country:l.trim(),countryCode:d,language:A?A.language:f.trim(),languageCode:I}}},Oe={id:"pricing",title:"Pricing",isApplicable:()=>!0,execute:async(e,{prompt:a})=>{let t=e.pricingTerms===se,n=t?"":e.pricing??"$999",s=e.pricingMonthly??(t?e.pricing??"":""),i=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
|
|
56
55
|
leave blank) if you only want to charge a monthly fee. You can
|
|
57
56
|
also add a recurring monthly fee on the next prompt \u2014 combining
|
|
58
57
|
the two is fine (e.g. $499 upfront + $49/month).
|
|
@@ -60,7 +59,7 @@ the two is fine (e.g. $499 upfront + $49/month).
|
|
|
60
59
|
Use the currency that matches your clients' region. Klaudius
|
|
61
60
|
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:s,validate:w=>{if(U(i)&&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
|
|
62
61
|
a recurring monthly fee \u2014 either on its own (if upfront was 0)
|
|
63
|
-
or alongside the upfront fee.`}}),c=U(i),u=U(o),r,
|
|
62
|
+
or alongside the upfront fee.`}}),c=U(i),u=U(o),l,r,d;return c&&!u?(l=o.trim(),r=se,d=o.trim()):!c&&u?(l=i.trim(),r=Ee,d=void 0):(l=i.trim(),r=`upfront, then ${o.trim()}/month`,d=o.trim()),{pricing:l,pricingTerms:r,pricingMonthly:d}}},Ne={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
|
|
64
63
|
run outreach to them automatically (email, SMS, or WhatsApp).
|
|
65
64
|
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})=>({name:await a({type:"text",message:"What name should sign off your outreach messages?",placeholder:"e.g. Mike Smith \u2014 or your business name if you'd rather",initialValue:e.name??e.emailFromName??"",validate:B("Name"),note:{title:"Sign-off name",body:`Klaudius signs off every outreach message and follow-up with this
|
|
66
65
|
name \u2014 e.g. "Cordiali saluti, Marco" in Italian, "Best, Mike" in
|
|
@@ -84,7 +83,7 @@ candidate \u2014 so opting into multiple channels also gives you fallback covera
|
|
|
84
83
|
when one channel doesn't work.
|
|
85
84
|
|
|
86
85
|
You'll be asked to pick your first-choice channel now, then optionally a
|
|
87
|
-
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)"},s=["email","sms","whatsapp"],i=e.outreachPriority??[],o=[],c=await a({type:"select",message:"Which channel should Klaudius try FIRST for each candidate?",initialValue:i[0]??"email",options:s.map(u=>({value:u,label:n[u]}))});for(o.push(c);o.length<s.length;){let u=s.filter(f=>!o.includes(f)),
|
|
86
|
+
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)"},s=["email","sms","whatsapp"],i=e.outreachPriority??[],o=[],c=await a({type:"select",message:"Which channel should Klaudius try FIRST for each candidate?",initialValue:i[0]??"email",options:s.map(u=>({value:u,label:n[u]}))});for(o.push(c);o.length<s.length;){let u=s.filter(f=>!o.includes(f)),l=o.length===1?"second":"third",r=o[o.length-1],d=n[r].replace(/\s*\(.*\)$/,"").toLowerCase(),w=await a({type:"select",message:`Should Klaudius use another channel as ${l} priority (for candidates where ${d} isn't viable or fails)?`,initialValue:i[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}}},Ke={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
|
|
88
87
|
address candidates will see as the sender. Use a domain you control
|
|
89
88
|
(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)"}]}),s=n!=="custom"?ae[n]:void 0,i=await a({type:"text",message:"Email address to send outreach from",placeholder:"you@yourbusiness.com",initialValue:e.emailAddress??"",validate:Te}),o=s?.appPasswordHelp??ne,c=await a({type:"password",message:"Paste the app password",initialValue:e.emailPassword??"",validate:B("App password"),note:{title:"App password",body:`An app password is a separate, single-purpose password that your
|
|
90
89
|
email provider issues for third-party apps like Klaudius. It is NOT
|
|
@@ -94,7 +93,7 @@ your normal account login password.
|
|
|
94
93
|
|
|
95
94
|
Once generated, it's stored locally in this project's .env file.
|
|
96
95
|
It is never sent to Klaudius's servers \u2014 only to your email
|
|
97
|
-
provider when sending outreach.`}}),u,r,
|
|
96
|
+
provider when sending outreach.`}}),u,l,r,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:B("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"});l=parseInt(A,10),r=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:B("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=s.smtpHost,l=s.smtpPort,r=s.imapHost,d=s.imapPort,w=s.sentFolder,f=s.inboxFolder;return{emailProvider:n,emailAddress:i,emailPassword:c,emailFromName:e.name,emailSmtpHost:u,emailSmtpPort:l,emailImapHost:r,emailImapPort:d,emailSentFolder:w,emailInboxFolder:f}}},Le={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:
|
|
98
97
|
|
|
99
98
|
\u2022 macOS iMessage \u2014 free, uses Messages.app on your Mac.
|
|
100
99
|
Reaches other Apple users as iMessage for free. To reach
|
|
@@ -128,7 +127,7 @@ number unless you're comfortable with that.
|
|
|
128
127
|
|
|
129
128
|
You'll be asked how many accounts to link and a short label for each
|
|
130
129
|
(used only locally \u2014 appears in logs, in the .env file, and in this
|
|
131
|
-
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)"}]}),s=parseInt(n,10),i=["primary","secondary","tertiary","quaternary","quinary"],o=[];for(let c=0;c<s;c++){let u=await a({type:"text",message:s===1?"Label for this WhatsApp account (used only locally \u2014 'primary' is fine)":`Label for WhatsApp account ${c+1} of ${s} (e.g. 'primary', 'uk-1', 'us-east')`,initialValue:e.whatsappAccounts?.[c]??i[c],validate:
|
|
130
|
+
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)"}]}),s=parseInt(n,10),i=["primary","secondary","tertiary","quaternary","quinary"],o=[];for(let c=0;c<s;c++){let u=await a({type:"text",message:s===1?"Label for this WhatsApp account (used only locally \u2014 'primary' is fine)":`Label for WhatsApp account ${c+1} of ${s} (e.g. 'primary', 'uk-1', 'us-east')`,initialValue:e.whatsappAccounts?.[c]??i[c],validate:l=>{let r=l.trim();if(!r)return"Required";if(r.length>30)return"Too long (max 30 characters)";if(r.startsWith("-")||r.endsWith("-"))return"Can't start or end with a hyphen";if(!/^[A-Za-z0-9_-]+$/.test(r))return"Letters, digits, underscore, hyphen only (no spaces)";if(o.includes(r))return"Duplicate label"}});o.push(u.trim())}return{whatsappAccounts:o}}},Ge={id:"deploy-provider",title:"Deployment host",isApplicable:()=>!0,execute:async(e,{prompt:a,info:t})=>(t({title:"Where should Klaudius deploy the websites it builds?",body:`Every client site Klaudius builds is a static website, so it deploys
|
|
132
131
|
cleanly to either host below \u2014 pick whichever you'd rather have an
|
|
133
132
|
account with. Both have a free tier that's plenty for getting started.
|
|
134
133
|
|
|
@@ -138,7 +137,7 @@ account with. Both have a free tier that's plenty for getting started.
|
|
|
138
137
|
|
|
139
138
|
This only changes where sites are hosted and which credential you set
|
|
140
139
|
up next. Everything else \u2014 how sites are found, built, and pitched \u2014
|
|
141
|
-
is identical
|
|
140
|
+
is identical.`}),{deployProvider:await a({type:"select",message:"Which host should Klaudius deploy client sites to?",initialValue:e.deployProvider??"vercel",options:[{value:"vercel",label:"Vercel (default)"},{value:"cloudflare",label:"Cloudflare Pages"}]})})},ze={id:"vercel",title:"Vercel deployment",isApplicable:e=>(e.deployProvider??"vercel")==="vercel",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
|
|
142
141
|
Vercel API token to do this without an interactive login.
|
|
143
142
|
|
|
144
143
|
How to get one (one-time, ~30 seconds):
|
|
@@ -232,11 +231,11 @@ in another tab/app and paste this prompt verbatim:
|
|
|
232
231
|
The wizard is asking for: (1) project URL, (2) the secret/service-
|
|
233
232
|
role key, (3) a personal access token. Walk me through where to
|
|
234
233
|
find each one in the current Supabase dashboard UI, including the
|
|
235
|
-
exact menu paths and any caveats for newer vs. legacy projects."`});let s=(await a({type:"text",message:"Paste your Supabase API URL",placeholder:"https://YOUR_REF.supabase.co",initialValue:e.supabaseUrl??"",validate:
|
|
234
|
+
exact menu paths and any caveats for newer vs. legacy projects."`});let s=(await a({type:"text",message:"Paste your Supabase API URL",placeholder:"https://YOUR_REF.supabase.co",initialValue:e.supabaseUrl??"",validate:r=>/^https:\/\/[a-z0-9]+\.supabase\.co(\/rest\/v1\/?)?$/i.test(r.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:
|
|
236
235
|
Settings \u2192 Data API \u2192 'API URL'
|
|
237
236
|
|
|
238
237
|
It looks like https://xxxx.supabase.co. Click to copy and paste
|
|
239
|
-
below.`}})).trim().replace(/\/rest\/v1\/?$/i,"").replace(/\/$/,""),i=s.match(/^https:\/\/([a-z0-9]+)\.supabase\.co/i)?.[1]??"",
|
|
238
|
+
below.`}})).trim().replace(/\/rest\/v1\/?$/i,"").replace(/\/$/,""),i=s.match(/^https:\/\/([a-z0-9]+)\.supabase\.co/i)?.[1]??"",c=(await a({type:"password",message:"Paste the Supabase secret key (sb_secret_\u2026)",initialValue:e.supabaseServiceKey??"",validate:r=>{let d=r.trim();if(d.length<20)return"Looks too short";if(d.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(!d.startsWith("sb_secret_")&&!d.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:
|
|
240
239
|
https://supabase.com/dashboard/project/${i}/settings/api-keys
|
|
241
240
|
|
|
242
241
|
Under 'Secret keys', find the row whose value starts with
|
|
@@ -248,7 +247,7 @@ are client-side keys with no write permissions).
|
|
|
248
247
|
Don't confuse this page with 'Edge Functions \u2192 Secrets' in the
|
|
249
248
|
left sidebar \u2014 that's an unrelated feature (env vars for Edge
|
|
250
249
|
Functions). The page you want is Settings (gear icon, bottom
|
|
251
|
-
of the left sidebar) \u2192 API Keys.`}}),
|
|
250
|
+
of the left sidebar) \u2192 API Keys.`}})).replace(/\s+/g,""),l=(await a({type:"password",message:"Paste the Supabase personal access token",initialValue:e.supabasePat??"",validate:r=>r.trim().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
|
|
252
251
|
ACCOUNT-wide token (not project-scoped) used by the Supabase MCP and
|
|
253
252
|
by Klaudius's schema migration.
|
|
254
253
|
|
|
@@ -258,7 +257,7 @@ Open this exact page:
|
|
|
258
257
|
Click 'Generate new token', name it 'Klaudius', and set the
|
|
259
258
|
expiration to 'Never' (recommended \u2014 saves you having to rotate
|
|
260
259
|
it later). Copy the value (starts with 'sbp_') and paste it
|
|
261
|
-
below.`}});return{supabaseUrl:s,supabaseServiceKey:
|
|
260
|
+
below.`}})).replace(/\s+/g,"");return{supabaseUrl:s,supabaseServiceKey:c,supabasePat:l,supabaseProjectRef:i}}},De={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
|
|
262
261
|
without websites in your target region. Without a key, the pipeline has
|
|
263
262
|
no source of leads \u2014 so this is required.
|
|
264
263
|
|
|
@@ -313,7 +312,7 @@ How to create one:
|
|
|
313
312
|
'KlaudiusNotifierBot'). Each username has to be globally
|
|
314
313
|
unique, so add a personal suffix if it's taken.
|
|
315
314
|
6. BotFather replies with a token like
|
|
316
|
-
'1234567890:AAEhBP_yourtokenhere\u2026'. Copy it and paste below.`}}),s=null,i=0,o=null,c=null;for(;s===null;){i++;let u=i>1,
|
|
315
|
+
'1234567890:AAEhBP_yourtokenhere\u2026'. Copy it and paste below.`}}),s=null,i=0,o=null,c=null;for(;s===null;){i++;let u=i>1,l=c==="network"?`${o}
|
|
317
316
|
|
|
318
317
|
This is usually a network problem on your end (corporate WiFi or VPN
|
|
319
318
|
blocking Telegram, ISP DNS issue, a momentary drop). Check your
|
|
@@ -322,7 +321,7 @@ to retry.`:`${o}
|
|
|
322
321
|
|
|
323
322
|
Make sure you sent a regular text message (e.g. 'hi'), not
|
|
324
323
|
just a /start tap \u2014 /start alone doesn't always register.
|
|
325
|
-
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?
|
|
324
|
+
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?l:`Klaudius will auto-detect your chat ID by asking Telegram for
|
|
326
325
|
any messages your bot has received. To make that work:
|
|
327
326
|
|
|
328
327
|
1. In the Telegram app, search for the bot you just created
|
|
@@ -331,5 +330,5 @@ any messages your bot has received. To make that work:
|
|
|
331
330
|
If the chat starts with a 'Start' button, tap that first,
|
|
332
331
|
THEN send 'hi'. /start alone doesn't always show up.
|
|
333
332
|
3. Press Enter below \u2014 Klaudius will detect the chat ID for
|
|
334
|
-
you.`}});let
|
|
335
|
-
`);return aa(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,s)=>J(Ce,{dimColor:!1,children:n.length===0?" ":n},s))})]})}import{jsx as p,jsxs as V}from"react/jsx-runtime";function ja({defaults:e,onComplete:a,onlySection:t,banner:n}){let{exit:s}=oa(),i=Q({...e}),o=Q(new Map),[,c]=M(0),u=()=>c(h=>h+1),[r
|
|
333
|
+
you.`}});let r=await ee({botToken:n});if(r.ok&&r.chatId)s=r.chatId;else if(r.reason==="no_messages")o="No messages from you to your bot have been picked up yet.",c="no_messages";else if(r.reason==="network")o=r.message??"Could not reach Telegram.",c="network";else throw new Error(`Telegram chat ID auto-detect failed: ${r.message??"unknown error"}`)}return{telegramBotToken:n,telegramChatId:s}}},x=[xe,Me,Oe,Ne,Be,Re,Ke,Le,Fe,Ge,ze,Ve,Ue,De,He];import{Box as re,Text as We}from"ink";import{jsx as le,jsxs as je}from"react/jsx-runtime";var _e={pending:"\u25CB",current:"\u25C9",done:"\u2713",skipped:"\xB7"},$e={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:je(We,{color:$e[a.status],bold:a.status==="current",dimColor:t&&a.status!=="current",children:[_e[a.status]," ",a.title]})},a.id)})})}import{useEffect as qe,useState as ce}from"react";import{Box as j,Text as H,useInput as Ye}from"ink";import Ze 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[s,i]=ce(typeof e.initialValue=="string"?e.initialValue:""),[o,c]=ce(null);qe(()=>(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]),Ye((l,r)=>{y("TextPromptUI:useInput fired",{input:l,ctrl:r.ctrl,escape:r.escape,return:r.return}),r.escape&&n()});let u=l=>{y("TextPromptUI:handleSubmit",{raw:l.slice(0,30)});let r=l;if(e.validate){let d=e.validate(r);if(d){y("TextPromptUI:validate failed",{err:d}),c(d);return}}c(null),t(r)};return q(j,{flexDirection:"column",children:[q(H,{children:[F(H,{color:"cyan",children:"?"})," ",e.message]}),q(j,{children:[F(H,{color:"green",children:"\u203A "}),F(Ze,{value:s,onChange:i,onSubmit:u,placeholder:e.placeholder,mask:a?"\u2022":void 0})]}),o&&F(j,{marginTop:0,children:F(H,{color:"red",children:o})})]})}import{useState as Je}from"react";import{Box as ge,Text as Y,useInput as Xe}from"ink";import{jsx as pe,jsxs as Z}from"react/jsx-runtime";function he({spec:e,onSubmit:a,onBack:t}){let n=e.options??[],s=typeof e.initialValue=="string"?Math.max(0,n.findIndex(c=>c.value===e.initialValue)):0,[i,o]=Je(s===-1?0:s);return Xe((c,u)=>{if(u.escape)t();else if(u.upArrow)o(l=>(l-1+n.length)%n.length);else if(u.downArrow)o(l=>(l+1)%n.length);else if(u.return){let l=n[i];l&&a(l.value)}}),Z(ge,{flexDirection:"column",children:[Z(Y,{children:[pe(Y,{color:"cyan",children:"?"})," ",e.message]}),pe(ge,{flexDirection:"column",marginTop:0,children:n.map((c,u)=>{let l=u===i;return Z(Y,{color:l?"cyan":void 0,bold:l,children:[l?"\u25CF ":"\u25CB ",c.label]},c.value)})})]})}import{useState as Qe}from"react";import{Box as me,Text as G,useInput as ea}from"ink";import{jsx as ye,jsxs as z}from"react/jsx-runtime";function fe({spec:e,onSubmit:a,onBack:t}){let[n,s]=Qe(typeof e.initialValue=="boolean"?e.initialValue:!0);return ea((i,o)=>{o.escape?t():o.leftArrow||o.rightArrow?s(c=>!c):i==="y"||i==="Y"?s(!0):i==="n"||i==="N"?s(!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 aa}from"react/jsx-runtime";function X({title:e,body:a}){let t=a.split(`
|
|
334
|
+
`);return aa(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,s)=>J(Ce,{dimColor:!1,children:n.length===0?" ":n},s))})]})}import{jsx as p,jsxs as V}from"react/jsx-runtime";function ja({defaults:e,onComplete:a,onlySection:t,banner:n}){let{exit:s}=oa(),i=Q({...e}),o=Q(new Map),[,c]=M(0),u=()=>c(h=>h+1),[l,r]=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(i.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);na(()=>{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 P=++h;return y("orchestrator:promptFn called",{id:P,type:g.type,message:g.message.slice(0,60)}),b(null),new Promise((S,m)=>{w({id:P,spec:g,resolve:T=>{y("orchestrator:prompt resolved",{id:P,type:g.type,value:typeof T=="string"?T.slice(0,30):T}),S(T)},reject:T=>{y("orchestrator:prompt rejected",{id:P,reason:T.message}),m(T)}})})},$=g=>{A(P=>[...P,g])};return(async()=>{try{let g=t?x.filter(m=>m.id===t):x,P=()=>g.filter(m=>m.isApplicable(i.current)).length,S=0;for(;S<g.length;){let m=g[S];if(!m.isApplicable(i.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");r(m.id);let T=g.slice(0,S+1).filter(k=>k.isApplicable(i.current)).length;Se({current:T,total:P()}),u();try{let k=await m.execute(i.current,{prompt:C,info:$});i.current={...i.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)i.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(i.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),r(null),u(),await new Promise(m=>setTimeout(m,200)),a(i.current),s()}catch(g){y("orchestrator:caught error",{name:g?.name,message:g?.message}),g instanceof D&&(s(),process.exit(0));let P=g instanceof Error?g.message:String(g);b(`Setup error: ${P}`),u()}})(),()=>{y("WizardApp:useEffect cleanup ran (component unmounting)")}},[s,a]),ia((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"),s(),process.exit(0))});let ke=ta(()=>x.map(h=>({id:h.id,title:h.title,status:o.current.get(h.id)??"pending"})),[l,O,I]);return V(v,{flexDirection:"column",paddingY:1,children:[V(v,{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(v,{children:[p(ue,{items:ke}),V(v,{flexDirection:"column",flexGrow:1,marginLeft:2,children:[n&&V(v,{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})]}),!t&&l!==null&&l!=="ai-agent"&&p(v,{marginBottom:1,children:p(E,{color:"green",children:"Nothing here is permanent, you can customize any of this later."})}),f.map((h,C)=>p(v,{marginBottom:1,children:p(X,{title:h.title,body:h.body})},C)),d?.spec.note&&p(v,{marginBottom:1,children:p(X,{title:d.spec.note.title,body:d.spec.note.body})}),d&&ra(d),I&&p(v,{marginTop:1,children:p(E,{color:"red",children:I})}),O&&p(v,{marginTop:1,children:p(E,{color:"green",bold:!0,children:"\u2713 Setup complete. Continuing\u2026"})})]})]}),p(v,{marginTop:1,children:p(E,{dimColor:!0,children:sa(t,l)})})]})}function sa(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 ra(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{ja as WizardApp};
|
package/dist/bin.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as Q,b as Me,c as Ue,d as _,f as je,g as Ke}from"./chunk-SZ4KCTSL.js";import{a as le,b as He,c as Fe,d as ce,e as Ve,i as Ge}from"./chunk-ZTT5HVYU.js";import{Command as co}from"commander";import{spawn as jt}from"child_process";import T from"picocolors";function G(){let e=process.version,
|
|
3
|
-
`));let
|
|
4
|
-
`)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${
|
|
5
|
-
Please share that file so we can trace what happened.`);return
|
|
2
|
+
import{a as Q,b as Me,c as Ue,d as _,f as je,g as Ke}from"./chunk-SZ4KCTSL.js";import{a as le,b as He,c as Fe,d as ce,e as Ve,i as Ge}from"./chunk-ZTT5HVYU.js";import{Command as co}from"commander";import{spawn as jt}from"child_process";import T from"picocolors";function G(){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 s=parseInt(n[1],10),t=parseInt(n[2],10),i=parseInt(n[3],10),a=`${s}.${t}.${i}`;return s<22||s===22&&t<15?{ok:!1,version:a,major:s,minor:t,message:`Your installed Node.js is ${a}. 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:a,major:s,minor:t}}import{spawn as Lt}from"child_process";var se=3,de=10,Dt=[["python3"],["python"],["py","-3"]];async function Ae(){for(let e of Dt){let n=await Ut(e[0],[...e.slice(1),"--version"]),s=(n.stdout+n.stderr).trim();if(/Python was not found/i.test(s)||n.code!==0)continue;let t=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(s);if(!t)continue;let i=parseInt(t[1],10),a=parseInt(t[2],10),r=t[3]?`${i}.${a}.${t[3]}`:`${i}.${a}`;return{command:[...e],version:r,major:i,minor:a}}return null}async function Z(){let e=Mt(),n=await Ae();if(!n){let r=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${se}.${de}+ is not installed (or not on PATH). Install it from ${e}.`+r}}let{command:s,version:t,major:i,minor:a}=n;return i<se||i===se&&a<de?{ok:!1,version:t,major:i,minor:a,command:s,message:`Your installed Python is ${t}. Klaudius needs Python ${se}.${de} or newer (the pipeline depends on packages that only ship wheels for ${se}.${de}+). Install a newer Python from ${e} \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:t,major:i,minor:a,command:s}}function Mt(){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/"}}function Ut(e,n){return new Promise(s=>{let t=Lt(e,n,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";t.stdout?.on("data",r=>{i+=r.toString()}),t.stderr?.on("data",r=>{a+=r.toString()}),t.on("close",r=>s({code:r??1,stdout:i,stderr:a})),t.on("error",()=>s({code:1,stdout:i,stderr:a}))})}var Be=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function We(e={}){console.log(T.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
|
+
`));let n=[];n.push(Kt());let s=await Z();n.push(Ht(s)),n.push(await Ft(s.command)),n.push(await Vt()),n.push(await Gt());for(let i of n){let a=i.status==="ok"?T.green("\u2713"):T.red("\u2717");console.log(` ${a} ${i.name}${i.detail?T.dim(` \u2014 ${i.detail}`):""}`),i.nextAction&&console.log(` ${T.dim("\u2192")} ${T.cyan(i.nextAction)}`)}console.log();let t=n.filter(i=>i.status==="fail");if(t.length===0){Bt();return}console.log(T.red(T.bold(`${t.length} check${t.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius preflight\`.`))),console.log(),console.log(T.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(T.dim(" user, then re-run `npx klaudius preflight` until every check passes.")),console.log(),process.exitCode=1}function Kt(){let e=G();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal before re-running."}}function Ht(e){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:e.message??"Install Python 3.10+ from https://www.python.org/downloads/"}}async function Ft(e){let n=e??["python3"],s=await Pe(n[0],[...n.slice(1),"-m","pip","--version"]);return s.code===0?{name:"pip available",status:"ok",detail:(s.stdout||s.stderr).trim().split(`
|
|
4
|
+
`)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${n.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${n.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function Vt(){let e=await Pe("npm",["--version"]);return e.code!==0?{name:"npm / npx available",status:"fail",detail:"npm not found",nextAction:"npm ships with Node.js \u2014 reinstall Node from https://nodejs.org/."}:(await Pe("npx",["--version"])).code!==0?{name:"npm / npx available",status:"fail",detail:`npm ${e.stdout.trim()} ok, npx missing`,nextAction:"npx ships with npm 5.2+ \u2014 reinstall Node from https://nodejs.org/."}:{name:"npm / npx available",status:"ok",detail:`npm ${e.stdout.trim()}`}}async function Gt(){try{return await fetch(Be,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:Be}}catch(e){return{name:"klaudius.dev reachable",status:"fail",detail:e.name==="TimeoutError"?"timed out":"could not connect",nextAction:"Check your internet connection, VPN, or firewall \u2014 init needs klaudius.dev to validate your license and download the template."}}}function Bt(){console.log(T.green(T.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(T.bold("NEXT STEP \u2014 this one is for you to run, not the AI assistant:")),console.log(" It's an interactive wizard (it asks for your license key and passwords),"),console.log(" so the assistant can't fill it in. Open a NEW terminal tab and run:"),console.log(),console.log(` ${T.cyan("npx klaudius init my-agency")}`),console.log(),console.log(T.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(T.dim(" run it in a new terminal.")),console.log()}function Pe(e,n){return new Promise(s=>{let t=jt(e,n,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";t.stdout?.on("data",r=>{i+=r.toString()}),t.stderr?.on("data",r=>{a+=r.toString()}),t.on("close",r=>s({code:r??1,stdout:i,stderr:a})),t.on("error",()=>s({code:1,stdout:i,stderr:a}))})}import{mkdir as Se,readdir as Tn,readFile as ht,stat as gt,writeFile as Ie}from"fs/promises";import{spawnSync as kt}from"child_process";import{resolve as _n,isAbsolute as Cn,join as q,normalize as In}from"path";import*as y from"@clack/prompts";import d from"picocolors";import Wt from"react";import{render as Yt}from"ink";async function I(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:s}=await import("./WizardApp-XPK4JB6T.js"),t=null;Q("runWizard:start",{onlySection:n.onlySection,hasDefaults:Object.keys(e).length>0}),Ue(),await new Promise(a=>setImmediate(a)),await new Promise(a=>setTimeout(a,0)),Q("runWizard:event loop drained, mounting Ink");let i=Yt(Wt.createElement(s,{defaults:e,onlySection:n.onlySection,banner:n.banner,onComplete:a=>{Q("runWizard:onComplete called",{keys:Object.keys(a).length}),t=a}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(Q("runWizard:render returned, awaiting exit"),await i.waitUntilExit(),Q("runWizard:waitUntilExit resolved",{resultIsNull:t===null}),!t)throw new Error(`Wizard exited without completing. Diagnostic log: ${Me}
|
|
5
|
+
Please share that file so we can trace what happened.`);return t}var be="claude-code";function Ye(e){if(e==="claude-code"||e==="codex")return e}var Te="vercel";function ze(e){if(e==="vercel"||e==="cloudflare")return e}function ue(e){let n=[],s=i=>{n.push(""),n.push("# "+"=".repeat(60)),n.push(`# ${i}`),n.push("# "+"=".repeat(60)),n.push("")},t=(i,a)=>{if(a==null||a===""){n.push(`# ${i}=`);return}let r=String(a);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(r)){let c=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");n.push(`${i}="${c}"`)}else n.push(`${i}=${r}`)};return n.push("# Klaudius configuration"),n.push("# Generated by `npx klaudius init`. Edit freely."),n.push("# NEVER commit this file. .gitignore already excludes it."),s("Klaudius licence"),t("KLAUDIUS_LICENSE_KEY",e.licenseKey),s("AI coding agent"),t("AI_AGENT",e.aiAgent??be),s("Operating country and language"),t("OPERATOR_COUNTRY",e.country),t("OPERATOR_COUNTRY_CODE",e.countryCode),t("OPERATOR_LANGUAGE",e.language),t("OPERATOR_LANGUAGE_CODE",e.languageCode),s("Pricing"),t("PRICING",e.pricing),t("PRICING_TERMS",e.pricingTerms),t("PRICING_MONTHLY",e.pricingMonthly),s("Automated outreach features"),t("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),t("OPERATOR_NAME",e.name),t("SIGNATURE",e.signature),t("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),t("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),s("Email outreach"),t("EMAIL_ADDRESS",e.emailAddress),t("EMAIL_PASSWORD",e.emailPassword),t("EMAIL_FROM_NAME",e.emailFromName),t("EMAIL_SMTP_HOST",e.emailSmtpHost),t("EMAIL_SMTP_PORT",e.emailSmtpPort),t("EMAIL_IMAP_HOST",e.emailImapHost),t("EMAIL_IMAP_PORT",e.emailImapPort),t("EMAIL_SENT_FOLDER",e.emailSentFolder),t("EMAIL_INBOX_FOLDER",e.emailInboxFolder),s("SMS outreach"),t("SMS_PROVIDER",e.smsProvider),t("TEST_PHONE",e.testPhone),t("TWILIO_ACCOUNT_SID",e.twilioAccountSid),t("TWILIO_AUTH_TOKEN",e.twilioAuthToken),t("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),s("WhatsApp outreach"),t("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),s("Supabase (pipeline state)"),t("SUPABASE_URL",e.supabaseUrl),t("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),t("SUPABASE_PAT",e.supabasePat),t("SUPABASE_PROJECT_REF",e.supabaseProjectRef),s("Deployment"),t("DEPLOY_PROVIDER",e.deployProvider??Te),t("VERCEL_TOKEN",e.vercelToken),t("VERCEL_SCOPE",e.vercelScope??""),t("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),t("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("Search APIs"),t("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),t("SERPAPI_KEY",e.serpapiKey),s("Telegram notifications (optional)"),t("TELEGRAM_BOT_TOKEN",e.telegramBotToken),t("TELEGRAM_CHAT_ID",e.telegramChatId),s("Rate limiting (sensible defaults)"),t("REQUESTS_PER_MINUTE",10),t("REQUEST_DELAY",2),n.join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`}function pe(e){let
|
|
8
|
-
`}function me(e){let
|
|
9
|
-
`)}function zt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var qe=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel' or 'cloudflare'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch to Cloudflare Pages, run `klaudius configure` (adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID)."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'}];function qt(e,
|
|
7
|
+
`}function pe(e){let n={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(n,null,2)+`
|
|
8
|
+
`}function me(e){let n=e.supabaseProjectRef,s=zt(e.supabasePat);return["# Codex MCP config \u2014 generated by `npx klaudius init` / `configure`.","# Edit freely. NEVER commit this file \u2014 .gitignore already excludes it.","# See `.codex/config.toml.example` for the documented format.","","[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${n}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${s}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
|
|
9
|
+
`)}function zt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var qe=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel' or 'cloudflare'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch to Cloudflare Pages, run `npx klaudius configure` (adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID)."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'}];function qt(e,n){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(n)){let s=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${s}"`}return`${e}=${n}`}function Xe(e,n,s){let t=s.filter(r=>!(r.key in n));if(t.length===0)return null;let i=e.endsWith(`
|
|
10
10
|
`)?"":`
|
|
11
|
-
`,
|
|
11
|
+
`,a=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let r of t)a.push(""),r.comment&&a.push(`# ${r.comment}`),a.push(qt(r.key,r.value));return e+i+a.join(`
|
|
12
12
|
`)+`
|
|
13
|
-
`}function Xt(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function $(e){let
|
|
14
|
-
`)){let
|
|
15
|
-
`+B.bold(B.cyan(e))),detail:e=>console.log(B.dim(" "+e))};var sn="https://klaudius.dev",an="/api/licenses/validate",rn="0.15.
|
|
13
|
+
`}function Xt(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function $(e){let n={};for(let s of e.split(`
|
|
14
|
+
`)){let t=s.trim();if(!t||t.startsWith("#"))continue;let i=t.indexOf("=");if(i===-1)continue;let a=t.slice(0,i).trim(),r=Xt(t.slice(i+1).trim());n[a]=r}return n}function Je(e){let n=c=>{let p=e[c];if(!p)return;let g=parseInt(p,10);return isNaN(g)?void 0:g},s=e.SMS_PROVIDER,t=c=>c==="email"||c==="sms"||c==="whatsapp",i=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(t),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(t),r=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Ye(e.AI_AGENT)??be,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:i&&i.length>0?i:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:n("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:n("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:s==="imessage"||s==="twilio"?s:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:ze(e.DEPLOY_PROVIDER)??Te,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN||void 0,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,emailPassword:e.EMAIL_PASSWORD,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function _e(e){let n=w=>{let V=e[w];if(!V)return;let x=parseInt(V,10);return isNaN(x)?void 0:x},s=e.SUPABASE_URL,t=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),i=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,r=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",p=ze(e.DEPLOY_PROVIDER)??Te,g=e.VERCEL_TOKEN,l=e.CLOUDFLARE_API_TOKEN,A=e.CLOUDFLARE_ACCOUNT_ID;if(!r||!s||!t||!i||!a||!(p==="cloudflare"?!!l&&!!A:!!g))return null;let P=e.SMS_PROVIDER,L=w=>w==="email"||w==="sms"||w==="whatsapp",U=e.OUTREACH_CHANNELS?.split(",").map(w=>w.trim()).filter(L),N=e.OUTREACH_PRIORITY?.split(",").map(w=>w.trim()).filter(L),b=e.WHATSAPP_ACCOUNTS?.split(",").map(w=>w.trim()).filter(w=>w.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Ye(e.AI_AGENT)??be,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:r,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:U&&U.length>0?U:void 0,outreachPriority:N&&N.length>0?N:void 0,whatsappAccounts:b&&b.length>0?b:void 0,emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:n("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:n("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:P==="imessage"||P==="twilio"?P:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:p,vercelToken:g,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:l||void 0,cloudflareAccountId:A||void 0,supabaseUrl:s,supabaseServiceKey:t,supabasePat:i,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{mkdir as Jt,rm as Qt}from"fs/promises";import{Readable as Zt}from"stream";import*as Qe from"tar";var en="https://klaudius.dev/api/template";function tn(e){return Zt.fromWeb(e)}async function fe(e){let n=process.env.KLAUDIUS_TEMPLATE_URL??en,s="0.15.2",t;try{t=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:s,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(r){throw new Error(`Could not reach klaudius.dev to download the template: ${_(r)}`)}if(!t.ok){let r="";try{let c=await t.json();r=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${t.status}${r}`)}if(!t.body)throw new Error("Template download succeeded but response had no body");let i=t.headers.get("x-klaudius-tier");await Jt(e.destDir,{recursive:!0});let a=0;try{await new Promise((r,c)=>{let p=Qe.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{a++}});p.on("finish",r),p.on("error",c),tn(t.body).on("error",c).pipe(p)})}catch(r){throw await Qt(e.destDir,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Failed to extract template archive: ${r.message}`)}return{filesExtracted:a,tier:i}}import{createHash as nn}from"crypto";import{hostname as Ze,userInfo as on,platform as et,arch as tt}from"os";import B from"picocolors";var o={info:e=>console.log(B.cyan("\u2139"),e),success:e=>console.log(B.green("\u2713"),e),warn:e=>console.log(B.yellow("\u26A0"),e),error:e=>console.error(B.red("\u2717"),e),step:e=>console.log(B.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+B.bold(B.cyan(e))),detail:e=>console.log(B.dim(" "+e))};var sn="https://klaudius.dev",an="/api/licenses/validate",rn="0.15.2";async function nt(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let n=e.trim(),t=(process.env.KLAUDIUS_API_URL??sn).replace(/\/$/,"")+an,i=ie(),a;try{a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:n,machine_id:i,hostname:Ze(),os:`${et()}-${tt()}`,cli_version:rn})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${_(c)}). Check your internet connection or try again later.`}}let r;try{r=await a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${a.status}).`}}function ie(){let e=[Ze(),on().username,et(),tt()].join("|");return nn("sha256").update(e).digest("hex").slice(0,32)}import{readFile as ln}from"fs/promises";import{join as cn}from"path";async function ee(e){let n=e.serviceKey.replace(/\s+/g,"");try{let s=await fetch(e.url+"/rest/v1/",{headers:{apikey:n,Authorization:`Bearer ${n}`}});return s.status===401||s.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${s.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(s){return{ok:!1,message:`Could not reach Supabase: ${_(s)}`}}}async function ot(e){let n;try{n=await ln(cn(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(t){return{ok:!1,message:`Could not read scripts/schema.sql: ${t.message}`}}let s=e.pat.replace(/\s+/g,"");try{let t=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({query:n})});if(t.ok)return{ok:!0};let i=await t.text();return i.includes("already exists")||i.includes('relation "clients" already exists')||i.includes("duplicate")?(o.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${t.status}): ${i.slice(0,300)}`}}catch(t){return{ok:!1,message:`Schema apply failed: ${t.message}`}}}async function he(e){try{let n=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(n.status===401||n.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${n.status}). The token is invalid, expired, or has been revoked.`};if(!n.ok)return{ok:!1,message:`Vercel API returned HTTP ${n.status}. Try again or check status.vercel.com.`};let s=await n.json();return{ok:!0,username:s.user?.username??s.user?.email}}catch(n){return{ok:!1,message:`Could not reach Vercel: ${_(n)}`}}}var st="https://api.cloudflare.com/client/v4";function it(e){let n=e?.errors?.[0];if(n)return n.message?`${n.message}${n.code?` (code ${n.code})`:""}`:void 0}async function ge(e){let{token:n,accountId:s}=e,t={Authorization:`Bearer ${n}`,"Content-Type":"application/json"};try{let i=await fetch(`${st}/user/tokens/verify`,{headers:t});if(i.status===401||i.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await i.json(),r=a.result?.status;if(a.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${it(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}try{let i=await fetch(`${st}/accounts/${encodeURIComponent(s)}/pages/projects`,{headers:t});if(i.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${s} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(i.status===404)return{ok:!1,message:`Account ${s} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await i.json();return a.success===!1?{ok:!1,message:it(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${_(i)}`}}}async function ke(e){try{let n=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":e,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(n.ok)return{ok:!0};if(n.status===429)return{ok:!0};let s={};try{s=await n.json()}catch{}let t=s.error?.message??"",i=s.error?.status??"";return n.status===400&&(i==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(t))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:n.status===401||n.status===403?{ok:!1,message:t||`Google rejected the key (HTTP ${n.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`}:{ok:!1,message:`Google API returned HTTP ${n.status}${t?`: ${t}`:""}.`}}catch(n){return{ok:!1,message:`Could not reach Google: ${_(n)}`}}}import dn from"nodemailer";import{ImapFlow as un}from"imapflow";async function rt(e){let n=dn.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await n.verify()}catch(t){return{ok:!1,failedAt:"smtp",message:at(t,"SMTP")}}finally{n.close()}let s=new un({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1});try{await s.connect(),await s.logout()}catch(t){try{await s.logout()}catch{}return{ok:!1,failedAt:"imap",message:at(t,"IMAP")}}return{ok:!0}}function at(e,n){let s=e instanceof Error?e.message:String(e),t=s.toLowerCase();return t.includes("invalid credentials")||t.includes("authentication failed")||t.includes("auth failed")||t.includes("login failed")?`${n} rejected the credentials. Most common causes:
|
|
16
16
|
\u2022 The app password is wrong, expired, or for a different provider.
|
|
17
17
|
\u2022 The email address doesn't match the account that issued the password.
|
|
18
|
-
\u2022 2FA is required but no app-specific password was generated.`:
|
|
19
|
-
`+
|
|
20
|
-
${e.stdout??""}`;return yn.find(
|
|
21
|
-
`,"utf-8")}var Sn="0.15.
|
|
18
|
+
\u2022 2FA is required but no app-specific password was generated.`:t.includes("etimedout")||t.includes("timeout")?`${n} server didn't respond in time. Check the host/port, or your network.`:t.includes("enotfound")||t.includes("getaddrinfo")?`${n} host could not be resolved. Check the host setting.`:`${n} check failed: ${s}`}async function lt(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let n=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,s=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let t=await fetch(n,{headers:{Authorization:`Basic ${s}`}});if(t.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!t.ok)return{ok:!1,message:`Twilio API returned HTTP ${t.status}. Try again or check status.twilio.com.`};let i=await t.json();return i.status&&i.status!=="active"?{ok:!1,message:`Twilio account is in '${i.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:i.friendly_name}}catch(t){return{ok:!1,message:`Could not reach Twilio: ${_(t)}`}}}import{spawn as pn}from"child_process";async function ct(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let s=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,t=await mn(s);if(t.code===0)return{ok:!0};let i=t.stderr.toLowerCase();return i.includes("can't get application")||i.includes("isn't running")||i.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:i.includes("(-1728)")||i.includes("not found")||i.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:i.includes("(-1719)")||i.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${t.stderr.trim()||`exit code ${t.code}`}`}}function mn(e){return new Promise(n=>{let s=pn("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),t="";s.stderr.on("data",i=>{t+=i.toString()}),s.on("close",i=>n({code:i??1,stderr:t})),s.on("error",i=>n({code:1,stderr:i.message}))})}import{spawn as dt}from"child_process";function fn(){let e=process.env.NODE_OPTIONS?.trim(),n=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:n}}var te=2,ut=2e3,hn=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function pt(e,n){let s=e+`
|
|
19
|
+
`+n;return hn.some(t=>t.test(s))}function mt(e){return new Promise(n=>setTimeout(n,e))}function gn(e,n,s){return new Promise(t=>{let i=dt(e,n,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:s.env??process.env}),a="",r="";i.stdout?.on("data",c=>{let p=c.toString();a+=p,process.stdout.write(p)}),i.stderr?.on("data",c=>{let p=c.toString();r+=p,process.stderr.write(p)}),i.on("close",c=>t({code:c??1,stdout:a,stderr:r})),i.on("error",c=>t({code:1,stdout:a,stderr:r+c.message}))})}async function Ce(e,n,s){let t={code:0,stdout:"",stderr:""};for(let i=0;i<=te;i++){if(t=await gn(e,n,{cwd:s.cwd,env:s.env}),t.code===0||!pt(t.stderr,t.stdout))return t;i<te&&(o.detail(`${s.label} failed with a transient network error \u2014 retrying (${i+2}/${te+1})\u2026`),await mt(ut))}return t}function kn(e,n,s){return new Promise(t=>{let i=dt(e,n,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",r="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{r+=c.toString()}),i.on("close",c=>t({code:c??1,stdout:a,stderr:r})),i.on("error",c=>t({code:1,stdout:a,stderr:r+c.message}))})}var yn=[{pattern:/UNABLE_TO_VERIFY_LEAF_SIGNATURE|unable to verify the first certificate/i,hint:"TLS-handshake error \u2014 your machine appears to be intercepting HTTPS (antivirus, corporate proxy, or VPN re-signing traffic with its own root CA). We work around this with NODE_OPTIONS=--use-system-ca, which needs Node 22.15+. Run `node --version` to verify, upgrade if older, then re-run setup."},{pattern:/Microsoft Visual C\+\+ 14\.0 or greater is required/i,hint:"Python tried to compile a package from source and couldn't find the Microsoft C++ Build Tools. The latest Klaudius pins supabase<2.26 to skip the offending dependency entirely. Update with `npm install -g klaudius@latest` and re-run init \u2014 that should bypass the source build."}];function wn(e){let n=`${e.stderr??""}
|
|
20
|
+
${e.stdout??""}`;return yn.find(t=>t.pattern.test(n))?.hint}async function En(e){let n=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],s=["-m","pip","install","--quiet","--user"],i=(await Ae())?.command??["python3"],a=async c=>{let p={code:0,stdout:"",stderr:""};for(let g=0;g<=te;g++){if(p=await kn(i[0],[...i.slice(1),...c],{cwd:e}),p.code===0||!pt(p.stderr,p.stdout))return p;g<te&&(o.detail(`pip install hit a transient network error \u2014 retrying (${g+2}/${te+1})\u2026`),await mt(ut))}return p},r=await a([...s,"--break-system-packages",...n]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(o.detail("Older pip detected; retrying without --break-system-packages"),r=await a([...s,...n])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function ye(e){let n={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},s=fn(),t=(p,g)=>{let l=wn(g);l&&((n.hints??={})[p]=l)};o.step("Running npm install (Next.js, Playwright JS, etc.)...");let i=await Ce("npm",["install"],{cwd:e,label:"npm install",env:s});n.npm=i.code===0?"ok":"failed",i.code!==0&&t("npm",i),o.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let a=await En(e);n.pip=a.code===0?"ok":"failed",a.code!==0&&t("pip",a),o.step("Installing Playwright browser (chromium ~200MB; one-time)...");let r=await Ce("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:s});n.playwright=r.code===0?"ok":"failed",r.code!==0&&t("playwright",r),o.step("Installing Patchright browser (chromium ~200MB; one-time)...");let c=await Ce("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:s});return n.patchright=c.code===0?"ok":"failed",c.code!==0&&t("patchright",c),n}import{mkdir as An,readFile as Pn,writeFile as bn}from"fs/promises";import{join as ft}from"path";async function we(e,n){let s=ft(e,".claude");await An(s,{recursive:!0});let t=ft(s,"settings.json"),i={};try{let p=await Pn(t,"utf-8"),g=JSON.parse(p);g&&typeof g=="object"&&!Array.isArray(g)&&(i=g)}catch{}let a=i.enabledMcpjsonServers,r=Array.isArray(a)?a.filter(p=>typeof p=="string"):[];r.includes(n)||r.push(n);let c={...i,enabledMcpjsonServers:r};await bn(t,JSON.stringify(c,null,2)+`
|
|
21
|
+
`,"utf-8")}var Sn="0.15.2",C=5;function z(e,n){o.blank(),o.error(`${e} validation failed ${C} times in a row. Pausing setup so you don't get stuck in a loop.`),o.detail(`Last error: ${n}`),o.blank(),o.detail("Your credentials are saved in `.env`. Two ways forward:"),o.detail(" \u2022 Open `.env` in any text editor, fix the value, re-run `npx klaudius init` and pick Resume."),o.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),o.blank(),process.exit(1)}async function yt(e){let n=e.target??".",s=Cn(n)?n:_n(process.cwd(),n),t=On(s);t&&(o.error("Klaudius can't be installed inside a protected system folder."),o.detail(`Path: ${s}`),o.detail(`Reason: ${t}`),o.blank(),o.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),o.blank(),process.platform==="win32"?(o.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${d.cyan("cd $HOME\\Documents")}`),console.log(` ${d.cyan("npx klaudius init my-agency")}`)):(o.detail("For example:"),console.log(` ${d.cyan("cd ~/Documents")}`),console.log(` ${d.cyan("npx klaudius init my-agency")}`)),o.blank(),process.exit(1)),process.platform==="win32"&&$n()&&(o.warn("You appear to be running in an elevated (Administrator) PowerShell."),o.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius init."),o.blank());let i=await Rn(s);if(i.kind==="scaffolded"){o.blank(),o.warn(`Found an existing Klaudius project at ${d.bold(s)}.`),o.detail("(Your .env and project files are in place.)"),o.blank(),i.nodeModulesMissing?(o.detail("It looks like a previous setup didn't finish installing dependencies."),o.detail("To pick up where it left off, run:"),o.blank(),s!==process.cwd()&&console.log(` ${d.cyan(`cd ${n}`)}`),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Everything is scaffolded and dependencies look installed."),o.detail("Pick the action you wanted:"),o.blank(),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius update")} ${d.dim("# pull the latest skills, scripts, lessons")}`),o.blank()),o.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius init`."),o.blank();return}if(i.kind==="occupied"){let u=n===".";o.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),o.detail(`Path: ${s}`),o.detail(`Contains: ${i.entries.slice(0,5).join(", ")}${i.entries.length>5?`, \u2026 (+${i.entries.length-5} more)`:""}`),o.blank(),u?(o.detail("Two ways forward:"),o.blank(),o.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${d.cyan("npx klaudius init my-agency")}`),o.blank(),o.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${d.cyan("mkdir my-agency && cd my-agency && npx klaudius init")}`)):(o.detail(`The folder '${n}' already exists and isn't empty.`),o.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius init ${n}-2`)}`),o.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await vn(e.license),r=y.spinner();r.start("Validating license");let c=await nt(a);c.ok||(r.stop(`License invalid: ${c.reason??"unknown"}`,2),o.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),r.stop(`License valid (${c.tier??"core"} tier)`);let p=await Z();p.ok||(o.error(p.message??"Python version check failed."),o.blank(),o.detail("Once you've installed Python 3.10+, re-run `npx klaudius init` in this folder."),process.exit(1));let g=G();g.ok||(o.error(g.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius init` in this folder."),process.exit(1));let l,A=!1;if(i.kind==="partial")if(await xn(s)==="resume"){let f=await ht(i.envPath,"utf-8"),m=_e($(f));m?(o.success("Resuming with values from your existing .env"),o.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=m,A=!0):(o.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await I())}else{let f=await ht(i.envPath,"utf-8"),m=_e($(f));l=await I(m??{})}else l=await I();l.licenseKey=a,await D(s,l),A||(o.success("Saved .env"),o.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),o.blank();for(let u=1;;u++){let f=y.spinner();f.start("Validating Supabase credentials");let m=await ee({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(m.ok){f.stop("Supabase credentials accepted");break}f.stop(m.message??"Supabase check failed",2),u>=C&&z("Supabase",m.message??"Supabase check failed");let E=m.message??"Supabase check failed";o.blank(),o.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${u+1} of ${C})`),o.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),o.blank(),l=await I(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
22
22
|
${E}
|
|
23
23
|
|
|
24
24
|
Re-enter the URL, secret key, or PAT below. Press Enter on any
|
|
@@ -48,27 +48,27 @@ ${E}
|
|
|
48
48
|
|
|
49
49
|
Either fix the underlying issue (sign in to Messages.app, configure
|
|
50
50
|
Text Message Forwarding) and press Enter through, or change SMS
|
|
51
|
-
provider to Twilio.`}),await D(s,l)}}if(l.telegramBotToken&&l.telegramChatId){o.blank();let u=0,f=!1;for(;!f;){u++;let m=y.spinner();m.start("Validating Telegram bot + chat (sending a test ping)");let E=await Ke({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(E.ok){m.stop(E.botHandle?`Telegram bot ${E.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),f=!0;break}m.stop(E.message??"Telegram check failed",2);let De=E.message??"Telegram check failed";o.blank(),o.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),o.blank();let Y=await y.select({message:"What would you like to do?",initialValue:u>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(y.isCancel(Y)&&(y.cancel("Setup cancelled. Your .env is saved \u2014 re-run `klaudius init` to resume."),process.exit(0)),Y==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await D(s,l),o.success("Skipped Telegram. Setup will continue."),o.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),f=!0;break}if(Y==="edit"&&(o.blank(),l=await I(l,{onlySection:"telegram",banner:`Telegram check failed:
|
|
51
|
+
provider to Twilio.`}),await D(s,l)}}if(l.telegramBotToken&&l.telegramChatId){o.blank();let u=0,f=!1;for(;!f;){u++;let m=y.spinner();m.start("Validating Telegram bot + chat (sending a test ping)");let E=await Ke({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(E.ok){m.stop(E.botHandle?`Telegram bot ${E.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),f=!0;break}m.stop(E.message??"Telegram check failed",2);let De=E.message??"Telegram check failed";o.blank(),o.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),o.blank();let Y=await y.select({message:"What would you like to do?",initialValue:u>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(y.isCancel(Y)&&(y.cancel("Setup cancelled. Your .env is saved \u2014 re-run `npx klaudius init` to resume."),process.exit(0)),Y==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await D(s,l),o.success("Skipped Telegram. Setup will continue."),o.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),f=!0;break}if(Y==="edit"&&(o.blank(),l=await I(l,{onlySection:"telegram",banner:`Telegram check failed:
|
|
52
52
|
${De}
|
|
53
53
|
|
|
54
54
|
Re-enter the bot token or chat_id below.
|
|
55
|
-
Press Enter on any field to keep its current value.`}),await D(s,l),!l.telegramBotToken||!l.telegramChatId)){o.success("Skipped Telegram. Setup will continue."),f=!0;break}}}o.blank();let h=y.spinner();h.start("Downloading Klaudius template");let P;try{P=(await fe({licenseKey:
|
|
55
|
+
Press Enter on any field to keep its current value.`}),await D(s,l),!l.telegramBotToken||!l.telegramChatId)){o.success("Skipped Telegram. Setup will continue."),f=!0;break}}}o.blank();let h=y.spinner();h.start("Downloading Klaudius template");let P;try{P=(await fe({licenseKey:a,machineId:ie(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:s})).filesExtracted,h.stop(`Downloaded ${P} files into ${d.bold(s)}`)}catch(u){h.stop(u.message,2);let f=l.aiAgent==="codex"?".codex/config.toml":".mcp.json";o.detail(`Your .env / ${f} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await Se(q(s,"clients"),{recursive:!0});let L=await Ge(s);await ce(s,Ve(Sn,L)),o.success("Wrote .klaudius/manifest.json");let U=!1,N="";if(e.skipSchema)o.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),o.detail(`Apply manually later via the SQL editor: ${l.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+l.supabaseProjectRef+"/sql/new").replace(l.supabaseProjectRef+".supabase.co","")}`);else{o.blank();let u=y.spinner();u.start("Applying schema to Supabase");let f=await ot({projectRoot:s,pat:l.supabasePat,projectRef:l.supabaseProjectRef});f.ok?u.stop("Schema applied (or already present)"):(u.stop(f.message??"Schema apply failed",2),U=!0,N=`https://supabase.com/dashboard/project/${l.supabaseProjectRef}/sql/new`)}let b=[],w={};if(e.skipInstall)o.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{o.blank(),o.heading("Installing dependencies");let u=await ye(s);o.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&b.push("npm"),u.pip==="failed"&&b.push("pip"),u.playwright==="failed"&&b.push("playwright"),u.patchright==="failed"&&b.push("patchright"),w=u.hints??{}}let V=l.outreachEnabled&&l.outreachPriority?.includes("whatsapp")&&(l.whatsappAccounts?.length??0)>0,x=!e.skipInstall&&!b.includes("npm");if(V&&x){o.blank(),o.heading("Linking WhatsApp accounts"),console.log(d.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
|
|
56
56
|
phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
|
|
57
|
-
Link a Device, and point it at the QR shown in this terminal.`)),o.blank();for(let u of l.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${u}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius pair-whatsapp --label ${u})`));let f=kt(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:s,stdio:"inherit"});f.status===0?o.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${f.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))),o.blank()}}else if(V&&!
|
|
58
|
-
`:"",f=l.aiAgent==="codex"?"codex":"claude",m=l.aiAgent==="codex"?"Codex":"Claude Code",E=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";b.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),o.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan(f)} ${d.dim(`# open ${m} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${b.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius doctor."`)),o.blank(),console.log(d.dim(` (Don't have ${m} yet? Install with: \`${E}\`)`)),o.blank(),console.log(d.dim("Or do it yourself:")),o.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify everything")}`),o.blank()),U&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(N)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),o.blank()),b.includes("pip")&&!w.pip&&(console.log(d.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(d.dim(`Python 3.10+. Install a newer one from ${Nn()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),o.blank());let Y=["npm","playwright","patchright"].filter(J=>b.includes(J)&&!w[J]);if(Y.length>0){let J=Y.length===1?"keeps":"keep";console.log(d.dim(`If ${Y.join(" / ")} ${J} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius install`.")),o.blank()}console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),o.blank();return}y.outro(d.green(d.bold("Project ready."))),console.log(d.dim("Next steps:")),s!==process.cwd()&&console.log(` ${d.cyan(`cd ${e.target}`)}`);let j=process.platform==="win32"?"start":process.platform==="linux"?"xdg-open":"open",X=d.dim("# read this first \u2014 operator basics + commands");console.log(` ${d.cyan(`${j} DOCS.html`)}${" ".repeat(Math.max(1,17-j.length))}${X}`);let re=l.aiAgent==="codex"?"codex":"claude",Le=l.aiAgent==="codex"?"Codex":"Claude Code";console.log(` ${d.cyan(re)} ${d.dim(`# open ${Le} in this project`)}`),console.log(` ${d.dim(`then ask ${Le}:`)}`),console.log(` ${d.cyan(' "Run the pipeline."')}`),o.blank()}async function D(e,t){await Se(e,{recursive:!0}),await Ie(q(e,".env"),ue(t),"utf-8"),t.aiAgent==="codex"?(await Se(q(e,".codex"),{recursive:!0}),await Ie(q(e,".codex","config.toml"),me(t),"utf-8")):(await Ie(q(e,".mcp.json"),pe(t),"utf-8"),await we(e,"supabase"))}async function Rn(e){try{(await gt(e)).isDirectory()||(o.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Tn(e),s=t.filter(c=>!c.startsWith(".DS_Store"));if(s.length===0)return{kind:"fresh"};let n=new Set([".env",".mcp.json",".claude",".codex"]),a=s.every(c=>n.has(c)),i=s.includes(".env"),r=t.includes(".klaudius");if(a&&i&&!r)return{kind:"partial",envPath:q(e,".env")};if(r&&i){let c=!0;try{c=!(await gt(q(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:s}}async function vn(e){o.blank(),o.warn(`Found a partial setup at ${d.bold(e)}.`),o.detail(`A previous init wrote ${d.bold(".env")} but didn't finish scaffolding.`),o.blank();let t=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(t)&&(y.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function xn(e){if(e&&e.trim().length>0)return e;y.intro("Klaudius");let t=await y.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:s=>s.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return y.isCancel(t)&&(y.cancel("Setup cancelled. No files written."),process.exit(0)),t}function On(e){let t=In(e);if(process.platform==="win32"){let s=t.toLowerCase();if(s.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(s.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(s.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(s.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let s=["/System/","/usr/","/bin/","/sbin/"];for(let n of s)if(t.startsWith(n))return`Inside ${n.slice(0,-1)} (system-managed directory).`}}function $n(){if(process.platform!=="win32")return!1;try{return kt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Nn(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}import{access as Ln,readFile as Dn}from"fs/promises";import{join as Re,resolve as Mn}from"path";import x from"picocolors";async function Et(e){let t=e.target?Mn(process.cwd(),e.target):process.cwd(),s=await wt(Re(t,".env")),n=await wt(Re(t,"package.json"));(!s||!n)&&(o.error("This doesn't look like a Klaudius project."),o.detail(`Path: ${t}`),s||o.detail("Missing: .env"),n||o.detail("Missing: package.json"),o.blank(),o.detail("Run `npx klaudius init` to scaffold a new project first,"),o.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let a="claude-code";try{$(await Dn(Re(t,".env"),"utf-8")).AI_AGENT==="codex"&&(a="codex")}catch{}o.heading("Installing dependencies");let i=await ye(t);o.blank(),o.detail(`npm: ${i.npm}, pip: ${i.pip}, playwright: ${i.playwright}, patchright: ${i.patchright}`);let r=[];if(i.npm==="failed"&&r.push("npm"),i.pip==="failed"&&r.push("pip"),i.playwright==="failed"&&r.push("playwright"),i.patchright==="failed"&&r.push("patchright"),r.length===0){o.blank(),console.log(x.green(x.bold("All dependencies installed."))),console.log(x.dim("Run `npx klaudius doctor` to verify everything else (credentials, files).")),o.blank();return}o.blank(),console.log(x.yellow(x.bold(`${r.join(", ")} still failing.`))),o.blank();for(let[l,A]of Object.entries(i.hints??{}))console.log(x.yellow(`Likely cause of ${l} failure:`)),console.log(x.dim(` ${A}`)),o.blank();let c=a==="codex"?"codex":"claude",p=a==="codex"?"Codex":"Claude Code",g=a==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(x.dim("Options:")),console.log(x.dim(` \u2022 Open ${p} in this folder (\`${c}\`) and paste:`)),console.log(x.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius doctor."`)),console.log(x.dim(` (Don't have ${p} yet? Install with: \`${g}\`)`)),console.log(x.dim(" \u2022 Or run `npx klaudius doctor` for a structured diagnostic.")),console.log(x.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),o.blank(),process.exitCode=1}async function wt(e){try{return await Ln(e),!0}catch{return!1}}import{readFile as Un,writeFile as ve,access as jn}from"fs/promises";import{join as ne}from"path";import*as Ee from"@clack/prompts";import K from"picocolors";import{mkdir as Kn}from"fs/promises";async function At(e){let t=e.projectRoot??process.cwd(),s=ne(t,".env"),n=ne(t,".mcp.json"),a=ne(t,".codex","config.toml"),i=await xe(ne(t,".klaudius","manifest.json")),r=await xe(s);!i&&!r&&(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius init` first."),process.exit(1));let c=G();c.ok||(o.error(c.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `klaudius configure` in this folder."),process.exit(1));let p={};try{let h=await Un(s,"utf-8");p=$(h)}catch{o.warn("No .env found. Starting from an empty configuration.")}let g=Je(p);Ee.intro("Reconfigure Klaudius"),o.detail("Press Enter on any prompt to keep its current value."),o.blank();let l=await I(g),A=g.aiAgent??"claude-code";if(l.aiAgent&&l.aiAgent!==A&&(o.error(`Switching AI coding agent (${A} \u2192 ${l.aiAgent}) isn't supported via configure.`),o.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius init <new-folder>")} ${K.dim("# pick the new agent in the wizard")}`),o.blank(),o.detail(".env is unchanged."),process.exit(1)),l.supabaseUrl!==p.SUPABASE_URL||l.supabaseServiceKey!==p.SUPABASE_SERVICE_KEY){o.heading("Re-validating Supabase credentials");let h=await ee({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});h.ok||(o.error(h.message??"Supabase check failed"),o.warn("Aborting. .env not modified."),process.exit(1)),o.success("Supabase credentials accepted")}await ve(s,ue(l),"utf-8"),o.success("Updated .env"),l.aiAgent==="codex"?(await Kn(ne(t,".codex"),{recursive:!0}),await ve(a,me(l),"utf-8"),o.success("Updated .codex/config.toml")):(await ve(n,pe(l),"utf-8"),o.success("Updated .mcp.json"),await we(t,"supabase")),o.blank(),Ee.outro(K.green("Configuration updated.")),await Hn(t,i)}async function Hn(e,t){let s=await xe(ne(e,"node_modules"));o.blank(),t?s||(o.detail("Your project files are in place but dependencies aren't installed yet."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius install")} ${K.dim("# (re-)installs npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${K.cyan("npx klaudius doctor")} ${K.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius init")} ${K.dim("# pick Resume when prompted")}`),o.blank())}async function xe(e){try{return await jn(e),!0}catch{return!1}}import{copyFile as Pt,mkdir as bt,readdir as Fn,readFile as Vn,rm as ae,writeFile as Tt,access as _t}from"fs/promises";import{dirname as Ct,join as O,relative as Gn}from"path";import{tmpdir as Bn}from"os";import*as oe from"@clack/prompts";import Oe from"picocolors";var $e="0.15.0";async function It(e){let t=e.projectRoot??process.cwd(),s=await Fe(t);s||(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius init` first."),process.exit(1));for(let k of He)delete s.files[k];let n,a=O(t,".env"),i,r;try{i=await Vn(a,"utf-8"),r=$(i)}catch{o.error("Couldn't read .env from this directory."),o.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}n=r.KLAUDIUS_LICENSE_KEY??"",n||(o.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),o.detail("This file is created by `npx klaudius init`. If your project predates"),o.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius init`"),o.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=Xe(i,r,qe);c!==null&&(await Tt(a,c,"utf-8"),o.detail("Backfilled new env keys")),oe.intro(`Update from ${s.templateVersion} \u2192 ${$e}`);let g=r.AI_AGENT==="codex"?"codex":"claude-code",l=O(Bn(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{o.heading("Downloading the latest Klaudius template");let k=await fe({licenseKey:n,machineId:ie(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:g,destDir:l});o.success(`Fetched ${k.filesExtracted} canonical files`),A=l}catch(k){o.error(k.message),o.detail("Update aborted. Your project is unchanged."),await ae(l,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let h=await Wn(A,t,s),P=h.filter(k=>k.state==="new"),L=h.filter(k=>k.state==="clean-update"),U=h.filter(k=>k.state==="user-only"),N=h.filter(k=>k.state==="conflict"),b=h.filter(k=>k.state==="no-change"),w=h.filter(k=>k.state==="removed-clean"),V=h.filter(k=>k.state==="removed-modified"),v=[...N,...V];if(o.blank(),o.heading("Change summary"),o.detail(`${H(b.length,"file")} unchanged`),o.detail(`${H(P.length,"new file")}`),o.detail(`${H(L.length,"file")} updated cleanly (no local edits)`),o.detail(`${H(U.length,"file")} you've edited (no upstream change \u2014 left alone)`),o.detail(`${H(w.length,"file")} removed upstream (deleted cleanly)`),o.detail(`${H(N.length,"file")} with conflicts (you edited AND we have a new version)`),o.detail(`${H(V.length,"file")} removed upstream but edited locally (need your decision)`),P.length===0&&L.length===0&&w.length===0&&v.length===0){o.blank(),oe.outro(Oe.green("Already up to date.")),await ae(l,{recursive:!0,force:!0}).catch(()=>{});return}o.blank(),o.heading("Applying clean updates");for(let k of[...P,...L]){let j=O(A,k.path),X=O(t,k.path);await bt(Ct(X),{recursive:!0}),await Pt(j,X),s.files[k.path]=k.canonicalHash}P.length+L.length>0&&o.success(`Wrote ${H(P.length+L.length,"file")}`);for(let k of w){let j=O(t,k.path);await ae(j,{force:!0}),delete s.files[k.path]}if(w.length>0&&o.success(`Deleted ${H(w.length,"file")} removed upstream`),v.length>0){o.blank(),o.heading(`${v.length} conflict(s) need resolution`);let k=O(t,".klaudius","incoming");try{await ae(k,{recursive:!0,force:!0})}catch{}for(let j of N){let X=O(A,j.path),re=O(k,j.path);await bt(Ct(re),{recursive:!0}),await Pt(X,re)}await Tt(O(t,".klaudius","conflicts.md"),Yn(v,s.templateVersion,$e),"utf-8"),N.length>0&&o.detail("Staged canonical versions to .klaudius/incoming/"),o.detail("Wrote conflict report to .klaudius/conflicts.md")}if(s.updatedAt=new Date().toISOString(),v.length===0&&(s.templateVersion=$e),await ce(t,s),o.blank(),v.length===0)oe.outro(Oe.green("Update complete."));else{let k=g==="codex"?"Codex":"Claude Code";oe.outro(Oe.yellow(`${v.length} conflict(s) staged. Open ${k} in this project and ask:
|
|
59
|
-
"Run /resolve-conflicts"`))}await ae(l,{recursive:!0,force:!0}).catch(()=>{})}async function Wn(e,
|
|
60
|
-
`)}import{access as zn,readFile as Rt,stat as qn}from"fs/promises";import{join as M}from"path";import S from"picocolors";import{spawn as Xn}from"child_process";async function
|
|
61
|
-
`)),s.push(await Jn()),s.push(await Qn());let
|
|
57
|
+
Link a Device, and point it at the QR shown in this terminal.`)),o.blank();for(let u of l.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${u}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius pair-whatsapp --label ${u})`));let f=kt(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:s,stdio:"inherit"});f.status===0?o.detail(`Paired '${u}'.`):(console.log(d.yellow(`'${u}' did not pair (exit ${f.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))),o.blank()}}else if(V&&!x){o.blank(),console.log(d.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius install` completes successfully, pair via:"));for(let u of l.whatsappAccounts)console.log(d.cyan(` npx klaudius pair-whatsapp --label ${u}`))}o.blank();let k=[...b,...U?["schema"]:[]];if(k.length>0){y.outro(d.yellow(d.bold(`Setup paused \u2014 ${k.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),o.blank();for(let[J,Nt]of Object.entries(w))console.log(d.yellow(`Likely cause of ${J} failure:`)),console.log(d.dim(` ${Nt}`)),o.blank();let u=s!==process.cwd()?` ${d.cyan(`cd ${e.target}`)}
|
|
58
|
+
`:"",f=l.aiAgent==="codex"?"codex":"claude",m=l.aiAgent==="codex"?"Codex":"Claude Code",E=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";b.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),o.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan(f)} ${d.dim(`# open ${m} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${b.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius doctor."`)),o.blank(),console.log(d.dim(` (Don't have ${m} yet? Install with: \`${E}\`)`)),o.blank(),console.log(d.dim("Or do it yourself:")),o.blank(),u&&process.stdout.write(u),console.log(` ${d.cyan("npx klaudius install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius doctor")} ${d.dim("# verify everything")}`),o.blank()),U&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(N)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),o.blank()),b.includes("pip")&&!w.pip&&(console.log(d.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(d.dim(`Python 3.10+. Install a newer one from ${Nn()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),o.blank());let Y=["npm","playwright","patchright"].filter(J=>b.includes(J)&&!w[J]);if(Y.length>0){let J=Y.length===1?"keeps":"keep";console.log(d.dim(`If ${Y.join(" / ")} ${J} failing with network errors (ECONNRESET,`)),console.log(d.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(d.dim("phone's hotspot, then re-run `npx klaudius install`.")),o.blank()}console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),o.blank();return}y.outro(d.green(d.bold("Project ready."))),console.log(d.dim("Next steps:")),s!==process.cwd()&&console.log(` ${d.cyan(`cd ${e.target}`)}`);let j=process.platform==="win32"?"start":process.platform==="linux"?"xdg-open":"open",X=d.dim("# read this first \u2014 operator basics + commands");console.log(` ${d.cyan(`${j} DOCS.html`)}${" ".repeat(Math.max(1,17-j.length))}${X}`);let re=l.aiAgent==="codex"?"codex":"claude",Le=l.aiAgent==="codex"?"Codex":"Claude Code";console.log(` ${d.cyan(re)} ${d.dim(`# open ${Le} in this project`)}`),console.log(` ${d.dim(`then ask ${Le}:`)}`),console.log(` ${d.cyan(' "Run the pipeline."')}`),o.blank()}async function D(e,n){await Se(e,{recursive:!0}),await Ie(q(e,".env"),ue(n),"utf-8"),n.aiAgent==="codex"?(await Se(q(e,".codex"),{recursive:!0}),await Ie(q(e,".codex","config.toml"),me(n),"utf-8")):(await Ie(q(e,".mcp.json"),pe(n),"utf-8"),await we(e,"supabase"))}async function Rn(e){try{(await gt(e)).isDirectory()||(o.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let n=await Tn(e),s=n.filter(c=>!c.startsWith(".DS_Store"));if(s.length===0)return{kind:"fresh"};let t=new Set([".env",".mcp.json",".claude",".codex"]),i=s.every(c=>t.has(c)),a=s.includes(".env"),r=n.includes(".klaudius");if(i&&a&&!r)return{kind:"partial",envPath:q(e,".env")};if(r&&a){let c=!0;try{c=!(await gt(q(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:s}}async function xn(e){o.blank(),o.warn(`Found a partial setup at ${d.bold(e)}.`),o.detail(`A previous init wrote ${d.bold(".env")} but didn't finish scaffolding.`),o.blank();let n=await y.select({message:"How would you like to proceed?",initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return y.isCancel(n)&&(y.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),n}async function vn(e){if(e&&e.trim().length>0)return e;y.intro("Klaudius");let n=await y.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:s=>s.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return y.isCancel(n)&&(y.cancel("Setup cancelled. No files written."),process.exit(0)),n}function On(e){let n=In(e);if(process.platform==="win32"){let s=n.toLowerCase();if(s.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(s.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(s.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(s.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let s=["/System/","/usr/","/bin/","/sbin/"];for(let t of s)if(n.startsWith(t))return`Inside ${t.slice(0,-1)} (system-managed directory).`}}function $n(){if(process.platform!=="win32")return!1;try{return kt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Nn(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}import{access as Ln,readFile as Dn}from"fs/promises";import{join as Re,resolve as Mn}from"path";import v from"picocolors";async function Et(e){let n=e.target?Mn(process.cwd(),e.target):process.cwd(),s=await wt(Re(n,".env")),t=await wt(Re(n,"package.json"));(!s||!t)&&(o.error("This doesn't look like a Klaudius project."),o.detail(`Path: ${n}`),s||o.detail("Missing: .env"),t||o.detail("Missing: package.json"),o.blank(),o.detail("Run `npx klaudius init` to scaffold a new project first,"),o.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let i="claude-code";try{$(await Dn(Re(n,".env"),"utf-8")).AI_AGENT==="codex"&&(i="codex")}catch{}o.heading("Installing dependencies");let a=await ye(n);o.blank(),o.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let r=[];if(a.npm==="failed"&&r.push("npm"),a.pip==="failed"&&r.push("pip"),a.playwright==="failed"&&r.push("playwright"),a.patchright==="failed"&&r.push("patchright"),r.length===0){o.blank(),console.log(v.green(v.bold("All dependencies installed."))),console.log(v.dim("Run `npx klaudius doctor` to verify everything else (credentials, files).")),o.blank();return}o.blank(),console.log(v.yellow(v.bold(`${r.join(", ")} still failing.`))),o.blank();for(let[l,A]of Object.entries(a.hints??{}))console.log(v.yellow(`Likely cause of ${l} failure:`)),console.log(v.dim(` ${A}`)),o.blank();let c=i==="codex"?"codex":"claude",p=i==="codex"?"Codex":"Claude Code",g=i==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(v.dim("Options:")),console.log(v.dim(` \u2022 Open ${p} in this folder (\`${c}\`) and paste:`)),console.log(v.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius doctor."`)),console.log(v.dim(` (Don't have ${p} yet? Install with: \`${g}\`)`)),console.log(v.dim(" \u2022 Or run `npx klaudius doctor` for a structured diagnostic.")),console.log(v.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),o.blank(),process.exitCode=1}async function wt(e){try{return await Ln(e),!0}catch{return!1}}import{readFile as Un,writeFile as xe,access as jn}from"fs/promises";import{join as ne}from"path";import*as Ee from"@clack/prompts";import K from"picocolors";import{mkdir as Kn}from"fs/promises";async function At(e){let n=e.projectRoot??process.cwd(),s=ne(n,".env"),t=ne(n,".mcp.json"),i=ne(n,".codex","config.toml"),a=await ve(ne(n,".klaudius","manifest.json")),r=await ve(s);!a&&!r&&(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius init` first."),process.exit(1));let c=G();c.ok||(o.error(c.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius configure` in this folder."),process.exit(1));let p={};try{let h=await Un(s,"utf-8");p=$(h)}catch{o.warn("No .env found. Starting from an empty configuration.")}let g=Je(p);Ee.intro("Reconfigure Klaudius"),o.detail("Press Enter on any prompt to keep its current value."),o.blank();let l=await I(g),A=g.aiAgent??"claude-code";if(l.aiAgent&&l.aiAgent!==A&&(o.error(`Switching AI coding agent (${A} \u2192 ${l.aiAgent}) isn't supported via configure.`),o.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius init <new-folder>")} ${K.dim("# pick the new agent in the wizard")}`),o.blank(),o.detail(".env is unchanged."),process.exit(1)),l.supabaseUrl!==p.SUPABASE_URL||l.supabaseServiceKey!==p.SUPABASE_SERVICE_KEY){o.heading("Re-validating Supabase credentials");let h=await ee({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});h.ok||(o.error(h.message??"Supabase check failed"),o.warn("Aborting. .env not modified."),process.exit(1)),o.success("Supabase credentials accepted")}await xe(s,ue(l),"utf-8"),o.success("Updated .env"),l.aiAgent==="codex"?(await Kn(ne(n,".codex"),{recursive:!0}),await xe(i,me(l),"utf-8"),o.success("Updated .codex/config.toml")):(await xe(t,pe(l),"utf-8"),o.success("Updated .mcp.json"),await we(n,"supabase")),o.blank(),Ee.outro(K.green("Configuration updated.")),await Hn(n,a)}async function Hn(e,n){let s=await ve(ne(e,"node_modules"));o.blank(),n?s||(o.detail("Your project files are in place but dependencies aren't installed yet."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius install")} ${K.dim("# (re-)installs npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${K.cyan("npx klaudius doctor")} ${K.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius init")} ${K.dim("# pick Resume when prompted")}`),o.blank())}async function ve(e){try{return await jn(e),!0}catch{return!1}}import{copyFile as Pt,mkdir as bt,readdir as Fn,readFile as Vn,rm as ae,writeFile as Tt,access as _t}from"fs/promises";import{dirname as Ct,join as O,relative as Gn}from"path";import{tmpdir as Bn}from"os";import*as oe from"@clack/prompts";import Oe from"picocolors";var $e="0.15.2";async function It(e){let n=e.projectRoot??process.cwd(),s=await Fe(n);s||(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius init` first."),process.exit(1));for(let k of He)delete s.files[k];let t,i=O(n,".env"),a,r;try{a=await Vn(i,"utf-8"),r=$(a)}catch{o.error("Couldn't read .env from this directory."),o.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}t=r.KLAUDIUS_LICENSE_KEY??"",t||(o.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),o.detail("This file is created by `npx klaudius init`. If your project predates"),o.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius init`"),o.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=Xe(a,r,qe);c!==null&&(await Tt(i,c,"utf-8"),o.detail("Backfilled new env keys")),oe.intro(`Update from ${s.templateVersion} \u2192 ${$e}`);let g=r.AI_AGENT==="codex"?"codex":"claude-code",l=O(Bn(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{o.heading("Downloading the latest Klaudius template");let k=await fe({licenseKey:t,machineId:ie(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:g,destDir:l});o.success(`Fetched ${k.filesExtracted} canonical files`),A=l}catch(k){o.error(k.message),o.detail("Update aborted. Your project is unchanged."),await ae(l,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let h=await Wn(A,n,s),P=h.filter(k=>k.state==="new"),L=h.filter(k=>k.state==="clean-update"),U=h.filter(k=>k.state==="user-only"),N=h.filter(k=>k.state==="conflict"),b=h.filter(k=>k.state==="no-change"),w=h.filter(k=>k.state==="removed-clean"),V=h.filter(k=>k.state==="removed-modified"),x=[...N,...V];if(o.blank(),o.heading("Change summary"),o.detail(`${H(b.length,"file")} unchanged`),o.detail(`${H(P.length,"new file")}`),o.detail(`${H(L.length,"file")} updated cleanly (no local edits)`),o.detail(`${H(U.length,"file")} you've edited (no upstream change \u2014 left alone)`),o.detail(`${H(w.length,"file")} removed upstream (deleted cleanly)`),o.detail(`${H(N.length,"file")} with conflicts (you edited AND we have a new version)`),o.detail(`${H(V.length,"file")} removed upstream but edited locally (need your decision)`),P.length===0&&L.length===0&&w.length===0&&x.length===0){o.blank(),oe.outro(Oe.green("Already up to date.")),await ae(l,{recursive:!0,force:!0}).catch(()=>{});return}o.blank(),o.heading("Applying clean updates");for(let k of[...P,...L]){let j=O(A,k.path),X=O(n,k.path);await bt(Ct(X),{recursive:!0}),await Pt(j,X),s.files[k.path]=k.canonicalHash}P.length+L.length>0&&o.success(`Wrote ${H(P.length+L.length,"file")}`);for(let k of w){let j=O(n,k.path);await ae(j,{force:!0}),delete s.files[k.path]}if(w.length>0&&o.success(`Deleted ${H(w.length,"file")} removed upstream`),x.length>0){o.blank(),o.heading(`${x.length} conflict(s) need resolution`);let k=O(n,".klaudius","incoming");try{await ae(k,{recursive:!0,force:!0})}catch{}for(let j of N){let X=O(A,j.path),re=O(k,j.path);await bt(Ct(re),{recursive:!0}),await Pt(X,re)}await Tt(O(n,".klaudius","conflicts.md"),Yn(x,s.templateVersion,$e),"utf-8"),N.length>0&&o.detail("Staged canonical versions to .klaudius/incoming/"),o.detail("Wrote conflict report to .klaudius/conflicts.md")}if(s.updatedAt=new Date().toISOString(),x.length===0&&(s.templateVersion=$e),await ce(n,s),o.blank(),x.length===0)oe.outro(Oe.green("Update complete."));else{let k=g==="codex"?"Codex":"Claude Code";oe.outro(Oe.yellow(`${x.length} conflict(s) staged. Open ${k} in this project and ask:
|
|
59
|
+
"Run /resolve-conflicts"`))}await ae(l,{recursive:!0,force:!0}).catch(()=>{})}async function Wn(e,n,s){let t=await St(e),i=new Set(t),a=[];for(let r of t){let c=await le(O(e,r)),p=s.files[r],g=O(n,r),l;try{await _t(g),l=await le(g)}catch{a.push({path:r,state:"new",canonicalHash:c,manifestHash:p});continue}c===p?l===p?a.push({path:r,state:"no-change",canonicalHash:c,localHash:l,manifestHash:p}):a.push({path:r,state:"user-only",canonicalHash:c,localHash:l,manifestHash:p}):l===p?a.push({path:r,state:"clean-update",canonicalHash:c,localHash:l,manifestHash:p}):a.push({path:r,state:"conflict",canonicalHash:c,localHash:l,manifestHash:p})}for(let r of Object.keys(s.files)){if(i.has(r))continue;let c=s.files[r],p=O(n,r),g;try{await _t(p),g=await le(p)}catch{delete s.files[r];continue}g===c?a.push({path:r,state:"removed-clean",localHash:g,manifestHash:c}):a.push({path:r,state:"removed-modified",localHash:g,manifestHash:c})}return a}function H(e,n){return`${e} ${n}${e===1?"":"s"}`}async function St(e,n=e){let s=await Fn(e,{withFileTypes:!0}),t=[];for(let i of s){let a=O(e,i.name);i.isDirectory()?t.push(...await St(a,n)):i.isFile()&&t.push(Gn(n,a))}return t}function Yn(e,n,s){let t=e.filter(c=>c.state==="conflict").length,i=e.filter(c=>c.state==="removed-modified").length,a=[];a.push("# Update Conflicts"),a.push(""),a.push(`Generated by \`npx klaudius update\` on ${new Date().toISOString()}.`),a.push(`Updating from canonical version **${n}** to **${s}**.`),a.push("");let r=[];t>0&&r.push(`${t} file${t===1?"":"s"} ha${t===1?"s":"ve"} BOTH local edits AND upstream changes`),i>0&&r.push(`${i} file${i===1?"":"s"} ${i===1?"was":"were"} removed upstream but edited locally`),a.push(r.join(", and ")+"."),a.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),a.push(""),a.push("---"),a.push("");for(let c of e)a.push(`## ${c.path}`),a.push(""),c.state==="removed-modified"?(a.push("**Type:** Removed upstream"),a.push(""),a.push(`- Your local copy: \`${c.path}\``),a.push("- This file no longer exists in the canonical template."),a.push("- You've modified it locally since install."),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),a.push("2. Delete \u2014 remove the file from disk and from the manifest")):(a.push("**Type:** Edit conflict"),a.push(""),a.push(`- Your version (with your local edits): \`${c.path}\``),a.push(`- New canonical version: \`.klaudius/incoming/${c.path}\``),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(`- New canonical hash: \`${(c.canonicalHash??"(none)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 discard the new canonical changes"),a.push("2. Take canonical \u2014 overwrite my edits with the new version"),a.push("3. Merge \u2014 review both side-by-side and produce a combined version")),a.push(""),a.push("---"),a.push("");return a.join(`
|
|
60
|
+
`)}import{access as zn,readFile as Rt,stat as qn}from"fs/promises";import{join as M}from"path";import S from"picocolors";import{spawn as Xn}from"child_process";async function xt(e){let n=e.projectRoot??process.cwd(),s=[];console.log(S.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
61
|
+
`)),s.push(await Jn()),s.push(await Qn());let t=M(n,".env"),i=M(n,".klaudius","manifest.json"),a=M(n,".mcp.json"),r=M(n,".codex","config.toml"),c=await W(t),p=await W(i),g="claude-code";if(c)try{$(await Rt(t,"utf-8")).AI_AGENT==="codex"&&(g="codex")}catch{}if(g==="claude-code"){let h=await W(M(n,"AGENTS.md")),P=!await W(M(n,".claude"));h&&P&&(g="codex")}if(s.push({name:".env present",status:c?"ok":"fail",detail:c?t:"missing",nextAction:c?void 0:"Run `npx klaudius init` in this folder."}),s.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?"ok":"fail",detail:p?i:"missing",nextAction:p?void 0:c?"Init didn't finish \u2014 run `npx klaudius init` and pick Resume.":"Run `npx klaudius init`."}),g==="codex"){let h=await W(r);s.push({name:".codex/config.toml present",status:h?"ok":"warn",detail:h?r:"missing",nextAction:h?void 0:"Run `npx klaudius configure` to regenerate."})}else{let h=await W(a);s.push({name:".mcp.json present",status:h?"ok":"warn",detail:h?a:"missing",nextAction:h?void 0:"Run `npx klaudius configure` to regenerate."})}if(s.push(await oo(g)),s.push(await Zn(n)),s.push(await eo(n)),s.push(await to()),!c)s.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)s.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let h=await Rt(t,"utf-8"),P=$(h);await no(P,s)}console.log();for(let h of s){let P=h.status==="ok"?S.green("\u2713"):h.status==="warn"?S.yellow("\u26A0"):h.status==="skip"?S.dim("\xB7"):S.red("\u2717");console.log(` ${P} ${h.name}${h.detail?S.dim(` \u2014 ${h.detail}`):""}`),h.nextAction&&console.log(` ${S.dim("\u2192")} ${S.cyan(h.nextAction)}`)}let l=s.filter(h=>h.status==="fail").length,A=s.filter(h=>h.status==="warn").length;console.log(),l===0&&A===0?console.log(S.green(S.bold("Everything checks out. You're good to go."))):l===0?console.log(S.yellow(S.bold(`${A} warning${A===1?"":"s"} \u2014 review above.`))):(console.log(S.red(S.bold(`${l} failed check${l===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function W(e){try{return await zn(e),!0}catch{return!1}}async function Jn(){let e=await Z();return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:"Install Python 3.10+ from https://www.python.org/downloads/"}}async function Qn(){let e=process.version,n=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!n)return{name:"Node \u2265 22.15",status:"warn",detail:e};let s=parseInt(n[1],10),t=parseInt(n[2],10);return s<22||s===22&&t<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function Zn(e){let n=M(e,"node_modules");if(!await W(n))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius install` in this folder."};try{if(!(await qn(n)).isDirectory())return{name:"node_modules installed",status:"warn",detail:"exists but isn't a directory"}}catch{}return{name:"node_modules installed",status:"ok"}}async function eo(e){let n=process.platform==="darwin"?M(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?M(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):M(process.env.HOME??"",".cache","ms-playwright");return await W(n)?{name:"Playwright browser installed",status:"ok",detail:n}:{name:"Playwright browser installed",status:"fail",detail:"no browser cache found",nextAction:"Run `npx playwright install chromium` in this folder."}}async function to(){let e=["supabase","dotenv","requests","httpx","PIL"],n=`import sys
|
|
62
62
|
try:
|
|
63
|
-
${e.map(
|
|
63
|
+
${e.map(t=>` import ${t}`).join(`
|
|
64
64
|
`)}
|
|
65
65
|
except Exception as e:
|
|
66
66
|
print(str(e))
|
|
67
67
|
sys.exit(1)
|
|
68
|
-
`,s=await
|
|
69
|
-
`).pop()??"import failed",nextAction:"Run `npx klaudius install` in this folder."}}async function no(e,
|
|
70
|
-
`)[0]}:{name:s,status:"warn",detail:"not found",nextAction:
|
|
71
|
-
`));let
|
|
72
|
-
If you haven't already, add '${
|
|
73
|
-
WHATSAPP_ACCOUNTS=primary,${
|
|
74
|
-
(Skip this if '${
|
|
68
|
+
`,s=await vt("python3",["-c",n]);return s.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(s.stdout||s.stderr).trim().split(`
|
|
69
|
+
`).pop()??"import failed",nextAction:"Run `npx klaudius install` in this folder."}}async function no(e,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let t=await ee({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});n.push({name:"Supabase credentials",status:t.ok?"ok":"fail",detail:t.ok?"connected":t.message,nextAction:t.ok?void 0:"Run `npx klaudius configure` to fix the URL or key."})}else n.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});if((e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":"vercel")==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let t=await ge({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});n.push({name:"Cloudflare token + account",status:t.ok?"ok":"fail",detail:t.ok?`valid (${t.projectCount??0} Pages project${t.projectCount===1?"":"s"})`:t.message,nextAction:t.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius configure`."})}else n.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius configure` and pick Cloudflare."});else if(e.VERCEL_TOKEN){let t=await he(e.VERCEL_TOKEN);n.push({name:"Vercel token",status:t.ok?"ok":"fail",detail:t.ok?t.username??"valid":t.message,nextAction:t.ok?void 0:"Generate a new token at https://vercel.com/account/tokens, then `npx klaudius configure`."})}else n.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let t=await ke(e.GOOGLE_PLACES_API_KEY);n.push({name:"Google Places API key",status:t.ok?"ok":"fail",detail:t.ok?"accepted":t.message,nextAction:t.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius configure`."})}else n.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let t=await je({botToken:e.TELEGRAM_BOT_TOKEN});n.push({name:"Telegram bot token",status:t.ok?"ok":"fail",detail:t.ok?`bot ${t.botHandle??"ok"} (chat_id not tested)`:t.message,nextAction:t.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?n.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):n.push({name:"Telegram credentials",status:"skip",detail:"not configured (optional)"})}async function oo(e){let n=e==="codex"?"codex":"claude",s=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",t=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",i=await vt(n,["--version"]);return i.code===0?{name:s,status:"ok",detail:(i.stdout||i.stderr).trim().split(`
|
|
70
|
+
`)[0]}:{name:s,status:"warn",detail:"not found",nextAction:t}}function vt(e,n){return new Promise(s=>{let t=Xn(e,n,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";t.stdout?.on("data",r=>{i+=r.toString()}),t.stderr?.on("data",r=>{a+=r.toString()}),t.on("close",r=>s({code:r??1,stdout:i,stderr:a})),t.on("error",()=>s({code:1,stdout:i,stderr:a}))})}import{existsSync as so}from"fs";import{spawnSync as io}from"child_process";import{join as ao,resolve as ro}from"path";import R from"picocolors";async function Ot(e){let n=ro(e.projectRoot??process.cwd()),s=ao(n,"scripts","whatsapp.mjs");so(s)||(console.error(R.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(R.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius init`).")),console.error(R.dim(`Looked for: ${s}`)),process.exit(1));let t=(e.label??"primary").trim(),i=t.replace(/[^A-Za-z0-9_-]/g,"");i||(console.error(R.red(`Invalid label '${t}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),i!==t&&console.error(R.yellow(`Note: cleaned label '${t}' \u2192 '${i}' (filename-safe characters only).`)),console.log(R.cyan(`Pairing WhatsApp account '${i}'...`)),console.log(R.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
|
|
71
|
+
`));let a=io(process.execPath,[s,"pair","--account",i],{cwd:n,stdio:"inherit"});if(a.status===0){console.log(R.green(`Paired '${i}'.`)),console.log(R.dim(`
|
|
72
|
+
If you haven't already, add '${i}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
73
|
+
WHATSAPP_ACCOUNTS=primary,${i}
|
|
74
|
+
(Skip this if '${i}' is already there or you set it via the init wizard.)`));return}a.error?console.error(R.red(`Pair failed: ${a.error.message}`)):(console.error(R.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(R.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(R.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(R.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${i}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as lo}from"child_process";var Ne="--use-system-ca";function $t(){let e=process.env.NODE_OPTIONS??"";if(e.includes(Ne)||!G().ok)return;let s=e?`${e} ${Ne}`:Ne,t=lo(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:s},stdio:"inherit"});t.signal&&(process.kill(process.pid,t.signal),process.exit(1)),process.exit(t.status??1)}$t();var uo="0.15.2",F=new co;F.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(uo);F.command("preflight").description("Check this machine can run Klaudius (Node, Python, pip, npm, network) \u2014 no project or license needed. Safe for an AI assistant to run, fix, and re-run before init.").action(async()=>{try{await We({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});F.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").action(async(e,n)=>{try{await yt({target:e,license:n.license,skipInstall:!!n.skipInstall,skipSchema:!!n.skipSchema})}catch(s){console.error("init failed:",s.message),process.exit(1)}});F.command("install").description("Re-run dependency installers against an already-scaffolded project (npm, pip, playwright, patchright)").argument("[target]","Project directory (defaults to current directory)").action(async e=>{try{await Et({target:e})}catch(n){console.error("install failed:",n.message),process.exit(1)}});F.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await At({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});F.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await It({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});F.command("doctor").description("Diagnose a broken install \u2014 env versions, files, installed deps, credentials").option("--offline","Skip credential validations that require network calls").action(async e=>{try{await xt({offline:!!e.offline})}catch(n){console.error("doctor failed:",n.message),process.exit(1)}});F.command("pair-whatsapp").description("Link a WhatsApp account to this project (or re-pair if it logged out)").option("--label <name>","Account label (default: primary). Should match a value in WHATSAPP_ACCOUNTS.","primary").action(async e=>{try{await Ot({label:e.label})}catch(n){console.error("pair-whatsapp failed:",n.message),process.exit(1)}});F.parse(process.argv);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.15.
|
|
3
|
+
"version": "0.15.2",
|
|
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": {
|