klaudius 0.15.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 P,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
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,8 +22,7 @@ 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. You can change this any time via
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}),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
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
@@ -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. You can switch later with \`npx klaudius configure\`.`}),{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
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):
@@ -332,4 +331,4 @@ any messages your bot has received. To make that work:
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
333
  you.`}});let l=await ee({botToken:n});if(l.ok&&l.chatId)s=l.chatId;else if(l.reason==="no_messages")o="No messages from you to your bot have been picked up yet.",c="no_messages";else if(l.reason==="network")o=l.message??"Could not reach Telegram.",c="network";else throw new Error(`Telegram chat ID auto-detect failed: ${l.message??"unknown error"}`)}return{telegramBotToken:n,telegramChatId: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((r,l)=>{y("TextPromptUI:useInput fired",{input:r,ctrl:l.ctrl,escape:l.escape,return:l.return}),l.escape&&n()});let u=r=>{y("TextPromptUI:handleSubmit",{raw:r.slice(0,30)});let l=r;if(e.validate){let d=e.validate(l);if(d){y("TextPromptUI:validate failed",{err:d}),c(d);return}}c(null),t(l)};return q(j,{flexDirection:"column",children:[q(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(r=>(r-1+n.length)%n.length);else if(u.downArrow)o(r=>(r+1)%n.length);else if(u.return){let r=n[i];r&&a(r.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 r=u===i;return Z(Y,{color:r?"cyan":void 0,bold:r,children:[r?"\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(`
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,l]=M(null),[d,w]=M(null),[f,A]=M([]),[I,b]=M(null),[O,we]=M(!1),[W,Se]=M({current:0,total:0}),R=()=>{let h=o.current;for(let C of x){let $=C.isApplicable(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 v=++h;return y("orchestrator:promptFn called",{id:v,type:g.type,message:g.message.slice(0,60)}),b(null),new Promise((S,m)=>{w({id:v,spec:g,resolve:T=>{y("orchestrator:prompt resolved",{id:v,type:g.type,value:typeof T=="string"?T.slice(0,30):T}),S(T)},reject:T=>{y("orchestrator:prompt rejected",{id:v,reason:T.message}),m(T)}})})},$=g=>{A(v=>[...v,g])};return(async()=>{try{let g=t?x.filter(m=>m.id===t):x,v=()=>g.filter(m=>m.isApplicable(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");l(m.id);let T=g.slice(0,S+1).filter(k=>k.isApplicable(i.current)).length;Se({current:T,total:v()}),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),l(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 v=g instanceof Error?g.message:String(g);b(`Setup error: ${v}`),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"})),[r,O,I]);return V(P,{flexDirection:"column",paddingY:1,children:[V(P,{marginBottom:1,children:[p(E,{bold:!0,color:"cyan",children:"Klaudius setup"}),p(E,{dimColor:!0,children:" \xB7 "}),p(E,{dimColor:!0,children:W.total>0?`Step ${W.current} of ${W.total}`:"Loading\u2026"})]}),V(P,{children:[p(ue,{items:ke}),V(P,{flexDirection:"column",flexGrow:1,marginLeft:2,children:[n&&V(P,{marginBottom:1,borderStyle:"round",borderColor:"red",paddingX:1,flexDirection:"column",children:[p(E,{color:"red",bold:!0,children:"\u26A0 Heads up"}),p(E,{children:n})]}),f.map((h,C)=>p(P,{marginBottom:1,children:p(X,{title:h.title,body:h.body})},C)),d?.spec.note&&p(P,{marginBottom:1,children:p(X,{title:d.spec.note.title,body:d.spec.note.body})}),d&&ra(d),I&&p(P,{marginTop:1,children:p(E,{color:"red",children:I})}),O&&p(P,{marginTop:1,children:p(E,{color:"green",bold:!0,children:"\u2713 Setup complete. Continuing\u2026"})})]})]}),p(P,{marginTop:1,children:p(E,{dimColor:!0,children:sa(t,r)})})]})}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};
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),[r,l]=M(null),[d,w]=M(null),[f,A]=M([]),[I,b]=M(null),[O,we]=M(!1),[W,Se]=M({current:0,total:0}),R=()=>{let h=o.current;for(let C of x){let $=C.isApplicable(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");l(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),l(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"})),[r,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&&r!==null&&r!=="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,r)})})]})}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,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
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,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)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(t[1],10),n=parseInt(t[2],10),a=parseInt(t[3],10),i=`${s}.${n}.${a}`;return s<22||s===22&&n<15?{ok:!1,version:i,major:s,minor:n,message:`Your installed Node.js is ${i}. 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:i,major:s,minor:n}}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 t=await Ut(e[0],[...e.slice(1),"--version"]),s=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(s)||t.code!==0)continue;let n=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(s);if(!n)continue;let a=parseInt(n[1],10),i=parseInt(n[2],10),r=n[3]?`${a}.${i}.${n[3]}`:`${a}.${i}`;return{command:[...e],version:r,major:a,minor:i}}return null}async function Z(){let e=Mt(),t=await Ae();if(!t){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:n,major:a,minor:i}=t;return a<se||a===se&&i<de?{ok:!1,version:n,major:a,minor:i,command:s,message:`Your installed Python is ${n}. 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:n,major:a,minor:i,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,t){return new Promise(s=>{let n=Lt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",i="";n.stdout?.on("data",r=>{a+=r.toString()}),n.stderr?.on("data",r=>{i+=r.toString()}),n.on("close",r=>s({code:r??1,stdout:a,stderr:i})),n.on("error",()=>s({code:1,stdout:a,stderr:i}))})}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
3
  `));let t=[];t.push(Kt());let s=await Z();t.push(Ht(s)),t.push(await Ft(s.command)),t.push(await Vt()),t.push(await Gt());for(let a of t){let i=a.status==="ok"?T.green("\u2713"):T.red("\u2717");console.log(` ${i} ${a.name}${a.detail?T.dim(` \u2014 ${a.detail}`):""}`),a.nextAction&&console.log(` ${T.dim("\u2192")} ${T.cyan(a.nextAction)}`)}console.log();let n=t.filter(a=>a.status==="fail");if(n.length===0){Bt();return}console.log(T.red(T.bold(`${n.length} check${n.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 t=e??["python3"],s=await Pe(t[0],[...t.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:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.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,t){return new Promise(s=>{let n=jt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",i="";n.stdout?.on("data",r=>{a+=r.toString()}),n.stderr?.on("data",r=>{i+=r.toString()}),n.on("close",r=>s({code:r??1,stdout:a,stderr:i})),n.on("error",()=>s({code:1,stdout:a,stderr:i}))})}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={},t={}){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-U4NLWZDO.js"),n=null;Q("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),Ue(),await new Promise(i=>setImmediate(i)),await new Promise(i=>setTimeout(i,0)),Q("runWizard:event loop drained, mounting Ink");let a=Yt(Wt.createElement(s,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:i=>{Q("runWizard:onComplete called",{keys:Object.keys(i).length}),n=i}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(Q("runWizard:render returned, awaiting exit"),await a.waitUntilExit(),Q("runWizard:waitUntilExit resolved",{resultIsNull:n===null}),!n)throw new Error(`Wizard exited without completing. Diagnostic log: ${Me}
4
+ `)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.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,t){return new Promise(s=>{let n=jt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",i="";n.stdout?.on("data",r=>{a+=r.toString()}),n.stderr?.on("data",r=>{i+=r.toString()}),n.on("close",r=>s({code:r??1,stdout:a,stderr:i})),n.on("error",()=>s({code:1,stdout:a,stderr:i}))})}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={},t={}){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-R5DTNQF5.js"),n=null;Q("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),Ue(),await new Promise(i=>setImmediate(i)),await new Promise(i=>setTimeout(i,0)),Q("runWizard:event loop drained, mounting Ink");let a=Yt(Wt.createElement(s,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:i=>{Q("runWizard:onComplete called",{keys:Object.keys(i).length}),n=i}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(Q("runWizard:render returned, awaiting exit"),await a.waitUntilExit(),Q("runWizard:waitUntilExit resolved",{resultIsNull:n===null}),!n)throw new Error(`Wizard exited without completing. Diagnostic log: ${Me}
5
5
  Please share that file so we can trace what happened.`);return n}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 t=[],s=a=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${a}`),t.push("# "+"=".repeat(60)),t.push("")},n=(a,i)=>{if(i==null||i===""){t.push(`# ${a}=`);return}let r=String(i);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(r)){let c=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${a}="${c}"`)}else t.push(`${a}=${r}`)};return t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),s("Klaudius licence"),n("KLAUDIUS_LICENSE_KEY",e.licenseKey),s("AI coding agent"),n("AI_AGENT",e.aiAgent??be),s("Operating country and language"),n("OPERATOR_COUNTRY",e.country),n("OPERATOR_COUNTRY_CODE",e.countryCode),n("OPERATOR_LANGUAGE",e.language),n("OPERATOR_LANGUAGE_CODE",e.languageCode),s("Pricing"),n("PRICING",e.pricing),n("PRICING_TERMS",e.pricingTerms),n("PRICING_MONTHLY",e.pricingMonthly),s("Automated outreach features"),n("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),n("OPERATOR_NAME",e.name),n("SIGNATURE",e.signature),n("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),n("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),s("Email outreach"),n("EMAIL_ADDRESS",e.emailAddress),n("EMAIL_PASSWORD",e.emailPassword),n("EMAIL_FROM_NAME",e.emailFromName),n("EMAIL_SMTP_HOST",e.emailSmtpHost),n("EMAIL_SMTP_PORT",e.emailSmtpPort),n("EMAIL_IMAP_HOST",e.emailImapHost),n("EMAIL_IMAP_PORT",e.emailImapPort),n("EMAIL_SENT_FOLDER",e.emailSentFolder),n("EMAIL_INBOX_FOLDER",e.emailInboxFolder),s("SMS outreach"),n("SMS_PROVIDER",e.smsProvider),n("TEST_PHONE",e.testPhone),n("TWILIO_ACCOUNT_SID",e.twilioAccountSid),n("TWILIO_AUTH_TOKEN",e.twilioAuthToken),n("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),s("WhatsApp outreach"),n("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),s("Supabase (pipeline state)"),n("SUPABASE_URL",e.supabaseUrl),n("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),n("SUPABASE_PAT",e.supabasePat),n("SUPABASE_PROJECT_REF",e.supabaseProjectRef),s("Deployment"),n("DEPLOY_PROVIDER",e.deployProvider??Te),n("VERCEL_TOKEN",e.vercelToken),n("VERCEL_SCOPE",e.vercelScope??""),n("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),n("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("Search APIs"),n("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("SERPAPI_KEY",e.serpapiKey),s("Telegram notifications (optional)"),n("TELEGRAM_BOT_TOKEN",e.telegramBotToken),n("TELEGRAM_CHAT_ID",e.telegramChatId),s("Rate limiting (sensible defaults)"),n("REQUESTS_PER_MINUTE",10),n("REQUEST_DELAY",2),t.join(`
6
6
  `)+`
7
7
  `}function pe(e){let t={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(t,null,2)+`
@@ -11,14 +11,14 @@ Please share that file so we can trace what happened.`);return n}var be="claude-
11
11
  `,i=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let r of n)i.push(""),r.comment&&i.push(`# ${r.comment}`),i.push(qt(r.key,r.value));return e+a+i.join(`
12
12
  `)+`
13
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 t={};for(let s of e.split(`
14
- `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let a=n.indexOf("=");if(a===-1)continue;let i=n.slice(0,a).trim(),r=Xt(n.slice(a+1).trim());t[i]=r}return t}function Je(e){let t=c=>{let p=e[c];if(!p)return;let g=parseInt(p,10);return isNaN(g)?void 0:g},s=e.SMS_PROVIDER,n=c=>c==="email"||c==="sms"||c==="whatsapp",a=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(n),i=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(n),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:a&&a.length>0?a:void 0,outreachPriority:i&&i.length>0?i: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:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("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 t=w=>{let V=e[w];if(!V)return;let v=parseInt(V,10);return isNaN(v)?void 0:v},s=e.SUPABASE_URL,n=e.SUPABASE_SERVICE_KEY,a=e.SUPABASE_PAT,i=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||!n||!a||!i||!(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:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("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:n,supabasePat:a,supabaseProjectRef:i,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 t=process.env.KLAUDIUS_TEMPLATE_URL??en,s="0.15.0",n;try{n=await fetch(t,{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(!n.ok){let r="";try{let c=await n.json();r=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${n.status}${r}`)}if(!n.body)throw new Error("Template download succeeded but response had no body");let a=n.headers.get("x-klaudius-tier");await Jt(e.destDir,{recursive:!0});let i=0;try{await new Promise((r,c)=>{let p=Qe.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{i++}});p.on("finish",r),p.on("error",c),tn(n.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:i,tier:a}}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.0";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 t=e.trim(),n=(process.env.KLAUDIUS_API_URL??sn).replace(/\/$/,"")+an,a=ie(),i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:a,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 i.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${i.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${i.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){try{let t=await fetch(e.url+"/rest/v1/",{headers:{apikey:e.serviceKey,Authorization:`Bearer ${e.serviceKey}`}});return t.status===401||t.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${t.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(t){return{ok:!1,message:`Could not reach Supabase: ${_(t)}`}}}async function ot(e){let t;try{t=await ln(cn(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(s){return{ok:!1,message:`Could not read scripts/schema.sql: ${s.message}`}}try{let s=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${e.pat}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(s.ok)return{ok:!0};let n=await s.text();return n.includes("already exists")||n.includes('relation "clients" already exists')||n.includes("duplicate")?(o.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${s.status}): ${n.slice(0,300)}`}}catch(s){return{ok:!1,message:`Schema apply failed: ${s.message}`}}}async function he(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let s=await t.json();return{ok:!0,username:s.user?.username??s.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${_(t)}`}}}var st="https://api.cloudflare.com/client/v4";function it(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ge(e){let{token:t,accountId:s}=e,n={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let a=await fetch(`${st}/user/tokens/verify`,{headers:n});if(a.status===401||a.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${a.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} verifying the token. Try again or check cloudflarestatus.com.`};let i=await a.json(),r=i.result?.status;if(i.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${it(i)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${_(a)}`}}try{let a=await fetch(`${st}/accounts/${encodeURIComponent(s)}/pages/projects`,{headers:n});if(a.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(a.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(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let i=await a.json();return i.success===!1?{ok:!1,message:it(i)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(i.result)?i.result.length:void 0}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${_(a)}`}}}async function ke(e){try{let t=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(t.ok)return{ok:!0};if(t.status===429)return{ok:!0};let s={};try{s=await t.json()}catch{}let n=s.error?.message??"",a=s.error?.status??"";return t.status===400&&(a==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(n))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:t.status===401||t.status===403?{ok:!1,message:n||`Google rejected the key (HTTP ${t.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 ${t.status}${n?`: ${n}`:""}.`}}catch(t){return{ok:!1,message:`Could not reach Google: ${_(t)}`}}}import dn from"nodemailer";import{ImapFlow as un}from"imapflow";async function rt(e){let t=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 t.verify()}catch(n){return{ok:!1,failedAt:"smtp",message:at(n,"SMTP")}}finally{t.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(n){try{await s.logout()}catch{}return{ok:!1,failedAt:"imap",message:at(n,"IMAP")}}return{ok:!0}}function at(e,t){let s=e instanceof Error?e.message:String(e),n=s.toLowerCase();return n.includes("invalid credentials")||n.includes("authentication failed")||n.includes("auth failed")||n.includes("login failed")?`${t} rejected the credentials. Most common causes:
14
+ `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let a=n.indexOf("=");if(a===-1)continue;let i=n.slice(0,a).trim(),r=Xt(n.slice(a+1).trim());t[i]=r}return t}function Je(e){let t=c=>{let p=e[c];if(!p)return;let g=parseInt(p,10);return isNaN(g)?void 0:g},s=e.SMS_PROVIDER,n=c=>c==="email"||c==="sms"||c==="whatsapp",a=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(n),i=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(n),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:a&&a.length>0?a:void 0,outreachPriority:i&&i.length>0?i: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:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("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 t=w=>{let V=e[w];if(!V)return;let v=parseInt(V,10);return isNaN(v)?void 0:v},s=e.SUPABASE_URL,n=e.SUPABASE_SERVICE_KEY,a=e.SUPABASE_PAT,i=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||!n||!a||!i||!(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:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("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:n,supabasePat:a,supabaseProjectRef:i,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 t=process.env.KLAUDIUS_TEMPLATE_URL??en,s="0.15.1",n;try{n=await fetch(t,{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(!n.ok){let r="";try{let c=await n.json();r=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${n.status}${r}`)}if(!n.body)throw new Error("Template download succeeded but response had no body");let a=n.headers.get("x-klaudius-tier");await Jt(e.destDir,{recursive:!0});let i=0;try{await new Promise((r,c)=>{let p=Qe.extract({cwd:e.destDir,strict:!0,onReadEntry:()=>{i++}});p.on("finish",r),p.on("error",c),tn(n.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:i,tier:a}}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.1";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 t=e.trim(),n=(process.env.KLAUDIUS_API_URL??sn).replace(/\/$/,"")+an,a=ie(),i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:a,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 i.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${i.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${i.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){try{let t=await fetch(e.url+"/rest/v1/",{headers:{apikey:e.serviceKey,Authorization:`Bearer ${e.serviceKey}`}});return t.status===401||t.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${t.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(t){return{ok:!1,message:`Could not reach Supabase: ${_(t)}`}}}async function ot(e){let t;try{t=await ln(cn(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(s){return{ok:!1,message:`Could not read scripts/schema.sql: ${s.message}`}}try{let s=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${e.pat}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(s.ok)return{ok:!0};let n=await s.text();return n.includes("already exists")||n.includes('relation "clients" already exists')||n.includes("duplicate")?(o.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${s.status}): ${n.slice(0,300)}`}}catch(s){return{ok:!1,message:`Schema apply failed: ${s.message}`}}}async function he(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let s=await t.json();return{ok:!0,username:s.user?.username??s.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${_(t)}`}}}var st="https://api.cloudflare.com/client/v4";function it(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ge(e){let{token:t,accountId:s}=e,n={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let a=await fetch(`${st}/user/tokens/verify`,{headers:n});if(a.status===401||a.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${a.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} verifying the token. Try again or check cloudflarestatus.com.`};let i=await a.json(),r=i.result?.status;if(i.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${it(i)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${_(a)}`}}try{let a=await fetch(`${st}/accounts/${encodeURIComponent(s)}/pages/projects`,{headers:n});if(a.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(a.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(!a.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${a.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let i=await a.json();return i.success===!1?{ok:!1,message:it(i)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(i.result)?i.result.length:void 0}}catch(a){return{ok:!1,message:`Could not reach Cloudflare: ${_(a)}`}}}async function ke(e){try{let t=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(t.ok)return{ok:!0};if(t.status===429)return{ok:!0};let s={};try{s=await t.json()}catch{}let n=s.error?.message??"",a=s.error?.status??"";return t.status===400&&(a==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(n))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:t.status===401||t.status===403?{ok:!1,message:n||`Google rejected the key (HTTP ${t.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 ${t.status}${n?`: ${n}`:""}.`}}catch(t){return{ok:!1,message:`Could not reach Google: ${_(t)}`}}}import dn from"nodemailer";import{ImapFlow as un}from"imapflow";async function rt(e){let t=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 t.verify()}catch(n){return{ok:!1,failedAt:"smtp",message:at(n,"SMTP")}}finally{t.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(n){try{await s.logout()}catch{}return{ok:!1,failedAt:"imap",message:at(n,"IMAP")}}return{ok:!0}}function at(e,t){let s=e instanceof Error?e.message:String(e),n=s.toLowerCase();return n.includes("invalid credentials")||n.includes("authentication failed")||n.includes("auth failed")||n.includes("login failed")?`${t} 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
18
  \u2022 2FA is required but no app-specific password was generated.`:n.includes("etimedout")||n.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:n.includes("enotfound")||n.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}async function lt(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,s=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let n=await fetch(t,{headers:{Authorization:`Basic ${s}`}});if(n.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!n.ok)return{ok:!1,message:`Twilio API returned HTTP ${n.status}. Try again or check status.twilio.com.`};let a=await n.json();return a.status&&a.status!=="active"?{ok:!1,message:`Twilio account is in '${a.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:a.friendly_name}}catch(n){return{ok:!1,message:`Could not reach Twilio: ${_(n)}`}}}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,"")}"`,n=await mn(s);if(n.code===0)return{ok:!0};let a=n.stderr.toLowerCase();return a.includes("can't get application")||a.includes("isn't running")||a.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:a.includes("(-1728)")||a.includes("not found")||a.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:a.includes("(-1719)")||a.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${n.stderr.trim()||`exit code ${n.code}`}`}}function mn(e){return new Promise(t=>{let s=pn("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),n="";s.stderr.on("data",a=>{n+=a.toString()}),s.on("close",a=>t({code:a??1,stderr:n})),s.on("error",a=>t({code:1,stderr:a.message}))})}import{spawn as dt}from"child_process";function fn(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}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,t){let s=e+`
19
19
  `+t;return hn.some(n=>n.test(s))}function mt(e){return new Promise(t=>setTimeout(t,e))}function gn(e,t,s){return new Promise(n=>{let a=dt(e,t,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:s.env??process.env}),i="",r="";a.stdout?.on("data",c=>{let p=c.toString();i+=p,process.stdout.write(p)}),a.stderr?.on("data",c=>{let p=c.toString();r+=p,process.stderr.write(p)}),a.on("close",c=>n({code:c??1,stdout:i,stderr:r})),a.on("error",c=>n({code:1,stdout:i,stderr:r+c.message}))})}async function Ce(e,t,s){let n={code:0,stdout:"",stderr:""};for(let a=0;a<=te;a++){if(n=await gn(e,t,{cwd:s.cwd,env:s.env}),n.code===0||!pt(n.stderr,n.stdout))return n;a<te&&(o.detail(`${s.label} failed with a transient network error \u2014 retrying (${a+2}/${te+1})\u2026`),await mt(ut))}return n}function kn(e,t,s){return new Promise(n=>{let a=dt(e,t,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),i="",r="";a.stdout?.on("data",c=>{i+=c.toString()}),a.stderr?.on("data",c=>{r+=c.toString()}),a.on("close",c=>n({code:c??1,stdout:i,stderr:r})),a.on("error",c=>n({code:1,stdout:i,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 t=`${e.stderr??""}
20
20
  ${e.stdout??""}`;return yn.find(n=>n.pattern.test(t))?.hint}async function En(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],s=["-m","pip","install","--quiet","--user"],a=(await Ae())?.command??["python3"],i=async c=>{let p={code:0,stdout:"",stderr:""};for(let g=0;g<=te;g++){if(p=await kn(a[0],[...a.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 i([...s,"--break-system-packages",...t]);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 i([...s,...t])),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 t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},s=fn(),n=(p,g)=>{let l=wn(g);l&&((t.hints??={})[p]=l)};o.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await Ce("npm",["install"],{cwd:e,label:"npm install",env:s});t.npm=a.code===0?"ok":"failed",a.code!==0&&n("npm",a),o.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let i=await En(e);t.pip=i.code===0?"ok":"failed",i.code!==0&&n("pip",i),o.step("Installing Playwright browser (chromium ~200MB; one-time)...");let r=await Ce("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:s});t.playwright=r.code===0?"ok":"failed",r.code!==0&&n("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 t.patchright=c.code===0?"ok":"failed",c.code!==0&&n("patchright",c),t}import{mkdir as An,readFile as Pn,writeFile as bn}from"fs/promises";import{join as ft}from"path";async function we(e,t){let s=ft(e,".claude");await An(s,{recursive:!0});let n=ft(s,"settings.json"),a={};try{let p=await Pn(n,"utf-8"),g=JSON.parse(p);g&&typeof g=="object"&&!Array.isArray(g)&&(a=g)}catch{}let i=a.enabledMcpjsonServers,r=Array.isArray(i)?i.filter(p=>typeof p=="string"):[];r.includes(t)||r.push(t);let c={...a,enabledMcpjsonServers:r};await bn(n,JSON.stringify(c,null,2)+`
21
- `,"utf-8")}var Sn="0.15.0",C=5;function z(e,t){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: ${t}`),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 `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 t=e.target??".",s=Cn(t)?t:_n(process.cwd(),t),n=On(s);n&&(o.error("Klaudius can't be installed inside a protected system folder."),o.detail(`Path: ${s}`),o.detail(`Reason: ${n}`),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 klaudius init."),o.blank());let a=await Rn(s);if(a.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(),a.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 ${t}`)}`),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(a.kind==="occupied"){let u=t===".";o.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),o.detail(`Path: ${s}`),o.detail(`Contains: ${a.entries.slice(0,5).join(", ")}${a.entries.length>5?`, \u2026 (+${a.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 '${t}' already exists and isn't empty.`),o.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius init ${t}-2`)}`),o.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let i=await xn(e.license),r=y.spinner();r.start("Validating license");let c=await nt(i);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 `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 `klaudius init` in this folder."),process.exit(1));let l,A=!1;if(a.kind==="partial")if(await vn(s)==="resume"){let f=await ht(a.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(a.envPath,"utf-8"),m=_e($(f));l=await I(m??{})}else l=await I();l.licenseKey=i,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:
21
+ `,"utf-8")}var Sn="0.15.1",C=5;function z(e,t){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: ${t}`),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 `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 t=e.target??".",s=Cn(t)?t:_n(process.cwd(),t),n=On(s);n&&(o.error("Klaudius can't be installed inside a protected system folder."),o.detail(`Path: ${s}`),o.detail(`Reason: ${n}`),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 klaudius init."),o.blank());let a=await Rn(s);if(a.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(),a.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 ${t}`)}`),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(a.kind==="occupied"){let u=t===".";o.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),o.detail(`Path: ${s}`),o.detail(`Contains: ${a.entries.slice(0,5).join(", ")}${a.entries.length>5?`, \u2026 (+${a.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 '${t}' already exists and isn't empty.`),o.detail("Either pick a different name:"),console.log(` ${d.cyan(`npx klaudius init ${t}-2`)}`),o.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let i=await xn(e.license),r=y.spinner();r.start("Validating license");let c=await nt(i);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 `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 `klaudius init` in this folder."),process.exit(1));let l,A=!1;if(a.kind==="partial")if(await vn(s)==="resume"){let f=await ht(a.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(a.envPath,"utf-8"),m=_e($(f));l=await I(m??{})}else l=await I();l.licenseKey=i,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
@@ -55,7 +55,7 @@ Re-enter the bot token or chat_id below.
55
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:i,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,v=!e.skipInstall&&!b.includes("npm");if(V&&v){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
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&&!v){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,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:
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.1";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
59
  "Run /resolve-conflicts"`))}await ae(l,{recursive:!0,force:!0}).catch(()=>{})}async function Wn(e,t,s){let n=await St(e),a=new Set(n),i=[];for(let r of n){let c=await le(O(e,r)),p=s.files[r],g=O(t,r),l;try{await _t(g),l=await le(g)}catch{i.push({path:r,state:"new",canonicalHash:c,manifestHash:p});continue}c===p?l===p?i.push({path:r,state:"no-change",canonicalHash:c,localHash:l,manifestHash:p}):i.push({path:r,state:"user-only",canonicalHash:c,localHash:l,manifestHash:p}):l===p?i.push({path:r,state:"clean-update",canonicalHash:c,localHash:l,manifestHash:p}):i.push({path:r,state:"conflict",canonicalHash:c,localHash:l,manifestHash:p})}for(let r of Object.keys(s.files)){if(a.has(r))continue;let c=s.files[r],p=O(t,r),g;try{await _t(p),g=await le(p)}catch{delete s.files[r];continue}g===c?i.push({path:r,state:"removed-clean",localHash:g,manifestHash:c}):i.push({path:r,state:"removed-modified",localHash:g,manifestHash:c})}return i}function H(e,t){return`${e} ${t}${e===1?"":"s"}`}async function St(e,t=e){let s=await Fn(e,{withFileTypes:!0}),n=[];for(let a of s){let i=O(e,a.name);a.isDirectory()?n.push(...await St(i,t)):a.isFile()&&n.push(Gn(t,i))}return n}function Yn(e,t,s){let n=e.filter(c=>c.state==="conflict").length,a=e.filter(c=>c.state==="removed-modified").length,i=[];i.push("# Update Conflicts"),i.push(""),i.push(`Generated by \`npx klaudius update\` on ${new Date().toISOString()}.`),i.push(`Updating from canonical version **${t}** to **${s}**.`),i.push("");let r=[];n>0&&r.push(`${n} file${n===1?"":"s"} ha${n===1?"s":"ve"} BOTH local edits AND upstream changes`),a>0&&r.push(`${a} file${a===1?"":"s"} ${a===1?"was":"were"} removed upstream but edited locally`),i.push(r.join(", and ")+"."),i.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."),i.push(""),i.push("---"),i.push("");for(let c of e)i.push(`## ${c.path}`),i.push(""),c.state==="removed-modified"?(i.push("**Type:** Removed upstream"),i.push(""),i.push(`- Your local copy: \`${c.path}\``),i.push("- This file no longer exists in the canonical template."),i.push("- You've modified it locally since install."),i.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),i.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),i.push(""),i.push("**Resolution options for the SKILL to walk through:**"),i.push(""),i.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),i.push("2. Delete \u2014 remove the file from disk and from the manifest")):(i.push("**Type:** Edit conflict"),i.push(""),i.push(`- Your version (with your local edits): \`${c.path}\``),i.push(`- New canonical version: \`.klaudius/incoming/${c.path}\``),i.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),i.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),i.push(`- New canonical hash: \`${(c.canonicalHash??"(none)").slice(0,16)}\``),i.push(""),i.push("**Resolution options for the SKILL to walk through:**"),i.push(""),i.push("1. Keep mine \u2014 discard the new canonical changes"),i.push("2. Take canonical \u2014 overwrite my edits with the new version"),i.push("3. Merge \u2014 review both side-by-side and produce a combined version")),i.push(""),i.push("---"),i.push("");return i.join(`
60
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 vt(e){let t=e.projectRoot??process.cwd(),s=[];console.log(S.bold(`Klaudius doctor \u2014 checking your project\u2026
61
61
  `)),s.push(await Jn()),s.push(await Qn());let n=M(t,".env"),a=M(t,".klaudius","manifest.json"),i=M(t,".mcp.json"),r=M(t,".codex","config.toml"),c=await W(n),p=await W(a),g="claude-code";if(c)try{$(await Rt(n,"utf-8")).AI_AGENT==="codex"&&(g="codex")}catch{}if(g==="claude-code"){let h=await W(M(t,"AGENTS.md")),P=!await W(M(t,".claude"));h&&P&&(g="codex")}if(s.push({name:".env present",status:c?"ok":"fail",detail:c?n:"missing",nextAction:c?void 0:"Run `klaudius init` in this folder."}),s.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?"ok":"fail",detail:p?a:"missing",nextAction:p?void 0:c?"Init didn't finish \u2014 run `klaudius init` and pick Resume.":"Run `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 `klaudius configure` to regenerate."})}else{let h=await W(i);s.push({name:".mcp.json present",status:h?"ok":"warn",detail:h?i:"missing",nextAction:h?void 0:"Run `klaudius configure` to regenerate."})}if(s.push(await oo(g)),s.push(await Zn(t)),s.push(await eo(t)),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(n,"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,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let s=parseInt(t[1],10),n=parseInt(t[2],10);return s<22||s===22&&n<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function Zn(e){let t=M(e,"node_modules");if(!await W(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius install` in this folder."};try{if(!(await qn(t)).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 t=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(t)?{name:"Playwright browser installed",status:"ok",detail:t}:{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"],t=`import sys
@@ -71,4 +71,4 @@ except Exception as e:
71
71
  `));let i=io(process.execPath,[s,"pair","--account",a],{cwd:t,stdio:"inherit"});if(i.status===0){console.log(R.green(`Paired '${a}'.`)),console.log(R.dim(`
72
72
  If you haven't already, add '${a}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
73
73
  WHATSAPP_ACCOUNTS=primary,${a}
74
- (Skip this if '${a}' is already there or you set it via the init wizard.)`));return}i.error?console.error(R.red(`Pair failed: ${i.error.message}`)):(console.error(R.red(`Pair did not complete (exit ${i.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/${a}/daemon.log`))),process.exit(i.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,n=lo(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:s},stdio:"inherit"});n.signal&&(process.kill(process.pid,n.signal),process.exit(1)),process.exit(n.status??1)}$t();var uo="0.15.0",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,t)=>{try{await yt({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.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(t){console.error("install failed:",t.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 vt({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.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(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});F.parse(process.argv);
74
+ (Skip this if '${a}' is already there or you set it via the init wizard.)`));return}i.error?console.error(R.red(`Pair failed: ${i.error.message}`)):(console.error(R.red(`Pair did not complete (exit ${i.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/${a}/daemon.log`))),process.exit(i.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,n=lo(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:s},stdio:"inherit"});n.signal&&(process.kill(process.pid,n.signal),process.exit(1)),process.exit(n.status??1)}$t();var uo="0.15.1",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,t)=>{try{await yt({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.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(t){console.error("install failed:",t.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 vt({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.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(t){console.error("pair-whatsapp failed:",t.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.0",
3
+ "version": "0.15.1",
4
4
  "description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code (find, build, deploy, outreach end-to-end).",
5
5
  "homepage": "https://klaudius.dev",
6
6
  "bugs": {