klaudius 0.30.0 → 0.30.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +21 -21
- package/package.json +3 -3
package/dist/bin.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
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 as Zt,l as en,o as tn,q as Ae,r as Ye,s as L}from"./chunk-LF3CA26Y.js";import{Command as
|
|
2
|
+
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 as Zt,l as en,o as tn,q as Ae,r as Ye,s as L}from"./chunk-LF3CA26Y.js";import{Command as Aa}from"commander";import{spawn as on}from"child_process";import{existsSync as Ds}from"fs";import{homedir as Hs}from"os";import O from"picocolors";import{win32 as Ss}from"path";var bs=["&","^","%","!"];function _s(e){return bs.filter(t=>e.includes(t))}function Ee(e){let t=[];for(let{label:n,path:s}of e){let o=_s(s);o.length>0&&t.push({label:n,path:s,chars:o})}return t}function Ts(e){let t=(e??"").trim().replace(/^["']|["']$/g,"");if(!t||t==="undefined"||t==="null")return null;let n=t.toLowerCase().split(/[\\/]/);if(n.length<2||n.includes("system32"))return null;let s=Ss.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(s)?t:null}function Pe(e,t){let n=Ts(e);return n===null?!1:t?t(n):!0}function Se(e,t){let n=e[0],s=[...new Set(e.flatMap(p=>p.chars))],o=s.map(p=>`"${p}"`).join(", "),a=s.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${o} in it ${a?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${a?"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 ce(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10),a=`${n}.${s}.${o}`;return n<22||n===22&&s<15?{ok:!1,version:a,major:n,minor:s,message:`Your installed Node.js is ${a}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:a,major:n,minor:s}}import{spawn as Is}from"child_process";import{existsSync as Cs}from"fs";import{homedir as Rs}from"os";import{delimiter as xs,join as We}from"path";var Os=new Set(["Restricted","AllSigned"]);function vs(e,t=Cs){for(let n of e.split(xs)){let s=n.replace(/"/g,"");if(!s)continue;let o=We(s,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let a of["npx.exe","npx.bat","npx.cmd"]){let r=We(s,a);if(t(r))return{path:r,isPs1:!1}}}return null}async function sn(){let e=vs(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await $s();if(!t)return{blocked:!1,shimPath:e.path};let n=We(Rs(),".local","node")+"\\";return{blocked:Os.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function $s(){let e=We(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 s=Is(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",a=setTimeout(()=>{s.kill(),n(null)},8e3);s.stdout.on("data",r=>{o+=r.toString()}),s.stderr?.resume(),s.on("close",r=>{clearTimeout(a),n(r===0&&o.trim()?o.trim():null)}),s.on("error",()=>{clearTimeout(a),n(null)})})}import{spawn as Ns}from"child_process";var Ne=3,ze=10,Ls=[["python3"],["python"],["py","-3"]];async function q(){for(let e of Ls){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 s=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!s)continue;let o=parseInt(s[1],10),a=parseInt(s[2],10),r=s[3]?`${o}.${a}.${s[3]}`:`${o}.${a}`;return{command:[...e],version:r,major:o,minor:a}}return null}async function be(){let e=Ms(),t=await q();if(!t){let r=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}.${ze}+ is not installed (or not on PATH). Install it from ${e}.`+r}}let{command:n,version:s,major:o,minor:a}=t;return o<Ne||o===Ne&&a<ze?{ok:!1,version:s,major:o,minor:a,command:n,message:`Your installed Python is ${s}. Klaudius needs Python ${Ne}.${ze} or newer (the pipeline depends on packages that only ship wheels for ${Ne}.${ze}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:s,major:o,minor:a,command:n}}function Ms(){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 s=Ns(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",a="";s.stdout?.on("data",r=>{o+=r.toString()}),s.stderr?.on("data",r=>{a+=r.toString()}),s.on("close",r=>n({code:r??1,stdout:o,stderr:a})),s.on("error",()=>n({code:1,stdout:o,stderr:a}))})}var an=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function rn(e={}){console.log(O.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
3
|
`));let t=[];t.push(Us());let n=await be();if(t.push(Fs(n)),t.push(await js(n.command)),t.push(await Ks()),process.platform==="win32"){let o=await Gs();o&&t.push(o);let a=await Bs();a&&t.push(a)}t.push(await Vs());for(let o of t){let a=o.status==="ok"?O.green("\u2713"):o.status==="warn"?O.yellow("!"):O.red("\u2717");console.log(` ${a} ${o.name}${o.detail?O.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${O.dim("\u2192")} ${O.cyan(o.nextAction)}`)}console.log();let s=t.filter(o=>o.status==="fail");if(s.length===0){let o=t.filter(a=>a.status==="warn").length;Ys(o);return}console.log(O.red(O.bold(`${s.length} check${s.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(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 Us(){let e=ce();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal before re-running."}}function Fs(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 js(e){let t=e??["python3"],n=await qe(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 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 tab 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.")),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 Lt}from"fs/promises";import{spawnSync as Ut}from"child_process";import{homedir as ho}from"os";import{resolve as mo,isAbsolute as go,join as X,normalize as yo}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")}})}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(`
|
|
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 tab 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.")),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 Lt}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")}})}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(`
|
|
5
5
|
`)+`
|
|
6
6
|
`}function tt(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
7
|
`}function nt(e){let t=e.supabaseProjectRef,n=Js(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 = "${Rt}"`,""]:[],"[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(`
|
|
@@ -10,20 +10,20 @@ 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
|
|
|
10
10
|
`,a=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let r of s)a.push(""),r.comment&&a.push(`# ${r.comment}`),a.push(Xs(r.key,r.value));return e+o+a.join(`
|
|
11
11
|
`)+`
|
|
12
12
|
`}function Zs(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 s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let a=s.slice(0,o).trim(),r=Zs(s.slice(o+1).trim());t[a]=r}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,s=c=>c==="email"||c==="sms"||c==="whatsapp"||c==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(s),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(s),r=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)??Ct,aiPlan:Je(e.AI_PLAN),qaPhase:Xe(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:a&&a.length>0?a:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailProvider:Ze(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:It(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)??xt,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 re=e[_];if(!re)return;let j=parseInt(re,10);return isNaN(j)?void 0:j},n=e.SUPABASE_URL,s=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,r=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",l=dn(e.DEPLOY_PROVIDER)??xt,p=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,k=e.CLOUDFLARE_ACCOUNT_ID,d=e.NETLIFY_AUTH_TOKEN,S=e.SELFHOST_DEPLOY_TARGET,y=e.SELFHOST_URL_TEMPLATE;if(!r||!n||!s||!o||!a||!(l==="cloudflare"?!!u&&!!k: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)??Ct,aiPlan:Je(e.AI_PLAN),qaPhase:Xe(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:r,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:Ze(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:It(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:k||void 0,netlifyAuthToken:d||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:S||void 0,selfhostUrlTemplate:y||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:a,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
|
|
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 ri(e,{withFileTypes:!0}),s=[];for(let o of n){let a=Sn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await ge(a,t)):o.isFile()&&s.push(li(t,a).split(ci).join("/")))}return s}async function bn(e){let t=await ge(e),n={};for(let s of t)it.has(s)||(n[s]=await _e(Sn(e,s)));return n}import{copyFile as di,mkdir as _n,mkdtemp as ui,readdir as Tn,rm as In}from"fs/promises";import{tmpdir as pi}from"os";import{dirname as fi,join as ot}from"path";import{Readable as hi}from"stream";import*as Cn from"tar";var mi="https://klaudius.dev/api/template";function gi(e){return hi.fromWeb(e)}async function at(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??mi,n="0.30.
|
|
15
|
-
`+de.bold(de.cyan(e))),detail:e=>console.log(de.dim(" "+e))};var Pi="https://registry.npmjs.org/klaudius/latest";async function Si(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Pi,{signal:t.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let o=await s.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function bi(e,t){let n=a=>a.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(s[a])||Number.isNaN(o[a]))return!1;if(s[a]>o[a])return!0;if(s[a]<o[a])return!1}return!1}async function ct(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Si();!n||!bi(n,t)||(i.blank(),i.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(i.detail("Your project content is fetched fresh either way, so you're not missing any"),i.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),i.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),i.blank())}import{createHash as _i}from"crypto";import{hostname as Ln,userInfo as Ti,platform as Mn,arch as Dn}from"os";var Ii="https://klaudius.dev",Ci="/api/licenses/validate",Ri="0.30.
|
|
16
|
-
`)};try{let a=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(a.ok)return{ok:!0};if(a.status===429)return{ok:!0};let r={};try{r=await a.json()}catch{}let c=r.error?.message??"",l=r.error?.status??"";return a.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 and enable 'Places API (New)' for the project this key belongs to, then try again."}:a.status===401||a.status===403?{ok:!1,message:o(
|
|
13
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let a=s.slice(0,o).trim(),r=Zs(s.slice(o+1).trim());t[a]=r}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,s=c=>c==="email"||c==="sms"||c==="whatsapp"||c==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(s),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(s),r=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)??Ct,aiPlan:Je(e.AI_PLAN),qaPhase:Xe(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:a&&a.length>0?a:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailProvider:Ze(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:It(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)??xt,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 re=e[_];if(!re)return;let j=parseInt(re,10);return isNaN(j)?void 0:j},n=e.SUPABASE_URL,s=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,r=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",l=dn(e.DEPLOY_PROVIDER)??xt,p=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,k=e.CLOUDFLARE_ACCOUNT_ID,d=e.NETLIFY_AUTH_TOKEN,S=e.SELFHOST_DEPLOY_TARGET,y=e.SELFHOST_URL_TEMPLATE;if(!r||!n||!s||!o||!a||!(l==="cloudflare"?!!u&&!!k: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)??Ct,aiPlan:Je(e.AI_PLAN),qaPhase:Xe(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:r,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:Ze(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:It(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:k||void 0,netlifyAuthToken:d||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:S||void 0,selfhostUrlTemplate:y||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:a,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 Ja,mkdir as Xa,readdir as ri,stat as Za}from"fs/promises";import{dirname as tr,join as Sn,relative as li,sep as ci}from"path";import{fileURLToPath as sr}from"url";import{createHash as yn}from"crypto";import{readFile as ei}from"fs/promises";async function _e(e){let t=await ei(e);return yn("sha256").update(t).digest("hex")}function Ot(e){return yn("sha256").update(e).digest("hex")}import{mkdir as ti,readFile as ni,writeFile as si,access as ii}from"fs/promises";import{dirname as oi,join as kn}from"path";var ai=".klaudius",wn=`${ai}/manifest.json`,it=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=kn(e,wn);try{await ii(t)}catch{return null}let n=await ni(t,"utf-8"),s=JSON.parse(n),o={};for(let[a,r]of Object.entries(s.files??{}))o[a.split("\\").join("/")]=r;return s.files=o,Array.isArray(s.ignored)?s.ignored=s.ignored.filter(a=>typeof a=="string").map(a=>a.split("\\").join("/")):delete s.ignored,s}async function Le(e,t){let n=kn(e,wn);await ti(oi(n),{recursive:!0}),await si(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 ri(e,{withFileTypes:!0}),s=[];for(let o of n){let a=Sn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await ge(a,t)):o.isFile()&&s.push(li(t,a).split(ci).join("/")))}return s}async function bn(e){let t=await ge(e),n={};for(let s of t)it.has(s)||(n[s]=await _e(Sn(e,s)));return n}import{copyFile as di,mkdir as _n,mkdtemp as ui,readdir as Tn,rm as In}from"fs/promises";import{tmpdir as pi}from"os";import{dirname as fi,join as ot}from"path";import{Readable as hi}from"stream";import*as Cn from"tar";var mi="https://klaudius.dev/api/template";function gi(e){return hi.fromWeb(e)}async function at(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??mi,n="0.30.1",s;try{s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${I(c)}`)}if(!s.ok){let c="";try{let l=await s.json();c=l.reason?` (${l.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${c}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),a=await ui(ot(pi(),"klaudius-template-")),r=0;try{try{await new Promise((p,u)=>{let k=Cn.extract({cwd:a,strict:!0});k.on("finish",p),k.on("error",u),gi(s.body).on("error",u).pipe(k)})}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(a);try{for(let p of l){let u=ot(e.destDir,p);await _n(fi(u),{recursive:!0}),await di(ot(a,p),u),r++}}catch(p){let u=await Tn(e.destDir).catch(()=>[]);for(let k of u)c.has(k)||await In(ot(e.destDir,k),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await In(a,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:r,tier:o}}import{copyFile as yi,mkdir as ki,readFile as Rn,rm as wi}from"fs/promises";import{dirname as Ai,join as ye}from"path";import{structuredPatch as Ei}from"diff";var xn=ye(".klaudius","base"),rt=ye(".klaudius","conflict-base");async function lt(e,t,n){let s=ye(e,xn);await wi(s,{recursive:!0,force:!0});for(let o of n){let a=ye(s,o);await ki(Ai(a),{recursive:!0}),await yi(ye(t,o),a)}}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,rt,t),"utf-8")}catch{return null}}function $n(e,t,n,s){return Te(n)?null:e!==null&&!Te(e)&&(!s||Ot(e)===s)?e:t!==null&&!Te(t)&&s&&Ot(t)===s?t:null}function Te(e){return e.includes("\0")||e.includes("\uFFFD")}function Nn(e,t,n=60){let s=Ei("base","new",e,t,"","",{context:2});if(s.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=s.hunks.map(l=>`${l.newStart}-${l.newStart+Math.max(l.newLines-1,0)}`).join(", "),a=[`Upstream changed ${s.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],r=0,c=!1;for(let l of s.hunks){if(r>=n){c=!0;break}a.push(`@@ -${l.oldStart},${l.oldLines} +${l.newStart},${l.newLines} @@`),r+=1;let p=Math.max(n-r,0),u=l.lines.slice(0,p);if(a.push(...u),r+=u.length,u.length<l.lines.length){c=!0;break}}return a.push("```"),c&&a.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),a}import de from"picocolors";var i={info:e=>console.log(de.cyan("\u2139"),e),success:e=>console.log(de.green("\u2713"),e),warn:e=>console.log(de.yellow("\u26A0"),e),error:e=>console.error(de.red("\u2717"),e),step:e=>console.log(de.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+de.bold(de.cyan(e))),detail:e=>console.log(de.dim(" "+e))};var Pi="https://registry.npmjs.org/klaudius/latest";async function Si(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Pi,{signal:t.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let o=await s.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function bi(e,t){let n=a=>a.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(s[a])||Number.isNaN(o[a]))return!1;if(s[a]>o[a])return!0;if(s[a]<o[a])return!1}return!1}async function ct(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Si();!n||!bi(n,t)||(i.blank(),i.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(i.detail("Your project content is fetched fresh either way, so you're not missing any"),i.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),i.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),i.blank())}import{createHash as _i}from"crypto";import{hostname as Ln,userInfo as Ti,platform as Mn,arch as Dn}from"os";var Ii="https://klaudius.dev",Ci="/api/licenses/validate",Ri="0.30.1";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(),s=(process.env.KLAUDIUS_API_URL??Ii).replace(/\/$/,"")+Ci,o=Me(),a;try{a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Ln(),os:`${Mn()}-${Dn()}`,cli_version:Ri})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${I(c)}). Check your internet connection or try again later.`}}let r;try{r=await a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${a.status}).`}}function Me(){let e=[Ln(),Ti().username,Mn(),Dn()].join("|");return _i("sha256").update(e).digest("hex").slice(0,32)}import{readFile as xi}from"fs/promises";import{join as Oi}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 xi(Oi(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(s){return{ok:!1,message:`Could not read scripts/schema.sql: ${s.message}`}}let n=e.pat.replace(/\s+/g,"");try{let s=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(s.ok)return{ok:!0};let o=await s.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(i.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${s.status}): ${o.slice(0,300)}`}}catch(s){return{ok:!1,message:`Schema apply failed: ${s.message}`}}}async function dt(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 ut(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${Fn}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await o.json(),r=a.result?.status;if(a.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${jn(a)??"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:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await o.json();return a.success===!1?{ok:!1,message:jn(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.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 pt(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${Kn}/user`,{headers:n});if(s.status===401||s.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} verifying the token. Try again or check netlifystatus.com.`}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}try{let s=await fetch(`${Kn}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),a=Array.isArray(o)?o:[];if(a.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let r=typeof a[0]?.slug=="string"?a[0].slug:void 0;return{ok:!0,accountCount:a.length,accountSlug:r}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}}function vi(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,s=/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} ${s}`}async function Ce(e){let t=Zt(e);if(t)return{ok:!1,message:t};let n=le(e),s=n.value,o=a=>{let r=[a],c=en(e);return c&&r.push(c),n.repairs.length>0&&r.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.`),r.join(`
|
|
16
|
+
`)};try{let a=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(a.ok)return{ok:!0};if(a.status===429)return{ok:!0};let r={};try{r=await a.json()}catch{}let c=r.error?.message??"",l=r.error?.status??"";return a.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 and enable 'Places API (New)' for the project this key belongs to, then try again."}:a.status===401||a.status===403?{ok:!1,message:o(vi(a.status,c))}:{ok:!1,message:o(`Google API returned HTTP ${a.status}${c?`: ${c}`:""}.`)}}catch(a){return{ok:!1,message:`Could not reach Google: ${I(a)}`}}}import $i from"nodemailer";import{ImapFlow as Ni}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 s=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return s.includes("invalid credentials")||s.includes("authentication failed")||s.includes("auth failed")||s.includes("login failed")||s.includes("invalid login")?"auth":s.includes("etimedout")||s.includes("timeout")||s.includes("enotfound")||s.includes("getaddrinfo")||s.includes("econnrefused")||s.includes("econnreset")?"network":"other"}async function ie(e){let t=$i.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(o){return{ok:!1,failedAt:"smtp",message:Bn(o,"SMTP",e.usesAccountPassword),failureKind:Gn(o)}}finally{t.close()}let n=new Ni({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),s;try{if(await n.connect(),e.draftsFolder)try{let o=await n.list(),a=e.draftsFolder.toLowerCase();if(!o.some(c=>c.path.toLowerCase()===a)){let c=o.find(l=>l.specialUse==="\\Drafts")?.path;s={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:s}}function Bn(e,t,n){let s=e instanceof Error?e.message:String(e),o=s.toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
|
|
17
17
|
\u2022 The mailbox password is wrong or mistyped.
|
|
18
18
|
\u2022 The email address doesn't match this mailbox's login.
|
|
19
19
|
\u2022 The provider is blocking third-party apps \u2014 check that third-party
|
|
20
20
|
access is enabled and 2FA is off in your provider's settings.`:`${t} rejected the credentials. Most common causes:
|
|
21
21
|
\u2022 The app password is wrong, expired, or for a different provider.
|
|
22
22
|
\u2022 The email address doesn't match the account that issued the password.
|
|
23
|
-
\u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}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 s=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(s.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!s.ok)return{ok:!1,message:`Twilio API returned HTTP ${s.status}. Try again or check status.twilio.com.`};let o=await s.json();return o.status&&o.status!=="active"?{ok:!1,message:`Twilio account is in '${o.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:o.friendly_name}}catch(s){return{ok:!1,message:`Could not reach Twilio: ${I(s)}`}}}async function ft(e){return e.provider==="pingen"?
|
|
24
|
-
`+t;return
|
|
25
|
-
${e.stdout??""}`;return
|
|
26
|
-
`,"utf-8")}var Zn="0.30.
|
|
23
|
+
\u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}async function 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 s=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(s.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!s.ok)return{ok:!1,message:`Twilio API returned HTTP ${s.status}. Try again or check status.twilio.com.`};let o=await s.json();return o.status&&o.status!=="active"?{ok:!1,message:`Twilio account is in '${o.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:o.friendly_name}}catch(s){return{ok:!1,message:`Could not reach Twilio: ${I(s)}`}}}async function ft(e){return e.provider==="pingen"?Li(e):Mi(e)}async function Li(e){if(!e.pingenClientId||!e.pingenClientSecret||!e.pingenOrgId)return{ok:!1,message:"Missing Pingen Client ID, Client Secret, or organisation id."};let t=e.pingenStaging?"https://identity-staging.pingen.com":"https://identity.pingen.com",n=e.pingenStaging?"https://api-staging.pingen.com":"https://api.pingen.com";try{let s=await fetch(`${t}/auth/access-tokens`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:e.pingenClientId,client_secret:e.pingenClientSecret,scope:"letter"})});if(!s.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${s.status}). Check the Client ID and Secret under your organisation's 'API Access' page \u2014 note that staging and production credentials are separate.`};let o=(await s.json()).access_token;if(!o)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let a=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${o}`}});return a.status===403||a.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"}:a.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${a.status}. Try again shortly.`}}catch(s){return{ok:!1,message:`Could not reach Pingen: ${I(s)}`}}}async function Mi(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 Di}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,"")}"`,s=await Hi(n);if(s.code===0)return{ok:!0};let o=s.stderr.toLowerCase();return o.includes("can't get application")||o.includes("isn't running")||o.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:o.includes("(-1728)")||o.includes("not found")||o.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:o.includes("(-1719)")||o.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${s.stderr.trim()||`exit code ${s.code}`}`}}function Hi(e){return new Promise(t=>{let n=Di("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),s="";n.stderr.on("data",o=>{s+=o.toString()}),n.on("close",o=>t({code:o??1,stderr:s})),n.on("error",o=>t({code:1,stderr:o.message}))})}import{spawn as ht}from"child_process";import{existsSync as Ui}from"fs";import{homedir as Fi}from"os";function ji(){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,Ki=[/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+`
|
|
24
|
+
`+t;return Ki.some(s=>s.test(n))}function Qn(e){return new Promise(t=>setTimeout(t,e))}function Gi(e,t,n){return new Promise(s=>{let o=n.shell?ht([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):ht(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),a="",r="";o.stdout?.on("data",c=>{let l=c.toString();a+=l,process.stdout.write(l)}),o.stderr?.on("data",c=>{let l=c.toString();r+=l,process.stderr.write(l)}),o.on("close",c=>s({code:c??1,stdout:a,stderr:r})),o.on("error",c=>s({code:1,stdout:a,stderr:r+c.message}))})}async function vt(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=Re;o++){if(s=await Gi(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!zn(s.stderr,s.stdout))return s;o<Re&&(i.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${Re+1})\u2026`),await Qn(Wn))}return s}function Bi(e,t,n){return new Promise(s=>{let o=ht(e,t,{cwd:n.cwd,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",c=>s({code:1,stdout:a,stderr:r+c.message}))})}var Vi=[{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 Yi(e){let t=`${e.stderr??""}
|
|
25
|
+
${e.stdout??""}`;return Vi.find(s=>s.pattern.test(t))?.hint}async function Wi(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"],a=async c=>{let l={code:0,stdout:"",stderr:""};for(let p=0;p<=Re;p++){if(l=await Bi(o[0],[...o.slice(1),...c],{cwd:e}),l.code===0||!zn(l.stderr,l.stdout))return l;p<Re&&(i.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${Re+1})\u2026`),await Qn(Wn))}return l},r=await a([...n,"--break-system-packages",...t]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),r=await a([...n,...t])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function mt(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=ji(),s=process.platform==="win32",o;if(s){let u=Ee([{label:"your Windows user folder",path:Fi()},{label:"the project folder",path:e}]);if(u.length>0){let k=await new Promise(S=>{let y=ht("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=k.code===0?k.stdout.trim():void 0;if(!Pe(d,Ui)){let{detail:S,action:y}=Se(u,"install");o=`${S}. ${y}`}}}let a=(u,k)=>{let d=Yi(k);if(d){(t.hints??={})[u]=d;return}o&&(u==="npm"||u==="playwright"||u==="patchright")&&!Object.values(t.hints??{}).includes(o)&&((t.hints??={})[u]=o)};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let r=await vt("npm",["install"],{cwd:e,label:"npm install",env:n,shell:s});t.npm=r.code===0?"ok":"failed",r.code!==0&&a("npm",r),i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let c=await Wi(e);t.pip=c.code===0?"ok":"failed",c.code!==0&&a("pip",c),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let l=await vt("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:s});t.playwright=l.code===0?"ok":"failed",l.code!==0&&a("playwright",l),i.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await vt("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:s});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&a("patchright",p),t}import{copyFile as zi,access as Qi}from"fs/promises";import{dirname as qi,join as Ji}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 $t(){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 Xi(e){let[t,...n]=e.command,s=await Qe(t,[...n,"-c","import sys; print(sys.executable)"]),o=s.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(s.code!==0||!o)return{ok:!1,reason:"no-exe-path"};let a=Ji(qi(o),"python3.exe"),r=await Qi(a).then(()=>!0,()=>!1);if(!r){if(/[\\/]WindowsApps[\\/]/i.test(a))return{ok:!1,reason:"store-python",target:a};try{await zi(o,a)}catch{return{ok:!1,reason:"not-writable",target:a,manualCommand:`copy "${o}" "${a}"`}}}let c=await qn();return{ok:!0,target:a,created:!r,verified:c.state==="real",postState:c.state==="real"?void 0:c.state}}var Zi="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 gt(){let e=await $t();if(e.status!=="broken")return;let t=await Xi(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.";i.success(n);return}if(t.ok&&t.postState==="stub"){i.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),i.detail(Zi);return}if(t.ok){i.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."),i.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"){i.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"){i.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),i.detail(t.manualCommand??"");return}i.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 eo,spawnSync as Jn}from"child_process";import{mkdtemp as to,rm as no,rmdir as so,writeFile as io,stat as Nt,unlink as oo,mkdir as ao}from"fs/promises";import{createServer as ro}from"net";import{tmpdir as lo}from"os";import{join as xe}from"path";function co(){return new Promise((e,t)=>{let n=ro();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let s=n.address(),o=typeof s=="object"&&s?s.port:0;n.close(()=>e(o))})})}function yt(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 uo(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function uo(e){let t=`klaudius-smoke-${process.pid}`,n=xe(".klaudius",`qa-smoke-${process.pid}.png`),s=xe(e,n),o,a,r=!1;try{o=await to(xe(lo(),"klaudius-qa-smoke-")),await io(xe(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let c=await co();a=eo("python3",["-m","http.server",String(c),"--directory",o],{stdio:"ignore",shell:!1});let l=!1;a.on("error",()=>{l=!0}),a.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 k=xe(e,".klaudius"),d=await Nt(k).then(()=>!0,()=>!1);await ao(k,{recursive:!0}),r=!d;let S=yt(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=yt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await Nt(s).catch(()=>null);if((!E||E.size===0)&&(y=yt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await Nt(s).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{yt(e,[`-s=${t}`,"close"]),a&&!a.killed&&a.kill(),await oo(s).catch(()=>{}),r&&await so(xe(e,".klaudius")).catch(()=>{}),o&&await no(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as po,readFile as fo,writeFile as ho}from"fs/promises";import{join as Xn}from"path";async function wt(e,t){let n=Xn(e,".claude");await po(n,{recursive:!0});let s=Xn(n,"settings.json"),o={};try{let l=await fo(s,"utf-8"),p=JSON.parse(l);p&&typeof p=="object"&&!Array.isArray(p)&&(o=p)}catch{}let a=o.enabledMcpjsonServers,r=Array.isArray(a)?a.filter(l=>typeof l=="string"):[];r.includes(t)||r.push(t);let c={...o,enabledMcpjsonServers:r};await ho(s,JSON.stringify(c,null,2)+`
|
|
26
|
+
`,"utf-8")}var Zn="0.30.1",v=5,H=!1;function U(e,t){i.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 wo(e){let t;try{t=await Dt(e,"utf-8")}catch{U("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let s=JSON.parse(n),o={};for(let[a,r]of Object.entries(s))r!=null&&(o[a]=typeof r=="string"?r:String(r));return o}catch(s){U("answers",`Answers file is not valid JSON: ${s.message}`)}return K(t)}function ue(e){return`npx klaudius@latest init ${At(Oe(e))}`}function Oe(e){if(process.platform==="win32")return e;let t=mo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Ao(e){let t=[];try{let s=(await ts(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let a=X(e,o.name);if(!await es(X(a,".env")))continue;let r=await es(X(a,".klaudius","manifest.json"));if(t.push({path:a,finished:r}),t.length>=3)break}}catch{}return t}async function es(e){try{return await Ht(e),!0}catch{return!1}}function At(e){return/\s/.test(e)?`"${e}"`:e}function ee(e,t,n){i.blank(),i.error(`${t} validation failed ${v} times in a row. Pausing setup so you don't get stuck in a loop.`),i.detail(`Last error: ${n}`),i.blank(),i.detail("Your credentials are saved in `.env`. Two ways forward:"),i.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),i.blank(),console.log(` ${h.cyan(ue(e))}`),i.blank(),i.detail(` (Your .env is at ${Oe(X(e,".env"))} \u2014 open it in any text editor.)`),i.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),i.blank(),process.exit(1)}async function ns(e){let t=e.target??".",n=yo(t)?t:go(process.cwd(),t),s=bo(n);s&&(i.error("Klaudius can't be installed inside a protected system folder."),i.detail(`Path: ${n}`),i.detail(`Reason: ${s}`),i.blank(),i.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),i.blank(),process.platform==="win32"?(i.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${h.cyan("cd $HOME\\Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)):(i.detail("For example:"),console.log(` ${h.cyan("cd ~/Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)),i.blank(),process.exit(1)),process.platform==="win32"&&_o()&&(i.warn("You appear to be running in an elevated (Administrator) PowerShell."),i.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),i.blank()),await ct("init",Zn);let o=await Eo(n);if(o.kind==="scaffolded"){i.blank(),i.warn(`Found an existing Klaudius project at ${h.bold(n)}.`),i.detail("(Your .env and project files are in place.)"),i.blank(),o.nodeModulesMissing?(i.detail("It looks like a previous setup didn't finish installing dependencies."),i.detail("To pick up where it left off, run:"),i.blank(),n!==process.cwd()&&console.log(` ${h.cyan(`cd ${At(t)}`)}`),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retries npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Everything is scaffolded and dependencies look installed."),i.detail("Pick the action you wanted:"),i.blank(),console.log(` ${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")}`),i.blank()),i.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),i.blank();return}if(o.kind==="occupied"){let f=t===".",g=await Ao(n);if(g.length>0){i.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),i.detail(`You're in: ${Oe(n)}`),i.blank();for(let m of g)i.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:`),i.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(ue(m.path))} ${h.dim("# then pick Resume")}`),i.blank();process.exit(1)}i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),i.blank(),f?(i.detail("Two ways forward:"),i.blank(),i.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`),i.blank(),i.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")}`)):(i.detail(`The folder '${t}' already exists and isn't empty.`),i.detail("Either pick a different name:"),console.log(` ${h.cyan(`npx klaudius@latest init ${t}-2`)}`),i.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=null;e.answers&&(H=!0,a=await wo(e.answers),i.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let r=e.license??a?.KLAUDIUS_LICENSE_KEY;H&&(!r||r.trim().length===0)&&U("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let c=await So(r),l=P.spinner();l.start("Validating license");let p=await Hn(c);p.ok||(l.stop(`License invalid: ${p.reason??"unknown"}`,2),i.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||(i.error(u.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${ue(n)}`),process.exit(1)),await gt();let k=ce();k.ok||(i.error(k.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${ue(n)}`),process.exit(1));let d,S=!1;if(a){let f=st(a);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,i.success("Loaded setup answers (non-interactive mode)")}else if(o.kind==="partial")if(await Po(n)==="resume"){let g=await Dt(o.envPath,"utf-8"),m=st(K(g));m?(i.success("Resuming with values from your existing .env"),i.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),d=m,S=!0,d.aiPlan||(d=await L(d,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
|
|
27
27
|
runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),d=await L())}else{let g=await Dt(o.envPath,"utf-8"),m=st(K(g));d=await L(m??{})}else d=await L();d.licenseKey=c,await M(n,d),S||(i.success("Saved .env"),i.success(d.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.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";i.blank(),H&&U("supabase",A),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${f+1} of ${v})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await L(d,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
28
28
|
${A}
|
|
29
29
|
|
|
@@ -95,13 +95,13 @@ password. Your browser will open to Microsoft's sign-in page \u2014
|
|
|
95
95
|
sign in as `+(d.emailAddress??"your outreach mailbox")+` and approve.
|
|
96
96
|
(No browser on this machine? It falls back to a short code you can
|
|
97
97
|
enter from any device.)`)),i.blank();let f=await q();if(f){let[g,...m]=f.command,A=Ut(g,[...m,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});A.status===0?i.success("Outlook mailbox connected."):(i.blank(),console.log(h.yellow(`The Microsoft sign-in didn't complete (exit ${A.status??"signalled"}). Setup continues without it.`)),w(f))}else console.log(h.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),w(null)}else ke&&!$e&&(i.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")));i.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.")),i.blank();for(let[D,Ke]of Object.entries(_))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${Ke}`)),i.blank();let f=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${At(e.target)}`)}
|
|
98
|
-
`:"",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 ${_o()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),i.blank());let N=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if(N.length>0){let D=N.length===1?"keeps":"keep";console.log(h.dim(`If ${N.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(To(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 Lt(X(e,".env"),et(t),"utf-8"),t.aiAgent==="codex"?(await Mt(X(e,".codex"),{recursive:!0}),await Lt(X(e,".codex","config.toml"),nt(t),"utf-8")):(await Lt(X(e,".mcp.json"),tt(t),"utf-8"),await wt(e,"supabase"))}async function Ao(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 Eo(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 Po(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 So(e){let t=yo(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 bo(){if(process.platform!=="win32")return!1;try{return Ut("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function _o(){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 To(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 Io,readFile as Co}from"fs/promises";import{join as Ft,resolve as Ro}from"path";import V from"picocolors";async function is(e){let t=e.target?Ro(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 Co(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 Io(e),!0}catch{return!1}}import{readFile as xo,writeFile as jt,access as Oo}from"fs/promises";import{join as ve}from"path";import*as te from"@clack/prompts";import oe from"picocolors";import{mkdir as vo}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 xo(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 L(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($o(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,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 vo(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 $o(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 Oo(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 Lo}from"os";import*as fe from"@clack/prompts";import De from"picocolors";var He="0.30.0";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=$(Lo(),`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 Mo(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}=Do(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 Le(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),N=await Et($(k,m.path),"utf-8"),D=$n(A,T,N,m.manifestHash);D!==null?(f.set(m.path,D),x.set(m.path,Nn(D,N))):A!==null&&(Te(A)||Te(N))?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"),Ho(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 Le(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:
|
|
99
|
-
"Run /resolve-conflicts"`))}await pe(u,{recursive:!0,force:!0}).catch(()=>{})}async function
|
|
98
|
+
`:"",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 N=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if(N.length>0){let D=N.length===1?"keeps":"keep";console.log(h.dim(`If ${N.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 Lt(X(e,".env"),et(t),"utf-8"),t.aiAgent==="codex"?(await Mt(X(e,".codex"),{recursive:!0}),await Lt(X(e,".codex","config.toml"),nt(t),"utf-8")):(await Lt(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 L(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(No(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,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 Lo(t,a)}function No(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 Lo(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.1";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 Le(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),N=await Et($(k,m.path),"utf-8"),D=$n(A,T,N,m.manifestHash);D!==null?(f.set(m.path,D),x.set(m.path,Nn(D,N))):A!==null&&(Te(A)||Te(N))?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 Le(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:
|
|
99
|
+
"Run /resolve-conflicts"`))}await pe(u,{recursive:!0,force:!0}).catch(()=>{})}async function Do(e,t,n){let s=await ge(e),o=new Set(s),a=new Set(n.ignored??[]),r=[];for(let c of s){if(a.has(c))continue;let l=await _e($(e,c)),p=n.files[c],u=$(t,c),k;try{await ls(u),k=await _e(u)}catch{let d=p!==void 0&&!An.has(c)?"locally-deleted":"new";r.push({path:c,state:d,canonicalHash:l,manifestHash:p});continue}l===p?k===p?r.push({path:c,state:"no-change",canonicalHash:l,localHash:k,manifestHash:p}):r.push({path:c,state:"user-only",canonicalHash:l,localHash:k,manifestHash:p}):k===p?r.push({path:c,state:"clean-update",canonicalHash:l,localHash:k,manifestHash:p}):r.push({path:c,state:"conflict",canonicalHash:l,localHash:k,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 ls(p),u=await _e(p)}catch{delete n.files[c];continue}u===l?r.push({path:c,state:"removed-clean",localHash:u,manifestHash:l}):r.push({path:c,state:"removed-modified",localHash:u,manifestHash:l})}return r}function Y(e,t){return`${e} ${t}${e===1?"":"s"}`}function Ho(e,t){let n=e.includes(`\r
|
|
100
100
|
`)?`\r
|
|
101
101
|
`:`
|
|
102
|
-
`,s=e.split(/\r?\n/),o=new Set(s.map(l=>l.trim()).filter(l=>l!=="")),a=[];for(let l of t.split(/\r?\n/)){let p=l.trim();p===""||p.startsWith("#")||o.has(p)||(a.push(p),o.add(p))}if(a.length===0)return{merged:e,added:a};let r=[...s];for(;r.length>0&&r[r.length-1].trim()==="";)r.pop();r.push("","# Added by `klaudius update` (new canonical ignore patterns)",...a);let c=[...new Set(s.map(l=>l.trim()).filter(l=>l.startsWith("!")))].filter(l=>!a.includes(l));return r.push(...c,""),{merged:r.join(n),added:a}}function
|
|
103
|
-
`)}import{existsSync as
|
|
104
|
-
`)),n.push(await
|
|
102
|
+
`,s=e.split(/\r?\n/),o=new Set(s.map(l=>l.trim()).filter(l=>l!=="")),a=[];for(let l of t.split(/\r?\n/)){let p=l.trim();p===""||p.startsWith("#")||o.has(p)||(a.push(p),o.add(p))}if(a.length===0)return{merged:e,added:a};let r=[...s];for(;r.length>0&&r[r.length-1].trim()==="";)r.pop();r.push("","# Added by `klaudius update` (new canonical ignore patterns)",...a);let c=[...new Set(s.map(l=>l.trim()).filter(l=>l.startsWith("!")))].filter(l=>!a.includes(l));return r.push(...c,""),{merged:r.join(n),added:a}}function Uo(e,t,n,s=new Map,o=new Map){let a=e.filter(u=>u.state==="conflict").length,r=e.filter(u=>u.state==="locally-deleted").length,c=e.filter(u=>u.state==="removed-modified").length,l=[];l.push("# Update Conflicts"),l.push(""),l.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),l.push(`Updating from canonical version **${t}** to **${n}**.`),l.push("");let p=[];a>0&&p.push(`${a} file${a===1?"":"s"} ha${a===1?"s":"ve"} BOTH local edits AND upstream changes`),r>0&&p.push(`${r} file${r===1?"":"s"} you deleted locally ${r===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 k=s.get(u.path);k&&k.length>0&&(l.push(""),l.push("**What upstream changed since your base:**"),l.push(""),l.push(...k),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(`
|
|
103
|
+
`)}import{existsSync as Fo}from"fs";import{access as jo,readFile as Ue,stat as Ko}from"fs/promises";import{homedir as Go}from"os";import{join as W}from"path";import F from"picocolors";import{spawn as ds,spawnSync as Bo}from"child_process";async function us(e){let t=e.projectRoot??process.cwd(),n=[];console.log(F.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
104
|
+
`)),n.push(await Vo());let s=await qo();s&&n.push(s),n.push(await Yo());let o=W(t,".env"),a=W(t,".klaudius","manifest.json"),r=W(t,".mcp.json"),c=W(t,".codex","config.toml"),l=await ne(o),p=await ne(a),u="claude-code";if(l)try{K(await Ue(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 k=!1;if(l){let y={};try{y=K(await Ue(o,"utf-8"))}catch{}let E=Je(y.AI_PLAN),b=Xe(y.QA_PHASE)??Ae(E);k=b==="off";let C=E==="codex-plus"&&u==="codex"?` \xB7 model pin ${Rt}`:"";n.push({name:"Plan / QA pass",status:E?"ok":"warn",detail:E?`${Ye[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 Ue(a,"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?`${a} (template ${E})`:a:"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(r);n.push({name:".mcp.json present",status:y?"ok":"warn",detail:y?r:"missing",nextAction:y?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await ra(u)),process.platform==="win32"){let y=await Wo(t);y&&n.push(y)}if(n.push(await zo(t)),n.push(await Qo(t)),n.push(await Jo(t,k)),n.push(await Zo()),n.push(await Xo(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 Ue(o,"utf-8"),E=K(y);await ea(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 jo(e),!0}catch{return!1}}async function Vo(){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 Yo(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let n=parseInt(t[1],10),s=parseInt(t[2],10);return n<22||n===22&&s<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function Wo(e){let t=Ee([{label:"your Windows user folder",path:Go()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",s=await Vt("npm",["config","get","script-shell"],!0),o=s.code===0?s.stdout.trim():void 0;if(Pe(o,Fo))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:a,action:r}=Se(t,"doctor"),c=t.some(l=>l.chars.includes("&"));return{name:n,status:c?"fail":"warn",detail:a,nextAction:r}}async function zo(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 Ko(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 Qo(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 qo(){let e=await $t();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 Jo(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 s=await kt(e);if(s.ok)return{name:"QA screenshot chain",status:"ok",detail:"served a page with python3 and screenshotted it"};let o=s.stage!=="python3-server"&&t;return{name:"QA screenshot chain",status:o?"warn":"fail",detail:`${s.stage?`${s.stage}: `:""}${s.detail??"failed"}`+(o?" (QA pass is off \u2014 this matters when you enable it, and for browser-based gathering)":""),nextAction:s.remediation}}async function Xo(e){let t=W(e,".klaudius","notify-failures.log");try{let n=(await Ue(t,"utf8")).trim();if(!n)return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"};let s=n.split(/\r?\n/);return{name:"Alert delivery",status:"warn",detail:`${s.length} failed send${s.length===1?"":"s"} recorded; latest: "${s[s.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 Zo(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
|
|
105
105
|
try:
|
|
106
106
|
${e.map(a=>` import ${a}`).join(`
|
|
107
107
|
`)}
|
|
@@ -109,17 +109,17 @@ except Exception as e:
|
|
|
109
109
|
print(str(e))
|
|
110
110
|
sys.exit(1)
|
|
111
111
|
`,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 s=n.command,o=await Vt(s[0],[...s.slice(1),"-c",t]);return o.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(o.stdout||o.stderr).trim().split(`
|
|
112
|
-
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function
|
|
113
|
-
`)[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 na(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 sa(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 ia(e,t){let n="Email credentials (SMTP + IMAP)",s=ea(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."}:ta(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,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 oa(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,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 aa(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(`
|
|
114
|
-
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:s}}function Vt(e,t,n=!1){return new Promise(s=>{let o=n?ds([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ds(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{existsSync as
|
|
115
|
-
`));let a=
|
|
112
|
+
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function ea(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let r=await Ie({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:r.ok?"ok":"fail",detail:r.ok?"connected":r.message,nextAction:r.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});let s=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(s==="selfhost"){let r=e.SELFHOST_DEPLOY_TARGET??"",c=e.SELFHOST_URL_TEMPLATE??"",l=[],p=Be(r);p&&l.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let u=Ve(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 ${r} (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(s==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let r=await ut({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:r.ok?"ok":"fail",detail:r.ok?`valid (${r.projectCount??0} Pages project${r.projectCount===1?"":"s"})`:r.message,nextAction:r.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Cloudflare."});else if(s==="netlify")if(e.NETLIFY_AUTH_TOKEN){let r=await pt({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:r.ok?"ok":"fail",detail:r.ok?r.accountSlug?`valid (team: ${r.accountSlug})`:"valid":r.message,nextAction:r.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 r=await dt(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:r.ok?"ok":"fail",detail:r.ok?r.username??"valid":r.message,nextAction:r.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 r=await Ce(e.GOOGLE_PLACES_API_KEY),c=le(e.GOOGLE_PLACES_API_KEY);r.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:r.ok?"ok":"fail",detail:r.ok?"accepted":r.message,nextAction:r.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 oa(e,n)),t.push(...await aa(e)),t.push(await sa(e)),t.push(await ia(e));let o=(e.NOTIFY_CHANNEL??"").toLowerCase(),a=o==="email"||o==="sms"||o==="none"||o==="off"?o:"telegram";if(a==="none"||a==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(a==="email"){let r=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:r&&e.EMAIL_ADDRESS?"ok":"fail",detail:r&&e.EMAIL_ADDRESS?`alerts go to ${r}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:r&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(a==="sms"){let r=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:r&&c?"ok":"fail",detail:r&&c?`alerts go to ${r} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:r?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:r&&c?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let r=await Jt({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:r.ok?"ok":"fail",detail:r.ok?`bot ${r.botHandle??"ok"} (chat_id not tested)`:r.message,nextAction:r.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 ta(e){let t=a=>!!a&&/^\d+$/.test(a.trim()),n=ps(e)?!!e.EMAIL_ADDRESS:!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),s=(e.OUTREACH_CHANNELS??"").split(",").map(a=>a.trim()),o=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&s.includes("email");return o&&n?"active":o?"incomplete":n?"parked":"unconfigured"}function ps(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function na(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[r,...c]=n.command,l=Bo(r,[...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(`
|
|
113
|
+
`)[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,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,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(`
|
|
114
|
+
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:s}}function Vt(e,t,n=!1){return new Promise(s=>{let o=n?ds([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ds(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{existsSync as la}from"fs";import{spawnSync as ca}from"child_process";import{join as da,resolve as ua}from"path";import G from"picocolors";async function fs(e){let t=ua(e.projectRoot??process.cwd()),n=da(t,"scripts","whatsapp.mjs");la(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 s=(e.label??"primary").trim(),o=s.replace(/[^A-Za-z0-9_-]/g,"");o||(console.error(G.red(`Invalid label '${s}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),o!==s&&console.error(G.yellow(`Note: cleaned label '${s}' \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.
|
|
115
|
+
`));let a=ca(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(a.status===0){console.log(G.green(`Paired '${o}'.`)),console.log(G.dim(`
|
|
116
116
|
If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
117
117
|
WHATSAPP_ACCOUNTS=primary,${o}
|
|
118
|
-
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}a.error?console.error(G.red(`Pair failed: ${a.error.message}`)):(console.error(G.red(`Pair did not complete (exit ${a.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(a.status??1)}import{spawnSync as Fe,spawn as
|
|
118
|
+
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}a.error?console.error(G.red(`Pair failed: ${a.error.message}`)):(console.error(G.red(`Pair did not complete (exit ${a.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(a.status??1)}import{spawnSync as Fe,spawn as pa}from"child_process";import{existsSync as je,mkdirSync as ys,rmSync as ks,mkdtempSync as ws}from"fs";import{homedir as Yt,tmpdir as As}from"os";import{join as z}from"path";import he from"picocolors";var fa=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function hs(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win.zip"}async function Es(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1));let t=ha();if(t&&!e.reinstall&&!e.from){gs(),console.log(he.green("Opened the Klaudius app.")),ms();return}let n=await ga(e.from);console.log(he.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?ya(n):ka(n),gs(),console.log(he.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),ms()}function ms(){process.platform==="darwin"?console.log(he.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(he.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function St(){return z(Yt(),"Applications","Klaudius.app")}function Wt(){return z(process.env.LOCALAPPDATA??z(Yt(),"AppData","Local"),"Klaudius")}function ha(){return process.platform==="darwin"?je(St()):je(z(Wt(),"app","Klaudius.exe"))}async function ma(){try{let{readFileSync:e}=await import("fs"),n=e(z(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function ga(e){if(e)return je(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await ma();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=`${fa}?file=${encodeURIComponent(hs())}`,s=z(ws(z(As(),"klaudius-app-")),hs());console.log(he.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.30.1"}});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 a=Buffer.from(await o.arrayBuffer()),{writeFileSync:r}=await import("fs");return r(s,a),s}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 ya(e){let t=z(Yt(),"Applications");ys(t,{recursive:!0});let n=ws(z(As(),"klaudius-app-x-")),s=Fe("ditto",["-xk",e,n],{stdio:"pipe"});s.status!==0&&(console.error(`Couldn't extract the app: ${s.stderr?.toString().trim()}`),process.exit(1));let o=z(n,"Klaudius.app");je(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),ks(St(),{recursive:!0,force:!0});let a=Fe("mv",[o,St()],{stdio:"pipe"});a.status!==0&&(console.error(`Couldn't install to ~/Applications: ${a.stderr?.toString().trim()}`),process.exit(1))}function ka(e){let t=Wt(),n=z(t,"app");ks(n,{recursive:!0,force:!0}),ys(n,{recursive:!0});let s=Fe("powershell.exe",["-NoProfile","-Command",`Expand-Archive -LiteralPath '${e}' -DestinationPath '${n}' -Force`],{stdio:"pipe"});s.status!==0&&(console.error(`Couldn't extract the app: ${s.stderr?.toString().trim()}`),process.exit(1));let o=z(n,"Klaudius.exe");je(o)||(console.error("Archive didn't contain Klaudius.exe \u2014 is this the right file?"),process.exit(1));let a=`
|
|
119
119
|
$W = New-Object -ComObject WScript.Shell
|
|
120
120
|
foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetFolderPath('Desktop'))) {
|
|
121
121
|
$S = $W.CreateShortcut((Join-Path $dir 'Klaudius.lnk'))
|
|
122
122
|
$S.TargetPath = '${o}'
|
|
123
123
|
$S.WorkingDirectory = '${n}'
|
|
124
124
|
$S.Save()
|
|
125
|
-
}`;Fe("powershell.exe",["-NoProfile","-Command",a],{stdio:"pipe"}).status!==0&&(console.log(he.yellow("App installed, but couldn't create shortcuts \u2014 launch it from:")),console.log(he.cyan(` ${o}`)))}function gs(){if(process.platform==="darwin")Fe("open",["-a",St()],{stdio:"pipe"});else{let e=z(Wt(),"app","Klaudius.exe");
|
|
125
|
+
}`;Fe("powershell.exe",["-NoProfile","-Command",a],{stdio:"pipe"}).status!==0&&(console.log(he.yellow("App installed, but couldn't create shortcuts \u2014 launch it from:")),console.log(he.cyan(` ${o}`)))}function gs(){if(process.platform==="darwin")Fe("open",["-a",St()],{stdio:"pipe"});else{let e=z(Wt(),"app","Klaudius.exe");pa(e,[],{detached:!0,stdio:"ignore"}).unref()}}import{spawnSync as wa}from"child_process";var zt="--use-system-ca";function Ps(){let e=process.env.NODE_OPTIONS??"";if(e.includes(zt)||!ce().ok)return;let n=e?`${e} ${zt}`:zt,s=wa(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});s.signal&&(process.kill(process.pid,s.signal),process.exit(1)),process.exit(s.status??1)}Ps();var Ea="0.30.1",se=new Aa;se.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Ea);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 rn({})}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 ns({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 is({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 as({})}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 cs({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 us({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 Es({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 fs({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});se.parse(process.argv);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.30.
|
|
4
|
-
"description": "Scaffold and maintain a Klaudius project
|
|
3
|
+
"version": "0.30.1",
|
|
4
|
+
"description": "Scaffold and maintain a Klaudius project \u2014 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": {
|
|
7
7
|
"email": "hello@klaudius.dev"
|
|
@@ -55,4 +55,4 @@
|
|
|
55
55
|
"typescript": "^5.5.0"
|
|
56
56
|
},
|
|
57
57
|
"private": false
|
|
58
|
-
}
|
|
58
|
+
}
|