klaudius 0.34.0 → 0.34.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
CHANGED
|
@@ -1,131 +1,139 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as
|
|
3
|
-
`));let t=[];t.push(
|
|
4
|
-
`)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function ri(){let e=process.platform==="win32",t=await it("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 it("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 ai(){let e=await hn();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 li(){let e=Se([{label:"your Windows user folder",path:ni()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await it("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(be(s,ti))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(l=>`"${l}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=_e(e,"preflight"),a=e.some(l=>l.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function ci(){try{return await fetch(gn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:gn}}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 di(e=0){e>0?console.log(L.green(L.bold("Your machine is ready."))+L.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(L.green(L.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(L.bold("NEXT STEP \u2014 this one is for you to run, not the AI assistant:")),console.log(" It's an interactive wizard (it asks for your license key and passwords),"),console.log(" so the assistant can't fill it in. Open a NEW terminal WINDOW and run:"),console.log(),console.log(` ${L.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(L.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(L.dim(" run it in a new terminal window.")),console.log()}function it(e,t,n=!1){return new Promise(s=>{let o=n?mn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):mn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:a})),o.on("error",()=>s({code:1,stdout:r,stderr:a}))})}import{mkdir as Yt,readdir as hs,readFile as Wt,stat as qt,writeFile as Vt}from"fs/promises";import{spawnSync as zt}from"child_process";import{homedir as Fo}from"os";import{resolve as Uo,isAbsolute as Ho,join as Z,normalize as jo}from"path";import*as P from"@clack/prompts";import m from"picocolors";var ui={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"},pi={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 kn(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let s=pi[(t??"").toUpperCase()];return s?`${s.pre??""}${n}${s.post??""}`:n}function Mt(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?ui[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 Ft="claude-code",Ut="gpt-5.6-terra";function wn(e){if(e==="claude-code"||e==="codex")return e}var fi=["claude-pro","claude-max-5x","claude-max-20x","claude-team-standard","claude-team-premium","claude-other","codex-plus","codex-pro","codex-business","codex-business-premium","codex-other"];function ot(e){let t=e?.trim().toLowerCase()??"";return fi.includes(t)?t:void 0}function rt(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 Ht="vercel";function An(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function En(e){if(e==="telegram"||e==="email"||e==="sms")return e}function Pn(e){if(e==="password"||e==="oauth-microsoft")return e}function hi(e){if(e==="custom"||e!==void 0&&Object.hasOwn(X,e))return e}function at(e){let t=hi(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[s,o]of Object.entries(X))if(o.smtpHost===n)return s;return"custom"}}function Sn(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let s of t.split(",")){let o=s.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(s=>{let o=/^[a-z0-9_]+$/.test(s)&&s!=="auto",r=l=>{let c=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`];return c?.trim()?c.trim():void 0},a=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(l=>!r(l)).map(l=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`);for(let l of["SMTP_PORT","IMAP_PORT"]){let c=r(l);c!==void 0&&!/^\d+$/.test(c)&&a.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`)}return{label:s,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:a,smtpHost:r("SMTP_HOST"),smtpPort:parseInt(r("SMTP_PORT")??"587",10),imapHost:r("IMAP_HOST"),imapPort:parseInt(r("IMAP_PORT")??"993",10),password:r("PASSWORD"),login:r("LOGIN")}})}function lt(e){let t=[],n=l=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${l}`),t.push("# "+"=".repeat(60)),t.push("")},s=(l,c)=>{if(c==null||c===""){t.push(`# ${l}=`);return}let f=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(f)){let u=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${l}="${u}"`)}else t.push(`${l}=${f}`)};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??Ft),s("AI_PLAN",e.aiPlan),s("QA_PHASE",e.qaPhase??Ee(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(o)].join(",")),n("Pricing"),s("PRICING",kn(e.pricing,e.countryCode)),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",kn(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",Mt(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??Ht),s("VERCEL_TOKEN",e.vercelToken),s("VERCEL_SCOPE",e.vercelScope??""),s("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),s("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),s("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),s("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),s("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),s("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),s("NOTIFY_CHANNEL",e.notifyChannel),s("NOTIFY_TO",e.notifyTo),s("TELEGRAM_BOT_TOKEN",e.telegramBotToken),s("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(l=>/^#?\s*([A-Z0-9_]+)=/.exec(l)?.[1]).filter(l=>!!l)),a=Object.entries(e.preservedEnv??{}).filter(([l])=>!r.has(l));if(a.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[l,c]of a)s(l,c)}return t.join(`
|
|
2
|
+
import{b as Pe,c as ut,d as Q,e as I,f as Sn,g as bn,h as pt,i as ft,j as _n,k as ge,l as Tn,m as In,p as Cn,r as Ie,s as Ce,t as Re,u as F}from"./chunk-3XX6MJ72.js";import{Command as ha}from"commander";import{spawn as On}from"child_process";import{existsSync as ki}from"fs";import{homedir as Ai}from"os";import N from"picocolors";import{win32 as oi}from"path";var ri=["&","^","%","!"];function ai(e){return ri.filter(t=>e.includes(t))}function xe(e){let t=[];for(let{label:n,path:s}of e){let o=ai(s);o.length>0&&t.push({label:n,path:s,chars:o})}return t}function li(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=oi.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(s)?t:null}function Oe(e,t){let n=li(e);return n===null?!1:t?t(n):!0}function ve(e,t){let n=e[0],s=[...new Set(e.flatMap(p=>p.chars))],o=s.map(p=>`"${p}"`).join(", "),r=s.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${o} in it ${r?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${r?"will":"may"} fail here with a misleading demand to install Visual Studio \u2014 Visual Studio is NOT needed and installing it will not fix this. Instead point npm's build steps at a shell that parses these paths correctly: PowerShell 7 (pwsh) or Git Bash, whichever is installed \u2014 npm config set script-shell "<full path to pwsh.exe or bash.exe>" (applies to all npm projects on this machine) \u2014 ${t==="preflight"?'then re-run this preflight \u2014 the "Install path safe for npm builds" check passes once script-shell is set.':t==="doctor"?"then re-run doctor \u2014 this check passes once script-shell is set.":'then re-run `npx klaudius@latest install`; `npx klaudius@latest doctor` confirms the fix (its "Install path safe for npm builds" check passes once script-shell is set).'} Windows PowerShell 5.1 ("powershell") will NOT work: it can't run the "||" in packages' install scripts. If neither shell is installed, PowerShell 7 is a small download: winget install Microsoft.PowerShell. If only the PROJECT folder is affected (not the user folder), moving the project to a plain path like C:\\klaudius also fixes it, or scope the npm setting to just this project by adding --location=project (run inside the project folder).`}}function ye(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10),r=`${n}.${s}.${o}`;return n<22||n===22&&s<15?{ok:!1,version:r,major:n,minor:s,message:`Your installed Node.js is ${r}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:r,major:n,minor:s}}import{spawn as ci}from"child_process";import{existsSync as di}from"fs";import{homedir as ui}from"os";import{delimiter as pi,join as ht}from"path";var fi=new Set(["Restricted","AllSigned"]);function hi(e,t=di){for(let n of e.split(pi)){let s=n.replace(/"/g,"");if(!s)continue;let o=ht(s,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let a=ht(s,r);if(t(a))return{path:a,isPs1:!1}}}return null}async function xn(){let e=hi(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await mi();if(!t)return{blocked:!1,shimPath:e.path};let n=ht(ui(),".local","node")+"\\";return{blocked:fi.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function mi(){let e=ht(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await Rn(e)??await Rn("powershell.exe")}function Rn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let s=ci(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",r=setTimeout(()=>{s.kill(),n(null)},8e3);s.stdout.on("data",a=>{o+=a.toString()}),s.stderr?.resume(),s.on("close",a=>{clearTimeout(r),n(a===0&&o.trim()?o.trim():null)}),s.on("error",()=>{clearTimeout(r),n(null)})})}import{spawn as gi}from"child_process";var Ze=3,mt=10,yi=[["python3"],["python"],["py","-3"]];async function W(){for(let e of yi){let t=await gt(e[0],[...e.slice(1),"--version"]),n=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(n)||t.code!==0)continue;let s=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!s)continue;let o=parseInt(s[1],10),r=parseInt(s[2],10),a=s[3]?`${o}.${r}.${s[3]}`:`${o}.${r}`;return{command:[...e],version:a,major:o,minor:r}}return null}async function Le(){let e=wi(),t=await W();if(!t){let a=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${Ze}.${mt}+ is not installed (or not on PATH). Install it from ${e}.`+a}}let{command:n,version:s,major:o,minor:r}=t;return o<Ze||o===Ze&&r<mt?{ok:!1,version:s,major:o,minor:r,command:n,message:`Your installed Python is ${s}. Klaudius needs Python ${Ze}.${mt} or newer (the pipeline depends on packages that only ship wheels for ${Ze}.${mt}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:s,major:o,minor:r,command:n}}function wi(){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 gt(e,t){return new Promise(n=>{let s=gi(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",a=>{o+=a.toString()}),s.stderr?.on("data",a=>{r+=a.toString()}),s.on("close",a=>n({code:a??1,stdout:o,stderr:r})),s.on("error",()=>n({code:1,stdout:o,stderr:r}))})}var vn=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function Ln(e={}){console.log(N.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
|
+
`));let t=[];t.push(Ei());let n=await Le();if(t.push(Pi(n)),t.push(await Si(n.command)),t.push(await bi()),process.platform==="win32"){let o=await _i();o&&t.push(o);let r=await Ti();r&&t.push(r)}t.push(await Ii());for(let o of t){let r=o.status==="ok"?N.green("\u2713"):o.status==="warn"?N.yellow("!"):N.red("\u2717");console.log(` ${r} ${o.name}${o.detail?N.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${N.dim("\u2192")} ${N.cyan(o.nextAction)}`)}console.log();let s=t.filter(o=>o.status==="fail");if(s.length===0){let o=t.filter(r=>r.status==="warn").length;Ci(o);return}console.log(N.red(N.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(N.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(N.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Ei(){let e=ye();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal window before re-running."}}function Pi(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 Si(e){let t=e??["python3"],n=await yt(t[0],[...t.slice(1),"-m","pip","--version"]);return n.code===0?{name:"pip available",status:"ok",detail:(n.stdout||n.stderr).trim().split(`
|
|
4
|
+
`)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function bi(){let e=process.platform==="win32",t=await yt("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 yt("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 _i(){let e=await xn();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 Ti(){let e=xe([{label:"your Windows user folder",path:Ai()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await yt("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(Oe(s,ki))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(d=>`"${d}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=ve(e,"preflight"),a=e.some(d=>d.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function Ii(){try{return await fetch(vn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:vn}}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 Ci(e=0){e>0?console.log(N.green(N.bold("Your machine is ready."))+N.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(N.green(N.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(N.bold("NEXT STEP \u2014 this one is for you to run, not the AI assistant:")),console.log(" It's an interactive wizard (it asks for your license key and passwords),"),console.log(" so the assistant can't fill it in. Open a NEW terminal WINDOW and run:"),console.log(),console.log(` ${N.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(N.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(N.dim(" run it in a new terminal window.")),console.log()}function yt(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}),r="",a="";o.stdout?.on("data",d=>{r+=d.toString()}),o.stderr?.on("data",d=>{a+=d.toString()}),o.on("close",d=>s({code:d??1,stdout:r,stderr:a})),o.on("error",()=>s({code:1,stdout:r,stderr:a}))})}import{mkdir as Bt,readdir as Os,readFile as Ve,rm as Cs,stat as cn,writeFile as it}from"fs/promises";import{spawnSync as dn}from"child_process";import{existsSync as tr}from"fs";import{homedir as vs}from"os";import{resolve as nr,isAbsolute as sr,join as j,normalize as ir}from"path";import*as E from"@clack/prompts";import h from"picocolors";var Ri={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"},xi={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 wt(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let s=xi[(t??"").toUpperCase()];return s?`${s.pre??""}${n}${s.post??""}`:n}function Jt(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?Ri[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 Xt="claude-code",Zt="gpt-5.6-terra";function Nn(e){if(e==="claude-code"||e==="codex")return e}var Oi=["claude-pro","claude-max-5x","claude-max-20x","claude-team-standard","claude-team-premium","claude-other","codex-plus","codex-pro","codex-business","codex-business-premium","codex-other"];function kt(e){let t=e?.trim().toLowerCase()??"";return Oi.includes(t)?t:void 0}function At(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 en="vercel";function $n(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function Mn(e){if(e==="telegram"||e==="email"||e==="sms")return e}function Dn(e){if(e==="password"||e==="oauth-microsoft")return e}function vi(e){if(e==="custom"||e!==void 0&&Object.hasOwn(Q,e))return e}function et(e){let t=vi(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[s,o]of Object.entries(Q))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",r=d=>{let c=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${d}`];return c?.trim()?c.trim():void 0},a=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(d=>!r(d)).map(d=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${d}`);for(let d of["SMTP_PORT","IMAP_PORT"]){let c=r(d);c!==void 0&&!/^\d+$/.test(c)&&a.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${d}`)}return{label:s,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:a,smtpHost:r("SMTP_HOST"),smtpPort:parseInt(r("SMTP_PORT")??"587",10),imapHost:r("IMAP_HOST"),imapPort:parseInt(r("IMAP_PORT")??"993",10),password:r("PASSWORD"),login:r("LOGIN")}})}function Et(e){let t=[],n=d=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${d}`),t.push("# "+"=".repeat(60)),t.push("")},s=(d,c)=>{if(c==null||c===""){t.push(`# ${d}=`);return}let p=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(p)){let u=p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${d}="${u}"`)}else t.push(`${d}=${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??Xt),s("AI_PLAN",e.aiPlan),s("QA_PHASE",e.qaPhase??Ce(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(o)].join(",")),n("Pricing"),s("PRICING",wt(e.pricing,e.countryCode)),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",wt(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",Jt(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??en),s("VERCEL_TOKEN",e.vercelToken),s("VERCEL_SCOPE",e.vercelScope??""),s("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),s("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),s("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),s("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),s("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),s("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),s("NOTIFY_CHANNEL",e.notifyChannel),s("NOTIFY_TO",e.notifyTo),s("TELEGRAM_BOT_TOKEN",e.telegramBotToken),s("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(d=>/^#?\s*([A-Z0-9_]+)=/.exec(d)?.[1]).filter(d=>!!d)),a=Object.entries(e.preservedEnv??{}).filter(([d])=>!r.has(d));if(a.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[d,c]of a)s(d,c)}return t.join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`}function
|
|
7
|
-
`}function
|
|
8
|
-
`)}function
|
|
6
|
+
`}function Pt(e){let t={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(t,null,2)+`
|
|
7
|
+
`}function St(e){let t=e.supabaseProjectRef,n=Li(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&&Ie.has(e.aiPlan)?[`# Set by the wizard for ${Re[e.aiPlan]}. Change or delete to use Codex's default.`,`model = "${Zt}"`,""]:[],"[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${t}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${n}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
|
|
8
|
+
`)}function Li(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Un=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel', 'cloudflare', or 'netlify'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch host, run `npx klaudius@latest configure` (Cloudflare adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID; Netlify adds NETLIFY_AUTH_TOKEN)."},{key:"PIPELINE_MODES",value:"classic",comment:"Lead streams the pipeline targets \u2014 any combination of 'classic' (no website at all), 'rescue' (existing website verifiably dead or bad) and 'booking' (Google-listed website is a booking-platform page), at least one. Pre-modes installs targeted no-website businesses only \u2014 this records that explicitly. Edit the list (e.g. 'classic,rescue,booking') or re-run `npx klaudius@latest configure`."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'},{key:"NOTIFY_CHANNEL",value:"telegram",comment:"How scripts/notify.sh routes pipeline alerts: 'telegram' (default), 'email' (to your own inbox), or 'sms' (to your own phone). Pre-NOTIFY_CHANNEL installs alerted via Telegram, so this records that explicitly. NOTIFY_TO optionally overrides the email/sms destination."},{key:"QA_PHASE",value:"on",comment:"'on' runs the independent QA pass after each build (the behaviour this install already had); 'off' goes straight from build to deploy for more sites per usage window. Flip it here any time, or run `npx klaudius@latest configure` and pick your plan to get the matching default."}];function Ni(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function Hn(e,t,n){let s=n.filter(a=>!(a.key in t));if(s.length===0)return null;let o=e.endsWith(`
|
|
9
9
|
`)?"":`
|
|
10
|
-
`,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let a of s)r.push(""),a.comment&&r.push(`# ${a.comment}`),r.push(
|
|
10
|
+
`,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let a of s)r.push(""),a.comment&&r.push(`# ${a.comment}`),r.push(Ni(a.key,a.value));return e+o+r.join(`
|
|
11
11
|
`)+`
|
|
12
|
-
`}function
|
|
13
|
-
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),a
|
|
14
|
-
`,"utf-8")}function
|
|
15
|
-
`+pe.bold(pe.cyan(e))),detail:e=>console.log(pe.dim(" "+e))};var Hi="https://registry.npmjs.org/klaudius/latest";async function ji(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Hi,{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 Ki(e,t){let n=r=>r.split("-")[0].split(".").map(a=>Number.parseInt(a,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(s[r])||Number.isNaN(o[r]))return!1;if(s[r]>o[r])return!0;if(s[r]<o[r])return!1}return!1}async function kt(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await ji();!n||!Ki(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 Gi}from"crypto";import{hostname as Vn,userInfo as Bi,platform as Yn,arch as Wn}from"os";var Vi="https://klaudius.dev",Yi="/api/licenses/validate",Wi="0.34.0";async function qn(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??Vi).replace(/\/$/,"")+Yi,o=Ve(),r;try{r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Vn(),os:`${Yn()}-${Wn()}`,cli_version:Wi})})}catch(l){return{ok:!1,reason:`Could not reach the Klaudius license server (${I(l)}). Check your internet connection or try again later.`}}let a;try{a=await r.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${r.status}).`}}return a.ok?{ok:!0,tier:a.tier??"core"}:{ok:!1,reason:a.reason??`License rejected (HTTP ${r.status}).`}}function Ve(){let e=[Vn(),Bi().username,Yn(),Wn()].join("|");return Gi("sha256").update(e).digest("hex").slice(0,32)}import{readFile as qi}from"fs/promises";import{join as zi}from"path";async function xe(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)}`}}}function zn(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function wt(e){let t;try{t=await qi(zi(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{ok:!1,message:Xi(s.status,o)}}catch(s){return{ok:!1,message:`Schema apply failed: ${I(s)}`}}}function Qi(e){let t=[...e.matchAll(/ALTER TABLE clients ADD COLUMN IF NOT EXISTS (\w+)/g)].map(s=>s[1]),n=[...e.matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/g)].map(s=>s[1]);return{clientsColumns:[...new Set(t)],tables:[...new Set(n)]}}function Ji(e,t){let n="";try{let o=JSON.parse(t);o&&typeof o.code=="string"&&(n=o.code)}catch{}return{missing:e===400&&n==="42703"||e===404&&(n==="PGRST205"||n==="42P01"),code:n}}async function At(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{clientsColumns:s,tables:o}=Qi(e.sql),r=[];s.length>0&&r.push({path:`clients?select=${s.join(",")}&limit=0`,label:"clients columns"});for(let l of o)l!=="clients"&&r.push({path:`${l}?select=*&limit=0`,label:`${l} table`});let a=[];try{for(let l of r){let c=await fetch(`${t}/rest/v1/${l.path}`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(c.ok)continue;let f=Ji(c.status,await c.text());if(f.missing){a.push(l.label);continue}return{ok:!1,missing:a,unreachable:`HTTP ${c.status}${f.code?` ${f.code}`:""}`}}}catch(l){return{ok:!1,missing:a,unreachable:I(l)}}return{ok:a.length===0,missing:a}}function Xi(e,t){let n=t;try{let s=JSON.parse(t);s&&typeof s.message=="string"&&(n=s.message)}catch{}return n=n.replace(/\s+/g," ").trim().slice(0,300),e===401?"Supabase rejected the access token (HTTP 401) \u2014 SUPABASE_PAT in .env is invalid, expired or revoked. Create a new token at https://supabase.com/dashboard/account/tokens and run `npx klaudius@latest configure`.":e===403?"The Supabase access token doesn't cover this project (HTTP 403) \u2014 it was scoped to a different organisation or project. Create a token that includes this project at https://supabase.com/dashboard/account/tokens and run `npx klaudius@latest configure`.":e===429?"Supabase rate-limited the request (HTTP 429). Wait a minute and try again.":`Supabase Management API rejected the schema (HTTP ${e}): ${n}`}function Zi(e){try{let t=JSON.parse(e);return t.error?.code==="not_found"?!0:/user not found/i.test(t.error?.message??"")}catch{return!1}}function eo(e,t){return e===401||e===403?{kind:"rejected",message:`Vercel rejected the token (HTTP ${e}). It may be invalid, expired or revoked.`}:e===404&&Zi(t)?{kind:"scope",message:"Vercel rejected the token (HTTP 404). Its Scope doesn't include your account, for example it was limited to a single project."}:{kind:"api",message:`Vercel API returned HTTP ${e}. Try again or check status.vercel.com.`}}async function Re(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let s=await t.text().catch(()=>"");return{ok:!1,...eo(t.status,s)}}let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,kind:"network",message:`Could not reach Vercel: ${I(t)}`}}}var Qn="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 ve(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${Qn}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let r=await o.json(),a=r.result?.status;if(r.success===!1||a&&a!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${a?` (status: ${a})`:""}. ${Jn(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}try{let o=await fetch(`${Qn}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let r=await o.json();return r.success===!1?{ok:!1,message:Jn(r)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(r.result)?r.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}}var Xn="https://api.netlify.com/api/v1";async function Oe(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${Xn}/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(`${Xn}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),r=Array.isArray(o)?o:[];if(r.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let a=typeof r[0]?.slug=="string"?r[0].slug:void 0;return{ok:!0,accountCount:r.length,accountSlug:a}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}}function to(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 Le(e){let t=dn(e);if(t)return{ok:!1,message:t};let n=de(e),s=n.value,o=r=>{let a=[r],l=un(e);return l&&a.push(l),n.repairs.length>0&&a.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),a.join(`
|
|
16
|
-
`)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let a={};try{a=await r.json()}catch{}let
|
|
12
|
+
`}function $i(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 V(e){let t={};for(let n of e.split(`
|
|
13
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),a=$i(s.slice(o+1).trim());t[r]=a}return t}var jn=["VERCEL_TOKEN","CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","NETLIFY_AUTH_TOKEN","EMAIL_PROVIDER","EMAIL_AUTH","EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT","SMS_PROVIDER","TEST_PHONE","TWILIO_ACCOUNT_SID","TWILIO_AUTH_TOKEN","TWILIO_PHONE_NUMBER","WHATSAPP_ACCOUNTS","LETTER_PROVIDER","PINGEN_CLIENT_ID","PINGEN_CLIENT_SECRET","PINGEN_ORG_ID","POSTGRID_API_KEY","NOTIFY_CHANNEL","TELEGRAM_BOT_TOKEN","TELEGRAM_CHAT_ID"];function Kn(e,t,n={}){let s={...e},o=c=>(t[c]??"").trim()!=="";if(!o("PRICING_TERMS")&&(o("PRICING")||o("PRICING_MONTHLY"))){let c=_n(wt(t.PRICING,s.countryCode)??"",wt(t.PRICING_MONTHLY,s.countryCode)??"");s.pricing=c.pricing,s.pricingTerms=c.pricingTerms,s.pricingMonthly=c.pricingMonthly}s.signature&&s.name&&s.signature.trim()===s.name.trim()&&(s.signature=void 0),o("EMAIL_FROM_NAME")||(s.emailFromName=s.name?.trim()&&s.emailAddress?.trim()?s.name.trim():void 0);let r=s.emailProvider&&s.emailProvider!=="custom"?Q[s.emailProvider]:void 0,a=et(n)===s.emailProvider&&(n.EMAIL_ADDRESS??"").trim().toLowerCase()===(s.emailAddress??"").trim().toLowerCase(),d=[["EMAIL_SENT_FOLDER","emailSentFolder",r?.sentFolder],["EMAIL_DRAFTS_FOLDER","emailDraftsFolder",r?.draftsFolder],["EMAIL_INBOX_FOLDER","emailInboxFolder",r?.inboxFolder]];for(let[c,p,u]of d)o(c)||a&&(n[c]??"").trim()||(s[p]=u);return s}function Gn(e){let t=d=>{let c=e[d];if(!c)return;let p=parseInt(c,10);return isNaN(p)?void 0:p},n=e.SMS_PROVIDER,s=d=>d==="email"||d==="sms"||d==="whatsapp"||d==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(d=>d.trim()).filter(s),r=e.OUTREACH_PRIORITY?.split(",").map(d=>d.trim()).filter(s),a=e.WHATSAPP_ACCOUNTS?.split(",").map(d=>d.trim()).filter(d=>d.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Nn(e.AI_AGENT)??Xt,aiPlan:kt(e.AI_PLAN),qaPhase:At(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(d=>d.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:r&&r.length>0?r:void 0,whatsappAccounts:a&&a.length>0?a:void 0,emailProvider:et(e),emailAuth:Dn(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:Jt(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:$n(e.DEPLOY_PROVIDER)??en,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:Mn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function bt(e){let t=b=>{let ie=e[b];if(!ie)return;let B=parseInt(ie,10);return isNaN(B)?void 0:B},n=e.SUPABASE_URL,s=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),r=e.SUPABASE_PROJECT_REF,a=e.PRICING,d=e.PRICING_TERMS||"one-off, no monthly fees",c=$n(e.DEPLOY_PROVIDER)??en,p=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,A=e.CLOUDFLARE_ACCOUNT_ID,P=e.NETLIFY_AUTH_TOKEN,T=e.SELFHOST_DEPLOY_TARGET,m=e.SELFHOST_URL_TEMPLATE;if(!a||!n||!s||!o||!r||!(c==="cloudflare"?!!u&&!!A:c==="netlify"?!!P:c==="selfhost"?!!T&&!!m:!!p))return null;let S=e.SMS_PROVIDER,C=b=>b==="email"||b==="sms"||b==="whatsapp"||b==="letter",G=e.OUTREACH_CHANNELS?.split(",").map(b=>b.trim()).filter(C),me=e.OUTREACH_PRIORITY?.split(",").map(b=>b.trim()).filter(C),ne=e.WHATSAPP_ACCOUNTS?.split(",").map(b=>b.trim()).filter(b=>b.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Nn(e.AI_AGENT)??Xt,aiPlan:kt(e.AI_PLAN),qaPhase:At(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(b=>b.trim().toLowerCase()).filter(Boolean):void 0,pricing:a,pricingTerms:d,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:G&&G.length>0?G:void 0,outreachPriority:me&&me.length>0?me:void 0,whatsappAccounts:ne&&ne.length>0?ne:void 0,emailProvider:et(e),emailAuth:Dn(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:S==="imessage"||S==="twilio"?S:void 0,testPhone:Jt(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:c,vercelToken:p,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:A||void 0,netlifyAuthToken:P||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:T||void 0,selfhostUrlTemplate:m||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:Mn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Ya,mkdir as Wa,readdir as Ki,stat as qa}from"fs/promises";import{dirname as Qa,join as Qn,relative as Gi,sep as Bi}from"path";import{fileURLToPath as Xa}from"url";import{createHash as Bn}from"crypto";import{readFile as Mi}from"fs/promises";async function Ne(e){let t=await Mi(e);return Bn("sha256").update(t).digest("hex")}function tn(e){return Bn("sha256").update(e).digest("hex")}import{mkdir as Di,readFile as Fi,writeFile as Ui,access as Hi}from"fs/promises";import{dirname as ji,join as Vn}from"path";var tt=".klaudius",Yn=`${tt}/manifest.json`,_t=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json"]),Wn=new Set(["clients/README.md"]),Tt=new Set(["package-lock.json"]);async function qn(e){let t=Vn(e,Yn);try{await Hi(t)}catch{return null}let n=await Fi(t,"utf-8"),s=JSON.parse(n),o={};for(let[r,a]of Object.entries(s.files??{}))o[r.split("\\").join("/")]=a;return s.files=o,Array.isArray(s.ignored)?s.ignored=s.ignored.filter(r=>typeof r=="string").map(r=>r.split("\\").join("/")):delete s.ignored,s}async function nt(e,t){let n=Vn(e,Yn);await Di(ji(n),{recursive:!0}),await Ui(n,JSON.stringify(t,null,2)+`
|
|
14
|
+
`,"utf-8")}function zn(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function Se(e,t=e){let n=await Ki(e,{withFileTypes:!0}),s=[];for(let o of n){let r=Qn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await Se(r,t)):o.isFile()&&s.push(Gi(t,r).split(Bi).join("/")))}return s}async function Jn(e){let t=await Se(e),n={};for(let s of t)_t.has(s)||(n[s]=await Ne(Qn(e,s)));return n}import{copyFile as Vi,mkdir as Xn,mkdtemp as Yi,readdir as Zn,rm as es}from"fs/promises";import{tmpdir as Wi}from"os";import{dirname as qi,join as It}from"path";import{Readable as zi}from"stream";import*as ts from"tar";var Qi="https://klaudius.dev/api/template";function Ji(e){return zi.fromWeb(e)}async function Ct(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Qi,n="0.34.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(d){throw new Error(`Could not reach klaudius.dev to download the template: ${I(d)}`)}if(!s.ok){let d="";try{let c=await s.json();d=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${d}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),r=await Yi(It(Wi(),"klaudius-template-")),a=0;try{try{await new Promise((p,u)=>{let A=ts.extract({cwd:r,strict:!0});A.on("finish",p),A.on("error",u),Ji(s.body).on("error",u).pipe(A)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await Xn(e.destDir,{recursive:!0});let d=new Set(await Zn(e.destDir)),c=await Se(r);try{for(let p of c){let u=It(e.destDir,p);await Xn(qi(u),{recursive:!0}),await Vi(It(r,p),u),a++}}catch(p){let u=await Zn(e.destDir).catch(()=>[]);for(let A of u)d.has(A)||await es(It(e.destDir,A),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await es(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:a,tier:o}}import{copyFile as Xi,mkdir as Zi,readFile as ns,rm as eo}from"fs/promises";import{dirname as to,join as be}from"path";import{structuredPatch as no}from"diff";var ss=be(".klaudius","base"),Rt=be(".klaudius","conflict-base");async function xt(e,t,n){let s=be(e,ss);await eo(s,{recursive:!0,force:!0});for(let o of n){let r=be(s,o);await Zi(to(r),{recursive:!0}),await Xi(be(t,o),r)}}async function is(e,t){try{return await ns(be(e,ss,t),"utf-8")}catch{return null}}async function os(e,t){try{return await ns(be(e,Rt,t),"utf-8")}catch{return null}}function rs(e,t,n,s){return $e(n)?null:e!==null&&!$e(e)&&(!s||tn(e)===s)?e:t!==null&&!$e(t)&&s&&tn(t)===s?t:null}function $e(e){return e.includes("\0")||e.includes("\uFFFD")}function as(e,t,n=60){let s=no("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(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),r=[`Upstream changed ${s.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],a=0,d=!1;for(let c of s.hunks){if(a>=n){d=!0;break}r.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),a+=1;let p=Math.max(n-a,0),u=c.lines.slice(0,p);if(r.push(...u),a+=u.length,u.length<c.lines.length){d=!0;break}}return r.push("```"),d&&r.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),r}import we from"picocolors";var i={info:e=>console.log(we.cyan("\u2139"),e),success:e=>console.log(we.green("\u2713"),e),warn:e=>console.log(we.yellow("\u26A0"),e),error:e=>console.error(we.red("\u2717"),e),step:e=>console.log(we.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+we.bold(we.cyan(e))),detail:e=>console.log(we.dim(" "+e))};var so="https://registry.npmjs.org/klaudius/latest";async function io(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(so,{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 oo(e,t){let n=r=>r.split("-")[0].split(".").map(a=>Number.parseInt(a,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(s[r])||Number.isNaN(o[r]))return!1;if(s[r]>o[r])return!0;if(s[r]<o[r])return!1}return!1}async function Ot(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await io();!n||!oo(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 ro}from"crypto";import{hostname as ls,userInfo as ao,platform as cs,arch as ds}from"os";var lo="https://klaudius.dev",co="/api/licenses/validate",uo="0.34.1";async function us(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??lo).replace(/\/$/,"")+co,o=st(),r;try{r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:ls(),os:`${cs()}-${ds()}`,cli_version:uo})})}catch(d){return{ok:!1,reason:`Could not reach the Klaudius license server (${I(d)}). Check your internet connection or try again later.`}}let a;try{a=await r.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${r.status}).`}}return a.ok?{ok:!0,tier:a.tier??"core"}:{ok:!1,reason:a.reason??`License rejected (HTTP ${r.status}).`}}function st(){let e=[ls(),ao().username,cs(),ds()].join("|");return ro("sha256").update(e).digest("hex").slice(0,32)}import{readFile as po}from"fs/promises";import{join as fo}from"path";async function Me(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)}`}}}function ps(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function vt(e){let t;try{t=await po(fo(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{ok:!1,message:go(s.status,o)}}catch(s){return{ok:!1,message:`Schema apply failed: ${I(s)}`}}}function ho(e){let t=[...e.matchAll(/ALTER TABLE clients ADD COLUMN IF NOT EXISTS (\w+)/g)].map(s=>s[1]),n=[...e.matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/g)].map(s=>s[1]);return{clientsColumns:[...new Set(t)],tables:[...new Set(n)]}}function mo(e,t){let n="";try{let o=JSON.parse(t);o&&typeof o.code=="string"&&(n=o.code)}catch{}return{missing:e===400&&n==="42703"||e===404&&(n==="PGRST205"||n==="42P01"),code:n}}async function Lt(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{clientsColumns:s,tables:o}=ho(e.sql),r=[];s.length>0&&r.push({path:`clients?select=${s.join(",")}&limit=0`,label:"clients columns"});for(let d of o)d!=="clients"&&r.push({path:`${d}?select=*&limit=0`,label:`${d} table`});let a=[];try{for(let d of r){let c=await fetch(`${t}/rest/v1/${d.path}`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(c.ok)continue;let p=mo(c.status,await c.text());if(p.missing){a.push(d.label);continue}return{ok:!1,missing:a,unreachable:`HTTP ${c.status}${p.code?` ${p.code}`:""}`}}}catch(d){return{ok:!1,missing:a,unreachable:I(d)}}return{ok:a.length===0,missing:a}}function go(e,t){let n=t;try{let s=JSON.parse(t);s&&typeof s.message=="string"&&(n=s.message)}catch{}return n=n.replace(/\s+/g," ").trim().slice(0,300),e===401?"Supabase rejected the access token (HTTP 401) \u2014 SUPABASE_PAT in .env is invalid, expired or revoked. Create a new token at https://supabase.com/dashboard/account/tokens and run `npx klaudius@latest configure`.":e===403?"The Supabase access token doesn't cover this project (HTTP 403) \u2014 it was scoped to a different organisation or project. Create a token that includes this project at https://supabase.com/dashboard/account/tokens and run `npx klaudius@latest configure`.":e===429?"Supabase rate-limited the request (HTTP 429). Wait a minute and try again.":`Supabase Management API rejected the schema (HTTP ${e}): ${n}`}function yo(e){try{let t=JSON.parse(e);return t.error?.code==="not_found"?!0:/user not found/i.test(t.error?.message??"")}catch{return!1}}function wo(e,t){return e===401||e===403?{kind:"rejected",message:`Vercel rejected the token (HTTP ${e}). It may be invalid, expired or revoked.`}:e===404&&yo(t)?{kind:"scope",message:"Vercel rejected the token (HTTP 404). Its Scope doesn't include your account, for example it was limited to a single project."}:{kind:"api",message:`Vercel API returned HTTP ${e}. Try again or check status.vercel.com.`}}async function De(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let s=await t.text().catch(()=>"");return{ok:!1,...wo(t.status,s)}}let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,kind:"network",message:`Could not reach Vercel: ${I(t)}`}}}var fs="https://api.cloudflare.com/client/v4";function hs(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Fe(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${fs}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let r=await o.json(),a=r.result?.status;if(r.success===!1||a&&a!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${a?` (status: ${a})`:""}. ${hs(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}try{let o=await fetch(`${fs}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let r=await o.json();return r.success===!1?{ok:!1,message:hs(r)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(r.result)?r.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}}var ms="https://api.netlify.com/api/v1";async function Ue(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${ms}/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(`${ms}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),r=Array.isArray(o)?o:[];if(r.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let a=typeof r[0]?.slug=="string"?r[0].slug:void 0;return{ok:!0,accountCount:r.length,accountSlug:a}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}}function ko(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 He(e){let t=Tn(e);if(t)return{ok:!1,message:t};let n=ge(e),s=n.value,o=r=>{let a=[r],d=In(e);return d&&a.push(d),n.repairs.length>0&&a.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),a.join(`
|
|
16
|
+
`)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let a={};try{a=await r.json()}catch{}let d=a.error?.message??"",c=a.error?.status??"";return r.status===400&&(c==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(d))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library/places.googleapis.com and press Enable for the project this key belongs to, then try again. (That page is 'Places API (New)' \u2014 the older 'Places API' is a different API and won't work.)"}:r.status===401||r.status===403?{ok:!1,message:o(ko(r.status,d))}:{ok:!1,message:o(`Google API returned HTTP ${r.status}${d?`: ${d}`:""}.`)}}catch(r){return{ok:!1,message:`Could not reach Google: ${I(r)}`}}}import Ao from"nodemailer";import{ImapFlow as Eo}from"imapflow";function Po(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function gs(e,t,n){let s=t.toLowerCase(),o=e.filter(Po);if(o.some(d=>d.path.toLowerCase()===s))return;let r=s.startsWith("inbox")?void 0:[`inbox.${s}`,`inbox/${s}`],a=o.find(d=>d.specialUse===n)?.path??(r&&o.find(d=>r.includes(d.path.toLowerCase()))?.path);return{configured:t,detected:a||void 0}}function nn(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 pe(e){let t=Ao.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(a){return{ok:!1,failedAt:"smtp",message:ys(a,"SMTP",e.usesAccountPassword,e.knownProvider),failureKind:nn(a)}}finally{t.close()}let n=new Eo({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),s,o,r;try{if(await n.connect(),e.sentFolder||e.draftsFolder)try{let a=await n.list();e.sentFolder&&(s=gs(a,e.sentFolder,"\\Sent")),e.draftsFolder&&(o=gs(a,e.draftsFolder,"\\Drafts"))}catch{r=!0}await n.logout()}catch(a){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:ys(a,"IMAP",e.usesAccountPassword,e.knownProvider),failureKind:nn(a)}}return{ok:!0,sentFolderIssue:s,draftsFolderIssue:o,foldersUnverified:r}}function ys(e,t,n,s){let o=e instanceof Error?e.message:String(e),r=o.toLowerCase();return nn(e)==="auth"||r.includes("invalid credentials")||r.includes("authentication failed")||r.includes("auth failed")||r.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
|
-
access is enabled and 2FA is off in your provider's settings
|
|
20
|
+
access is enabled and 2FA is off in your provider's settings.`:s===!1?`${t} rejected the credentials. Most common causes:
|
|
21
|
+
\u2022 The password is wrong or mistyped. Signing in to the mailbox's webmail
|
|
22
|
+
with it is a quick way to check.
|
|
23
|
+
\u2022 The email address isn't this mailbox's login name.
|
|
24
|
+
\u2022 The server or port belongs to a different mailbox or provider.
|
|
25
|
+
\u2022 The provider needs an app password here rather than the normal one.`:`${t} rejected the credentials. Most common causes:
|
|
21
26
|
\u2022 The app password is wrong, expired, or for a different provider.
|
|
22
27
|
\u2022 The email address doesn't match the account that issued the password.
|
|
23
28
|
\u2022 The address is an alias (e.g. a Google Workspace alias domain) \u2014 the
|
|
24
29
|
sign-in must use the account's primary address. Keep the alias as
|
|
25
30
|
EMAIL_ADDRESS and set EMAIL_LOGIN in .env to the primary address.
|
|
26
|
-
\u2022 2FA is required but no app-specific password was generated.`:
|
|
27
|
-
`+t;return
|
|
28
|
-
${e.stdout??""}`;return
|
|
29
|
-
`,"utf-8"),"added"}catch(r){return i.warn(`Couldn't write ${o} (${r instanceof Error?r.message:String(r)}). The parallel-run dispatch may occasionally ask for approval.`),"skipped"}}async function
|
|
30
|
-
`,"utf-8")}var
|
|
31
|
-
runs on. It sets the QA-pass default (and, on the smaller ChatGPT plans, the model).`}))):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),
|
|
32
|
-
${
|
|
31
|
+
\u2022 2FA is required but no app-specific password was generated.`:r.includes("etimedout")||r.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:r.includes("enotfound")||r.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${o}`}import*as Nt from"@clack/prompts";var So=[{key:"emailSentFolder",envKey:"EMAIL_SENT_FOLDER",label:"Sent",consequence:"Sent mail wouldn't be filed there, and follow-ups couldn't see what was sent to whom.",issue:e=>e.sentFolderIssue},{key:"emailDraftsFolder",envKey:"EMAIL_DRAFTS_FOLDER",label:"Drafts",consequence:"Saving drafts (manual-approval outreach, /send-invoice) would fail.",issue:e=>e.draftsFolderIssue}];async function $t(e,t,n){let s=!1;for(let o of So){let r=o.issue(e);if(r){if(i.blank(),r.detected){if(n.nonInteractive){t[o.key]=r.detected,s=!0,i.warn(`Your mailbox has no "${r.configured}" folder \u2014 it calls its ${o.label} folder "${r.detected}". Using that.`);continue}i.warn(`Your mailbox has no "${r.configured}" folder.`),i.detail(`It calls its ${o.label} folder "${r.detected}".`);let a=await Nt.confirm({message:`Use "${r.detected}" instead?`,initialValue:!0});if(Nt.isCancel(a))return n.onCancel?.(),s;a?(t[o.key]=r.detected,s=!0,i.success(`${o.envKey} set to "${r.detected}"`)):i.warn(`Keeping "${r.configured}". ${o.consequence}`);continue}i.warn(`Your mailbox has no "${r.configured}" folder. ${o.consequence}`),i.detail(`After setup, ask your AI agent to list the mailbox's folders and set ${o.envKey} in .env to the real name.`)}}return s}async function ws(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 Mt(e){return e.provider==="pingen"?bo(e):_o(e)}async function bo(e){if(!e.pingenClientId||!e.pingenClientSecret||!e.pingenOrgId)return{ok:!1,message:"Missing Pingen Client ID, Client Secret, or organisation id."};let t=e.pingenStaging?"https://identity-staging.pingen.com":"https://identity.pingen.com",n=e.pingenStaging?"https://api-staging.pingen.com":"https://api.pingen.com";try{let s=await fetch(`${t}/auth/access-tokens`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:e.pingenClientId,client_secret:e.pingenClientSecret,scope:"letter"})});if(!s.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${s.status}). Check the Client ID and Secret under your organisation's 'API Access' page \u2014 note that staging and production credentials are separate.`};let o=(await s.json()).access_token;if(!o)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let r=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${o}`}});return r.status===403||r.status===404?{ok:!1,message:"Pingen accepted the credentials but not the organisation id. Copy it from the dashboard URL: app.pingen.com/organisations/<id>/\u2026"}:r.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${r.status}. Try again shortly.`}}catch(s){return{ok:!1,message:`Could not reach Pingen: ${I(s)}`}}}async function _o(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 To}from"child_process";async function ks(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 Io(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 Io(e){return new Promise(t=>{let n=To("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 Dt}from"child_process";import{existsSync as Co}from"fs";import{homedir as Ro}from"os";function xo(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var je=2,As=2e3,Oo=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Es(e,t){let n=e+`
|
|
32
|
+
`+t;return Oo.some(s=>s.test(n))}function Ps(e){return new Promise(t=>setTimeout(t,e))}function vo(e,t,n){return new Promise(s=>{let o=n.shell?Dt([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):Dt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),r="",a="";o.stdout?.on("data",d=>{let c=d.toString();r+=c,process.stdout.write(c)}),o.stderr?.on("data",d=>{let c=d.toString();a+=c,process.stderr.write(c)}),o.on("close",d=>s({code:d??1,stdout:r,stderr:a})),o.on("error",d=>s({code:1,stdout:r,stderr:a+d.message}))})}async function sn(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=je;o++){if(s=await vo(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!Es(s.stderr,s.stdout))return s;o<je&&(i.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${je+1})\u2026`),await Ps(As))}return s}function Lo(e,t,n){return new Promise(s=>{let o=Dt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",d=>{r+=d.toString()}),o.stderr?.on("data",d=>{a+=d.toString()}),o.on("close",d=>s({code:d??1,stdout:r,stderr:a})),o.on("error",d=>s({code:1,stdout:r,stderr:a+d.message}))})}var No=[{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 $o(e){let t=`${e.stderr??""}
|
|
33
|
+
${e.stdout??""}`;return No.find(s=>s.pattern.test(t))?.hint}async function Mo(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await W())?.command??["python3"],r=async d=>{let c={code:0,stdout:"",stderr:""};for(let p=0;p<=je;p++){if(c=await Lo(o[0],[...o.slice(1),...d],{cwd:e}),c.code===0||!Es(c.stderr,c.stdout))return c;p<je&&(i.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${je+1})\u2026`),await Ps(As))}return c},a=await r([...n,"--break-system-packages",...t]);return a.code!==0&&/no such option:.*break-system-packages/i.test(a.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),a=await r([...n,...t])),a.code!==0&&(a.stderr.trim()&&process.stderr.write(a.stderr),a.stdout.trim()&&process.stdout.write(a.stdout)),a}async function Ft(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=xo(),s=process.platform==="win32",o;if(s){let u=xe([{label:"your Windows user folder",path:Ro()},{label:"the project folder",path:e}]);if(u.length>0){let A=await new Promise(T=>{let m=Dt("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),l="",S="";m.stdout?.on("data",C=>{l+=C.toString()}),m.stderr?.on("data",C=>{S+=C.toString()}),m.on("close",C=>T({code:C??1,stdout:l,stderr:S})),m.on("error",C=>T({code:1,stdout:l,stderr:C.message}))}),P=A.code===0?A.stdout.trim():void 0;if(!Oe(P,Co)){let{detail:T,action:m}=ve(u,"install");o=`${T}. ${m}`}}}let r=(u,A)=>{let P=$o(A);if(P){(t.hints??={})[u]=P;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 a=await sn("npm",["install"],{cwd:e,label:"npm install",env:n,shell:s});t.npm=a.code===0?"ok":"failed",a.code!==0&&r("npm",a),i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let d=await Mo(e);t.pip=d.code===0?"ok":"failed",d.code!==0&&r("pip",d),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await sn("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:s});t.playwright=c.code===0?"ok":"failed",c.code!==0&&r("playwright",c),i.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await sn("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:s});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&r("patchright",p),t}import{copyFile as Do,access as Fo}from"fs/promises";import{dirname as Uo,join as Ho}from"path";async function Ss(){let e=await gt("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 on(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await Ss();if(e.state==="real")return{status:"ok",version:e.version};let t=await W();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function jo(e){let[t,...n]=e.command,s=await gt(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 r=Ho(Uo(o),"python3.exe"),a=await Fo(r).then(()=>!0,()=>!1);if(!a){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await Do(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let d=await Ss();return{ok:!0,target:r,created:!a,verified:d.state==="real",postState:d.state==="real"?void 0:d.state}}var Ko="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 Ut(){let e=await on();if(e.status!=="broken")return;let t=await jo(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(Ko);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 Go,spawnSync as bs}from"child_process";import{mkdtemp as Bo,rm as Vo,rmdir as Yo,writeFile as Wo,stat as rn,unlink as qo,mkdir as zo}from"fs/promises";import{createServer as Qo}from"net";import{tmpdir as Jo}from"os";import{join as Ke}from"path";function Xo(){return new Promise((e,t)=>{let n=Qo();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 Ht(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?bs(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):bs("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function jt(e){try{return await Zo(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Zo(e){let t=`klaudius-smoke-${process.pid}`,n=Ke(".klaudius",`qa-smoke-${process.pid}.png`),s=Ke(e,n),o,r,a=!1;try{o=await Bo(Ke(Jo(),"klaudius-qa-smoke-")),await Wo(Ke(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let d=await Xo();r=Go("python3",["-m","http.server",String(d),"--directory",o],{stdio:"ignore",shell:!1});let c=!1;r.on("error",()=>{c=!0}),r.on("exit",()=>{c=!0});let p=`http://127.0.0.1:${d}/`,u=!1;for(let S=0;S<24&&!c;S++)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 A=Ke(e,".klaudius"),P=await rn(A).then(()=>!0,()=>!1);await zo(A,{recursive:!0}),a=!P;let T=Ht(e,[`-s=${t}`,"open",p]);if(T.status!==0)return{ok:!1,stage:"browser",detail:((T.stderr??"")+(T.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 m=Ht(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await rn(s).catch(()=>null);if((!l||l.size===0)&&(m=Ht(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await rn(s).catch(()=>null)),!l||l.size===0){let S=((m.stderr??"")+(m.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${S?` (${S})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{Ht(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await qo(s).catch(()=>{}),a&&await Yo(Ke(e,".klaudius")).catch(()=>{}),o&&await Vo(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as _s,readFile as er,writeFile as Ts}from"fs/promises";import{join as Kt}from"path";var Ge="Bash(claude --bg --permission-mode auto *)";async function Is(e){let t;try{t=await er(e,"utf-8")}catch{return{}}try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return null}async function Be(e,t){let n=Kt(e,".claude"),s=Kt(n,"settings.local.json"),o=".claude/settings.local.json";try{await _s(n,{recursive:!0});let r=await Is(s);if(r===null)return i.warn(`${o} isn't valid JSON, so it was left as-is. Fix it and re-run to pre-approve the parallel-run dispatch.`),"skipped";let a=r.permissions&&typeof r.permissions=="object"&&!Array.isArray(r.permissions)?r.permissions:{},d=a.allow,c=Array.isArray(d)?d.filter(u=>typeof u=="string"):[];if(c.includes(t))return"present";c.push(t);let p={...r,permissions:{...a,allow:c}};return await Ts(s,JSON.stringify(p,null,2)+`
|
|
34
|
+
`,"utf-8"),"added"}catch(r){return i.warn(`Couldn't write ${o} (${r instanceof Error?r.message:String(r)}). The parallel-run dispatch may occasionally ask for approval.`),"skipped"}}async function Gt(e,t){let n=Kt(e,".claude");await _s(n,{recursive:!0});let s=Kt(n,"settings.json"),o=await Is(s)??{},r=o.enabledMcpjsonServers,a=Array.isArray(r)?r.filter(c=>typeof c=="string"):[];a.includes(t)||a.push(t);let d={...o,enabledMcpjsonServers:a};await Ts(s,JSON.stringify(d,null,2)+`
|
|
35
|
+
`,"utf-8")}var Rs="0.34.1",$=5,x=!1;function H(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)}function an(e){return j(e,tt,"setup-pending")}function ln(e){return j(e,tt,"ms-signin.json")}async function xs(e){return Ve(j(e,".ms-token.json"),"utf-8").then(t=>String(JSON.parse(t).account?.address??"")).then(t=>t.trim().toLowerCase()).catch(()=>"")}function or(e){let t=process.env.KLAUDIUS_WHATSAPP_STATE_DIR||j(vs(),".klaudius","whatsapp");return tr(j(t,e,"auth","creds.json"))}async function rr(e){let t;try{t=await Ve(e,"utf-8")}catch{H("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let s=JSON.parse(n),o={};for(let[r,a]of Object.entries(s))a!=null&&(o[r]=typeof a=="string"?a:String(a));return o}catch(s){H("answers",`Answers file is not valid JSON: ${s.message}`)}return V(t)}function fe(e){return`npx klaudius@latest init ${Yt(Ye(e))}`}function Ye(e){if(process.platform==="win32")return e;let t=vs();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function ar(e){let t=[];try{let s=(await Os(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let r=j(e,o.name);if(!await Vt(j(r,".env")))continue;let a=await Vt(j(r,".klaudius","manifest.json"));if(t.push({path:r,finished:a}),t.length>=3)break}}catch{}return t}async function Vt(e){try{return await cn(e),!0}catch{return!1}}function Yt(e){return/\s/.test(e)?`"${e}"`:e}function re(e,t,n){i.blank(),i.error(`${t} validation failed ${$} 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(fe(e))}`),i.blank(),i.detail(` (Your .env is at ${Ye(j(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 Ls(e){let t=e.target??".",n=sr(t)?t:nr(process.cwd(),t),s=ur(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"&&pr()&&(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 Ot("init",Rs);let o=await lr(n),r=o.kind==="scaffolded"&&!!e.answers&&await Vt(an(n));if(o.kind==="scaffolded"&&!r){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 ${Yt(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===".",y=await ar(n);if(y.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: ${Ye(n)}`),i.blank();for(let g of y)i.detail(g.finished?`Found a finished project at ${Ye(g.path)}. To work in it:`:`Found an unfinished setup at ${Ye(g.path)}. To pick up where it left off:`),i.blank(),g.finished?(console.log(` ${h.cyan(`cd ${Ye(g.path)}`)}`),console.log(` ${h.cyan("claude")} ${h.dim("# open Claude Code in the project")}`)):console.log(` ${h.cyan(fe(g.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&&(x=!0,a=await rr(e.answers),i.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let d=a??{},c={};if(a){let f=await Ve(j(n,".env"),"utf-8").catch(()=>null);f&&(c=V(f),a={...Object.fromEntries(Object.entries(c).filter(([g])=>!jn.includes(g))),...a})}let p=e.license??a?.KLAUDIUS_LICENSE_KEY;x&&(!p||p.trim().length===0)&&H("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let u=await dr(p),A=E.spinner();A.start("Validating license");let P=await us(u);P.ok||(A.stop(`License invalid: ${P.reason??"unknown"}`,2),i.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),x&&H("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)),A.stop(`License valid (${P.tier??"core"} tier)`);let T=await Le();T.ok||(i.error(T.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${fe(n)}`),process.exit(1)),await Ut();let m=ye();m.ok||(i.error(m.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${fe(n)}`),process.exit(1));let l,S=!1;if(a){let f=bt(a);f||H("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."),l=Kn(f,d,c),i.success("Loaded setup answers (non-interactive mode)");let y=c.AI_AGENT==="codex"?"codex":"claude-code";if(r&&y!==(l.aiAgent??"claude-code")){let g=k=>k==="codex"?"Codex":"Claude Code";H("install",`This folder was set up for ${g(y)}, so it can't carry on as ${g(l.aiAgent??"claude-code")}. Give the folder a different name to set up fresh, or switch back.`)}}else if(o.kind==="partial")if(await cr(n)==="resume"){let y=await Ve(o.envPath,"utf-8"),g=bt(V(y));g?(i.success("Resuming with values from your existing .env"),i.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=g,S=!0,l.aiPlan||(l=await F(l,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
|
|
36
|
+
runs on. It sets the QA-pass default (and, on the smaller ChatGPT plans, the model).`}))):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await F())}else{let y=await Ve(o.envPath,"utf-8"),g=bt(V(y));l=await F(g??{})}else l=await F();l.licenseKey=u,await U(n,l),S||(i.success("Saved .env"),i.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let f=1;;f++){let y=E.spinner();y.start("Validating Supabase credentials");let g=await Me({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(g.ok){y.stop("Supabase credentials accepted");break}y.stop(g.message??"Supabase check failed",2),f>=$&&re(n,"Supabase",g.message??"Supabase check failed");let k=g.message??"Supabase check failed";i.blank(),x&&H("supabase",k),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
37
|
+
${k}
|
|
33
38
|
|
|
34
39
|
Re-enter the URL, secret key, or PAT below. Press Enter on any
|
|
35
|
-
field to keep what's already there.`}),await
|
|
36
|
-
${
|
|
40
|
+
field to keep what's already there.`}),await U(n,l)}if(i.blank(),l.deployProvider==="cloudflare")for(let f=1;;f++){let y=E.spinner();y.start("Validating Cloudflare token + account");let g=await Fe({token:l.cloudflareApiToken??"",accountId:l.cloudflareAccountId??""});if(g.ok){y.stop(`Cloudflare credentials accepted (${g.projectCount??0} existing Pages project${g.projectCount===1?"":"s"})`);break}y.stop(g.message??"Cloudflare check failed",2),f>=$&&re(n,"Cloudflare",g.message??"Cloudflare check failed");let k=g.message??"Cloudflare check failed";i.blank(),x&&H("cloudflare",k),i.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
|
|
41
|
+
${k}
|
|
37
42
|
|
|
38
43
|
Re-enter the API token or Account ID below. The token needs the
|
|
39
44
|
"Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
|
|
40
|
-
the current value.`}),await
|
|
41
|
-
${
|
|
45
|
+
the current value.`}),await U(n,l)}else if(l.deployProvider==="netlify")for(let f=1;;f++){let y=E.spinner();y.start("Validating Netlify token");let g=await Ue({token:l.netlifyAuthToken??""});if(g.ok){y.stop(g.accountSlug?`Netlify token accepted (team: ${g.accountSlug})`:"Netlify token accepted");break}y.stop(g.message??"Netlify check failed",2),f>=$&&re(n,"Netlify",g.message??"Netlify check failed");let k=g.message??"Netlify check failed";i.blank(),x&&H("netlify",k),i.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"netlify",banner:`Netlify rejected the token:
|
|
46
|
+
${k}
|
|
42
47
|
|
|
43
48
|
Generate a new token at
|
|
44
49
|
https://app.netlify.com/user/applications#personal-access-tokens
|
|
45
|
-
and paste it below. Press Enter to keep the current value.`}),await
|
|
46
|
-
`);
|
|
47
|
-
${
|
|
50
|
+
and paste it below. Press Enter to keep the current value.`}),await U(n,l)}else if(l.deployProvider==="selfhost")for(let f=1;;f++){let y=pt(l.selfhostDeployTarget??""),g=ft(l.selfhostUrlTemplate??"");if(!y&&!g){i.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let k=[y&&`SELFHOST_DEPLOY_TARGET: ${y}`,g&&`SELFHOST_URL_TEMPLATE: ${g}`].filter(Boolean).join(`
|
|
51
|
+
`);f>=$&&re(n,"Self-host",k),i.blank(),x&&H("selfhost",k),i.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${f+1} of ${$})`),i.blank(),l=await F(l,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
|
|
52
|
+
${k}
|
|
48
53
|
|
|
49
|
-
Re-enter them below. Press Enter on a field to keep its current value.`}),await
|
|
54
|
+
Re-enter them below. Press Enter on a field to keep its current value.`}),await U(n,l)}else for(let f=1;;f++){let y=E.spinner();y.start("Validating Vercel token");let g=await De(l.vercelToken??"");if(g.ok){y.stop(g.username?`Vercel token accepted (signed in as ${g.username})`:"Vercel token accepted");break}y.stop(g.message,2);let k=g.message,R=g.kind==="rejected"||g.kind==="scope",M=R?`${k} Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration).`:k;f>=$&&re(n,"Vercel",M),i.blank(),x&&H("vercel",M),i.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"vercel",banner:R?`${k}
|
|
50
55
|
|
|
51
56
|
Create a new token at https://vercel.com/account/settings/tokens
|
|
52
57
|
(Scope: Full Account, Expiration: No Expiration) and paste it
|
|
53
|
-
below. Press Enter to keep the current value.`:`${
|
|
58
|
+
below. Press Enter to keep the current value.`:`${k}
|
|
54
59
|
|
|
55
60
|
Press Enter to keep the current value and try again, or paste a
|
|
56
|
-
different token.`}),await
|
|
57
|
-
${
|
|
61
|
+
different token.`}),await U(n,l)}i.blank();for(let f=1;;f++){let y=ge(l.googlePlacesApiKey??""),g=E.spinner();g.start("Validating Google Places API key");let k=await He(l.googlePlacesApiKey??"");if(k.ok){if(g.stop("Google Places API key accepted"),y.changed){if(y.repairs.length>0){i.blank(),i.warn("Corrected look-alike characters in your Google Places API key:");for(let M of y.repairs)i.detail(` ${M}`);i.detail("These come from keys that were transcribed rather than copied."),i.detail("Google accepted the corrected key, and .env now holds it.")}l.googlePlacesApiKey=y.value,await U(n,l)}break}g.stop(k.message??"Google Places check failed",2),f>=$&&re(n,"Google Places",k.message??"Google Places check failed");let R=k.message??"Google Places check failed";i.blank(),x&&H("google-places",R),i.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"google-places",banner:`Google rejected the key:
|
|
62
|
+
${R}
|
|
58
63
|
|
|
59
64
|
Generate (or fix) the key at https://console.cloud.google.com
|
|
60
|
-
and paste it below. Press Enter to keep the current value.`}),await
|
|
65
|
+
and paste it below. Press Enter to keep the current value.`}),await U(n,l)}let C=!1;if(x&&l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAuth!=="oauth-microsoft"){let f=[["email address",l.emailAddress],["password",l.emailPassword],["SMTP host",l.emailSmtpHost],["IMAP host",l.emailImapHost]].filter(([,k])=>!k).map(([k])=>k),y=[["SMTP port",l.emailSmtpPort],["IMAP port",l.emailImapPort]].filter(([,k])=>!k).map(([k])=>k),g=[...f.length>0?[`the ${f.join(", ")} ${f.length===1?"is":"are"} missing`]:[],...y.length>0?[`the ${y.join(" and ")} ${y.length===1?"isn't a number":"aren't numbers"}`]:[]];g.length>0&&H("email",`Email outreach is switched on, but ${g.join(", and ")}. Fill ${g.length===1&&f.length+y.length===1?"it":"them"} in, or turn email off.`)}if(l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAddress&&l.emailPassword&&l.emailSmtpHost&&l.emailSmtpPort&&l.emailImapHost&&l.emailImapPort){i.blank();let f=0,y=!1,g;for(;!y;){f++;let k=E.spinner();k.start("Validating email credentials (SMTP + IMAP)");let R=l.emailProvider&&l.emailProvider!=="custom"?l.emailProvider:Pe(l.emailSmtpHost),M=R?Q[R]:void 0,D=await pe({emailAddress:l.emailAddress,emailLogin:l.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:l.emailPassword,emailSmtpHost:l.emailSmtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:l.emailImapHost,emailImapPort:l.emailImapPort,usesAccountPassword:M?.usesAccountPassword,knownProvider:!!M,sentFolder:(l.emailSentFolder??"").trim()||"Sent",draftsFolder:(l.emailDraftsFolder??"").trim()||"Drafts"});if(D.ok){k.stop("Email credentials accepted (SMTP + IMAP)"),await $t(D,l,{nonInteractive:x,onCancel:()=>{E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
61
66
|
|
|
62
|
-
${
|
|
63
|
-
`),process.exit(0)}})&&await
|
|
67
|
+
${fe(n)}
|
|
68
|
+
`),process.exit(0)}})&&await U(n,l);break}k.stop(D.message??"Email check failed",2);let Te=`${R}\0${l.emailAddress}\0${l.emailPassword}`;if(M&&D.failureKind!=="network"&&g!==Te){g=Te;let Ee=ut(R,l.emailSmtpHost,l.emailImapHost),oe,Pn=0;if(Ee.length>0){i.blank(),i.warn(`That server rejected the login. ${M.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let ee of Ee){let zt=E.spinner();zt.start(`Trying ${ee.label} (${ee.smtpHost})`);let Qt=await pe({emailAddress:l.emailAddress,emailLogin:l.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:l.emailPassword,emailSmtpHost:ee.smtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:ee.imapHost,emailImapPort:l.emailImapPort});if(Qt.ok){zt.stop(`${ee.label}: your login works here (${ee.smtpHost})`),oe=ee;break}Qt.failureKind!=="network"&&Pn++,zt.stop(Qt.failureKind==="network"?`${ee.label}: unreachable`:`${ee.label}: rejected too`,2)}}if(oe){if(i.blank(),i.success("Found it \u2014 your password was right all along; the server was the only problem."),x){i.detail(`Non-interactive: using the working ${oe.label} servers automatically.`),l.emailSmtpHost=oe.smtpHost,l.emailImapHost=oe.imapHost,await U(n,l);continue}let ee=await E.confirm({message:`Use the ${oe.label} servers (${oe.smtpHost} / ${oe.imapHost})?`,initialValue:!0});if(E.isCancel(ee)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
64
69
|
|
|
65
|
-
${
|
|
66
|
-
`),process.exit(0)),
|
|
70
|
+
${fe(n)}
|
|
71
|
+
`),process.exit(0)),ee){l.emailSmtpHost=oe.smtpHost,l.emailImapHost=oe.imapHost,await U(n,l);continue}}else Ee.length>0&&(i.blank(),Pn===0?i.warn("Couldn't reach any of the alternate servers \u2014 this looks like a network problem, not a credential problem. Check your connection and retry."):M.noAltWorkedHint&&i.warn(M.noAltWorkedHint))}let Xe=D.message??"Email check failed";i.blank(),i.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),i.detail("You can skip it now and wire it up later from inside the project."),i.blank(),x&&H("email",Xe);let ue=await E.select({message:`What would you like to do? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:f>=3?"skip":f>=2?"edit":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my email details and retry"},{value:"skip",label:"Skip email for now (finish setup; wire email up later)"}]});if(E.isCancel(ue)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
67
72
|
|
|
68
|
-
${
|
|
69
|
-
`),process.exit(0))
|
|
70
|
-
${
|
|
73
|
+
${fe(n)}
|
|
74
|
+
`),process.exit(0)),ue==="skip"){l.outreachChannels=(l.outreachChannels??[]).filter(Ee=>Ee!=="email"),l.outreachPriority=(l.outreachPriority??[]).filter(Ee=>Ee!=="email"),l.outreachChannels.length===0&&(l.outreachEnabled=!1),await U(n,l),C=!0,i.success("Skipped email for now. Setup will continue."),l.outreachEnabled?i.detail("Outreach will use your other channel(s); email stays off until it's fixed."):i.detail("Automated outreach is off until email is fixed \u2014 everything else works."),y=!0;break}ue==="edit"&&(i.blank(),l=await F(l,{onlySection:"email",banner:`${D.failedAt==="imap"?"IMAP":"SMTP"} check failed:
|
|
75
|
+
${Xe}
|
|
71
76
|
|
|
72
77
|
Re-enter the email address, app password, or server details below.
|
|
73
78
|
Press Enter on any field to keep its current value.
|
|
74
79
|
|
|
75
80
|
Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
|
|
76
|
-
at the "Server settings" question.`}),await
|
|
77
|
-
${
|
|
81
|
+
at the "Server settings" question.`}),await U(n,l))}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="twilio"&&l.twilioAccountSid&&l.twilioAuthToken){i.blank();for(let f=1;;f++){let y=E.spinner();y.start("Validating Twilio credentials");let g=await ws({accountSid:l.twilioAccountSid,authToken:l.twilioAuthToken});if(g.ok){y.stop(g.friendlyName?`Twilio credentials accepted (${g.friendlyName})`:"Twilio credentials accepted");break}y.stop(g.message??"Twilio check failed",2),f>=$&&re(n,"Twilio",g.message??"Twilio check failed");let k=g.message??"Twilio check failed";i.blank(),x&&H("sms",k),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"sms",banner:`Twilio rejected the credentials:
|
|
82
|
+
${k}
|
|
78
83
|
|
|
79
84
|
Re-enter the Account SID or Auth Token below.
|
|
80
|
-
Press Enter on any field to keep its current value.`}),await
|
|
81
|
-
${
|
|
85
|
+
Press Enter on any field to keep its current value.`}),await U(n,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("letter")&&l.letterProvider){i.blank();for(let f=1;;f++){let y=E.spinner();y.start("Validating letter provider credentials");let g=await Mt({provider:l.letterProvider,pingenClientId:l.pingenClientId,pingenClientSecret:l.pingenClientSecret,pingenOrgId:l.pingenOrgId,postgridApiKey:l.postgridApiKey});if(g.ok){y.stop(g.friendlyName?`Letter provider credentials accepted (${g.friendlyName})`:"Letter provider credentials accepted");break}y.stop(g.message??"Letter provider check failed",2),f>=$&&re(n,"Letter provider",g.message??"Letter provider check failed");let k=g.message??"Letter provider check failed";i.blank(),x&&H("letter",k),i.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"letter",banner:`The letter provider rejected the credentials:
|
|
86
|
+
${k}
|
|
82
87
|
|
|
83
88
|
Re-enter them below.
|
|
84
|
-
Press Enter on any field to keep its current value.`}),await
|
|
89
|
+
Press Enter on any field to keep its current value.`}),await U(n,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="imessage"&&l.testPhone){i.blank();for(let f=1;;f++){let y=E.spinner();y.start("Validating iMessage setup (sending a test ping)");let g=await ks({testPhone:l.testPhone});if(g.ok){if(y.stop("iMessage dispatched (check your phone for the test ping)"),x){console.error("NOTE: iMessage dispatch succeeded but DELIVERY is unverified in non-interactive mode. Check the test message arrived on your phone; if not, open Messages on this Mac, confirm it's signed in with your Apple ID, and enable Settings \u2192 Messages \u2192 Text Message Forwarding on your iPhone.");break}let R=await E.confirm({message:"Did the test message actually arrive on your phone?",initialValue:!0});if(E.isCancel(R)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
85
90
|
|
|
86
|
-
${
|
|
87
|
-
`),process.exit(0)),
|
|
91
|
+
${fe(n)}
|
|
92
|
+
`),process.exit(0)),R)break;y.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),f>=$&&re(n,"iMessage","Test message dispatched but never delivered"),i.blank(),i.warn("Messages accepted the send but it didn't arrive. Usual fixes: make sure TEST_PHONE is in international format (+44\u2026 not 07\u2026); open Messages on this Mac and confirm it's signed in with your Apple ID; and on your iPhone enable Settings \u2192 Messages \u2192 Text Message Forwarding for this Mac. Fix, then retry."),i.blank(),l=await F(l,{onlySection:"sms",banner:`The test message was dispatched but never arrived on your phone.
|
|
88
93
|
Re-check the number below (international format with a leading +).
|
|
89
|
-
Press Enter on any field to keep its current value.`}),await
|
|
90
|
-
${
|
|
94
|
+
Press Enter on any field to keep its current value.`}),await U(n,l);continue}y.stop(g.message??"iMessage check failed",2),f>=$&&re(n,"iMessage",g.message??"iMessage check failed");let k=g.message??"iMessage check failed";i.blank(),x&&H("sms",k),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${f+1} of ${$})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),l=await F(l,{onlySection:"sms",banner:`iMessage check failed:
|
|
95
|
+
${k}
|
|
91
96
|
|
|
92
97
|
Either fix the underlying issue (sign in to Messages.app, configure
|
|
93
98
|
Text Message Forwarding) and press Enter through, or change SMS
|
|
94
|
-
provider to Twilio.`}),await
|
|
99
|
+
provider to Twilio.`}),await U(n,l)}}if((l.notifyChannel??"telegram")==="telegram"&&l.telegramBotToken&&l.telegramChatId){i.blank();let f=0,y=!1;for(;!y;){f++;let g=E.spinner();g.start("Validating Telegram bot + chat (sending a test ping)");let k=await bn({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(k.ok){g.stop(k.botHandle?`Telegram bot ${k.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),y=!0;break}g.stop(k.message??"Telegram check failed",2);let R=k.message??"Telegram check failed";i.blank(),i.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),i.blank(),x&&H("notifications",R);let M=await E.select({message:`What would you like to do? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:f>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(E.isCancel(M)&&(E.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
95
100
|
|
|
96
|
-
${
|
|
97
|
-
`),process.exit(0)),
|
|
98
|
-
${
|
|
101
|
+
${fe(n)}
|
|
102
|
+
`),process.exit(0)),M==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await U(n,l),i.success("Skipped Telegram. Setup will continue."),i.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),y=!0;break}if(M==="edit"&&(i.blank(),l=await F(l,{onlySection:"notifications",banner:`Telegram check failed:
|
|
103
|
+
${R}
|
|
99
104
|
|
|
100
105
|
Re-enter the bot token or chat_id below.
|
|
101
|
-
Press Enter on any field to keep its current value.`}),await
|
|
106
|
+
Press Enter on any field to keep its current value.`}),await U(n,l),(l.notifyChannel??"telegram")!=="telegram"||!l.telegramBotToken||!l.telegramChatId)){i.success("Skipped Telegram. Setup will continue."),y=!0;break}}}if(i.blank(),r)i.detail("Picking up the setup that didn't finish in this folder \u2014 your files are already here.");else{let f=E.spinner();f.start("Downloading Klaudius template");let y;try{y=(await Ct({licenseKey:u,machineId:st(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:n})).filesExtracted,f.stop(`Downloaded ${y} files into ${h.bold(n)}`)}catch(k){f.stop(k.message,2);let R=l.aiAgent==="codex"?".codex/config.toml":".mcp.json";i.detail(`Your .env / ${R} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await Bt(j(n,"clients"),{recursive:!0});let g=await Jn(n);x&&(await Bt(j(n,tt),{recursive:!0}),await it(an(n),`${new Date().toISOString()}
|
|
107
|
+
`,"utf-8")),await nt(n,zn(Rs,g)),i.success("Wrote .klaudius/manifest.json");try{await xt(n,n,Object.keys(g))}catch{}}let G=!1,me="",ne="";if(e.skipSchema)i.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),i.detail(`Apply manually later via the SQL editor: ${l.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+l.supabaseProjectRef+"/sql/new").replace(l.supabaseProjectRef+".supabase.co","")}`);else{i.blank();let f=E.spinner();f.start("Applying schema to Supabase");let y=await vt({projectRoot:n,pat:l.supabasePat,projectRef:l.supabaseProjectRef});y.ok?f.stop("Schema applied (or already present)"):(f.stop(y.message??"Schema apply failed",2),G=!0,me=y.message?.trim()||"the database refused the request",ne=`https://supabase.com/dashboard/project/${l.supabaseProjectRef}/sql/new`)}let b=[],ie={};if(e.skipInstall)i.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{i.blank(),i.heading("Installing dependencies");let f=await Ft(n);if(i.detail(`npm: ${f.npm}, pip: ${f.pip}, playwright: ${f.playwright}, patchright: ${f.patchright}`),f.npm==="failed"&&b.push("npm"),f.pip==="failed"&&b.push("pip"),f.playwright==="failed"&&b.push("playwright"),f.patchright==="failed"&&b.push("patchright"),ie=f.hints??{},f.npm!=="failed"&&f.playwright!=="failed"){i.step("Checking the QA screenshot chain (serving a test page and screenshotting it)\u2026");let y=await jt(n);y.ok?i.success("QA screenshot chain verified (local page served and screenshotted)."):(i.warn(`QA screenshot chain check failed${y.stage?` (${y.stage})`:""}: ${y.detail??"unknown"}`),y.remediation&&i.detail(y.remediation))}}let B=l.outreachEnabled&&l.outreachPriority?.includes("whatsapp")&&(l.whatsappAccounts?.length??0)>0,_e=!e.skipInstall&&!b.includes("npm"),Qe=(l.whatsappAccounts??[]).filter(f=>!(r&&or(f)));if(B&&_e&&Qe.length>0){i.blank(),i.heading("Linking WhatsApp accounts"),console.log(h.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
|
|
102
108
|
phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
|
|
103
|
-
Link a Device, and point it at the QR shown in this terminal.`)),i.blank();for(let
|
|
109
|
+
Link a Device, and point it at the QR shown in this terminal.`)),i.blank();for(let f of Qe){console.log(h.cyan(`Pairing WhatsApp account '${f}'...`)),console.log(h.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${f})`));let y=dn(process.execPath,["scripts/whatsapp.mjs","pair","--account",f],{cwd:n,stdio:"inherit"});y.status===0?i.detail(`Paired '${f}'.`):(console.log(h.yellow(`'${f}' did not pair (exit ${y.status??"signalled"}). You can finish later via:`)),console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${f}`))),i.blank()}}else if(B&&!_e){i.blank(),console.log(h.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let f of l.whatsappAccounts)console.log(h.cyan(` npx klaudius@latest pair-whatsapp --label ${f}`))}let w=l.emailAuth==="oauth-microsoft"&&l.outreachEnabled&&l.outreachChannels?.includes("email"),v=!e.skipInstall&&!b.includes("pip"),L=(l.emailAddress??"").trim().toLowerCase(),se=await xs(n),_=await Ve(ln(n),"utf-8").then(f=>JSON.parse(f)).catch(()=>null),K=String(_?.entered??"").trim().toLowerCase(),de=String(_?.token??"").trim().toLowerCase(),Je=r&&(se!==""&&(se===L||K!==""&&K===L&&de===se))&&await Vt(j(n,".ms-token.json")),An=f=>{console.log(h.dim("Connect it any time from the project folder with:")),console.log(h.cyan(` ${f?f.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(h.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(w&&Je)i.blank(),i.detail("Your Outlook mailbox is already connected \u2014 leaving that sign-in alone.");else if(w&&v){i.blank(),i.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(h.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
|
|
104
110
|
password. Your browser will open to Microsoft's sign-in page \u2014
|
|
105
|
-
sign in as `+(
|
|
111
|
+
sign in as `+(l.emailAddress??"your outreach mailbox")+` and approve.
|
|
106
112
|
(No browser on this machine? It falls back to a short code you can
|
|
107
|
-
enter from any device.)`)),i.blank();let
|
|
108
|
-
`:"",y=d.aiAgent==="codex"?"codex":"claude",h=d.aiAgent==="codex"?"Codex":"Claude Code",A=d.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";v.length>0&&(console.log(m.dim(`Easiest fix \u2014 let ${h} finish it for you:`)),i.blank(),p&&process.stdout.write(p),console.log(` ${m.cyan(y)} ${m.dim(`# open ${h} in this folder`)}`),console.log(m.dim(" Then paste:")),console.log(m.cyan(` "Finish my Klaudius install \u2014 ${v.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(m.dim(` (Don't have ${h} yet? Install with: \`${A}\`)`)),i.blank(),console.log(m.dim("Or do it yourself:")),i.blank(),p&&process.stdout.write(p),console.log(` ${m.cyan("npx klaudius@latest install")} ${m.dim("# retry the failing installers")}`),console.log(` ${m.cyan("npx klaudius@latest doctor")} ${m.dim("# verify everything")}`),i.blank()),Y&&(console.log(m.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${m.cyan(le)}`),console.log(m.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),v.includes("pip")&&!_.pip&&(console.log(m.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(m.dim(`Python 3.10+. Install a newer one from ${zo()}`)),console.log(m.dim("and open a fresh Terminal before retrying.")),i.blank());let C=["npm","playwright","patchright"].filter(M=>v.includes(M)&&!_[M]);if(C.length>0){let M=C.length===1?"keeps":"keep";console.log(m.dim(`If ${C.join(" / ")} ${M} failing with network errors (ECONNRESET,`)),console.log(m.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(m.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}g&&(console.log(m.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${h}`)),console.log(m.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(m.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Qo(d,n,e.target),g){let p=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(m.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(m.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(m.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(m.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(m.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(m.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(m.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(i.blank(),console.log(m.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 D(e,t){await Yt(e,{recursive:!0}),await Vt(Z(e,".env"),lt(t),"utf-8"),t.aiAgent==="codex"?(await Yt(Z(e,".codex"),{recursive:!0}),await Vt(Z(e,".codex","config.toml"),dt(t),"utf-8")):(await Vt(Z(e,".mcp.json"),ct(t),"utf-8"),await Rt(e,"supabase"),await Me(e,De))}async function Bo(e){try{(await qt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await hs(e),n=t.filter(l=>!l.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(l=>s.has(l)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:Z(e,".env")};if(a&&r){let l=!0;try{l=!(await qt(Z(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Vo(e){i.blank(),i.warn(`Found a partial setup at ${m.bold(e)}.`),i.detail(`A previous init wrote ${m.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await P.select({message:`How would you like to proceed? ${m.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 Yo(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 Wo(e){let t=jo(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 qo(){if(process.platform!=="win32")return!1;try{return zt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function zo(){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 Qo(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(m.green(m.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ee(e.aiPlan))==="off";console.log(`${m.bold("Your plan:")} ${Pe[e.aiPlan]}`),console.log(m.dim(r?` \u2192 QA pass off${Ae.has(e.aiPlan)&&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(m.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(m.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let r=`cd ${vt(n)}`;console.log(` ${m.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${m.dim("# go into your project folder")}`)}console.log(` ${m.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${m.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(m.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${m.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${m.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${m.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${m.cyan('"Run the pipeline for one client."')}`),console.log(m.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(m.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(m.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as Jo,readFile as Xo}from"fs/promises";import{join as Qt,resolve as Zo}from"path";import W from"picocolors";async function ys(e){let t=e.target?Zo(process.cwd(),e.target):process.cwd(),n=await gs(Qt(t,".env")),s=await gs(Qt(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{G(await Xo(Qt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await _t(t);i.blank(),i.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let a=[];if(r.npm==="failed"&&a.push("npm"),r.pip==="failed"&&a.push("pip"),r.playwright==="failed"&&a.push("playwright"),r.patchright==="failed"&&a.push("patchright"),a.length===0){i.blank(),console.log(W.green(W.bold("All dependencies installed."))),console.log(W.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(W.yellow(W.bold(`${a.join(", ")} still failing.`))),i.blank();for(let[u,E]of Object.entries(r.hints??{}))console.log(W.yellow(`Likely cause of ${u} failure:`)),console.log(W.dim(` ${E}`)),i.blank();let l=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",f=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(W.dim("Options:")),console.log(W.dim(` \u2022 Open ${c} in this folder (\`${l}\`) and paste:`)),console.log(W.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(W.dim(` (Don't have ${c} yet? Install with: \`${f}\`)`)),console.log(W.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(W.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function gs(e){try{return await Jo(e),!0}catch{return!1}}import{readFile as er,writeFile as Jt,access as tr}from"fs/promises";import{join as Ue}from"path";import*as q from"@clack/prompts";import ae from"picocolors";import{mkdir as nr}from"fs/promises";import{spawnSync as ks}from"child_process";async function ws(e){let t=e.projectRoot??process.cwd(),n=Ue(t,".env"),s=Ue(t,".mcp.json"),o=Ue(t,".codex","config.toml"),r=await Xt(Ue(t,".klaudius","manifest.json")),a=await Xt(n);!r&&!a&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let l=ue();l.ok||(i.error(l.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let c={};try{let g=await er(n,"utf-8");c=G(g)}catch{i.warn("No .env found. Starting from an empty configuration.")}let f=Tn(c);Object.keys(c).length>0&&(f.pipelineModes??=["classic"]),q.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await N(f),E=f.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==E&&(i.error(`Switching AI coding agent (${E} \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(` ${ae.cyan("npx klaudius@latest init <new-folder>")} ${ae.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let g=await xe({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});g.ok||(i.error(g.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let d=ir(u,c);if(d==="vercel"){let g=q.spinner();g.start("Validating Vercel token");let k=await Re(u.vercelToken??"");k.ok?g.stop(k.username?`Vercel token accepted (signed in as ${k.username})`:"Vercel token accepted"):(g.stop(k.message,2),i.warn("Writing the token exactly as you entered it \u2014 not verified."),i.detail(k.kind==="rejected"||k.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then re-run `npx klaudius@latest configure`.":k.kind==="network"?"Couldn't reach Vercel \u2014 check your connection, then run `npx klaudius@latest doctor`.":"Vercel's API returned an error \u2014 try again shortly (status.vercel.com), then run `npx klaudius@latest doctor`."))}else if(d==="cloudflare"){let g=q.spinner();g.start("Validating Cloudflare token + account");let k=await ve({token:u.cloudflareApiToken??"",accountId:u.cloudflareAccountId??""});k.ok?g.stop("Cloudflare credentials accepted"):(g.stop(k.message??"Cloudflare check failed",2),i.warn("Writing the credentials exactly as you entered them \u2014 not verified."),i.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(d==="netlify"){let g=q.spinner();g.start("Validating Netlify token");let k=await Oe({token:u.netlifyAuthToken??""});k.ok?g.stop(k.accountSlug?`Netlify token accepted (team: ${k.accountSlug})`:"Netlify token accepted"):(g.stop(k.message??"Netlify check failed",2),i.warn("Writing the token exactly as you entered it \u2014 not verified."),i.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let b=de(u.googlePlacesApiKey??"");if(b.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let g=await Le(u.googlePlacesApiKey);if(g.ok){if(b.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let k of b.repairs)i.detail(` ${k}`);i.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=b.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(g.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(sr(u,c)){let g=q.spinner();g.start("Validating email credentials (SMTP + IMAP)");let k=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:we(u.emailSmtpHost),S=await oe({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:k?X[k].usesAccountPassword:void 0,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});S.ok?(g.stop("Email credentials accepted (SMTP + IMAP)"),await Pt(S,u,{nonInteractive:!1,onCancel:()=>i.detail("Left the folder names as they are.")})):(g.stop(S.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(S.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,lt(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await nr(Ue(t,".codex"),{recursive:!0}),await Jt(o,dt(u),"utf-8"),i.success("Updated .codex/config.toml")):(await Jt(s,ct(u),"utf-8"),i.success("Updated .mcp.json"),await Rt(t,"supabase"),await Me(t,De)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let g=await K();if(!(g!==null&&ks(g.command[0],[...g.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!g)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 S=await q.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});q.isCancel(S)||!S?i.detail(`Skipped. Connect it any time with: ${g.command.join(" ")} scripts/ms_oauth.py login`):ks(g.command[0],[...g.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: ${g.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),q.outro(ae.green("Configuration updated.")),await or(t,r)}function sr(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"]];if(n.some(([o])=>o===void 0||o===""))return!1;let s=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([o,r])=>String(o)!==(t[r]??""))||s.some(([o,r])=>o!==void 0&&o!==(t[r]??""))}function ir(e,t){let n=(s,o)=>(s??"")!==(t[o]??"");switch(e.deployProvider??"vercel"){case"vercel":return e.vercelToken&&n(e.vercelToken,"VERCEL_TOKEN")?"vercel":null;case"cloudflare":return e.cloudflareApiToken&&e.cloudflareAccountId&&(n(e.cloudflareApiToken,"CLOUDFLARE_API_TOKEN")||n(e.cloudflareAccountId,"CLOUDFLARE_ACCOUNT_ID"))?"cloudflare":null;case"netlify":return e.netlifyAuthToken&&n(e.netlifyAuthToken,"NETLIFY_AUTH_TOKEN")?"netlify":null;default:return null}}async function or(e,t){let n=await Xt(Ue(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(` ${ae.cyan("npx klaudius@latest install")} ${ae.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest doctor")} ${ae.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(` ${ae.cyan("npx klaudius@latest init")} ${ae.dim("# pick Resume when prompted")}`),i.blank())}async function Xt(e){try{return await tr(e),!0}catch{return!1}}import{copyFile as As,mkdir as Zt,readFile as Ye,rm as fe,writeFile as Ot,access as Es}from"fs/promises";import{dirname as en,join as R}from"path";import{tmpdir as rr}from"os";import*as he from"@clack/prompts";import We from"picocolors";var qe="0.34.0";async function Ss(e){let t=e.projectRoot??process.cwd(),n=await vn(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 pt)delete n.files[w];let s,o=R(t,".env"),r,a;try{r=await Ye(o,"utf-8"),a=G(r)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=a.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let l=e.check?null:_n(r,a,bn);l!==null&&(await Ot(o,l,"utf-8"),i.detail("Backfilled new env keys")),await kt("update",qe),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${qe}`),await Tt();let f=a.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&f==="claude-code"&&await Me(t,De)==="added"&&i.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=R(rr(),`klaudius-update-${process.pid}-${Date.now()}`),E;try{i.heading("Downloading the latest Klaudius template");let w=await mt({licenseKey:s,machineId:Ve(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:f,destDir:u});i.success(`Fetched ${w.filesExtracted} canonical files`),E=u}catch(w){i.error(w.message),i.detail("Update aborted. Your project is unchanged."),await fe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await lr(E,t,n);if(e.check){let w=d.filter(h=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(h.state)),O=d.filter(h=>["conflict","locally-deleted","removed-modified"].includes(h.state)),p="unknown";if(a.SUPABASE_URL&&a.SUPABASE_SERVICE_KEY){let h=await Ye(R(E,"scripts","schema.sql"),"utf-8").catch(()=>""),A=await At({url:a.SUPABASE_URL,serviceKey:a.SUPABASE_SERVICE_KEY,sql:h});A.unreachable?i.detail(`Database schema not checked (${A.unreachable}).`):A.ok?p="current":(p="stale",i.detail(`Database schema is behind (missing: ${A.missing.join(", ")}); update applies scripts/schema.sql.`))}let y=w.length>0||p==="stale";i.blank(),y?(w.length>0&&i.detail(`${z(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(We.yellow("An update is available."))):he.outro(We.green("Already up to date.")),console.log(`[klaudius-update-check] status=${y?"behind":"current"} pending=${w.length+(p==="stale"?1:0)} conflicts=${O.length} schema=${p}`),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}let b=!1,g=d.find(w=>w.path===".gitignore"&&w.state==="conflict");if(g){let w=R(t,".gitignore"),O=await Ye(w,"utf-8"),p=await Ye(R(E,".gitignore"),"utf-8"),{merged:y,added:h}=cr(O,p);h.length>0&&await Ot(w,y,"utf-8"),n.files[".gitignore"]=g.canonicalHash,g.state="gitignore-merged",b=!0,i.detail(h.length>0?`.gitignore auto-merged: kept all your lines, appended ${z(h.length,"new canonical pattern")}: ${h.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let k=d.filter(w=>w.state==="new"),S=d.filter(w=>w.state==="clean-update"),x=d.filter(w=>w.state==="user-only"),Y=d.filter(w=>w.state==="conflict"),le=d.filter(w=>w.state==="no-change"),v=d.filter(w=>w.state==="locally-deleted"),_=d.filter(w=>w.state==="removed-clean"),ce=d.filter(w=>w.state==="removed-modified"),U=[...Y,...v,...ce],ke=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${z(le.length,"file")} unchanged`),i.detail(`${z(k.length,"new file")}`),i.detail(`${z(S.length,"file")} updated cleanly (no local edits)`),i.detail(`${z(x.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${z(_.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${z(Y.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${z(v.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${z(ce.length,"file")} removed upstream but edited locally (need your decision)`),ke>0&&(i.detail(`${z(ke,"file")} kept deleted (previously resolved \u2014 skipped)`),ke<=10))for(let w of n.ignored)i.detail(` kept deleted: ${w}`);let Ke=async()=>{let w=!1,O=p=>fe(p,{recursive:!0,force:!0}).catch(()=>{w=!0});await O(R(t,".klaudius","incoming")),await O(R(t,gt)),await O(R(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(k.length===0&&S.length===0&&_.length===0&&U.length===0&&!b){await Ps(t,a,!1),await Ke(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=qe,await Be(t,n)),i.blank(),he.outro(We.green("Already up to date.")),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let w of[...k,...S]){let O=R(E,w.path),p=R(t,w.path);await Zt(en(p),{recursive:!0}),await As(O,p),n.files[w.path]=w.canonicalHash}k.length+S.length>0&&i.success(`Wrote ${z(k.length+S.length,"file")}`),[...k,...S].some(w=>w.path==="package.json"||w.path==="package-lock.json")&&i.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let w of _){let O=R(t,w.path);await fe(O,{force:!0}),delete n.files[w.path]}if(_.length>0&&i.success(`Deleted ${z(_.length,"file")} removed upstream`),await Ps(t,a,U.some(w=>w.path==="scripts/schema.sql")),U.length>0){i.blank(),i.heading(`${U.length} conflict(s) need resolution`);let w=R(t,".klaudius","incoming");try{await fe(w,{recursive:!0,force:!0})}catch{}for(let h of[...Y,...v]){let A=R(E,h.path),T=R(w,h.path);await Zt(en(T),{recursive:!0}),await As(A,T)}let O=new Map,p=new Map;for(let h of Y){let A=await jn(t,h.path),T=await Kn(t,h.path),C=await Ye(R(E,h.path),"utf-8"),M=Gn(A,T,C,h.manifestHash);M!==null?(p.set(h.path,M),O.set(h.path,Bn(M,C))):A!==null&&(Ce(A)||Ce(C))?O.set(h.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+h.path+"` directly._"]):A===null?O.set(h.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._"]):O.set(h.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/"+h.path+"` directly._"])}let y=R(t,gt);try{await fe(y,{recursive:!0,force:!0})}catch{}for(let[h,A]of p){let T=R(y,h);await Zt(en(T),{recursive:!0}),await Ot(T,A,"utf-8")}await Ot(R(t,".klaudius","conflicts.md"),dr(U,n.templateVersion,qe,O,p),"utf-8"),Y.length+v.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),p.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=qe,U.length===0?(delete n.pendingConflicts,await Ke()):n.pendingConflicts=U.length,await Be(t,n);try{await yt(t,E,await ge(E))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),U.length===0)he.outro(We.green("Update complete."));else{let w=f==="codex"?"Codex":"Claude Code";he.outro(We.yellow(`${U.length} conflict(s) staged. Open ${w} in this project and ask:
|
|
109
|
-
|
|
113
|
+
enter from any device.)`)),i.blank();let f=await W();if(f){let[y,...g]=f.command,k=dn(y,[...g,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});if(k.status===0){if(i.success("Outlook mailbox connected."),x){let R={entered:(l.emailAddress??"").trim(),token:await xs(n)};await it(ln(n),`${JSON.stringify(R)}
|
|
114
|
+
`,"utf-8").catch(()=>{})}}else i.blank(),console.log(h.yellow(`The Microsoft sign-in didn't complete (exit ${k.status??"signalled"}). Setup continues without it.`)),An(f)}else console.log(h.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),An(null)}else w&&!v&&(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 En=[...b,...G?["schema"]:[]];if(En.length>0){E.outro(h.yellow(h.bold(`Setup paused \u2014 ${En.join(", ")} failed.`))),console.log(h.dim("Your credentials and project files are all saved.")),i.blank();for(let[D,Te]of Object.entries(ie))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${Te}`)),i.blank();let f=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${Yt(e.target)}`)}
|
|
115
|
+
`:"",y=l.aiAgent==="codex"?"codex":"claude",g=l.aiAgent==="codex"?"Codex":"Claude Code",k=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";b.length>0&&(console.log(h.dim(`Easiest fix \u2014 let ${g} finish it for you:`)),i.blank(),f&&process.stdout.write(f),console.log(` ${h.cyan(y)} ${h.dim(`# open ${g} in this folder`)}`),console.log(h.dim(" Then paste:")),console.log(h.cyan(` "Finish my Klaudius install \u2014 ${b.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(h.dim(` (Don't have ${g} yet? Install with: \`${k}\`)`)),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()),G&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(ne)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),b.includes("pip")&&!ie.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 ${fr()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),i.blank());let M=["npm","playwright","patchright"].filter(D=>b.includes(D)&&!ie[D]);if(M.length>0){let D=M.length===1?"keeps":"keep";console.log(h.dim(`If ${M.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()}if(C&&(console.log(h.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${g}`)),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(),x){let D=[];G&&D.push(`Couldn't create the database tables: ${me.replace(/[:.\s]+$/,"")}. Check the database access token on the Database step.`);let Te=b.filter(ue=>ue==="playwright"||ue==="patchright"),Xe=b.filter(ue=>ue!=="playwright"&&ue!=="patchright");Xe.length>0&&D.push(`Couldn't finish installing ${Xe.join(", ")}. The install output says why.`),Te.length>0&&D.push("Couldn't download the browsers Klaudius uses to gather business details, check the sites it builds and make invoices. The install output says why. If your network blocks large downloads, a different network, such as a phone hotspot, often gets past it."),D.push("Then try again \u2014 setup carries on from here. If it keeps failing, email hello@klaudius.dev with the last few lines."),H(G&&b.length===0?"supabase":"install",D.join(`
|
|
116
|
+
`))}return}if(await Cs(an(n),{force:!0}),await Cs(ln(n),{force:!0}),hr(l,n,e.target),C){let f=l.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."')),l.outreachEnabled&&(l.outreachChannels??[]).length>0&&(i.blank(),console.log(h.yellow(`Note: your other channel(s) \u2014 ${(l.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),i.blank()}}async function U(e,t){await Bt(e,{recursive:!0}),await it(j(e,".env"),Et(t),"utf-8"),t.aiAgent==="codex"?(await Bt(j(e,".codex"),{recursive:!0}),await it(j(e,".codex","config.toml"),St(t),"utf-8")):(await it(j(e,".mcp.json"),Pt(t),"utf-8"),await Gt(e,"supabase"),await Be(e,Ge))}async function lr(e){try{(await cn(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Os(e),n=t.filter(d=>!d.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(d=>s.has(d)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:j(e,".env")};if(a&&r){let d=!0;try{d=!(await cn(j(e,"node_modules"))).isDirectory()}catch{d=!0}return{kind:"scaffolded",nodeModulesMissing:d}}return{kind:"occupied",entries:n}}async function cr(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 E.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 E.isCancel(t)&&(E.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function dr(e){if(e&&e.trim().length>0)return e;E.intro("Klaudius");let t=await E.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return E.isCancel(t)&&(E.cancel("Setup cancelled. No files written."),process.exit(0)),t}function ur(e){let t=ir(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 pr(){if(process.platform!=="win32")return!1;try{return dn("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function fr(){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 hr(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(E.outro(h.green(h.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ce(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${Re[e.aiPlan]}`),console.log(h.dim(r?` \u2192 QA pass off${Ie.has(e.aiPlan)&&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 r=`cd ${Yt(n)}`;console.log(` ${h.cyan(r)}${" ".repeat(Math.max(1,27-r.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 mr,readFile as gr}from"fs/promises";import{join as un,resolve as yr}from"path";import J from"picocolors";async function $s(e){let t=e.target?yr(process.cwd(),e.target):process.cwd(),n=await Ns(un(t,".env")),s=await Ns(un(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{V(await gr(un(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await Ft(t);i.blank(),i.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let a=[];if(r.npm==="failed"&&a.push("npm"),r.pip==="failed"&&a.push("pip"),r.playwright==="failed"&&a.push("playwright"),r.patchright==="failed"&&a.push("patchright"),a.length===0){i.blank(),console.log(J.green(J.bold("All dependencies installed."))),console.log(J.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(J.yellow(J.bold(`${a.join(", ")} still failing.`))),i.blank();for(let[u,A]of Object.entries(r.hints??{}))console.log(J.yellow(`Likely cause of ${u} failure:`)),console.log(J.dim(` ${A}`)),i.blank();let d=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",p=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(J.dim("Options:")),console.log(J.dim(` \u2022 Open ${c} in this folder (\`${d}\`) and paste:`)),console.log(J.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(J.dim(` (Don't have ${c} yet? Install with: \`${p}\`)`)),console.log(J.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(J.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function Ns(e){try{return await mr(e),!0}catch{return!1}}import{readFile as wr,writeFile as pn,access as kr}from"fs/promises";import{join as We}from"path";import*as X from"@clack/prompts";import he from"picocolors";import{mkdir as Ar}from"fs/promises";import{spawnSync as Ms}from"child_process";async function Ds(e){let t=e.projectRoot??process.cwd(),n=We(t,".env"),s=We(t,".mcp.json"),o=We(t,".codex","config.toml"),r=await fn(We(t,".klaudius","manifest.json")),a=await fn(n);!r&&!a&&(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 d=ye();d.ok||(i.error(d.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 c={};try{let m=await wr(n,"utf-8");c=V(m)}catch{i.warn("No .env found. Starting from an empty configuration.")}let p=Gn(c);Object.keys(c).length>0&&(p.pipelineModes??=["classic"]),X.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await F(p),A=p.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==A&&(i.error(`Switching AI coding agent (${A} \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(` ${he.cyan("npx klaudius@latest init <new-folder>")} ${he.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let m=await Me({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});m.ok||(i.error(m.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let P=Pr(u,c);if(P==="vercel"){let m=X.spinner();m.start("Validating Vercel token");let l=await De(u.vercelToken??"");l.ok?m.stop(l.username?`Vercel token accepted (signed in as ${l.username})`:"Vercel token accepted"):(m.stop(l.message,2),i.warn("Writing the token exactly as you entered it \u2014 not verified."),i.detail(l.kind==="rejected"||l.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then re-run `npx klaudius@latest configure`.":l.kind==="network"?"Couldn't reach Vercel \u2014 check your connection, then run `npx klaudius@latest doctor`.":"Vercel's API returned an error \u2014 try again shortly (status.vercel.com), then run `npx klaudius@latest doctor`."))}else if(P==="cloudflare"){let m=X.spinner();m.start("Validating Cloudflare token + account");let l=await Fe({token:u.cloudflareApiToken??"",accountId:u.cloudflareAccountId??""});l.ok?m.stop("Cloudflare credentials accepted"):(m.stop(l.message??"Cloudflare check failed",2),i.warn("Writing the credentials exactly as you entered them \u2014 not verified."),i.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(P==="netlify"){let m=X.spinner();m.start("Validating Netlify token");let l=await Ue({token:u.netlifyAuthToken??""});l.ok?m.stop(l.accountSlug?`Netlify token accepted (team: ${l.accountSlug})`:"Netlify token accepted"):(m.stop(l.message??"Netlify check failed",2),i.warn("Writing the token exactly as you entered it \u2014 not verified."),i.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let T=ge(u.googlePlacesApiKey??"");if(T.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let m=await He(u.googlePlacesApiKey);if(m.ok){if(T.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let l of T.repairs)i.detail(` ${l}`);i.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=T.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(m.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(Er(u,c)){let m=X.spinner();m.start("Validating email credentials (SMTP + IMAP)");let l=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:Pe(u.emailSmtpHost),S=await pe({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:l?Q[l].usesAccountPassword:void 0,knownProvider:!!l,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});S.ok?(m.stop("Email credentials accepted (SMTP + IMAP)"),await $t(S,u,{nonInteractive:!1,onCancel:()=>i.detail("Left the folder names as they are.")})):(m.stop(S.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(S.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 pn(n,Et(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await Ar(We(t,".codex"),{recursive:!0}),await pn(o,St(u),"utf-8"),i.success("Updated .codex/config.toml")):(await pn(s,Pt(u),"utf-8"),i.success("Updated .mcp.json"),await Gt(t,"supabase"),await Be(t,Ge)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let m=await W();if(!(m!==null&&Ms(m.command[0],[...m.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!m)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 S=await X.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});X.isCancel(S)||!S?i.detail(`Skipped. Connect it any time with: ${m.command.join(" ")} scripts/ms_oauth.py login`):Ms(m.command[0],[...m.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: ${m.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),X.outro(he.green("Configuration updated.")),await Sr(t,r)}function Er(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"]];if(n.some(([o])=>o===void 0||o===""))return!1;let s=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([o,r])=>String(o)!==(t[r]??""))||s.some(([o,r])=>o!==void 0&&o!==(t[r]??""))}function Pr(e,t){let n=(s,o)=>(s??"")!==(t[o]??"");switch(e.deployProvider??"vercel"){case"vercel":return e.vercelToken&&n(e.vercelToken,"VERCEL_TOKEN")?"vercel":null;case"cloudflare":return e.cloudflareApiToken&&e.cloudflareAccountId&&(n(e.cloudflareApiToken,"CLOUDFLARE_API_TOKEN")||n(e.cloudflareAccountId,"CLOUDFLARE_ACCOUNT_ID"))?"cloudflare":null;case"netlify":return e.netlifyAuthToken&&n(e.netlifyAuthToken,"NETLIFY_AUTH_TOKEN")?"netlify":null;default:return null}}async function Sr(e,t){let n=await fn(We(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(` ${he.cyan("npx klaudius@latest install")} ${he.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${he.cyan("npx klaudius@latest doctor")} ${he.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(` ${he.cyan("npx klaudius@latest init")} ${he.dim("# pick Resume when prompted")}`),i.blank())}async function fn(e){try{return await kr(e),!0}catch{return!1}}import{copyFile as Fs,mkdir as hn,readFile as ot,rm as ke,writeFile as Wt,access as Us}from"fs/promises";import{dirname as mn,join as O}from"path";import{tmpdir as br}from"os";import*as Ae from"@clack/prompts";import rt from"picocolors";var at="0.34.1";async function js(e){let t=e.projectRoot??process.cwd(),n=await qn(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 _t)delete n.files[w];let s,o=O(t,".env"),r,a;try{r=await ot(o,"utf-8"),a=V(r)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=a.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 d=e.check?null:Hn(r,a,Un);d!==null&&(await Wt(o,d,"utf-8"),i.detail("Backfilled new env keys")),await Ot("update",at),Ae.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${at}`),await Ut();let p=a.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&p==="claude-code"&&await Be(t,Ge)==="added"&&i.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=O(br(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{i.heading("Downloading the latest Klaudius template");let w=await Ct({licenseKey:s,machineId:st(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});i.success(`Fetched ${w.filesExtracted} canonical files`),A=u}catch(w){i.error(w.message),i.detail("Update aborted. Your project is unchanged."),await ke(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let P=await Tr(A,t,n);if(e.check){let w=P.filter(_=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(_.state)),v=P.filter(_=>["conflict","locally-deleted","removed-modified"].includes(_.state)),L="unknown";if(a.SUPABASE_URL&&a.SUPABASE_SERVICE_KEY){let _=await ot(O(A,"scripts","schema.sql"),"utf-8").catch(()=>""),K=await Lt({url:a.SUPABASE_URL,serviceKey:a.SUPABASE_SERVICE_KEY,sql:_});K.unreachable?i.detail(`Database schema not checked (${K.unreachable}).`):K.ok?L="current":(L="stale",i.detail(`Database schema is behind (missing: ${K.missing.join(", ")}); update applies scripts/schema.sql.`))}let se=w.length>0||L==="stale";i.blank(),se?(w.length>0&&i.detail(`${Z(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),Ae.outro(rt.yellow("An update is available."))):Ae.outro(rt.green("Already up to date.")),console.log(`[klaudius-update-check] status=${se?"behind":"current"} pending=${w.length+(L==="stale"?1:0)} conflicts=${v.length} schema=${L}`),await ke(u,{recursive:!0,force:!0}).catch(()=>{});return}let T=!1,m=P.find(w=>w.path===".gitignore"&&w.state==="conflict");if(m){let w=O(t,".gitignore"),v=await ot(w,"utf-8"),L=await ot(O(A,".gitignore"),"utf-8"),{merged:se,added:_}=Ir(v,L);_.length>0&&await Wt(w,se,"utf-8"),n.files[".gitignore"]=m.canonicalHash,m.state="gitignore-merged",T=!0,i.detail(_.length>0?`.gitignore auto-merged: kept all your lines, appended ${Z(_.length,"new canonical pattern")}: ${_.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let l=P.filter(w=>w.state==="new"),S=P.filter(w=>w.state==="clean-update"),C=P.filter(w=>w.state==="user-only"),G=P.filter(w=>w.state==="conflict"),me=P.filter(w=>w.state==="no-change"),ne=P.filter(w=>w.state==="locally-deleted"),b=P.filter(w=>w.state==="removed-clean"),ie=P.filter(w=>w.state==="removed-modified"),B=[...G,...ne,...ie],_e=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${Z(me.length,"file")} unchanged`),i.detail(`${Z(l.length,"new file")}`),i.detail(`${Z(S.length,"file")} updated cleanly (no local edits)`),i.detail(`${Z(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${Z(b.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${Z(G.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${Z(ne.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${Z(ie.length,"file")} removed upstream but edited locally (need your decision)`),_e>0&&(i.detail(`${Z(_e,"file")} kept deleted (previously resolved \u2014 skipped)`),_e<=10))for(let w of n.ignored)i.detail(` kept deleted: ${w}`);let Qe=async()=>{let w=!1,v=L=>ke(L,{recursive:!0,force:!0}).catch(()=>{w=!0});await v(O(t,".klaudius","incoming")),await v(O(t,Rt)),await v(O(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(l.length===0&&S.length===0&&b.length===0&&B.length===0&&!T){await Hs(t,a,!1),await Qe(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=at,await nt(t,n)),i.blank(),Ae.outro(rt.green("Already up to date.")),await ke(u,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let w of[...l,...S]){let v=O(A,w.path),L=O(t,w.path);await hn(mn(L),{recursive:!0}),await Fs(v,L),n.files[w.path]=w.canonicalHash}l.length+S.length>0&&i.success(`Wrote ${Z(l.length+S.length,"file")}`),[...l,...S].some(w=>w.path==="package.json"||w.path==="package-lock.json")&&i.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let w of b){let v=O(t,w.path);await ke(v,{force:!0}),delete n.files[w.path]}if(b.length>0&&i.success(`Deleted ${Z(b.length,"file")} removed upstream`),await Hs(t,a,B.some(w=>w.path==="scripts/schema.sql")),B.length>0){i.blank(),i.heading(`${B.length} conflict(s) need resolution`);let w=O(t,".klaudius","incoming");try{await ke(w,{recursive:!0,force:!0})}catch{}for(let _ of[...G,...ne]){let K=O(A,_.path),de=O(w,_.path);await hn(mn(de),{recursive:!0}),await Fs(K,de)}let v=new Map,L=new Map;for(let _ of G){let K=await is(t,_.path),de=await os(t,_.path),dt=await ot(O(A,_.path),"utf-8"),Je=rs(K,de,dt,_.manifestHash);Je!==null?(L.set(_.path,Je),v.set(_.path,as(Je,dt))):K!==null&&($e(K)||$e(dt))?v.set(_.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+_.path+"` directly._"]):K===null?v.set(_.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._"]):v.set(_.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/"+_.path+"` directly._"])}let se=O(t,Rt);try{await ke(se,{recursive:!0,force:!0})}catch{}for(let[_,K]of L){let de=O(se,_);await hn(mn(de),{recursive:!0}),await Wt(de,K,"utf-8")}await Wt(O(t,".klaudius","conflicts.md"),Cr(B,n.templateVersion,at,v,L),"utf-8"),G.length+ne.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),L.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=at,B.length===0?(delete n.pendingConflicts,await Qe()):n.pendingConflicts=B.length,await nt(t,n);try{await xt(t,A,await Se(A))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),B.length===0)Ae.outro(rt.green("Update complete."));else{let w=p==="codex"?"Codex":"Claude Code";Ae.outro(rt.yellow(`${B.length} conflict(s) staged. Open ${w} in this project and ask:
|
|
117
|
+
"Run /resolve-conflicts"`))}await ke(u,{recursive:!0,force:!0}).catch(()=>{})}async function Hs(e,t,n){let s=await _r(e,t,n);return console.log(`[klaudius-update] schema=${s}`),s}async function _r(e,t,n){let s=(t.SUPABASE_PAT??"").replace(/\s+/g,""),o=(t.SUPABASE_PROJECT_REF??"").trim();if(!s||!o)return i.detail("Database schema not checked: SUPABASE_PAT / SUPABASE_PROJECT_REF aren't in .env. Run `npx klaudius@latest configure` to add them, or paste scripts/schema.sql into your Supabase SQL editor (safe to re-run)."),"skipped";let r=await vt({projectRoot:e,pat:s,projectRef:o});return r.ok?(i.success(n?"Database schema applied from your current scripts/schema.sql \u2014 resolve its conflict, then run update again to apply the new version":"Database schema up to date"),"applied"):(i.warn(r.message??"Database schema could not be applied"),i.detail(`Paste scripts/schema.sql into the SQL editor to apply it by hand (safe to re-run): ${ps(o)}`),"failed")}async function Tr(e,t,n){let s=await Se(e),o=new Set(s),r=new Set(n.ignored??[]),a=[];for(let d of s){if(r.has(d))continue;let c=await Ne(O(e,d)),p=n.files[d],u=O(t,d),A;try{await Us(u),A=await Ne(u)}catch{let T=p!==void 0&&!Wn.has(d)&&!Tt.has(d)?"locally-deleted":"new";a.push({path:d,state:T,canonicalHash:c,manifestHash:p});continue}let P=Tt.has(d);c===p?A===p||P?a.push({path:d,state:"no-change",canonicalHash:c,localHash:A,manifestHash:p}):a.push({path:d,state:"user-only",canonicalHash:c,localHash:A,manifestHash:p}):A===p||P?a.push({path:d,state:"clean-update",canonicalHash:c,localHash:A,manifestHash:p}):a.push({path:d,state:"conflict",canonicalHash:c,localHash:A,manifestHash:p})}for(let d of Object.keys(n.files)){if(o.has(d))continue;let c=n.files[d],p=O(t,d),u;try{await Us(p),u=await Ne(p)}catch{delete n.files[d];continue}u===c||Tt.has(d)?a.push({path:d,state:"removed-clean",localHash:u,manifestHash:c}):a.push({path:d,state:"removed-modified",localHash:u,manifestHash:c})}return a}function Z(e,t){return`${e} ${t}${e===1?"":"s"}`}function Ir(e,t){let n=e.includes(`\r
|
|
110
118
|
`)?`\r
|
|
111
119
|
`:`
|
|
112
|
-
`,s=e.split(/\r?\n/),o=new Set(s.map(c=>c.trim()).filter(c=>c!=="")),r=[];for(let c of t.split(/\r?\n/)){let
|
|
113
|
-
`)}import{existsSync as
|
|
114
|
-
`)),n.push(await
|
|
120
|
+
`,s=e.split(/\r?\n/),o=new Set(s.map(c=>c.trim()).filter(c=>c!=="")),r=[];for(let c of t.split(/\r?\n/)){let p=c.trim();p===""||p.startsWith("#")||o.has(p)||(r.push(p),o.add(p))}if(r.length===0)return{merged:e,added:r};let a=[...s];for(;a.length>0&&a[a.length-1].trim()==="";)a.pop();a.push("","# Added by `klaudius update` (new canonical ignore patterns)",...r);let d=[...new Set(s.map(c=>c.trim()).filter(c=>c.startsWith("!")))].filter(c=>!r.includes(c));return a.push(...d,""),{merged:a.join(n),added:r}}function Cr(e,t,n,s=new Map,o=new Map){let r=e.filter(u=>u.state==="conflict").length,a=e.filter(u=>u.state==="locally-deleted").length,d=e.filter(u=>u.state==="removed-modified").length,c=[];c.push("# Update Conflicts"),c.push(""),c.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),c.push(`Updating from canonical version **${t}** to **${n}**.`),c.push("");let p=[];r>0&&p.push(`${r} file${r===1?"":"s"} ha${r===1?"s":"ve"} BOTH local edits AND upstream changes`),a>0&&p.push(`${a} file${a===1?"":"s"} you deleted locally ${a===1?"is":"are"} still shipped by the canonical template`),d>0&&p.push(`${d} file${d===1?"":"s"} ${d===1?"was":"were"} removed upstream but edited locally`),c.push(p.join(", and ")+"."),c.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."),c.push(""),c.push("---"),c.push("");for(let u of e){if(c.push(`## ${u.path}`),c.push(""),u.state==="locally-deleted")c.push("**Type:** Deleted locally"),c.push(""),c.push("- You deleted this file after it was installed; the canonical template still ships it."),c.push(`- New canonical version staged at: \`.klaudius/incoming/${u.path}\``),c.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),c.push(`- New canonical hash: \`${(u.canonicalHash??"(none)").slice(0,16)}\``),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Restore \u2014 copy the canonical version back into place"),c.push("2. Keep deleted \u2014 never reinstall this file (recorded in the manifest's ignore list)");else if(u.state==="removed-modified")c.push("**Type:** Removed upstream"),c.push(""),c.push(`- Your local copy: \`${u.path}\``),c.push("- This file no longer exists in the canonical template."),c.push("- You've modified it locally since install."),c.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),c.push(`- Your local hash now: \`${(u.localHash??"(missing)").slice(0,16)}\``),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),c.push("2. Delete \u2014 remove the file from disk and from the manifest");else{c.push("**Type:** Edit conflict"),c.push(""),c.push(`- Your version (with your local edits): \`${u.path}\``),c.push(`- New canonical version: \`.klaudius/incoming/${u.path}\``),o.has(u.path)&&c.push(`- Pre-edit base (3-way merge ancestor): \`.klaudius/conflict-base/${u.path}\``),c.push(`- Hash at last install/update: \`${(u.manifestHash??"(none)").slice(0,16)}\``),c.push(`- Your local hash now: \`${(u.localHash??"(missing)").slice(0,16)}\``),c.push(`- New canonical hash: \`${(u.canonicalHash??"(none)").slice(0,16)}\``);let A=s.get(u.path);A&&A.length>0&&(c.push(""),c.push("**What upstream changed since your base:**"),c.push(""),c.push(...A),c.push(""),c.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._")),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Keep mine \u2014 discard the new canonical changes"),c.push("2. Take canonical \u2014 overwrite my edits with the new version"),c.push("3. Merge \u2014 review both side-by-side and produce a combined version")}c.push(""),c.push("---"),c.push("")}return c.join(`
|
|
121
|
+
`)}import{existsSync as Rr}from"fs";import{access as xr,readFile as qe,stat as Or}from"fs/promises";import{homedir as vr}from"os";import{join as q}from"path";import Y from"picocolors";import{spawn as Ks,spawnSync as Lr}from"child_process";async function Gs(e){let t=e.projectRoot??process.cwd(),n=[];console.log(Y.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
122
|
+
`)),n.push(await Nr());let s=await Ur();s&&n.push(s),n.push(await $r());let o=q(t,".env"),r=q(t,".klaudius","manifest.json"),a=q(t,".mcp.json"),d=q(t,".codex","config.toml"),c=await ae(o),p=await ae(r),u="claude-code";if(c)try{V(await qe(o,"utf-8")).AI_AGENT==="codex"&&(u="codex")}catch{}if(u==="claude-code"){let m=await ae(q(t,"AGENTS.md")),l=!await ae(q(t,".claude"));m&&l&&(u="codex")}n.push({name:".env present",status:c?"ok":"fail",detail:c?o:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."});let A=!1;if(c){let m={};try{m=V(await qe(o,"utf-8"))}catch{}let l=kt(m.AI_PLAN),S=At(m.QA_PHASE)??Ce(l);A=S==="off";let C=l&&Ie.has(l)&&u==="codex"?` \xB7 model pin ${Zt}`:"";n.push({name:"Plan / QA pass",status:l?"ok":"warn",detail:l?`${Re[l]} \xB7 QA pass ${S}${C}`:`plan not set \xB7 QA pass ${S}`,nextAction:l?void 0:"Run `npx klaudius@latest configure` and pick your plan \u2014 on Claude Pro, ChatGPT Plus, or a Standard seat on Claude Team or ChatGPT Business, it turns the QA pass off so each run fits your usage window."})}{let m=0,l="";if(p)try{let S=JSON.parse(await qe(r,"utf-8"));m=typeof S.pendingConflicts=="number"?S.pendingConflicts:0,l=typeof S.templateVersion=="string"?S.templateVersion:""}catch{}n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?m>0?"warn":"ok":"fail",detail:p?m>0?`${l||"version unknown"} \u2014 ${m} conflict${m===1?"":"s"} from the last update still unresolved`:l?`${r} (template ${l})`:r:"missing",nextAction:p?m>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:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."})}if(u==="codex"){let m=await ae(d);n.push({name:".codex/config.toml present",status:m?"ok":"warn",detail:m?d:"missing",nextAction:m?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let m=await ae(a);n.push({name:".mcp.json present",status:m?"ok":"warn",detail:m?a:"missing",nextAction:m?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await Qr(u)),process.platform==="win32"){let m=await Mr(t);m&&n.push(m)}if(n.push(await Dr(t)),n.push(await Fr(t)),n.push(await Hr(t,A)),n.push(await Kr()),n.push(await jr(t)),!c)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 m=await qe(o,"utf-8"),l=V(m);await Gr(l,n,t)}console.log();for(let m of n){let l=m.status==="ok"?Y.green("\u2713"):m.status==="warn"?Y.yellow("\u26A0"):m.status==="skip"?Y.dim("\xB7"):Y.red("\u2717");console.log(` ${l} ${m.name}${m.detail?Y.dim(` \u2014 ${m.detail}`):""}`),m.nextAction&&console.log(` ${Y.dim("\u2192")} ${Y.cyan(m.nextAction)}`)}let P=n.filter(m=>m.status==="fail").length,T=n.filter(m=>m.status==="warn").length;console.log(),P===0&&T===0?console.log(Y.green(Y.bold("Everything checks out. You're good to go."))):P===0?console.log(Y.yellow(Y.bold(`${T} warning${T===1?"":"s"} \u2014 review above.`))):(console.log(Y.red(Y.bold(`${P} failed check${P===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function ae(e){try{return await xr(e),!0}catch{return!1}}async function Nr(){let e=await Le();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 $r(){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 Mr(e){let t=xe([{label:"your Windows user folder",path:vr()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",s=await gn("npm",["config","get","script-shell"],!0),o=s.code===0?s.stdout.trim():void 0;if(Oe(o,Rr))return{name:n,status:"ok",detail:`${t[0].label} contains ${t[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${o}) handles it`};let{detail:r,action:a}=ve(t,"doctor"),d=t.some(c=>c.chars.includes("&"));return{name:n,status:d?"fail":"warn",detail:r,nextAction:a}}async function Dr(e){let t=q(e,"node_modules");if(!await ae(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await Or(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 Fr(e){let t=process.platform==="darwin"?q(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?q(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):q(process.env.HOME??"",".cache","ms-playwright");return await ae(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 Ur(){let e=await on();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 Hr(e,t){if(!await ae(q(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 jt(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 jr(e){let t=q(e,".klaudius","notify-failures.log");try{let n=(await qe(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 Kr(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
|
|
115
123
|
try:
|
|
116
124
|
${e.map(r=>` import ${r}`).join(`
|
|
117
125
|
`)}
|
|
118
126
|
except Exception as e:
|
|
119
127
|
print(str(e))
|
|
120
128
|
sys.exit(1)
|
|
121
|
-
`,n=await
|
|
122
|
-
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function
|
|
123
|
-
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await ne(B(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 Cr(e,t){let n="Database schema up to date",s=(e.SUPABASE_URL??"").trim(),o=(e.SUPABASE_SERVICE_KEY??"").trim();if(!s||!o)return{name:n,status:"skip",detail:"Supabase credentials not set"};let r="";try{r=await He(B(t,"scripts","schema.sql"),"utf-8")}catch{return{name:n,status:"skip",detail:"scripts/schema.sql missing \u2014 run `npx klaudius@latest update`"}}let a=await At({url:s,serviceKey:o,sql:r});return a.unreachable?{name:n,status:"skip",detail:`Could not verify (${a.unreachable}) \u2014 see the Supabase rows above.`}:a.ok?{name:n,status:"ok",detail:"every table and column the pipeline expects is present"}:{name:n,status:"warn",detail:`missing: ${a.missing.join(", ")} \u2014 this database was provisioned before they were added, so the pipeline files ahead of it will fail on them.`,nextAction:"Run `npx klaudius@latest update` \u2014 it re-applies scripts/schema.sql (safe on an existing database). Or paste scripts/schema.sql into your Supabase SQL editor."}}async function xr(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(f=>f.trim().toLowerCase()),s=(e.LETTER_PROVIDER??"").trim().toLowerCase(),o=n.includes("letter");if(!o&&(!s||s==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(o&&s!=="pingen"&&s!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!o)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${s} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let r=await St({provider:s,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!r.ok)return{name:t,status:"fail",detail:r.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let a=`${s} credentials accepted`+(r.friendlyName?` (${r.friendlyName})`:""),l=(e.SUPABASE_ANON_KEY??"").trim();if(!l)return{name:t,status:"warn",detail:a+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let c=pn(l);if(c&&c!=="anon")return{name:t,status:"fail",detail:a+`, but SUPABASE_ANON_KEY holds a '${c}' 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 f=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:l,Authorization:`Bearer ${l}`}});if(f.ok){let u=await f.json();if(Array.isArray(u)&&u.length>0)return{name:t,status:"fail",detail:a+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(s==="postgrid"){let f=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(u=>!(e[u]??"").trim());if(f.length>0)return{name:t,status:"warn",detail:a+`, but PostGrid needs your return address and .env is missing ${f.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:a}}async function Rr(e,t){let n="Email credentials (SMTP + IMAP)",s=Tr(e);if(s==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Ts(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."}:Ir(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 c=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(f=>f.endsWith("_PORT")?!e[f]||!/^\d+$/.test(e[f].trim()):!e[f]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${c.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=at(e),r=o&&o!=="custom"?o:we(e.EMAIL_SMTP_HOST),a={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:r?X[r].usesAccountPassword:void 0,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},l=await oe(a);if(l.ok){if(l.foldersUnverified)return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the mailbox's folder list could not be read, so the Sent and Drafts folder names are unverified`,nextAction:"Re-run doctor; if it persists, check the mailbox's folder names by hand."};let c=Is(l,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await K())?.command.join(" ")});return c?{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but ${c.detail}`,nextAction:c.nextAction}:{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(l.failureKind==="network")return{name:n,status:"fail",detail:l.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(r){let c=Xe(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(j.dim(` (email login rejected \u2014 probing ${X[r].label}'s other regional servers, up to ~10s each\u2026)`));let f=0;for(let E of c){let d=await oe({...a,emailSmtpHost:E.smtpHost,emailImapHost:E.imapHost});if(!d.ok&&d.failureKind!=="network"&&f++,d.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${E.label} (${E.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${E.smtpHost} and EMAIL_IMAP_HOST=${E.imapHost} in .env (or ask your AI agent to).`}}let u=(l.message??"login rejected").split(/\.\s|\n/)[0];return f===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 ${X[r].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:r==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":r==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:l.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}function Is(e,t){let n=[],s=[],o=[];if(e.sentFolderIssue){let{configured:a,detected:l}=e.sentFolderIssue;n.push(`the server has no "${a}" folder \u2014 sent mail isn't being filed, so follow-ups can't see what was sent to whom`),l?s.push(`${t.sentKey}="${l}"`):o.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:a,detected:l}=e.draftsFolderIssue;n.push(`the server has no "${a}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),l?s.push(`${t.draftsKey}="${l}"`):o.push(t.draftsKey)}if(n.length===0)return;let r=[];if(s.length>0&&r.push(`Set ${s.join(" and ")} in .env (or ask your AI agent to).`),o.length>0){let a=t.python||"python3",l=t.account&&t.account!=="primary"?`${a} scripts/gmail.py folders --account ${t.account}`:`${a} scripts/gmail.py folders`;r.push(`Run \`${l}\` to list this mailbox's folder names, then set ${o.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:r.join(" ")}}async function vr(e){let t=[];for(let n of Sn(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()}_SENT_FOLDER`,r=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,a=await oe({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,sentFolder:(e[o]??"").trim()||"Sent",draftsFolder:(e[r]??"").trim()||"Drafts"});if(a.ok){let l=Is(a,{sentKey:o,draftsKey:r,account:n.label,python:(await K())?.command.join(" ")});l?t.push({name:s,status:"warn",detail:`authenticated (${n.smtpHost}), but ${l.detail}`,nextAction:l.nextAction}):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 Or(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 tn(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
|
|
124
|
-
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:s}}function
|
|
125
|
-
`));let r
|
|
129
|
+
`,n=await W();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 gn(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(`
|
|
130
|
+
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function Gr(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let a=await Me({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:a.ok?"ok":"fail",detail:a.ok?"connected":a.message,nextAction:a.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});let s=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(s==="selfhost"){let a=e.SELFHOST_DEPLOY_TARGET??"",d=e.SELFHOST_URL_TEMPLATE??"",c=[],p=pt(a);p&&c.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let u=ft(d);u&&c.push(`SELFHOST_URL_TEMPLATE: ${u}`),t.push({name:"Self-host deploy config",status:c.length===0?"ok":"fail",detail:c.length===0?`target ${a} (SSH reachability tested at first deploy)`:c.join("; "),nextAction:c.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 a=await Fe({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:a.ok?"ok":"fail",detail:a.ok?`valid (${a.projectCount??0} Pages project${a.projectCount===1?"":"s"})`:a.message,nextAction:a.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Cloudflare."});else if(s==="netlify")if(e.NETLIFY_AUTH_TOKEN){let a=await Ue({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:a.ok?"ok":"fail",detail:a.ok?a.accountSlug?`valid (team: ${a.accountSlug})`:"valid":a.message,nextAction:a.ok?void 0:"Fix the token at https://app.netlify.com/user/applications#personal-access-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Netlify token",status:"fail",detail:"NETLIFY_AUTH_TOKEN missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Netlify."});else if(e.VERCEL_TOKEN){let a=await De(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:a.ok?"ok":"fail",detail:a.ok?a.username??"valid":a.message,nextAction:a.ok?void 0:a.kind==="rejected"||a.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then `npx klaudius@latest configure`.":a.kind==="network"?"Couldn't reach Vercel \u2014 check your connection, then re-run `npx klaudius@latest doctor`.":"Vercel's API returned an error \u2014 try again shortly (status.vercel.com), then re-run `npx klaudius@latest doctor`."})}else t.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let a=await He(e.GOOGLE_PLACES_API_KEY),d=ge(e.GOOGLE_PLACES_API_KEY);a.ok&&d.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 "+(d.repairs.length>0?`it contains look-alike characters (${d.repairs.join("; ")}). `:"it contains invisible or stray characters. ")+"The pipeline's scripts read .env directly and will fail on it.",nextAction:"Run `npx klaudius@latest configure` and press Enter through the prompts \u2014 it rewrites .env with the corrected key."}):t.push({name:"Google Places API key",status:a.ok?"ok":"fail",detail:a.ok?"accepted":a.message,nextAction:a.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius@latest configure`."})}else t.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});t.push(await qr(e,n)),t.push(...await zr(e)),t.push(await Yr(e,n)),t.push(await Wr(e));let o=(e.NOTIFY_CHANNEL??"").toLowerCase(),r=o==="email"||o==="sms"||o==="none"||o==="off"?o:"telegram";if(r==="none"||r==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(r==="email"){let a=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:a&&e.EMAIL_ADDRESS?"ok":"fail",detail:a&&e.EMAIL_ADDRESS?`alerts go to ${a}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:a&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(r==="sms"){let a=e.NOTIFY_TO||e.TEST_PHONE,d=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:a&&d?"ok":"fail",detail:a&&d?`alerts go to ${a} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:a?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:a&&d?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let a=await Sn({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:a.ok?"ok":"fail",detail:a.ok?`bot ${a.botHandle??"ok"} (chat_id not tested)`:a.message,nextAction:a.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?t.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):t.push({name:"Notifications",status:"skip",detail:"not configured (optional)"})}function Br(e){let t=r=>!!r&&/^\d+$/.test(r.trim()),n=Bs(e)?!!e.EMAIL_ADDRESS:!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),s=(e.OUTREACH_CHANNELS??"").split(",").map(r=>r.trim()),o=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&s.includes("email");return o&&n?"active":o?"incomplete":n?"parked":"unconfigured"}function Bs(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function Vr(e){let t="Email account (Microsoft sign-in)",n=await W(),o=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[a,...d]=n.command,c=Lr(a,[...d,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),p=`${c.stdout??""}${c.stderr??""}`.trim();if(c.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(`
|
|
131
|
+
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await ae(q(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 Yr(e,t){let n="Database schema up to date",s=(e.SUPABASE_URL??"").trim(),o=(e.SUPABASE_SERVICE_KEY??"").trim();if(!s||!o)return{name:n,status:"skip",detail:"Supabase credentials not set"};let r="";try{r=await qe(q(t,"scripts","schema.sql"),"utf-8")}catch{return{name:n,status:"skip",detail:"scripts/schema.sql missing \u2014 run `npx klaudius@latest update`"}}let a=await Lt({url:s,serviceKey:o,sql:r});return a.unreachable?{name:n,status:"skip",detail:`Could not verify (${a.unreachable}) \u2014 see the Supabase rows above.`}:a.ok?{name:n,status:"ok",detail:"every table and column the pipeline expects is present"}:{name:n,status:"warn",detail:`missing: ${a.missing.join(", ")} \u2014 this database was provisioned before they were added, so the pipeline files ahead of it will fail on them.`,nextAction:"Run `npx klaudius@latest update` \u2014 it re-applies scripts/schema.sql (safe on an existing database). Or paste scripts/schema.sql into your Supabase SQL editor."}}async function Wr(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 r=await Mt({provider:s,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!r.ok)return{name:t,status:"fail",detail:r.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let a=`${s} credentials accepted`+(r.friendlyName?` (${r.friendlyName})`:""),d=(e.SUPABASE_ANON_KEY??"").trim();if(!d)return{name:t,status:"warn",detail:a+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let c=Cn(d);if(c&&c!=="anon")return{name:t,status:"fail",detail:a+`, but SUPABASE_ANON_KEY holds a '${c}' 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:d,Authorization:`Bearer ${d}`}});if(p.ok){let u=await p.json();if(Array.isArray(u)&&u.length>0)return{name:t,status:"fail",detail:a+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(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:a+`, but PostGrid needs your return address and .env is missing ${p.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:a}}async function qr(e,t){let n="Email credentials (SMTP + IMAP)",s=Br(e);if(s==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Bs(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."}:Vr(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 c=["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 ${c.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=et(e),r=o&&o!=="custom"?o:Pe(e.EMAIL_SMTP_HOST),a={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:r?Q[r].usesAccountPassword:void 0,knownProvider:!!r,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},d=await pe(a);if(d.ok){if(d.foldersUnverified)return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the mailbox's folder list could not be read, so the Sent and Drafts folder names are unverified`,nextAction:"Re-run doctor; if it persists, check the mailbox's folder names by hand."};let c=Vs(d,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await W())?.command.join(" ")});return c?{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but ${c.detail}`,nextAction:c.nextAction}:{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(d.failureKind==="network")return{name:n,status:"fail",detail:d.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(r){let c=ut(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(Y.dim(` (email login rejected \u2014 probing ${Q[r].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let A of c){let P=await pe({...a,emailSmtpHost:A.smtpHost,emailImapHost:A.imapHost});if(!P.ok&&P.failureKind!=="network"&&p++,P.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${A.label} (${A.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${A.smtpHost} and EMAIL_IMAP_HOST=${A.imapHost} in .env (or ask your AI agent to).`}}let u=(d.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 ${Q[r].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:r==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":r==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:d.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}function Vs(e,t){let n=[],s=[],o=[];if(e.sentFolderIssue){let{configured:a,detected:d}=e.sentFolderIssue;n.push(`the server has no "${a}" folder \u2014 sent mail isn't being filed, so follow-ups can't see what was sent to whom`),d?s.push(`${t.sentKey}="${d}"`):o.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:a,detected:d}=e.draftsFolderIssue;n.push(`the server has no "${a}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),d?s.push(`${t.draftsKey}="${d}"`):o.push(t.draftsKey)}if(n.length===0)return;let r=[];if(s.length>0&&r.push(`Set ${s.join(" and ")} in .env (or ask your AI agent to).`),o.length>0){let a=t.python||"python3",d=t.account&&t.account!=="primary"?`${a} scripts/gmail.py folders --account ${t.account}`:`${a} scripts/gmail.py folders`;r.push(`Run \`${d}\` to list this mailbox's folder names, then set ${o.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:r.join(" ")}}async function zr(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()}_SENT_FOLDER`,r=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,a=Pe(n.smtpHost),d=await pe({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,usesAccountPassword:a?Q[a].usesAccountPassword:void 0,knownProvider:!!a,sentFolder:(e[o]??"").trim()||"Sent",draftsFolder:(e[r]??"").trim()||"Drafts"});if(d.ok){let c=Vs(d,{sentKey:o,draftsKey:r,account:n.label,python:(await W())?.command.join(" ")});c?t.push({name:s,status:"warn",detail:`authenticated (${n.smtpHost}), but ${c.detail}`,nextAction:c.nextAction}):t.push({name:s,status:"ok",detail:`authenticated (${n.smtpHost})`})}else t.push({name:s,status:"fail",detail:d.message,nextAction:d.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 Qr(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 gn(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
|
|
132
|
+
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:s}}function gn(e,t,n=!1){return new Promise(s=>{let o=n?Ks([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Ks(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",d=>{r+=d.toString()}),o.stderr?.on("data",d=>{a+=d.toString()}),o.on("close",d=>s({code:d??1,stdout:r,stderr:a})),o.on("error",()=>s({code:1,stdout:r,stderr:a}))})}import{existsSync as Jr}from"fs";import{spawnSync as Xr}from"child_process";import{join as Zr,resolve as ea}from"path";import z from"picocolors";async function Ys(e){let t=ea(e.projectRoot??process.cwd()),n=Zr(t,"scripts","whatsapp.mjs");Jr(n)||(console.error(z.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(z.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(z.dim(`Looked for: ${n}`)),process.exit(1));let s=(e.label??"primary").trim(),o=s.replace(/[^A-Za-z0-9_-]/g,"");o||(console.error(z.red(`Invalid label '${s}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),o!==s&&console.error(z.yellow(`Note: cleaned label '${s}' \u2192 '${o}' (filename-safe characters only).`)),console.log(z.cyan(`Pairing WhatsApp account '${o}'...`)),console.log(z.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.
|
|
133
|
+
`));let r=Xr(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(z.green(`Paired '${o}'.`)),console.log(z.dim(`
|
|
126
134
|
If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
127
135
|
WHATSAPP_ACCOUNTS=primary,${o}
|
|
128
|
-
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(
|
|
136
|
+
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(z.red(`Pair failed: ${r.error.message}`)):(console.error(z.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(z.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(z.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(z.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as ze,spawn as ta}from"child_process";import{existsSync as lt,mkdirSync as na,readdirSync as sa,rmSync as Qs,mkdtempSync as Js}from"fs";import{homedir as yn,tmpdir as Xs}from"os";import{join as te}from"path";import le from"picocolors";var ia=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function Ws(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Zs(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&ct()&&ti();let t=ra();if(t&&!e.reinstall&&!e.from){zs(),console.log(le.green("Opened the Klaudius app.")),qs();return}let n=await la(e.from);console.log(le.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?ca(n):da(n),zs(),console.log(le.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),qs()}function qs(){process.platform==="darwin"?console.log(le.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(le.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function qt(){return te(yn(),"Applications","Klaudius.app")}function ei(){return process.env.LOCALAPPDATA??te(yn(),"AppData","Local")}function oa(){return te(ei(),"Klaudius")}function ct(){let e=te(ei(),"Programs");try{for(let t of sa(e)){if(!/laudius/i.test(t))continue;let n=te(e,t,"Klaudius.exe");if(lt(n))return n}}catch{}return null}function ra(){return process.platform==="darwin"?lt(qt()):ct()!==null}async function aa(){try{let{readFileSync:e}=await import("fs"),n=e(te(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function la(e){if(e)return lt(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await aa();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=`${ia}?file=${encodeURIComponent(Ws())}`,s=te(Js(te(Xs(),"klaudius-app-")),Ws());console.log(le.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.34.1"}});if(!o.ok){let d=`HTTP ${o.status}`;try{let c=await o.json();c.reason&&(d=c.reason)}catch{}throw new Error(d)}let r=Buffer.from(await o.arrayBuffer()),{writeFileSync:a}=await import("fs");return a(s,r),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 ca(e){let t=te(yn(),"Applications");na(t,{recursive:!0});let n=Js(te(Xs(),"klaudius-app-x-")),s=ze("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=te(n,"Klaudius.app");lt(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),Qs(qt(),{recursive:!0,force:!0});let r=ze("mv",[o,qt()],{stdio:"pipe"});r.status!==0&&(console.error(`Couldn't install to ~/Applications: ${r.stderr?.toString().trim()}`),process.exit(1))}function da(e){/\.exe$/i.test(e)||(console.error("Expected the Klaudius installer (.exe). A zip can't be installed here \u2014 an unzipped copy can never update itself."),process.exit(1));let t=ze(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!ua(6e4)){let s=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,o=ct();if(o&&ni(o)){console.log(le.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(le.dim("Open it from the Start Menu if it doesn't appear shortly."));return}console.error(`Klaudius didn't finish installing (${s}).`),console.error("Check your Start Menu for Klaudius \u2014 it may still be finishing."),console.error("If it isn't there, email hello@klaudius.dev."),process.exit(1)}ti()}function ua(e){let t=Date.now()+e;for(;;){let n=ct();if(n)return n;if(Date.now()>=t)return null;pa(500)}}function pa(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function ti(){let e=oa();if(!lt(te(e,"app","Klaudius.exe")))return;console.log(le.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
|
|
129
137
|
$legacy = '${e.replace(/'/g,"''")}'
|
|
130
138
|
# Compare against the directory PLUS its separator, so a sibling folder whose
|
|
131
139
|
# name merely starts with the same text ("Klaudius Desktop") is never matched.
|
|
@@ -139,4 +147,4 @@ foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetF
|
|
|
139
147
|
Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
|
|
140
148
|
}
|
|
141
149
|
}
|
|
142
|
-
}`;
|
|
150
|
+
}`;ze("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Qs(e,{recursive:!0,force:!0})}catch{console.log(le.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function zs(){if(process.platform==="darwin"){ze("open",["-a",qt()],{stdio:"pipe"});return}let e=ct();if(!e||ni(e))return;ta(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function ni(e){let t=ze("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(s=>s.trim().toLowerCase()===n)}function si(e){return new Promise(t=>{if(e.destroyed||e.writableEnded||!e.writable){t();return}let n=()=>t();e.once("error",n);try{e.write("",n)}catch{n()}})}async function wn(e=0){await Promise.all([si(process.stdout),si(process.stderr)]),process.exit(e)}import{spawnSync as fa}from"child_process";var kn="--use-system-ca";function ii(){let e=process.env.NODE_OPTIONS??"";if(e.includes(kn)||!ye().ok)return;let n=e?`${e} ${kn}`:kn,s=fa(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)}ii();var ma="0.34.1",ce=new ha;ce.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(ma);ce.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 Ln({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});ce.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 Ls({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await wn(process.exitCode??0)}catch(n){console.error("init failed:",n.message),process.exit(1)}});ce.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 $s({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});ce.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await Ds({}),await wn(process.exitCode??0)}catch(e){console.error("configure failed:",e.message),process.exit(1)}});ce.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 js({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});ce.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 Gs({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});ce.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 Zs({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});ce.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 Ys({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ce.parse(process.argv);
|