klaudius 0.26.0 → 0.27.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +44 -44
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,113 +1,113 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as ue,c as Re,d as
|
|
3
|
-
`));let t=[];t.push(
|
|
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
|
|
2
|
+
import{b as ue,c as Re,d as B,e as _,f as _t,g as It,h as xe,i as Oe,j as se,k as Ct,l as Rt,o as xt,q as pe,r as Ne,s as R}from"./chunk-ABFQ7C7Q.js";import{Command as uo}from"commander";import{spawn as vt}from"child_process";import{existsSync as is}from"fs";import{homedir as os}from"os";import I from"picocolors";import{win32 as Gn}from"path";var Bn=["&","^","%","!"];function Vn(e){return Bn.filter(t=>e.includes(t))}function fe(e){let t=[];for(let{label:n,path:s}of e){let o=Vn(s);o.length>0&&t.push({label:n,path:s,chars:o})}return t}function Yn(e){let t=(e??"").trim().replace(/^["']|["']$/g,"");if(!t||t==="undefined"||t==="null")return null;let n=t.toLowerCase().split(/[\\/]/);if(n.length<2||n.includes("system32"))return null;let s=Gn.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(s)?t:null}function he(e,t){let n=Yn(e);return n===null?!1:t?t(n):!0}function me(e,t){let n=e[0],s=[...new Set(e.flatMap(u=>u.chars))],o=s.map(u=>`"${u}"`).join(", "),r=s.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${o} in it ${r?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${r?"will":"may"} fail here with a misleading demand to install Visual Studio \u2014 Visual Studio is NOT needed and installing it will not fix this. Instead point npm's build steps at a shell that parses these paths correctly: PowerShell 7 (pwsh) or Git Bash, whichever is installed \u2014 npm config set script-shell "<full path to pwsh.exe or bash.exe>" (applies to all npm projects on this machine) \u2014 ${t==="preflight"?'then re-run this preflight \u2014 the "Install path safe for npm builds" check passes once script-shell is set.':t==="doctor"?"then re-run doctor \u2014 this check passes once script-shell is set.":'then re-run `npx klaudius@latest install`; `npx klaudius@latest doctor` confirms the fix (its "Install path safe for npm builds" check passes once script-shell is set).'} Windows PowerShell 5.1 ("powershell") will NOT work: it can't run the "||" in packages' install scripts. If neither shell is installed, PowerShell 7 is a small download: winget install Microsoft.PowerShell. If only the PROJECT folder is affected (not the user folder), moving the project to a plain path like C:\\klaudius also fixes it, or scope the npm setting to just this project by adding --location=project (run inside the project folder).`}}function ie(){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 n=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10),r=`${n}.${s}.${o}`;return n<22||n===22&&s<15?{ok:!1,version:r,major:n,minor:s,message:`Your installed Node.js is ${r}. 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:r,major:n,minor:s}}import{spawn as Wn}from"child_process";import{existsSync as zn}from"fs";import{homedir as qn}from"os";import{delimiter as Qn,join as ve}from"path";var Xn=new Set(["Restricted","AllSigned"]);function Jn(e,t=zn){for(let n of e.split(Qn)){let s=n.replace(/"/g,"");if(!s)continue;let o=ve(s,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let c=ve(s,r);if(t(c))return{path:c,isPs1:!1}}}return null}async function Nt(){let e=Jn(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Zn();if(!t)return{blocked:!1,shimPath:e.path};let n=ve(qn(),".local","node")+"\\";return{blocked:Xn.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Zn(){let e=ve(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await Ot(e)??await Ot("powershell.exe")}function Ot(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let s=Wn(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",r=setTimeout(()=>{s.kill(),n(null)},8e3);s.stdout.on("data",c=>{o+=c.toString()}),s.stderr?.resume(),s.on("close",c=>{clearTimeout(r),n(c===0&&o.trim()?o.trim():null)}),s.on("error",()=>{clearTimeout(r),n(null)})})}import{spawn as es}from"child_process";var be=3,Le=10,ts=[["python3"],["python"],["py","-3"]];async function z(){for(let e of ts){let t=await ss(e[0],[...e.slice(1),"--version"]),n=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(n)||t.code!==0)continue;let s=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!s)continue;let o=parseInt(s[1],10),r=parseInt(s[2],10),c=s[3]?`${o}.${r}.${s[3]}`:`${o}.${r}`;return{command:[...e],version:c,major:o,minor:r}}return null}async function ge(){let e=ns(),t=await z();if(!t){let c=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 ${be}.${Le}+ is not installed (or not on PATH). Install it from ${e}.`+c}}let{command:n,version:s,major:o,minor:r}=t;return o<be||o===be&&r<Le?{ok:!1,version:s,major:o,minor:r,command:n,message:`Your installed Python is ${s}. Klaudius needs Python ${be}.${Le} or newer (the pipeline depends on packages that only ship wheels for ${be}.${Le}+). 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:s,major:o,minor:r,command:n}}function ns(){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 ss(e,t){return new Promise(n=>{let s=es(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",c=>{o+=c.toString()}),s.stderr?.on("data",c=>{r+=c.toString()}),s.on("close",c=>n({code:c??1,stdout:o,stderr:r})),s.on("error",()=>n({code:1,stdout:o,stderr:r}))})}var Lt=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function $t(e={}){console.log(I.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
|
+
`));let t=[];t.push(as());let n=await ge();if(t.push(rs(n)),t.push(await ls(n.command)),t.push(await cs()),process.platform==="win32"){let o=await ds();o&&t.push(o);let r=await us();r&&t.push(r)}t.push(await ps());for(let o of t){let r=o.status==="ok"?I.green("\u2713"):o.status==="warn"?I.yellow("!"):I.red("\u2717");console.log(` ${r} ${o.name}${o.detail?I.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${I.dim("\u2192")} ${I.cyan(o.nextAction)}`)}console.log();let s=t.filter(o=>o.status==="fail");if(s.length===0){let o=t.filter(r=>r.status==="warn").length;fs(o);return}console.log(I.red(I.bold(`${s.length} check${s.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(I.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(I.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function as(){let e=ie();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 rs(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 ls(e){let t=e??["python3"],n=await $e(t[0],[...t.slice(1),"-m","pip","--version"]);return n.code===0?{name:"pip available",status:"ok",detail:(n.stdout||n.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 cs(){let e=process.platform==="win32",t=await $e("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 $e("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 ds(){let e=await Nt();if(e.npxMissing)return null;let t="npx runs in PowerShell";if(!e.blocked){let n="resolves to a policy-immune shim";return e.shimPath&&(n=e.policy?`ExecutionPolicy ${e.policy} allows the npx.ps1 shim`:"npx.ps1 shim present but ExecutionPolicy unreadable \u2014 assuming it runs"),{name:t,status:"ok",detail:n}}return{name:t,status:"fail",detail:`ExecutionPolicy ${e.policy} blocks ${e.shimPath}, which PowerShell prefers over npx.cmd`,nextAction:e.ownInstall?`In PowerShell run: Remove-Item "$env:USERPROFILE\\.local\\node\\np*.ps1" \u2014 it deletes only the PowerShell shims from Klaudius's own Node install (npx falls back to npx.cmd). It prints nothing back; that means it worked. Then re-run this preflight.`:"In Windows PowerShell (the classic blue one, not PowerShell 7) run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned \u2014 printing nothing back means it worked; confirm with Get-ExecutionPolicy (should say RemoteSigned), then re-run this preflight. If it prints an error instead, your organisation manages this setting \u2014 ask IT."}}async function us(){let e=fe([{label:"your Windows user folder",path:os()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await $e("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(he(s,is))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(l=>`"${l}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=me(e,"preflight"),c=e.some(l=>l.chars.includes("&"));return{name:t,status:c?"fail":"warn",detail:o,nextAction:r}}async function ps(){try{return await fetch(Lt,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:Lt}}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 fs(e=0){e>0?console.log(I.green(I.bold("Your machine is ready."))+I.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(I.green(I.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(I.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(` ${I.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(I.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(I.dim(" run it in a new terminal.")),console.log()}function $e(e,t,n=!1){return new Promise(s=>{let o=n?vt([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):vt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",c="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{c+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:c})),o.on("error",()=>s({code:1,stdout:r,stderr:c}))})}import{mkdir as ht,readdir as _n,readFile as Sn,stat as mt,writeFile as ft}from"fs/promises";import{spawnSync as gt}from"child_process";import{homedir as gi}from"os";import{resolve as yi,isAbsolute as ki,join as V,normalize as wi}from"path";import*as E from"@clack/prompts";import p from"picocolors";var rt="claude-code",lt="gpt-5.6-terra";function Mt(e){if(e==="claude-code"||e==="codex")return e}var hs=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function Me(e){let t=e?.trim().toLowerCase()??"";return hs.includes(t)?t:void 0}function De(e){let t=e?.trim().toLowerCase();if(t==="on"||t==="true"||t==="yes"||t==="1")return"on";if(t==="off"||t==="false"||t==="no"||t==="0")return"off"}var ct="vercel";function Dt(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function Ht(e){if(e==="telegram"||e==="email"||e==="sms")return e}function Ut(e){if(e==="password"||e==="oauth-microsoft")return e}function ms(e){if(e==="custom"||e!==void 0&&Object.hasOwn(B,e))return e}function He(e){let t=ms(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[s,o]of Object.entries(B))if(o.smtpHost===n)return s;return"custom"}}function jt(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let s of t.split(",")){let o=s.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(s=>{let o=/^[a-z0-9_]+$/.test(s)&&s!=="auto",r=l=>{let d=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`];return d?.trim()?d.trim():void 0},c=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(l=>!r(l)).map(l=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`);for(let l of["SMTP_PORT","IMAP_PORT"]){let d=r(l);d!==void 0&&!/^\d+$/.test(d)&&c.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`)}return{label:s,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:c,smtpHost:r("SMTP_HOST"),smtpPort:parseInt(r("SMTP_PORT")??"587",10),imapHost:r("IMAP_HOST"),imapPort:parseInt(r("IMAP_PORT")??"993",10),password:r("PASSWORD")}})}function Ue(e){let t=[],n=l=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${l}`),t.push("# "+"=".repeat(60)),t.push("")},s=(l,d)=>{if(d==null||d===""){t.push(`# ${l}=`);return}let u=String(d);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(u)){let a=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${l}="${a}"`)}else t.push(`${l}=${u}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),s("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),s("AI_AGENT",e.aiAgent??rt),s("AI_PLAN",e.aiPlan),s("QA_PHASE",e.qaPhase??pe(e.aiPlan)),n("Operating country and language"),s("OPERATOR_COUNTRY",e.country),s("OPERATOR_COUNTRY_CODE",e.countryCode),s("OPERATOR_LANGUAGE",e.language),s("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let o=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];s("PIPELINE_MODES",[...new Set(["classic",...o])].join(",")),n("Pricing"),s("PRICING",e.pricing),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",e.pricingMonthly),n("Automated outreach features"),s("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),s("OPERATOR_NAME",e.name),s("SIGNATURE",e.signature),s("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),s("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),s("EMAIL_PROVIDER",e.emailProvider),s("EMAIL_AUTH",e.emailAuth??"password"),s("EMAIL_ADDRESS",e.emailAddress),s("EMAIL_PASSWORD",e.emailPassword),s("EMAIL_FROM_NAME",e.emailFromName),s("EMAIL_SMTP_HOST",e.emailSmtpHost),s("EMAIL_SMTP_PORT",e.emailSmtpPort),s("EMAIL_IMAP_HOST",e.emailImapHost),s("EMAIL_IMAP_PORT",e.emailImapPort),s("EMAIL_SENT_FOLDER",e.emailSentFolder),s("EMAIL_INBOX_FOLDER",e.emailInboxFolder),n("SMS outreach"),s("SMS_PROVIDER",e.smsProvider),s("TEST_PHONE",e.testPhone),s("TWILIO_ACCOUNT_SID",e.twilioAccountSid),s("TWILIO_AUTH_TOKEN",e.twilioAuthToken),s("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),s("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Letter outreach"),s("LETTER_PROVIDER",e.letterProvider??"none"),s("PINGEN_CLIENT_ID",e.pingenClientId),s("PINGEN_CLIENT_SECRET",e.pingenClientSecret),s("PINGEN_ORG_ID",e.pingenOrgId),s("POSTGRID_API_KEY",e.postgridApiKey),n("Supabase (pipeline state)"),s("SUPABASE_URL",e.supabaseUrl),s("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),s("SUPABASE_ANON_KEY",e.supabaseAnonKey),s("SUPABASE_PAT",e.supabasePat),s("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),s("DEPLOY_PROVIDER",e.deployProvider??ct),s("VERCEL_TOKEN",e.vercelToken),s("VERCEL_SCOPE",e.vercelScope??""),s("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),s("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),s("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),s("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),s("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),s("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),s("NOTIFY_CHANNEL",e.notifyChannel),s("NOTIFY_TO",e.notifyTo),s("TELEGRAM_BOT_TOKEN",e.telegramBotToken),s("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(l=>/^#?\s*([A-Z0-9_]+)=/.exec(l)?.[1]).filter(l=>!!l)),c=Object.entries(e.preservedEnv??{}).filter(([l])=>!r.has(l));if(c.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[l,d]of c)s(l,d)}return t.join(`
|
|
5
5
|
`)+`
|
|
6
6
|
`}function je(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)+`
|
|
7
|
-
`}function Fe(e){let t=e.supabaseProjectRef,n=
|
|
8
|
-
`)}function
|
|
7
|
+
`}function Fe(e){let t=e.supabaseProjectRef,n=gs(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.","",...e.aiPlan==="codex-plus"?["# Set by the wizard for ChatGPT Plus. Change or delete to use Codex's default.",`model = "${lt}"`,""]:[],"[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${t}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${n}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
|
|
8
|
+
`)}function gs(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Ft=[{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:"PIPELINE_MODES",value:"classic",comment:"Lead streams the pipeline targets. Pre-modes installs targeted no-website businesses only ('classic') \u2014 this records that explicitly. Add 'rescue' (businesses whose existing website is verifiably dead or bad) and/or 'booking' (businesses whose Google-listed website is a booking-platform page) \u2014 e.g. 'classic,rescue,booking' \u2014 or re-run `npx klaudius@latest configure`."},{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.'},{key:"NOTIFY_CHANNEL",value:"telegram",comment:"How scripts/notify.sh routes pipeline alerts: 'telegram' (default), 'email' (to your own inbox), or 'sms' (to your own phone). Pre-NOTIFY_CHANNEL installs alerted via Telegram, so this records that explicitly. NOTIFY_TO optionally overrides the email/sms destination."},{key:"QA_PHASE",value:"on",comment:"'on' runs the independent QA pass after each build (the behaviour this install already had); 'off' goes straight from build to deploy for more sites per usage window. Flip it here any time, or run `npx klaudius@latest configure` and pick your plan to get the matching default."}];function ys(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function Kt(e,t,n){let s=n.filter(c=>!(c.key in t));if(s.length===0)return null;let o=e.endsWith(`
|
|
9
9
|
`)?"":`
|
|
10
|
-
`,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let c of
|
|
10
|
+
`,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let c of s)r.push(""),c.comment&&r.push(`# ${c.comment}`),r.push(ys(c.key,c.value));return e+o+r.join(`
|
|
11
11
|
`)+`
|
|
12
|
-
`}function
|
|
13
|
-
`)){let
|
|
14
|
-
`,"utf-8")}function Qt(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function le(e,t=e){let n=await
|
|
15
|
-
`+oe.bold(oe.cyan(e))),detail:e=>console.log(oe.dim(" "+e))};var
|
|
16
|
-
`)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":
|
|
12
|
+
`}function ks(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function H(e){let t={};for(let n of e.split(`
|
|
13
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),c=ks(s.slice(o+1).trim());t[r]=c}return t}function Gt(e){let t=l=>{let d=e[l];if(!d)return;let u=parseInt(d,10);return isNaN(u)?void 0:u},n=e.SMS_PROVIDER,s=l=>l==="email"||l==="sms"||l==="whatsapp"||l==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(l=>l.trim()).filter(s),r=e.OUTREACH_PRIORITY?.split(",").map(l=>l.trim()).filter(s),c=e.WHATSAPP_ACCOUNTS?.split(",").map(l=>l.trim()).filter(l=>l.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Mt(e.AI_AGENT)??rt,aiPlan:Me(e.AI_PLAN),qaPhase:De(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:r&&r.length>0?r:void 0,whatsappAccounts:c&&c.length>0?c:void 0,emailProvider:He(e),emailAuth:Ut(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:n==="imessage"||n==="twilio"?n:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:Dt(e.DEPLOY_PROVIDER)??ct,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN||void 0,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID||void 0,netlifyAuthToken:e.NETLIFY_AUTH_TOKEN||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:e.SELFHOST_DEPLOY_TARGET||void 0,selfhostUrlTemplate:e.SELFHOST_URL_TEMPLATE||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,emailPassword:e.EMAIL_PASSWORD,notifyChannel:Ht(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function dt(e){let t=S=>{let ne=e[S];if(!ne)return;let D=parseInt(ne,10);return isNaN(D)?void 0:D},n=e.SUPABASE_URL,s=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),r=e.SUPABASE_PROJECT_REF,c=e.PRICING,l=e.PRICING_TERMS||"one-off, no monthly fees",d=Dt(e.DEPLOY_PROVIDER)??ct,u=e.VERCEL_TOKEN,a=e.CLOUDFLARE_API_TOKEN,y=e.CLOUDFLARE_ACCOUNT_ID,g=e.NETLIFY_AUTH_TOKEN,k=e.SELFHOST_DEPLOY_TARGET,P=e.SELFHOST_URL_TEMPLATE;if(!c||!n||!s||!o||!r||!(d==="cloudflare"?!!a&&!!y:d==="netlify"?!!g:d==="selfhost"?!!k&&!!P:!!u))return null;let x=e.SMS_PROVIDER,N=S=>S==="email"||S==="sms"||S==="whatsapp"||S==="letter",T=e.OUTREACH_CHANNELS?.split(",").map(S=>S.trim()).filter(N),W=e.OUTREACH_PRIORITY?.split(",").map(S=>S.trim()).filter(N),G=e.WHATSAPP_ACCOUNTS?.split(",").map(S=>S.trim()).filter(S=>S.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Mt(e.AI_AGENT)??rt,aiPlan:Me(e.AI_PLAN),qaPhase:De(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(S=>S.trim().toLowerCase()).filter(Boolean):void 0,pricing:c,pricingTerms:l,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:T&&T.length>0?T:void 0,outreachPriority:W&&W.length>0?W:void 0,whatsappAccounts:G&&G.length>0?G:void 0,emailProvider:He(e),emailAuth:Ut(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,smsProvider:x==="imessage"||x==="twilio"?x:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,deployProvider:d,vercelToken:u,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:a||void 0,cloudflareAccountId:y||void 0,netlifyAuthToken:g||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:k||void 0,selfhostUrlTemplate:P||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:Ht(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Ko,mkdir as Go,readdir as _s,stat as Bo}from"fs/promises";import{dirname as Yo,join as Xt,relative as Is,sep as Cs}from"path";import{fileURLToPath as zo}from"url";import{createHash as Bt}from"crypto";import{readFile as ws}from"fs/promises";async function ye(e){let t=await ws(e);return Bt("sha256").update(t).digest("hex")}function Vt(e){return Bt("sha256").update(e).digest("hex")}import{mkdir as As,readFile as Es,writeFile as Ps,access as Ss}from"fs/promises";import{dirname as bs,join as Yt}from"path";var Ts=".klaudius",Wt=`${Ts}/manifest.json`,Ke=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml",".ms-token.json"]),zt=new Set(["clients/README.md"]);async function qt(e){let t=Yt(e,Wt);try{await Ss(t)}catch{return null}let n=await Es(t,"utf-8"),s=JSON.parse(n),o={};for(let[r,c]of Object.entries(s.files??{}))o[r.split("\\").join("/")]=c;return s.files=o,Array.isArray(s.ignored)?s.ignored=s.ignored.filter(r=>typeof r=="string").map(r=>r.split("\\").join("/")):delete s.ignored,s}async function Ge(e,t){let n=Yt(e,Wt);await As(bs(n),{recursive:!0}),await Ps(n,JSON.stringify(t,null,2)+`
|
|
14
|
+
`,"utf-8")}function Qt(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function le(e,t=e){let n=await _s(e,{withFileTypes:!0}),s=[];for(let o of n){let r=Xt(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await le(r,t)):o.isFile()&&s.push(Is(t,r).split(Cs).join("/")))}return s}async function Jt(e){let t=await le(e),n={};for(let s of t)Ke.has(s)||(n[s]=await ye(Xt(e,s)));return n}import{copyFile as Rs,mkdir as Zt,mkdtemp as xs,readdir as en,rm as tn}from"fs/promises";import{tmpdir as Os}from"os";import{dirname as Ns,join as Be}from"path";import{Readable as vs}from"stream";import*as nn from"tar";var Ls="https://klaudius.dev/api/template";function $s(e){return vs.fromWeb(e)}async function Ve(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Ls,n="0.27.1",s;try{s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(l){throw new Error(`Could not reach klaudius.dev to download the template: ${_(l)}`)}if(!s.ok){let l="";try{let d=await s.json();l=d.reason?` (${d.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${l}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),r=await xs(Be(Os(),"klaudius-template-")),c=0;try{try{await new Promise((u,a)=>{let y=nn.extract({cwd:r,strict:!0});y.on("finish",u),y.on("error",a),$s(s.body).on("error",a).pipe(y)})}catch(u){throw new Error(`Failed to extract template archive: ${u.message}`)}await Zt(e.destDir,{recursive:!0});let l=new Set(await en(e.destDir)),d=await le(r);try{for(let u of d){let a=Be(e.destDir,u);await Zt(Ns(a),{recursive:!0}),await Rs(Be(r,u),a),c++}}catch(u){let a=await en(e.destDir).catch(()=>[]);for(let y of a)l.has(y)||await tn(Be(e.destDir,y),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${u.message}`)}}finally{await tn(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:c,tier:o}}import{copyFile as Ms,mkdir as Ds,readFile as Hs,rm as Us}from"fs/promises";import{dirname as js,join as Te}from"path";import{structuredPatch as Fs}from"diff";var sn=Te(".klaudius","base");async function Ye(e,t,n){let s=Te(e,sn);await Us(s,{recursive:!0,force:!0});for(let o of n){let r=Te(s,o);await Ds(js(r),{recursive:!0}),await Ms(Te(t,o),r)}}async function on(e,t){try{return await Hs(Te(e,sn,t),"utf-8")}catch{return null}}function ut(e){return e.includes("\0")||e.includes("\uFFFD")}function an(e,t,n=60){let s=Fs("base","new",e,t,"","",{context:2});if(s.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=s.hunks.map(d=>`${d.newStart}-${d.newStart+Math.max(d.newLines-1,0)}`).join(", "),r=[`Upstream changed ${s.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],c=0,l=!1;for(let d of s.hunks){if(c>=n){l=!0;break}r.push(`@@ -${d.oldStart},${d.oldLines} +${d.newStart},${d.newLines} @@`),c+=1;let u=Math.max(n-c,0),a=d.lines.slice(0,u);if(r.push(...a),c+=a.length,a.length<d.lines.length){l=!0;break}}return r.push("```"),l&&r.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),r}import oe from"picocolors";var i={info:e=>console.log(oe.cyan("\u2139"),e),success:e=>console.log(oe.green("\u2713"),e),warn:e=>console.log(oe.yellow("\u26A0"),e),error:e=>console.error(oe.red("\u2717"),e),step:e=>console.log(oe.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+oe.bold(oe.cyan(e))),detail:e=>console.log(oe.dim(" "+e))};var Ks="https://registry.npmjs.org/klaudius/latest";async function Gs(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Ks,{signal:t.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let o=await s.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function Bs(e,t){let n=r=>r.split("-")[0].split(".").map(c=>Number.parseInt(c,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(s[r])||Number.isNaN(o[r]))return!1;if(s[r]>o[r])return!0;if(s[r]<o[r])return!1}return!1}async function We(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Gs();!n||!Bs(n,t)||(i.blank(),i.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(i.detail("Your project content is fetched fresh either way, so you're not missing any"),i.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),i.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),i.blank())}import{createHash as Vs}from"crypto";import{hostname as rn,userInfo as Ys,platform as ln,arch as cn}from"os";var Ws="https://klaudius.dev",zs="/api/licenses/validate",qs="0.27.1";async function dn(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(),s=(process.env.KLAUDIUS_API_URL??Ws).replace(/\/$/,"")+zs,o=_e(),r;try{r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:rn(),os:`${ln()}-${cn()}`,cli_version:qs})})}catch(l){return{ok:!1,reason:`Could not reach the Klaudius license server (${_(l)}). Check your internet connection or try again later.`}}let c;try{c=await r.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${r.status}).`}}return c.ok?{ok:!0,tier:c.tier??"core"}:{ok:!1,reason:c.reason??`License rejected (HTTP ${r.status}).`}}function _e(){let e=[rn(),Ys().username,ln(),cn()].join("|");return Vs("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Qs}from"fs/promises";import{join as Xs}from"path";async function ke(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${_(n)}`}}}async function un(e){let t;try{t=await Qs(Xs(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(s){return{ok:!1,message:`Could not read scripts/schema.sql: ${s.message}`}}let n=e.pat.replace(/\s+/g,"");try{let s=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(s.ok)return{ok:!0};let o=await s.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(i.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${s.status}): ${o.slice(0,300)}`}}catch(s){return{ok:!1,message:`Schema apply failed: ${s.message}`}}}async function ze(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${_(t)}`}}}var pn="https://api.cloudflare.com/client/v4";function fn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function qe(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${pn}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let r=await o.json(),c=r.result?.status;if(r.success===!1||c&&c!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${c?` (status: ${c})`:""}. ${fn(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${_(o)}`}}try{let o=await fetch(`${pn}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let r=await o.json();return r.success===!1?{ok:!1,message:fn(r)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(r.result)?r.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${_(o)}`}}}var hn="https://api.netlify.com/api/v1";async function Qe(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${hn}/user`,{headers:n});if(s.status===401||s.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${s.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(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} verifying the token. Try again or check netlifystatus.com.`}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${_(s)}`}}try{let s=await fetch(`${hn}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),r=Array.isArray(o)?o:[];if(r.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 c=typeof r[0]?.slug=="string"?r[0].slug:void 0;return{ok:!0,accountCount:r.length,accountSlug:c}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${_(s)}`}}}async function we(e){let t=Ct(e);if(t)return{ok:!1,message:t};let n=se(e),s=n.value,o=r=>{let c=[r],l=Rt(e);return l&&c.push(l),n.repairs.length>0&&c.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),c.join(`
|
|
16
|
+
`)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let c={};try{c=await r.json()}catch{}let l=c.error?.message??"",d=c.error?.status??"";return r.status===400&&(d==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(l))?{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."}:r.status===401||r.status===403?{ok:!1,message:o(l||`Google rejected the key (HTTP ${r.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`)}:{ok:!1,message:o(`Google API returned HTTP ${r.status}${l?`: ${l}`:""}.`)}}catch(r){return{ok:!1,message:`Could not reach Google: ${_(r)}`}}}import Js from"nodemailer";import{ImapFlow as Zs}from"imapflow";function mn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let s=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return s.includes("invalid credentials")||s.includes("authentication failed")||s.includes("auth failed")||s.includes("login failed")||s.includes("invalid login")?"auth":s.includes("etimedout")||s.includes("timeout")||s.includes("enotfound")||s.includes("getaddrinfo")||s.includes("econnrefused")||s.includes("econnreset")?"network":"other"}async function X(e){let t=Js.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(s){return{ok:!1,failedAt:"smtp",message:gn(s,"SMTP",e.usesAccountPassword),failureKind:mn(s)}}finally{t.close()}let n=new Zs({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await n.connect(),await n.logout()}catch(s){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:gn(s,"IMAP",e.usesAccountPassword),failureKind:mn(s)}}return{ok:!0}}function gn(e,t,n){let s=e instanceof Error?e.message:String(e),o=s.toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
|
|
17
17
|
\u2022 The mailbox password is wrong or mistyped.
|
|
18
18
|
\u2022 The email address doesn't match this mailbox's login.
|
|
19
19
|
\u2022 The provider is blocking third-party apps \u2014 check that third-party
|
|
20
20
|
access is enabled and 2FA is off in your provider's settings.`:`${t} rejected the credentials. Most common causes:
|
|
21
21
|
\u2022 The app password is wrong, expired, or for a different provider.
|
|
22
22
|
\u2022 The email address doesn't match the account that issued the password.
|
|
23
|
-
\u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${
|
|
24
|
-
`+t;return
|
|
25
|
-
${e.stdout??""}`;return
|
|
26
|
-
`,"utf-8")}var bn="0.
|
|
27
|
-
runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(
|
|
23
|
+
\u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}async function yn(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let s=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(s.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(!s.ok)return{ok:!1,message:`Twilio API returned HTTP ${s.status}. Try again or check status.twilio.com.`};let o=await s.json();return o.status&&o.status!=="active"?{ok:!1,message:`Twilio account is in '${o.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:o.friendly_name}}catch(s){return{ok:!1,message:`Could not reach Twilio: ${_(s)}`}}}async function Xe(e){return e.provider==="pingen"?ei(e):ti(e)}async function ei(e){if(!e.pingenClientId||!e.pingenClientSecret||!e.pingenOrgId)return{ok:!1,message:"Missing Pingen Client ID, Client Secret, or organisation id."};let t=e.pingenStaging?"https://identity-staging.pingen.com":"https://identity.pingen.com",n=e.pingenStaging?"https://api-staging.pingen.com":"https://api.pingen.com";try{let s=await fetch(`${t}/auth/access-tokens`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:e.pingenClientId,client_secret:e.pingenClientSecret,scope:"letter"})});if(!s.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${s.status}). Check the Client ID and Secret under your organisation's 'API Access' page \u2014 note that staging and production credentials are separate.`};let o=(await s.json()).access_token;if(!o)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let r=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${o}`}});return r.status===403||r.status===404?{ok:!1,message:"Pingen accepted the credentials but not the organisation id. Copy it from the dashboard URL: app.pingen.com/organisations/<id>/\u2026"}:r.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${r.status}. Try again shortly.`}}catch(s){return{ok:!1,message:`Could not reach Pingen: ${_(s)}`}}}async function ti(e){if(!e.postgridApiKey)return{ok:!1,message:"Missing PostGrid API key."};try{let t=await fetch("https://api.postgrid.com/print-mail/v1/letters?limit=1",{headers:{"x-api-key":e.postgridApiKey}});return t.status===401||t.status===403?{ok:!1,message:"PostGrid rejected the API key (HTTP "+t.status+"). Copy it from the PostGrid dashboard \u2014 the live key starts with 'live_sk_'."}:t.ok?{ok:!0,friendlyName:e.postgridApiKey.startsWith("test_")?"test mode \u2014 letters will NOT print":void 0}:{ok:!1,message:`PostGrid API returned HTTP ${t.status}. Try again shortly.`}}catch(t){return{ok:!1,message:`Could not reach PostGrid: ${_(t)}`}}}import{spawn as ni}from"child_process";async function kn(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,s=await si(n);if(s.code===0)return{ok:!0};let o=s.stderr.toLowerCase();return o.includes("can't get application")||o.includes("isn't running")||o.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."}:o.includes("(-1728)")||o.includes("not found")||o.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.`}:o.includes("(-1719)")||o.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: ${s.stderr.trim()||`exit code ${s.code}`}`}}function si(e){return new Promise(t=>{let n=ni("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),s="";n.stderr.on("data",o=>{s+=o.toString()}),n.on("close",o=>t({code:o??1,stderr:s})),n.on("error",o=>t({code:1,stderr:o.message}))})}import{spawn as Je}from"child_process";import{existsSync as ii}from"fs";import{homedir as oi}from"os";function ai(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var Ae=2,wn=2e3,ri=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function An(e,t){let n=e+`
|
|
24
|
+
`+t;return ri.some(s=>s.test(n))}function En(e){return new Promise(t=>setTimeout(t,e))}function li(e,t,n){return new Promise(s=>{let o=n.shell?Je([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):Je(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),r="",c="";o.stdout?.on("data",l=>{let d=l.toString();r+=d,process.stdout.write(d)}),o.stderr?.on("data",l=>{let d=l.toString();c+=d,process.stderr.write(d)}),o.on("close",l=>s({code:l??1,stdout:r,stderr:c})),o.on("error",l=>s({code:1,stdout:r,stderr:c+l.message}))})}async function pt(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=Ae;o++){if(s=await li(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!An(s.stderr,s.stdout))return s;o<Ae&&(i.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${Ae+1})\u2026`),await En(wn))}return s}function ci(e,t,n){return new Promise(s=>{let o=Je(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),r="",c="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{c+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:c})),o.on("error",l=>s({code:1,stdout:r,stderr:c+l.message}))})}var di=[{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 ui(e){let t=`${e.stderr??""}
|
|
25
|
+
${e.stdout??""}`;return di.find(s=>s.pattern.test(t))?.hint}async function pi(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await z())?.command??["python3"],r=async l=>{let d={code:0,stdout:"",stderr:""};for(let u=0;u<=Ae;u++){if(d=await ci(o[0],[...o.slice(1),...l],{cwd:e}),d.code===0||!An(d.stderr,d.stdout))return d;u<Ae&&(i.detail(`pip install hit a transient network error \u2014 retrying (${u+2}/${Ae+1})\u2026`),await En(wn))}return d},c=await r([...n,"--break-system-packages",...t]);return c.code!==0&&/no such option:.*break-system-packages/i.test(c.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),c=await r([...n,...t])),c.code!==0&&(c.stderr.trim()&&process.stderr.write(c.stderr),c.stdout.trim()&&process.stdout.write(c.stdout)),c}async function Ze(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=ai(),s=process.platform==="win32",o;if(s){let a=fe([{label:"your Windows user folder",path:oi()},{label:"the project folder",path:e}]);if(a.length>0){let y=await new Promise(k=>{let P=Je("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),b="",x="";P.stdout?.on("data",N=>{b+=N.toString()}),P.stderr?.on("data",N=>{x+=N.toString()}),P.on("close",N=>k({code:N??1,stdout:b,stderr:x})),P.on("error",N=>k({code:1,stdout:b,stderr:N.message}))}),g=y.code===0?y.stdout.trim():void 0;if(!he(g,ii)){let{detail:k,action:P}=me(a,"install");o=`${k}. ${P}`}}}let r=(a,y)=>{let g=ui(y);if(g){(t.hints??={})[a]=g;return}o&&(a==="npm"||a==="playwright"||a==="patchright")&&!Object.values(t.hints??{}).includes(o)&&((t.hints??={})[a]=o)};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let c=await pt("npm",["install"],{cwd:e,label:"npm install",env:n,shell:s});t.npm=c.code===0?"ok":"failed",c.code!==0&&r("npm",c),i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await pi(e);t.pip=l.code===0?"ok":"failed",l.code!==0&&r("pip",l),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let d=await pt("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:s});t.playwright=d.code===0?"ok":"failed",d.code!==0&&r("playwright",d),i.step("Installing Patchright browser (chromium ~200MB; one-time)...");let u=await pt("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:s});return t.patchright=u.code===0?"ok":"failed",u.code!==0&&r("patchright",u),t}import{mkdir as fi,readFile as hi,writeFile as mi}from"fs/promises";import{join as Pn}from"path";async function et(e,t){let n=Pn(e,".claude");await fi(n,{recursive:!0});let s=Pn(n,"settings.json"),o={};try{let d=await hi(s,"utf-8"),u=JSON.parse(d);u&&typeof u=="object"&&!Array.isArray(u)&&(o=u)}catch{}let r=o.enabledMcpjsonServers,c=Array.isArray(r)?r.filter(d=>typeof d=="string"):[];c.includes(t)||c.push(t);let l={...o,enabledMcpjsonServers:c};await mi(s,JSON.stringify(l,null,2)+`
|
|
26
|
+
`,"utf-8")}var bn="0.27.1",C=5;function ce(e){return`npx klaudius@latest init ${tt(Ee(e))}`}function Ee(e){if(process.platform==="win32")return e;let t=gi();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Ai(e){let t=[];try{let s=(await _n(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let r=V(e,o.name);if(!await Tn(V(r,".env")))continue;let c=await Tn(V(r,".klaudius","manifest.json"));if(t.push({path:r,finished:c}),t.length>=3)break}}catch{}return t}async function Tn(e){try{return await mt(e),!0}catch{return!1}}function tt(e){return/\s/.test(e)?`"${e}"`:e}function J(e,t,n){i.blank(),i.error(`${t} validation failed ${C} times in a row. Pausing setup so you don't get stuck in a loop.`),i.detail(`Last error: ${n}`),i.blank(),i.detail("Your credentials are saved in `.env`. Two ways forward:"),i.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),i.blank(),console.log(` ${p.cyan(ce(e))}`),i.blank(),i.detail(` (Your .env is at ${Ee(V(e,".env"))} \u2014 open it in any text editor.)`),i.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),i.blank(),process.exit(1)}async function In(e){let t=e.target??".",n=ki(t)?t:yi(process.cwd(),t),s=bi(n);s&&(i.error("Klaudius can't be installed inside a protected system folder."),i.detail(`Path: ${n}`),i.detail(`Reason: ${s}`),i.blank(),i.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),i.blank(),process.platform==="win32"?(i.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${p.cyan("cd $HOME\\Documents")}`),console.log(` ${p.cyan("npx klaudius@latest init my-agency")}`)):(i.detail("For example:"),console.log(` ${p.cyan("cd ~/Documents")}`),console.log(` ${p.cyan("npx klaudius@latest init my-agency")}`)),i.blank(),process.exit(1)),process.platform==="win32"&&Ti()&&(i.warn("You appear to be running in an elevated (Administrator) PowerShell."),i.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."),i.blank()),await We("init",bn);let o=await Ei(n);if(o.kind==="scaffolded"){i.blank(),i.warn(`Found an existing Klaudius project at ${p.bold(n)}.`),i.detail("(Your .env and project files are in place.)"),i.blank(),o.nodeModulesMissing?(i.detail("It looks like a previous setup didn't finish installing dependencies."),i.detail("To pick up where it left off, run:"),i.blank(),n!==process.cwd()&&console.log(` ${p.cyan(`cd ${tt(t)}`)}`),console.log(` ${p.cyan("npx klaudius@latest install")} ${p.dim("# retries npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Everything is scaffolded and dependencies look installed."),i.detail("Pick the action you wanted:"),i.blank(),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${p.cyan("npx klaudius@latest configure")} ${p.dim("# change a credential / API key")}`),console.log(` ${p.cyan("npx klaudius@latest update")} ${p.dim("# pull the latest skills, scripts, lessons")}`),i.blank()),i.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),i.blank();return}if(o.kind==="occupied"){let f=t===".",m=await Ai(n);if(m.length>0){i.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),i.detail(`You're in: ${Ee(n)}`),i.blank();for(let h of m)i.detail(h.finished?`Found a finished project at ${Ee(h.path)}. To work in it:`:`Found an unfinished setup at ${Ee(h.path)}. To pick up where it left off:`),i.blank(),h.finished?(console.log(` ${p.cyan(`cd ${Ee(h.path)}`)}`),console.log(` ${p.cyan("claude")} ${p.dim("# open Claude Code in the project")}`)):console.log(` ${p.cyan(ce(h.path))} ${p.dim("# then pick Resume")}`),i.blank();process.exit(1)}i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),i.blank(),f?(i.detail("Two ways forward:"),i.blank(),i.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${p.cyan("npx klaudius@latest init my-agency")}`),i.blank(),i.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${p.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(i.detail(`The folder '${t}' already exists and isn't empty.`),i.detail("Either pick a different name:"),console.log(` ${p.cyan(`npx klaudius@latest init ${t}-2`)}`),i.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=await Si(e.license),c=E.spinner();c.start("Validating license");let l=await dn(r);l.ok||(c.stop(`License invalid: ${l.reason??"unknown"}`,2),i.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),c.stop(`License valid (${l.tier??"core"} tier)`);let d=await ge();d.ok||(i.error(d.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${ce(n)}`),process.exit(1));let u=ie();u.ok||(i.error(u.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${ce(n)}`),process.exit(1));let a,y=!1;if(o.kind==="partial")if(await Pi(n)==="resume"){let m=await Sn(o.envPath,"utf-8"),h=dt(H(m));h?(i.success("Resuming with values from your existing .env"),i.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),a=h,y=!0,a.aiPlan||(a=await R(a,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
|
|
27
|
+
runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),a=await R())}else{let m=await Sn(o.envPath,"utf-8"),h=dt(H(m));a=await R(h??{})}else a=await R();a.licenseKey=r,await O(n,a),y||(i.success("Saved .env"),i.success(a.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let f=1;;f++){let m=E.spinner();m.start("Validating Supabase credentials");let h=await ke({url:a.supabaseUrl,serviceKey:a.supabaseServiceKey});if(h.ok){m.stop("Supabase credentials accepted");break}m.stop(h.message??"Supabase check failed",2),f>=C&&J(n,"Supabase",h.message??"Supabase check failed");let w=h.message??"Supabase check failed";i.blank(),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${f+1} of ${C})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await R(a,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
28
28
|
${w}
|
|
29
29
|
|
|
30
30
|
Re-enter the URL, secret key, or PAT below. Press Enter on any
|
|
31
|
-
field to keep what's already there.`}),await O(n,a)}if(
|
|
31
|
+
field to keep what's already there.`}),await O(n,a)}if(i.blank(),a.deployProvider==="cloudflare")for(let f=1;;f++){let m=E.spinner();m.start("Validating Cloudflare token + account");let h=await qe({token:a.cloudflareApiToken??"",accountId:a.cloudflareAccountId??""});if(h.ok){m.stop(`Cloudflare credentials accepted (${h.projectCount??0} existing Pages project${h.projectCount===1?"":"s"})`);break}m.stop(h.message??"Cloudflare check failed",2),f>=C&&J(n,"Cloudflare",h.message??"Cloudflare check failed");let w=h.message??"Cloudflare check failed";i.blank(),i.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${f+1} of ${C})`),i.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await R(a,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
|
|
32
32
|
${w}
|
|
33
33
|
|
|
34
34
|
Re-enter the API token or Account ID below. The token needs the
|
|
35
35
|
"Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
|
|
36
|
-
the current value.`}),await O(n,a)}else if(a.deployProvider==="netlify")for(let f=1;;f++){let m=E.spinner();m.start("Validating Netlify token");let h=await Qe({token:a.netlifyAuthToken??""});if(h.ok){m.stop(h.accountSlug?`Netlify token accepted (team: ${h.accountSlug})`:"Netlify token accepted");break}m.stop(h.message??"Netlify check failed",2),f>=C&&J(n,"Netlify",h.message??"Netlify check failed");let w=h.message??"Netlify check failed";
|
|
36
|
+
the current value.`}),await O(n,a)}else if(a.deployProvider==="netlify")for(let f=1;;f++){let m=E.spinner();m.start("Validating Netlify token");let h=await Qe({token:a.netlifyAuthToken??""});if(h.ok){m.stop(h.accountSlug?`Netlify token accepted (team: ${h.accountSlug})`:"Netlify token accepted");break}m.stop(h.message??"Netlify check failed",2),f>=C&&J(n,"Netlify",h.message??"Netlify check failed");let w=h.message??"Netlify check failed";i.blank(),i.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${f+1} of ${C})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await R(a,{onlySection:"netlify",banner:`Netlify rejected the token:
|
|
37
37
|
${w}
|
|
38
38
|
|
|
39
39
|
Generate a new token at
|
|
40
40
|
https://app.netlify.com/user/applications#personal-access-tokens
|
|
41
|
-
and paste it below. Press Enter to keep the current value.`}),await O(n,a)}else if(a.deployProvider==="selfhost")for(let f=1;;f++){let m=xe(a.selfhostDeployTarget??""),h=Oe(a.selfhostUrlTemplate??"");if(!m&&!h){
|
|
42
|
-
`);f>=C&&J(n,"Self-host",w),
|
|
41
|
+
and paste it below. Press Enter to keep the current value.`}),await O(n,a)}else if(a.deployProvider==="selfhost")for(let f=1;;f++){let m=xe(a.selfhostDeployTarget??""),h=Oe(a.selfhostUrlTemplate??"");if(!m&&!h){i.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let w=[m&&`SELFHOST_DEPLOY_TARGET: ${m}`,h&&`SELFHOST_URL_TEMPLATE: ${h}`].filter(Boolean).join(`
|
|
42
|
+
`);f>=C&&J(n,"Self-host",w),i.blank(),i.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${f+1} of ${C})`),i.blank(),a=await R(a,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
|
|
43
43
|
${w}
|
|
44
44
|
|
|
45
|
-
Re-enter them below. Press Enter on a field to keep its current value.`}),await O(n,a)}else for(let f=1;;f++){let m=E.spinner();m.start("Validating Vercel token");let h=await ze(a.vercelToken??"");if(h.ok){m.stop(h.username?`Vercel token accepted (signed in as ${h.username})`:"Vercel token accepted");break}m.stop(h.message??"Vercel check failed",2),f>=C&&J(n,"Vercel",h.message??"Vercel check failed");let w=h.message??"Vercel check failed";
|
|
45
|
+
Re-enter them below. Press Enter on a field to keep its current value.`}),await O(n,a)}else for(let f=1;;f++){let m=E.spinner();m.start("Validating Vercel token");let h=await ze(a.vercelToken??"");if(h.ok){m.stop(h.username?`Vercel token accepted (signed in as ${h.username})`:"Vercel token accepted");break}m.stop(h.message??"Vercel check failed",2),f>=C&&J(n,"Vercel",h.message??"Vercel check failed");let w=h.message??"Vercel check failed";i.blank(),i.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${f+1} of ${C})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await R(a,{onlySection:"vercel",banner:`Vercel rejected the token:
|
|
46
46
|
${w}
|
|
47
47
|
|
|
48
48
|
Generate a new token at https://vercel.com/account/tokens and
|
|
49
|
-
paste it below. Press Enter to keep the current value.`}),await O(n,a)}
|
|
49
|
+
paste it below. Press Enter to keep the current value.`}),await O(n,a)}i.blank();for(let f=1;;f++){let m=se(a.googlePlacesApiKey??""),h=E.spinner();h.start("Validating Google Places API key");let w=await we(a.googlePlacesApiKey??"");if(w.ok){if(h.stop("Google Places API key accepted"),m.changed){if(m.repairs.length>0){i.blank(),i.warn("Corrected look-alike characters in your Google Places API key:");for(let v of m.repairs)i.detail(` ${v}`);i.detail("These come from keys that were transcribed rather than copied."),i.detail("Google accepted the corrected key, and .env now holds it.")}a.googlePlacesApiKey=m.value,await O(n,a)}break}h.stop(w.message??"Google Places check failed",2),f>=C&&J(n,"Google Places",w.message??"Google Places check failed");let Q=w.message??"Google Places check failed";i.blank(),i.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${f+1} of ${C})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await R(a,{onlySection:"google-places",banner:`Google rejected the key:
|
|
50
50
|
${Q}
|
|
51
51
|
|
|
52
52
|
Generate (or fix) the key at https://console.cloud.google.com
|
|
53
|
-
and paste it below. Press Enter to keep the current value.`}),await O(n,a)}let g=!1;if(a.outreachEnabled&&a.outreachChannels?.includes("email")&&a.emailAddress&&a.emailPassword&&a.emailSmtpHost&&a.emailSmtpPort&&a.emailImapHost&&a.emailImapPort){
|
|
53
|
+
and paste it below. Press Enter to keep the current value.`}),await O(n,a)}let g=!1;if(a.outreachEnabled&&a.outreachChannels?.includes("email")&&a.emailAddress&&a.emailPassword&&a.emailSmtpHost&&a.emailSmtpPort&&a.emailImapHost&&a.emailImapPort){i.blank();let f=0,m=!1,h;for(;!m;){f++;let w=E.spinner();w.start("Validating email credentials (SMTP + IMAP)");let Q=a.emailProvider&&a.emailProvider!=="custom"?a.emailProvider:ue(a.emailSmtpHost),v=Q?B[Q]:void 0,j=await X({emailAddress:a.emailAddress,emailPassword:a.emailPassword,emailSmtpHost:a.emailSmtpHost,emailSmtpPort:a.emailSmtpPort,emailImapHost:a.emailImapHost,emailImapPort:a.emailImapPort,usesAccountPassword:v?.usesAccountPassword});if(j.ok){w.stop("Email credentials accepted (SMTP + IMAP)");break}w.stop(j.message??"Email check failed",2);let Ce=`${Q}\0${a.emailAddress}\0${a.emailPassword}`;if(v&&j.failureKind!=="network"&&h!==Ce){h=Ce;let ae=Re(Q,a.emailSmtpHost,a.emailImapHost),re,Tt=0;if(ae.length>0){i.blank(),i.warn(`That server rejected the login. ${v.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let F of ae){let ot=E.spinner();ot.start(`Trying ${F.label} (${F.smtpHost})`);let at=await X({emailAddress:a.emailAddress,emailPassword:a.emailPassword,emailSmtpHost:F.smtpHost,emailSmtpPort:a.emailSmtpPort,emailImapHost:F.imapHost,emailImapPort:a.emailImapPort});if(at.ok){ot.stop(`${F.label}: your login works here (${F.smtpHost})`),re=F;break}at.failureKind!=="network"&&Tt++,ot.stop(at.failureKind==="network"?`${F.label}: unreachable`:`${F.label}: rejected too`,2)}}if(re){i.blank(),i.success("Found it \u2014 your password was right all along; the server was the only problem.");let F=await E.confirm({message:`Use the ${re.label} servers (${re.smtpHost} / ${re.imapHost})?`,initialValue:!0});if(E.isCancel(F)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
54
54
|
|
|
55
55
|
${ce(n)}
|
|
56
|
-
`),process.exit(0)),F){a.emailSmtpHost=re.smtpHost,a.emailImapHost=re.imapHost,await O(n,a);continue}}else ae.length>0&&(
|
|
56
|
+
`),process.exit(0)),F){a.emailSmtpHost=re.smtpHost,a.emailImapHost=re.imapHost,await O(n,a);continue}}else ae.length>0&&(i.blank(),Tt===0?i.warn("Couldn't reach any of the alternate servers \u2014 this looks like a network problem, not a credential problem. Check your connection and retry."):v.noAltWorkedHint&&i.warn(v.noAltWorkedHint))}let Kn=j.message??"Email check failed";i.blank(),i.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),i.detail("You can skip it now and wire it up later from inside the project."),i.blank();let it=await E.select({message:`What would you like to do? ${p.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:f>=3?"skip":f>=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(E.isCancel(it)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
57
57
|
|
|
58
58
|
${ce(n)}
|
|
59
|
-
`),process.exit(0)),
|
|
59
|
+
`),process.exit(0)),it==="skip"){a.outreachChannels=(a.outreachChannels??[]).filter(ae=>ae!=="email"),a.outreachPriority=(a.outreachPriority??[]).filter(ae=>ae!=="email"),a.outreachChannels.length===0&&(a.outreachEnabled=!1),await O(n,a),g=!0,i.success("Skipped email for now. Setup will continue."),a.outreachEnabled?i.detail("Outreach will use your other channel(s); email stays off until it's fixed."):i.detail("Automated outreach is off until email is fixed \u2014 everything else works."),m=!0;break}it==="edit"&&(i.blank(),a=await R(a,{onlySection:"email",banner:`${j.failedAt==="imap"?"IMAP":"SMTP"} check failed:
|
|
60
60
|
${Kn}
|
|
61
61
|
|
|
62
62
|
Re-enter the email address, app password, or server details below.
|
|
63
63
|
Press Enter on any field to keep its current value.
|
|
64
64
|
|
|
65
65
|
Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
|
|
66
|
-
at the "Server settings" question.`}),await O(n,a))}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="twilio"&&a.twilioAccountSid&&a.twilioAuthToken){
|
|
66
|
+
at the "Server settings" question.`}),await O(n,a))}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="twilio"&&a.twilioAccountSid&&a.twilioAuthToken){i.blank();for(let f=1;;f++){let m=E.spinner();m.start("Validating Twilio credentials");let h=await yn({accountSid:a.twilioAccountSid,authToken:a.twilioAuthToken});if(h.ok){m.stop(h.friendlyName?`Twilio credentials accepted (${h.friendlyName})`:"Twilio credentials accepted");break}m.stop(h.message??"Twilio check failed",2),f>=C&&J(n,"Twilio",h.message??"Twilio check failed");let w=h.message??"Twilio check failed";i.blank(),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${f+1} of ${C})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await R(a,{onlySection:"sms",banner:`Twilio rejected the credentials:
|
|
67
67
|
${w}
|
|
68
68
|
|
|
69
69
|
Re-enter the Account SID or Auth Token below.
|
|
70
|
-
Press Enter on any field to keep its current value.`}),await O(n,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("letter")&&a.letterProvider){
|
|
70
|
+
Press Enter on any field to keep its current value.`}),await O(n,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("letter")&&a.letterProvider){i.blank();for(let f=1;;f++){let m=E.spinner();m.start("Validating letter provider credentials");let h=await Xe({provider:a.letterProvider,pingenClientId:a.pingenClientId,pingenClientSecret:a.pingenClientSecret,pingenOrgId:a.pingenOrgId,postgridApiKey:a.postgridApiKey});if(h.ok){m.stop(h.friendlyName?`Letter provider credentials accepted (${h.friendlyName})`:"Letter provider credentials accepted");break}m.stop(h.message??"Letter provider check failed",2),f>=C&&J(n,"Letter provider",h.message??"Letter provider check failed");let w=h.message??"Letter provider check failed";i.blank(),i.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${f+1} of ${C})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await R(a,{onlySection:"letter",banner:`The letter provider rejected the credentials:
|
|
71
71
|
${w}
|
|
72
72
|
|
|
73
73
|
Re-enter them below.
|
|
74
|
-
Press Enter on any field to keep its current value.`}),await O(n,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="imessage"&&a.testPhone){
|
|
74
|
+
Press Enter on any field to keep its current value.`}),await O(n,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="imessage"&&a.testPhone){i.blank();for(let f=1;;f++){let m=E.spinner();m.start("Validating iMessage setup (sending a test ping)");let h=await kn({testPhone:a.testPhone});if(h.ok){m.stop("iMessage dispatched (check your phone for the test ping)");break}m.stop(h.message??"iMessage check failed",2),f>=C&&J(n,"iMessage",h.message??"iMessage check failed");let w=h.message??"iMessage check failed";i.blank(),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${f+1} of ${C})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await R(a,{onlySection:"sms",banner:`iMessage check failed:
|
|
75
75
|
${w}
|
|
76
76
|
|
|
77
77
|
Either fix the underlying issue (sign in to Messages.app, configure
|
|
78
78
|
Text Message Forwarding) and press Enter through, or change SMS
|
|
79
|
-
provider to Twilio.`}),await O(n,a)}}if((a.notifyChannel??"telegram")==="telegram"&&a.telegramBotToken&&a.telegramChatId){
|
|
79
|
+
provider to Twilio.`}),await O(n,a)}}if((a.notifyChannel??"telegram")==="telegram"&&a.telegramBotToken&&a.telegramChatId){i.blank();let f=0,m=!1;for(;!m;){f++;let h=E.spinner();h.start("Validating Telegram bot + chat (sending a test ping)");let w=await It({botToken:a.telegramBotToken,chatId:a.telegramChatId});if(w.ok){h.stop(w.botHandle?`Telegram bot ${w.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),m=!0;break}h.stop(w.message??"Telegram check failed",2);let Q=w.message??"Telegram check failed";i.blank(),i.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),i.blank();let v=await E.select({message:`What would you like to do? ${p.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:f>=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(E.isCancel(v)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
80
80
|
|
|
81
81
|
${ce(n)}
|
|
82
|
-
`),process.exit(0)),v==="skip"){a.telegramBotToken=void 0,a.telegramChatId=void 0,await O(n,a),
|
|
82
|
+
`),process.exit(0)),v==="skip"){a.telegramBotToken=void 0,a.telegramChatId=void 0,await O(n,a),i.success("Skipped Telegram. Setup will continue."),i.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(v==="edit"&&(i.blank(),a=await R(a,{onlySection:"notifications",banner:`Telegram check failed:
|
|
83
83
|
${Q}
|
|
84
84
|
|
|
85
85
|
Re-enter the bot token or chat_id below.
|
|
86
|
-
Press Enter on any field to keep its current value.`}),await O(n,a),(a.notifyChannel??"telegram")!=="telegram"||!a.telegramBotToken||!a.telegramChatId)){
|
|
86
|
+
Press Enter on any field to keep its current value.`}),await O(n,a),(a.notifyChannel??"telegram")!=="telegram"||!a.telegramBotToken||!a.telegramChatId)){i.success("Skipped Telegram. Setup will continue."),m=!0;break}}}i.blank();let k=E.spinner();k.start("Downloading Klaudius template");let P;try{P=(await Ve({licenseKey:r,machineId:_e(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:a.aiAgent,destDir:n})).filesExtracted,k.stop(`Downloaded ${P} files into ${p.bold(n)}`)}catch(f){k.stop(f.message,2);let m=a.aiAgent==="codex"?".codex/config.toml":".mcp.json";i.detail(`Your .env / ${m} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await ht(V(n,"clients"),{recursive:!0});let b=await Jt(n);await Ge(n,Qt(bn,b)),i.success("Wrote .klaudius/manifest.json");try{await Ye(n,n,Object.keys(b))}catch{}let x=!1,N="";if(e.skipSchema)i.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),i.detail(`Apply manually later via the SQL editor: ${a.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+a.supabaseProjectRef+"/sql/new").replace(a.supabaseProjectRef+".supabase.co","")}`);else{i.blank();let f=E.spinner();f.start("Applying schema to Supabase");let m=await un({projectRoot:n,pat:a.supabasePat,projectRef:a.supabaseProjectRef});m.ok?f.stop("Schema applied (or already present)"):(f.stop(m.message??"Schema apply failed",2),x=!0,N=`https://supabase.com/dashboard/project/${a.supabaseProjectRef}/sql/new`)}let T=[],W={};if(e.skipInstall)i.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{i.blank(),i.heading("Installing dependencies");let f=await Ze(n);i.detail(`npm: ${f.npm}, pip: ${f.pip}, playwright: ${f.playwright}, patchright: ${f.patchright}`),f.npm==="failed"&&T.push("npm"),f.pip==="failed"&&T.push("pip"),f.playwright==="failed"&&T.push("playwright"),f.patchright==="failed"&&T.push("patchright"),W=f.hints??{}}let G=a.outreachEnabled&&a.outreachPriority?.includes("whatsapp")&&(a.whatsappAccounts?.length??0)>0,S=!e.skipInstall&&!T.includes("npm");if(G&&S){i.blank(),i.heading("Linking WhatsApp accounts"),console.log(p.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
|
|
87
87
|
phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
|
|
88
|
-
Link a Device, and point it at the QR shown in this terminal.`)),
|
|
88
|
+
Link a Device, and point it at the QR shown in this terminal.`)),i.blank();for(let f of a.whatsappAccounts){console.log(p.cyan(`Pairing WhatsApp account '${f}'...`)),console.log(p.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${f})`));let m=gt(process.execPath,["scripts/whatsapp.mjs","pair","--account",f],{cwd:n,stdio:"inherit"});m.status===0?i.detail(`Paired '${f}'.`):(console.log(p.yellow(`'${f}' did not pair (exit ${m.status??"signalled"}). You can finish later via:`)),console.log(p.cyan(` npx klaudius@latest pair-whatsapp --label ${f}`))),i.blank()}}else if(G&&!S){i.blank(),console.log(p.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(p.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let f of a.whatsappAccounts)console.log(p.cyan(` npx klaudius@latest pair-whatsapp --label ${f}`))}let ne=a.emailAuth==="oauth-microsoft"&&a.outreachEnabled&&a.outreachChannels?.includes("email"),D=!e.skipInstall&&!T.includes("pip"),de=f=>{console.log(p.dim("Connect it any time from the project folder with:")),console.log(p.cyan(` ${f?f.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(p.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(ne&&D){i.blank(),i.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(p.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
|
|
89
89
|
password. Your browser will open to Microsoft's sign-in page \u2014
|
|
90
90
|
sign in as `+(a.emailAddress??"your outreach mailbox")+` and approve.
|
|
91
91
|
(No browser on this machine? It falls back to a short code you can
|
|
92
|
-
enter from any device.)`)),
|
|
93
|
-
`:"",m=a.aiAgent==="codex"?"codex":"claude",h=a.aiAgent==="codex"?"Codex":"Claude Code",w=a.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";T.length>0&&(console.log(p.dim(`Easiest fix \u2014 let ${h} finish it for you:`)),s.blank(),f&&process.stdout.write(f),console.log(` ${p.cyan(m)} ${p.dim(`# open ${h} in this folder`)}`),console.log(p.dim(" Then paste:")),console.log(p.cyan(` "Finish my Klaudius install \u2014 ${T.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(p.dim(` (Don't have ${h} yet? Install with: \`${w}\`)`)),s.blank(),console.log(p.dim("Or do it yourself:")),s.blank(),f&&process.stdout.write(f),console.log(` ${p.cyan("npx klaudius@latest install")} ${p.dim("# retry the failing installers")}`),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# verify everything")}`),s.blank()),x&&(console.log(p.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${p.cyan(N)}`),console.log(p.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),T.includes("pip")&&!W.pip&&(console.log(p.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(p.dim(`Python 3.10+. Install a newer one from ${_s()}`)),console.log(p.dim("and open a fresh Terminal before retrying.")),s.blank());let v=["npm","playwright","patchright"].filter(j=>T.includes(j)&&!W[j]);if(v.length>0){let j=v.length===1?"keeps":"keep";console.log(p.dim(`If ${v.join(" / ")} ${j} failing with network errors (ECONNRESET,`)),console.log(p.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(p.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}g&&(console.log(p.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${h}`)),console.log(p.dim("to finish setting it up \u2014 your email details are saved in .env.")),s.blank()),console.log(p.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}if(Is(a,n,e.target),g){let f=a.aiAgent==="codex"?"Codex":"Claude Code";console.log(p.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(p.dim(`Your details are saved in .env. To finish it, ask ${f}:`)),console.log(p.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(p.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(p.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(p.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(p.cyan(' and send a test email to my own address to confirm."')),a.outreachEnabled&&(a.outreachChannels??[]).length>0&&(s.blank(),console.log(p.yellow(`Note: your other channel(s) \u2014 ${(a.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),s.blank()}}async function O(e,t){await ht(e,{recursive:!0}),await ft(B(e,".env"),Ue(t),"utf-8"),t.aiAgent==="codex"?(await ht(B(e,".codex"),{recursive:!0}),await ft(B(e,".codex","config.toml"),Fe(t),"utf-8")):(await ft(B(e,".mcp.json"),je(t),"utf-8"),await et(e,"supabase"))}async function Es(e){try{(await mt(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await _n(e),n=t.filter(l=>!l.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(l=>i.has(l)),r=n.includes(".env"),c=t.includes(".klaudius");if(o&&r&&!c)return{kind:"partial",envPath:B(e,".env")};if(c&&r){let l=!0;try{l=!(await mt(B(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Ps(e){s.blank(),s.warn(`Found a partial setup at ${p.bold(e)}.`),s.detail(`A previous init wrote ${p.bold(".env")} but didn't finish scaffolding.`),s.blank();let t=await E.select({message:`How would you like to proceed? ${p.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return E.isCancel(t)&&(E.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Ss(e){if(e&&e.trim().length>0)return e;E.intro("Klaudius");let t=await E.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return E.isCancel(t)&&(E.cancel("Setup cancelled. No files written."),process.exit(0)),t}function bs(e){let t=ws(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let i of n)if(t.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function Ts(){if(process.platform!=="win32")return!1;try{return gt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function _s(){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 Is(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(E.outro(p.green(p.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??pe(e.aiPlan))==="off";console.log(`${p.bold("Your plan:")} ${Ne[e.aiPlan]}`),console.log(p.dim(r?` \u2192 QA pass off${e.aiPlan==="codex-plus"&&e.aiAgent==="codex"?", model pinned to Terra":""}, so each run fits your usage window.`:" \u2192 full pipeline, including the independent QA pass after every build.")),console.log(p.dim(" Change it any time: edit QA_PHASE in .env, or re-run `npx klaudius@latest configure`.")),s.blank()}if(console.log(p.bold("Next steps:")),s.blank(),t!==process.cwd()&&n){let r=`cd ${tt(n)}`;console.log(` ${p.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${p.dim("# go into your project folder")}`)}console.log(` ${p.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${p.dim(`# opens ${o} in this project`)}`),s.blank(),console.log(p.bold(`Some starter prompts for ${o}:`)),s.blank(),console.log(` ${p.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${p.cyan(`I know I'm ready to start using Klaudius."`)}`),s.blank(),console.log(` ${p.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),s.blank(),console.log(` ${p.cyan('"Run the pipeline for one client."')}`),console.log(p.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.")),s.blank(),e.aiAgent!=="codex"&&(console.log(p.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(p.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),s.blank())}import{access as Cs,readFile as Rs}from"fs/promises";import{join as yt,resolve as xs}from"path";import U from"picocolors";async function Rn(e){let t=e.target?xs(process.cwd(),e.target):process.cwd(),n=await Cn(yt(t,".env")),i=await Cn(yt(t,"package.json"));(!n||!i)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),n||s.detail("Missing: .env"),i||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{H(await Rs(yt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}s.heading("Installing dependencies");let r=await Ze(t);s.blank(),s.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let c=[];if(r.npm==="failed"&&c.push("npm"),r.pip==="failed"&&c.push("pip"),r.playwright==="failed"&&c.push("playwright"),r.patchright==="failed"&&c.push("patchright"),c.length===0){s.blank(),console.log(U.green(U.bold("All dependencies installed."))),console.log(U.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(U.yellow(U.bold(`${c.join(", ")} still failing.`))),s.blank();for(let[a,y]of Object.entries(r.hints??{}))console.log(U.yellow(`Likely cause of ${a} failure:`)),console.log(U.dim(` ${y}`)),s.blank();let l=o==="codex"?"codex":"claude",d=o==="codex"?"Codex":"Claude Code",u=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(U.dim("Options:")),console.log(U.dim(` \u2022 Open ${d} in this folder (\`${l}\`) and paste:`)),console.log(U.cyan(` "Finish my Klaudius install \u2014 ${c.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(U.dim(` (Don't have ${d} yet? Install with: \`${u}\`)`)),console.log(U.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(U.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function Cn(e){try{return await Cs(e),!0}catch{return!1}}import{readFile as Os,writeFile as kt,access as Ns}from"fs/promises";import{join as Pe}from"path";import*as q from"@clack/prompts";import Z from"picocolors";import{mkdir as vs}from"fs/promises";import{spawnSync as xn}from"child_process";async function On(e){let t=e.projectRoot??process.cwd(),n=Pe(t,".env"),i=Pe(t,".mcp.json"),o=Pe(t,".codex","config.toml"),r=await wt(Pe(t,".klaudius","manifest.json")),c=await wt(n);!r&&!c&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let l=se();l.ok||(s.error(l.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let d={};try{let k=await Os(n,"utf-8");d=H(k)}catch{s.warn("No .env found. Starting from an empty configuration.")}let u=Gt(d);Object.keys(d).length>0&&(u.pipelineModes??=["classic"]),q.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let a=await R(u),y=u.aiAgent??"claude-code";if(a.aiAgent&&a.aiAgent!==y&&(s.error(`Switching AI coding agent (${y} \u2192 ${a.aiAgent}) isn't supported via configure.`),s.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),s.blank(),console.log(` ${Z.cyan("npx klaudius@latest init <new-folder>")} ${Z.dim("# pick the new agent in the wizard")}`),s.blank(),s.detail(".env is unchanged."),process.exit(1)),a.supabaseUrl!==d.SUPABASE_URL||a.supabaseServiceKey!==d.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let k=await ke({url:a.supabaseUrl,serviceKey:a.supabaseServiceKey});k.ok||(s.error(k.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let g=ie(a.googlePlacesApiKey??"");if(g.changed&&a.googlePlacesApiKey){s.heading("Checking your Google Places API key");let k=await we(a.googlePlacesApiKey);if(k.ok){if(g.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let P of g.repairs)s.detail(` ${P}`);s.detail("These come from keys that were transcribed rather than copied.")}a.googlePlacesApiKey=g.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(k.message??"Google rejected the Google Places API key"),s.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),s.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Ls(a,d)){let k=q.spinner();k.start("Validating email credentials (SMTP + IMAP)");let P=a.emailProvider&&a.emailProvider!=="custom"?a.emailProvider:ue(a.emailSmtpHost),b=await X({emailAddress:a.emailAddress,emailPassword:a.emailPassword,emailSmtpHost:a.emailSmtpHost,emailSmtpPort:a.emailSmtpPort,emailImapHost:a.emailImapHost,emailImapPort:a.emailImapPort,usesAccountPassword:P?V[P].usesAccountPassword:void 0});b.ok?k.stop("Email credentials accepted (SMTP + IMAP)"):(k.stop(b.message??"Email check failed",2),s.warn("Writing the email settings exactly as you entered them \u2014 not verified."),s.detail(b.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await kt(n,Ue(a),"utf-8"),s.success("Updated .env"),a.aiAgent==="codex"?(await vs(Pe(t,".codex"),{recursive:!0}),await kt(o,Fe(a),"utf-8"),s.success("Updated .codex/config.toml")):(await kt(i,je(a),"utf-8"),s.success("Updated .mcp.json"),await et(t,"supabase")),a.emailAuth==="oauth-microsoft"&&a.outreachEnabled&&a.outreachChannels?.includes("email")){let k=await z();if(!(k!==null&&xn(k.command[0],[...k.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(s.blank(),!k)s.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),s.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let b=await q.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});q.isCancel(b)||!b?s.detail(`Skipped. Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`):xn(k.command[0],[...k.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?s.success("Outlook mailbox connected."):(s.warn("The Microsoft sign-in didn't complete."),s.detail(`Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`))}}s.blank(),q.outro(Z.green("Configuration updated.")),await $s(t,r)}function Ls(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([i])=>i===void 0||i==="")?!1:n.some(([i,o])=>String(i)!==(t[o]??""))}async function $s(e,t){let n=await wt(Pe(e,"node_modules"));s.blank(),t?n||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${Z.cyan("npx klaudius@latest install")} ${Z.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${Z.cyan("npx klaudius@latest doctor")} ${Z.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${Z.cyan("npx klaudius@latest init")} ${Z.dim("# pick Resume when prompted")}`),s.blank())}async function wt(e){try{return await Ns(e),!0}catch{return!1}}import{copyFile as Nn,mkdir as vn,readFile as nt,rm as Ie,writeFile as At,access as Ln}from"fs/promises";import{dirname as $n,join as L}from"path";import{tmpdir as Ms}from"os";import*as Se from"@clack/prompts";import Et from"picocolors";var it="0.26.0";async function Mn(e){let t=e.projectRoot??process.cwd(),n=await qt(t);n||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let A of Ke)delete n.files[A];let i,o=L(t,".env"),r,c;try{r=await nt(o,"utf-8"),c=H(r)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=c.KLAUDIUS_LICENSE_KEY??"",i||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius@latest init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let l=Kt(r,c,Ft);l!==null&&(await At(o,l,"utf-8"),s.detail("Backfilled new env keys")),await We("update",it),Se.intro(`Update from ${n.templateVersion} \u2192 ${it}`);let u=c.AI_AGENT==="codex"?"codex":"claude-code",a=L(Ms(),`klaudius-update-${process.pid}-${Date.now()}`),y;try{s.heading("Downloading the latest Klaudius template");let A=await Be({licenseKey:i,machineId:_e(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:u,destDir:a});s.success(`Fetched ${A.filesExtracted} canonical files`),y=a}catch(A){s.error(A.message),s.detail("Update aborted. Your project is unchanged."),await Ie(a,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let g=await Ds(y,t,n),k=!1,P=g.find(A=>A.path===".gitignore"&&A.state==="conflict");if(P){let A=L(t,".gitignore"),f=await nt(A,"utf-8"),m=await nt(L(y,".gitignore"),"utf-8"),{merged:h,added:w}=Hs(f,m);w.length>0&&await At(A,h,"utf-8"),n.files[".gitignore"]=P.canonicalHash,P.state="gitignore-merged",k=!0,s.detail(w.length>0?`.gitignore auto-merged: kept all your lines, appended ${K(w.length,"new canonical pattern")}: ${w.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let b=g.filter(A=>A.state==="new"),x=g.filter(A=>A.state==="clean-update"),N=g.filter(A=>A.state==="user-only"),T=g.filter(A=>A.state==="conflict"),W=g.filter(A=>A.state==="no-change"),G=g.filter(A=>A.state==="locally-deleted"),S=g.filter(A=>A.state==="removed-clean"),ne=g.filter(A=>A.state==="removed-modified"),D=[...T,...G,...ne],de=n.ignored?.length??0;if(s.blank(),s.heading("Change summary"),s.detail(`${K(W.length,"file")} unchanged`),s.detail(`${K(b.length,"new file")}`),s.detail(`${K(x.length,"file")} updated cleanly (no local edits)`),s.detail(`${K(N.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${K(S.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${K(T.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${K(G.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),s.detail(`${K(ne.length,"file")} removed upstream but edited locally (need your decision)`),de>0&&(s.detail(`${K(de,"file")} kept deleted (previously resolved \u2014 skipped)`),de<=10))for(let A of n.ignored)s.detail(` kept deleted: ${A}`);if(b.length===0&&x.length===0&&S.length===0&&D.length===0&&!k){s.blank(),Se.outro(Et.green("Already up to date.")),await Ie(a,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let A of[...b,...x]){let f=L(y,A.path),m=L(t,A.path);await vn($n(m),{recursive:!0}),await Nn(f,m),n.files[A.path]=A.canonicalHash}b.length+x.length>0&&s.success(`Wrote ${K(b.length+x.length,"file")}`);for(let A of S){let f=L(t,A.path);await Ie(f,{force:!0}),delete n.files[A.path]}if(S.length>0&&s.success(`Deleted ${K(S.length,"file")} removed upstream`),D.length>0){s.blank(),s.heading(`${D.length} conflict(s) need resolution`);let A=L(t,".klaudius","incoming");try{await Ie(A,{recursive:!0,force:!0})}catch{}for(let m of[...T,...G]){let h=L(y,m.path),w=L(A,m.path);await vn($n(w),{recursive:!0}),await Nn(h,w)}let f=new Map;for(let m of T){let h=await on(t,m.path),w=h!==null?await nt(L(y,m.path),"utf-8"):"";h!==null&&(ut(h)||ut(w))?f.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):h===null?f.set(m.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):m.manifestHash&&Bt(h)!==m.manifestHash?f.set(m.path,["_The base snapshot is newer than the version your edits diverged from (an earlier update's conflicts were left unresolved), so a precise upstream diff isn't available for this file \u2014 compare against `.klaudius/incoming/"+m.path+"` directly._"]):f.set(m.path,an(h,w))}await At(L(t,".klaudius","conflicts.md"),Us(D,n.templateVersion,it,f),"utf-8"),T.length+G.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),D.length===0&&(n.templateVersion=it),await Ge(t,n);try{await Ye(t,y,await le(y))}catch{s.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(s.blank(),D.length===0)Se.outro(Et.green("Update complete."));else{let A=u==="codex"?"Codex":"Claude Code";Se.outro(Et.yellow(`${D.length} conflict(s) staged. Open ${A} in this project and ask:
|
|
94
|
-
"Run /resolve-conflicts"`))}await Ie(a,{recursive:!0,force:!0}).catch(()=>{})}async function
|
|
92
|
+
enter from any device.)`)),i.blank();let f=await z();if(f){let[m,...h]=f.command,w=gt(m,[...h,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});w.status===0?i.success("Outlook mailbox connected."):(i.blank(),console.log(p.yellow(`The Microsoft sign-in didn't complete (exit ${w.status??"signalled"}). Setup continues without it.`)),de(f))}else console.log(p.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),de(null)}else ne&&!D&&(i.blank(),console.log(p.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(p.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(p.cyan(" python3 scripts/ms_oauth.py login")));i.blank();let A=[...T,...x?["schema"]:[]];if(A.length>0){E.outro(p.yellow(p.bold(`Setup paused \u2014 ${A.join(", ")} failed.`))),console.log(p.dim("Your credentials and project files are all saved.")),i.blank();for(let[j,Ce]of Object.entries(W))console.log(p.yellow(`Likely cause of ${j} failure:`)),console.log(p.dim(` ${Ce}`)),i.blank();let f=n!==process.cwd()&&e.target?` ${p.cyan(`cd ${tt(e.target)}`)}
|
|
93
|
+
`:"",m=a.aiAgent==="codex"?"codex":"claude",h=a.aiAgent==="codex"?"Codex":"Claude Code",w=a.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";T.length>0&&(console.log(p.dim(`Easiest fix \u2014 let ${h} finish it for you:`)),i.blank(),f&&process.stdout.write(f),console.log(` ${p.cyan(m)} ${p.dim(`# open ${h} in this folder`)}`),console.log(p.dim(" Then paste:")),console.log(p.cyan(` "Finish my Klaudius install \u2014 ${T.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(p.dim(` (Don't have ${h} yet? Install with: \`${w}\`)`)),i.blank(),console.log(p.dim("Or do it yourself:")),i.blank(),f&&process.stdout.write(f),console.log(` ${p.cyan("npx klaudius@latest install")} ${p.dim("# retry the failing installers")}`),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# verify everything")}`),i.blank()),x&&(console.log(p.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${p.cyan(N)}`),console.log(p.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),T.includes("pip")&&!W.pip&&(console.log(p.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(p.dim(`Python 3.10+. Install a newer one from ${_i()}`)),console.log(p.dim("and open a fresh Terminal before retrying.")),i.blank());let v=["npm","playwright","patchright"].filter(j=>T.includes(j)&&!W[j]);if(v.length>0){let j=v.length===1?"keeps":"keep";console.log(p.dim(`If ${v.join(" / ")} ${j} failing with network errors (ECONNRESET,`)),console.log(p.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(p.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}g&&(console.log(p.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${h}`)),console.log(p.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(p.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Ii(a,n,e.target),g){let f=a.aiAgent==="codex"?"Codex":"Claude Code";console.log(p.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(p.dim(`Your details are saved in .env. To finish it, ask ${f}:`)),console.log(p.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(p.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(p.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(p.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(p.cyan(' and send a test email to my own address to confirm."')),a.outreachEnabled&&(a.outreachChannels??[]).length>0&&(i.blank(),console.log(p.yellow(`Note: your other channel(s) \u2014 ${(a.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),i.blank()}}async function O(e,t){await ht(e,{recursive:!0}),await ft(V(e,".env"),Ue(t),"utf-8"),t.aiAgent==="codex"?(await ht(V(e,".codex"),{recursive:!0}),await ft(V(e,".codex","config.toml"),Fe(t),"utf-8")):(await ft(V(e,".mcp.json"),je(t),"utf-8"),await et(e,"supabase"))}async function Ei(e){try{(await mt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await _n(e),n=t.filter(l=>!l.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(l=>s.has(l)),r=n.includes(".env"),c=t.includes(".klaudius");if(o&&r&&!c)return{kind:"partial",envPath:V(e,".env")};if(c&&r){let l=!0;try{l=!(await mt(V(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Pi(e){i.blank(),i.warn(`Found a partial setup at ${p.bold(e)}.`),i.detail(`A previous init wrote ${p.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await E.select({message:`How would you like to proceed? ${p.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return E.isCancel(t)&&(E.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Si(e){if(e&&e.trim().length>0)return e;E.intro("Klaudius");let t=await E.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return E.isCancel(t)&&(E.cancel("Setup cancelled. No files written."),process.exit(0)),t}function bi(e){let t=wi(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let s of n)if(t.startsWith(s))return`Inside ${s.slice(0,-1)} (system-managed directory).`}}function Ti(){if(process.platform!=="win32")return!1;try{return gt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function _i(){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 Ii(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(E.outro(p.green(p.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??pe(e.aiPlan))==="off";console.log(`${p.bold("Your plan:")} ${Ne[e.aiPlan]}`),console.log(p.dim(r?` \u2192 QA pass off${e.aiPlan==="codex-plus"&&e.aiAgent==="codex"?", model pinned to Terra":""}, so each run fits your usage window.`:" \u2192 full pipeline, including the independent QA pass after every build.")),console.log(p.dim(" Change it any time: edit QA_PHASE in .env, or re-run `npx klaudius@latest configure`.")),i.blank()}if(console.log(p.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let r=`cd ${tt(n)}`;console.log(` ${p.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${p.dim("# go into your project folder")}`)}console.log(` ${p.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${p.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(p.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${p.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${p.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${p.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${p.cyan('"Run the pipeline for one client."')}`),console.log(p.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.")),i.blank(),e.aiAgent!=="codex"&&(console.log(p.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(p.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as Ci,readFile as Ri}from"fs/promises";import{join as yt,resolve as xi}from"path";import U from"picocolors";async function Rn(e){let t=e.target?xi(process.cwd(),e.target):process.cwd(),n=await Cn(yt(t,".env")),s=await Cn(yt(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{H(await Ri(yt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await Ze(t);i.blank(),i.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let c=[];if(r.npm==="failed"&&c.push("npm"),r.pip==="failed"&&c.push("pip"),r.playwright==="failed"&&c.push("playwright"),r.patchright==="failed"&&c.push("patchright"),c.length===0){i.blank(),console.log(U.green(U.bold("All dependencies installed."))),console.log(U.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(U.yellow(U.bold(`${c.join(", ")} still failing.`))),i.blank();for(let[a,y]of Object.entries(r.hints??{}))console.log(U.yellow(`Likely cause of ${a} failure:`)),console.log(U.dim(` ${y}`)),i.blank();let l=o==="codex"?"codex":"claude",d=o==="codex"?"Codex":"Claude Code",u=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(U.dim("Options:")),console.log(U.dim(` \u2022 Open ${d} in this folder (\`${l}\`) and paste:`)),console.log(U.cyan(` "Finish my Klaudius install \u2014 ${c.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(U.dim(` (Don't have ${d} yet? Install with: \`${u}\`)`)),console.log(U.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(U.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function Cn(e){try{return await Ci(e),!0}catch{return!1}}import{readFile as Oi,writeFile as kt,access as Ni}from"fs/promises";import{join as Pe}from"path";import*as q from"@clack/prompts";import Z from"picocolors";import{mkdir as vi}from"fs/promises";import{spawnSync as xn}from"child_process";async function On(e){let t=e.projectRoot??process.cwd(),n=Pe(t,".env"),s=Pe(t,".mcp.json"),o=Pe(t,".codex","config.toml"),r=await wt(Pe(t,".klaudius","manifest.json")),c=await wt(n);!r&&!c&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let l=ie();l.ok||(i.error(l.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let d={};try{let k=await Oi(n,"utf-8");d=H(k)}catch{i.warn("No .env found. Starting from an empty configuration.")}let u=Gt(d);Object.keys(d).length>0&&(u.pipelineModes??=["classic"]),q.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let a=await R(u),y=u.aiAgent??"claude-code";if(a.aiAgent&&a.aiAgent!==y&&(i.error(`Switching AI coding agent (${y} \u2192 ${a.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${Z.cyan("npx klaudius@latest init <new-folder>")} ${Z.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),a.supabaseUrl!==d.SUPABASE_URL||a.supabaseServiceKey!==d.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let k=await ke({url:a.supabaseUrl,serviceKey:a.supabaseServiceKey});k.ok||(i.error(k.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let g=se(a.googlePlacesApiKey??"");if(g.changed&&a.googlePlacesApiKey){i.heading("Checking your Google Places API key");let k=await we(a.googlePlacesApiKey);if(k.ok){if(g.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let P of g.repairs)i.detail(` ${P}`);i.detail("These come from keys that were transcribed rather than copied.")}a.googlePlacesApiKey=g.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(k.message??"Google rejected the Google Places API key"),i.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),i.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Li(a,d)){let k=q.spinner();k.start("Validating email credentials (SMTP + IMAP)");let P=a.emailProvider&&a.emailProvider!=="custom"?a.emailProvider:ue(a.emailSmtpHost),b=await X({emailAddress:a.emailAddress,emailPassword:a.emailPassword,emailSmtpHost:a.emailSmtpHost,emailSmtpPort:a.emailSmtpPort,emailImapHost:a.emailImapHost,emailImapPort:a.emailImapPort,usesAccountPassword:P?B[P].usesAccountPassword:void 0});b.ok?k.stop("Email credentials accepted (SMTP + IMAP)"):(k.stop(b.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(b.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await kt(n,Ue(a),"utf-8"),i.success("Updated .env"),a.aiAgent==="codex"?(await vi(Pe(t,".codex"),{recursive:!0}),await kt(o,Fe(a),"utf-8"),i.success("Updated .codex/config.toml")):(await kt(s,je(a),"utf-8"),i.success("Updated .mcp.json"),await et(t,"supabase")),a.emailAuth==="oauth-microsoft"&&a.outreachEnabled&&a.outreachChannels?.includes("email")){let k=await z();if(!(k!==null&&xn(k.command[0],[...k.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!k)i.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),i.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let b=await q.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});q.isCancel(b)||!b?i.detail(`Skipped. Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`):xn(k.command[0],[...k.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?i.success("Outlook mailbox connected."):(i.warn("The Microsoft sign-in didn't complete."),i.detail(`Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),q.outro(Z.green("Configuration updated.")),await $i(t,r)}function Li(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([s])=>s===void 0||s==="")?!1:n.some(([s,o])=>String(s)!==(t[o]??""))}async function $i(e,t){let n=await wt(Pe(e,"node_modules"));i.blank(),t?n||(i.detail("Your project files are in place but dependencies aren't installed yet."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${Z.cyan("npx klaudius@latest install")} ${Z.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${Z.cyan("npx klaudius@latest doctor")} ${Z.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${Z.cyan("npx klaudius@latest init")} ${Z.dim("# pick Resume when prompted")}`),i.blank())}async function wt(e){try{return await Ni(e),!0}catch{return!1}}import{copyFile as Nn,mkdir as vn,readFile as nt,rm as Ie,writeFile as At,access as Ln}from"fs/promises";import{dirname as $n,join as L}from"path";import{tmpdir as Mi}from"os";import*as Se from"@clack/prompts";import Et from"picocolors";var st="0.27.1";async function Mn(e){let t=e.projectRoot??process.cwd(),n=await qt(t);n||(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let A of Ke)delete n.files[A];let s,o=L(t,".env"),r,c;try{r=await nt(o,"utf-8"),c=H(r)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=c.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let l=Kt(r,c,Ft);l!==null&&(await At(o,l,"utf-8"),i.detail("Backfilled new env keys")),await We("update",st),Se.intro(`Update from ${n.templateVersion} \u2192 ${st}`);let u=c.AI_AGENT==="codex"?"codex":"claude-code",a=L(Mi(),`klaudius-update-${process.pid}-${Date.now()}`),y;try{i.heading("Downloading the latest Klaudius template");let A=await Ve({licenseKey:s,machineId:_e(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:u,destDir:a});i.success(`Fetched ${A.filesExtracted} canonical files`),y=a}catch(A){i.error(A.message),i.detail("Update aborted. Your project is unchanged."),await Ie(a,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let g=await Di(y,t,n),k=!1,P=g.find(A=>A.path===".gitignore"&&A.state==="conflict");if(P){let A=L(t,".gitignore"),f=await nt(A,"utf-8"),m=await nt(L(y,".gitignore"),"utf-8"),{merged:h,added:w}=Hi(f,m);w.length>0&&await At(A,h,"utf-8"),n.files[".gitignore"]=P.canonicalHash,P.state="gitignore-merged",k=!0,i.detail(w.length>0?`.gitignore auto-merged: kept all your lines, appended ${K(w.length,"new canonical pattern")}: ${w.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let b=g.filter(A=>A.state==="new"),x=g.filter(A=>A.state==="clean-update"),N=g.filter(A=>A.state==="user-only"),T=g.filter(A=>A.state==="conflict"),W=g.filter(A=>A.state==="no-change"),G=g.filter(A=>A.state==="locally-deleted"),S=g.filter(A=>A.state==="removed-clean"),ne=g.filter(A=>A.state==="removed-modified"),D=[...T,...G,...ne],de=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${K(W.length,"file")} unchanged`),i.detail(`${K(b.length,"new file")}`),i.detail(`${K(x.length,"file")} updated cleanly (no local edits)`),i.detail(`${K(N.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${K(S.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${K(T.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${K(G.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${K(ne.length,"file")} removed upstream but edited locally (need your decision)`),de>0&&(i.detail(`${K(de,"file")} kept deleted (previously resolved \u2014 skipped)`),de<=10))for(let A of n.ignored)i.detail(` kept deleted: ${A}`);if(b.length===0&&x.length===0&&S.length===0&&D.length===0&&!k){i.blank(),Se.outro(Et.green("Already up to date.")),await Ie(a,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let A of[...b,...x]){let f=L(y,A.path),m=L(t,A.path);await vn($n(m),{recursive:!0}),await Nn(f,m),n.files[A.path]=A.canonicalHash}b.length+x.length>0&&i.success(`Wrote ${K(b.length+x.length,"file")}`);for(let A of S){let f=L(t,A.path);await Ie(f,{force:!0}),delete n.files[A.path]}if(S.length>0&&i.success(`Deleted ${K(S.length,"file")} removed upstream`),D.length>0){i.blank(),i.heading(`${D.length} conflict(s) need resolution`);let A=L(t,".klaudius","incoming");try{await Ie(A,{recursive:!0,force:!0})}catch{}for(let m of[...T,...G]){let h=L(y,m.path),w=L(A,m.path);await vn($n(w),{recursive:!0}),await Nn(h,w)}let f=new Map;for(let m of T){let h=await on(t,m.path),w=h!==null?await nt(L(y,m.path),"utf-8"):"";h!==null&&(ut(h)||ut(w))?f.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):h===null?f.set(m.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):m.manifestHash&&Vt(h)!==m.manifestHash?f.set(m.path,["_The base snapshot is newer than the version your edits diverged from (an earlier update's conflicts were left unresolved), so a precise upstream diff isn't available for this file \u2014 compare against `.klaudius/incoming/"+m.path+"` directly._"]):f.set(m.path,an(h,w))}await At(L(t,".klaudius","conflicts.md"),Ui(D,n.templateVersion,st,f),"utf-8"),T.length+G.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),D.length===0&&(n.templateVersion=st),await Ge(t,n);try{await Ye(t,y,await le(y))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),D.length===0)Se.outro(Et.green("Update complete."));else{let A=u==="codex"?"Codex":"Claude Code";Se.outro(Et.yellow(`${D.length} conflict(s) staged. Open ${A} in this project and ask:
|
|
94
|
+
"Run /resolve-conflicts"`))}await Ie(a,{recursive:!0,force:!0}).catch(()=>{})}async function Di(e,t,n){let s=await le(e),o=new Set(s),r=new Set(n.ignored??[]),c=[];for(let l of s){if(r.has(l))continue;let d=await ye(L(e,l)),u=n.files[l],a=L(t,l),y;try{await Ln(a),y=await ye(a)}catch{let g=u!==void 0&&!zt.has(l)?"locally-deleted":"new";c.push({path:l,state:g,canonicalHash:d,manifestHash:u});continue}d===u?y===u?c.push({path:l,state:"no-change",canonicalHash:d,localHash:y,manifestHash:u}):c.push({path:l,state:"user-only",canonicalHash:d,localHash:y,manifestHash:u}):y===u?c.push({path:l,state:"clean-update",canonicalHash:d,localHash:y,manifestHash:u}):c.push({path:l,state:"conflict",canonicalHash:d,localHash:y,manifestHash:u})}for(let l of Object.keys(n.files)){if(o.has(l))continue;let d=n.files[l],u=L(t,l),a;try{await Ln(u),a=await ye(u)}catch{delete n.files[l];continue}a===d?c.push({path:l,state:"removed-clean",localHash:a,manifestHash:d}):c.push({path:l,state:"removed-modified",localHash:a,manifestHash:d})}return c}function K(e,t){return`${e} ${t}${e===1?"":"s"}`}function Hi(e,t){let n=e.includes(`\r
|
|
95
95
|
`)?`\r
|
|
96
96
|
`:`
|
|
97
|
-
`,
|
|
98
|
-
`)}import{existsSync as
|
|
99
|
-
`)),n.push(await
|
|
97
|
+
`,s=e.split(/\r?\n/),o=new Set(s.map(d=>d.trim()).filter(d=>d!=="")),r=[];for(let d of t.split(/\r?\n/)){let u=d.trim();u===""||u.startsWith("#")||o.has(u)||(r.push(u),o.add(u))}if(r.length===0)return{merged:e,added:r};let c=[...s];for(;c.length>0&&c[c.length-1].trim()==="";)c.pop();c.push("","# Added by `klaudius update` (new canonical ignore patterns)",...r);let l=[...new Set(s.map(d=>d.trim()).filter(d=>d.startsWith("!")))].filter(d=>!r.includes(d));return c.push(...l,""),{merged:c.join(n),added:r}}function Ui(e,t,n,s=new Map){let o=e.filter(u=>u.state==="conflict").length,r=e.filter(u=>u.state==="locally-deleted").length,c=e.filter(u=>u.state==="removed-modified").length,l=[];l.push("# Update Conflicts"),l.push(""),l.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),l.push(`Updating from canonical version **${t}** to **${n}**.`),l.push("");let d=[];o>0&&d.push(`${o} file${o===1?"":"s"} ha${o===1?"s":"ve"} BOTH local edits AND upstream changes`),r>0&&d.push(`${r} file${r===1?"":"s"} you deleted locally ${r===1?"is":"are"} still shipped by the canonical template`),c>0&&d.push(`${c} file${c===1?"":"s"} ${c===1?"was":"were"} removed upstream but edited locally`),l.push(d.join(", and ")+"."),l.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."),l.push(""),l.push("---"),l.push("");for(let u of e){if(l.push(`## ${u.path}`),l.push(""),u.state==="locally-deleted")l.push("**Type:** Deleted locally"),l.push(""),l.push("- You deleted this file after it was installed; the canonical template still ships it."),l.push(`- New canonical version staged at: \`.klaudius/incoming/${u.path}\``),l.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),l.push(`- New canonical hash: \`${(u.canonicalHash??"(none)").slice(0,16)}\``),l.push(""),l.push("**Resolution options for the SKILL to walk through:**"),l.push(""),l.push("1. Restore \u2014 copy the canonical version back into place"),l.push("2. Keep deleted \u2014 never reinstall this file (recorded in the manifest's ignore list)");else if(u.state==="removed-modified")l.push("**Type:** Removed upstream"),l.push(""),l.push(`- Your local copy: \`${u.path}\``),l.push("- This file no longer exists in the canonical template."),l.push("- You've modified it locally since install."),l.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),l.push(`- Your local hash now: \`${(u.localHash??"(missing)").slice(0,16)}\``),l.push(""),l.push("**Resolution options for the SKILL to walk through:**"),l.push(""),l.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),l.push("2. Delete \u2014 remove the file from disk and from the manifest");else{l.push("**Type:** Edit conflict"),l.push(""),l.push(`- Your version (with your local edits): \`${u.path}\``),l.push(`- New canonical version: \`.klaudius/incoming/${u.path}\``),l.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),l.push(`- Your local hash now: \`${(u.localHash??"(missing)").slice(0,16)}\``),l.push(`- New canonical hash: \`${(u.canonicalHash??"(none)").slice(0,16)}\``);let a=s.get(u.path);a&&a.length>0&&(l.push(""),l.push("**What upstream changed since your base:**"),l.push(""),l.push(...a),l.push(""),l.push("_If your local edits don't touch the hunks above, merging is mechanical: take the canonical version and re-apply your edits (or apply the hunks to your copy). If they overlap, compare both versions properly before choosing._")),l.push(""),l.push("**Resolution options for the SKILL to walk through:**"),l.push(""),l.push("1. Keep mine \u2014 discard the new canonical changes"),l.push("2. Take canonical \u2014 overwrite my edits with the new version"),l.push("3. Merge \u2014 review both side-by-side and produce a combined version")}l.push(""),l.push("---"),l.push("")}return l.join(`
|
|
98
|
+
`)}import{existsSync as ji}from"fs";import{access as Fi,readFile as Pt,stat as Ki}from"fs/promises";import{homedir as Gi}from"os";import{join as Y}from"path";import $ from"picocolors";import{spawn as Dn,spawnSync as Bi}from"child_process";async function Hn(e){let t=e.projectRoot??process.cwd(),n=[];console.log($.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
99
|
+
`)),n.push(await Vi()),n.push(await Yi());let s=Y(t,".env"),o=Y(t,".klaudius","manifest.json"),r=Y(t,".mcp.json"),c=Y(t,".codex","config.toml"),l=await ee(s),d=await ee(o),u="claude-code";if(l)try{H(await Pt(s,"utf-8")).AI_AGENT==="codex"&&(u="codex")}catch{}if(u==="claude-code"){let g=await ee(Y(t,"AGENTS.md")),k=!await ee(Y(t,".claude"));g&&k&&(u="codex")}if(n.push({name:".env present",status:l?"ok":"fail",detail:l?s:"missing",nextAction:l?void 0:"Run `npx klaudius@latest init` in this folder."}),l){let g={};try{g=H(await Pt(s,"utf-8"))}catch{}let k=Me(g.AI_PLAN),P=De(g.QA_PHASE)??pe(k),b=k==="codex-plus"&&u==="codex"?` \xB7 model pin ${lt}`:"";n.push({name:"Plan / QA pass",status:k?"ok":"warn",detail:k?`${Ne[k]} \xB7 QA pass ${P}${b}`:`plan not set \xB7 QA pass ${P}`,nextAction:k?void 0:"Run `npx klaudius@latest configure` and pick your plan \u2014 on Claude Pro / ChatGPT Plus it turns the QA pass off so each run fits your usage window."})}if(n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:d?"ok":"fail",detail:d?o:"missing",nextAction:d?void 0:l?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."}),u==="codex"){let g=await ee(c);n.push({name:".codex/config.toml present",status:g?"ok":"warn",detail:g?c:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let g=await ee(r);n.push({name:".mcp.json present",status:g?"ok":"warn",detail:g?r:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await io(u)),process.platform==="win32"){let g=await Wi(t);g&&n.push(g)}if(n.push(await zi(t)),n.push(await qi(t)),n.push(await Qi()),!l)n.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)n.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let g=await Pt(s,"utf-8"),k=H(g);await Xi(k,n,t)}console.log();for(let g of n){let k=g.status==="ok"?$.green("\u2713"):g.status==="warn"?$.yellow("\u26A0"):g.status==="skip"?$.dim("\xB7"):$.red("\u2717");console.log(` ${k} ${g.name}${g.detail?$.dim(` \u2014 ${g.detail}`):""}`),g.nextAction&&console.log(` ${$.dim("\u2192")} ${$.cyan(g.nextAction)}`)}let a=n.filter(g=>g.status==="fail").length,y=n.filter(g=>g.status==="warn").length;console.log(),a===0&&y===0?console.log($.green($.bold("Everything checks out. You're good to go."))):a===0?console.log($.yellow($.bold(`${y} warning${y===1?"":"s"} \u2014 review above.`))):(console.log($.red($.bold(`${a} failed check${a===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function ee(e){try{return await Fi(e),!0}catch{return!1}}async function Vi(){let e=await ge();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 Yi(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let n=parseInt(t[1],10),s=parseInt(t[2],10);return n<22||n===22&&s<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 Wi(e){let t=fe([{label:"your Windows user folder",path:Gi()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",s=await St("npm",["config","get","script-shell"],!0),o=s.code===0?s.stdout.trim():void 0;if(he(o,ji))return{name:n,status:"ok",detail:`${t[0].label} contains ${t[0].chars.map(d=>`"${d}"`).join(", ")}, but npm's script-shell (${o}) handles it`};let{detail:r,action:c}=me(t,"doctor"),l=t.some(d=>d.chars.includes("&"));return{name:n,status:l?"fail":"warn",detail:r,nextAction:c}}async function zi(e){let t=Y(e,"node_modules");if(!await ee(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await Ki(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 qi(e){let t=process.platform==="darwin"?Y(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?Y(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):Y(process.env.HOME??"",".cache","ms-playwright");return await ee(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 Qi(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
|
|
100
100
|
try:
|
|
101
101
|
${e.map(r=>` import ${r}`).join(`
|
|
102
102
|
`)}
|
|
103
103
|
except Exception as e:
|
|
104
104
|
print(str(e))
|
|
105
105
|
sys.exit(1)
|
|
106
|
-
`,n=await z();if(!n)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
|
|
107
|
-
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function
|
|
108
|
-
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await ee(Y(e,".ms-token.json"))?{name:t,status:"warn",detail:"token cache present, but no Python found to verify it"}:{name:t,status:"fail",detail:"no Microsoft sign-in found (.ms-token.json missing)",nextAction:o}}async function eo(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(u=>u.trim().toLowerCase()),i=(e.LETTER_PROVIDER??"").trim().toLowerCase(),o=n.includes("letter");if(!o&&(!i||i==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(o&&i!=="pingen"&&i!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!o)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${i} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let r=await Xe({provider:i,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!r.ok)return{name:t,status:"fail",detail:r.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let c=`${i} credentials accepted`+(r.friendlyName?` (${r.friendlyName})`:""),l=(e.SUPABASE_ANON_KEY??"").trim();if(!l)return{name:t,status:"warn",detail:c+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let d=xt(l);if(d&&d!=="anon")return{name:t,status:"fail",detail:c+`, but SUPABASE_ANON_KEY holds a '${d}' key \u2014 shipping it in a claim page would expose the whole database`,nextAction:"Replace SUPABASE_ANON_KEY with the key whose role is 'anon' (Supabase dashboard \u2192 Settings \u2192 API keys)."};if(e.SUPABASE_URL)try{let u=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:l,Authorization:`Bearer ${l}`}});if(u.ok){let a=await u.json();if(Array.isArray(a)&&a.length>0)return{name:t,status:"fail",detail:c+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(i==="postgrid"){let u=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(a=>!(e[a]??"").trim());if(u.length>0)return{name:t,status:"warn",detail:c+`, but PostGrid needs your return address and .env is missing ${u.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:c}}async function to(e,t){let n="Email credentials (SMTP + IMAP)",i=Js(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Un(e))return i==="parked"?{name:"Email account (Microsoft sign-in)",status:"warn",detail:"Outlook mailbox saved in .env but email isn't an active outreach channel (skipped during setup?)",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."}:i==="incomplete"?{name:"Email account (Microsoft sign-in)",status:"fail",detail:"EMAIL_AUTH=oauth-microsoft but EMAIL_ADDRESS is missing from .env",nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}:Zs(t);if(i==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(i==="incomplete"){let d=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(u=>u.endsWith("_PORT")?!e[u]||!/^\d+$/.test(e[u].trim()):!e[u]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${d.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=He(e),r=o&&o!=="custom"?o:ue(e.EMAIL_SMTP_HOST),c={emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:r?V[r].usesAccountPassword:void 0},l=await X(c);if(l.ok)return{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`};if(l.failureKind==="network")return{name:n,status:"fail",detail:l.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(r){let d=Re(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(d.length>0){console.log($.dim(` (email login rejected \u2014 probing ${V[r].label}'s other regional servers, up to ~10s each\u2026)`));let u=0;for(let y of d){let g=await X({...c,emailSmtpHost:y.smtpHost,emailImapHost:y.imapHost});if(!g.ok&&g.failureKind!=="network"&&u++,g.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${y.label} (${y.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${y.smtpHost} and EMAIL_IMAP_HOST=${y.imapHost} in .env (or ask your AI agent to).`}}let a=(l.message??"login rejected").split(/\.\s|\n/)[0];return u===0?{name:n,status:"fail",detail:`${a} \u2014 and none of the alternate servers were reachable either; this looks like a network problem`,nextAction:"Check your connection and re-run doctor before touching the password."}:{name:n,status:"fail",detail:`${a} \u2014 tried all ${V[r].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:r==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":r==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:l.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}async function no(e){let t=[];for(let n of jt(e)){let i=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:i,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:i,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:i,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:i,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let o=await X({emailAddress:n.address,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort});o.ok?t.push({name:i,status:"ok",detail:`authenticated (${n.smtpHost})`}):t.push({name:i,status:"fail",detail:o.message,nextAction:o.failureKind==="network"?"Looks like a network/host problem \u2014 check this mailbox's SMTP/IMAP hosts in .env.":"Check this mailbox's password and hosts in .env (regional providers often need a different server)."})}return t}async function io(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",i=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`.",o=await St(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
|
|
109
|
-
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:
|
|
110
|
-
`));let r=
|
|
106
|
+
`,n=await z();if(!n)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 s=n.command,o=await St(s[0],[...s.slice(1),"-c",t]);return o.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(o.stdout||o.stderr).trim().split(`
|
|
107
|
+
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function Xi(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let c=await ke({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:c.ok?"ok":"fail",detail:c.ok?"connected":c.message,nextAction:c.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":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(s==="selfhost"){let c=e.SELFHOST_DEPLOY_TARGET??"",l=e.SELFHOST_URL_TEMPLATE??"",d=[],u=xe(c);u&&d.push(`SELFHOST_DEPLOY_TARGET: ${u}`);let a=Oe(l);a&&d.push(`SELFHOST_URL_TEMPLATE: ${a}`),t.push({name:"Self-host deploy config",status:d.length===0?"ok":"fail",detail:d.length===0?`target ${c} (SSH reachability tested at first deploy)`:d.join("; "),nextAction:d.length===0?void 0:"Run `npx klaudius@latest configure` and fix the self-host deployment answers."})}else if(s==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let c=await qe({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:c.ok?"ok":"fail",detail:c.ok?`valid (${c.projectCount??0} Pages project${c.projectCount===1?"":"s"})`:c.message,nextAction:c.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 c=await Qe({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:c.ok?"ok":"fail",detail:c.ok?c.accountSlug?`valid (team: ${c.accountSlug})`:"valid":c.message,nextAction:c.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 c=await ze(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:c.ok?"ok":"fail",detail:c.ok?c.username??"valid":c.message,nextAction:c.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 c=await we(e.GOOGLE_PLACES_API_KEY),l=se(e.GOOGLE_PLACES_API_KEY);c.ok&&l.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 "+(l.repairs.length>0?`it contains look-alike characters (${l.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:c.ok?"ok":"fail",detail:c.ok?"accepted":c.message,nextAction:c.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)"});t.push(await no(e,n)),t.push(...await so(e)),t.push(await eo(e)),t.push(await to(e));let o=(e.NOTIFY_CHANNEL??"").toLowerCase(),r=o==="email"||o==="sms"||o==="none"||o==="off"?o:"telegram";if(r==="none"||r==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(r==="email"){let c=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:c&&e.EMAIL_ADDRESS?"ok":"fail",detail:c&&e.EMAIL_ADDRESS?`alerts go to ${c}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:c&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(r==="sms"){let c=e.NOTIFY_TO||e.TEST_PHONE,l=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:c&&l?"ok":"fail",detail:c&&l?`alerts go to ${c} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:c?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:c&&l?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let c=await _t({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:c.ok?"ok":"fail",detail:c.ok?`bot ${c.botHandle??"ok"} (chat_id not tested)`:c.message,nextAction:c.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:"Notifications",status:"skip",detail:"not configured (optional)"})}function Ji(e){let t=r=>!!r&&/^\d+$/.test(r.trim()),n=Un(e)?!!e.EMAIL_ADDRESS:!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),s=(e.OUTREACH_CHANNELS??"").split(",").map(r=>r.trim()),o=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&s.includes("email");return o&&n?"active":o?"incomplete":n?"parked":"unconfigured"}function Un(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function Zi(e){let t="Email account (Microsoft sign-in)",n=await z(),o=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[c,...l]=n.command,d=Bi(c,[...l,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),u=`${d.stdout??""}${d.stderr??""}`.trim();if(d.status===0){let a=/signed in as (\S+)/.exec(u)?.[1];return{name:t,status:"ok",detail:a?`signed in as ${a} (token refresh works)`:"signed in (token refresh works)"}}return{name:t,status:"fail",detail:u.split(`
|
|
108
|
+
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await ee(Y(e,".ms-token.json"))?{name:t,status:"warn",detail:"token cache present, but no Python found to verify it"}:{name:t,status:"fail",detail:"no Microsoft sign-in found (.ms-token.json missing)",nextAction:o}}async function eo(e){let t="Database schema up to date",n=(e.SUPABASE_URL??"").trim().replace(/\/+$/,""),s=(e.SUPABASE_SERVICE_KEY??"").trim();if(!n||!s)return{name:t,status:"skip",detail:"Supabase credentials not set"};try{let o=await fetch(`${n}/rest/v1/clients?select=postal_address&limit=1`,{headers:{apikey:s,Authorization:`Bearer ${s}`}});if(o.ok)return{name:t,status:"ok",detail:"clients.postal_address present"};let r=await o.text();return o.status===400&&/postal_address/.test(r)?(e.OUTREACH_CHANNELS??"").split(",").some(l=>l.trim().toLowerCase()==="letter")?{name:t,status:"warn",detail:"clients.postal_address is missing \u2014 this database was provisioned before the letter channel. Captures still work (values are stored under extra), but the letter channel reads the real column.",nextAction:"Run once in the Supabase SQL editor: ALTER TABLE clients ADD COLUMN IF NOT EXISTS postal_address JSONB;"}:{name:t,status:"skip",detail:"clients.postal_address absent \u2014 only needed by the letter channel, which isn't enabled"}:{name:t,status:"skip",detail:`Could not verify (HTTP ${o.status}) \u2014 see the Supabase rows above.`}}catch{return{name:t,status:"skip",detail:"Supabase unreachable \u2014 skipped schema check"}}}async function to(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(u=>u.trim().toLowerCase()),s=(e.LETTER_PROVIDER??"").trim().toLowerCase(),o=n.includes("letter");if(!o&&(!s||s==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(o&&s!=="pingen"&&s!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!o)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${s} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let r=await Xe({provider:s,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!r.ok)return{name:t,status:"fail",detail:r.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let c=`${s} credentials accepted`+(r.friendlyName?` (${r.friendlyName})`:""),l=(e.SUPABASE_ANON_KEY??"").trim();if(!l)return{name:t,status:"warn",detail:c+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let d=xt(l);if(d&&d!=="anon")return{name:t,status:"fail",detail:c+`, but SUPABASE_ANON_KEY holds a '${d}' key \u2014 shipping it in a claim page would expose the whole database`,nextAction:"Replace SUPABASE_ANON_KEY with the key whose role is 'anon' (Supabase dashboard \u2192 Settings \u2192 API keys)."};if(e.SUPABASE_URL)try{let u=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:l,Authorization:`Bearer ${l}`}});if(u.ok){let a=await u.json();if(Array.isArray(a)&&a.length>0)return{name:t,status:"fail",detail:c+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(s==="postgrid"){let u=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(a=>!(e[a]??"").trim());if(u.length>0)return{name:t,status:"warn",detail:c+`, but PostGrid needs your return address and .env is missing ${u.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:c}}async function no(e,t){let n="Email credentials (SMTP + IMAP)",s=Ji(e);if(s==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Un(e))return s==="parked"?{name:"Email account (Microsoft sign-in)",status:"warn",detail:"Outlook mailbox saved in .env but email isn't an active outreach channel (skipped during setup?)",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."}:s==="incomplete"?{name:"Email account (Microsoft sign-in)",status:"fail",detail:"EMAIL_AUTH=oauth-microsoft but EMAIL_ADDRESS is missing from .env",nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}:Zi(t);if(s==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(s==="incomplete"){let d=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(u=>u.endsWith("_PORT")?!e[u]||!/^\d+$/.test(e[u].trim()):!e[u]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${d.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=He(e),r=o&&o!=="custom"?o:ue(e.EMAIL_SMTP_HOST),c={emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:r?B[r].usesAccountPassword:void 0},l=await X(c);if(l.ok)return{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`};if(l.failureKind==="network")return{name:n,status:"fail",detail:l.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(r){let d=Re(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(d.length>0){console.log($.dim(` (email login rejected \u2014 probing ${B[r].label}'s other regional servers, up to ~10s each\u2026)`));let u=0;for(let y of d){let g=await X({...c,emailSmtpHost:y.smtpHost,emailImapHost:y.imapHost});if(!g.ok&&g.failureKind!=="network"&&u++,g.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${y.label} (${y.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${y.smtpHost} and EMAIL_IMAP_HOST=${y.imapHost} in .env (or ask your AI agent to).`}}let a=(l.message??"login rejected").split(/\.\s|\n/)[0];return u===0?{name:n,status:"fail",detail:`${a} \u2014 and none of the alternate servers were reachable either; this looks like a network problem`,nextAction:"Check your connection and re-run doctor before touching the password."}:{name:n,status:"fail",detail:`${a} \u2014 tried all ${B[r].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:r==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":r==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:l.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}async function so(e){let t=[];for(let n of jt(e)){let s=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:s,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:s,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:s,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:s,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let o=await X({emailAddress:n.address,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort});o.ok?t.push({name:s,status:"ok",detail:`authenticated (${n.smtpHost})`}):t.push({name:s,status:"fail",detail:o.message,nextAction:o.failureKind==="network"?"Looks like a network/host problem \u2014 check this mailbox's SMTP/IMAP hosts in .env.":"Check this mailbox's password and hosts in .env (regional providers often need a different server)."})}return t}async function io(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",s=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`.",o=await St(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
|
|
109
|
+
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:s}}function St(e,t,n=!1){return new Promise(s=>{let o=n?Dn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Dn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",c="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{c+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:c})),o.on("error",()=>s({code:1,stdout:r,stderr:c}))})}import{existsSync as oo}from"fs";import{spawnSync as ao}from"child_process";import{join as ro,resolve as lo}from"path";import M from"picocolors";async function jn(e){let t=lo(e.projectRoot??process.cwd()),n=ro(t,"scripts","whatsapp.mjs");oo(n)||(console.error(M.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(M.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(M.dim(`Looked for: ${n}`)),process.exit(1));let s=(e.label??"primary").trim(),o=s.replace(/[^A-Za-z0-9_-]/g,"");o||(console.error(M.red(`Invalid label '${s}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),o!==s&&console.error(M.yellow(`Note: cleaned label '${s}' \u2192 '${o}' (filename-safe characters only).`)),console.log(M.cyan(`Pairing WhatsApp account '${o}'...`)),console.log(M.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.
|
|
110
|
+
`));let r=ao(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(M.green(`Paired '${o}'.`)),console.log(M.dim(`
|
|
111
111
|
If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
112
112
|
WHATSAPP_ACCOUNTS=primary,${o}
|
|
113
|
-
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(M.red(`Pair failed: ${r.error.message}`)):(console.error(M.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(M.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(M.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(M.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as
|
|
113
|
+
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(M.red(`Pair failed: ${r.error.message}`)):(console.error(M.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(M.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(M.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(M.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as co}from"child_process";var bt="--use-system-ca";function Fn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(bt)||!ie().ok)return;let n=e?`${e} ${bt}`:bt,s=co(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});s.signal&&(process.kill(process.pid,s.signal),process.exit(1)),process.exit(s.status??1)}Fn();var po="0.27.1",te=new uo;te.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(po);te.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 $t({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});te.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 In({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});te.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 Rn({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});te.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await On({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});te.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await Mn({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});te.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 Hn({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});te.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 jn({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});te.parse(process.argv);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.27.1",
|
|
4
4
|
"description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code or Codex (find, build, deploy, outreach end-to-end).",
|
|
5
5
|
"homepage": "https://klaudius.dev",
|
|
6
6
|
"bugs": {
|