klaudius 0.22.0 → 0.22.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +10 -8
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -12,8 +12,8 @@ Please share that file so we can trace what happened.`);return i}var qe="claude-
|
|
|
12
12
|
`)+`
|
|
13
13
|
`}function zn(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 H(e){let t={};for(let n of e.split(`
|
|
14
14
|
`)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.indexOf("=");if(s===-1)continue;let a=i.slice(0,s).trim(),l=zn(i.slice(s+1).trim());t[a]=l}return t}function Ct(e){let t=c=>{let u=e[c];if(!u)return;let m=parseInt(u,10);return isNaN(m)?void 0:m},n=e.SMS_PROVIDER,i=c=>c==="email"||c==="sms"||c==="whatsapp",s=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(i),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(i),l=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Pt(e.AI_AGENT)??qe,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,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(c=>c.trim().toLowerCase()).filter(Boolean):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:s&&s.length>0?s:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailProvider:Re(e),emailAuth:St(e.EMAIL_AUTH),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:n==="imessage"||n==="twilio"?n:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:Tt(e.DEPLOY_PROVIDER)??Je,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN||void 0,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID||void 0,netlifyAuthToken:e.NETLIFY_AUTH_TOKEN||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:e.SELFHOST_DEPLOY_TARGET||void 0,selfhostUrlTemplate:e.SELFHOST_URL_TEMPLATE||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,emailPassword:e.EMAIL_PASSWORD,notifyChannel:bt(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function Xe(e){let t=g=>{let L=e[g];if(!L)return;let Y=parseInt(L,10);return isNaN(Y)?void 0:Y},n=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),s=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,l=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",u=Tt(e.DEPLOY_PROVIDER)??Je,m=e.VERCEL_TOKEN,r=e.CLOUDFLARE_API_TOKEN,E=e.CLOUDFLARE_ACCOUNT_ID,y=e.NETLIFY_AUTH_TOKEN,k=e.SELFHOST_DEPLOY_TARGET,b=e.SELFHOST_URL_TEMPLATE;if(!l||!n||!i||!s||!a||!(u==="cloudflare"?!!r&&!!E:u==="netlify"?!!y:u==="selfhost"?!!k&&!!b:!!m))return null;let N=e.SMS_PROVIDER,ie=g=>g==="email"||g==="sms"||g==="whatsapp",P=e.OUTREACH_CHANNELS?.split(",").map(g=>g.trim()).filter(ie),F=e.OUTREACH_PRIORITY?.split(",").map(g=>g.trim()).filter(ie),O=e.WHATSAPP_ACCOUNTS?.split(",").map(g=>g.trim()).filter(g=>g.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Pt(e.AI_AGENT)??qe,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,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(g=>g.trim().toLowerCase()).filter(Boolean):void 0,pricing:l,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:P&&P.length>0?P:void 0,outreachPriority:F&&F.length>0?F:void 0,whatsappAccounts:O&&O.length>0?O:void 0,emailProvider:Re(e),emailAuth:St(e.EMAIL_AUTH),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:N==="imessage"||N==="twilio"?N:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:u,vercelToken:m,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:r||void 0,cloudflareAccountId:E||void 0,netlifyAuthToken:y||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:k||void 0,selfhostUrlTemplate:b||void 0,supabaseUrl:n,supabaseServiceKey:i,supabasePat:s,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:bt(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as ts,mkdir as ns,readdir as oo,stat as os}from"fs/promises";import{dirname as ss,join as Nt,relative as io,sep as so}from"path";import{fileURLToPath as rs}from"url";import{createHash as qn}from"crypto";import{readFile as Jn}from"fs/promises";async function ue(e){let t=await Jn(e);return qn("sha256").update(t).digest("hex")}import{mkdir as Xn,readFile as Qn,writeFile as Zn,access as eo}from"fs/promises";import{dirname as to,join as Rt}from"path";var no=".klaudius",xt=`${no}/manifest.json`,Ne=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml",".ms-token.json"]);async function Ot(e){let t=Rt(e,xt);try{await eo(t)}catch{return null}let n=await Qn(t,"utf-8"),i=JSON.parse(n),s={};for(let[a,l]of Object.entries(i.files??{}))s[a.split("\\").join("/")]=l;return i.files=s,i}async function $e(e,t){let n=Rt(e,xt);await Xn(to(n),{recursive:!0}),await Zn(n,JSON.stringify(t,null,2)+`
|
|
15
|
-
`,"utf-8")}function vt(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function pe(e,t=e){let n=await oo(e,{withFileTypes:!0}),i=[];for(let s of n){let a=Nt(e,s.name);s.isDirectory()?i.push(...await pe(a,t)):s.isFile()&&i.push(io(t,a).split(so).join("/"))}return i}async function $t(e){let t=await pe(e),n={};for(let i of t)Ne.has(i)||(n[i]=await ue(Nt(e,i)));return n}import{copyFile as ao,mkdir as Lt,mkdtemp as ro,readdir as Mt,rm as Dt}from"fs/promises";import{tmpdir as lo}from"os";import{dirname as co,join as Le}from"path";import{Readable as uo}from"stream";import*as Ht from"tar";var po="https://klaudius.dev/api/template";function fo(e){return uo.fromWeb(e)}async function Me(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??po,n="0.22.
|
|
16
|
-
`+te.bold(te.cyan(e))),detail:e=>console.log(te.dim(" "+e))};var mo="https://registry.npmjs.org/klaudius/latest";async function ho(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(mo,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let s=await i.json();return typeof s.version=="string"?s.version:null}catch{return null}finally{clearTimeout(n)}}function go(e,t){let n=a=>a.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),i=n(e),s=n(t);if(i.length<3||s.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(i[a])||Number.isNaN(s[a]))return!1;if(i[a]>s[a])return!0;if(i[a]<s[a])return!1}return!1}async function De(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await ho();!n||!go(n,t)||(o.blank(),o.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(o.detail("Your project content is fetched fresh either way, so you're not missing any"),o.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),o.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),o.blank())}import{createHash as yo}from"crypto";import{hostname as Ut,userInfo as ko,platform as jt,arch as Ft}from"os";var wo="https://klaudius.dev",Eo="/api/licenses/validate",Ao="0.22.
|
|
15
|
+
`,"utf-8")}function vt(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function pe(e,t=e){let n=await oo(e,{withFileTypes:!0}),i=[];for(let s of n){let a=Nt(e,s.name);s.isDirectory()?i.push(...await pe(a,t)):s.isFile()&&i.push(io(t,a).split(so).join("/"))}return i}async function $t(e){let t=await pe(e),n={};for(let i of t)Ne.has(i)||(n[i]=await ue(Nt(e,i)));return n}import{copyFile as ao,mkdir as Lt,mkdtemp as ro,readdir as Mt,rm as Dt}from"fs/promises";import{tmpdir as lo}from"os";import{dirname as co,join as Le}from"path";import{Readable as uo}from"stream";import*as Ht from"tar";var po="https://klaudius.dev/api/template";function fo(e){return uo.fromWeb(e)}async function Me(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??po,n="0.22.2",i;try{i=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:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${T(c)}`)}if(!i.ok){let c="";try{let u=await i.json();c=u.reason?` (${u.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${i.status}${c}`)}if(!i.body)throw new Error("Template download succeeded but response had no body");let s=i.headers.get("x-klaudius-tier"),a=await ro(Le(lo(),"klaudius-template-")),l=0;try{try{await new Promise((m,r)=>{let E=Ht.extract({cwd:a,strict:!0});E.on("finish",m),E.on("error",r),fo(i.body).on("error",r).pipe(E)})}catch(m){throw new Error(`Failed to extract template archive: ${m.message}`)}await Lt(e.destDir,{recursive:!0});let c=new Set(await Mt(e.destDir)),u=await pe(a);try{for(let m of u){let r=Le(e.destDir,m);await Lt(co(r),{recursive:!0}),await ao(Le(a,m),r),l++}}catch(m){let r=await Mt(e.destDir).catch(()=>[]);for(let E of r)c.has(E)||await Dt(Le(e.destDir,E),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${m.message}`)}}finally{await Dt(a,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:s}}import te from"picocolors";var o={info:e=>console.log(te.cyan("\u2139"),e),success:e=>console.log(te.green("\u2713"),e),warn:e=>console.log(te.yellow("\u26A0"),e),error:e=>console.error(te.red("\u2717"),e),step:e=>console.log(te.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
16
|
+
`+te.bold(te.cyan(e))),detail:e=>console.log(te.dim(" "+e))};var mo="https://registry.npmjs.org/klaudius/latest";async function ho(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(mo,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let s=await i.json();return typeof s.version=="string"?s.version:null}catch{return null}finally{clearTimeout(n)}}function go(e,t){let n=a=>a.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),i=n(e),s=n(t);if(i.length<3||s.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(i[a])||Number.isNaN(s[a]))return!1;if(i[a]>s[a])return!0;if(i[a]<s[a])return!1}return!1}async function De(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await ho();!n||!go(n,t)||(o.blank(),o.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(o.detail("Your project content is fetched fresh either way, so you're not missing any"),o.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),o.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),o.blank())}import{createHash as yo}from"crypto";import{hostname as Ut,userInfo as ko,platform as jt,arch as Ft}from"os";var wo="https://klaudius.dev",Eo="/api/licenses/validate",Ao="0.22.2";async function Kt(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(),i=(process.env.KLAUDIUS_API_URL??wo).replace(/\/$/,"")+Eo,s=Ae(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:s,hostname:Ut(),os:`${jt()}-${Ft()}`,cli_version:Ao})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${T(c)}). Check your internet connection or try again later.`}}let l;try{l=await a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return l.ok?{ok:!0,tier:l.tier??"core"}:{ok:!1,reason:l.reason??`License rejected (HTTP ${a.status}).`}}function Ae(){let e=[Ut(),ko().username,jt(),Ft()].join("|");return yo("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Po}from"fs/promises";import{join as To}from"path";async function fe(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${T(n)}`}}}async function Gt(e){let t;try{t=await Po(To(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(i){return{ok:!1,message:`Could not read scripts/schema.sql: ${i.message}`}}let n=e.pat.replace(/\s+/g,"");try{let i=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(i.ok)return{ok:!0};let s=await i.text();return s.includes("already exists")||s.includes('relation "clients" already exists')||s.includes("duplicate")?(o.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${i.status}): ${s.slice(0,300)}`}}catch(i){return{ok:!1,message:`Schema apply failed: ${i.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 n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${T(t)}`}}}var Vt="https://api.cloudflare.com/client/v4";function Yt(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Ue(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let s=await fetch(`${Vt}/user/tokens/verify`,{headers:i});if(s.status===401||s.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await s.json(),l=a.result?.status;if(a.success===!1||l&&l!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${l?` (status: ${l})`:""}. ${Yt(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${T(s)}`}}try{let s=await fetch(`${Vt}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:i});if(s.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (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(s.status===404)return{ok:!1,message:`Account ${n} 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(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await s.json();return a.success===!1?{ok:!1,message:Yt(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${T(s)}`}}}var Bt="https://api.netlify.com/api/v1";async function je(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${Bt}/user`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} verifying the token. Try again or check netlifystatus.com.`}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${T(i)}`}}try{let i=await fetch(`${Bt}/accounts`,{headers:n});if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} listing your teams. Try again or check netlifystatus.com.`};let s=await i.json(),a=Array.isArray(s)?s:[];if(a.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let l=typeof a[0]?.slug=="string"?a[0].slug:void 0;return{ok:!0,accountCount:a.length,accountSlug:l}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${T(i)}`}}}async function me(e){let t=ht(e);if(t)return{ok:!1,message:t};let n=Z(e),i=n.value,s=a=>{let l=[a],c=gt(e);return c&&l.push(c),n.repairs.length>0&&l.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),l.join(`
|
|
17
17
|
`)};try{let a=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":i,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(a.ok)return{ok:!0};if(a.status===429)return{ok:!0};let l={};try{l=await a.json()}catch{}let c=l.error?.message??"",u=l.error?.status??"";return a.status===400&&(u==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(c))?{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."}:a.status===401||a.status===403?{ok:!1,message:s(c||`Google rejected the key (HTTP ${a.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`)}:{ok:!1,message:s(`Google API returned HTTP ${a.status}${c?`: ${c}`:""}.`)}}catch(a){return{ok:!1,message:`Could not reach Google: ${T(a)}`}}}import bo from"nodemailer";import{ImapFlow as So}from"imapflow";function Wt(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let i=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return i.includes("invalid credentials")||i.includes("authentication failed")||i.includes("auth failed")||i.includes("login failed")||i.includes("invalid login")?"auth":i.includes("etimedout")||i.includes("timeout")||i.includes("enotfound")||i.includes("getaddrinfo")||i.includes("econnrefused")||i.includes("econnreset")?"network":"other"}async function ne(e){let t=bo.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(i){return{ok:!1,failedAt:"smtp",message:zt(i,"SMTP",e.usesAccountPassword),failureKind:Wt(i)}}finally{t.close()}let n=new So({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await n.connect(),await n.logout()}catch(i){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:zt(i,"IMAP",e.usesAccountPassword),failureKind:Wt(i)}}return{ok:!0}}function zt(e,t,n){let i=e instanceof Error?e.message:String(e),s=i.toLowerCase();return s.includes("invalid credentials")||s.includes("authentication failed")||s.includes("auth failed")||s.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
|
|
18
18
|
\u2022 The mailbox password is wrong or mistyped.
|
|
19
19
|
\u2022 The email address doesn't match this mailbox's login.
|
|
@@ -24,7 +24,7 @@ Please share that file so we can trace what happened.`);return i}var qe="claude-
|
|
|
24
24
|
\u2022 2FA is required but no app-specific password was generated.`:s.includes("etimedout")||s.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:s.includes("enotfound")||s.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${i}`}async function qt(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`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let i=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(i.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!i.ok)return{ok:!1,message:`Twilio API returned HTTP ${i.status}. Try again or check status.twilio.com.`};let s=await i.json();return s.status&&s.status!=="active"?{ok:!1,message:`Twilio account is in '${s.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:s.friendly_name}}catch(i){return{ok:!1,message:`Could not reach Twilio: ${T(i)}`}}}import{spawn as _o}from"child_process";async function Jt(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,i=await Io(n);if(i.code===0)return{ok:!0};let s=i.stderr.toLowerCase();return s.includes("can't get application")||s.includes("isn't running")||s.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."}:s.includes("(-1728)")||s.includes("not found")||s.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.`}:s.includes("(-1719)")||s.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${i.stderr.trim()||`exit code ${i.code}`}`}}function Io(e){return new Promise(t=>{let n=_o("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),i="";n.stderr.on("data",s=>{i+=s.toString()}),n.on("close",s=>t({code:s??1,stderr:i})),n.on("error",s=>t({code:1,stderr:s.message}))})}import{spawn as Ze}from"child_process";function Co(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var he=2,Xt=2e3,Ro=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Qt(e,t){let n=e+`
|
|
25
25
|
`+t;return Ro.some(i=>i.test(n))}function Zt(e){return new Promise(t=>setTimeout(t,e))}function xo(e,t,n){return new Promise(i=>{let s=n.shell?Ze([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):Ze(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),a="",l="";s.stdout?.on("data",c=>{let u=c.toString();a+=u,process.stdout.write(u)}),s.stderr?.on("data",c=>{let u=c.toString();l+=u,process.stderr.write(u)}),s.on("close",c=>i({code:c??1,stdout:a,stderr:l})),s.on("error",c=>i({code:1,stdout:a,stderr:l+c.message}))})}async function Qe(e,t,n){let i={code:0,stdout:"",stderr:""};for(let s=0;s<=he;s++){if(i=await xo(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!Qt(i.stderr,i.stdout))return i;s<he&&(o.detail(`${n.label} failed with a transient network error \u2014 retrying (${s+2}/${he+1})\u2026`),await Zt(Xt))}return i}function Oo(e,t,n){return new Promise(i=>{let s=Ze(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";s.stdout?.on("data",c=>{a+=c.toString()}),s.stderr?.on("data",c=>{l+=c.toString()}),s.on("close",c=>i({code:c??1,stdout:a,stderr:l})),s.on("error",c=>i({code:1,stdout:a,stderr:l+c.message}))})}var vo=[{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. Re-run with `npx klaudius@latest init` (pulls the latest) \u2014 that should bypass the source build."}];function No(e){let t=`${e.stderr??""}
|
|
26
26
|
${e.stdout??""}`;return vo.find(i=>i.pattern.test(t))?.hint}async function $o(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],s=(await B())?.command??["python3"],a=async c=>{let u={code:0,stdout:"",stderr:""};for(let m=0;m<=he;m++){if(u=await Oo(s[0],[...s.slice(1),...c],{cwd:e}),u.code===0||!Qt(u.stderr,u.stdout))return u;m<he&&(o.detail(`pip install hit a transient network error \u2014 retrying (${m+2}/${he+1})\u2026`),await Zt(Xt))}return u},l=await a([...n,"--break-system-packages",...t]);return l.code!==0&&/no such option:.*break-system-packages/i.test(l.stderr)&&(o.detail("Older pip detected; retrying without --break-system-packages"),l=await a([...n,...t])),l.code!==0&&(l.stderr.trim()&&process.stderr.write(l.stderr),l.stdout.trim()&&process.stdout.write(l.stdout)),l}async function Fe(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=Co(),i=process.platform==="win32",s=(m,r)=>{let E=No(r);E&&((t.hints??={})[m]=E)};o.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await Qe("npm",["install"],{cwd:e,label:"npm install",env:n,shell:i});t.npm=a.code===0?"ok":"failed",a.code!==0&&s("npm",a),o.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await $o(e);t.pip=l.code===0?"ok":"failed",l.code!==0&&s("pip",l),o.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Qe("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:i});t.playwright=c.code===0?"ok":"failed",c.code!==0&&s("playwright",c),o.step("Installing Patchright browser (chromium ~200MB; one-time)...");let u=await Qe("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:i});return t.patchright=u.code===0?"ok":"failed",u.code!==0&&s("patchright",u),t}import{mkdir as Lo,readFile as Mo,writeFile as Do}from"fs/promises";import{join as en}from"path";async function Ke(e,t){let n=en(e,".claude");await Lo(n,{recursive:!0});let i=en(n,"settings.json"),s={};try{let u=await Mo(i,"utf-8"),m=JSON.parse(u);m&&typeof m=="object"&&!Array.isArray(m)&&(s=m)}catch{}let a=s.enabledMcpjsonServers,l=Array.isArray(a)?a.filter(u=>typeof u=="string"):[];l.includes(t)||l.push(t);let c={...s,enabledMcpjsonServers:l};await Do(i,JSON.stringify(c,null,2)+`
|
|
27
|
-
`,"utf-8")}var nn="0.22.
|
|
27
|
+
`,"utf-8")}var nn="0.22.2",S=5;function re(e){return`npx klaudius@latest init ${Ge(ge(e))}`}function ge(e){if(process.platform==="win32")return e;let t=Ho();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Ko(e){let t=[];try{let i=(await sn(e,{withFileTypes:!0})).filter(s=>s.isDirectory()&&!s.name.startsWith(".")).slice(0,200);for(let s of i){let a=G(e,s.name);if(!await on(G(a,".env")))continue;let l=await on(G(a,".klaudius","manifest.json"));if(t.push({path:a,finished:l}),t.length>=3)break}}catch{}return t}async function on(e){try{return await nt(e),!0}catch{return!1}}function Ge(e){return/\s/.test(e)?`"${e}"`:e}function oe(e,t,n){o.blank(),o.error(`${t} validation failed ${S} times in a row. Pausing setup so you don't get stuck in a loop.`),o.detail(`Last error: ${n}`),o.blank(),o.detail("Your credentials are saved in `.env`. Two ways forward:"),o.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),o.blank(),console.log(` ${d.cyan(re(e))}`),o.blank(),o.detail(` (Your .env is at ${ge(G(e,".env"))} \u2014 open it in any text editor.)`),o.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),o.blank(),process.exit(1)}async function an(e){let t=e.target??".",n=jo(t)?t:Uo(process.cwd(),t),i=Bo(n);i&&(o.error("Klaudius can't be installed inside a protected system folder."),o.detail(`Path: ${n}`),o.detail(`Reason: ${i}`),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@latest init my-agency")}`)):(o.detail("For example:"),console.log(` ${d.cyan("cd ~/Documents")}`),console.log(` ${d.cyan("npx klaudius@latest init my-agency")}`)),o.blank(),process.exit(1)),process.platform==="win32"&&Wo()&&(o.warn("You appear to be running in an elevated (Administrator) PowerShell."),o.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),o.blank()),await De("init",nn);let s=await Go(n);if(s.kind==="scaffolded"){o.blank(),o.warn(`Found an existing Klaudius project at ${d.bold(n)}.`),o.detail("(Your .env and project files are in place.)"),o.blank(),s.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(),n!==process.cwd()&&console.log(` ${d.cyan(`cd ${Ge(t)}`)}`),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retries npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${d.cyan("npx klaudius@latest 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@latest doctor")} ${d.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${d.cyan("npx klaudius@latest configure")} ${d.dim("# change a credential / API key")}`),console.log(` ${d.cyan("npx klaudius@latest 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@latest init`."),o.blank();return}if(s.kind==="occupied"){let p=t===".",h=await Ko(n);if(h.length>0){o.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),o.detail(`You're in: ${ge(n)}`),o.blank();for(let f of h)o.detail(f.finished?`Found a finished project at ${ge(f.path)}. To work in it:`:`Found an unfinished setup at ${ge(f.path)}. To pick up where it left off:`),o.blank(),f.finished?(console.log(` ${d.cyan(`cd ${ge(f.path)}`)}`),console.log(` ${d.cyan("claude")} ${d.dim("# open Claude Code in the project")}`)):console.log(` ${d.cyan(re(f.path))} ${d.dim("# then pick Resume")}`),o.blank();process.exit(1)}o.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),o.detail(`Path: ${n}`),o.detail(`Contains: ${s.entries.slice(0,5).join(", ")}${s.entries.length>5?`, \u2026 (+${s.entries.length-5} more)`:""}`),o.blank(),p?(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@latest 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@latest 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@latest init ${t}-2`)}`),o.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await Yo(e.license),l=w.spinner();l.start("Validating license");let c=await Kt(a);c.ok||(l.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)),l.stop(`License valid (${c.tier??"core"} tier)`);let u=await de();u.ok||(o.error(u.message??"Python version check failed."),o.blank(),o.detail(`Once you've installed Python 3.10+, re-run the same command: ${re(n)}`),process.exit(1));let m=ee();m.ok||(o.error(m.message??"Node.js version check failed."),o.blank(),o.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${re(n)}`),process.exit(1));let r,E=!1;if(s.kind==="partial")if(await Vo(n)==="resume"){let h=await tn(s.envPath,"utf-8"),f=Xe(H(h));f?(o.success("Resuming with values from your existing .env"),o.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),r=f,E=!0):(o.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await I())}else{let h=await tn(s.envPath,"utf-8"),f=Xe(H(h));r=await I(f??{})}else r=await I();r.licenseKey=a,await R(n,r),E||(o.success("Saved .env"),o.success(r.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),o.blank();for(let p=1;;p++){let h=w.spinner();h.start("Validating Supabase credentials");let f=await fe({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(f.ok){h.stop("Supabase credentials accepted");break}h.stop(f.message??"Supabase check failed",2),p>=S&&oe(n,"Supabase",f.message??"Supabase check failed");let A=f.message??"Supabase check failed";o.blank(),o.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${p+1} of ${S})`),o.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await I(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
28
28
|
${A}
|
|
29
29
|
|
|
30
30
|
Re-enter the URL, secret key, or PAT below. Press Enter on any
|
|
@@ -81,10 +81,12 @@ ${z}
|
|
|
81
81
|
Re-enter the bot token or chat_id below.
|
|
82
82
|
Press Enter on any field to keep its current value.`}),await R(n,r),(r.notifyChannel??"telegram")!=="telegram"||!r.telegramBotToken||!r.telegramChatId)){o.success("Skipped Telegram. Setup will continue."),h=!0;break}}}o.blank();let k=w.spinner();k.start("Downloading Klaudius template");let b;try{b=(await Me({licenseKey:a,machineId:Ae(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:r.aiAgent,destDir:n})).filesExtracted,k.stop(`Downloaded ${b} files into ${d.bold(n)}`)}catch(p){k.stop(p.message,2);let h=r.aiAgent==="codex"?".codex/config.toml":".mcp.json";o.detail(`Your .env / ${h} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await tt(G(n,"clients"),{recursive:!0});let j=await $t(n);await $e(n,vt(nn,j)),o.success("Wrote .klaudius/manifest.json");let N=!1,ie="";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: ${r.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+r.supabaseProjectRef+"/sql/new").replace(r.supabaseProjectRef+".supabase.co","")}`);else{o.blank();let p=w.spinner();p.start("Applying schema to Supabase");let h=await Gt({projectRoot:n,pat:r.supabasePat,projectRef:r.supabaseProjectRef});h.ok?p.stop("Schema applied (or already present)"):(p.stop(h.message??"Schema apply failed",2),N=!0,ie=`https://supabase.com/dashboard/project/${r.supabaseProjectRef}/sql/new`)}let P=[],F={};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 p=await Fe(n);o.detail(`npm: ${p.npm}, pip: ${p.pip}, playwright: ${p.playwright}, patchright: ${p.patchright}`),p.npm==="failed"&&P.push("npm"),p.pip==="failed"&&P.push("pip"),p.playwright==="failed"&&P.push("playwright"),p.patchright==="failed"&&P.push("patchright"),F=p.hints??{}}let O=r.outreachEnabled&&r.outreachPriority?.includes("whatsapp")&&(r.whatsappAccounts?.length??0)>0,g=!e.skipInstall&&!P.includes("npm");if(O&&g){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
|
|
83
83
|
phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
|
|
84
|
-
Link a Device, and point it at the QR shown in this terminal.`)),o.blank();for(let p of r.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${p}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${p})`));let h=ot(process.execPath,["scripts/whatsapp.mjs","pair","--account",p],{cwd:n,stdio:"inherit"});h.status===0?o.detail(`Paired '${p}'.`):(console.log(d.yellow(`'${p}' did not pair (exit ${h.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))),o.blank()}}else if(O&&!g){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@latest install` completes successfully, pair via:"));for(let p of r.whatsappAccounts)console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))}let L=r.emailAuth==="oauth-microsoft"&&r.outreachEnabled&&r.outreachChannels?.includes("email"),Y=!e.skipInstall&&!P.includes("pip"),we=p=>{console.log(d.dim("Connect it any time from the project folder with:")),console.log(d.cyan(` ${p?p.command.join(" "):"python3"} scripts/ms_oauth.py login`))};if(L&&Y){o.blank(),o.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(d.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
|
|
85
|
-
password.
|
|
86
|
-
|
|
87
|
-
`:"",h=r.aiAgent==="codex"?"codex":"claude",f=r.aiAgent==="codex"?"Codex":"Claude Code",A=r.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";P.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),o.blank(),p&&process.stdout.write(p),console.log(` ${d.cyan(h)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${P.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),o.blank(),console.log(d.dim(` (Don't have ${f} yet? Install with: \`${A}\`)`)),o.blank(),console.log(d.dim("Or do it yourself:")),o.blank(),p&&process.stdout.write(p),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify everything")}`),o.blank()),N&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(ie)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),o.blank()),P.includes("pip")&&!F.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 ${zo()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),o.blank());let C=["npm","playwright","patchright"].filter(M=>P.includes(M)&&!F[M]);if(C.length>0){let M=C.length===1?"keeps":"keep";console.log(d.dim(`If ${C.join(" / ")} ${M} 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@latest install`.")),o.blank()}y&&(console.log(d.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${f}`)),console.log(d.dim("to finish setting it up \u2014 your email details are saved in .env.")),o.blank()),console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),o.blank();return}if(qo(r,n,e.target),y){let p=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(d.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(d.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(d.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(d.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(d.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(d.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(d.cyan(' and send a test email to my own address to confirm."')),r.outreachEnabled&&(r.outreachChannels??[]).length>0&&(o.blank(),console.log(d.yellow(`Note: your other channel(s) \u2014 ${(r.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),o.blank()}}async function R(e,t){await tt(e,{recursive:!0}),await et(G(e,".env"),xe(t),"utf-8"),t.aiAgent==="codex"?(await tt(G(e,".codex"),{recursive:!0}),await et(G(e,".codex","config.toml"),ve(t),"utf-8")):(await et(G(e,".mcp.json"),Oe(t),"utf-8"),await Ke(e,"supabase"))}async function Go(e){try{(await nt(e)).isDirectory()||(o.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await sn(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),s=n.every(c=>i.has(c)),a=n.includes(".env"),l=t.includes(".klaudius");if(s&&a&&!l)return{kind:"partial",envPath:G(e,".env")};if(l&&a){let c=!0;try{c=!(await nt(G(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function Vo(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 w.select({message:`How would you like to proceed? ${d.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,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 w.isCancel(t)&&(w.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Yo(e){if(e&&e.trim().length>0)return e;w.intro("Klaudius");let t=await w.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return w.isCancel(t)&&(w.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Bo(e){let t=Fo(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let i of n)if(t.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function Wo(){if(process.platform!=="win32")return!1;try{return ot("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function zo(){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 qo(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",s=e.aiAgent==="codex"?"Codex":"Claude Code";if(w.outro(d.green(d.bold("Project ready."))),console.log(d.bold("Next steps:")),o.blank(),t!==process.cwd()&&n){let a=`cd ${Ge(n)}`;console.log(` ${d.cyan(a)}${" ".repeat(Math.max(1,27-a.length))}${d.dim("# go into your project folder")}`)}console.log(` ${d.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${d.dim(`# opens ${s} in this project`)}`),o.blank(),console.log(d.bold(`Some starter prompts for ${s}:`)),o.blank(),console.log(` ${d.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${d.cyan(`I know I'm ready to start using Klaudius."`)}`),o.blank(),console.log(` ${d.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),o.blank(),console.log(` ${d.cyan('"Run the pipeline for one client."')}`),console.log(d.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),o.blank(),e.aiAgent!=="codex"&&(console.log(d.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(d.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),o.blank())}import{access as Jo,readFile as Xo}from"fs/promises";import{join as it,resolve as Qo}from"path";import $ from"picocolors";async function ln(e){let t=e.target?Qo(process.cwd(),e.target):process.cwd(),n=await rn(it(t,".env")),i=await rn(it(t,"package.json"));(!n||!i)&&(o.error("This doesn't look like a Klaudius project."),o.detail(`Path: ${t}`),n||o.detail("Missing: .env"),i||o.detail("Missing: package.json"),o.blank(),o.detail("Run `npx klaudius@latest 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 s="claude-code";try{H(await Xo(it(t,".env"),"utf-8")).AI_AGENT==="codex"&&(s="codex")}catch{}o.heading("Installing dependencies");let a=await Fe(t);o.blank(),o.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let l=[];if(a.npm==="failed"&&l.push("npm"),a.pip==="failed"&&l.push("pip"),a.playwright==="failed"&&l.push("playwright"),a.patchright==="failed"&&l.push("patchright"),l.length===0){o.blank(),console.log($.green($.bold("All dependencies installed."))),console.log($.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),o.blank();return}o.blank(),console.log($.yellow($.bold(`${l.join(", ")} still failing.`))),o.blank();for(let[r,E]of Object.entries(a.hints??{}))console.log($.yellow(`Likely cause of ${r} failure:`)),console.log($.dim(` ${E}`)),o.blank();let c=s==="codex"?"codex":"claude",u=s==="codex"?"Codex":"Claude Code",m=s==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log($.dim("Options:")),console.log($.dim(` \u2022 Open ${u} in this folder (\`${c}\`) and paste:`)),console.log($.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log($.dim(` (Don't have ${u} yet? Install with: \`${m}\`)`)),console.log($.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log($.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),o.blank(),process.exitCode=1}async function rn(e){try{return await Jo(e),!0}catch{return!1}}import{readFile as Zo,writeFile as st,access as ei}from"fs/promises";import{join as ye}from"path";import*as W from"@clack/prompts";import q from"picocolors";import{mkdir as ti}from"fs/promises";import{spawnSync as cn}from"child_process";async function dn(e){let t=e.projectRoot??process.cwd(),n=ye(t,".env"),i=ye(t,".mcp.json"),s=ye(t,".codex","config.toml"),a=await at(ye(t,".klaudius","manifest.json")),l=await at(n);!a&&!l&&(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ee();c.ok||(o.error(c.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let u={};try{let k=await Zo(n,"utf-8");u=H(k)}catch{o.warn("No .env found. Starting from an empty configuration.")}let m=Ct(u);Object.keys(u).length>0&&(m.pipelineModes??=["classic"]),W.intro("Reconfigure Klaudius"),o.detail("Press Enter on any prompt to keep its current value."),o.blank();let r=await I(m),E=m.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==E&&(o.error(`Switching AI coding agent (${E} \u2192 ${r.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(` ${q.cyan("npx klaudius@latest init <new-folder>")} ${q.dim("# pick the new agent in the wizard")}`),o.blank(),o.detail(".env is unchanged."),process.exit(1)),r.supabaseUrl!==u.SUPABASE_URL||r.supabaseServiceKey!==u.SUPABASE_SERVICE_KEY){o.heading("Re-validating Supabase credentials");let k=await fe({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});k.ok||(o.error(k.message??"Supabase check failed"),o.warn("Aborting. .env not modified."),process.exit(1)),o.success("Supabase credentials accepted")}let y=Z(r.googlePlacesApiKey??"");if(y.changed&&r.googlePlacesApiKey){o.heading("Checking your Google Places API key");let k=await me(r.googlePlacesApiKey);if(k.ok){if(y.repairs.length>0){o.warn("Corrected look-alike characters in your Google Places API key:");for(let b of y.repairs)o.detail(` ${b}`);o.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=y.value,o.success("Google accepted the key \u2014 writing the corrected value to .env")}else o.error(k.message??"Google rejected the Google Places API key"),o.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),o.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(ni(r,u)){let k=W.spinner();k.start("Validating email credentials (SMTP + IMAP)");let b=r.emailProvider&&r.emailProvider!=="custom"?r.emailProvider:ce(r.emailSmtpHost),j=await ne({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort,usesAccountPassword:b?K[b].usesAccountPassword:void 0});j.ok?k.stop("Email credentials accepted (SMTP + IMAP)"):(k.stop(j.message??"Email check failed",2),o.warn("Writing the email settings exactly as you entered them \u2014 not verified."),o.detail(j.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await st(n,xe(r),"utf-8"),o.success("Updated .env"),r.aiAgent==="codex"?(await ti(ye(t,".codex"),{recursive:!0}),await st(s,ve(r),"utf-8"),o.success("Updated .codex/config.toml")):(await st(i,Oe(r),"utf-8"),o.success("Updated .mcp.json"),await Ke(t,"supabase")),r.emailAuth==="oauth-microsoft"&&r.outreachEnabled&&r.outreachChannels?.includes("email")){let k=await B();if(!(k!==null&&cn(k.command[0],[...k.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(o.blank(),!k)o.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),o.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let j=await W.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});W.isCancel(j)||!j?o.detail(`Skipped. Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`):cn(k.command[0],[...k.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit"}).status===0?o.success("Outlook mailbox connected."):(o.warn("The Microsoft sign-in didn't complete."),o.detail(`Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`))}}o.blank(),W.outro(q.green("Configuration updated.")),await oi(t,a)}function ni(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([i])=>i===void 0||i==="")?!1:n.some(([i,s])=>String(i)!==(t[s]??""))}async function oi(e,t){let n=await at(ye(e,"node_modules"));o.blank(),t?n||(o.detail("Your project files are in place but dependencies aren't installed yet."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${q.cyan("npx klaudius@latest install")} ${q.dim("# (re-)installs npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${q.cyan("npx klaudius@latest doctor")} ${q.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(` ${q.cyan("npx klaudius@latest init")} ${q.dim("# pick Resume when prompted")}`),o.blank())}async function at(e){try{return await ei(e),!0}catch{return!1}}import{copyFile as un,mkdir as pn,readFile as ii,rm as Pe,writeFile as fn,access as mn}from"fs/promises";import{dirname as hn,join as U}from"path";import{tmpdir as si}from"os";import*as ke from"@clack/prompts";import rt from"picocolors";var Ve="0.22.0";async function gn(e){let t=e.projectRoot??process.cwd(),n=await Ot(t);n||(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let g of Ne)delete n.files[g];let i,s=U(t,".env"),a,l;try{a=await ii(s,"utf-8"),l=H(a)}catch{o.error("Couldn't read .env from this directory."),o.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=l.KLAUDIUS_LICENSE_KEY??"",i||(o.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),o.detail("This file is created by `npx klaudius@latest init`. If your project predates"),o.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),o.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=It(a,l,_t);c!==null&&(await fn(s,c,"utf-8"),o.detail("Backfilled new env keys")),await De("update",Ve),ke.intro(`Update from ${n.templateVersion} \u2192 ${Ve}`);let m=l.AI_AGENT==="codex"?"codex":"claude-code",r=U(si(),`klaudius-update-${process.pid}-${Date.now()}`),E;try{o.heading("Downloading the latest Klaudius template");let g=await Me({licenseKey:i,machineId:Ae(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:m,destDir:r});o.success(`Fetched ${g.filesExtracted} canonical files`),E=r}catch(g){o.error(g.message),o.detail("Update aborted. Your project is unchanged."),await Pe(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let y=await ai(E,t,n),k=y.filter(g=>g.state==="new"),b=y.filter(g=>g.state==="clean-update"),j=y.filter(g=>g.state==="user-only"),N=y.filter(g=>g.state==="conflict"),ie=y.filter(g=>g.state==="no-change"),P=y.filter(g=>g.state==="removed-clean"),F=y.filter(g=>g.state==="removed-modified"),O=[...N,...F];if(o.blank(),o.heading("Change summary"),o.detail(`${J(ie.length,"file")} unchanged`),o.detail(`${J(k.length,"new file")}`),o.detail(`${J(b.length,"file")} updated cleanly (no local edits)`),o.detail(`${J(j.length,"file")} you've edited (no upstream change \u2014 left alone)`),o.detail(`${J(P.length,"file")} removed upstream (deleted cleanly)`),o.detail(`${J(N.length,"file")} with conflicts (you edited AND we have a new version)`),o.detail(`${J(F.length,"file")} removed upstream but edited locally (need your decision)`),k.length===0&&b.length===0&&P.length===0&&O.length===0){o.blank(),ke.outro(rt.green("Already up to date.")),await Pe(r,{recursive:!0,force:!0}).catch(()=>{});return}o.blank(),o.heading("Applying clean updates");for(let g of[...k,...b]){let L=U(E,g.path),Y=U(t,g.path);await pn(hn(Y),{recursive:!0}),await un(L,Y),n.files[g.path]=g.canonicalHash}k.length+b.length>0&&o.success(`Wrote ${J(k.length+b.length,"file")}`);for(let g of P){let L=U(t,g.path);await Pe(L,{force:!0}),delete n.files[g.path]}if(P.length>0&&o.success(`Deleted ${J(P.length,"file")} removed upstream`),O.length>0){o.blank(),o.heading(`${O.length} conflict(s) need resolution`);let g=U(t,".klaudius","incoming");try{await Pe(g,{recursive:!0,force:!0})}catch{}for(let L of N){let Y=U(E,L.path),we=U(g,L.path);await pn(hn(we),{recursive:!0}),await un(Y,we)}await fn(U(t,".klaudius","conflicts.md"),ri(O,n.templateVersion,Ve),"utf-8"),N.length>0&&o.detail("Staged canonical versions to .klaudius/incoming/"),o.detail("Wrote conflict report to .klaudius/conflicts.md")}if(n.updatedAt=new Date().toISOString(),O.length===0&&(n.templateVersion=Ve),await $e(t,n),o.blank(),O.length===0)ke.outro(rt.green("Update complete."));else{let g=m==="codex"?"Codex":"Claude Code";ke.outro(rt.yellow(`${O.length} conflict(s) staged. Open ${g} in this project and ask:
|
|
84
|
+
Link a Device, and point it at the QR shown in this terminal.`)),o.blank();for(let p of r.whatsappAccounts){console.log(d.cyan(`Pairing WhatsApp account '${p}'...`)),console.log(d.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${p})`));let h=ot(process.execPath,["scripts/whatsapp.mjs","pair","--account",p],{cwd:n,stdio:"inherit"});h.status===0?o.detail(`Paired '${p}'.`):(console.log(d.yellow(`'${p}' did not pair (exit ${h.status??"signalled"}). You can finish later via:`)),console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))),o.blank()}}else if(O&&!g){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@latest install` completes successfully, pair via:"));for(let p of r.whatsappAccounts)console.log(d.cyan(` npx klaudius@latest pair-whatsapp --label ${p}`))}let L=r.emailAuth==="oauth-microsoft"&&r.outreachEnabled&&r.outreachChannels?.includes("email"),Y=!e.skipInstall&&!P.includes("pip"),we=p=>{console.log(d.dim("Connect it any time from the project folder with:")),console.log(d.cyan(` ${p?p.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(d.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(L&&Y){o.blank(),o.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(d.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
|
|
85
|
+
password. Your browser will open to Microsoft's sign-in page \u2014
|
|
86
|
+
sign in as `+(r.emailAddress??"your outreach mailbox")+` and approve.
|
|
87
|
+
(No browser on this machine? It falls back to a short code you can
|
|
88
|
+
enter from any device.)`)),o.blank();let p=await B();if(p){let[h,...f]=p.command,A=ot(h,[...f,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});A.status===0?o.success("Outlook mailbox connected."):(o.blank(),console.log(d.yellow(`The Microsoft sign-in didn't complete (exit ${A.status??"signalled"}). Setup continues without it.`)),we(p))}else console.log(d.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),we(null)}else L&&!Y&&(o.blank(),console.log(d.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(d.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(d.cyan(" python3 scripts/ms_oauth.py login")));o.blank();let ct=[...P,...N?["schema"]:[]];if(ct.length>0){w.outro(d.yellow(d.bold(`Setup paused \u2014 ${ct.join(", ")} failed.`))),console.log(d.dim("Your credentials and project files are all saved.")),o.blank();for(let[M,Te]of Object.entries(F))console.log(d.yellow(`Likely cause of ${M} failure:`)),console.log(d.dim(` ${Te}`)),o.blank();let p=n!==process.cwd()&&e.target?` ${d.cyan(`cd ${Ge(e.target)}`)}
|
|
89
|
+
`:"",h=r.aiAgent==="codex"?"codex":"claude",f=r.aiAgent==="codex"?"Codex":"Claude Code",A=r.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";P.length>0&&(console.log(d.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),o.blank(),p&&process.stdout.write(p),console.log(` ${d.cyan(h)} ${d.dim(`# open ${f} in this folder`)}`),console.log(d.dim(" Then paste:")),console.log(d.cyan(` "Finish my Klaudius install \u2014 ${P.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),o.blank(),console.log(d.dim(` (Don't have ${f} yet? Install with: \`${A}\`)`)),o.blank(),console.log(d.dim("Or do it yourself:")),o.blank(),p&&process.stdout.write(p),console.log(` ${d.cyan("npx klaudius@latest install")} ${d.dim("# retry the failing installers")}`),console.log(` ${d.cyan("npx klaudius@latest doctor")} ${d.dim("# verify everything")}`),o.blank()),N&&(console.log(d.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${d.cyan(ie)}`),console.log(d.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),o.blank()),P.includes("pip")&&!F.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 ${zo()}`)),console.log(d.dim("and open a fresh Terminal before retrying.")),o.blank());let C=["npm","playwright","patchright"].filter(M=>P.includes(M)&&!F[M]);if(C.length>0){let M=C.length===1?"keeps":"keep";console.log(d.dim(`If ${C.join(" / ")} ${M} 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@latest install`.")),o.blank()}y&&(console.log(d.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${f}`)),console.log(d.dim("to finish setting it up \u2014 your email details are saved in .env.")),o.blank()),console.log(d.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),o.blank();return}if(qo(r,n,e.target),y){let p=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(d.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(d.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(d.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(d.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(d.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(d.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(d.cyan(' and send a test email to my own address to confirm."')),r.outreachEnabled&&(r.outreachChannels??[]).length>0&&(o.blank(),console.log(d.yellow(`Note: your other channel(s) \u2014 ${(r.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),o.blank()}}async function R(e,t){await tt(e,{recursive:!0}),await et(G(e,".env"),xe(t),"utf-8"),t.aiAgent==="codex"?(await tt(G(e,".codex"),{recursive:!0}),await et(G(e,".codex","config.toml"),ve(t),"utf-8")):(await et(G(e,".mcp.json"),Oe(t),"utf-8"),await Ke(e,"supabase"))}async function Go(e){try{(await nt(e)).isDirectory()||(o.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await sn(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),s=n.every(c=>i.has(c)),a=n.includes(".env"),l=t.includes(".klaudius");if(s&&a&&!l)return{kind:"partial",envPath:G(e,".env")};if(l&&a){let c=!0;try{c=!(await nt(G(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function Vo(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 w.select({message:`How would you like to proceed? ${d.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,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 w.isCancel(t)&&(w.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Yo(e){if(e&&e.trim().length>0)return e;w.intro("Klaudius");let t=await w.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return w.isCancel(t)&&(w.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Bo(e){let t=Fo(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let i of n)if(t.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function Wo(){if(process.platform!=="win32")return!1;try{return ot("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function zo(){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 qo(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",s=e.aiAgent==="codex"?"Codex":"Claude Code";if(w.outro(d.green(d.bold("Project ready."))),console.log(d.bold("Next steps:")),o.blank(),t!==process.cwd()&&n){let a=`cd ${Ge(n)}`;console.log(` ${d.cyan(a)}${" ".repeat(Math.max(1,27-a.length))}${d.dim("# go into your project folder")}`)}console.log(` ${d.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${d.dim(`# opens ${s} in this project`)}`),o.blank(),console.log(d.bold(`Some starter prompts for ${s}:`)),o.blank(),console.log(` ${d.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${d.cyan(`I know I'm ready to start using Klaudius."`)}`),o.blank(),console.log(` ${d.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),o.blank(),console.log(` ${d.cyan('"Run the pipeline for one client."')}`),console.log(d.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),o.blank(),e.aiAgent!=="codex"&&(console.log(d.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(d.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),o.blank())}import{access as Jo,readFile as Xo}from"fs/promises";import{join as it,resolve as Qo}from"path";import $ from"picocolors";async function ln(e){let t=e.target?Qo(process.cwd(),e.target):process.cwd(),n=await rn(it(t,".env")),i=await rn(it(t,"package.json"));(!n||!i)&&(o.error("This doesn't look like a Klaudius project."),o.detail(`Path: ${t}`),n||o.detail("Missing: .env"),i||o.detail("Missing: package.json"),o.blank(),o.detail("Run `npx klaudius@latest 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 s="claude-code";try{H(await Xo(it(t,".env"),"utf-8")).AI_AGENT==="codex"&&(s="codex")}catch{}o.heading("Installing dependencies");let a=await Fe(t);o.blank(),o.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let l=[];if(a.npm==="failed"&&l.push("npm"),a.pip==="failed"&&l.push("pip"),a.playwright==="failed"&&l.push("playwright"),a.patchright==="failed"&&l.push("patchright"),l.length===0){o.blank(),console.log($.green($.bold("All dependencies installed."))),console.log($.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),o.blank();return}o.blank(),console.log($.yellow($.bold(`${l.join(", ")} still failing.`))),o.blank();for(let[r,E]of Object.entries(a.hints??{}))console.log($.yellow(`Likely cause of ${r} failure:`)),console.log($.dim(` ${E}`)),o.blank();let c=s==="codex"?"codex":"claude",u=s==="codex"?"Codex":"Claude Code",m=s==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log($.dim("Options:")),console.log($.dim(` \u2022 Open ${u} in this folder (\`${c}\`) and paste:`)),console.log($.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log($.dim(` (Don't have ${u} yet? Install with: \`${m}\`)`)),console.log($.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log($.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),o.blank(),process.exitCode=1}async function rn(e){try{return await Jo(e),!0}catch{return!1}}import{readFile as Zo,writeFile as st,access as ei}from"fs/promises";import{join as ye}from"path";import*as W from"@clack/prompts";import q from"picocolors";import{mkdir as ti}from"fs/promises";import{spawnSync as cn}from"child_process";async function dn(e){let t=e.projectRoot??process.cwd(),n=ye(t,".env"),i=ye(t,".mcp.json"),s=ye(t,".codex","config.toml"),a=await at(ye(t,".klaudius","manifest.json")),l=await at(n);!a&&!l&&(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ee();c.ok||(o.error(c.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let u={};try{let k=await Zo(n,"utf-8");u=H(k)}catch{o.warn("No .env found. Starting from an empty configuration.")}let m=Ct(u);Object.keys(u).length>0&&(m.pipelineModes??=["classic"]),W.intro("Reconfigure Klaudius"),o.detail("Press Enter on any prompt to keep its current value."),o.blank();let r=await I(m),E=m.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==E&&(o.error(`Switching AI coding agent (${E} \u2192 ${r.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(` ${q.cyan("npx klaudius@latest init <new-folder>")} ${q.dim("# pick the new agent in the wizard")}`),o.blank(),o.detail(".env is unchanged."),process.exit(1)),r.supabaseUrl!==u.SUPABASE_URL||r.supabaseServiceKey!==u.SUPABASE_SERVICE_KEY){o.heading("Re-validating Supabase credentials");let k=await fe({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});k.ok||(o.error(k.message??"Supabase check failed"),o.warn("Aborting. .env not modified."),process.exit(1)),o.success("Supabase credentials accepted")}let y=Z(r.googlePlacesApiKey??"");if(y.changed&&r.googlePlacesApiKey){o.heading("Checking your Google Places API key");let k=await me(r.googlePlacesApiKey);if(k.ok){if(y.repairs.length>0){o.warn("Corrected look-alike characters in your Google Places API key:");for(let b of y.repairs)o.detail(` ${b}`);o.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=y.value,o.success("Google accepted the key \u2014 writing the corrected value to .env")}else o.error(k.message??"Google rejected the Google Places API key"),o.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),o.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(ni(r,u)){let k=W.spinner();k.start("Validating email credentials (SMTP + IMAP)");let b=r.emailProvider&&r.emailProvider!=="custom"?r.emailProvider:ce(r.emailSmtpHost),j=await ne({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort,usesAccountPassword:b?K[b].usesAccountPassword:void 0});j.ok?k.stop("Email credentials accepted (SMTP + IMAP)"):(k.stop(j.message??"Email check failed",2),o.warn("Writing the email settings exactly as you entered them \u2014 not verified."),o.detail(j.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await st(n,xe(r),"utf-8"),o.success("Updated .env"),r.aiAgent==="codex"?(await ti(ye(t,".codex"),{recursive:!0}),await st(s,ve(r),"utf-8"),o.success("Updated .codex/config.toml")):(await st(i,Oe(r),"utf-8"),o.success("Updated .mcp.json"),await Ke(t,"supabase")),r.emailAuth==="oauth-microsoft"&&r.outreachEnabled&&r.outreachChannels?.includes("email")){let k=await B();if(!(k!==null&&cn(k.command[0],[...k.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(o.blank(),!k)o.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),o.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let j=await W.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});W.isCancel(j)||!j?o.detail(`Skipped. Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`):cn(k.command[0],[...k.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?o.success("Outlook mailbox connected."):(o.warn("The Microsoft sign-in didn't complete."),o.detail(`Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`))}}o.blank(),W.outro(q.green("Configuration updated.")),await oi(t,a)}function ni(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([i])=>i===void 0||i==="")?!1:n.some(([i,s])=>String(i)!==(t[s]??""))}async function oi(e,t){let n=await at(ye(e,"node_modules"));o.blank(),t?n||(o.detail("Your project files are in place but dependencies aren't installed yet."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${q.cyan("npx klaudius@latest install")} ${q.dim("# (re-)installs npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${q.cyan("npx klaudius@latest doctor")} ${q.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(` ${q.cyan("npx klaudius@latest init")} ${q.dim("# pick Resume when prompted")}`),o.blank())}async function at(e){try{return await ei(e),!0}catch{return!1}}import{copyFile as un,mkdir as pn,readFile as ii,rm as Pe,writeFile as fn,access as mn}from"fs/promises";import{dirname as hn,join as U}from"path";import{tmpdir as si}from"os";import*as ke from"@clack/prompts";import rt from"picocolors";var Ve="0.22.2";async function gn(e){let t=e.projectRoot??process.cwd(),n=await Ot(t);n||(o.error("This doesn't look like a Klaudius project."),o.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let g of Ne)delete n.files[g];let i,s=U(t,".env"),a,l;try{a=await ii(s,"utf-8"),l=H(a)}catch{o.error("Couldn't read .env from this directory."),o.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=l.KLAUDIUS_LICENSE_KEY??"",i||(o.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),o.detail("This file is created by `npx klaudius@latest init`. If your project predates"),o.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),o.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=It(a,l,_t);c!==null&&(await fn(s,c,"utf-8"),o.detail("Backfilled new env keys")),await De("update",Ve),ke.intro(`Update from ${n.templateVersion} \u2192 ${Ve}`);let m=l.AI_AGENT==="codex"?"codex":"claude-code",r=U(si(),`klaudius-update-${process.pid}-${Date.now()}`),E;try{o.heading("Downloading the latest Klaudius template");let g=await Me({licenseKey:i,machineId:Ae(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:m,destDir:r});o.success(`Fetched ${g.filesExtracted} canonical files`),E=r}catch(g){o.error(g.message),o.detail("Update aborted. Your project is unchanged."),await Pe(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let y=await ai(E,t,n),k=y.filter(g=>g.state==="new"),b=y.filter(g=>g.state==="clean-update"),j=y.filter(g=>g.state==="user-only"),N=y.filter(g=>g.state==="conflict"),ie=y.filter(g=>g.state==="no-change"),P=y.filter(g=>g.state==="removed-clean"),F=y.filter(g=>g.state==="removed-modified"),O=[...N,...F];if(o.blank(),o.heading("Change summary"),o.detail(`${J(ie.length,"file")} unchanged`),o.detail(`${J(k.length,"new file")}`),o.detail(`${J(b.length,"file")} updated cleanly (no local edits)`),o.detail(`${J(j.length,"file")} you've edited (no upstream change \u2014 left alone)`),o.detail(`${J(P.length,"file")} removed upstream (deleted cleanly)`),o.detail(`${J(N.length,"file")} with conflicts (you edited AND we have a new version)`),o.detail(`${J(F.length,"file")} removed upstream but edited locally (need your decision)`),k.length===0&&b.length===0&&P.length===0&&O.length===0){o.blank(),ke.outro(rt.green("Already up to date.")),await Pe(r,{recursive:!0,force:!0}).catch(()=>{});return}o.blank(),o.heading("Applying clean updates");for(let g of[...k,...b]){let L=U(E,g.path),Y=U(t,g.path);await pn(hn(Y),{recursive:!0}),await un(L,Y),n.files[g.path]=g.canonicalHash}k.length+b.length>0&&o.success(`Wrote ${J(k.length+b.length,"file")}`);for(let g of P){let L=U(t,g.path);await Pe(L,{force:!0}),delete n.files[g.path]}if(P.length>0&&o.success(`Deleted ${J(P.length,"file")} removed upstream`),O.length>0){o.blank(),o.heading(`${O.length} conflict(s) need resolution`);let g=U(t,".klaudius","incoming");try{await Pe(g,{recursive:!0,force:!0})}catch{}for(let L of N){let Y=U(E,L.path),we=U(g,L.path);await pn(hn(we),{recursive:!0}),await un(Y,we)}await fn(U(t,".klaudius","conflicts.md"),ri(O,n.templateVersion,Ve),"utf-8"),N.length>0&&o.detail("Staged canonical versions to .klaudius/incoming/"),o.detail("Wrote conflict report to .klaudius/conflicts.md")}if(n.updatedAt=new Date().toISOString(),O.length===0&&(n.templateVersion=Ve),await $e(t,n),o.blank(),O.length===0)ke.outro(rt.green("Update complete."));else{let g=m==="codex"?"Codex":"Claude Code";ke.outro(rt.yellow(`${O.length} conflict(s) staged. Open ${g} in this project and ask:
|
|
88
90
|
"Run /resolve-conflicts"`))}await Pe(r,{recursive:!0,force:!0}).catch(()=>{})}async function ai(e,t,n){let i=await pe(e),s=new Set(i),a=[];for(let l of i){let c=await ue(U(e,l)),u=n.files[l],m=U(t,l),r;try{await mn(m),r=await ue(m)}catch{a.push({path:l,state:"new",canonicalHash:c,manifestHash:u});continue}c===u?r===u?a.push({path:l,state:"no-change",canonicalHash:c,localHash:r,manifestHash:u}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:r,manifestHash:u}):r===u?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:r,manifestHash:u}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:r,manifestHash:u})}for(let l of Object.keys(n.files)){if(s.has(l))continue;let c=n.files[l],u=U(t,l),m;try{await mn(u),m=await ue(u)}catch{delete n.files[l];continue}m===c?a.push({path:l,state:"removed-clean",localHash:m,manifestHash:c}):a.push({path:l,state:"removed-modified",localHash:m,manifestHash:c})}return a}function J(e,t){return`${e} ${t}${e===1?"":"s"}`}function ri(e,t,n){let i=e.filter(c=>c.state==="conflict").length,s=e.filter(c=>c.state==="removed-modified").length,a=[];a.push("# Update Conflicts"),a.push(""),a.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),a.push(`Updating from canonical version **${t}** to **${n}**.`),a.push("");let l=[];i>0&&l.push(`${i} file${i===1?"":"s"} ha${i===1?"s":"ve"} BOTH local edits AND upstream changes`),s>0&&l.push(`${s} file${s===1?"":"s"} ${s===1?"was":"were"} removed upstream but edited locally`),a.push(l.join(", and ")+"."),a.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),a.push(""),a.push("---"),a.push("");for(let c of e)a.push(`## ${c.path}`),a.push(""),c.state==="removed-modified"?(a.push("**Type:** Removed upstream"),a.push(""),a.push(`- Your local copy: \`${c.path}\``),a.push("- This file no longer exists in the canonical template."),a.push("- You've modified it locally since install."),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),a.push("2. Delete \u2014 remove the file from disk and from the manifest")):(a.push("**Type:** Edit conflict"),a.push(""),a.push(`- Your version (with your local edits): \`${c.path}\``),a.push(`- New canonical version: \`.klaudius/incoming/${c.path}\``),a.push(`- Hash at last install/update: \`${(c.manifestHash??"(none)").slice(0,16)}\``),a.push(`- Your local hash now: \`${(c.localHash??"(missing)").slice(0,16)}\``),a.push(`- New canonical hash: \`${(c.canonicalHash??"(none)").slice(0,16)}\``),a.push(""),a.push("**Resolution options for the SKILL to walk through:**"),a.push(""),a.push("1. Keep mine \u2014 discard the new canonical changes"),a.push("2. Take canonical \u2014 overwrite my edits with the new version"),a.push("3. Merge \u2014 review both side-by-side and produce a combined version")),a.push(""),a.push("---"),a.push("");return a.join(`
|
|
89
91
|
`)}import{access as li,readFile as yn,stat as ci}from"fs/promises";import{join as V}from"path";import x from"picocolors";import{spawn as kn,spawnSync as di}from"child_process";async function wn(e){let t=e.projectRoot??process.cwd(),n=[];console.log(x.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
90
92
|
`)),n.push(await ui()),n.push(await pi());let i=V(t,".env"),s=V(t,".klaudius","manifest.json"),a=V(t,".mcp.json"),l=V(t,".codex","config.toml"),c=await X(i),u=await X(s),m="claude-code";if(c)try{H(await yn(i,"utf-8")).AI_AGENT==="codex"&&(m="codex")}catch{}if(m==="claude-code"){let y=await X(V(t,"AGENTS.md")),k=!await X(V(t,".claude"));y&&k&&(m="codex")}if(n.push({name:".env present",status:c?"ok":"fail",detail:c?i:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."}),n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:u?"ok":"fail",detail:u?s:"missing",nextAction:u?void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."}),m==="codex"){let y=await X(l);n.push({name:".codex/config.toml present",status:y?"ok":"warn",detail:y?l:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let y=await X(a);n.push({name:".mcp.json present",status:y?"ok":"warn",detail:y?a:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await Ei(m)),n.push(await fi(t)),n.push(await mi(t)),n.push(await hi()),!c)n.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)n.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let y=await yn(i,"utf-8"),k=H(y);await gi(k,n,t)}console.log();for(let y of n){let k=y.status==="ok"?x.green("\u2713"):y.status==="warn"?x.yellow("\u26A0"):y.status==="skip"?x.dim("\xB7"):x.red("\u2717");console.log(` ${k} ${y.name}${y.detail?x.dim(` \u2014 ${y.detail}`):""}`),y.nextAction&&console.log(` ${x.dim("\u2192")} ${x.cyan(y.nextAction)}`)}let r=n.filter(y=>y.status==="fail").length,E=n.filter(y=>y.status==="warn").length;console.log(),r===0&&E===0?console.log(x.green(x.bold("Everything checks out. You're good to go."))):r===0?console.log(x.yellow(x.bold(`${E} warning${E===1?"":"s"} \u2014 review above.`))):(console.log(x.red(x.bold(`${r} failed check${r===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function X(e){try{return await li(e),!0}catch{return!1}}async function ui(){let e=await de();return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:"Install Python 3.10+ from https://www.python.org/downloads/"}}async function pi(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let n=parseInt(t[1],10),i=parseInt(t[2],10);return n<22||n===22&&i<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function fi(e){let t=V(e,"node_modules");if(!await X(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await ci(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 mi(e){let t=process.platform==="darwin"?V(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?V(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):V(process.env.HOME??"",".cache","ms-playwright");return await X(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 hi(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
|
|
@@ -101,4 +103,4 @@ except Exception as e:
|
|
|
101
103
|
`));let a=Pi(process.execPath,[n,"pair","--account",s],{cwd:t,stdio:"inherit"});if(a.status===0){console.log(v.green(`Paired '${s}'.`)),console.log(v.dim(`
|
|
102
104
|
If you haven't already, add '${s}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
103
105
|
WHATSAPP_ACCOUNTS=primary,${s}
|
|
104
|
-
(Skip this if '${s}' is already there or you set it via the init wizard.)`));return}a.error?console.error(v.red(`Pair failed: ${a.error.message}`)):(console.error(v.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(v.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(v.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(v.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${s}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as Si}from"child_process";var lt="--use-system-ca";function Tn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(lt)||!ee().ok)return;let n=e?`${e} ${lt}`:lt,i=Si(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}Tn();var Ii="0.22.
|
|
106
|
+
(Skip this if '${s}' is already there or you set it via the init wizard.)`));return}a.error?console.error(v.red(`Pair failed: ${a.error.message}`)):(console.error(v.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(v.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(v.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(v.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${s}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as Si}from"child_process";var lt="--use-system-ca";function Tn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(lt)||!ee().ok)return;let n=e?`${e} ${lt}`:lt,i=Si(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}Tn();var Ii="0.22.2",Q=new _i;Q.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Ii);Q.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 At({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});Q.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 an({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});Q.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 ln({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});Q.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await dn({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});Q.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await gn({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});Q.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 wn({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});Q.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 Pn({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});Q.parse(process.argv);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.22.
|
|
3
|
+
"version": "0.22.2",
|
|
4
4
|
"description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code (find, build, deploy, outreach end-to-end).",
|
|
5
5
|
"homepage": "https://klaudius.dev",
|
|
6
6
|
"bugs": {
|