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