klaudius 0.17.2 → 0.17.4
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 +44 -43
- package/package.json +1 -1
- package/dist/chunk-ZTT5HVYU.js +0 -4
- package/dist/scaffold-I6CHSWDK.js +0 -1
package/dist/bin.js
CHANGED
|
@@ -1,79 +1,80 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as Q,b as
|
|
3
|
-
`));let n=[];n.push(
|
|
4
|
-
`)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${n.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${n.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function
|
|
5
|
-
Please share that file so we can trace what happened.`);return t}var
|
|
2
|
+
import{a as Q,b as Ve,c as Ge,d as P,f as Be,g as Ye}from"./chunk-SZ4KCTSL.js";import{Command as Ls}from"commander";import{spawn as We}from"child_process";import _ from"picocolors";function G(){let e=process.version,n=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let s=parseInt(n[1],10),t=parseInt(n[2],10),i=parseInt(n[3],10),a=`${s}.${t}.${i}`;return s<22||s===22&&t<15?{ok:!1,version:a,major:s,minor:t,message:`Your installed Node.js is ${a}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:a,major:s,minor:t}}import{spawn as qt}from"child_process";var ie=3,de=10,Jt=[["python3"],["python"],["py","-3"]];async function ae(){for(let e of Jt){let n=await Qt(e[0],[...e.slice(1),"--version"]),s=(n.stdout+n.stderr).trim();if(/Python was not found/i.test(s)||n.code!==0)continue;let t=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(s);if(!t)continue;let i=parseInt(t[1],10),a=parseInt(t[2],10),l=t[3]?`${i}.${a}.${t[3]}`:`${i}.${a}`;return{command:[...e],version:l,major:i,minor:a}}return null}async function Z(){let e=Xt(),n=await ae();if(!n){let l=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${ie}.${de}+ is not installed (or not on PATH). Install it from ${e}.`+l}}let{command:s,version:t,major:i,minor:a}=n;return i<ie||i===ie&&a<de?{ok:!1,version:t,major:i,minor:a,command:s,message:`Your installed Python is ${t}. Klaudius needs Python ${ie}.${de} or newer (the pipeline depends on packages that only ship wheels for ${ie}.${de}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:t,major:i,minor:a,command:s}}function Xt(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Qt(e,n){return new Promise(s=>{let t=qt(e,n,{stdio:["ignore","pipe","pipe"],shell:!1}),i="",a="";t.stdout?.on("data",l=>{i+=l.toString()}),t.stderr?.on("data",l=>{a+=l.toString()}),t.on("close",l=>s({code:l??1,stdout:i,stderr:a})),t.on("error",()=>s({code:1,stdout:i,stderr:a}))})}var ze=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function qe(e={}){console.log(_.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
|
+
`));let n=[];n.push(Zt());let s=await Z();n.push(en(s)),n.push(await tn(s.command)),n.push(await nn()),n.push(await sn());for(let i of n){let a=i.status==="ok"?_.green("\u2713"):_.red("\u2717");console.log(` ${a} ${i.name}${i.detail?_.dim(` \u2014 ${i.detail}`):""}`),i.nextAction&&console.log(` ${_.dim("\u2192")} ${_.cyan(i.nextAction)}`)}console.log();let t=n.filter(i=>i.status==="fail");if(t.length===0){on();return}console.log(_.red(_.bold(`${t.length} check${t.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(_.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(_.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Zt(){let e=G();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal before re-running."}}function en(e){return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:e.message??"Install Python 3.10+ from https://www.python.org/downloads/"}}async function tn(e){let n=e??["python3"],s=await Ie(n[0],[...n.slice(1),"-m","pip","--version"]);return s.code===0?{name:"pip available",status:"ok",detail:(s.stdout||s.stderr).trim().split(`
|
|
4
|
+
`)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${n.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${n.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function nn(){let e=process.platform==="win32",n=await Ie("npm",["--version"],e);return n.code!==0?{name:"npm / npx available",status:"fail",detail:"npm not found",nextAction:"npm ships with Node.js \u2014 reinstall Node from https://nodejs.org/."}:(await Ie("npx",["--version"],e)).code!==0?{name:"npm / npx available",status:"fail",detail:`npm ${n.stdout.trim()} ok, npx missing`,nextAction:"npx ships with npm 5.2+ \u2014 reinstall Node from https://nodejs.org/."}:{name:"npm / npx available",status:"ok",detail:`npm ${n.stdout.trim()}`}}async function sn(){try{return await fetch(ze,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:ze}}catch(e){return{name:"klaudius.dev reachable",status:"fail",detail:e.name==="TimeoutError"?"timed out":"could not connect",nextAction:"Check your internet connection, VPN, or firewall \u2014 init needs klaudius.dev to validate your license and download the template."}}}function on(){console.log(_.green(_.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(_.bold("NEXT STEP \u2014 this one is for you to run, not the AI assistant:")),console.log(" It's an interactive wizard (it asks for your license key and passwords),"),console.log(" so the assistant can't fill it in. Open a NEW terminal tab and run:"),console.log(),console.log(` ${_.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(_.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(_.dim(" run it in a new terminal.")),console.log()}function Ie(e,n,s=!1){return new Promise(t=>{let i=s?We([e,...n].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):We(e,n,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{l+=c.toString()}),i.on("close",c=>t({code:c??1,stdout:a,stderr:l})),i.on("error",()=>t({code:1,stdout:a,stderr:l}))})}import{mkdir as Le,readdir as Qn,readFile as St,stat as It,writeFile as $e}from"fs/promises";import{spawnSync as xt}from"child_process";import{resolve as Zn,isAbsolute as es,join as q,normalize as ts}from"path";import*as k from"@clack/prompts";import u from"picocolors";import an from"react";import{render as rn}from"ink";async function S(e={},n={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius@latest init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:s}=await import("./WizardApp-LW4VIMPN.js"),t=null;Q("runWizard:start",{onlySection:n.onlySection,hasDefaults:Object.keys(e).length>0}),Ge(),await new Promise(a=>setImmediate(a)),await new Promise(a=>setTimeout(a,0)),Q("runWizard:event loop drained, mounting Ink");let i=rn(an.createElement(s,{defaults:e,onlySection:n.onlySection,banner:n.banner,onComplete:a=>{Q("runWizard:onComplete called",{keys:Object.keys(a).length}),t=a}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(Q("runWizard:render returned, awaiting exit"),await i.waitUntilExit(),Q("runWizard:waitUntilExit resolved",{resultIsNull:t===null}),!t)throw new Error(`Wizard exited without completing. Diagnostic log: ${Ve}
|
|
5
|
+
Please share that file so we can trace what happened.`);return t}var Re="claude-code";function Je(e){if(e==="claude-code"||e==="codex")return e}var xe="vercel";function Xe(e){if(e==="vercel"||e==="cloudflare"||e==="netlify")return e}function ue(e){let n=[],s=i=>{n.push(""),n.push("# "+"=".repeat(60)),n.push(`# ${i}`),n.push("# "+"=".repeat(60)),n.push("")},t=(i,a)=>{if(a==null||a===""){n.push(`# ${i}=`);return}let l=String(a);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(l)){let c=l.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");n.push(`${i}="${c}"`)}else n.push(`${i}=${l}`)};return n.push("# Klaudius configuration"),n.push("# Generated by `npx klaudius init`. Edit freely."),n.push("# NEVER commit this file. .gitignore already excludes it."),s("Klaudius licence"),t("KLAUDIUS_LICENSE_KEY",e.licenseKey),s("AI coding agent"),t("AI_AGENT",e.aiAgent??Re),s("Operating country and language"),t("OPERATOR_COUNTRY",e.country),t("OPERATOR_COUNTRY_CODE",e.countryCode),t("OPERATOR_LANGUAGE",e.language),t("OPERATOR_LANGUAGE_CODE",e.languageCode),s("Pricing"),t("PRICING",e.pricing),t("PRICING_TERMS",e.pricingTerms),t("PRICING_MONTHLY",e.pricingMonthly),s("Automated outreach features"),t("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),t("OPERATOR_NAME",e.name),t("SIGNATURE",e.signature),t("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),t("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),s("Email outreach"),t("EMAIL_ADDRESS",e.emailAddress),t("EMAIL_PASSWORD",e.emailPassword),t("EMAIL_FROM_NAME",e.emailFromName),t("EMAIL_SMTP_HOST",e.emailSmtpHost),t("EMAIL_SMTP_PORT",e.emailSmtpPort),t("EMAIL_IMAP_HOST",e.emailImapHost),t("EMAIL_IMAP_PORT",e.emailImapPort),t("EMAIL_SENT_FOLDER",e.emailSentFolder),t("EMAIL_INBOX_FOLDER",e.emailInboxFolder),s("SMS outreach"),t("SMS_PROVIDER",e.smsProvider),t("TEST_PHONE",e.testPhone),t("TWILIO_ACCOUNT_SID",e.twilioAccountSid),t("TWILIO_AUTH_TOKEN",e.twilioAuthToken),t("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),s("WhatsApp outreach"),t("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),s("Supabase (pipeline state)"),t("SUPABASE_URL",e.supabaseUrl),t("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),t("SUPABASE_PAT",e.supabasePat),t("SUPABASE_PROJECT_REF",e.supabaseProjectRef),s("Deployment"),t("DEPLOY_PROVIDER",e.deployProvider??xe),t("VERCEL_TOKEN",e.vercelToken),t("VERCEL_SCOPE",e.vercelScope??""),t("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),t("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),t("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),t("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),s("Search APIs"),t("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),t("SERPAPI_KEY",e.serpapiKey),s("Telegram notifications (optional)"),t("TELEGRAM_BOT_TOKEN",e.telegramBotToken),t("TELEGRAM_CHAT_ID",e.telegramChatId),s("Rate limiting (sensible defaults)"),t("REQUESTS_PER_MINUTE",10),t("REQUEST_DELAY",2),n.join(`
|
|
6
6
|
`)+`
|
|
7
7
|
`}function pe(e){let n={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(n,null,2)+`
|
|
8
|
-
`}function fe(e){let n=e.supabaseProjectRef,
|
|
9
|
-
`)}function
|
|
8
|
+
`}function fe(e){let n=e.supabaseProjectRef,s=ln(e.supabasePat);return["# Codex MCP config \u2014 generated by `npx klaudius init` / `configure`.","# Edit freely. NEVER commit this file \u2014 .gitignore already excludes it.","# See `.codex/config.toml.example` for the documented format.","","[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${n}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${s}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
|
|
9
|
+
`)}function ln(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Qe=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel', 'cloudflare', or 'netlify'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch host, run `npx klaudius@latest configure` (Cloudflare adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID; Netlify adds NETLIFY_AUTH_TOKEN)."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'}];function cn(e,n){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(n)){let s=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${s}"`}return`${e}=${n}`}function Ze(e,n,s){let t=s.filter(l=>!(l.key in n));if(t.length===0)return null;let i=e.endsWith(`
|
|
10
10
|
`)?"":`
|
|
11
|
-
`,a=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let l of t)a.push(""),l.comment&&a.push(`# ${l.comment}`),a.push(
|
|
11
|
+
`,a=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let l of t)a.push(""),l.comment&&a.push(`# ${l.comment}`),a.push(cn(l.key,l.value));return e+i+a.join(`
|
|
12
12
|
`)+`
|
|
13
|
-
`}function
|
|
14
|
-
`)){let t=
|
|
15
|
-
|
|
13
|
+
`}function dn(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function $(e){let n={};for(let s of e.split(`
|
|
14
|
+
`)){let t=s.trim();if(!t||t.startsWith("#"))continue;let i=t.indexOf("=");if(i===-1)continue;let a=t.slice(0,i).trim(),l=dn(t.slice(i+1).trim());n[a]=l}return n}function et(e){let n=c=>{let p=e[c];if(!p)return;let m=parseInt(p,10);return isNaN(m)?void 0:m},s=e.SMS_PROVIDER,t=c=>c==="email"||c==="sms"||c==="whatsapp",i=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(t),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(t),l=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Je(e.AI_AGENT)??Re,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:i&&i.length>0?i:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:n("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:n("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:s==="imessage"||s==="twilio"?s:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:Xe(e.DEPLOY_PROVIDER)??xe,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,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,emailPassword:e.EMAIL_PASSWORD,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function ve(e){let n=E=>{let v=e[E];if(!v)return;let y=parseInt(v,10);return isNaN(y)?void 0:y},s=e.SUPABASE_URL,t=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),i=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,l=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",p=Xe(e.DEPLOY_PROVIDER)??xe,m=e.VERCEL_TOKEN,r=e.CLOUDFLARE_API_TOKEN,w=e.CLOUDFLARE_ACCOUNT_ID,g=e.NETLIFY_AUTH_TOKEN;if(!l||!s||!t||!i||!a||!(p==="cloudflare"?!!r&&!!w:p==="netlify"?!!g:!!m))return null;let L=e.SMS_PROVIDER,V=E=>E==="email"||E==="sms"||E==="whatsapp",D=e.OUTREACH_CHANNELS?.split(",").map(E=>E.trim()).filter(V),T=e.OUTREACH_PRIORITY?.split(",").map(E=>E.trim()).filter(V),I=e.WHATSAPP_ACCOUNTS?.split(",").map(E=>E.trim()).filter(E=>E.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Je(e.AI_AGENT)??Re,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pricing:l,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:D&&D.length>0?D:void 0,outreachPriority:T&&T.length>0?T:void 0,whatsappAccounts:I&&I.length>0?I:void 0,emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:n("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:n("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:L==="imessage"||L==="twilio"?L:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:p,vercelToken:m,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:r||void 0,cloudflareAccountId:w||void 0,netlifyAuthToken:g||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,supabaseUrl:s,supabaseServiceKey:t,supabasePat:i,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,serpapiKey:e.SERPAPI_KEY,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as so,mkdir as oo,readdir as wn,stat as io}from"fs/promises";import{dirname as ro,join as it,relative as An}from"path";import{fileURLToPath as co}from"url";import{createHash as un}from"crypto";import{readFile as pn}from"fs/promises";async function ee(e){let n=await pn(e);return un("sha256").update(n).digest("hex")}import{mkdir as fn,readFile as mn,writeFile as hn,access as gn}from"fs/promises";import{dirname as yn,join as tt}from"path";var kn=".klaudius",nt=`${kn}/manifest.json`,me=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml"]);async function st(e){let n=tt(e,nt);try{await gn(n)}catch{return null}let s=await mn(n,"utf-8");return JSON.parse(s)}async function he(e,n){let s=tt(e,nt);await fn(yn(s),{recursive:!0}),await hn(s,JSON.stringify(n,null,2)+`
|
|
15
|
+
`,"utf-8")}function ot(e,n){let s=new Date().toISOString();return{version:1,templateVersion:e,installedAt:s,updatedAt:s,files:n}}async function ge(e,n=e){let s=await wn(e,{withFileTypes:!0}),t=[];for(let i of s){let a=it(e,i.name);i.isDirectory()?t.push(...await ge(a,n)):i.isFile()&&t.push(An(n,a))}return t}async function at(e){let n=await ge(e),s={};for(let t of n)me.has(t)||(s[t]=await ee(it(e,t)));return s}import{copyFile as En,mkdir as rt,mkdtemp as Pn,readdir as lt,rm as ct}from"fs/promises";import{tmpdir as bn}from"os";import{dirname as Tn,join as ye}from"path";import{Readable as _n}from"stream";import*as dt from"tar";var Cn="https://klaudius.dev/api/template";function Sn(e){return _n.fromWeb(e)}async function ke(e){let n=process.env.KLAUDIUS_TEMPLATE_URL??Cn,s="0.17.4",t;try{t=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:s,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${P(c)}`)}if(!t.ok){let c="";try{let p=await t.json();c=p.reason?` (${p.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${t.status}${c}`)}if(!t.body)throw new Error("Template download succeeded but response had no body");let i=t.headers.get("x-klaudius-tier"),a=await Pn(ye(bn(),"klaudius-template-")),l=0;try{try{await new Promise((m,r)=>{let w=dt.extract({cwd:a,strict:!0});w.on("finish",m),w.on("error",r),Sn(t.body).on("error",r).pipe(w)})}catch(m){throw new Error(`Failed to extract template archive: ${m.message}`)}await rt(e.destDir,{recursive:!0});let c=new Set(await lt(e.destDir)),p=await ge(a);try{for(let m of p){let r=ye(e.destDir,m);await rt(Tn(r),{recursive:!0}),await En(ye(a,m),r),l++}}catch(m){let r=await lt(e.destDir).catch(()=>[]);for(let w of r)c.has(w)||await ct(ye(e.destDir,w),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${m.message}`)}}finally{await ct(a,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:i}}import B from"picocolors";var o={info:e=>console.log(B.cyan("\u2139"),e),success:e=>console.log(B.green("\u2713"),e),warn:e=>console.log(B.yellow("\u26A0"),e),error:e=>console.error(B.red("\u2717"),e),step:e=>console.log(B.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
16
|
+
`+B.bold(B.cyan(e))),detail:e=>console.log(B.dim(" "+e))};var In="https://registry.npmjs.org/klaudius/latest";async function Rn(e=1500){let n=new AbortController,s=setTimeout(()=>n.abort(),e);try{let t=await fetch(In,{signal:n.signal,headers:{accept:"application/json"}});if(!t.ok)return null;let i=await t.json();return typeof i.version=="string"?i.version:null}catch{return null}finally{clearTimeout(s)}}function xn(e,n){let s=a=>a.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),t=s(e),i=s(n);if(t.length<3||i.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(t[a])||Number.isNaN(i[a]))return!1;if(t[a]>i[a])return!0;if(t[a]<i[a])return!1}return!1}async function we(e,n){if(n==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let s=await Rn();!s||!xn(s,n)||(o.blank(),o.warn(`A newer Klaudius CLI is available: you have ${n}, latest is ${s}.`),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 vn}from"crypto";import{hostname as ut,userInfo as On,platform as pt,arch as ft}from"os";var Nn="https://klaudius.dev",$n="/api/licenses/validate",Ln="0.17.4";async function mt(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let n=e.trim(),t=(process.env.KLAUDIUS_API_URL??Nn).replace(/\/$/,"")+$n,i=re(),a;try{a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:n,machine_id:i,hostname:ut(),os:`${pt()}-${ft()}`,cli_version:Ln})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${P(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 re(){let e=[ut(),On().username,pt(),ft()].join("|");return vn("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Dn}from"fs/promises";import{join as Mn}from"path";async function te(e){let n=e.serviceKey.replace(/\s+/g,"");try{let s=await fetch(e.url+"/rest/v1/",{headers:{apikey:n,Authorization:`Bearer ${n}`}});return s.status===401||s.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${s.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(s){return{ok:!1,message:`Could not reach Supabase: ${P(s)}`}}}async function ht(e){let n;try{n=await Dn(Mn(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(t){return{ok:!1,message:`Could not read scripts/schema.sql: ${t.message}`}}let s=e.pat.replace(/\s+/g,"");try{let t=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({query:n})});if(t.ok)return{ok:!0};let i=await t.text();return i.includes("already exists")||i.includes('relation "clients" already exists')||i.includes("duplicate")?(o.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${t.status}): ${i.slice(0,300)}`}}catch(t){return{ok:!1,message:`Schema apply failed: ${t.message}`}}}async function Ae(e){try{let n=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(n.status===401||n.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${n.status}). The token is invalid, expired, or has been revoked.`};if(!n.ok)return{ok:!1,message:`Vercel API returned HTTP ${n.status}. Try again or check status.vercel.com.`};let s=await n.json();return{ok:!0,username:s.user?.username??s.user?.email}}catch(n){return{ok:!1,message:`Could not reach Vercel: ${P(n)}`}}}var gt="https://api.cloudflare.com/client/v4";function yt(e){let n=e?.errors?.[0];if(n)return n.message?`${n.message}${n.code?` (code ${n.code})`:""}`:void 0}async function Ee(e){let{token:n,accountId:s}=e,t={Authorization:`Bearer ${n}`,"Content-Type":"application/json"};try{let i=await fetch(`${gt}/user/tokens/verify`,{headers:t});if(i.status===401||i.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await i.json(),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(i){return{ok:!1,message:`Could not reach Cloudflare: ${P(i)}`}}try{let i=await fetch(`${gt}/accounts/${encodeURIComponent(s)}/pages/projects`,{headers:t});if(i.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${s} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(i.status===404)return{ok:!1,message:`Account ${s} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!i.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${i.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await i.json();return a.success===!1?{ok:!1,message:yt(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(i){return{ok:!1,message:`Could not reach Cloudflare: ${P(i)}`}}}var kt="https://api.netlify.com/api/v1";async function Pe(e){let{token:n}=e,s={Authorization:`Bearer ${n}`};try{let t=await fetch(`${kt}/user`,{headers:s});if(t.status===401||t.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${t.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(!t.ok)return{ok:!1,message:`Netlify API returned HTTP ${t.status} verifying the token. Try again or check netlifystatus.com.`}}catch(t){return{ok:!1,message:`Could not reach Netlify: ${P(t)}`}}try{let t=await fetch(`${kt}/accounts`,{headers:s});if(!t.ok)return{ok:!1,message:`Netlify API returned HTTP ${t.status} listing your teams. Try again or check netlifystatus.com.`};let i=await t.json(),a=Array.isArray(i)?i:[];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(t){return{ok:!1,message:`Could not reach Netlify: ${P(t)}`}}}async function be(e){try{let n=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":e,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(n.ok)return{ok:!0};if(n.status===429)return{ok:!0};let s={};try{s=await n.json()}catch{}let t=s.error?.message??"",i=s.error?.status??"";return n.status===400&&(i==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(t))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:n.status===401||n.status===403?{ok:!1,message:t||`Google rejected the key (HTTP ${n.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`}:{ok:!1,message:`Google API returned HTTP ${n.status}${t?`: ${t}`:""}.`}}catch(n){return{ok:!1,message:`Could not reach Google: ${P(n)}`}}}import Un from"nodemailer";import{ImapFlow as jn}from"imapflow";async function At(e){let n=Un.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await n.verify()}catch(t){return{ok:!1,failedAt:"smtp",message:wt(t,"SMTP")}}finally{n.close()}let s=new jn({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1});try{await s.connect(),await s.logout()}catch(t){try{await s.logout()}catch{}return{ok:!1,failedAt:"imap",message:wt(t,"IMAP")}}return{ok:!0}}function wt(e,n){let s=e instanceof Error?e.message:String(e),t=s.toLowerCase();return t.includes("invalid credentials")||t.includes("authentication failed")||t.includes("auth failed")||t.includes("login failed")?`${n} rejected the credentials. Most common causes:
|
|
16
17
|
\u2022 The app password is wrong, expired, or for a different provider.
|
|
17
18
|
\u2022 The email address doesn't match the account that issued the password.
|
|
18
|
-
\u2022 2FA is required but no app-specific password was generated.`:t.includes("etimedout")||t.includes("timeout")?`${n} server didn't respond in time. Check the host/port, or your network.`:t.includes("enotfound")||t.includes("getaddrinfo")?`${n} host could not be resolved. Check the host setting.`:`${n} check failed: ${
|
|
19
|
-
`+n;return
|
|
20
|
-
${e.stdout??""}`;return
|
|
21
|
-
`,"utf-8")}var
|
|
22
|
-
${
|
|
19
|
+
\u2022 2FA is required but no app-specific password was generated.`:t.includes("etimedout")||t.includes("timeout")?`${n} server didn't respond in time. Check the host/port, or your network.`:t.includes("enotfound")||t.includes("getaddrinfo")?`${n} host could not be resolved. Check the host setting.`:`${n} check failed: ${s}`}async function Et(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let n=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,s=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let t=await fetch(n,{headers:{Authorization:`Basic ${s}`}});if(t.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!t.ok)return{ok:!1,message:`Twilio API returned HTTP ${t.status}. Try again or check status.twilio.com.`};let i=await t.json();return i.status&&i.status!=="active"?{ok:!1,message:`Twilio account is in '${i.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:i.friendly_name}}catch(t){return{ok:!1,message:`Could not reach Twilio: ${P(t)}`}}}import{spawn as Kn}from"child_process";async function Pt(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let s=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,t=await Fn(s);if(t.code===0)return{ok:!0};let i=t.stderr.toLowerCase();return i.includes("can't get application")||i.includes("isn't running")||i.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:i.includes("(-1728)")||i.includes("not found")||i.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:i.includes("(-1719)")||i.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${t.stderr.trim()||`exit code ${t.code}`}`}}function Fn(e){return new Promise(n=>{let s=Kn("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),t="";s.stderr.on("data",i=>{t+=i.toString()}),s.on("close",i=>n({code:i??1,stderr:t})),s.on("error",i=>n({code:1,stderr:i.message}))})}import{spawn as Ne}from"child_process";function Hn(){let e=process.env.NODE_OPTIONS?.trim(),n=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:n}}var ne=2,bt=2e3,Vn=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Tt(e,n){let s=e+`
|
|
20
|
+
`+n;return Vn.some(t=>t.test(s))}function _t(e){return new Promise(n=>setTimeout(n,e))}function Gn(e,n,s){return new Promise(t=>{let i=s.shell?Ne([e,...n].join(" "),{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:s.env??process.env}):Ne(e,n,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:s.env??process.env}),a="",l="";i.stdout?.on("data",c=>{let p=c.toString();a+=p,process.stdout.write(p)}),i.stderr?.on("data",c=>{let p=c.toString();l+=p,process.stderr.write(p)}),i.on("close",c=>t({code:c??1,stdout:a,stderr:l})),i.on("error",c=>t({code:1,stdout:a,stderr:l+c.message}))})}async function Oe(e,n,s){let t={code:0,stdout:"",stderr:""};for(let i=0;i<=ne;i++){if(t=await Gn(e,n,{cwd:s.cwd,env:s.env,shell:s.shell}),t.code===0||!Tt(t.stderr,t.stdout))return t;i<ne&&(o.detail(`${s.label} failed with a transient network error \u2014 retrying (${i+2}/${ne+1})\u2026`),await _t(bt))}return t}function Bn(e,n,s){return new Promise(t=>{let i=Ne(e,n,{cwd:s.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{l+=c.toString()}),i.on("close",c=>t({code:c??1,stdout:a,stderr:l})),i.on("error",c=>t({code:1,stdout:a,stderr:l+c.message}))})}var Yn=[{pattern:/UNABLE_TO_VERIFY_LEAF_SIGNATURE|unable to verify the first certificate/i,hint:"TLS-handshake error \u2014 your machine appears to be intercepting HTTPS (antivirus, corporate proxy, or VPN re-signing traffic with its own root CA). We work around this with NODE_OPTIONS=--use-system-ca, which needs Node 22.15+. Run `node --version` to verify, upgrade if older, then re-run setup."},{pattern:/Microsoft Visual C\+\+ 14\.0 or greater is required/i,hint:"Python tried to compile a package from source and couldn't find the Microsoft C++ Build Tools. The latest Klaudius pins supabase<2.26 to skip the offending dependency entirely. Re-run with `npx klaudius@latest init` (pulls the latest) \u2014 that should bypass the source build."}];function Wn(e){let n=`${e.stderr??""}
|
|
21
|
+
${e.stdout??""}`;return Yn.find(t=>t.pattern.test(n))?.hint}async function zn(e){let n=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],s=["-m","pip","install","--quiet","--user","--prefer-binary"],i=(await ae())?.command??["python3"],a=async c=>{let p={code:0,stdout:"",stderr:""};for(let m=0;m<=ne;m++){if(p=await Bn(i[0],[...i.slice(1),...c],{cwd:e}),p.code===0||!Tt(p.stderr,p.stdout))return p;m<ne&&(o.detail(`pip install hit a transient network error \u2014 retrying (${m+2}/${ne+1})\u2026`),await _t(bt))}return p},l=await a([...s,"--break-system-packages",...n]);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([...s,...n])),l.code!==0&&(l.stderr.trim()&&process.stderr.write(l.stderr),l.stdout.trim()&&process.stdout.write(l.stdout)),l}async function Te(e){let n={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},s=Hn(),t=process.platform==="win32",i=(m,r)=>{let w=Wn(r);w&&((n.hints??={})[m]=w)};o.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await Oe("npm",["install"],{cwd:e,label:"npm install",env:s,shell:t});n.npm=a.code===0?"ok":"failed",a.code!==0&&i("npm",a),o.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await zn(e);n.pip=l.code===0?"ok":"failed",l.code!==0&&i("pip",l),o.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Oe("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:s,shell:t});n.playwright=c.code===0?"ok":"failed",c.code!==0&&i("playwright",c),o.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await Oe("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:s,shell:t});return n.patchright=p.code===0?"ok":"failed",p.code!==0&&i("patchright",p),n}import{mkdir as qn,readFile as Jn,writeFile as Xn}from"fs/promises";import{join as Ct}from"path";async function _e(e,n){let s=Ct(e,".claude");await qn(s,{recursive:!0});let t=Ct(s,"settings.json"),i={};try{let p=await Jn(t,"utf-8"),m=JSON.parse(p);m&&typeof m=="object"&&!Array.isArray(m)&&(i=m)}catch{}let a=i.enabledMcpjsonServers,l=Array.isArray(a)?a.filter(p=>typeof p=="string"):[];l.includes(n)||l.push(n);let c={...i,enabledMcpjsonServers:l};await Xn(t,JSON.stringify(c,null,2)+`
|
|
22
|
+
`,"utf-8")}var Rt="0.17.4",b=5;function Y(e,n){o.blank(),o.error(`${e} validation failed ${b} times in a row. Pausing setup so you don't get stuck in a loop.`),o.detail(`Last error: ${n}`),o.blank(),o.detail("Your credentials are saved in `.env`. Two ways forward:"),o.detail(" \u2022 Open `.env` in any text editor, fix the value, re-run `npx klaudius@latest init` and pick Resume."),o.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),o.blank(),process.exit(1)}async function vt(e){let n=e.target??".",s=es(n)?n:Zn(process.cwd(),n),t=is(s);t&&(o.error("Klaudius can't be installed inside a protected system folder."),o.detail(`Path: ${s}`),o.detail(`Reason: ${t}`),o.blank(),o.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),o.blank(),process.platform==="win32"?(o.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${u.cyan("cd $HOME\\Documents")}`),console.log(` ${u.cyan("npx klaudius@latest init my-agency")}`)):(o.detail("For example:"),console.log(` ${u.cyan("cd ~/Documents")}`),console.log(` ${u.cyan("npx klaudius@latest init my-agency")}`)),o.blank(),process.exit(1)),process.platform==="win32"&&as()&&(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 we("init",Rt);let i=await ns(s);if(i.kind==="scaffolded"){o.blank(),o.warn(`Found an existing Klaudius project at ${u.bold(s)}.`),o.detail("(Your .env and project files are in place.)"),o.blank(),i.nodeModulesMissing?(o.detail("It looks like a previous setup didn't finish installing dependencies."),o.detail("To pick up where it left off, run:"),o.blank(),s!==process.cwd()&&console.log(` ${u.cyan(`cd ${n}`)}`),console.log(` ${u.cyan("npx klaudius@latest install")} ${u.dim("# retries npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${u.cyan("npx klaudius@latest doctor")} ${u.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(` ${u.cyan("npx klaudius@latest doctor")} ${u.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${u.cyan("npx klaudius@latest configure")} ${u.dim("# change a credential / API key")}`),console.log(` ${u.cyan("npx klaudius@latest update")} ${u.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(i.kind==="occupied"){let d=n===".";o.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),o.detail(`Path: ${s}`),o.detail(`Contains: ${i.entries.slice(0,5).join(", ")}${i.entries.length>5?`, \u2026 (+${i.entries.length-5} more)`:""}`),o.blank(),d?(o.detail("Two ways forward:"),o.blank(),o.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${u.cyan("npx klaudius@latest init my-agency")}`),o.blank(),o.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${u.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(o.detail(`The folder '${n}' already exists and isn't empty.`),o.detail("Either pick a different name:"),console.log(` ${u.cyan(`npx klaudius@latest init ${n}-2`)}`),o.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await os(e.license),l=k.spinner();l.start("Validating license");let c=await mt(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 p=await Z();p.ok||(o.error(p.message??"Python version check failed."),o.blank(),o.detail("Once you've installed Python 3.10+, re-run `npx klaudius@latest init` in this folder."),process.exit(1));let m=G();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 `npx klaudius@latest init` in this folder."),process.exit(1));let r,w=!1;if(i.kind==="partial")if(await ss(s)==="resume"){let h=await St(i.envPath,"utf-8"),f=ve($(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,w=!0):(o.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await S())}else{let h=await St(i.envPath,"utf-8"),f=ve($(h));r=await S(f??{})}else r=await S();r.licenseKey=a,await M(s,r),w||(o.success("Saved .env"),o.success(r.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),o.blank();for(let d=1;;d++){let h=k.spinner();h.start("Validating Supabase credentials");let f=await te({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(f.ok){h.stop("Supabase credentials accepted");break}h.stop(f.message??"Supabase check failed",2),d>=b&&Y("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 ${d+1} of ${b})`),o.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await S(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
23
|
+
${A}
|
|
23
24
|
|
|
24
25
|
Re-enter the URL, secret key, or PAT below. Press Enter on any
|
|
25
|
-
field to keep what's already there.`}),await M(
|
|
26
|
-
${
|
|
26
|
+
field to keep what's already there.`}),await M(s,r)}if(o.blank(),r.deployProvider==="cloudflare")for(let d=1;;d++){let h=k.spinner();h.start("Validating Cloudflare token + account");let f=await Ee({token:r.cloudflareApiToken??"",accountId:r.cloudflareAccountId??""});if(f.ok){h.stop(`Cloudflare credentials accepted (${f.projectCount??0} existing Pages project${f.projectCount===1?"":"s"})`);break}h.stop(f.message??"Cloudflare check failed",2),d>=b&&Y("Cloudflare",f.message??"Cloudflare check failed");let A=f.message??"Cloudflare check failed";o.blank(),o.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${d+1} of ${b})`),o.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await S(r,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
|
|
27
|
+
${A}
|
|
27
28
|
|
|
28
29
|
Re-enter the API token or Account ID below. The token needs the
|
|
29
30
|
"Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
|
|
30
|
-
the current value.`}),await M(
|
|
31
|
-
${
|
|
31
|
+
the current value.`}),await M(s,r)}else if(r.deployProvider==="netlify")for(let d=1;;d++){let h=k.spinner();h.start("Validating Netlify token");let f=await Pe({token:r.netlifyAuthToken??""});if(f.ok){h.stop(f.accountSlug?`Netlify token accepted (team: ${f.accountSlug})`:"Netlify token accepted");break}h.stop(f.message??"Netlify check failed",2),d>=b&&Y("Netlify",f.message??"Netlify check failed");let A=f.message??"Netlify check failed";o.blank(),o.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${d+1} of ${b})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await S(r,{onlySection:"netlify",banner:`Netlify rejected the token:
|
|
32
|
+
${A}
|
|
32
33
|
|
|
33
34
|
Generate a new token at
|
|
34
35
|
https://app.netlify.com/user/applications#personal-access-tokens
|
|
35
|
-
and paste it below. Press Enter to keep the current value.`}),await M(
|
|
36
|
-
${
|
|
36
|
+
and paste it below. Press Enter to keep the current value.`}),await M(s,r)}else for(let d=1;;d++){let h=k.spinner();h.start("Validating Vercel token");let f=await Ae(r.vercelToken??"");if(f.ok){h.stop(f.username?`Vercel token accepted (signed in as ${f.username})`:"Vercel token accepted");break}h.stop(f.message??"Vercel check failed",2),d>=b&&Y("Vercel",f.message??"Vercel check failed");let A=f.message??"Vercel check failed";o.blank(),o.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${d+1} of ${b})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await S(r,{onlySection:"vercel",banner:`Vercel rejected the token:
|
|
37
|
+
${A}
|
|
37
38
|
|
|
38
39
|
Generate a new token at https://vercel.com/account/tokens and
|
|
39
|
-
paste it below. Press Enter to keep the current value.`}),await M(
|
|
40
|
-
${
|
|
40
|
+
paste it below. Press Enter to keep the current value.`}),await M(s,r)}o.blank();for(let d=1;;d++){let h=k.spinner();h.start("Validating Google Places API key");let f=await be(r.googlePlacesApiKey??"");if(f.ok){h.stop("Google Places API key accepted");break}h.stop(f.message??"Google Places check failed",2),d>=b&&Y("Google Places",f.message??"Google Places check failed");let A=f.message??"Google Places check failed";o.blank(),o.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${d+1} of ${b})`),o.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await S(r,{onlySection:"google-places",banner:`Google rejected the key:
|
|
41
|
+
${A}
|
|
41
42
|
|
|
42
43
|
Generate (or fix) the key at https://console.cloud.google.com
|
|
43
|
-
and paste it below. Press Enter to keep the current value.`}),await M(
|
|
44
|
-
${
|
|
44
|
+
and paste it below. Press Enter to keep the current value.`}),await M(s,r)}if(r.outreachEnabled&&r.outreachChannels?.includes("email")&&r.emailAddress&&r.emailPassword&&r.emailSmtpHost&&r.emailSmtpPort&&r.emailImapHost&&r.emailImapPort){o.blank();for(let d=1;;d++){let h=k.spinner();h.start("Validating email credentials (SMTP + IMAP)");let f=await At({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort});if(f.ok){h.stop("Email credentials accepted (SMTP + IMAP)");break}h.stop(f.message??"Email check failed",2),d>=b&&Y("Email",f.message??"Email check failed");let A=f.message??"Email check failed";o.blank(),o.warn(`Bouncing you back into the email section so you can fix it in place. (attempt ${d+1} of ${b})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await S(r,{onlySection:"email",banner:`${f.failedAt==="imap"?"IMAP":"SMTP"} check failed:
|
|
45
|
+
${A}
|
|
45
46
|
|
|
46
47
|
Re-enter the email address, app password, or host details below.
|
|
47
|
-
Press Enter on any field to keep its current value.`}),await M(
|
|
48
|
-
${
|
|
48
|
+
Press Enter on any field to keep its current value.`}),await M(s,r)}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="twilio"&&r.twilioAccountSid&&r.twilioAuthToken){o.blank();for(let d=1;;d++){let h=k.spinner();h.start("Validating Twilio credentials");let f=await Et({accountSid:r.twilioAccountSid,authToken:r.twilioAuthToken});if(f.ok){h.stop(f.friendlyName?`Twilio credentials accepted (${f.friendlyName})`:"Twilio credentials accepted");break}h.stop(f.message??"Twilio check failed",2),d>=b&&Y("Twilio",f.message??"Twilio check failed");let A=f.message??"Twilio check failed";o.blank(),o.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${d+1} of ${b})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await S(r,{onlySection:"sms",banner:`Twilio rejected the credentials:
|
|
49
|
+
${A}
|
|
49
50
|
|
|
50
51
|
Re-enter the Account SID or Auth Token below.
|
|
51
|
-
Press Enter on any field to keep its current value.`}),await M(
|
|
52
|
-
${
|
|
52
|
+
Press Enter on any field to keep its current value.`}),await M(s,r)}}if(r.outreachEnabled&&r.outreachChannels?.includes("sms")&&r.smsProvider==="imessage"&&r.testPhone){o.blank();for(let d=1;;d++){let h=k.spinner();h.start("Validating iMessage setup (sending a test ping)");let f=await Pt({testPhone:r.testPhone});if(f.ok){h.stop("iMessage dispatched (check your phone for the test ping)");break}h.stop(f.message??"iMessage check failed",2),d>=b&&Y("iMessage",f.message??"iMessage check failed");let A=f.message??"iMessage check failed";o.blank(),o.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${d+1} of ${b})`),o.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),o.blank(),r=await S(r,{onlySection:"sms",banner:`iMessage check failed:
|
|
53
|
+
${A}
|
|
53
54
|
|
|
54
55
|
Either fix the underlying issue (sign in to Messages.app, configure
|
|
55
56
|
Text Message Forwarding) and press Enter through, or change SMS
|
|
56
|
-
provider to Twilio.`}),await M(
|
|
57
|
-
${
|
|
57
|
+
provider to Twilio.`}),await M(s,r)}}if(r.telegramBotToken&&r.telegramChatId){o.blank();let d=0,h=!1;for(;!h;){d++;let f=k.spinner();f.start("Validating Telegram bot + chat (sending a test ping)");let A=await Ye({botToken:r.telegramBotToken,chatId:r.telegramChatId});if(A.ok){f.stop(A.botHandle?`Telegram bot ${A.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),h=!0;break}f.stop(A.message??"Telegram check failed",2);let He=A.message??"Telegram check failed";o.blank(),o.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),o.blank();let z=await k.select({message:"What would you like to do?",initialValue:d>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(k.isCancel(z)&&(k.cancel("Setup cancelled. Your .env is saved \u2014 re-run `npx klaudius@latest init` to resume."),process.exit(0)),z==="skip"){r.telegramBotToken=void 0,r.telegramChatId=void 0,await M(s,r),o.success("Skipped Telegram. Setup will continue."),o.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),h=!0;break}if(z==="edit"&&(o.blank(),r=await S(r,{onlySection:"telegram",banner:`Telegram check failed:
|
|
58
|
+
${He}
|
|
58
59
|
|
|
59
60
|
Re-enter the bot token or chat_id below.
|
|
60
|
-
Press Enter on any field to keep its current value.`}),await M(
|
|
61
|
+
Press Enter on any field to keep its current value.`}),await M(s,r),!r.telegramBotToken||!r.telegramChatId)){o.success("Skipped Telegram. Setup will continue."),h=!0;break}}}o.blank();let g=k.spinner();g.start("Downloading Klaudius template");let C;try{C=(await ke({licenseKey:a,machineId:re(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:r.aiAgent,destDir:s})).filesExtracted,g.stop(`Downloaded ${C} files into ${u.bold(s)}`)}catch(d){g.stop(d.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 Le(q(s,"clients"),{recursive:!0});let L=await at(s);await he(s,ot(Rt,L)),o.success("Wrote .klaudius/manifest.json");let V=!1,D="";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 d=k.spinner();d.start("Applying schema to Supabase");let h=await ht({projectRoot:s,pat:r.supabasePat,projectRef:r.supabaseProjectRef});h.ok?d.stop("Schema applied (or already present)"):(d.stop(h.message??"Schema apply failed",2),V=!0,D=`https://supabase.com/dashboard/project/${r.supabaseProjectRef}/sql/new`)}let T=[],I={};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 d=await Te(s);o.detail(`npm: ${d.npm}, pip: ${d.pip}, playwright: ${d.playwright}, patchright: ${d.patchright}`),d.npm==="failed"&&T.push("npm"),d.pip==="failed"&&T.push("pip"),d.playwright==="failed"&&T.push("playwright"),d.patchright==="failed"&&T.push("patchright"),I=d.hints??{}}let E=r.outreachEnabled&&r.outreachPriority?.includes("whatsapp")&&(r.whatsappAccounts?.length??0)>0,v=!e.skipInstall&&!T.includes("npm");if(E&&v){o.blank(),o.heading("Linking WhatsApp accounts"),console.log(u.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
|
|
61
62
|
phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
|
|
62
|
-
Link a Device, and point it at the QR shown in this terminal.`)),
|
|
63
|
-
`:"",m=r.aiAgent==="codex"?"codex":"claude",p=r.aiAgent==="codex"?"Codex":"Claude Code",w=r.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";T.length>0&&(console.log(u.dim(`Easiest fix \u2014 let ${p} finish it for you:`)),s.blank(),d&&process.stdout.write(d),console.log(` ${u.cyan(m)} ${u.dim(`# open ${p} in this folder`)}`),console.log(u.dim(" Then paste:")),console.log(u.cyan(` "Finish my Klaudius install \u2014 ${T.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(u.dim(` (Don't have ${p} yet? Install with: \`${w}\`)`)),s.blank(),console.log(u.dim("Or do it yourself:")),s.blank(),d&&process.stdout.write(d),console.log(` ${u.cyan("npx klaudius@latest install")} ${u.dim("# retry the failing installers")}`),console.log(` ${u.cyan("npx klaudius@latest doctor")} ${u.dim("# verify everything")}`),s.blank()),V&&(console.log(u.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${u.cyan(D)}`),console.log(u.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),T.includes("pip")&&!S.pip&&(console.log(u.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(u.dim(`Python 3.10+. Install a newer one from ${Kn()}`)),console.log(u.dim("and open a fresh Terminal before retrying.")),s.blank());let z=["npm","playwright","patchright"].filter(J=>T.includes(J)&&!S[J]);if(z.length>0){let J=z.length===1?"keeps":"keep";console.log(u.dim(`If ${z.join(" / ")} ${J} failing with network errors (ECONNRESET,`)),console.log(u.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(u.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}console.log(u.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}k.outro(u.green(u.bold("Project ready."))),console.log(u.dim("Next steps:")),o!==process.cwd()&&console.log(` ${u.cyan(`cd ${e.target}`)}`);let j=process.platform==="win32"?"start":process.platform==="linux"?"xdg-open":"open",X=u.dim("# read this first \u2014 operator basics + commands");console.log(` ${u.cyan(`${j} DOCS.html`)}${" ".repeat(Math.max(1,17-j.length))}${X}`);let re=r.aiAgent==="codex"?"codex":"claude",Me=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(` ${u.cyan(re)} ${u.dim(`# open ${Me} in this project`)}`),console.log(` ${u.dim(`then ask ${Me}:`)}`),console.log(` ${u.cyan(' "Run the pipeline."')}`),s.blank()}async function M(e,n){await ve(e,{recursive:!0}),await xe(q(e,".env"),ue(n),"utf-8"),n.aiAgent==="codex"?(await ve(q(e,".codex"),{recursive:!0}),await xe(q(e,".codex","config.toml"),fe(n),"utf-8")):(await xe(q(e,".mcp.json"),pe(n),"utf-8"),await Ee(e,"supabase"))}async function Ln(e){try{(await wt(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let n=await vn(e),o=n.filter(c=>!c.startsWith(".DS_Store"));if(o.length===0)return{kind:"fresh"};let t=new Set([".env",".mcp.json",".claude",".codex"]),i=o.every(c=>t.has(c)),a=o.includes(".env"),l=n.includes(".klaudius");if(i&&a&&!l)return{kind:"partial",envPath:q(e,".env")};if(l&&a){let c=!0;try{c=!(await wt(q(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:o}}async function Dn(e){s.blank(),s.warn(`Found a partial setup at ${u.bold(e)}.`),s.detail(`A previous init wrote ${u.bold(".env")} but didn't finish scaffolding.`),s.blank();let n=await k.select({message:"How would you like to proceed?",initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return k.isCancel(n)&&(k.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),n}async function Mn(e){if(e&&e.trim().length>0)return e;k.intro("Klaudius");let n=await k.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:o=>o.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return k.isCancel(n)&&(k.cancel("Setup cancelled. No files written."),process.exit(0)),n}function Un(e){let n=$n(e);if(process.platform==="win32"){let o=n.toLowerCase();if(o.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(o.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(o.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(o.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let o=["/System/","/usr/","/bin/","/sbin/"];for(let t of o)if(n.startsWith(t))return`Inside ${t.slice(0,-1)} (system-managed directory).`}}function jn(){if(process.platform!=="win32")return!1;try{return Et("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Kn(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}import{access as Hn,readFile as Fn}from"fs/promises";import{join as Oe,resolve as Vn}from"path";import O from"picocolors";async function Tt(e){let n=e.target?Vn(process.cwd(),e.target):process.cwd(),o=await bt(Oe(n,".env")),t=await bt(Oe(n,"package.json"));(!o||!t)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${n}`),o||s.detail("Missing: .env"),t||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let i="claude-code";try{$(await Fn(Oe(n,".env"),"utf-8")).AI_AGENT==="codex"&&(i="codex")}catch{}s.heading("Installing dependencies");let a=await Ae(n);s.blank(),s.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){s.blank(),console.log(O.green(O.bold("All dependencies installed."))),console.log(O.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(O.yellow(O.bold(`${l.join(", ")} still failing.`))),s.blank();for(let[r,A]of Object.entries(a.hints??{}))console.log(O.yellow(`Likely cause of ${r} failure:`)),console.log(O.dim(` ${A}`)),s.blank();let c=i==="codex"?"codex":"claude",f=i==="codex"?"Codex":"Claude Code",g=i==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(O.dim("Options:")),console.log(O.dim(` \u2022 Open ${f} in this folder (\`${c}\`) and paste:`)),console.log(O.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(O.dim(` (Don't have ${f} yet? Install with: \`${g}\`)`)),console.log(O.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(O.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function bt(e){try{return await Hn(e),!0}catch{return!1}}import{readFile as Gn,writeFile as Ne,access as Bn}from"fs/promises";import{join as ne}from"path";import*as Pe from"@clack/prompts";import K from"picocolors";import{mkdir as Yn}from"fs/promises";async function _t(e){let n=e.projectRoot??process.cwd(),o=ne(n,".env"),t=ne(n,".mcp.json"),i=ne(n,".codex","config.toml"),a=await $e(ne(n,".klaudius","manifest.json")),l=await $e(o);!a&&!l&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=G();c.ok||(s.error(c.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let f={};try{let h=await Gn(o,"utf-8");f=$(h)}catch{s.warn("No .env found. Starting from an empty configuration.")}let g=Ze(f);Pe.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let r=await I(g),A=g.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==A&&(s.error(`Switching AI coding agent (${A} \u2192 ${r.aiAgent}) isn't supported via configure.`),s.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),s.blank(),console.log(` ${K.cyan("npx klaudius@latest init <new-folder>")} ${K.dim("# pick the new agent in the wizard")}`),s.blank(),s.detail(".env is unchanged."),process.exit(1)),r.supabaseUrl!==f.SUPABASE_URL||r.supabaseServiceKey!==f.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let h=await ee({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});h.ok||(s.error(h.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}await Ne(o,ue(r),"utf-8"),s.success("Updated .env"),r.aiAgent==="codex"?(await Yn(ne(n,".codex"),{recursive:!0}),await Ne(i,fe(r),"utf-8"),s.success("Updated .codex/config.toml")):(await Ne(t,pe(r),"utf-8"),s.success("Updated .mcp.json"),await Ee(n,"supabase")),s.blank(),Pe.outro(K.green("Configuration updated.")),await Wn(n,a)}async function Wn(e,n){let o=await $e(ne(e,"node_modules"));s.blank(),n?o||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${K.cyan("npx klaudius@latest install")} ${K.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${K.cyan("npx klaudius@latest doctor")} ${K.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${K.cyan("npx klaudius@latest init")} ${K.dim("# pick Resume when prompted")}`),s.blank())}async function $e(e){try{return await Bn(e),!0}catch{return!1}}import{copyFile as Ct,mkdir as It,readdir as zn,readFile as qn,rm as ae,writeFile as St,access as Rt}from"fs/promises";import{dirname as xt,join as N,relative as Xn}from"path";import{tmpdir as Jn}from"os";import*as se from"@clack/prompts";import Le from"picocolors";var be="0.17.2";async function vt(e){let n=e.projectRoot??process.cwd(),o=await Ge(n);o||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let y of Ve)delete o.files[y];let t,i=N(n,".env"),a,l;try{a=await qn(i,"utf-8"),l=$(a)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}t=l.KLAUDIUS_LICENSE_KEY??"",t||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius@latest init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=Qe(a,l,Je);c!==null&&(await St(i,c,"utf-8"),s.detail("Backfilled new env keys")),await he("update",be),se.intro(`Update from ${o.templateVersion} \u2192 ${be}`);let g=l.AI_AGENT==="codex"?"codex":"claude-code",r=N(Jn(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{s.heading("Downloading the latest Klaudius template");let y=await me({licenseKey:t,machineId:ie(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:g,destDir:r});s.success(`Fetched ${y.filesExtracted} canonical files`),A=r}catch(y){s.error(y.message),s.detail("Update aborted. Your project is unchanged."),await ae(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let h=await Qn(A,n,o),C=h.filter(y=>y.state==="new"),L=h.filter(y=>y.state==="clean-update"),V=h.filter(y=>y.state==="user-only"),D=h.filter(y=>y.state==="conflict"),T=h.filter(y=>y.state==="no-change"),S=h.filter(y=>y.state==="removed-clean"),E=h.filter(y=>y.state==="removed-modified"),v=[...D,...E];if(s.blank(),s.heading("Change summary"),s.detail(`${H(T.length,"file")} unchanged`),s.detail(`${H(C.length,"new file")}`),s.detail(`${H(L.length,"file")} updated cleanly (no local edits)`),s.detail(`${H(V.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${H(S.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${H(D.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${H(E.length,"file")} removed upstream but edited locally (need your decision)`),C.length===0&&L.length===0&&S.length===0&&v.length===0){s.blank(),se.outro(Le.green("Already up to date.")),await ae(r,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let y of[...C,...L]){let j=N(A,y.path),X=N(n,y.path);await It(xt(X),{recursive:!0}),await Ct(j,X),o.files[y.path]=y.canonicalHash}C.length+L.length>0&&s.success(`Wrote ${H(C.length+L.length,"file")}`);for(let y of S){let j=N(n,y.path);await ae(j,{force:!0}),delete o.files[y.path]}if(S.length>0&&s.success(`Deleted ${H(S.length,"file")} removed upstream`),v.length>0){s.blank(),s.heading(`${v.length} conflict(s) need resolution`);let y=N(n,".klaudius","incoming");try{await ae(y,{recursive:!0,force:!0})}catch{}for(let j of D){let X=N(A,j.path),re=N(y,j.path);await It(xt(re),{recursive:!0}),await Ct(X,re)}await St(N(n,".klaudius","conflicts.md"),Zn(v,o.templateVersion,be),"utf-8"),D.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}if(o.updatedAt=new Date().toISOString(),v.length===0&&(o.templateVersion=be),await ce(n,o),s.blank(),v.length===0)se.outro(Le.green("Update complete."));else{let y=g==="codex"?"Codex":"Claude Code";se.outro(Le.yellow(`${v.length} conflict(s) staged. Open ${y} in this project and ask:
|
|
64
|
-
"Run /resolve-conflicts"`))}await
|
|
65
|
-
`)}import{access as
|
|
66
|
-
`)),
|
|
63
|
+
Link a Device, and point it at the QR shown in this terminal.`)),o.blank();for(let d of r.whatsappAccounts){console.log(u.cyan(`Pairing WhatsApp account '${d}'...`)),console.log(u.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${d})`));let h=xt(process.execPath,["scripts/whatsapp.mjs","pair","--account",d],{cwd:s,stdio:"inherit"});h.status===0?o.detail(`Paired '${d}'.`):(console.log(u.yellow(`'${d}' did not pair (exit ${h.status??"signalled"}). You can finish later via:`)),console.log(u.cyan(` npx klaudius@latest pair-whatsapp --label ${d}`))),o.blank()}}else if(E&&!v){o.blank(),console.log(u.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(u.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let d of r.whatsappAccounts)console.log(u.cyan(` npx klaudius@latest pair-whatsapp --label ${d}`))}o.blank();let y=[...T,...V?["schema"]:[]];if(y.length>0){k.outro(u.yellow(u.bold(`Setup paused \u2014 ${y.join(", ")} failed.`))),console.log(u.dim("Your credentials and project files are all saved.")),o.blank();for(let[X,zt]of Object.entries(I))console.log(u.yellow(`Likely cause of ${X} failure:`)),console.log(u.dim(` ${zt}`)),o.blank();let d=s!==process.cwd()?` ${u.cyan(`cd ${e.target}`)}
|
|
64
|
+
`:"",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";T.length>0&&(console.log(u.dim(`Easiest fix \u2014 let ${f} finish it for you:`)),o.blank(),d&&process.stdout.write(d),console.log(` ${u.cyan(h)} ${u.dim(`# open ${f} in this folder`)}`),console.log(u.dim(" Then paste:")),console.log(u.cyan(` "Finish my Klaudius install \u2014 ${T.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),o.blank(),console.log(u.dim(` (Don't have ${f} yet? Install with: \`${A}\`)`)),o.blank(),console.log(u.dim("Or do it yourself:")),o.blank(),d&&process.stdout.write(d),console.log(` ${u.cyan("npx klaudius@latest install")} ${u.dim("# retry the failing installers")}`),console.log(` ${u.cyan("npx klaudius@latest doctor")} ${u.dim("# verify everything")}`),o.blank()),V&&(console.log(u.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${u.cyan(D)}`),console.log(u.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),o.blank()),T.includes("pip")&&!I.pip&&(console.log(u.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(u.dim(`Python 3.10+. Install a newer one from ${rs()}`)),console.log(u.dim("and open a fresh Terminal before retrying.")),o.blank());let z=["npm","playwright","patchright"].filter(X=>T.includes(X)&&!I[X]);if(z.length>0){let X=z.length===1?"keeps":"keep";console.log(u.dim(`If ${z.join(" / ")} ${X} failing with network errors (ECONNRESET,`)),console.log(u.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(u.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),o.blank()}console.log(u.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),o.blank();return}k.outro(u.green(u.bold("Project ready."))),console.log(u.dim("Next steps:")),s!==process.cwd()&&console.log(` ${u.cyan(`cd ${e.target}`)}`);let j=process.platform==="win32"?"start":process.platform==="linux"?"xdg-open":"open",J=u.dim("# read this first \u2014 operator basics + commands");console.log(` ${u.cyan(`${j} DOCS.html`)}${" ".repeat(Math.max(1,17-j.length))}${J}`);let ce=r.aiAgent==="codex"?"codex":"claude",Fe=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(` ${u.cyan(ce)} ${u.dim(`# open ${Fe} in this project`)}`),console.log(` ${u.dim(`then ask ${Fe}:`)}`),console.log(` ${u.cyan(' "Run the pipeline."')}`),o.blank()}async function M(e,n){await Le(e,{recursive:!0}),await $e(q(e,".env"),ue(n),"utf-8"),n.aiAgent==="codex"?(await Le(q(e,".codex"),{recursive:!0}),await $e(q(e,".codex","config.toml"),fe(n),"utf-8")):(await $e(q(e,".mcp.json"),pe(n),"utf-8"),await _e(e,"supabase"))}async function ns(e){try{(await It(e)).isDirectory()||(o.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let n=await Qn(e),s=n.filter(c=>!c.startsWith(".DS_Store"));if(s.length===0)return{kind:"fresh"};let t=new Set([".env",".mcp.json",".claude",".codex"]),i=s.every(c=>t.has(c)),a=s.includes(".env"),l=n.includes(".klaudius");if(i&&a&&!l)return{kind:"partial",envPath:q(e,".env")};if(l&&a){let c=!0;try{c=!(await It(q(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:s}}async function ss(e){o.blank(),o.warn(`Found a partial setup at ${u.bold(e)}.`),o.detail(`A previous init wrote ${u.bold(".env")} but didn't finish scaffolding.`),o.blank();let n=await k.select({message:"How would you like to proceed?",initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return k.isCancel(n)&&(k.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),n}async function os(e){if(e&&e.trim().length>0)return e;k.intro("Klaudius");let n=await k.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:s=>s.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return k.isCancel(n)&&(k.cancel("Setup cancelled. No files written."),process.exit(0)),n}function is(e){let n=ts(e);if(process.platform==="win32"){let s=n.toLowerCase();if(s.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(s.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(s.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(s.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let s=["/System/","/usr/","/bin/","/sbin/"];for(let t of s)if(n.startsWith(t))return`Inside ${t.slice(0,-1)} (system-managed directory).`}}function as(){if(process.platform!=="win32")return!1;try{return xt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function rs(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}import{access as ls,readFile as cs}from"fs/promises";import{join as De,resolve as ds}from"path";import O from"picocolors";async function Nt(e){let n=e.target?ds(process.cwd(),e.target):process.cwd(),s=await Ot(De(n,".env")),t=await Ot(De(n,"package.json"));(!s||!t)&&(o.error("This doesn't look like a Klaudius project."),o.detail(`Path: ${n}`),s||o.detail("Missing: .env"),t||o.detail("Missing: package.json"),o.blank(),o.detail("Run `npx klaudius@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 i="claude-code";try{$(await cs(De(n,".env"),"utf-8")).AI_AGENT==="codex"&&(i="codex")}catch{}o.heading("Installing dependencies");let a=await Te(n);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(O.green(O.bold("All dependencies installed."))),console.log(O.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),o.blank();return}o.blank(),console.log(O.yellow(O.bold(`${l.join(", ")} still failing.`))),o.blank();for(let[r,w]of Object.entries(a.hints??{}))console.log(O.yellow(`Likely cause of ${r} failure:`)),console.log(O.dim(` ${w}`)),o.blank();let c=i==="codex"?"codex":"claude",p=i==="codex"?"Codex":"Claude Code",m=i==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(O.dim("Options:")),console.log(O.dim(` \u2022 Open ${p} in this folder (\`${c}\`) and paste:`)),console.log(O.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(O.dim(` (Don't have ${p} yet? Install with: \`${m}\`)`)),console.log(O.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(O.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),o.blank(),process.exitCode=1}async function Ot(e){try{return await ls(e),!0}catch{return!1}}import{readFile as us,writeFile as Me,access as ps}from"fs/promises";import{join as se}from"path";import*as Ce from"@clack/prompts";import K from"picocolors";import{mkdir as fs}from"fs/promises";async function $t(e){let n=e.projectRoot??process.cwd(),s=se(n,".env"),t=se(n,".mcp.json"),i=se(n,".codex","config.toml"),a=await Ue(se(n,".klaudius","manifest.json")),l=await Ue(s);!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=G();c.ok||(o.error(c.message??"Node.js version check failed."),o.blank(),o.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let p={};try{let g=await us(s,"utf-8");p=$(g)}catch{o.warn("No .env found. Starting from an empty configuration.")}let m=et(p);Ce.intro("Reconfigure Klaudius"),o.detail("Press Enter on any prompt to keep its current value."),o.blank();let r=await S(m),w=m.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==w&&(o.error(`Switching AI coding agent (${w} \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(` ${K.cyan("npx klaudius@latest init <new-folder>")} ${K.dim("# pick the new agent in the wizard")}`),o.blank(),o.detail(".env is unchanged."),process.exit(1)),r.supabaseUrl!==p.SUPABASE_URL||r.supabaseServiceKey!==p.SUPABASE_SERVICE_KEY){o.heading("Re-validating Supabase credentials");let g=await te({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});g.ok||(o.error(g.message??"Supabase check failed"),o.warn("Aborting. .env not modified."),process.exit(1)),o.success("Supabase credentials accepted")}await Me(s,ue(r),"utf-8"),o.success("Updated .env"),r.aiAgent==="codex"?(await fs(se(n,".codex"),{recursive:!0}),await Me(i,fe(r),"utf-8"),o.success("Updated .codex/config.toml")):(await Me(t,pe(r),"utf-8"),o.success("Updated .mcp.json"),await _e(n,"supabase")),o.blank(),Ce.outro(K.green("Configuration updated.")),await ms(n,a)}async function ms(e,n){let s=await Ue(se(e,"node_modules"));o.blank(),n?s||(o.detail("Your project files are in place but dependencies aren't installed yet."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius@latest install")} ${K.dim("# (re-)installs npm + pip + browsers; idempotent")}`),o.blank(),o.detail("Then verify with:"),o.blank(),console.log(` ${K.cyan("npx klaudius@latest doctor")} ${K.dim("# checks Node / Python / installers / credentials")}`),o.blank()):(o.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),o.detail("To finish setup, run:"),o.blank(),console.log(` ${K.cyan("npx klaudius@latest init")} ${K.dim("# pick Resume when prompted")}`),o.blank())}async function Ue(e){try{return await ps(e),!0}catch{return!1}}import{copyFile as Lt,mkdir as Dt,readdir as hs,readFile as gs,rm as le,writeFile as Mt,access as Ut}from"fs/promises";import{dirname as jt,join as N,relative as ys}from"path";import{tmpdir as ks}from"os";import*as oe from"@clack/prompts";import je from"picocolors";var Se="0.17.4";async function Kt(e){let n=e.projectRoot??process.cwd(),s=await st(n);s||(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 y of me)delete s.files[y];let t,i=N(n,".env"),a,l;try{a=await gs(i,"utf-8"),l=$(a)}catch{o.error("Couldn't read .env from this directory."),o.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}t=l.KLAUDIUS_LICENSE_KEY??"",t||(o.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),o.detail("This file is created by `npx klaudius@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=Ze(a,l,Qe);c!==null&&(await Mt(i,c,"utf-8"),o.detail("Backfilled new env keys")),await we("update",Se),oe.intro(`Update from ${s.templateVersion} \u2192 ${Se}`);let m=l.AI_AGENT==="codex"?"codex":"claude-code",r=N(ks(),`klaudius-update-${process.pid}-${Date.now()}`),w;try{o.heading("Downloading the latest Klaudius template");let y=await ke({licenseKey:t,machineId:re(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:m,destDir:r});o.success(`Fetched ${y.filesExtracted} canonical files`),w=r}catch(y){o.error(y.message),o.detail("Update aborted. Your project is unchanged."),await le(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let g=await ws(w,n,s),C=g.filter(y=>y.state==="new"),L=g.filter(y=>y.state==="clean-update"),V=g.filter(y=>y.state==="user-only"),D=g.filter(y=>y.state==="conflict"),T=g.filter(y=>y.state==="no-change"),I=g.filter(y=>y.state==="removed-clean"),E=g.filter(y=>y.state==="removed-modified"),v=[...D,...E];if(o.blank(),o.heading("Change summary"),o.detail(`${F(T.length,"file")} unchanged`),o.detail(`${F(C.length,"new file")}`),o.detail(`${F(L.length,"file")} updated cleanly (no local edits)`),o.detail(`${F(V.length,"file")} you've edited (no upstream change \u2014 left alone)`),o.detail(`${F(I.length,"file")} removed upstream (deleted cleanly)`),o.detail(`${F(D.length,"file")} with conflicts (you edited AND we have a new version)`),o.detail(`${F(E.length,"file")} removed upstream but edited locally (need your decision)`),C.length===0&&L.length===0&&I.length===0&&v.length===0){o.blank(),oe.outro(je.green("Already up to date.")),await le(r,{recursive:!0,force:!0}).catch(()=>{});return}o.blank(),o.heading("Applying clean updates");for(let y of[...C,...L]){let j=N(w,y.path),J=N(n,y.path);await Dt(jt(J),{recursive:!0}),await Lt(j,J),s.files[y.path]=y.canonicalHash}C.length+L.length>0&&o.success(`Wrote ${F(C.length+L.length,"file")}`);for(let y of I){let j=N(n,y.path);await le(j,{force:!0}),delete s.files[y.path]}if(I.length>0&&o.success(`Deleted ${F(I.length,"file")} removed upstream`),v.length>0){o.blank(),o.heading(`${v.length} conflict(s) need resolution`);let y=N(n,".klaudius","incoming");try{await le(y,{recursive:!0,force:!0})}catch{}for(let j of D){let J=N(w,j.path),ce=N(y,j.path);await Dt(jt(ce),{recursive:!0}),await Lt(J,ce)}await Mt(N(n,".klaudius","conflicts.md"),As(v,s.templateVersion,Se),"utf-8"),D.length>0&&o.detail("Staged canonical versions to .klaudius/incoming/"),o.detail("Wrote conflict report to .klaudius/conflicts.md")}if(s.updatedAt=new Date().toISOString(),v.length===0&&(s.templateVersion=Se),await he(n,s),o.blank(),v.length===0)oe.outro(je.green("Update complete."));else{let y=m==="codex"?"Codex":"Claude Code";oe.outro(je.yellow(`${v.length} conflict(s) staged. Open ${y} in this project and ask:
|
|
65
|
+
"Run /resolve-conflicts"`))}await le(r,{recursive:!0,force:!0}).catch(()=>{})}async function ws(e,n,s){let t=await Ft(e),i=new Set(t),a=[];for(let l of t){let c=await ee(N(e,l)),p=s.files[l],m=N(n,l),r;try{await Ut(m),r=await ee(m)}catch{a.push({path:l,state:"new",canonicalHash:c,manifestHash:p});continue}c===p?r===p?a.push({path:l,state:"no-change",canonicalHash:c,localHash:r,manifestHash:p}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:r,manifestHash:p}):r===p?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:r,manifestHash:p}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:r,manifestHash:p})}for(let l of Object.keys(s.files)){if(i.has(l))continue;let c=s.files[l],p=N(n,l),m;try{await Ut(p),m=await ee(p)}catch{delete s.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 F(e,n){return`${e} ${n}${e===1?"":"s"}`}async function Ft(e,n=e){let s=await hs(e,{withFileTypes:!0}),t=[];for(let i of s){let a=N(e,i.name);i.isDirectory()?t.push(...await Ft(a,n)):i.isFile()&&t.push(ys(n,a))}return t}function As(e,n,s){let t=e.filter(c=>c.state==="conflict").length,i=e.filter(c=>c.state==="removed-modified").length,a=[];a.push("# Update Conflicts"),a.push(""),a.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),a.push(`Updating from canonical version **${n}** to **${s}**.`),a.push("");let l=[];t>0&&l.push(`${t} file${t===1?"":"s"} ha${t===1?"s":"ve"} BOTH local edits AND upstream changes`),i>0&&l.push(`${i} file${i===1?"":"s"} ${i===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(`
|
|
66
|
+
`)}import{access as Es,readFile as Ht,stat as Ps}from"fs/promises";import{join as U}from"path";import R from"picocolors";import{spawn as Vt}from"child_process";async function Gt(e){let n=e.projectRoot??process.cwd(),s=[];console.log(R.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
67
|
+
`)),s.push(await bs()),s.push(await Ts());let t=U(n,".env"),i=U(n,".klaudius","manifest.json"),a=U(n,".mcp.json"),l=U(n,".codex","config.toml"),c=await W(t),p=await W(i),m="claude-code";if(c)try{$(await Ht(t,"utf-8")).AI_AGENT==="codex"&&(m="codex")}catch{}if(m==="claude-code"){let g=await W(U(n,"AGENTS.md")),C=!await W(U(n,".claude"));g&&C&&(m="codex")}if(s.push({name:".env present",status:c?"ok":"fail",detail:c?t:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."}),s.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?"ok":"fail",detail:p?i:"missing",nextAction:p?void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."}),m==="codex"){let g=await W(l);s.push({name:".codex/config.toml present",status:g?"ok":"warn",detail:g?l:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let g=await W(a);s.push({name:".mcp.json present",status:g?"ok":"warn",detail:g?a:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(s.push(await Rs(m)),s.push(await _s(n)),s.push(await Cs(n)),s.push(await Ss()),!c)s.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)s.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let g=await Ht(t,"utf-8"),C=$(g);await Is(C,s)}console.log();for(let g of s){let C=g.status==="ok"?R.green("\u2713"):g.status==="warn"?R.yellow("\u26A0"):g.status==="skip"?R.dim("\xB7"):R.red("\u2717");console.log(` ${C} ${g.name}${g.detail?R.dim(` \u2014 ${g.detail}`):""}`),g.nextAction&&console.log(` ${R.dim("\u2192")} ${R.cyan(g.nextAction)}`)}let r=s.filter(g=>g.status==="fail").length,w=s.filter(g=>g.status==="warn").length;console.log(),r===0&&w===0?console.log(R.green(R.bold("Everything checks out. You're good to go."))):r===0?console.log(R.yellow(R.bold(`${w} warning${w===1?"":"s"} \u2014 review above.`))):(console.log(R.red(R.bold(`${r} failed check${r===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function W(e){try{return await Es(e),!0}catch{return!1}}async function bs(){let e=await Z();return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:"Install Python 3.10+ from https://www.python.org/downloads/"}}async function Ts(){let e=process.version,n=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!n)return{name:"Node \u2265 22.15",status:"warn",detail:e};let s=parseInt(n[1],10),t=parseInt(n[2],10);return s<22||s===22&&t<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function _s(e){let n=U(e,"node_modules");if(!await W(n))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await Ps(n)).isDirectory())return{name:"node_modules installed",status:"warn",detail:"exists but isn't a directory"}}catch{}return{name:"node_modules installed",status:"ok"}}async function Cs(e){let n=process.platform==="darwin"?U(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?U(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):U(process.env.HOME??"",".cache","ms-playwright");return await W(n)?{name:"Playwright browser installed",status:"ok",detail:n}:{name:"Playwright browser installed",status:"fail",detail:"no browser cache found",nextAction:"Run `npx playwright install chromium` in this folder."}}async function Ss(){let e=["supabase","dotenv","requests","httpx","PIL"],n=`import sys
|
|
67
68
|
try:
|
|
68
|
-
${e.map(
|
|
69
|
+
${e.map(a=>` import ${a}`).join(`
|
|
69
70
|
`)}
|
|
70
71
|
except Exception as e:
|
|
71
72
|
print(str(e))
|
|
72
73
|
sys.exit(1)
|
|
73
|
-
`,
|
|
74
|
-
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function
|
|
75
|
-
`)[0]}:{name:
|
|
76
|
-
`));let a=
|
|
74
|
+
`,s=await ae();if(!s)return{name:"Python packages installed",status:"fail",detail:"no Python interpreter found (tried python3, python, py -3)",nextAction:"Fix the Python check above first \u2014 the packages live inside that interpreter."};let t=s.command,i=await Bt(t[0],[...t.slice(1),"-c",n]);return i.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(i.stdout||i.stderr).trim().split(`
|
|
75
|
+
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function Is(e,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let t=await te({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});n.push({name:"Supabase credentials",status:t.ok?"ok":"fail",detail:t.ok?"connected":t.message,nextAction:t.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else n.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});let s=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":"vercel";if(s==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let t=await Ee({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});n.push({name:"Cloudflare token + account",status:t.ok?"ok":"fail",detail:t.ok?`valid (${t.projectCount??0} Pages project${t.projectCount===1?"":"s"})`:t.message,nextAction:t.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius@latest configure`."})}else n.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Cloudflare."});else if(s==="netlify")if(e.NETLIFY_AUTH_TOKEN){let t=await Pe({token:e.NETLIFY_AUTH_TOKEN});n.push({name:"Netlify token",status:t.ok?"ok":"fail",detail:t.ok?t.accountSlug?`valid (team: ${t.accountSlug})`:"valid":t.message,nextAction:t.ok?void 0:"Fix the token at https://app.netlify.com/user/applications#personal-access-tokens, then `npx klaudius@latest configure`."})}else n.push({name:"Netlify token",status:"fail",detail:"NETLIFY_AUTH_TOKEN missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Netlify."});else if(e.VERCEL_TOKEN){let t=await Ae(e.VERCEL_TOKEN);n.push({name:"Vercel token",status:t.ok?"ok":"fail",detail:t.ok?t.username??"valid":t.message,nextAction:t.ok?void 0:"Generate a new token at https://vercel.com/account/tokens, then `npx klaudius@latest configure`."})}else n.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let t=await be(e.GOOGLE_PLACES_API_KEY);n.push({name:"Google Places API key",status:t.ok?"ok":"fail",detail:t.ok?"accepted":t.message,nextAction:t.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius@latest configure`."})}else n.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let t=await Be({botToken:e.TELEGRAM_BOT_TOKEN});n.push({name:"Telegram bot token",status:t.ok?"ok":"fail",detail:t.ok?`bot ${t.botHandle??"ok"} (chat_id not tested)`:t.message,nextAction:t.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?n.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):n.push({name:"Telegram credentials",status:"skip",detail:"not configured (optional)"})}async function Rs(e){let n=e==="codex"?"codex":"claude",s=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",t=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",i=await Bt(n,["--version"],process.platform==="win32");return i.code===0?{name:s,status:"ok",detail:(i.stdout||i.stderr).trim().split(`
|
|
76
|
+
`)[0]}:{name:s,status:"warn",detail:"not found",nextAction:t}}function Bt(e,n,s=!1){return new Promise(t=>{let i=s?Vt([e,...n].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Vt(e,n,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";i.stdout?.on("data",c=>{a+=c.toString()}),i.stderr?.on("data",c=>{l+=c.toString()}),i.on("close",c=>t({code:c??1,stdout:a,stderr:l})),i.on("error",()=>t({code:1,stdout:a,stderr:l}))})}import{existsSync as xs}from"fs";import{spawnSync as vs}from"child_process";import{join as Os,resolve as Ns}from"path";import x from"picocolors";async function Yt(e){let n=Ns(e.projectRoot??process.cwd()),s=Os(n,"scripts","whatsapp.mjs");xs(s)||(console.error(x.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(x.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(x.dim(`Looked for: ${s}`)),process.exit(1));let t=(e.label??"primary").trim(),i=t.replace(/[^A-Za-z0-9_-]/g,"");i||(console.error(x.red(`Invalid label '${t}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),i!==t&&console.error(x.yellow(`Note: cleaned label '${t}' \u2192 '${i}' (filename-safe characters only).`)),console.log(x.cyan(`Pairing WhatsApp account '${i}'...`)),console.log(x.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
|
|
77
|
+
`));let a=vs(process.execPath,[s,"pair","--account",i],{cwd:n,stdio:"inherit"});if(a.status===0){console.log(x.green(`Paired '${i}'.`)),console.log(x.dim(`
|
|
77
78
|
If you haven't already, add '${i}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
78
79
|
WHATSAPP_ACCOUNTS=primary,${i}
|
|
79
|
-
(Skip this if '${i}' is already there or you set it via the init wizard.)`));return}a.error?console.error(x.red(`Pair failed: ${a.error.message}`)):(console.error(x.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(x.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(x.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(x.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${i}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as
|
|
80
|
+
(Skip this if '${i}' is already there or you set it via the init wizard.)`));return}a.error?console.error(x.red(`Pair failed: ${a.error.message}`)):(console.error(x.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(x.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(x.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(x.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${i}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as $s}from"child_process";var Ke="--use-system-ca";function Wt(){let e=process.env.NODE_OPTIONS??"";if(e.includes(Ke)||!G().ok)return;let s=e?`${e} ${Ke}`:Ke,t=$s(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:s},stdio:"inherit"});t.signal&&(process.kill(process.pid,t.signal),process.exit(1)),process.exit(t.status??1)}Wt();var Ds="0.17.4",H=new Ls;H.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Ds);H.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 qe({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});H.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").action(async(e,n)=>{try{await vt({target:e,license:n.license,skipInstall:!!n.skipInstall,skipSchema:!!n.skipSchema})}catch(s){console.error("init failed:",s.message),process.exit(1)}});H.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 Nt({target:e})}catch(n){console.error("install failed:",n.message),process.exit(1)}});H.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await $t({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});H.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await Kt({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});H.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 Gt({offline:!!e.offline})}catch(n){console.error("doctor failed:",n.message),process.exit(1)}});H.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 Yt({label:e.label})}catch(n){console.error("pair-whatsapp failed:",n.message),process.exit(1)}});H.parse(process.argv);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.17.
|
|
3
|
+
"version": "0.17.4",
|
|
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": {
|
package/dist/chunk-ZTT5HVYU.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{copyFile as M,mkdir as L,readdir as P,stat as h}from"fs/promises";import{dirname as w,join as n,relative as T}from"path";import{fileURLToPath as j}from"url";import{createHash as y}from"crypto";import{readFile as x}from"fs/promises";async function f(t){let r=await x(t);return y("sha256").update(r).digest("hex")}import{mkdir as F,readFile as S,writeFile as R,access as A}from"fs/promises";import{dirname as E,join as m}from"path";var v=".klaudius",d=`${v}/manifest.json`,g=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml"]);async function O(t){let r=m(t,d);try{await A(r)}catch{return null}let e=await S(r,"utf-8");return JSON.parse(e)}async function k(t,r){let e=m(t,d);await F(E(e),{recursive:!0}),await R(e,JSON.stringify(r,null,2)+`
|
|
2
|
-
`,"utf-8")}function H(t,r){let e=new Date().toISOString();return{version:1,templateVersion:t,installedAt:e,updatedAt:e,files:r}}async function V(){let t=w(j(import.meta.url)),r=[n(t,"..","template"),n(t,"..","..","..","template"),n(t,"..","..","template")];for(let e of r)try{if((await h(e)).isDirectory())return e}catch{}throw new Error(`Could not find template directory. Searched:
|
|
3
|
-
${r.map(e=>" "+e).join(`
|
|
4
|
-
`)}`)}async function l(t,r=t){let e=await P(t,{withFileTypes:!0}),i=[];for(let s of e){let o=n(t,s.name);s.isDirectory()?i.push(...await l(o,r)):s.isFile()&&i.push(T(r,o))}return i}async function q(t,r,e={}){let i=e.overwrite??!1,s=await l(t),o={},u=0;for(let a of s){let p=n(t,a),c=n(r,a);if(o[a]=await f(p),!i)try{await h(c);continue}catch{}await L(w(c),{recursive:!0}),await M(p,c),u++}return{filesCopied:u,fileHashes:o}}async function z(t){let r=await l(t),e={};for(let i of r)g.has(i)||(e[i]=await f(n(t,i)));return e}export{f as a,g as b,O as c,k as d,H as e,V as f,l as g,q as h,z as i};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as a,g as b,h as c,i as d}from"./chunk-ZTT5HVYU.js";export{c as copyTemplate,d as hashAllFiles,a as locateTemplateRoot,b as walkFiles};
|