klaudius 0.30.3 → 0.30.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +64 -57
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b 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 Ks(){let e=process.platform==="win32",t=await qe("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 qe("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 Gs(){let e=await sn();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 Bs(){let e=Ee([{label:"your Windows user folder",path:Hs()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await qe("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(Pe(s,Ds))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:a}=Se(e,"preflight"),r=e.some(c=>c.chars.includes("&"));return{name:t,status:r?"fail":"warn",detail:o,nextAction:a}}async function Vs(){try{return await fetch(an,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:an}}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 Ys(e=0){e>0?console.log(O.green(O.bold("Your machine is ready."))+O.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(O.green(O.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(O.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 WINDOW and run:"),console.log(),console.log(` ${O.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(O.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(O.dim(" run it in a new terminal window.")),console.log()}function qe(e,t,n=!1){return new Promise(s=>{let o=n?on([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):on(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",r="";o.stdout?.on("data",c=>{a+=c.toString()}),o.stderr?.on("data",c=>{r+=c.toString()}),o.on("close",c=>s({code:c??1,stdout:a,stderr:r})),o.on("error",()=>s({code:1,stdout:a,stderr:r}))})}import{mkdir as Mt,readdir as ts,readFile as Dt,stat as Ht,writeFile as Nt}from"fs/promises";import{spawnSync as Ut}from"child_process";import{homedir as mo}from"os";import{resolve as go,isAbsolute as yo,join as X,normalize as ko}from"path";import*as P from"@clack/prompts";import h from"picocolors";var Ws={GB:"44",US:"1",CA:"1",AU:"61",NZ:"64",IE:"353",DE:"49",FR:"33",ES:"34",IT:"39",NL:"31",BE:"32",CH:"41",AT:"43",PT:"351",SE:"46",NO:"47",DK:"45",FI:"358",PL:"48",ZA:"27"},zs={US:{pre:"$"},CA:{pre:"$"},AU:{pre:"$"},NZ:{pre:"$"},GB:{pre:"\xA3"},IE:{pre:"\u20AC"},DE:{pre:"\u20AC"},FR:{pre:"\u20AC"},ES:{pre:"\u20AC"},IT:{pre:"\u20AC"},NL:{pre:"\u20AC"},BE:{pre:"\u20AC"},AT:{pre:"\u20AC"},PT:{pre:"\u20AC"},FI:{pre:"\u20AC"},CH:{pre:"CHF "},SE:{post:" kr"},NO:{post:" kr"},DK:{post:" kr"},PL:{post:" z\u0142"},ZA:{pre:"R"}};function ln(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let s=zs[(t??"").toUpperCase()];return s?`${s.pre??""}${n}${s.post??""}`:n}function It(e,t){if(!e)return e;let n=e.replace(/[\s().-]/g,"");if(/^\+\d{8,15}$/.test(n))return n;if(/^00\d{8,15}$/.test(n))return`+${n.slice(2)}`;let s=t?Ws[t.toUpperCase()]:void 0;return s==="1"&&/^1?\d{10}$/.test(n)?`+1${n.slice(-10)}`:s&&s!=="1"&&/^0\d{7,14}$/.test(n)?`+${s}${n.slice(1)}`:e}var Ct="claude-code",Rt="gpt-5.6-terra";function cn(e){if(e==="claude-code"||e==="codex")return e}var Qs=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function Je(e){let t=e?.trim().toLowerCase()??"";return Qs.includes(t)?t:void 0}function Xe(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 xt="vercel";function dn(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function un(e){if(e==="telegram"||e==="email"||e==="sms")return e}function pn(e){if(e==="password"||e==="oauth-microsoft")return e}function qs(e){if(e==="custom"||e!==void 0&&Object.hasOwn(J,e))return e}function Ze(e){let t=qs(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[s,o]of Object.entries(J))if(o.smtpHost===n)return s;return"custom"}}function fn(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",a=c=>{let l=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${c}`];return l?.trim()?l.trim():void 0},r=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(c=>!a(c)).map(c=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${c}`);for(let c of["SMTP_PORT","IMAP_PORT"]){let l=a(c);l!==void 0&&!/^\d+$/.test(l)&&r.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${c}`)}return{label:s,valid:o,auth:(a("AUTH")??"password").toLowerCase(),address:a("ADDRESS"),missing:r,smtpHost:a("SMTP_HOST"),smtpPort:parseInt(a("SMTP_PORT")??"587",10),imapHost:a("IMAP_HOST"),imapPort:parseInt(a("IMAP_PORT")??"993",10),password:a("PASSWORD"),login:a("LOGIN")}})}function et(e){let t=[],n=c=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${c}`),t.push("# "+"=".repeat(60)),t.push("")},s=(c,l)=>{if(l==null||l===""){t.push(`# ${c}=`);return}let p=String(l);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(p)){let u=p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${c}="${u}"`)}else t.push(`${c}=${p}`)};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??Ct),s("AI_PLAN",e.aiPlan),s("QA_PHASE",e.qaPhase??Ae(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",ln(e.pricing,e.countryCode)),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",ln(e.pricingMonthly,e.countryCode)),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),s("EMAIL_DRAFTS_FOLDER",e.emailDraftsFolder),n("SMS outreach"),s("SMS_PROVIDER",e.smsProvider),s("TEST_PHONE",It(e.testPhone,e.countryCode)),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??xt),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 a=new Set(t.map(c=>/^#?\s*([A-Z0-9_]+)=/.exec(c)?.[1]).filter(c=>!!c)),r=Object.entries(e.preservedEnv??{}).filter(([c])=>!a.has(c));if(r.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[c,l]of r)s(c,l)}return t.join(`
|
|
2
|
+
import{b as ke,c as Be,d as J,e as I,f as Jt,g as Xt,h as Ve,i as Ye,j as ce,k as Zt,l as en,o as tn,q as Ae,r as We,s as N}from"./chunk-F2UIJSEK.js";import{Command as Ir}from"commander";import{spawn as on}from"child_process";import{existsSync as Ui}from"fs";import{homedir as Fi}from"os";import O from"picocolors";import{win32 as _i}from"path";var Ti=["&","^","%","!"];function Ii(e){return Ti.filter(t=>e.includes(t))}function Ee(e){let t=[];for(let{label:n,path:i}of e){let o=Ii(i);o.length>0&&t.push({label:n,path:i,chars:o})}return t}function Ci(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 i=_i.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(i)?t:null}function Pe(e,t){let n=Ci(e);return n===null?!1:t?t(n):!0}function Se(e,t){let n=e[0],i=[...new Set(e.flatMap(p=>p.chars))],o=i.map(p=>`"${p}"`).join(", "),r=i.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 de(){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),i=parseInt(t[2],10),o=parseInt(t[3],10),r=`${n}.${i}.${o}`;return n<22||n===22&&i<15?{ok:!1,version:r,major:n,minor:i,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:i}}import{spawn as Ri}from"child_process";import{existsSync as xi}from"fs";import{homedir as Oi}from"os";import{delimiter as vi,join as ze}from"path";var $i=new Set(["Restricted","AllSigned"]);function Li(e,t=xi){for(let n of e.split(vi)){let i=n.replace(/"/g,"");if(!i)continue;let o=ze(i,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let a=ze(i,r);if(t(a))return{path:a,isPs1:!1}}}return null}async function sn(){let e=Li(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Ni();if(!t)return{blocked:!1,shimPath:e.path};let n=ze(Oi(),".local","node")+"\\";return{blocked:$i.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Ni(){let e=ze(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await nn(e)??await nn("powershell.exe")}function nn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let i=Ri(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",r=setTimeout(()=>{i.kill(),n(null)},8e3);i.stdout.on("data",a=>{o+=a.toString()}),i.stderr?.resume(),i.on("close",a=>{clearTimeout(r),n(a===0&&o.trim()?o.trim():null)}),i.on("error",()=>{clearTimeout(r),n(null)})})}import{spawn as Mi}from"child_process";var Ne=3,Qe=10,Di=[["python3"],["python"],["py","-3"]];async function Q(){for(let e of Di){let t=await qe(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 i=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!i)continue;let o=parseInt(i[1],10),r=parseInt(i[2],10),a=i[3]?`${o}.${r}.${i[3]}`:`${o}.${r}`;return{command:[...e],version:a,major:o,minor:r}}return null}async function be(){let e=Hi(),t=await Q();if(!t){let a=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 ${Ne}.${Qe}+ is not installed (or not on PATH). Install it from ${e}.`+a}}let{command:n,version:i,major:o,minor:r}=t;return o<Ne||o===Ne&&r<Qe?{ok:!1,version:i,major:o,minor:r,command:n,message:`Your installed Python is ${i}. Klaudius needs Python ${Ne}.${Qe} or newer (the pipeline depends on packages that only ship wheels for ${Ne}.${Qe}+). 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:i,major:o,minor:r,command:n}}function Hi(){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 qe(e,t){return new Promise(n=>{let i=Mi(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";i.stdout?.on("data",a=>{o+=a.toString()}),i.stderr?.on("data",a=>{r+=a.toString()}),i.on("close",a=>n({code:a??1,stdout:o,stderr:r})),i.on("error",()=>n({code:1,stdout:o,stderr:r}))})}var rn=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function an(e={}){console.log(O.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
|
+
`));let t=[];t.push(ji());let n=await be();if(t.push(Ki(n)),t.push(await Gi(n.command)),t.push(await Bi()),process.platform==="win32"){let o=await Vi();o&&t.push(o);let r=await Yi();r&&t.push(r)}t.push(await Wi());for(let o of t){let r=o.status==="ok"?O.green("\u2713"):o.status==="warn"?O.yellow("!"):O.red("\u2717");console.log(` ${r} ${o.name}${o.detail?O.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${O.dim("\u2192")} ${O.cyan(o.nextAction)}`)}console.log();let i=t.filter(o=>o.status==="fail");if(i.length===0){let o=t.filter(r=>r.status==="warn").length;zi(o);return}console.log(O.red(O.bold(`${i.length} check${i.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(O.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(O.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function ji(){let e=de();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 window before re-running."}}function Ki(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 Gi(e){let t=e??["python3"],n=await Je(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 Bi(){let e=process.platform==="win32",t=await Je("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 Je("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 Vi(){let e=await sn();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 Yi(){let e=Ee([{label:"your Windows user folder",path:Fi()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await Je("npm",["config","get","script-shell"],!0),i=n.code===0?n.stdout.trim():void 0;if(Pe(i,Ui))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${i}) handles it`};let{detail:o,action:r}=Se(e,"preflight"),a=e.some(c=>c.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function Wi(){try{return await fetch(rn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:rn}}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 zi(e=0){e>0?console.log(O.green(O.bold("Your machine is ready."))+O.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(O.green(O.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(O.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 WINDOW and run:"),console.log(),console.log(` ${O.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(O.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(O.dim(" run it in a new terminal window.")),console.log()}function Je(e,t,n=!1){return new Promise(i=>{let o=n?on([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):on(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",c=>{r+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>i({code:c??1,stdout:r,stderr:a})),o.on("error",()=>i({code:1,stdout:r,stderr:a}))})}import{mkdir as Dt,readdir as ti,readFile as Ht,stat as Ut,writeFile as Mt}from"fs/promises";import{spawnSync as Ft}from"child_process";import{homedir as yo}from"os";import{resolve as wo,isAbsolute as ko,join as X,normalize as Ao}from"path";import*as P from"@clack/prompts";import h from"picocolors";var Qi={GB:"44",US:"1",CA:"1",AU:"61",NZ:"64",IE:"353",DE:"49",FR:"33",ES:"34",IT:"39",NL:"31",BE:"32",CH:"41",AT:"43",PT:"351",SE:"46",NO:"47",DK:"45",FI:"358",PL:"48",ZA:"27"},qi={US:{pre:"$"},CA:{pre:"$"},AU:{pre:"$"},NZ:{pre:"$"},GB:{pre:"\xA3"},IE:{pre:"\u20AC"},DE:{pre:"\u20AC"},FR:{pre:"\u20AC"},ES:{pre:"\u20AC"},IT:{pre:"\u20AC"},NL:{pre:"\u20AC"},BE:{pre:"\u20AC"},AT:{pre:"\u20AC"},PT:{pre:"\u20AC"},FI:{pre:"\u20AC"},CH:{pre:"CHF "},SE:{post:" kr"},NO:{post:" kr"},DK:{post:" kr"},PL:{post:" z\u0142"},ZA:{pre:"R"}};function ln(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let i=qi[(t??"").toUpperCase()];return i?`${i.pre??""}${n}${i.post??""}`:n}function Ct(e,t){if(!e)return e;let n=e.replace(/[\s().-]/g,"");if(/^\+\d{8,15}$/.test(n))return n;if(/^00\d{8,15}$/.test(n))return`+${n.slice(2)}`;let i=t?Qi[t.toUpperCase()]:void 0;return i==="1"&&/^1?\d{10}$/.test(n)?`+1${n.slice(-10)}`:i&&i!=="1"&&/^0\d{7,14}$/.test(n)?`+${i}${n.slice(1)}`:e}var Rt="claude-code",xt="gpt-5.6-terra";function cn(e){if(e==="claude-code"||e==="codex")return e}var Ji=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function Xe(e){let t=e?.trim().toLowerCase()??"";return Ji.includes(t)?t:void 0}function Ze(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 Ot="vercel";function dn(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function un(e){if(e==="telegram"||e==="email"||e==="sms")return e}function pn(e){if(e==="password"||e==="oauth-microsoft")return e}function Xi(e){if(e==="custom"||e!==void 0&&Object.hasOwn(J,e))return e}function et(e){let t=Xi(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[i,o]of Object.entries(J))if(o.smtpHost===n)return i;return"custom"}}function fn(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let i of t.split(",")){let o=i.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(i=>{let o=/^[a-z0-9_]+$/.test(i)&&i!=="auto",r=c=>{let l=e[`EMAIL_ACCOUNT_${i.toUpperCase()}_${c}`];return l?.trim()?l.trim():void 0},a=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(c=>!r(c)).map(c=>`EMAIL_ACCOUNT_${i.toUpperCase()}_${c}`);for(let c of["SMTP_PORT","IMAP_PORT"]){let l=r(c);l!==void 0&&!/^\d+$/.test(l)&&a.push(`EMAIL_ACCOUNT_${i.toUpperCase()}_${c}`)}return{label:i,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:a,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"),login:r("LOGIN")}})}function tt(e){let t=[],n=c=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${c}`),t.push("# "+"=".repeat(60)),t.push("")},i=(c,l)=>{if(l==null||l===""){t.push(`# ${c}=`);return}let p=String(l);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(p)){let u=p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${c}="${u}"`)}else t.push(`${c}=${p}`)};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"),i("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),i("AI_AGENT",e.aiAgent??Rt),i("AI_PLAN",e.aiPlan),i("QA_PHASE",e.qaPhase??Ae(e.aiPlan)),n("Operating country and language"),i("OPERATOR_COUNTRY",e.country),i("OPERATOR_COUNTRY_CODE",e.countryCode),i("OPERATOR_LANGUAGE",e.language),i("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let o=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];i("PIPELINE_MODES",[...new Set(["classic",...o])].join(",")),n("Pricing"),i("PRICING",ln(e.pricing,e.countryCode)),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",ln(e.pricingMonthly,e.countryCode)),n("Automated outreach features"),i("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),i("OPERATOR_NAME",e.name),i("SIGNATURE",e.signature),i("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),i("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),i("EMAIL_PROVIDER",e.emailProvider),i("EMAIL_AUTH",e.emailAuth??"password"),i("EMAIL_ADDRESS",e.emailAddress),i("EMAIL_PASSWORD",e.emailPassword),i("EMAIL_FROM_NAME",e.emailFromName),i("EMAIL_SMTP_HOST",e.emailSmtpHost),i("EMAIL_SMTP_PORT",e.emailSmtpPort),i("EMAIL_IMAP_HOST",e.emailImapHost),i("EMAIL_IMAP_PORT",e.emailImapPort),i("EMAIL_SENT_FOLDER",e.emailSentFolder),i("EMAIL_INBOX_FOLDER",e.emailInboxFolder),i("EMAIL_DRAFTS_FOLDER",e.emailDraftsFolder),n("SMS outreach"),i("SMS_PROVIDER",e.smsProvider),i("TEST_PHONE",Ct(e.testPhone,e.countryCode)),i("TWILIO_ACCOUNT_SID",e.twilioAccountSid),i("TWILIO_AUTH_TOKEN",e.twilioAuthToken),i("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),i("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Letter outreach"),i("LETTER_PROVIDER",e.letterProvider??"none"),i("PINGEN_CLIENT_ID",e.pingenClientId),i("PINGEN_CLIENT_SECRET",e.pingenClientSecret),i("PINGEN_ORG_ID",e.pingenOrgId),i("POSTGRID_API_KEY",e.postgridApiKey),n("Supabase (pipeline state)"),i("SUPABASE_URL",e.supabaseUrl),i("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),i("SUPABASE_ANON_KEY",e.supabaseAnonKey),i("SUPABASE_PAT",e.supabasePat),i("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),i("DEPLOY_PROVIDER",e.deployProvider??Ot),i("VERCEL_TOKEN",e.vercelToken),i("VERCEL_SCOPE",e.vercelScope??""),i("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),i("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),i("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),i("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),i("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),i("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),i("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),i("NOTIFY_CHANNEL",e.notifyChannel),i("NOTIFY_TO",e.notifyTo),i("TELEGRAM_BOT_TOKEN",e.telegramBotToken),i("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(c=>/^#?\s*([A-Z0-9_]+)=/.exec(c)?.[1]).filter(c=>!!c)),a=Object.entries(e.preservedEnv??{}).filter(([c])=>!r.has(c));if(a.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[c,l]of a)i(c,l)}return t.join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`}function
|
|
7
|
-
`}function
|
|
8
|
-
`)}function
|
|
6
|
+
`}function nt(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 it(e){let t=e.supabaseProjectRef,n=Zi(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 = "${xt}"`,""]:[],"[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 Zi(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var hn=[{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 es(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function mn(e,t,n){let i=n.filter(a=>!(a.key in t));if(i.length===0)return null;let o=e.endsWith(`
|
|
9
9
|
`)?"":`
|
|
10
|
-
`,
|
|
10
|
+
`,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let a of i)r.push(""),a.comment&&r.push(`# ${a.comment}`),r.push(es(a.key,a.value));return e+o+r.join(`
|
|
11
11
|
`)+`
|
|
12
|
-
`}function
|
|
13
|
-
`)){let
|
|
14
|
-
`,"utf-8")}function Pn(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function ge(e,t=e){let n=await
|
|
15
|
-
`+
|
|
16
|
-
`)};try{let
|
|
12
|
+
`}function ts(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 K(e){let t={};for(let n of e.split(`
|
|
13
|
+
`)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o===-1)continue;let r=i.slice(0,o).trim(),a=ts(i.slice(o+1).trim());t[r]=a}return t}function gn(e){let t=c=>{let l=e[c];if(!l)return;let p=parseInt(l,10);return isNaN(p)?void 0:p},n=e.SMS_PROVIDER,i=c=>c==="email"||c==="sms"||c==="whatsapp"||c==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(i),r=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(i),a=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:cn(e.AI_AGENT)??Rt,aiPlan:Xe(e.AI_PLAN),qaPhase:Ze(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(c=>c.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:r&&r.length>0?r:void 0,whatsappAccounts:a&&a.length>0?a:void 0,emailProvider:et(e),emailAuth:pn(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,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:n==="imessage"||n==="twilio"?n:void 0,testPhone:Ct(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),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:dn(e.DEPLOY_PROVIDER)??Ot,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:un(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function st(e){let t=_=>{let le=e[_];if(!le)return;let j=parseInt(le,10);return isNaN(j)?void 0:j},n=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),r=e.SUPABASE_PROJECT_REF,a=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",l=dn(e.DEPLOY_PROVIDER)??Ot,p=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,w=e.CLOUDFLARE_ACCOUNT_ID,d=e.NETLIFY_AUTH_TOKEN,S=e.SELFHOST_DEPLOY_TARGET,y=e.SELFHOST_URL_TEMPLATE;if(!a||!n||!i||!o||!r||!(l==="cloudflare"?!!u&&!!w:l==="netlify"?!!d:l==="selfhost"?!!S&&!!y:!!p))return null;let b=e.SMS_PROVIDER,C=_=>_==="email"||_==="sms"||_==="whatsapp"||_==="letter",B=e.OUTREACH_CHANNELS?.split(",").map(_=>_.trim()).filter(C),ae=e.OUTREACH_PRIORITY?.split(",").map(_=>_.trim()).filter(C),R=e.WHATSAPP_ACCOUNTS?.split(",").map(_=>_.trim()).filter(_=>_.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:cn(e.AI_AGENT)??Rt,aiPlan:Xe(e.AI_PLAN),qaPhase:Ze(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(_=>_.trim().toLowerCase()).filter(Boolean):void 0,pricing:a,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:B&&B.length>0?B:void 0,outreachPriority:ae&&ae.length>0?ae:void 0,whatsappAccounts:R&&R.length>0?R:void 0,emailProvider:et(e),emailAuth:pn(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,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:b==="imessage"||b==="twilio"?b:void 0,testPhone:Ct(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),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:l,vercelToken:p,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:w||void 0,netlifyAuthToken:d||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:S||void 0,selfhostUrlTemplate:y||void 0,supabaseUrl:n,supabaseServiceKey:i,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:un(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as sa,mkdir as oa,readdir as cs,stat as ra}from"fs/promises";import{dirname as la,join as Sn,relative as ds,sep as us}from"path";import{fileURLToPath as da}from"url";import{createHash as yn}from"crypto";import{readFile as ns}from"fs/promises";async function _e(e){let t=await ns(e);return yn("sha256").update(t).digest("hex")}function vt(e){return yn("sha256").update(e).digest("hex")}import{mkdir as is,readFile as ss,writeFile as os,access as rs}from"fs/promises";import{dirname as as,join as wn}from"path";var ls=".klaudius",kn=`${ls}/manifest.json`,ot=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml",".ms-token.json"]),An=new Set(["clients/README.md"]);async function En(e){let t=wn(e,kn);try{await rs(t)}catch{return null}let n=await ss(t,"utf-8"),i=JSON.parse(n),o={};for(let[r,a]of Object.entries(i.files??{}))o[r.split("\\").join("/")]=a;return i.files=o,Array.isArray(i.ignored)?i.ignored=i.ignored.filter(r=>typeof r=="string").map(r=>r.split("\\").join("/")):delete i.ignored,i}async function Me(e,t){let n=wn(e,kn);await is(as(n),{recursive:!0}),await os(n,JSON.stringify(t,null,2)+`
|
|
14
|
+
`,"utf-8")}function Pn(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function ge(e,t=e){let n=await cs(e,{withFileTypes:!0}),i=[];for(let o of n){let r=Sn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?i.push(...await ge(r,t)):o.isFile()&&i.push(ds(t,r).split(us).join("/")))}return i}async function bn(e){let t=await ge(e),n={};for(let i of t)ot.has(i)||(n[i]=await _e(Sn(e,i)));return n}import{copyFile as ps,mkdir as _n,mkdtemp as fs,readdir as Tn,rm as In}from"fs/promises";import{tmpdir as hs}from"os";import{dirname as ms,join as rt}from"path";import{Readable as gs}from"stream";import*as Cn from"tar";var ys="https://klaudius.dev/api/template";function ws(e){return gs.fromWeb(e)}async function at(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??ys,n="0.30.4",i;try{i=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${I(c)}`)}if(!i.ok){let c="";try{let l=await i.json();c=l.reason?` (${l.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${i.status}${c}`)}if(!i.body)throw new Error("Template download succeeded but response had no body");let o=i.headers.get("x-klaudius-tier"),r=await fs(rt(hs(),"klaudius-template-")),a=0;try{try{await new Promise((p,u)=>{let w=Cn.extract({cwd:r,strict:!0});w.on("finish",p),w.on("error",u),ws(i.body).on("error",u).pipe(w)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await _n(e.destDir,{recursive:!0});let c=new Set(await Tn(e.destDir)),l=await ge(r);try{for(let p of l){let u=rt(e.destDir,p);await _n(ms(u),{recursive:!0}),await ps(rt(r,p),u),a++}}catch(p){let u=await Tn(e.destDir).catch(()=>[]);for(let w of u)c.has(w)||await In(rt(e.destDir,w),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await In(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:a,tier:o}}import{copyFile as ks,mkdir as As,readFile as Rn,rm as Es}from"fs/promises";import{dirname as Ps,join as ye}from"path";import{structuredPatch as Ss}from"diff";var xn=ye(".klaudius","base"),lt=ye(".klaudius","conflict-base");async function ct(e,t,n){let i=ye(e,xn);await Es(i,{recursive:!0,force:!0});for(let o of n){let r=ye(i,o);await As(Ps(r),{recursive:!0}),await ks(ye(t,o),r)}}async function On(e,t){try{return await Rn(ye(e,xn,t),"utf-8")}catch{return null}}async function vn(e,t){try{return await Rn(ye(e,lt,t),"utf-8")}catch{return null}}function $n(e,t,n,i){return Te(n)?null:e!==null&&!Te(e)&&(!i||vt(e)===i)?e:t!==null&&!Te(t)&&i&&vt(t)===i?t:null}function Te(e){return e.includes("\0")||e.includes("\uFFFD")}function Ln(e,t,n=60){let i=Ss("base","new",e,t,"","",{context:2});if(i.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=i.hunks.map(l=>`${l.newStart}-${l.newStart+Math.max(l.newLines-1,0)}`).join(", "),r=[`Upstream changed ${i.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],a=0,c=!1;for(let l of i.hunks){if(a>=n){c=!0;break}r.push(`@@ -${l.oldStart},${l.oldLines} +${l.newStart},${l.newLines} @@`),a+=1;let p=Math.max(n-a,0),u=l.lines.slice(0,p);if(r.push(...u),a+=u.length,u.length<l.lines.length){c=!0;break}}return r.push("```"),c&&r.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),r}import ue from"picocolors";var s={info:e=>console.log(ue.cyan("\u2139"),e),success:e=>console.log(ue.green("\u2713"),e),warn:e=>console.log(ue.yellow("\u26A0"),e),error:e=>console.error(ue.red("\u2717"),e),step:e=>console.log(ue.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+ue.bold(ue.cyan(e))),detail:e=>console.log(ue.dim(" "+e))};var bs="https://registry.npmjs.org/klaudius/latest";async function _s(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(bs,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let o=await i.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function Ts(e,t){let n=r=>r.split("-")[0].split(".").map(a=>Number.parseInt(a,10)),i=n(e),o=n(t);if(i.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(i[r])||Number.isNaN(o[r]))return!1;if(i[r]>o[r])return!0;if(i[r]<o[r])return!1}return!1}async function dt(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await _s();!n||!Ts(n,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(s.detail("Your project content is fetched fresh either way, so you're not missing any"),s.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),s.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),s.blank())}import{createHash as Is}from"crypto";import{hostname as Nn,userInfo as Cs,platform as Mn,arch as Dn}from"os";var Rs="https://klaudius.dev",xs="/api/licenses/validate",Os="0.30.4";async function Hn(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),i=(process.env.KLAUDIUS_API_URL??Rs).replace(/\/$/,"")+xs,o=De(),r;try{r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Nn(),os:`${Mn()}-${Dn()}`,cli_version:Os})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${I(c)}). Check your internet connection or try again later.`}}let a;try{a=await r.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${r.status}).`}}return a.ok?{ok:!0,tier:a.tier??"core"}:{ok:!1,reason:a.reason??`License rejected (HTTP ${r.status}).`}}function De(){let e=[Nn(),Cs().username,Mn(),Dn()].join("|");return Is("sha256").update(e).digest("hex").slice(0,32)}import{readFile as vs}from"fs/promises";import{join as $s}from"path";async function Ie(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: ${I(n)}`}}}async function Un(e){let t;try{t=await vs($s(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(i){return{ok:!1,message:`Could not read scripts/schema.sql: ${i.message}`}}let n=e.pat.replace(/\s+/g,"");try{let i=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(i.ok)return{ok:!0};let o=await i.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(s.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${i.status}): ${o.slice(0,300)}`}}catch(i){return{ok:!1,message:`Schema apply failed: ${i.message}`}}}async function ut(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: ${I(t)}`}}}var Fn="https://api.cloudflare.com/client/v4";function jn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function pt(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${Fn}/user/tokens/verify`,{headers:i});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(),a=r.result?.status;if(r.success===!1||a&&a!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${a?` (status: ${a})`:""}. ${jn(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}try{let o=await fetch(`${Fn}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:i});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:jn(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: ${I(o)}`}}}var Kn="https://api.netlify.com/api/v1";async function ft(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${Kn}/user`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} verifying the token. Try again or check netlifystatus.com.`}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${I(i)}`}}try{let i=await fetch(`${Kn}/accounts`,{headers:n});if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} listing your teams. Try again or check netlifystatus.com.`};let o=await i.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 a=typeof r[0]?.slug=="string"?r[0].slug:void 0;return{ok:!0,accountCount:r.length,accountSlug:a}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${I(i)}`}}}function Ls(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,i=/caller does not have permission|billing/i.test(t)?"This usually means the key's Google Cloud project has no active billing account \u2014 Places needs billing set up even though Google's free monthly credit covers normal use. Check https://console.cloud.google.com/billing for the project this key belongs to. (Less often: the key's restrictions block the Places API \u2014 check Credentials.)":"Common causes: the key is wrong or deleted, billing is not enabled on its Cloud project, or the key's restrictions block the Places API. Check https://console.cloud.google.com/billing and the key's entry under Credentials.";return`${n} ${i}`}async function Ce(e){let t=Zt(e);if(t)return{ok:!1,message:t};let n=ce(e),i=n.value,o=r=>{let a=[r],c=en(e);return c&&a.push(c),n.repairs.length>0&&a.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.`),a.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":i,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let a={};try{a=await r.json()}catch{}let c=a.error?.message??"",l=a.error?.status??"";return r.status===400&&(l==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(c))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library/places.googleapis.com and press Enable for the project this key belongs to, then try again. (That page is 'Places API (New)' \u2014 the older 'Places API' is a different API and won't work.)"}:r.status===401||r.status===403?{ok:!1,message:o(Ls(r.status,c))}:{ok:!1,message:o(`Google API returned HTTP ${r.status}${c?`: ${c}`:""}.`)}}catch(r){return{ok:!1,message:`Could not reach Google: ${I(r)}`}}}import Ns from"nodemailer";import{ImapFlow as Ms}from"imapflow";function Gn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let i=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return i.includes("invalid credentials")||i.includes("authentication failed")||i.includes("auth failed")||i.includes("login failed")||i.includes("invalid login")?"auth":i.includes("etimedout")||i.includes("timeout")||i.includes("enotfound")||i.includes("getaddrinfo")||i.includes("econnrefused")||i.includes("econnreset")?"network":"other"}async function oe(e){let t=Ns.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(o){return{ok:!1,failedAt:"smtp",message:Bn(o,"SMTP",e.usesAccountPassword),failureKind:Gn(o)}}finally{t.close()}let n=new Ms({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),i;try{if(await n.connect(),e.draftsFolder)try{let o=await n.list(),r=e.draftsFolder.toLowerCase();if(!o.some(c=>c.path.toLowerCase()===r)){let c=o.find(l=>l.specialUse==="\\Drafts")?.path;i={configured:e.draftsFolder,detected:c}}}catch{}await n.logout()}catch(o){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Bn(o,"IMAP",e.usesAccountPassword),failureKind:Gn(o)}}return{ok:!0,draftsFolderIssue:i}}function Bn(e,t,n){let i=e instanceof Error?e.message:String(e),o=i.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
|
|
@@ -23,106 +23,113 @@ import{b as we,c as Ge,d as J,e as I,f as Jt,g as Xt,h as Be,i as Ve,j as le,k a
|
|
|
23
23
|
\u2022 The address is an alias (e.g. a Google Workspace alias domain) \u2014 the
|
|
24
24
|
sign-in must use the account's primary address. Keep the alias as
|
|
25
25
|
EMAIL_ADDRESS and set EMAIL_LOGIN in .env to the primary address.
|
|
26
|
-
\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: ${
|
|
27
|
-
`+t;return
|
|
28
|
-
${e.stdout??""}`;return
|
|
29
|
-
`,"utf-8")}var Zn="0.30.
|
|
30
|
-
runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(
|
|
26
|
+
\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: ${i}`}async function Vn(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let i=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(i.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!i.ok)return{ok:!1,message:`Twilio API returned HTTP ${i.status}. Try again or check status.twilio.com.`};let o=await i.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(i){return{ok:!1,message:`Could not reach Twilio: ${I(i)}`}}}async function ht(e){return e.provider==="pingen"?Ds(e):Hs(e)}async function Ds(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 i=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(!i.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${i.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 i.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(i){return{ok:!1,message:`Could not reach Pingen: ${I(i)}`}}}async function Hs(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: ${I(t)}`}}}import{spawn as Us}from"child_process";async function Yn(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,i=await Fs(n);if(i.code===0)return{ok:!0};let o=i.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: ${i.stderr.trim()||`exit code ${i.code}`}`}}function Fs(e){return new Promise(t=>{let n=Us("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),i="";n.stderr.on("data",o=>{i+=o.toString()}),n.on("close",o=>t({code:o??1,stderr:i})),n.on("error",o=>t({code:1,stderr:o.message}))})}import{spawn as mt}from"child_process";import{existsSync as js}from"fs";import{homedir as Ks}from"os";function Gs(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var Re=2,Wn=2e3,Bs=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function zn(e,t){let n=e+`
|
|
27
|
+
`+t;return Bs.some(i=>i.test(n))}function Qn(e){return new Promise(t=>setTimeout(t,e))}function Vs(e,t,n){return new Promise(i=>{let o=n.shell?mt([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):mt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),r="",a="";o.stdout?.on("data",c=>{let l=c.toString();r+=l,process.stdout.write(l)}),o.stderr?.on("data",c=>{let l=c.toString();a+=l,process.stderr.write(l)}),o.on("close",c=>i({code:c??1,stdout:r,stderr:a})),o.on("error",c=>i({code:1,stdout:r,stderr:a+c.message}))})}async function $t(e,t,n){let i={code:0,stdout:"",stderr:""};for(let o=0;o<=Re;o++){if(i=await Vs(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!zn(i.stderr,i.stdout))return i;o<Re&&(s.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${Re+1})\u2026`),await Qn(Wn))}return i}function Ys(e,t,n){return new Promise(i=>{let o=mt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",c=>{r+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>i({code:c??1,stdout:r,stderr:a})),o.on("error",c=>i({code:1,stdout:r,stderr:a+c.message}))})}var Ws=[{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 zs(e){let t=`${e.stderr??""}
|
|
28
|
+
${e.stdout??""}`;return Ws.find(i=>i.pattern.test(t))?.hint}async function Qs(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await Q())?.command??["python3"],r=async c=>{let l={code:0,stdout:"",stderr:""};for(let p=0;p<=Re;p++){if(l=await Ys(o[0],[...o.slice(1),...c],{cwd:e}),l.code===0||!zn(l.stderr,l.stdout))return l;p<Re&&(s.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${Re+1})\u2026`),await Qn(Wn))}return l},a=await r([...n,"--break-system-packages",...t]);return a.code!==0&&/no such option:.*break-system-packages/i.test(a.stderr)&&(s.detail("Older pip detected; retrying without --break-system-packages"),a=await r([...n,...t])),a.code!==0&&(a.stderr.trim()&&process.stderr.write(a.stderr),a.stdout.trim()&&process.stdout.write(a.stdout)),a}async function gt(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=Gs(),i=process.platform==="win32",o;if(i){let u=Ee([{label:"your Windows user folder",path:Ks()},{label:"the project folder",path:e}]);if(u.length>0){let w=await new Promise(S=>{let y=mt("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),E="",b="";y.stdout?.on("data",C=>{E+=C.toString()}),y.stderr?.on("data",C=>{b+=C.toString()}),y.on("close",C=>S({code:C??1,stdout:E,stderr:b})),y.on("error",C=>S({code:1,stdout:E,stderr:C.message}))}),d=w.code===0?w.stdout.trim():void 0;if(!Pe(d,js)){let{detail:S,action:y}=Se(u,"install");o=`${S}. ${y}`}}}let r=(u,w)=>{let d=zs(w);if(d){(t.hints??={})[u]=d;return}o&&(u==="npm"||u==="playwright"||u==="patchright")&&!Object.values(t.hints??{}).includes(o)&&((t.hints??={})[u]=o)};s.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await $t("npm",["install"],{cwd:e,label:"npm install",env:n,shell:i});t.npm=a.code===0?"ok":"failed",a.code!==0&&r("npm",a),s.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let c=await Qs(e);t.pip=c.code===0?"ok":"failed",c.code!==0&&r("pip",c),s.step("Installing Playwright browser (chromium ~200MB; one-time)...");let l=await $t("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:i});t.playwright=l.code===0?"ok":"failed",l.code!==0&&r("playwright",l),s.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await $t("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:i});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&r("patchright",p),t}import{copyFile as qs,access as Js}from"fs/promises";import{dirname as Xs,join as Zs}from"path";async function qn(){let e=await qe("python3",["--version"]),t=(e.stdout+e.stderr).trim();if(/Python was not found/i.test(t))return{state:"stub"};let n=/Python\s+(\d+\.\d+(?:\.\d+)?)/.exec(t);return e.code===0&&n?{state:"real",version:n[1]}:{state:"missing"}}async function Lt(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await qn();if(e.state==="real")return{status:"ok",version:e.version};let t=await Q();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function eo(e){let[t,...n]=e.command,i=await qe(t,[...n,"-c","import sys; print(sys.executable)"]),o=i.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(i.code!==0||!o)return{ok:!1,reason:"no-exe-path"};let r=Zs(Xs(o),"python3.exe"),a=await Js(r).then(()=>!0,()=>!1);if(!a){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await qs(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let c=await qn();return{ok:!0,target:r,created:!a,verified:c.state==="real",postState:c.state==="real"?void 0:c.state}}var to="A real python3.exe now exists, but the Microsoft Store placeholder still shadows it. Turn OFF both `python.exe` and `python3.exe` under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases, then open a fresh terminal.";async function yt(){let e=await Lt();if(e.status!=="broken")return;let t=await eo(e.fallback);if(t.ok&&t.verified){let n=t.created?e.literal==="stub"?"Fixed a Windows quirk: `python3` was a Store placeholder; it now runs your real Python.":"Fixed a Windows quirk: created the missing `python3` command from your real Python.":"The `python3` command now works \u2014 it runs your real Python.";s.success(n);return}if(t.ok&&t.postState==="stub"){s.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),s.detail(to);return}if(t.ok){s.warn("A python3.exe is in place next to your Python, but that folder isn't on this machine's PATH, so commands can't find it."),s.detail('Re-installing Python from python.org with "Add python.exe to PATH" ticked resolves it \u2014 then open a fresh terminal.');return}if(t.reason==="store-python"){s.warn('This Python was installed from the Microsoft Store, which blocks creating the `python3` alias next to it. Installing Python from python.org (tick "Add python.exe to PATH") resolves it.');return}if(t.reason==="not-writable"){s.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),s.detail(t.manualCommand??"");return}s.warn("This machine's `python3` command isn't working, and the automatic fix could not complete. Re-installing Python from python.org (tick \"Add python.exe to PATH\") resolves it.")}import{spawn as no,spawnSync as Jn}from"child_process";import{mkdtemp as io,rm as so,rmdir as oo,writeFile as ro,stat as Nt,unlink as ao,mkdir as lo}from"fs/promises";import{createServer as co}from"net";import{tmpdir as uo}from"os";import{join as xe}from"path";function po(){return new Promise((e,t)=>{let n=co();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let i=n.address(),o=typeof i=="object"&&i?i.port:0;n.close(()=>e(o))})})}function wt(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?Jn(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):Jn("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function kt(e){try{return await fo(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function fo(e){let t=`klaudius-smoke-${process.pid}`,n=xe(".klaudius",`qa-smoke-${process.pid}.png`),i=xe(e,n),o,r,a=!1;try{o=await io(xe(uo(),"klaudius-qa-smoke-")),await ro(xe(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let c=await po();r=no("python3",["-m","http.server",String(c),"--directory",o],{stdio:"ignore",shell:!1});let l=!1;r.on("error",()=>{l=!0}),r.on("exit",()=>{l=!0});let p=`http://127.0.0.1:${c}/`,u=!1;for(let b=0;b<24&&!l;b++)try{if((await fetch(p,{signal:AbortSignal.timeout(1e3)})).ok){u=!0;break}}catch{await new Promise(C=>setTimeout(C,500))}if(!u)return{ok:!1,stage:"python3-server",detail:"`python3 -m http.server` never came up on a free local port",remediation:process.platform==="win32"?"python3 on this machine isn't runnable (usually the Microsoft Store placeholder). Running `npx klaudius@latest update` fixes it automatically.":"Check `python3 --version` works in this terminal."};let w=xe(e,".klaudius"),d=await Nt(w).then(()=>!0,()=>!1);await lo(w,{recursive:!0}),a=!d;let S=wt(e,[`-s=${t}`,"open",p]);if(S.status!==0)return{ok:!1,stage:"browser",detail:((S.stderr??"")+(S.stdout??"")).slice(-400).trim()||"playwright-cli could not open a browser",remediation:"Run `npx playwright install chromium` in this folder"+(process.platform==="linux"?", and under WSL also `npx playwright install-deps chromium` (missing system libraries are the usual cause there).":".")};let y=wt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await Nt(i).catch(()=>null);if((!E||E.size===0)&&(y=wt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await Nt(i).catch(()=>null)),!E||E.size===0){let b=((y.stderr??"")+(y.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${b?` (${b})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{wt(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await ao(i).catch(()=>{}),a&&await oo(xe(e,".klaudius")).catch(()=>{}),o&&await so(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as ho,readFile as mo,writeFile as go}from"fs/promises";import{join as Xn}from"path";async function At(e,t){let n=Xn(e,".claude");await ho(n,{recursive:!0});let i=Xn(n,"settings.json"),o={};try{let l=await mo(i,"utf-8"),p=JSON.parse(l);p&&typeof p=="object"&&!Array.isArray(p)&&(o=p)}catch{}let r=o.enabledMcpjsonServers,a=Array.isArray(r)?r.filter(l=>typeof l=="string"):[];a.includes(t)||a.push(t);let c={...o,enabledMcpjsonServers:a};await go(i,JSON.stringify(c,null,2)+`
|
|
29
|
+
`,"utf-8")}var Zn="0.30.4",v=5,H=!1;function U(e,t){s.blank(),console.error(`INIT-BLOCKED section=${e}`),console.error(t),console.error("Fix this section's values in the answers file and re-run the same init command. Progress so far is saved in .env."),process.exit(2)}async function Eo(e){let t;try{t=await Ht(e,"utf-8")}catch{U("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let i=JSON.parse(n),o={};for(let[r,a]of Object.entries(i))a!=null&&(o[r]=typeof a=="string"?a:String(a));return o}catch(i){U("answers",`Answers file is not valid JSON: ${i.message}`)}return K(t)}function pe(e){return`npx klaudius@latest init ${Et(Oe(e))}`}function Oe(e){if(process.platform==="win32")return e;let t=yo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Po(e){let t=[];try{let i=(await ti(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of i){let r=X(e,o.name);if(!await ei(X(r,".env")))continue;let a=await ei(X(r,".klaudius","manifest.json"));if(t.push({path:r,finished:a}),t.length>=3)break}}catch{}return t}async function ei(e){try{return await Ut(e),!0}catch{return!1}}function Et(e){return/\s/.test(e)?`"${e}"`:e}function ee(e,t,n){s.blank(),s.error(`${t} validation failed ${v} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${n}`),s.blank(),s.detail("Your credentials are saved in `.env`. Two ways forward:"),s.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),s.blank(),console.log(` ${h.cyan(pe(e))}`),s.blank(),s.detail(` (Your .env is at ${Oe(X(e,".env"))} \u2014 open it in any text editor.)`),s.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),s.blank(),process.exit(1)}async function ni(e){let t=e.target??".",n=ko(t)?t:wo(process.cwd(),t),i=To(n);i&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${n}`),s.detail(`Reason: ${i}`),s.blank(),s.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),s.blank(),process.platform==="win32"?(s.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${h.cyan("cd $HOME\\Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)):(s.detail("For example:"),console.log(` ${h.cyan("cd ~/Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)),s.blank(),process.exit(1)),process.platform==="win32"&&Io()&&(s.warn("You appear to be running in an elevated (Administrator) PowerShell."),s.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."),s.blank()),await dt("init",Zn);let o=await So(n);if(o.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${h.bold(n)}.`),s.detail("(Your .env and project files are in place.)"),s.blank(),o.nodeModulesMissing?(s.detail("It looks like a previous setup didn't finish installing dependencies."),s.detail("To pick up where it left off, run:"),s.blank(),n!==process.cwd()&&console.log(` ${h.cyan(`cd ${Et(t)}`)}`),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retries npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Everything is scaffolded and dependencies look installed."),s.detail("Pick the action you wanted:"),s.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${h.cyan("npx klaudius@latest configure")} ${h.dim("# change a credential / API key")}`),console.log(` ${h.cyan("npx klaudius@latest update")} ${h.dim("# pull the latest skills, scripts, lessons")}`),s.blank()),s.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),s.blank();return}if(o.kind==="occupied"){let f=t===".",g=await Po(n);if(g.length>0){s.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),s.detail(`You're in: ${Oe(n)}`),s.blank();for(let m of g)s.detail(m.finished?`Found a finished project at ${Oe(m.path)}. To work in it:`:`Found an unfinished setup at ${Oe(m.path)}. To pick up where it left off:`),s.blank(),m.finished?(console.log(` ${h.cyan(`cd ${Oe(m.path)}`)}`),console.log(` ${h.cyan("claude")} ${h.dim("# open Claude Code in the project")}`)):console.log(` ${h.cyan(pe(m.path))} ${h.dim("# then pick Resume")}`),s.blank();process.exit(1)}s.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),s.detail(`Path: ${n}`),s.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),s.blank(),f?(s.detail("Two ways forward:"),s.blank(),s.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`),s.blank(),s.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${h.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(s.detail(`The folder '${t}' already exists and isn't empty.`),s.detail("Either pick a different name:"),console.log(` ${h.cyan(`npx klaudius@latest init ${t}-2`)}`),s.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=null;e.answers&&(H=!0,r=await Eo(e.answers),s.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let a=e.license??r?.KLAUDIUS_LICENSE_KEY;H&&(!a||a.trim().length===0)&&U("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let c=await _o(a),l=P.spinner();l.start("Validating license");let p=await Hn(c);p.ok||(l.stop(`License invalid: ${p.reason??"unknown"}`,2),s.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),H&&U("license",`${p.reason??"The license could not be validated."} If you believe this is in error, email hello@klaudius.dev with your purchase details.`),process.exit(1)),l.stop(`License valid (${p.tier??"core"} tier)`);let u=await be();u.ok||(s.error(u.message??"Python version check failed."),s.blank(),s.detail(`Once you've installed Python 3.10+, re-run the same command: ${pe(n)}`),process.exit(1)),await yt();let w=de();w.ok||(s.error(w.message??"Node.js version check failed."),s.blank(),s.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${pe(n)}`),process.exit(1));let d,S=!1;if(r){let f=st(r);f||U("answers","The answers file is missing required fields. Required: PRICING, SUPABASE_URL, SUPABASE_SERVICE_KEY, SUPABASE_PAT, SUPABASE_PROJECT_REF, plus the credentials for your DEPLOY_PROVIDER (VERCEL_TOKEN, or CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, or NETLIFY_AUTH_TOKEN, or SELFHOST_DEPLOY_TARGET + SELFHOST_URL_TEMPLATE). Keys match a working .env."),d=f,s.success("Loaded setup answers (non-interactive mode)")}else if(o.kind==="partial")if(await bo(n)==="resume"){let g=await Ht(o.envPath,"utf-8"),m=st(K(g));m?(s.success("Resuming with values from your existing .env"),s.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),d=m,S=!0,d.aiPlan||(d=await N(d,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
|
|
30
|
+
runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(s.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),d=await N())}else{let g=await Ht(o.envPath,"utf-8"),m=st(K(g));d=await N(m??{})}else d=await N();d.licenseKey=c,await M(n,d),S||(s.success("Saved .env"),s.success(d.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),s.blank();for(let f=1;;f++){let g=P.spinner();g.start("Validating Supabase credentials");let m=await Ie({url:d.supabaseUrl,serviceKey:d.supabaseServiceKey});if(m.ok){g.stop("Supabase credentials accepted");break}g.stop(m.message??"Supabase check failed",2),f>=v&&ee(n,"Supabase",m.message??"Supabase check failed");let A=m.message??"Supabase check failed";s.blank(),H&&U("supabase",A),s.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${f+1} of ${v})`),s.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
31
31
|
${A}
|
|
32
32
|
|
|
33
33
|
Re-enter the URL, secret key, or PAT below. Press Enter on any
|
|
34
|
-
field to keep what's already there.`}),await M(n,d)}if(
|
|
34
|
+
field to keep what's already there.`}),await M(n,d)}if(s.blank(),d.deployProvider==="cloudflare")for(let f=1;;f++){let g=P.spinner();g.start("Validating Cloudflare token + account");let m=await pt({token:d.cloudflareApiToken??"",accountId:d.cloudflareAccountId??""});if(m.ok){g.stop(`Cloudflare credentials accepted (${m.projectCount??0} existing Pages project${m.projectCount===1?"":"s"})`);break}g.stop(m.message??"Cloudflare check failed",2),f>=v&&ee(n,"Cloudflare",m.message??"Cloudflare check failed");let A=m.message??"Cloudflare check failed";s.blank(),H&&U("cloudflare",A),s.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${f+1} of ${v})`),s.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
|
|
35
35
|
${A}
|
|
36
36
|
|
|
37
37
|
Re-enter the API token or Account ID below. The token needs the
|
|
38
38
|
"Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
|
|
39
|
-
the current value.`}),await M(n,d)}else if(d.deployProvider==="netlify")for(let f=1;;f++){let g=P.spinner();g.start("Validating Netlify token");let m=await
|
|
39
|
+
the current value.`}),await M(n,d)}else if(d.deployProvider==="netlify")for(let f=1;;f++){let g=P.spinner();g.start("Validating Netlify token");let m=await ft({token:d.netlifyAuthToken??""});if(m.ok){g.stop(m.accountSlug?`Netlify token accepted (team: ${m.accountSlug})`:"Netlify token accepted");break}g.stop(m.message??"Netlify check failed",2),f>=v&&ee(n,"Netlify",m.message??"Netlify check failed");let A=m.message??"Netlify check failed";s.blank(),H&&U("netlify",A),s.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${f+1} of ${v})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"netlify",banner:`Netlify rejected the token:
|
|
40
40
|
${A}
|
|
41
41
|
|
|
42
42
|
Generate a new token at
|
|
43
43
|
https://app.netlify.com/user/applications#personal-access-tokens
|
|
44
|
-
and paste it below. Press Enter to keep the current value.`}),await M(n,d)}else if(d.deployProvider==="selfhost")for(let f=1;;f++){let g=
|
|
45
|
-
`);f>=v&&ee(n,"Self-host",A),
|
|
44
|
+
and paste it below. Press Enter to keep the current value.`}),await M(n,d)}else if(d.deployProvider==="selfhost")for(let f=1;;f++){let g=Ve(d.selfhostDeployTarget??""),m=Ye(d.selfhostUrlTemplate??"");if(!g&&!m){s.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let A=[g&&`SELFHOST_DEPLOY_TARGET: ${g}`,m&&`SELFHOST_URL_TEMPLATE: ${m}`].filter(Boolean).join(`
|
|
45
|
+
`);f>=v&&ee(n,"Self-host",A),s.blank(),H&&U("selfhost",A),s.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${f+1} of ${v})`),s.blank(),d=await N(d,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
|
|
46
46
|
${A}
|
|
47
47
|
|
|
48
|
-
Re-enter them below. Press Enter on a field to keep its current value.`}),await M(n,d)}else for(let f=1;;f++){let g=P.spinner();g.start("Validating Vercel token");let m=await
|
|
48
|
+
Re-enter them below. Press Enter on a field to keep its current value.`}),await M(n,d)}else for(let f=1;;f++){let g=P.spinner();g.start("Validating Vercel token");let m=await ut(d.vercelToken??"");if(m.ok){g.stop(m.username?`Vercel token accepted (signed in as ${m.username})`:"Vercel token accepted");break}g.stop(m.message??"Vercel check failed",2),f>=v&&ee(n,"Vercel",m.message??"Vercel check failed");let A=m.message??"Vercel check failed";s.blank(),H&&U("vercel",A),s.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${f+1} of ${v})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"vercel",banner:`Vercel rejected the token:
|
|
49
49
|
${A}
|
|
50
50
|
|
|
51
51
|
Generate a new token at https://vercel.com/account/tokens and
|
|
52
|
-
paste it below. Press Enter to keep the current value.`}),await M(n,d)}
|
|
52
|
+
paste it below. Press Enter to keep the current value.`}),await M(n,d)}s.blank();for(let f=1;;f++){let g=ce(d.googlePlacesApiKey??""),m=P.spinner();m.start("Validating Google Places API key");let A=await Ce(d.googlePlacesApiKey??"");if(A.ok){if(m.stop("Google Places API key accepted"),g.changed){if(g.repairs.length>0){s.blank(),s.warn("Corrected look-alike characters in your Google Places API key:");for(let L of g.repairs)s.detail(` ${L}`);s.detail("These come from keys that were transcribed rather than copied."),s.detail("Google accepted the corrected key, and .env now holds it.")}d.googlePlacesApiKey=g.value,await M(n,d)}break}m.stop(A.message??"Google Places check failed",2),f>=v&&ee(n,"Google Places",A.message??"Google Places check failed");let T=A.message??"Google Places check failed";s.blank(),H&&U("google-places",T),s.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${f+1} of ${v})`),s.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"google-places",banner:`Google rejected the key:
|
|
53
53
|
${T}
|
|
54
54
|
|
|
55
55
|
Generate (or fix) the key at https://console.cloud.google.com
|
|
56
|
-
and paste it below. Press Enter to keep the current value.`}),await M(n,d)}let y=!1;if(d.outreachEnabled&&d.outreachChannels?.includes("email")&&d.emailAddress&&d.emailPassword&&d.emailSmtpHost&&d.emailSmtpPort&&d.emailImapHost&&d.emailImapPort){
|
|
56
|
+
and paste it below. Press Enter to keep the current value.`}),await M(n,d)}let y=!1;if(d.outreachEnabled&&d.outreachChannels?.includes("email")&&d.emailAddress&&d.emailPassword&&d.emailSmtpHost&&d.emailSmtpPort&&d.emailImapHost&&d.emailImapPort){s.blank();let f=0,g=!1,m;for(;!g;){f++;let A=P.spinner();A.start("Validating email credentials (SMTP + IMAP)");let T=d.emailProvider&&d.emailProvider!=="custom"?d.emailProvider:ke(d.emailSmtpHost),L=T?J[T]:void 0,D=await oe({emailAddress:d.emailAddress,emailLogin:d.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:d.emailPassword,emailSmtpHost:d.emailSmtpHost,emailSmtpPort:d.emailSmtpPort,emailImapHost:d.emailImapHost,emailImapPort:d.emailImapPort,usesAccountPassword:L?.usesAccountPassword});if(D.ok){A.stop("Email credentials accepted (SMTP + IMAP)");break}A.stop(D.message??"Email check failed",2);let Ge=`${T}\0${d.emailAddress}\0${d.emailPassword}`;if(L&&D.failureKind!=="network"&&m!==Ge){m=Ge;let me=Be(T,d.emailSmtpHost,d.emailImapHost),Z,qt=0;if(me.length>0){s.blank(),s.warn(`That server rejected the login. ${L.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let z of me){let Tt=P.spinner();Tt.start(`Trying ${z.label} (${z.smtpHost})`);let It=await oe({emailAddress:d.emailAddress,emailLogin:d.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:d.emailPassword,emailSmtpHost:z.smtpHost,emailSmtpPort:d.emailSmtpPort,emailImapHost:z.imapHost,emailImapPort:d.emailImapPort});if(It.ok){Tt.stop(`${z.label}: your login works here (${z.smtpHost})`),Z=z;break}It.failureKind!=="network"&&qt++,Tt.stop(It.failureKind==="network"?`${z.label}: unreachable`:`${z.label}: rejected too`,2)}}if(Z){if(s.blank(),s.success("Found it \u2014 your password was right all along; the server was the only problem."),H){s.detail(`Non-interactive: using the working ${Z.label} servers automatically.`),d.emailSmtpHost=Z.smtpHost,d.emailImapHost=Z.imapHost,await M(n,d);continue}let z=await P.confirm({message:`Use the ${Z.label} servers (${Z.smtpHost} / ${Z.imapHost})?`,initialValue:!0});if(P.isCancel(z)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
57
57
|
|
|
58
|
-
${
|
|
59
|
-
`),process.exit(0)),
|
|
58
|
+
${pe(n)}
|
|
59
|
+
`),process.exit(0)),z){d.emailSmtpHost=Z.smtpHost,d.emailImapHost=Z.imapHost,await M(n,d);continue}}else me.length>0&&(s.blank(),qt===0?s.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."):L.noAltWorkedHint&&s.warn(L.noAltWorkedHint))}let Qt=D.message??"Email check failed";s.blank(),s.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),s.detail("You can skip it now and wire it up later from inside the project."),s.blank(),H&&U("email",Qt);let _t=await P.select({message:`What would you like to do? ${h.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(P.isCancel(_t)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
60
60
|
|
|
61
|
-
${
|
|
62
|
-
`),process.exit(0)),
|
|
61
|
+
${pe(n)}
|
|
62
|
+
`),process.exit(0)),_t==="skip"){d.outreachChannels=(d.outreachChannels??[]).filter(me=>me!=="email"),d.outreachPriority=(d.outreachPriority??[]).filter(me=>me!=="email"),d.outreachChannels.length===0&&(d.outreachEnabled=!1),await M(n,d),y=!0,s.success("Skipped email for now. Setup will continue."),d.outreachEnabled?s.detail("Outreach will use your other channel(s); email stays off until it's fixed."):s.detail("Automated outreach is off until email is fixed \u2014 everything else works."),g=!0;break}_t==="edit"&&(s.blank(),d=await N(d,{onlySection:"email",banner:`${D.failedAt==="imap"?"IMAP":"SMTP"} check failed:
|
|
63
63
|
${Qt}
|
|
64
64
|
|
|
65
65
|
Re-enter the email address, app password, or server details below.
|
|
66
66
|
Press Enter on any field to keep its current value.
|
|
67
67
|
|
|
68
68
|
Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
|
|
69
|
-
at the "Server settings" question.`}),await M(n,d))}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="twilio"&&d.twilioAccountSid&&d.twilioAuthToken){
|
|
69
|
+
at the "Server settings" question.`}),await M(n,d))}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="twilio"&&d.twilioAccountSid&&d.twilioAuthToken){s.blank();for(let f=1;;f++){let g=P.spinner();g.start("Validating Twilio credentials");let m=await Vn({accountSid:d.twilioAccountSid,authToken:d.twilioAuthToken});if(m.ok){g.stop(m.friendlyName?`Twilio credentials accepted (${m.friendlyName})`:"Twilio credentials accepted");break}g.stop(m.message??"Twilio check failed",2),f>=v&&ee(n,"Twilio",m.message??"Twilio check failed");let A=m.message??"Twilio check failed";s.blank(),H&&U("sms",A),s.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${f+1} of ${v})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"sms",banner:`Twilio rejected the credentials:
|
|
70
70
|
${A}
|
|
71
71
|
|
|
72
72
|
Re-enter the Account SID or Auth Token below.
|
|
73
|
-
Press Enter on any field to keep its current value.`}),await M(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("letter")&&d.letterProvider){
|
|
73
|
+
Press Enter on any field to keep its current value.`}),await M(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("letter")&&d.letterProvider){s.blank();for(let f=1;;f++){let g=P.spinner();g.start("Validating letter provider credentials");let m=await ht({provider:d.letterProvider,pingenClientId:d.pingenClientId,pingenClientSecret:d.pingenClientSecret,pingenOrgId:d.pingenOrgId,postgridApiKey:d.postgridApiKey});if(m.ok){g.stop(m.friendlyName?`Letter provider credentials accepted (${m.friendlyName})`:"Letter provider credentials accepted");break}g.stop(m.message??"Letter provider check failed",2),f>=v&&ee(n,"Letter provider",m.message??"Letter provider check failed");let A=m.message??"Letter provider check failed";s.blank(),s.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${f+1} of ${v})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"letter",banner:`The letter provider rejected the credentials:
|
|
74
74
|
${A}
|
|
75
75
|
|
|
76
76
|
Re-enter them below.
|
|
77
|
-
Press Enter on any field to keep its current value.`}),await M(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="imessage"&&d.testPhone){
|
|
77
|
+
Press Enter on any field to keep its current value.`}),await M(n,d)}}if(d.outreachEnabled&&d.outreachChannels?.includes("sms")&&d.smsProvider==="imessage"&&d.testPhone){s.blank();for(let f=1;;f++){let g=P.spinner();g.start("Validating iMessage setup (sending a test ping)");let m=await Yn({testPhone:d.testPhone});if(m.ok){if(g.stop("iMessage dispatched (check your phone for the test ping)"),H){console.error("NOTE: iMessage dispatch succeeded but DELIVERY is unverified in non-interactive mode. Check the test message arrived on your phone; if not, open Messages on this Mac, confirm it's signed in with your Apple ID, and enable Settings \u2192 Messages \u2192 Text Message Forwarding on your iPhone.");break}let T=await P.confirm({message:"Did the test message actually arrive on your phone?",initialValue:!0});if(P.isCancel(T)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
78
78
|
|
|
79
|
-
${
|
|
80
|
-
`),process.exit(0)),T)break;g.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),f>=v&&ee(n,"iMessage","Test message dispatched but never delivered"),
|
|
79
|
+
${pe(n)}
|
|
80
|
+
`),process.exit(0)),T)break;g.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),f>=v&&ee(n,"iMessage","Test message dispatched but never delivered"),s.blank(),s.warn("Messages accepted the send but it didn't arrive. Usual fixes: make sure TEST_PHONE is in international format (+44\u2026 not 07\u2026); open Messages on this Mac and confirm it's signed in with your Apple ID; and on your iPhone enable Settings \u2192 Messages \u2192 Text Message Forwarding for this Mac. Fix, then retry."),s.blank(),d=await N(d,{onlySection:"sms",banner:`The test message was dispatched but never arrived on your phone.
|
|
81
81
|
Re-check the number below (international format with a leading +).
|
|
82
|
-
Press Enter on any field to keep its current value.`}),await M(n,d);continue}g.stop(m.message??"iMessage check failed",2),f>=v&&ee(n,"iMessage",m.message??"iMessage check failed");let A=m.message??"iMessage check failed";
|
|
82
|
+
Press Enter on any field to keep its current value.`}),await M(n,d);continue}g.stop(m.message??"iMessage check failed",2),f>=v&&ee(n,"iMessage",m.message??"iMessage check failed");let A=m.message??"iMessage check failed";s.blank(),H&&U("sms",A),s.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${f+1} of ${v})`),s.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"sms",banner:`iMessage check failed:
|
|
83
83
|
${A}
|
|
84
84
|
|
|
85
85
|
Either fix the underlying issue (sign in to Messages.app, configure
|
|
86
86
|
Text Message Forwarding) and press Enter through, or change SMS
|
|
87
|
-
provider to Twilio.`}),await M(n,d)}}if((d.notifyChannel??"telegram")==="telegram"&&d.telegramBotToken&&d.telegramChatId){
|
|
87
|
+
provider to Twilio.`}),await M(n,d)}}if((d.notifyChannel??"telegram")==="telegram"&&d.telegramBotToken&&d.telegramChatId){s.blank();let f=0,g=!1;for(;!g;){f++;let m=P.spinner();m.start("Validating Telegram bot + chat (sending a test ping)");let A=await Xt({botToken:d.telegramBotToken,chatId:d.telegramChatId});if(A.ok){m.stop(A.botHandle?`Telegram bot ${A.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),g=!0;break}m.stop(A.message??"Telegram check failed",2);let T=A.message??"Telegram check failed";s.blank(),s.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),s.blank(),H&&U("notifications",T);let L=await P.select({message:`What would you like to do? ${h.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(P.isCancel(L)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
88
88
|
|
|
89
|
-
${
|
|
90
|
-
`),process.exit(0)),L==="skip"){d.telegramBotToken=void 0,d.telegramChatId=void 0,await M(n,d),
|
|
89
|
+
${pe(n)}
|
|
90
|
+
`),process.exit(0)),L==="skip"){d.telegramBotToken=void 0,d.telegramChatId=void 0,await M(n,d),s.success("Skipped Telegram. Setup will continue."),s.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`."),g=!0;break}if(L==="edit"&&(s.blank(),d=await N(d,{onlySection:"notifications",banner:`Telegram check failed:
|
|
91
91
|
${T}
|
|
92
92
|
|
|
93
93
|
Re-enter the bot token or chat_id below.
|
|
94
|
-
Press Enter on any field to keep its current value.`}),await M(n,d),(d.notifyChannel??"telegram")!=="telegram"||!d.telegramBotToken||!d.telegramChatId)){
|
|
94
|
+
Press Enter on any field to keep its current value.`}),await M(n,d),(d.notifyChannel??"telegram")!=="telegram"||!d.telegramBotToken||!d.telegramChatId)){s.success("Skipped Telegram. Setup will continue."),g=!0;break}}}s.blank();let E=P.spinner();E.start("Downloading Klaudius template");let b;try{b=(await at({licenseKey:c,machineId:De(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:d.aiAgent,destDir:n})).filesExtracted,E.stop(`Downloaded ${b} files into ${h.bold(n)}`)}catch(f){E.stop(f.message,2);let g=d.aiAgent==="codex"?".codex/config.toml":".mcp.json";s.detail(`Your .env / ${g} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await Dt(X(n,"clients"),{recursive:!0});let C=await bn(n);await Me(n,Pn(Zn,C)),s.success("Wrote .klaudius/manifest.json");try{await ct(n,n,Object.keys(C))}catch{}let B=!1,ae="";if(e.skipSchema)s.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),s.detail(`Apply manually later via the SQL editor: ${d.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+d.supabaseProjectRef+"/sql/new").replace(d.supabaseProjectRef+".supabase.co","")}`);else{s.blank();let f=P.spinner();f.start("Applying schema to Supabase");let g=await Un({projectRoot:n,pat:d.supabasePat,projectRef:d.supabaseProjectRef});g.ok?f.stop("Schema applied (or already present)"):(f.stop(g.message??"Schema apply failed",2),B=!0,ae=`https://supabase.com/dashboard/project/${d.supabaseProjectRef}/sql/new`)}let R=[],_={};if(e.skipInstall)s.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{s.blank(),s.heading("Installing dependencies");let f=await gt(n);if(s.detail(`npm: ${f.npm}, pip: ${f.pip}, playwright: ${f.playwright}, patchright: ${f.patchright}`),f.npm==="failed"&&R.push("npm"),f.pip==="failed"&&R.push("pip"),f.playwright==="failed"&&R.push("playwright"),f.patchright==="failed"&&R.push("patchright"),_=f.hints??{},f.npm!=="failed"&&f.playwright!=="failed"){s.step("Checking the QA screenshot chain (serving a test page and screenshotting it)\u2026");let g=await kt(n);g.ok?s.success("QA screenshot chain verified (local page served and screenshotted)."):(s.warn(`QA screenshot chain check failed${g.stage?` (${g.stage})`:""}: ${g.detail??"unknown"}`),g.remediation&&s.detail(g.remediation))}}let le=d.outreachEnabled&&d.outreachPriority?.includes("whatsapp")&&(d.whatsappAccounts?.length??0)>0,j=!e.skipInstall&&!R.includes("npm");if(le&&j){s.blank(),s.heading("Linking WhatsApp accounts"),console.log(h.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
|
|
95
95
|
phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
|
|
96
|
-
Link a Device, and point it at the QR shown in this terminal.`)),
|
|
96
|
+
Link a Device, and point it at the QR shown in this terminal.`)),s.blank();for(let f of d.whatsappAccounts){console.log(h.cyan(`Pairing WhatsApp account '${f}'...`)),console.log(h.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${f})`));let g=Ft(process.execPath,["scripts/whatsapp.mjs","pair","--account",f],{cwd:n,stdio:"inherit"});g.status===0?s.detail(`Paired '${f}'.`):(console.log(h.yellow(`'${f}' did not pair (exit ${g.status??"signalled"}). You can finish later via:`)),console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${f}`))),s.blank()}}else if(le&&!j){s.blank(),console.log(h.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let f of d.whatsappAccounts)console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${f}`))}let we=d.emailAuth==="oauth-microsoft"&&d.outreachEnabled&&d.outreachChannels?.includes("email"),Le=!e.skipInstall&&!R.includes("pip"),k=f=>{console.log(h.dim("Connect it any time from the project folder with:")),console.log(h.cyan(` ${f?f.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(h.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(we&&Le){s.blank(),s.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(h.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
|
|
97
97
|
password. Your browser will open to Microsoft's sign-in page \u2014
|
|
98
98
|
sign in as `+(d.emailAddress??"your outreach mailbox")+` and approve.
|
|
99
99
|
(No browser on this machine? It falls back to a short code you can
|
|
100
|
-
enter from any device.)`)),
|
|
101
|
-
`:"",g=d.aiAgent==="codex"?"codex":"claude",m=d.aiAgent==="codex"?"Codex":"Claude Code",A=d.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";R.length>0&&(console.log(h.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),i.blank(),f&&process.stdout.write(f),console.log(` ${h.cyan(g)} ${h.dim(`# open ${m} in this folder`)}`),console.log(h.dim(" Then paste:")),console.log(h.cyan(` "Finish my Klaudius install \u2014 ${R.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(h.dim(` (Don't have ${m} yet? Install with: \`${A}\`)`)),i.blank(),console.log(h.dim("Or do it yourself:")),i.blank(),f&&process.stdout.write(f),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retry the failing installers")}`),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify everything")}`),i.blank()),B&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(ae)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),R.includes("pip")&&!_.pip&&(console.log(h.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(h.dim(`Python 3.10+. Install a newer one from ${To()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),i.blank());let L=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if(L.length>0){let D=L.length===1?"keeps":"keep";console.log(h.dim(`If ${L.join(" / ")} ${D} failing with network errors (ECONNRESET,`)),console.log(h.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(h.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}y&&(console.log(h.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${m}`)),console.log(h.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(h.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Io(d,n,e.target),y){let f=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(h.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(h.dim(`Your details are saved in .env. To finish it, ask ${f}:`)),console.log(h.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(h.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(h.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(h.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(h.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(i.blank(),console.log(h.yellow(`Note: your other channel(s) \u2014 ${(d.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),i.blank()}}async function M(e,t){await Mt(e,{recursive:!0}),await Nt(X(e,".env"),et(t),"utf-8"),t.aiAgent==="codex"?(await Mt(X(e,".codex"),{recursive:!0}),await Nt(X(e,".codex","config.toml"),nt(t),"utf-8")):(await Nt(X(e,".mcp.json"),tt(t),"utf-8"),await wt(e,"supabase"))}async function Eo(e){try{(await Ht(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ts(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(c=>s.has(c)),a=n.includes(".env"),r=t.includes(".klaudius");if(o&&a&&!r)return{kind:"partial",envPath:X(e,".env")};if(r&&a){let c=!0;try{c=!(await Ht(X(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function Po(e){i.blank(),i.warn(`Found a partial setup at ${h.bold(e)}.`),i.detail(`A previous init wrote ${h.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await P.select({message:`How would you like to proceed? ${h.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 P.isCancel(t)&&(P.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function So(e){if(e&&e.trim().length>0)return e;P.intro("Klaudius");let t=await P.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 P.isCancel(t)&&(P.cancel("Setup cancelled. No files written."),process.exit(0)),t}function bo(e){let t=ko(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 _o(){if(process.platform!=="win32")return!1;try{return Ut("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function To(){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 Io(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(h.green(h.bold("Project ready."))),e.aiPlan){let a=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${Ye[e.aiPlan]}`),console.log(h.dim(a?` \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(h.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),i.blank()}if(console.log(h.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let a=`cd ${At(n)}`;console.log(` ${h.cyan(a)}${" ".repeat(Math.max(1,27-a.length))}${h.dim("# go into your project folder")}`)}console.log(` ${h.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${h.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(h.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${h.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${h.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${h.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${h.cyan('"Run the pipeline for one client."')}`),console.log(h.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(h.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(h.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as Co,readFile as Ro}from"fs/promises";import{join as Ft,resolve as xo}from"path";import V from"picocolors";async function is(e){let t=e.target?xo(process.cwd(),e.target):process.cwd(),n=await ss(Ft(t,".env")),s=await ss(Ft(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{K(await Ro(Ft(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let a=await mt(t);i.blank(),i.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let r=[];if(a.npm==="failed"&&r.push("npm"),a.pip==="failed"&&r.push("pip"),a.playwright==="failed"&&r.push("playwright"),a.patchright==="failed"&&r.push("patchright"),r.length===0){i.blank(),console.log(V.green(V.bold("All dependencies installed."))),console.log(V.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(V.yellow(V.bold(`${r.join(", ")} still failing.`))),i.blank();for(let[u,k]of Object.entries(a.hints??{}))console.log(V.yellow(`Likely cause of ${u} failure:`)),console.log(V.dim(` ${k}`)),i.blank();let c=o==="codex"?"codex":"claude",l=o==="codex"?"Codex":"Claude Code",p=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(V.dim("Options:")),console.log(V.dim(` \u2022 Open ${l} in this folder (\`${c}\`) and paste:`)),console.log(V.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(V.dim(` (Don't have ${l} yet? Install with: \`${p}\`)`)),console.log(V.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(V.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function ss(e){try{return await Co(e),!0}catch{return!1}}import{readFile as Oo,writeFile as jt,access as vo}from"fs/promises";import{join as ve}from"path";import*as te from"@clack/prompts";import oe from"picocolors";import{mkdir as $o}from"fs/promises";import{spawnSync as os}from"child_process";async function as(e){let t=e.projectRoot??process.cwd(),n=ve(t,".env"),s=ve(t,".mcp.json"),o=ve(t,".codex","config.toml"),a=await Kt(ve(t,".klaudius","manifest.json")),r=await Kt(n);!a&&!r&&(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 c=ce();c.ok||(i.error(c.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 l={};try{let S=await Oo(n,"utf-8");l=K(S)}catch{i.warn("No .env found. Starting from an empty configuration.")}let p=gn(l);Object.keys(l).length>0&&(p.pipelineModes??=["classic"]),te.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await N(p),k=p.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==k&&(i.error(`Switching AI coding agent (${k} \u2192 ${u.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(` ${oe.cyan("npx klaudius@latest init <new-folder>")} ${oe.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==l.SUPABASE_URL||u.supabaseServiceKey!==l.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let S=await Ie({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});S.ok||(i.error(S.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let d=le(u.googlePlacesApiKey??"");if(d.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let S=await Ce(u.googlePlacesApiKey);if(S.ok){if(d.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let y of d.repairs)i.detail(` ${y}`);i.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=d.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(S.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(Lo(u,l)){let S=te.spinner();S.start("Validating email credentials (SMTP + IMAP)");let y=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:we(u.emailSmtpHost),E=await ie({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:y?J[y].usesAccountPassword:void 0});E.ok?S.stop("Email credentials accepted (SMTP + IMAP)"):(S.stop(E.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(E.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 jt(n,et(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await $o(ve(t,".codex"),{recursive:!0}),await jt(o,nt(u),"utf-8"),i.success("Updated .codex/config.toml")):(await jt(s,tt(u),"utf-8"),i.success("Updated .mcp.json"),await wt(t,"supabase")),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let S=await q();if(!(S!==null&&os(S.command[0],[...S.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!S)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 E=await te.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});te.isCancel(E)||!E?i.detail(`Skipped. Connect it any time with: ${S.command.join(" ")} scripts/ms_oauth.py login`):os(S.command[0],[...S.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: ${S.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),te.outro(oe.green("Configuration updated.")),await No(t,a)}function Lo(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 No(e,t){let n=await Kt(ve(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(` ${oe.cyan("npx klaudius@latest install")} ${oe.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${oe.cyan("npx klaudius@latest doctor")} ${oe.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(` ${oe.cyan("npx klaudius@latest init")} ${oe.dim("# pick Resume when prompted")}`),i.blank())}async function Kt(e){try{return await vo(e),!0}catch{return!1}}import{copyFile as rs,mkdir as Gt,readFile as Et,rm as pe,writeFile as Pt,access as ls}from"fs/promises";import{dirname as Bt,join as $}from"path";import{tmpdir as Mo}from"os";import*as fe from"@clack/prompts";import De from"picocolors";var He="0.30.3";async function cs(e){let t=e.projectRoot??process.cwd(),n=await En(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 w of it)delete n.files[w];let s,o=$(t,".env"),a,r;try{a=await Et(o,"utf-8"),r=K(a)}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=r.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 c=e.check?null:mn(a,r,hn);c!==null&&(await Pt(o,c,"utf-8"),i.detail("Backfilled new env keys")),await ct("update",He),fe.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${He}`),await gt();let p=r.AI_AGENT==="codex"?"codex":"claude-code",u=$(Mo(),`klaudius-update-${process.pid}-${Date.now()}`),k;try{i.heading("Downloading the latest Klaudius template");let w=await at({licenseKey:s,machineId:Me(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});i.success(`Fetched ${w.filesExtracted} canonical files`),k=u}catch(w){i.error(w.message),i.detail("Update aborted. Your project is unchanged."),await pe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await Do(k,t,n);if(e.check){let w=d.filter(f=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(f.state)),x=d.filter(f=>["conflict","locally-deleted","removed-modified"].includes(f.state));i.blank(),w.length===0?fe.outro(De.green("Already up to date.")):(i.detail(`${Y(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),fe.outro(De.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${w.length===0?"current":"behind"} pending=${w.length} conflicts=${x.length}`),await pe(u,{recursive:!0,force:!0}).catch(()=>{});return}let S=!1,y=d.find(w=>w.path===".gitignore"&&w.state==="conflict");if(y){let w=$(t,".gitignore"),x=await Et(w,"utf-8"),f=await Et($(k,".gitignore"),"utf-8"),{merged:g,added:m}=Ho(x,f);m.length>0&&await Pt(w,g,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",S=!0,i.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${Y(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let E=d.filter(w=>w.state==="new"),b=d.filter(w=>w.state==="clean-update"),C=d.filter(w=>w.state==="user-only"),B=d.filter(w=>w.state==="conflict"),ae=d.filter(w=>w.state==="no-change"),R=d.filter(w=>w.state==="locally-deleted"),_=d.filter(w=>w.state==="removed-clean"),re=d.filter(w=>w.state==="removed-modified"),j=[...B,...R,...re],ke=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${Y(ae.length,"file")} unchanged`),i.detail(`${Y(E.length,"new file")}`),i.detail(`${Y(b.length,"file")} updated cleanly (no local edits)`),i.detail(`${Y(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${Y(_.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${Y(B.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${Y(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${Y(re.length,"file")} removed upstream but edited locally (need your decision)`),ke>0&&(i.detail(`${Y(ke,"file")} kept deleted (previously resolved \u2014 skipped)`),ke<=10))for(let w of n.ignored)i.detail(` kept deleted: ${w}`);let $e=async()=>{let w=!1,x=f=>pe(f,{recursive:!0,force:!0}).catch(()=>{w=!0});await x($(t,".klaudius","incoming")),await x($(t,rt)),await x($(t,".klaudius","conflicts.md")),w&&i.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(E.length===0&&b.length===0&&_.length===0&&j.length===0&&!S){await $e(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=He,await Ne(t,n)),i.blank(),fe.outro(De.green("Already up to date.")),await pe(u,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let w of[...E,...b]){let x=$(k,w.path),f=$(t,w.path);await Gt(Bt(f),{recursive:!0}),await rs(x,f),n.files[w.path]=w.canonicalHash}E.length+b.length>0&&i.success(`Wrote ${Y(E.length+b.length,"file")}`);for(let w of _){let x=$(t,w.path);await pe(x,{force:!0}),delete n.files[w.path]}if(_.length>0&&i.success(`Deleted ${Y(_.length,"file")} removed upstream`),j.length>0){i.blank(),i.heading(`${j.length} conflict(s) need resolution`);let w=$(t,".klaudius","incoming");try{await pe(w,{recursive:!0,force:!0})}catch{}for(let m of[...B,...R]){let A=$(k,m.path),T=$(w,m.path);await Gt(Bt(T),{recursive:!0}),await rs(A,T)}let x=new Map,f=new Map;for(let m of B){let A=await On(t,m.path),T=await vn(t,m.path),L=await Et($(k,m.path),"utf-8"),D=$n(A,T,L,m.manifestHash);D!==null?(f.set(m.path,D),x.set(m.path,Ln(D,L))):A!==null&&(Te(A)||Te(L))?x.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):A===null?x.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._"]):x.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._"])}let g=$(t,rt);try{await pe(g,{recursive:!0,force:!0})}catch{}for(let[m,A]of f){let T=$(g,m);await Gt(Bt(T),{recursive:!0}),await Pt(T,A,"utf-8")}await Pt($(t,".klaudius","conflicts.md"),Uo(j,n.templateVersion,He,x,f),"utf-8"),B.length+R.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),f.size>0&&i.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=He,j.length===0?(delete n.pendingConflicts,await $e()):n.pendingConflicts=j.length,await Ne(t,n);try{await lt(t,k,await ge(k))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),j.length===0)fe.outro(De.green("Update complete."));else{let w=p==="codex"?"Codex":"Claude Code";fe.outro(De.yellow(`${j.length} conflict(s) staged. Open ${w} in this project and ask:
|
|
102
|
-
"Run /resolve-conflicts"`))}await
|
|
100
|
+
enter from any device.)`)),s.blank();let f=await Q();if(f){let[g,...m]=f.command,A=Ft(g,[...m,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});A.status===0?s.success("Outlook mailbox connected."):(s.blank(),console.log(h.yellow(`The Microsoft sign-in didn't complete (exit ${A.status??"signalled"}). Setup continues without it.`)),k(f))}else console.log(h.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),k(null)}else we&&!Le&&(s.blank(),console.log(h.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(h.cyan(" python3 scripts/ms_oauth.py login")));s.blank();let x=[...R,...B?["schema"]:[]];if(x.length>0){P.outro(h.yellow(h.bold(`Setup paused \u2014 ${x.join(", ")} failed.`))),console.log(h.dim("Your credentials and project files are all saved.")),s.blank();for(let[D,Ge]of Object.entries(_))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${Ge}`)),s.blank();let f=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${Et(e.target)}`)}
|
|
101
|
+
`:"",g=d.aiAgent==="codex"?"codex":"claude",m=d.aiAgent==="codex"?"Codex":"Claude Code",A=d.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";R.length>0&&(console.log(h.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),s.blank(),f&&process.stdout.write(f),console.log(` ${h.cyan(g)} ${h.dim(`# open ${m} in this folder`)}`),console.log(h.dim(" Then paste:")),console.log(h.cyan(` "Finish my Klaudius install \u2014 ${R.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(h.dim(` (Don't have ${m} yet? Install with: \`${A}\`)`)),s.blank(),console.log(h.dim("Or do it yourself:")),s.blank(),f&&process.stdout.write(f),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retry the failing installers")}`),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify everything")}`),s.blank()),B&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(ae)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),R.includes("pip")&&!_.pip&&(console.log(h.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(h.dim(`Python 3.10+. Install a newer one from ${Co()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),s.blank());let L=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if(L.length>0){let D=L.length===1?"keeps":"keep";console.log(h.dim(`If ${L.join(" / ")} ${D} failing with network errors (ECONNRESET,`)),console.log(h.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(h.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}y&&(console.log(h.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${m}`)),console.log(h.dim("to finish setting it up \u2014 your email details are saved in .env.")),s.blank()),console.log(h.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}if(Ro(d,n,e.target),y){let f=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(h.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(h.dim(`Your details are saved in .env. To finish it, ask ${f}:`)),console.log(h.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(h.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(h.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(h.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(h.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(s.blank(),console.log(h.yellow(`Note: your other channel(s) \u2014 ${(d.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),s.blank()}}async function M(e,t){await Dt(e,{recursive:!0}),await Mt(X(e,".env"),tt(t),"utf-8"),t.aiAgent==="codex"?(await Dt(X(e,".codex"),{recursive:!0}),await Mt(X(e,".codex","config.toml"),it(t),"utf-8")):(await Mt(X(e,".mcp.json"),nt(t),"utf-8"),await At(e,"supabase"))}async function So(e){try{(await Ut(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ti(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(c=>i.has(c)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:X(e,".env")};if(a&&r){let c=!0;try{c=!(await Ut(X(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function bo(e){s.blank(),s.warn(`Found a partial setup at ${h.bold(e)}.`),s.detail(`A previous init wrote ${h.bold(".env")} but didn't finish scaffolding.`),s.blank();let t=await P.select({message:`How would you like to proceed? ${h.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 P.isCancel(t)&&(P.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function _o(e){if(e&&e.trim().length>0)return e;P.intro("Klaudius");let t=await P.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 P.isCancel(t)&&(P.cancel("Setup cancelled. No files written."),process.exit(0)),t}function To(e){let t=Ao(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 Io(){if(process.platform!=="win32")return!1;try{return Ft("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Co(){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 Ro(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(h.green(h.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${We[e.aiPlan]}`),console.log(h.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(h.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),s.blank()}if(console.log(h.bold("Next steps:")),s.blank(),t!==process.cwd()&&n){let r=`cd ${Et(n)}`;console.log(` ${h.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${h.dim("# go into your project folder")}`)}console.log(` ${h.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${h.dim(`# opens ${o} in this project`)}`),s.blank(),console.log(h.bold(`Some starter prompts for ${o}:`)),s.blank(),console.log(` ${h.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${h.cyan(`I know I'm ready to start using Klaudius."`)}`),s.blank(),console.log(` ${h.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),s.blank(),console.log(` ${h.cyan('"Run the pipeline for one client."')}`),console.log(h.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(h.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(h.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),s.blank())}import{access as xo,readFile as Oo}from"fs/promises";import{join as jt,resolve as vo}from"path";import V from"picocolors";async function si(e){let t=e.target?vo(process.cwd(),e.target):process.cwd(),n=await ii(jt(t,".env")),i=await ii(jt(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{K(await Oo(jt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}s.heading("Installing dependencies");let r=await gt(t);s.blank(),s.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let a=[];if(r.npm==="failed"&&a.push("npm"),r.pip==="failed"&&a.push("pip"),r.playwright==="failed"&&a.push("playwright"),r.patchright==="failed"&&a.push("patchright"),a.length===0){s.blank(),console.log(V.green(V.bold("All dependencies installed."))),console.log(V.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(V.yellow(V.bold(`${a.join(", ")} still failing.`))),s.blank();for(let[u,w]of Object.entries(r.hints??{}))console.log(V.yellow(`Likely cause of ${u} failure:`)),console.log(V.dim(` ${w}`)),s.blank();let c=o==="codex"?"codex":"claude",l=o==="codex"?"Codex":"Claude Code",p=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(V.dim("Options:")),console.log(V.dim(` \u2022 Open ${l} in this folder (\`${c}\`) and paste:`)),console.log(V.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(V.dim(` (Don't have ${l} yet? Install with: \`${p}\`)`)),console.log(V.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(V.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function ii(e){try{return await xo(e),!0}catch{return!1}}import{readFile as $o,writeFile as Kt,access as Lo}from"fs/promises";import{join as ve}from"path";import*as te from"@clack/prompts";import re from"picocolors";import{mkdir as No}from"fs/promises";import{spawnSync as oi}from"child_process";async function ri(e){let t=e.projectRoot??process.cwd(),n=ve(t,".env"),i=ve(t,".mcp.json"),o=ve(t,".codex","config.toml"),r=await Gt(ve(t,".klaudius","manifest.json")),a=await Gt(n);!r&&!a&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=de();c.ok||(s.error(c.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let l={};try{let S=await $o(n,"utf-8");l=K(S)}catch{s.warn("No .env found. Starting from an empty configuration.")}let p=gn(l);Object.keys(l).length>0&&(p.pipelineModes??=["classic"]),te.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let u=await N(p),w=p.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==w&&(s.error(`Switching AI coding agent (${w} \u2192 ${u.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(` ${re.cyan("npx klaudius@latest init <new-folder>")} ${re.dim("# pick the new agent in the wizard")}`),s.blank(),s.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==l.SUPABASE_URL||u.supabaseServiceKey!==l.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let S=await Ie({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});S.ok||(s.error(S.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let d=ce(u.googlePlacesApiKey??"");if(d.changed&&u.googlePlacesApiKey){s.heading("Checking your Google Places API key");let S=await Ce(u.googlePlacesApiKey);if(S.ok){if(d.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let y of d.repairs)s.detail(` ${y}`);s.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=d.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(S.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(Mo(u,l)){let S=te.spinner();S.start("Validating email credentials (SMTP + IMAP)");let y=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:ke(u.emailSmtpHost),E=await oe({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:y?J[y].usesAccountPassword:void 0});E.ok?S.stop("Email credentials accepted (SMTP + IMAP)"):(S.stop(E.message??"Email check failed",2),s.warn("Writing the email settings exactly as you entered them \u2014 not verified."),s.detail(E.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,tt(u),"utf-8"),s.success("Updated .env"),u.aiAgent==="codex"?(await No(ve(t,".codex"),{recursive:!0}),await Kt(o,it(u),"utf-8"),s.success("Updated .codex/config.toml")):(await Kt(i,nt(u),"utf-8"),s.success("Updated .mcp.json"),await At(t,"supabase")),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let S=await Q();if(!(S!==null&&oi(S.command[0],[...S.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(s.blank(),!S)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 E=await te.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});te.isCancel(E)||!E?s.detail(`Skipped. Connect it any time with: ${S.command.join(" ")} scripts/ms_oauth.py login`):oi(S.command[0],[...S.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: ${S.command.join(" ")} scripts/ms_oauth.py login`))}}s.blank(),te.outro(re.green("Configuration updated.")),await Do(t,r)}function Mo(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 Do(e,t){let n=await Gt(ve(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(` ${re.cyan("npx klaudius@latest install")} ${re.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${re.cyan("npx klaudius@latest doctor")} ${re.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(` ${re.cyan("npx klaudius@latest init")} ${re.dim("# pick Resume when prompted")}`),s.blank())}async function Gt(e){try{return await Lo(e),!0}catch{return!1}}import{copyFile as ai,mkdir as Bt,readFile as Pt,rm as fe,writeFile as St,access as li}from"fs/promises";import{dirname as Vt,join as $}from"path";import{tmpdir as Ho}from"os";import*as he from"@clack/prompts";import He from"picocolors";var Ue="0.30.4";async function ci(e){let t=e.projectRoot??process.cwd(),n=await En(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 k of ot)delete n.files[k];let i,o=$(t,".env"),r,a;try{r=await Pt(o,"utf-8"),a=K(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=a.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 c=e.check?null:mn(r,a,hn);c!==null&&(await St(o,c,"utf-8"),s.detail("Backfilled new env keys")),await dt("update",Ue),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Ue}`),await yt();let p=a.AI_AGENT==="codex"?"codex":"claude-code",u=$(Ho(),`klaudius-update-${process.pid}-${Date.now()}`),w;try{s.heading("Downloading the latest Klaudius template");let k=await at({licenseKey:i,machineId:De(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});s.success(`Fetched ${k.filesExtracted} canonical files`),w=u}catch(k){s.error(k.message),s.detail("Update aborted. Your project is unchanged."),await fe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await Uo(w,t,n);if(e.check){let k=d.filter(f=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(f.state)),x=d.filter(f=>["conflict","locally-deleted","removed-modified"].includes(f.state));s.blank(),k.length===0?he.outro(He.green("Already up to date.")):(s.detail(`${Y(k.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(He.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${k.length===0?"current":"behind"} pending=${k.length} conflicts=${x.length}`),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}let S=!1,y=d.find(k=>k.path===".gitignore"&&k.state==="conflict");if(y){let k=$(t,".gitignore"),x=await Pt(k,"utf-8"),f=await Pt($(w,".gitignore"),"utf-8"),{merged:g,added:m}=Fo(x,f);m.length>0&&await St(k,g,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",S=!0,s.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${Y(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let E=d.filter(k=>k.state==="new"),b=d.filter(k=>k.state==="clean-update"),C=d.filter(k=>k.state==="user-only"),B=d.filter(k=>k.state==="conflict"),ae=d.filter(k=>k.state==="no-change"),R=d.filter(k=>k.state==="locally-deleted"),_=d.filter(k=>k.state==="removed-clean"),le=d.filter(k=>k.state==="removed-modified"),j=[...B,...R,...le],we=n.ignored?.length??0;if(s.blank(),s.heading("Change summary"),s.detail(`${Y(ae.length,"file")} unchanged`),s.detail(`${Y(E.length,"new file")}`),s.detail(`${Y(b.length,"file")} updated cleanly (no local edits)`),s.detail(`${Y(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${Y(_.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${Y(B.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${Y(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),s.detail(`${Y(le.length,"file")} removed upstream but edited locally (need your decision)`),we>0&&(s.detail(`${Y(we,"file")} kept deleted (previously resolved \u2014 skipped)`),we<=10))for(let k of n.ignored)s.detail(` kept deleted: ${k}`);let Le=async()=>{let k=!1,x=f=>fe(f,{recursive:!0,force:!0}).catch(()=>{k=!0});await x($(t,".klaudius","incoming")),await x($(t,lt)),await x($(t,".klaudius","conflicts.md")),k&&s.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(E.length===0&&b.length===0&&_.length===0&&j.length===0&&!S){await Le(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ue,await Me(t,n)),s.blank(),he.outro(He.green("Already up to date.")),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let k of[...E,...b]){let x=$(w,k.path),f=$(t,k.path);await Bt(Vt(f),{recursive:!0}),await ai(x,f),n.files[k.path]=k.canonicalHash}E.length+b.length>0&&s.success(`Wrote ${Y(E.length+b.length,"file")}`);for(let k of _){let x=$(t,k.path);await fe(x,{force:!0}),delete n.files[k.path]}if(_.length>0&&s.success(`Deleted ${Y(_.length,"file")} removed upstream`),j.length>0){s.blank(),s.heading(`${j.length} conflict(s) need resolution`);let k=$(t,".klaudius","incoming");try{await fe(k,{recursive:!0,force:!0})}catch{}for(let m of[...B,...R]){let A=$(w,m.path),T=$(k,m.path);await Bt(Vt(T),{recursive:!0}),await ai(A,T)}let x=new Map,f=new Map;for(let m of B){let A=await On(t,m.path),T=await vn(t,m.path),L=await Pt($(w,m.path),"utf-8"),D=$n(A,T,L,m.manifestHash);D!==null?(f.set(m.path,D),x.set(m.path,Ln(D,L))):A!==null&&(Te(A)||Te(L))?x.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):A===null?x.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._"]):x.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._"])}let g=$(t,lt);try{await fe(g,{recursive:!0,force:!0})}catch{}for(let[m,A]of f){let T=$(g,m);await Bt(Vt(T),{recursive:!0}),await St(T,A,"utf-8")}await St($(t,".klaudius","conflicts.md"),jo(j,n.templateVersion,Ue,x,f),"utf-8"),B.length+R.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),f.size>0&&s.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Ue,j.length===0?(delete n.pendingConflicts,await Le()):n.pendingConflicts=j.length,await Me(t,n);try{await ct(t,w,await ge(w))}catch{s.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(s.blank(),j.length===0)he.outro(He.green("Update complete."));else{let k=p==="codex"?"Codex":"Claude Code";he.outro(He.yellow(`${j.length} conflict(s) staged. Open ${k} in this project and ask:
|
|
102
|
+
"Run /resolve-conflicts"`))}await fe(u,{recursive:!0,force:!0}).catch(()=>{})}async function Uo(e,t,n){let i=await ge(e),o=new Set(i),r=new Set(n.ignored??[]),a=[];for(let c of i){if(r.has(c))continue;let l=await _e($(e,c)),p=n.files[c],u=$(t,c),w;try{await li(u),w=await _e(u)}catch{let d=p!==void 0&&!An.has(c)?"locally-deleted":"new";a.push({path:c,state:d,canonicalHash:l,manifestHash:p});continue}l===p?w===p?a.push({path:c,state:"no-change",canonicalHash:l,localHash:w,manifestHash:p}):a.push({path:c,state:"user-only",canonicalHash:l,localHash:w,manifestHash:p}):w===p?a.push({path:c,state:"clean-update",canonicalHash:l,localHash:w,manifestHash:p}):a.push({path:c,state:"conflict",canonicalHash:l,localHash:w,manifestHash:p})}for(let c of Object.keys(n.files)){if(o.has(c))continue;let l=n.files[c],p=$(t,c),u;try{await li(p),u=await _e(p)}catch{delete n.files[c];continue}u===l?a.push({path:c,state:"removed-clean",localHash:u,manifestHash:l}):a.push({path:c,state:"removed-modified",localHash:u,manifestHash:l})}return a}function Y(e,t){return`${e} ${t}${e===1?"":"s"}`}function Fo(e,t){let n=e.includes(`\r
|
|
103
103
|
`)?`\r
|
|
104
104
|
`:`
|
|
105
|
-
`,
|
|
106
|
-
`)}import{existsSync as
|
|
107
|
-
`)),n.push(await
|
|
105
|
+
`,i=e.split(/\r?\n/),o=new Set(i.map(l=>l.trim()).filter(l=>l!=="")),r=[];for(let l of t.split(/\r?\n/)){let p=l.trim();p===""||p.startsWith("#")||o.has(p)||(r.push(p),o.add(p))}if(r.length===0)return{merged:e,added:r};let a=[...i];for(;a.length>0&&a[a.length-1].trim()==="";)a.pop();a.push("","# Added by `klaudius update` (new canonical ignore patterns)",...r);let c=[...new Set(i.map(l=>l.trim()).filter(l=>l.startsWith("!")))].filter(l=>!r.includes(l));return a.push(...c,""),{merged:a.join(n),added:r}}function jo(e,t,n,i=new Map,o=new Map){let r=e.filter(u=>u.state==="conflict").length,a=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 p=[];r>0&&p.push(`${r} file${r===1?"":"s"} ha${r===1?"s":"ve"} BOTH local edits AND upstream changes`),a>0&&p.push(`${a} file${a===1?"":"s"} you deleted locally ${a===1?"is":"are"} still shipped by the canonical template`),c>0&&p.push(`${c} file${c===1?"":"s"} ${c===1?"was":"were"} removed upstream but edited locally`),l.push(p.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}\``),o.has(u.path)&&l.push(`- Pre-edit base (3-way merge ancestor): \`.klaudius/conflict-base/${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 w=i.get(u.path);w&&w.length>0&&(l.push(""),l.push("**What upstream changed since your base:**"),l.push(""),l.push(...w),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(`
|
|
106
|
+
`)}import{existsSync as Ko}from"fs";import{access as Go,readFile as Fe,stat as Bo}from"fs/promises";import{homedir as Vo}from"os";import{join as W}from"path";import F from"picocolors";import{spawn as di,spawnSync as Yo}from"child_process";async function ui(e){let t=e.projectRoot??process.cwd(),n=[];console.log(F.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
107
|
+
`)),n.push(await Wo());let i=await Xo();i&&n.push(i),n.push(await zo());let o=W(t,".env"),r=W(t,".klaudius","manifest.json"),a=W(t,".mcp.json"),c=W(t,".codex","config.toml"),l=await ne(o),p=await ne(r),u="claude-code";if(l)try{K(await Fe(o,"utf-8")).AI_AGENT==="codex"&&(u="codex")}catch{}if(u==="claude-code"){let y=await ne(W(t,"AGENTS.md")),E=!await ne(W(t,".claude"));y&&E&&(u="codex")}n.push({name:".env present",status:l?"ok":"fail",detail:l?o:"missing",nextAction:l?void 0:"Run `npx klaudius@latest init` in this folder."});let w=!1;if(l){let y={};try{y=K(await Fe(o,"utf-8"))}catch{}let E=Xe(y.AI_PLAN),b=Ze(y.QA_PHASE)??Ae(E);w=b==="off";let C=E==="codex-plus"&&u==="codex"?` \xB7 model pin ${xt}`:"";n.push({name:"Plan / QA pass",status:E?"ok":"warn",detail:E?`${We[E]} \xB7 QA pass ${b}${C}`:`plan not set \xB7 QA pass ${b}`,nextAction:E?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."})}{let y=0,E="";if(p)try{let b=JSON.parse(await Fe(r,"utf-8"));y=typeof b.pendingConflicts=="number"?b.pendingConflicts:0,E=typeof b.templateVersion=="string"?b.templateVersion:""}catch{}n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?y>0?"warn":"ok":"fail",detail:p?y>0?`${E||"version unknown"} \u2014 ${y} conflict${y===1?"":"s"} from the last update still unresolved`:E?`${r} (template ${E})`:r:"missing",nextAction:p?y>0?'Open your agent in this folder and say "resolve the conflicts" \u2014 until then some files are still on the previous version.':void 0:l?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."})}if(u==="codex"){let y=await ne(c);n.push({name:".codex/config.toml present",status:y?"ok":"warn",detail:y?c:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let y=await ne(a);n.push({name:".mcp.json present",status:y?"ok":"warn",detail:y?a:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await cr(u)),process.platform==="win32"){let y=await Qo(t);y&&n.push(y)}if(n.push(await qo(t)),n.push(await Jo(t)),n.push(await Zo(t,w)),n.push(await tr()),n.push(await er(t)),!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 y=await Fe(o,"utf-8"),E=K(y);await nr(E,n,t)}console.log();for(let y of n){let E=y.status==="ok"?F.green("\u2713"):y.status==="warn"?F.yellow("\u26A0"):y.status==="skip"?F.dim("\xB7"):F.red("\u2717");console.log(` ${E} ${y.name}${y.detail?F.dim(` \u2014 ${y.detail}`):""}`),y.nextAction&&console.log(` ${F.dim("\u2192")} ${F.cyan(y.nextAction)}`)}let d=n.filter(y=>y.status==="fail").length,S=n.filter(y=>y.status==="warn").length;console.log(),d===0&&S===0?console.log(F.green(F.bold("Everything checks out. You're good to go."))):d===0?console.log(F.yellow(F.bold(`${S} warning${S===1?"":"s"} \u2014 review above.`))):(console.log(F.red(F.bold(`${d} failed check${d===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function ne(e){try{return await Go(e),!0}catch{return!1}}async function Wo(){let e=await be();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 zo(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let n=parseInt(t[1],10),i=parseInt(t[2],10);return n<22||n===22&&i<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function Qo(e){let t=Ee([{label:"your Windows user folder",path:Vo()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",i=await Yt("npm",["config","get","script-shell"],!0),o=i.code===0?i.stdout.trim():void 0;if(Pe(o,Ko))return{name:n,status:"ok",detail:`${t[0].label} contains ${t[0].chars.map(l=>`"${l}"`).join(", ")}, but npm's script-shell (${o}) handles it`};let{detail:r,action:a}=Se(t,"doctor"),c=t.some(l=>l.chars.includes("&"));return{name:n,status:c?"fail":"warn",detail:r,nextAction:a}}async function qo(e){let t=W(e,"node_modules");if(!await ne(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await Bo(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 Jo(e){let t=process.platform==="darwin"?W(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?W(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):W(process.env.HOME??"",".cache","ms-playwright");return await ne(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 Xo(){let e=await Lt();return e.status==="irrelevant"?null:e.status==="ok"?{name:"python3 runtime command",status:"ok",detail:`Python ${e.version}`}:e.status==="no-python"?{name:"python3 runtime command",status:"skip",detail:"no Python found \u2014 see the Python check above"}:{name:"python3 runtime command",status:"fail",detail:e.literal==="stub"?"`python3` is the Microsoft Store placeholder \u2014 every pipeline `python3` call dies":`\`python3\` is missing (your Python answers to \`${e.fallback.command.join(" ")}\`) \u2014 every pipeline \`python3\` call dies`,nextAction:"Fixed automatically by the updater \u2014 running `npx klaudius@latest update` creates the python3 alias from the real Python."}}async function Zo(e,t){if(!await ne(W(e,"node_modules","@playwright","cli")))return{name:"QA screenshot chain",status:"skip",detail:"project dependencies not installed",nextAction:"Run `npx klaudius@latest install` first."};let i=await kt(e);if(i.ok)return{name:"QA screenshot chain",status:"ok",detail:"served a page with python3 and screenshotted it"};let o=i.stage!=="python3-server"&&t;return{name:"QA screenshot chain",status:o?"warn":"fail",detail:`${i.stage?`${i.stage}: `:""}${i.detail??"failed"}`+(o?" (QA pass is off \u2014 this matters when you enable it, and for browser-based gathering)":""),nextAction:i.remediation}}async function er(e){let t=W(e,".klaudius","notify-failures.log");try{let n=(await Fe(t,"utf8")).trim();if(!n)return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"};let i=n.split(/\r?\n/);return{name:"Alert delivery",status:"warn",detail:`${i.length} failed send${i.length===1?"":"s"} recorded; latest: "${i[i.length-1]}"`,nextAction:"Check TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID in .env (rate limits also land here). Delete .klaudius/notify-failures.log once resolved."}}catch{return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"}}}async function tr(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
|
|
108
108
|
try:
|
|
109
|
-
${e.map(
|
|
109
|
+
${e.map(r=>` import ${r}`).join(`
|
|
110
110
|
`)}
|
|
111
111
|
except Exception as e:
|
|
112
112
|
print(str(e))
|
|
113
113
|
sys.exit(1)
|
|
114
|
-
`,n=await
|
|
115
|
-
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function
|
|
116
|
-
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await ne(W(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 sa(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 a=await o.text();return o.status===400&&/postal_address/.test(a)?(e.OUTREACH_CHANNELS??"").split(",").some(c=>c.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 ia(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(p=>p.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 a=await ft({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(!a.ok)return{name:t,status:"fail",detail:a.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let r=`${s} credentials accepted`+(a.friendlyName?` (${a.friendlyName})`:""),c=(e.SUPABASE_ANON_KEY??"").trim();if(!c)return{name:t,status:"warn",detail:r+", 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 l=tn(c);if(l&&l!=="anon")return{name:t,status:"fail",detail:r+`, but SUPABASE_ANON_KEY holds a '${l}' 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 p=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:c,Authorization:`Bearer ${c}`}});if(p.ok){let u=await p.json();if(Array.isArray(u)&&u.length>0)return{name:t,status:"fail",detail:r+", 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 p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(u=>!(e[u]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:r+`, but PostGrid needs your return address and .env is missing ${p.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:r}}async function oa(e,t){let n="Email credentials (SMTP + IMAP)",s=ta(e);if(s==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(ps(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."}:na(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 l=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(p=>p.endsWith("_PORT")?!e[p]||!/^\d+$/.test(e[p].trim()):!e[p]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${l.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=Ze(e),a=o&&o!=="custom"?o:we(e.EMAIL_SMTP_HOST),r={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,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:a?J[a].usesAccountPassword:void 0,draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},c=await ie(r);if(c.ok){if(c.draftsFolderIssue){let{configured:l,detected:p}=c.draftsFolderIssue;return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the server has no "${l}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`,nextAction:p?`Set EMAIL_DRAFTS_FOLDER="${p}" in .env (or ask your AI agent to).`:"Set EMAIL_DRAFTS_FOLDER in .env to this mailbox's drafts folder name."}}return{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(c.failureKind==="network")return{name:n,status:"fail",detail:c.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(a){let l=Ge(a,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(l.length>0){console.log(F.dim(` (email login rejected \u2014 probing ${J[a].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let k of l){let d=await ie({...r,emailSmtpHost:k.smtpHost,emailImapHost:k.imapHost});if(!d.ok&&d.failureKind!=="network"&&p++,d.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${k.label} (${k.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${k.smtpHost} and EMAIL_IMAP_HOST=${k.imapHost} in .env (or ask your AI agent to).`}}let u=(c.message??"login rejected").split(/\.\s|\n/)[0];return p===0?{name:n,status:"fail",detail:`${u} \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:`${u} \u2014 tried all ${J[a].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:a==="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`.":a==="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:c.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}async function aa(e){let t=[];for(let n of fn(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=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,a=await ie({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,draftsFolder:(e[o]??"").trim()||"Drafts"});if(a.ok)if(a.draftsFolderIssue){let{configured:r,detected:c}=a.draftsFolderIssue;t.push({name:s,status:"warn",detail:`authenticated (${n.smtpHost}), but the server has no "${r}" folder \u2014 saving drafts from this mailbox would fail`,nextAction:c?`Set ${o}="${c}" in .env (or ask your AI agent to).`:`Set ${o} in .env to this mailbox's drafts folder name.`})}else t.push({name:s,status:"ok",detail:`authenticated (${n.smtpHost})`});else t.push({name:s,status:"fail",detail:a.message,nextAction:a.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 ra(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 Vt(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
|
|
117
|
-
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:
|
|
118
|
-
`));let
|
|
114
|
+
`,n=await Q();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 i=n.command,o=await Yt(i[0],[...i.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(`
|
|
115
|
+
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function nr(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let a=await Ie({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:a.ok?"ok":"fail",detail:a.ok?"connected":a.message,nextAction:a.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 i=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(i==="selfhost"){let a=e.SELFHOST_DEPLOY_TARGET??"",c=e.SELFHOST_URL_TEMPLATE??"",l=[],p=Ve(a);p&&l.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let u=Ye(c);u&&l.push(`SELFHOST_URL_TEMPLATE: ${u}`),t.push({name:"Self-host deploy config",status:l.length===0?"ok":"fail",detail:l.length===0?`target ${a} (SSH reachability tested at first deploy)`:l.join("; "),nextAction:l.length===0?void 0:"Run `npx klaudius@latest configure` and fix the self-host deployment answers."})}else if(i==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let a=await pt({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:a.ok?"ok":"fail",detail:a.ok?`valid (${a.projectCount??0} Pages project${a.projectCount===1?"":"s"})`:a.message,nextAction:a.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(i==="netlify")if(e.NETLIFY_AUTH_TOKEN){let a=await ft({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:a.ok?"ok":"fail",detail:a.ok?a.accountSlug?`valid (team: ${a.accountSlug})`:"valid":a.message,nextAction:a.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 a=await ut(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:a.ok?"ok":"fail",detail:a.ok?a.username??"valid":a.message,nextAction:a.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 a=await Ce(e.GOOGLE_PLACES_API_KEY),c=ce(e.GOOGLE_PLACES_API_KEY);a.ok&&c.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 "+(c.repairs.length>0?`it contains look-alike characters (${c.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:a.ok?"ok":"fail",detail:a.ok?"accepted":a.message,nextAction:a.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 ar(e,n)),t.push(...await lr(e)),t.push(await or(e)),t.push(await rr(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 a=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:a&&e.EMAIL_ADDRESS?"ok":"fail",detail:a&&e.EMAIL_ADDRESS?`alerts go to ${a}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:a&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(r==="sms"){let a=e.NOTIFY_TO||e.TEST_PHONE,c=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:a&&c?"ok":"fail",detail:a&&c?`alerts go to ${a} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:a?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:a&&c?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let a=await Jt({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:a.ok?"ok":"fail",detail:a.ok?`bot ${a.botHandle??"ok"} (chat_id not tested)`:a.message,nextAction:a.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 ir(e){let t=r=>!!r&&/^\d+$/.test(r.trim()),n=pi(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),i=(e.OUTREACH_CHANNELS??"").split(",").map(r=>r.trim()),o=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&i.includes("email");return o&&n?"active":o?"incomplete":n?"parked":"unconfigured"}function pi(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function sr(e){let t="Email account (Microsoft sign-in)",n=await Q(),o=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[a,...c]=n.command,l=Yo(a,[...c,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),p=`${l.stdout??""}${l.stderr??""}`.trim();if(l.status===0){let u=/signed in as (\S+)/.exec(p)?.[1];return{name:t,status:"ok",detail:u?`signed in as ${u} (token refresh works)`:"signed in (token refresh works)"}}return{name:t,status:"fail",detail:p.split(`
|
|
116
|
+
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await ne(W(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 or(e){let t="Database schema up to date",n=(e.SUPABASE_URL??"").trim().replace(/\/+$/,""),i=(e.SUPABASE_SERVICE_KEY??"").trim();if(!n||!i)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:i,Authorization:`Bearer ${i}`}});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(c=>c.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 rr(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(p=>p.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 ht({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 a=`${i} credentials accepted`+(r.friendlyName?` (${r.friendlyName})`:""),c=(e.SUPABASE_ANON_KEY??"").trim();if(!c)return{name:t,status:"warn",detail:a+", 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 l=tn(c);if(l&&l!=="anon")return{name:t,status:"fail",detail:a+`, but SUPABASE_ANON_KEY holds a '${l}' 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 p=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:c,Authorization:`Bearer ${c}`}});if(p.ok){let u=await p.json();if(Array.isArray(u)&&u.length>0)return{name:t,status:"fail",detail:a+", 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 p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(u=>!(e[u]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:a+`, but PostGrid needs your return address and .env is missing ${p.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:a}}async function ar(e,t){let n="Email credentials (SMTP + IMAP)",i=ir(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(pi(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."}:sr(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 l=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(p=>p.endsWith("_PORT")?!e[p]||!/^\d+$/.test(e[p].trim()):!e[p]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${l.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=et(e),r=o&&o!=="custom"?o:ke(e.EMAIL_SMTP_HOST),a={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,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?J[r].usesAccountPassword:void 0,draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},c=await oe(a);if(c.ok){if(c.draftsFolderIssue){let{configured:l,detected:p}=c.draftsFolderIssue;return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the server has no "${l}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`,nextAction:p?`Set EMAIL_DRAFTS_FOLDER="${p}" in .env (or ask your AI agent to).`:"Set EMAIL_DRAFTS_FOLDER in .env to this mailbox's drafts folder name."}}return{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(c.failureKind==="network")return{name:n,status:"fail",detail:c.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 l=Be(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(l.length>0){console.log(F.dim(` (email login rejected \u2014 probing ${J[r].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let w of l){let d=await oe({...a,emailSmtpHost:w.smtpHost,emailImapHost:w.imapHost});if(!d.ok&&d.failureKind!=="network"&&p++,d.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${w.label} (${w.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${w.smtpHost} and EMAIL_IMAP_HOST=${w.imapHost} in .env (or ask your AI agent to).`}}let u=(c.message??"login rejected").split(/\.\s|\n/)[0];return p===0?{name:n,status:"fail",detail:`${u} \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:`${u} \u2014 tried all ${J[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:c.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}async function lr(e){let t=[];for(let n of fn(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=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,r=await oe({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,draftsFolder:(e[o]??"").trim()||"Drafts"});if(r.ok)if(r.draftsFolderIssue){let{configured:a,detected:c}=r.draftsFolderIssue;t.push({name:i,status:"warn",detail:`authenticated (${n.smtpHost}), but the server has no "${a}" folder \u2014 saving drafts from this mailbox would fail`,nextAction:c?`Set ${o}="${c}" in .env (or ask your AI agent to).`:`Set ${o} in .env to this mailbox's drafts folder name.`})}else t.push({name:i,status:"ok",detail:`authenticated (${n.smtpHost})`});else t.push({name:i,status:"fail",detail:r.message,nextAction:r.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 cr(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 Yt(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
|
|
117
|
+
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:i}}function Yt(e,t,n=!1){return new Promise(i=>{let o=n?di([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):di(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",c=>{r+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>i({code:c??1,stdout:r,stderr:a})),o.on("error",()=>i({code:1,stdout:r,stderr:a}))})}import{existsSync as dr}from"fs";import{spawnSync as ur}from"child_process";import{join as pr,resolve as fr}from"path";import G from"picocolors";async function fi(e){let t=fr(e.projectRoot??process.cwd()),n=pr(t,"scripts","whatsapp.mjs");dr(n)||(console.error(G.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(G.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(G.dim(`Looked for: ${n}`)),process.exit(1));let i=(e.label??"primary").trim(),o=i.replace(/[^A-Za-z0-9_-]/g,"");o||(console.error(G.red(`Invalid label '${i}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),o!==i&&console.error(G.yellow(`Note: cleaned label '${i}' \u2192 '${o}' (filename-safe characters only).`)),console.log(G.cyan(`Pairing WhatsApp account '${o}'...`)),console.log(G.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.
|
|
118
|
+
`));let r=ur(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(G.green(`Paired '${o}'.`)),console.log(G.dim(`
|
|
119
119
|
If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
120
120
|
WHATSAPP_ACCOUNTS=primary,${o}
|
|
121
|
-
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}
|
|
121
|
+
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(G.red(`Pair failed: ${r.error.message}`)):(console.error(G.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(G.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(G.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(G.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as $e,spawn as hr}from"child_process";import{existsSync as je,mkdirSync as mr,readdirSync as gr,rmSync as yi,mkdtempSync as wi}from"fs";import{homedir as Wt,tmpdir as ki}from"os";import{join as q}from"path";import ie from"picocolors";var yr=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function hi(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Ai(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&Ke()&&Pi();let t=kr();if(t&&!e.reinstall&&!e.from){gi(),console.log(ie.green("Opened the Klaudius app.")),mi();return}let n=await Er(e.from);console.log(ie.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Pr(n):Sr(n),gi(),console.log(ie.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),mi()}function mi(){process.platform==="darwin"?console.log(ie.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(ie.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function bt(){return q(Wt(),"Applications","Klaudius.app")}function Ei(){return process.env.LOCALAPPDATA??q(Wt(),"AppData","Local")}function wr(){return q(Ei(),"Klaudius")}function Ke(){let e=q(Ei(),"Programs");try{for(let t of gr(e)){if(!/laudius/i.test(t))continue;let n=q(e,t,"Klaudius.exe");if(je(n))return n}}catch{}return null}function kr(){return process.platform==="darwin"?je(bt()):Ke()!==null}async function Ar(){try{let{readFileSync:e}=await import("fs"),n=e(q(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function Er(e){if(e)return je(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await Ar();t||(console.error("Couldn't find your license key."),console.error("Run this from inside your Klaudius folder (the one `npx klaudius init` created)."),process.exit(1));let n=`${yr}?file=${encodeURIComponent(hi())}`,i=q(wi(q(ki(),"klaudius-app-")),hi());console.log(ie.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.30.4"}});if(!o.ok){let c=`HTTP ${o.status}`;try{let l=await o.json();l.reason&&(c=l.reason)}catch{}throw new Error(c)}let r=Buffer.from(await o.arrayBuffer()),{writeFileSync:a}=await import("fs");return a(i,r),i}catch(o){console.error(`Couldn't download the app (${o.message}). If you're offline, try again later; otherwise email hello@klaudius.dev.`),process.exit(1)}}function Pr(e){let t=q(Wt(),"Applications");mr(t,{recursive:!0});let n=wi(q(ki(),"klaudius-app-x-")),i=$e("ditto",["-xk",e,n],{stdio:"pipe"});i.status!==0&&(console.error(`Couldn't extract the app: ${i.stderr?.toString().trim()}`),process.exit(1));let o=q(n,"Klaudius.app");je(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),yi(bt(),{recursive:!0,force:!0});let r=$e("mv",[o,bt()],{stdio:"pipe"});r.status!==0&&(console.error(`Couldn't install to ~/Applications: ${r.stderr?.toString().trim()}`),process.exit(1))}function Sr(e){/\.exe$/i.test(e)||(console.error("Expected the Klaudius installer (.exe). A zip can't be installed here \u2014 an unzipped copy can never update itself."),process.exit(1));let t=$e(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!br(6e4)){let i=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,o=Ke();if(o&&Si(o)){console.log(ie.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(ie.dim("Open it from the Start Menu if it doesn't appear shortly."));return}console.error(`Klaudius didn't finish installing (${i}).`),console.error("Check your Start Menu for Klaudius \u2014 it may still be finishing."),console.error("If it isn't there, email hello@klaudius.dev."),process.exit(1)}Pi()}function br(e){let t=Date.now()+e;for(;;){let n=Ke();if(n)return n;if(Date.now()>=t)return null;_r(500)}}function _r(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Pi(){let e=wr();if(!je(q(e,"app","Klaudius.exe")))return;console.log(ie.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
|
|
122
|
+
$legacy = '${e.replace(/'/g,"''")}'
|
|
123
|
+
# Compare against the directory PLUS its separator, so a sibling folder whose
|
|
124
|
+
# name merely starts with the same text ("Klaudius Desktop") is never matched.
|
|
125
|
+
$legacyPrefix = $legacy.TrimEnd('\\') + '\\'
|
|
122
126
|
$W = New-Object -ComObject WScript.Shell
|
|
123
127
|
foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetFolderPath('Desktop'))) {
|
|
124
|
-
$
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
128
|
+
$lnk = Join-Path $dir 'Klaudius.lnk'
|
|
129
|
+
if (Test-Path -LiteralPath $lnk) {
|
|
130
|
+
$target = $W.CreateShortcut($lnk).TargetPath
|
|
131
|
+
if ($target -and $target.StartsWith($legacyPrefix, [StringComparison]::OrdinalIgnoreCase)) {
|
|
132
|
+
Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}`;$e("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{yi(e,{recursive:!0,force:!0})}catch{console.log(ie.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function gi(){if(process.platform==="darwin"){$e("open",["-a",bt()],{stdio:"pipe"});return}let e=Ke();if(!e||Si(e))return;hr(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function Si(e){let t=$e("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(i=>i.trim().toLowerCase()===n)}import{spawnSync as Tr}from"child_process";var zt="--use-system-ca";function bi(){let e=process.env.NODE_OPTIONS??"";if(e.includes(zt)||!de().ok)return;let n=e?`${e} ${zt}`:zt,i=Tr(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}bi();var Cr="0.30.4",se=new Ir;se.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Cr);se.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 an({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});se.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").option("--answers <file>","Non-interactive setup: read answers from a JSON or dotenv-format file (same keys as .env). On a failed check, exits with code 2 and an INIT-BLOCKED line instead of reopening the wizard.").action(async(e,t)=>{try{await ni({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers})}catch(n){console.error("init failed:",n.message),process.exit(1)}});se.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 si({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});se.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await ri({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});se.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").option("--check","Report whether an update is available without changing anything").action(async e=>{try{await ci({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});se.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 ui({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});se.command("app").description("Install (first run) and open the Klaudius desktop app").option("--from <archive>","Install from a local app archive (testing)").option("--reinstall","Reinstall even if already installed").action(async e=>{try{await Ai({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});se.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 fi({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});se.parse(process.argv);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.30.
|
|
3
|
+
"version": "0.30.4",
|
|
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": {
|