klaudius 0.35.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{WizardApp-NGM5HCC3.js → WizardApp-NTXHCSOW.js} +1 -1
- package/dist/bin.js +81 -76
- package/dist/chunk-FBALIRIM.js +520 -0
- package/package.json +2 -2
- package/dist/chunk-3XX6MJ72.js +0 -521
package/dist/bin.js
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
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 co(){let e=process.platform==="win32",t=await xt("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 xt("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 uo(){let e=await ei();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 po(){let e=Ge([{label:"your Windows user folder",path:oo()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await xt("npm",["config","get","script-shell"],!0),i=n.code===0?n.stdout.trim():void 0;if(Be(i,so))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${i}) handles it`};let{detail:s,action:o}=Ve(e,"preflight"),r=e.some(c=>c.chars.includes("&"));return{name:t,status:r?"fail":"warn",detail:s,nextAction:o}}async function fo(){try{return await fetch(ni,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:ni}}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 ho(e=0){e>0?console.log(V.green(V.bold("Your machine is ready."))+V.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(V.green(V.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(V.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(` ${V.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(V.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(V.dim(" run it in a new terminal window.")),console.log()}function xt(e,t,n=!1){return new Promise(i=>{let s=n?ti([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ti(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",c=>{o+=c.toString()}),s.stderr?.on("data",c=>{r+=c.toString()}),s.on("close",c=>i({code:c??1,stdout:o,stderr:r})),s.on("error",()=>i({code:1,stdout:o,stderr:r}))})}import{mkdir as on,readdir as ss,readFile as nt,rm as ts,stat as In,writeFile as gt}from"fs/promises";import{spawnSync as Cn}from"child_process";import{existsSync as jr}from"fs";import{homedir as os}from"os";import{resolve as Kr,isAbsolute as Gr,join as X,normalize as Br}from"path";import*as T from"@clack/prompts";import g from"picocolors";var mo={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"},go={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 Ot(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let i=go[(t??"").toUpperCase()];return i?`${i.pre??""}${n}${i.post??""}`:n}function mn(e,t){if(!e)return e;let n=e.replace(/[\s().-]/g,"");if(/^\+\d{8,15}$/.test(n))return n;if(/^00\d{8,15}$/.test(n))return`+${n.slice(2)}`;let i=t?mo[t.toUpperCase()]:void 0;return i==="1"&&/^1?\d{10}$/.test(n)?`+1${n.slice(-10)}`:i&&i!=="1"&&/^0\d{7,14}$/.test(n)?`+${i}${n.slice(1)}`:e}var gn="claude-code",yn="gpt-5.6-terra";function si(e){if(e==="claude-code"||e==="codex")return e}var yo=["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 $t(e){let t=e?.trim().toLowerCase()??"";return yo.includes(t)?t:void 0}function Lt(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 wn="vercel";function oi(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function ri(e){if(e==="telegram"||e==="email"||e==="sms")return e}function ai(e){if(e==="password"||e==="oauth-microsoft")return e}function wo(e){if(e==="custom"||e!==void 0&&Object.hasOwn(ce,e))return e}function ut(e){let t=wo(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[i,s]of Object.entries(ce))if(s.smtpHost===n)return i;return"custom"}}function li(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let i of t.split(",")){let s=i.trim().toLowerCase();s&&s!=="primary"&&!n.includes(s)&&n.push(s)}return n.map(i=>{let s=/^[a-z0-9_]+$/.test(i)&&i!=="auto",o=c=>{let u=e[`EMAIL_ACCOUNT_${i.toUpperCase()}_${c}`];return u?.trim()?u.trim():void 0},r=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(c=>!o(c)).map(c=>`EMAIL_ACCOUNT_${i.toUpperCase()}_${c}`);for(let c of["SMTP_PORT","IMAP_PORT"]){let u=o(c);u!==void 0&&!/^\d+$/.test(u)&&r.push(`EMAIL_ACCOUNT_${i.toUpperCase()}_${c}`)}return{label:i,valid:s,auth:(o("AUTH")??"password").toLowerCase(),address:o("ADDRESS"),missing:r,smtpHost:o("SMTP_HOST"),smtpPort:parseInt(o("SMTP_PORT")??"587",10),imapHost:o("IMAP_HOST"),imapPort:parseInt(o("IMAP_PORT")??"993",10),password:o("PASSWORD"),login:o("LOGIN")}})}function Nt(e){let t=[],n=c=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${c}`),t.push("# "+"=".repeat(60)),t.push("")},i=(c,u)=>{if(u==null||u===""){t.push(`# ${c}=`);return}let p=String(u);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(p)){let d=p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${c}="${d}"`)}else t.push(`${c}=${p}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),i("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),i("AI_AGENT",e.aiAgent??gn),i("AI_PLAN",e.aiPlan),i("QA_PHASE",e.qaPhase??je(e.aiPlan)),n("Operating country and language"),i("OPERATOR_COUNTRY",e.country),i("OPERATOR_COUNTRY_CODE",e.countryCode),i("OPERATOR_LANGUAGE",e.language),i("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let s=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];i("PIPELINE_MODES",[...new Set(s)].join(",")),n("Pricing"),i("PRICING",Ot(e.pricing,e.countryCode)),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",Ot(e.pricingMonthly,e.countryCode)),n("Automated outreach features"),i("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),i("OPERATOR_NAME",e.name),i("SIGNATURE",e.signature),i("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),i("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),i("EMAIL_PROVIDER",e.emailProvider),i("EMAIL_AUTH",e.emailAuth??"password"),i("EMAIL_ADDRESS",e.emailAddress),i("EMAIL_PASSWORD",e.emailPassword),i("EMAIL_FROM_NAME",e.emailFromName),i("EMAIL_SMTP_HOST",e.emailSmtpHost),i("EMAIL_SMTP_PORT",e.emailSmtpPort),i("EMAIL_IMAP_HOST",e.emailImapHost),i("EMAIL_IMAP_PORT",e.emailImapPort),i("EMAIL_SENT_FOLDER",e.emailSentFolder),i("EMAIL_INBOX_FOLDER",e.emailInboxFolder),i("EMAIL_DRAFTS_FOLDER",e.emailDraftsFolder),n("SMS outreach"),i("SMS_PROVIDER",e.smsProvider),i("TEST_PHONE",mn(e.testPhone,e.countryCode)),i("TWILIO_ACCOUNT_SID",e.twilioAccountSid),i("TWILIO_AUTH_TOKEN",e.twilioAuthToken),i("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),i("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Letter outreach"),i("LETTER_PROVIDER",e.letterProvider??"none"),i("PINGEN_CLIENT_ID",e.pingenClientId),i("PINGEN_CLIENT_SECRET",e.pingenClientSecret),i("PINGEN_ORG_ID",e.pingenOrgId),i("POSTGRID_API_KEY",e.postgridApiKey),n("Supabase (pipeline state)"),i("SUPABASE_URL",e.supabaseUrl),i("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),i("SUPABASE_ANON_KEY",e.supabaseAnonKey),i("SUPABASE_PAT",e.supabasePat),i("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),i("DEPLOY_PROVIDER",e.deployProvider??wn),i("VERCEL_TOKEN",e.vercelToken),i("VERCEL_SCOPE",e.vercelScope??""),i("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),i("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),i("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),i("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),i("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),i("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),i("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),i("NOTIFY_CHANNEL",e.notifyChannel),i("NOTIFY_TO",e.notifyTo),i("TELEGRAM_BOT_TOKEN",e.telegramBotToken),i("TELEGRAM_CHAT_ID",e.telegramChatId);let o=new Set(t.map(c=>/^#?\s*([A-Z0-9_]+)=/.exec(c)?.[1]).filter(c=>!!c)),r=Object.entries(e.preservedEnv??{}).filter(([c])=>!o.has(c));if(r.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[c,u]of r)i(c,u)}return t.join(`
|
|
2
|
+
import{a as Qe,b as mi,c as hi,d as Ye,e as _e,f as We,g as pe,h as Nt,i as te,j as H,k as gi,l as $t,m as Xe,n as Ze,o as yi,p as ki,q as wi,r as ke,s as Ai,t as Ei}from"./chunk-FBALIRIM.js";import{Command as vc}from"commander";import{spawn as bi}from"child_process";import{existsSync as Ho}from"fs";import{homedir as jo}from"os";import B from"picocolors";import{win32 as To}from"path";var Io=["&","^","%","!"];function Co(e){return Io.filter(t=>e.includes(t))}function et(e){let t=[];for(let{label:n,path:i}of e){let s=Co(i);s.length>0&&t.push({label:n,path:i,chars:s})}return t}function Ro(e){let t=(e??"").trim().replace(/^["']|["']$/g,"");if(!t||t==="undefined"||t==="null")return null;let n=t.toLowerCase().split(/[\\/]/);if(n.length<2||n.includes("system32"))return null;let i=To.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(i)?t:null}function tt(e,t){let n=Ro(e);return n===null?!1:t?t(n):!0}function nt(e,t){let n=e[0],i=[...new Set(e.flatMap(p=>p.chars))],s=i.map(p=>`"${p}"`).join(", "),o=i.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${s} in it ${o?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${o?"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 we(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),i=parseInt(t[2],10),s=parseInt(t[3],10),o=`${n}.${i}.${s}`;return n<22||n===22&&i<15?{ok:!1,version:o,major:n,minor:i,message:`Your installed Node.js is ${o}. 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:o,major:n,minor:i}}import{spawn as vo}from"child_process";import{existsSync as Oo}from"fs";import{homedir as xo}from"os";import{delimiter as Lo,join as Mt}from"path";var No=new Set(["Restricted","AllSigned"]);function $o(e,t=Oo){for(let n of e.split(Lo)){let i=n.replace(/"/g,"");if(!i)continue;let s=Mt(i,"npx.ps1");if(t(s))return{path:s,isPs1:!0};for(let o of["npx.exe","npx.bat","npx.cmd"]){let r=Mt(i,o);if(t(r))return{path:r,isPs1:!1}}}return null}async function Si(){let e=$o(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Mo();if(!t)return{blocked:!1,shimPath:e.path};let n=Mt(xo(),".local","node")+"\\";return{blocked:No.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Mo(){let e=Mt(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await Pi(e)??await Pi("powershell.exe")}function Pi(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let i=vo(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),s="",o=setTimeout(()=>{i.kill(),n(null)},8e3);i.stdout.on("data",r=>{s+=r.toString()}),i.stderr?.resume(),i.on("close",r=>{clearTimeout(o),n(r===0&&s.trim()?s.trim():null)}),i.on("error",()=>{clearTimeout(o),n(null)})})}import{spawn as Do}from"child_process";var At=3,Dt=10,Fo=[["python3"],["python"],["py","-3"]];async function Q(){for(let e of Fo){let t=await Ft(e[0],[...e.slice(1),"--version"]),n=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(n)||t.code!==0)continue;let i=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!i)continue;let s=parseInt(i[1],10),o=parseInt(i[2],10),r=i[3]?`${s}.${o}.${i[3]}`:`${s}.${o}`;return{command:[...e],version:r,major:s,minor:o}}return null}async function it(){let e=Uo(),t=await Q();if(!t){let r=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${At}.${Dt}+ is not installed (or not on PATH). Install it from ${e}.`+r}}let{command:n,version:i,major:s,minor:o}=t;return s<At||s===At&&o<Dt?{ok:!1,version:i,major:s,minor:o,command:n,message:`Your installed Python is ${i}. Klaudius needs Python ${At}.${Dt} or newer (the pipeline depends on packages that only ship wheels for ${At}.${Dt}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:i,major:s,minor:o,command:n}}function Uo(){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 Ft(e,t){return new Promise(n=>{let i=Do(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),s="",o="";i.stdout?.on("data",r=>{s+=r.toString()}),i.stderr?.on("data",r=>{o+=r.toString()}),i.on("close",r=>n({code:r??1,stdout:s,stderr:o})),i.on("error",()=>n({code:1,stdout:s,stderr:o}))})}var _i=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function Ti(e={}){console.log(B.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
|
+
`));let t=[];t.push(Ko());let n=await it();if(t.push(Go(n)),t.push(await Bo(n.command)),t.push(await Vo()),process.platform==="win32"){let s=await Yo();s&&t.push(s);let o=await Wo();o&&t.push(o)}t.push(await qo());for(let s of t){let o=s.status==="ok"?B.green("\u2713"):s.status==="warn"?B.yellow("!"):B.red("\u2717");console.log(` ${o} ${s.name}${s.detail?B.dim(` \u2014 ${s.detail}`):""}`),s.nextAction&&console.log(` ${B.dim("\u2192")} ${B.cyan(s.nextAction)}`)}console.log();let i=t.filter(s=>s.status==="fail");if(i.length===0){let s=t.filter(o=>o.status==="warn").length;zo(s);return}console.log(B.red(B.bold(`${i.length} check${i.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(B.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(B.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Ko(){let e=we();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 Go(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 Bo(e){let t=e??["python3"],n=await Ut(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 Vo(){let e=process.platform==="win32",t=await Ut("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 Ut("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 Yo(){let e=await Si();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 Wo(){let e=et([{label:"your Windows user folder",path:jo()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await Ut("npm",["config","get","script-shell"],!0),i=n.code===0?n.stdout.trim():void 0;if(tt(i,Ho))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(d=>`"${d}"`).join(", ")}, but npm's script-shell (${i}) handles it`};let{detail:s,action:o}=nt(e,"preflight"),r=e.some(d=>d.chars.includes("&"));return{name:t,status:r?"fail":"warn",detail:s,nextAction:o}}async function qo(){try{return await fetch(_i,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:_i}}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 zo(e=0){e>0?console.log(B.green(B.bold("Your machine is ready."))+B.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(B.green(B.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(B.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(` ${B.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(B.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(B.dim(" run it in a new terminal window.")),console.log()}function Ut(e,t,n=!1){return new Promise(i=>{let s=n?bi([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):bi(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",d=>{o+=d.toString()}),s.stderr?.on("data",d=>{r+=d.toString()}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",()=>i({code:1,stdout:o,stderr:r}))})}import{mkdir as mn,readdir as _s,readFile as Bn,rm as Ss,stat as Yn,writeFile as fn}from"fs/promises";import{spawnSync as Wn}from"child_process";import{existsSync as _a}from"fs";import{homedir as Ts}from"os";import{resolve as Ta,isAbsolute as Ia,join as X,normalize as Ca}from"path";import*as v from"@clack/prompts";import A from"picocolors";import Jo from"react";import{render as Qo}from"ink";async function W(e={},t={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius@latest init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:n}=await import("./WizardApp-NTXHCSOW.js"),i=null;Qe("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),hi(),await new Promise(o=>setImmediate(o)),await new Promise(o=>setTimeout(o,0)),Qe("runWizard:event loop drained, mounting Ink");let s=Qo(Jo.createElement(n,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:o=>{Qe("runWizard:onComplete called",{keys:Object.keys(o).length}),i=o}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});Qe("runWizard:render returned, awaiting exit");try{await s.waitUntilExit()}finally{process.stdin.pause(),process.stdin.ref()}if(Qe("runWizard:waitUntilExit resolved",{resultIsNull:i===null}),!i)throw new Error(`Wizard exited without completing. Diagnostic log: ${mi}
|
|
5
|
+
Please share that file so we can trace what happened.`);return i}var Xo={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"};function Ht(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let i=yi[(t??"").toUpperCase()];return i?`${i.pre??""}${n}${i.post??""}`:n}function Sn(e,t){if(!e)return e;let n=e.replace(/[\s().-]/g,"");if(/^\+\d{8,15}$/.test(n))return n;if(/^00\d{8,15}$/.test(n))return`+${n.slice(2)}`;let i=t?Xo[t.toUpperCase()]:void 0;return i==="1"&&/^1?\d{10}$/.test(n)?`+1${n.slice(-10)}`:i&&i!=="1"&&/^0\d{7,14}$/.test(n)?`+${i}${n.slice(1)}`:e}var bn="claude-code",_n="gpt-5.6-terra",jt={AI_AGENT:["claude-code","codex"],AI_PLAN:["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"],QA_PHASE:["on","off"],DEPLOY_PROVIDER:["vercel","cloudflare","netlify","selfhost"],EMAIL_AUTH:["password","oauth-microsoft"],SMS_PROVIDER:["twilio","imessage"],LETTER_PROVIDER:["pingen","postgrid","none"],NOTIFY_CHANNEL:["telegram","email","sms"]},qe=(e,t)=>jt[e].includes(t??"");function Tn(e){return qe("AI_AGENT",e)?e:void 0}function Pt(e){let t=e?.trim().toLowerCase()??"";return qe("AI_PLAN",t)?t:void 0}function St(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 In="vercel";function Cn(e){return qe("DEPLOY_PROVIDER",e)?e:void 0}function Rn(e){return qe("NOTIFY_CHANNEL",e)?e:void 0}function vn(e){return qe("EMAIL_AUTH",e)?e:void 0}function On(e){return qe("SMS_PROVIDER",e)?e:void 0}var Et="none";function xn(e){if(e!==Et)return qe("LETTER_PROVIDER",e)?e:void 0}function Ii(e,t){switch(e){case"AI_AGENT":return Tn(t);case"AI_PLAN":return Pt(t);case"QA_PHASE":return St(t);case"DEPLOY_PROVIDER":return Cn(t);case"EMAIL_AUTH":return vn(t);case"SMS_PROVIDER":return On(t);case"LETTER_PROVIDER":return t===Et?Et:xn(t);case"NOTIFY_CHANNEL":return Rn(t)}}function Zo(e){if(e==="custom"||e!==void 0&&Object.hasOwn(te,e))return e}function Te(e){let t=Zo(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n)return pe(n)??"custom"}function Ci(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let i of t.split(",")){let s=i.trim().toLowerCase();s&&s!=="primary"&&!n.includes(s)&&n.push(s)}return n.map(i=>{let s=/^[a-z0-9_]+$/.test(i)&&i!=="auto",o=d=>{let c=e[`EMAIL_ACCOUNT_${i.toUpperCase()}_${d}`];return c?.trim()?c.trim():void 0},r=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(d=>!o(d)).map(d=>`EMAIL_ACCOUNT_${i.toUpperCase()}_${d}`);for(let d of["SMTP_PORT","IMAP_PORT"]){let c=o(d);c!==void 0&&!/^\d+$/.test(c)&&r.push(`EMAIL_ACCOUNT_${i.toUpperCase()}_${d}`)}return{label:i,valid:s,auth:(o("AUTH")??"password").toLowerCase(),address:o("ADDRESS"),missing:r,smtpHost:o("SMTP_HOST"),smtpPort:parseInt(o("SMTP_PORT")??"587",10),imapHost:o("IMAP_HOST"),imapPort:parseInt(o("IMAP_PORT")??"993",10),password:o("PASSWORD"),login:o("LOGIN")}})}function st(e){let t=[],n=d=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${d}`),t.push("# "+"=".repeat(60)),t.push("")},i=(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"),i("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),i("AI_AGENT",e.aiAgent??bn),i("AI_PLAN",e.aiPlan),i("QA_PHASE",e.qaPhase??_e(e.aiPlan)),n("Operating country and language"),i("OPERATOR_COUNTRY",e.country),i("OPERATOR_COUNTRY_CODE",e.countryCode),i("OPERATOR_LANGUAGE",e.language),i("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let s=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];i("PIPELINE_MODES",[...new Set(s)].join(",")),n("Pricing"),i("PRICING",Ht(e.pricing,e.countryCode)),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",Ht(e.pricingMonthly,e.countryCode)),n("Automated outreach features"),i("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),i("OPERATOR_NAME",e.name),i("SIGNATURE",e.signature),i("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),i("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),i("EMAIL_PROVIDER",e.emailProvider),i("EMAIL_AUTH",e.emailAuth??"password"),i("EMAIL_ADDRESS",e.emailAddress),i("EMAIL_PASSWORD",e.emailPassword),i("EMAIL_FROM_NAME",e.emailFromName),i("EMAIL_SMTP_HOST",e.emailSmtpHost),i("EMAIL_SMTP_PORT",e.emailSmtpPort),i("EMAIL_IMAP_HOST",e.emailImapHost),i("EMAIL_IMAP_PORT",e.emailImapPort),i("EMAIL_SENT_FOLDER",e.emailSentFolder),i("EMAIL_INBOX_FOLDER",e.emailInboxFolder),i("EMAIL_DRAFTS_FOLDER",e.emailDraftsFolder),n("SMS outreach"),i("SMS_PROVIDER",e.smsProvider),i("TEST_PHONE",Sn(e.testPhone,e.countryCode)),i("TWILIO_ACCOUNT_SID",e.twilioAccountSid),i("TWILIO_AUTH_TOKEN",e.twilioAuthToken),i("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),i("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Letter outreach"),i("LETTER_PROVIDER",e.letterProvider??"none"),i("PINGEN_CLIENT_ID",e.pingenClientId),i("PINGEN_CLIENT_SECRET",e.pingenClientSecret),i("PINGEN_ORG_ID",e.pingenOrgId),i("POSTGRID_API_KEY",e.postgridApiKey),n("Supabase (pipeline state)"),i("SUPABASE_URL",e.supabaseUrl),i("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),i("SUPABASE_ANON_KEY",e.supabaseAnonKey),i("SUPABASE_PAT",e.supabasePat),i("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),i("DEPLOY_PROVIDER",e.deployProvider??In),i("VERCEL_TOKEN",e.vercelToken),i("VERCEL_SCOPE",e.vercelScope??""),i("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),i("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),i("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),i("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),i("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),i("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),i("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),i("NOTIFY_CHANNEL",e.notifyChannel),i("NOTIFY_TO",e.notifyTo),i("TELEGRAM_BOT_TOKEN",e.telegramBotToken),i("TELEGRAM_CHAT_ID",e.telegramChatId);let o=new Set(t.map(d=>/^#?\s*([A-Z0-9_]+)=/.exec(d)?.[1]).filter(d=>!!d)),r=Object.entries(e.preservedEnv??{}).filter(([d])=>!o.has(d));if(r.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[d,c]of r)i(d,c)}return t.join(`
|
|
5
6
|
`)+`
|
|
6
|
-
`}function
|
|
7
|
-
`}function
|
|
8
|
-
`)}function
|
|
7
|
+
`}function ot(e){let t={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(t,null,2)+`
|
|
8
|
+
`}function rt(e){let t=e.supabaseProjectRef,n=er(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&&Ye.has(e.aiPlan)?[`# Set by the wizard for ${We[e.aiPlan]}. Change or delete to use Codex's default.`,`model = "${_n}"`,""]:[],"[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(`
|
|
9
|
+
`)}function er(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Ri=[{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 tr(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function vi(e,t,n){let i=n.filter(r=>!(r.key in t));if(i.length===0)return null;let s=e.endsWith(`
|
|
9
10
|
`)?"":`
|
|
10
|
-
`,o=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let r of i)o.push(""),r.comment&&o.push(`# ${r.comment}`),o.push(
|
|
11
|
+
`,o=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let r of i)o.push(""),r.comment&&o.push(`# ${r.comment}`),o.push(tr(r.key,r.value));return e+s+o.join(`
|
|
11
12
|
`)+`
|
|
12
|
-
`}function
|
|
13
|
-
`)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.indexOf("=");if(s===-1)continue;let o=i.slice(0,s).trim(),r=
|
|
14
|
-
|
|
15
|
-
`+$e.bold($e.cyan(e))),detail:e=>console.log($e.dim(" "+e))};var Bo="https://registry.npmjs.org/klaudius/latest";async function Vo(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Bo,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let s=await i.json();return typeof s.version=="string"?s.version:null}catch{return null}finally{clearTimeout(n)}}function Yo(e,t){let n=o=>o.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),i=n(e),s=n(t);if(i.length<3||s.length<3)return!1;for(let o=0;o<3;o++){if(Number.isNaN(i[o])||Number.isNaN(s[o]))return!1;if(i[o]>s[o])return!0;if(i[o]<s[o])return!1}return!1}async function Vt(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Vo();!n||!Yo(n,t)||(a.blank(),a.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(a.detail("Your project content is fetched fresh either way, so you're not missing any"),a.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),a.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),a.blank())}import{createHash as Wo}from"crypto";import{hostname as Ni,userInfo as qo,platform as Mi,arch as Di}from"os";var zo="https://klaudius.dev",Jo="/api/licenses/validate",Qo="0.35.0";async function Fi(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),i=(process.env.KLAUDIUS_API_URL??zo).replace(/\/$/,"")+Jo,s=mt(),o;try{o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:s,hostname:Ni(),os:`${Mi()}-${Di()}`,cli_version:Qo})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${H(c)}). Check your internet connection or try again later.`}}let r;try{r=await o.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${o.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${o.status}).`}}function mt(){let e=[Ni(),qo().username,Mi(),Di()].join("|");return Wo("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Xo}from"fs/promises";import{join as Zo}from"path";async function We(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: ${H(n)}`}}}function Ui(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function Yt(e){let t;try{t=await Xo(Zo(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(i){return{ok:!1,message:`Could not read scripts/schema.sql: ${i.message}`}}let n=e.pat.replace(/\s+/g,"");try{let i=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(i.ok)return{ok:!0};let s=await i.text();return{ok:!1,message:nr(i.status,s)}}catch(i){return{ok:!1,message:`Schema apply failed: ${H(i)}`}}}function er(e){let t=[...e.matchAll(/ALTER TABLE clients ADD COLUMN IF NOT EXISTS (\w+)/g)].map(i=>i[1]),n=[...e.matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/g)].map(i=>i[1]);return{clientsColumns:[...new Set(t)],tables:[...new Set(n)]}}function tr(e,t){let n="";try{let s=JSON.parse(t);s&&typeof s.code=="string"&&(n=s.code)}catch{}return{missing:e===400&&n==="42703"||e===404&&(n==="PGRST205"||n==="42P01"),code:n}}async function Wt(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{clientsColumns:i,tables:s}=er(e.sql),o=[];i.length>0&&o.push({path:`clients?select=${i.join(",")}&limit=0`,label:"clients columns"});for(let c of s)c!=="clients"&&o.push({path:`${c}?select=*&limit=0`,label:`${c} table`});let r=[];try{for(let c of o){let u=await fetch(`${t}/rest/v1/${c.path}`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(u.ok)continue;let p=tr(u.status,await u.text());if(p.missing){r.push(c.label);continue}return{ok:!1,missing:r,unreachable:`HTTP ${u.status}${p.code?` ${p.code}`:""}`}}}catch(c){return{ok:!1,missing:r,unreachable:H(c)}}return{ok:r.length===0,missing:r}}function nr(e,t){let n=t;try{let i=JSON.parse(t);i&&typeof i.message=="string"&&(n=i.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 ir(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 sr(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&&ir(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 qe(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let i=await t.text().catch(()=>"");return{ok:!1,...sr(t.status,i)}}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: ${H(t)}`}}}var Hi="https://api.cloudflare.com/client/v4";function ji(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ze(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let s=await fetch(`${Hi}/user/tokens/verify`,{headers:i});if(s.status===401||s.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} verifying the token. Try again or check cloudflarestatus.com.`};let o=await s.json(),r=o.result?.status;if(o.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${ji(o)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}try{let s=await fetch(`${Hi}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:i});if(s.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(s.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(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let o=await s.json();return o.success===!1?{ok:!1,message:ji(o)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(o.result)?o.result.length:void 0}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}}var Ki="https://api.netlify.com/api/v1";async function Je(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${Ki}/user`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} verifying the token. Try again or check netlifystatus.com.`}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${H(i)}`}}try{let i=await fetch(`${Ki}/accounts`,{headers:n});if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} listing your teams. Try again or check netlifystatus.com.`};let s=await i.json(),o=Array.isArray(s)?s:[];if(o.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let r=typeof o[0]?.slug=="string"?o[0].slug:void 0;return{ok:!0,accountCount:o.length,accountSlug:r}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${H(i)}`}}}function or(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,i=/caller does not have permission|billing/i.test(t)?"This usually means the key's Google Cloud project has no active billing account \u2014 Places needs billing set up even though Google's free monthly credit covers normal use. Check https://console.cloud.google.com/billing for the project this key belongs to. (Less often: the key's restrictions block the Places API \u2014 check Credentials.)":"Common causes: the key is wrong or deleted, billing is not enabled on its Cloud project, or the key's restrictions block the Places API. Check https://console.cloud.google.com/billing and the key's entry under Credentials.";return`${n} ${i}`}async function Qe(e){let t=Jn(e);if(t)return{ok:!1,message:t};let n=Re(e),i=n.value,s=o=>{let r=[o],c=Qn(e);return c&&r.push(c),n.repairs.length>0&&r.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),r.join(`
|
|
16
|
-
`)};try{let o=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":i,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(o.ok)return{ok:!0};if(o.status===429)return{ok:!0};let r={};try{r=await o.json()}catch{}let c=r.error?.message??"",u=r.error?.status??"";return o.status===400&&(u==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(c))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library/places.googleapis.com and press Enable for the project this key belongs to, then try again. (That page is 'Places API (New)' \u2014 the older 'Places API' is a different API and won't work.)"}:o.status===401||o.status===403?{ok:!1,message:s(or(o.status,c))}:{ok:!1,message:s(`Google API returned HTTP ${o.status}${c?`: ${c}`:""}.`)}}catch(o){return{ok:!1,message:`Could not reach Google: ${H(o)}`}}}import rr from"nodemailer";import{ImapFlow as ar}from"imapflow";function lr(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function Gi(e,t,n){let i=t.toLowerCase(),s=e.filter(lr);if(s.some(c=>c.path.toLowerCase()===i))return;let o=i.startsWith("inbox")?void 0:[`inbox.${i}`,`inbox/${i}`],r=s.find(c=>c.specialUse===n)?.path??(o&&s.find(c=>o.includes(c.path.toLowerCase()))?.path);return{configured:t,detected:r||void 0}}function En(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let i=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return i.includes("invalid credentials")||i.includes("authentication failed")||i.includes("auth failed")||i.includes("login failed")||i.includes("invalid login")?"auth":i.includes("etimedout")||i.includes("timeout")||i.includes("enotfound")||i.includes("getaddrinfo")||i.includes("econnrefused")||i.includes("econnreset")?"network":"other"}async function _e(e){let t=rr.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(r){return{ok:!1,failedAt:"smtp",message:Bi(r,"SMTP",e.usesAccountPassword,e.knownProvider),failureKind:En(r)}}finally{t.close()}let n=new ar({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),i,s,o;try{if(await n.connect(),e.sentFolder||e.draftsFolder)try{let r=await n.list();e.sentFolder&&(i=Gi(r,e.sentFolder,"\\Sent")),e.draftsFolder&&(s=Gi(r,e.draftsFolder,"\\Drafts"))}catch{o=!0}await n.logout()}catch(r){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Bi(r,"IMAP",e.usesAccountPassword,e.knownProvider),failureKind:En(r)}}return{ok:!0,sentFolderIssue:i,draftsFolderIssue:s,foldersUnverified:o}}function Bi(e,t,n,i){let s=e instanceof Error?e.message:String(e),o=s.toLowerCase();return En(e)==="auth"||o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
|
|
13
|
+
`}function Ln(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 J(e){let t={};for(let n of e.split(`
|
|
14
|
+
`)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.indexOf("=");if(s===-1)continue;let o=i.slice(0,s).trim(),r=Ln(i.slice(s+1).trim());t[o]=r}return t}var Oi=["VERCEL_TOKEN","CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","NETLIFY_AUTH_TOKEN","SELFHOST_DEPLOY_TARGET","SELFHOST_URL_TEMPLATE","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 Nn(e,t,n){let i=wi(Ht(t,e.countryCode)??"",Ht(n,e.countryCode)??"");e.pricing=i.pricing,e.pricingTerms=i.pricingTerms,e.pricingMonthly=i.pricingMonthly}function $n(e){let t=e&&e!=="custom"?te[e]:void 0;return[["EMAIL_SENT_FOLDER","emailSentFolder",t?.sentFolder],["EMAIL_DRAFTS_FOLDER","emailDraftsFolder",t?.draftsFolder],["EMAIL_INBOX_FOLDER","emailInboxFolder",t?.inboxFolder]]}function xi(e,t,n={}){let i={...e},s=r=>(t[r]??"").trim()!=="";!s("PRICING_TERMS")&&(s("PRICING")||s("PRICING_MONTHLY"))&&Nn(i,t.PRICING,t.PRICING_MONTHLY),i.signature&&i.name&&i.signature.trim()===i.name.trim()&&(i.signature=void 0),s("EMAIL_FROM_NAME")||(i.emailFromName=i.name?.trim()&&i.emailAddress?.trim()?i.name.trim():void 0);let o=Te(n)===i.emailProvider&&(n.EMAIL_ADDRESS??"").trim().toLowerCase()===(i.emailAddress??"").trim().toLowerCase();for(let[r,d,c]of $n(i.emailProvider))s(r)||o&&(n[r]??"").trim()||(i[d]=c);return i}function Li(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,i=d=>d==="email"||d==="sms"||d==="whatsapp"||d==="letter",s=e.OUTREACH_CHANNELS?.split(",").map(d=>d.trim()).filter(i),o=e.OUTREACH_PRIORITY?.split(",").map(d=>d.trim()).filter(i),r=e.WHATSAPP_ACCOUNTS?.split(",").map(d=>d.trim()).filter(d=>d.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Tn(e.AI_AGENT)??bn,aiPlan:Pt(e.AI_PLAN),qaPhase:St(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:s&&s.length>0?s:void 0,outreachPriority:o&&o.length>0?o:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailProvider:Te(e),emailAuth:vn(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:On(n),testPhone:Sn(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,letterProvider:xn(e.LETTER_PROVIDER),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:Cn(e.DEPLOY_PROVIDER)??In,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:Rn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function at(e){let t=b=>{let C=e[b];if(!C)return;let M=parseInt(C,10);return isNaN(M)?void 0:M},n=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),s=e.SUPABASE_PAT?.replace(/\s+/g,""),o=e.SUPABASE_PROJECT_REF,r=e.PRICING,d=e.PRICING_TERMS||"one-off, no monthly fees",c=Cn(e.DEPLOY_PROVIDER)??In,p=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,g=e.CLOUDFLARE_ACCOUNT_ID,m=e.NETLIFY_AUTH_TOKEN,w=e.SELFHOST_DEPLOY_TARGET,h=e.SELFHOST_URL_TEMPLATE;if(!r||!n||!i||!s||!o||!(c==="cloudflare"?!!u&&!!g:c==="netlify"?!!m:c==="selfhost"?!!w&&!!h:!!p))return null;let E=e.SMS_PROVIDER,T=b=>b==="email"||b==="sms"||b==="whatsapp"||b==="letter",I=e.OUTREACH_CHANNELS?.split(",").map(b=>b.trim()).filter(T),O=e.OUTREACH_PRIORITY?.split(",").map(b=>b.trim()).filter(T),N=e.WHATSAPP_ACCOUNTS?.split(",").map(b=>b.trim()).filter(b=>b.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Tn(e.AI_AGENT)??bn,aiPlan:Pt(e.AI_PLAN),qaPhase:St(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:r,pricingTerms:d,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:I&&I.length>0?I:void 0,outreachPriority:O&&O.length>0?O:void 0,whatsappAccounts:N&&N.length>0?N:void 0,emailProvider:Te(e),emailAuth:vn(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:On(E),testPhone:Sn(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,letterProvider:xn(e.LETTER_PROVIDER),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:g||void 0,netlifyAuthToken:m||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:w||void 0,selfhostUrlTemplate:h||void 0,supabaseUrl:n,supabaseServiceKey:i,supabasePat:s,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:o,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:Rn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{readFile as nr}from"fs/promises";import xe from"picocolors";var a={info:e=>console.log(xe.cyan("\u2139"),e),success:e=>console.log(xe.green("\u2713"),e),warn:e=>console.log(xe.yellow("\u26A0"),e),error:e=>console.error(xe.red("\u2717"),e),step:e=>console.log(xe.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+xe.bold(xe.cyan(e))),detail:e=>console.log(xe.dim(" "+e))};var ir="Fix this section's values and try again.";function _(e,t){a.blank();for(let n of sr(e,t))console.error(n);process.exit(2)}function sr(e,t){return[`INIT-BLOCKED section=${e}`,t,ir,"INIT-BLOCKED end"]}function Kt(e){for(let t of Object.keys(jt)){if(!(t in e))continue;let n=e[t]??"";n.trim()!==""&&Ii(t,n)===void 0&&_("answers",`${t} is set to "${n}", which isn't one of the values it can take: ${jt[t].join(", ")}.`)}}async function Gt(e){let t;try{t=await nr(e,"utf-8")}catch{_("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let i=JSON.parse(n),s={};for(let[o,r]of Object.entries(i))r!=null&&(s[o]=typeof r=="string"?r:String(r));return s}catch(i){_("answers",`Answers file is not valid JSON: ${i.message}`)}return J(t)}function Mn(e){return e.filter(([,t])=>!t?.trim()).map(([t,,n])=>[t,n])}function Dn(e,t){return e.some(([,n])=>(t[n]??"").trim()!=="")?"were cleared":"have never been set"}function Bt(e,t={}){if(!e.smsProvider)return"SMS is still switched on but no SMS provider is set \u2014 turn SMS off, or pick iMessage or Twilio.";if(e.smsProvider!=="twilio")return;let n=Mn([["Account SID",e.twilioAccountSid,"TWILIO_ACCOUNT_SID"],["Auth Token",e.twilioAuthToken,"TWILIO_AUTH_TOKEN"],["sending number",e.twilioPhoneNumber,"TWILIO_PHONE_NUMBER"]]);return n.length>0?`SMS is still switched on but its Twilio details ${Dn(n,t)} (${n.map(([i])=>i).join(", ")}) \u2014 turn SMS off, or add the details.`:void 0}function Vt(e,t={}){if(!e.letterProvider)return"Letters are still switched on but no letter provider is set \u2014 turn letters off, or pick Pingen or PostGrid.";let n=e.letterProvider==="pingen"?Mn([["Client ID",e.pingenClientId,"PINGEN_CLIENT_ID"],["Client Secret",e.pingenClientSecret,"PINGEN_CLIENT_SECRET"],["organisation id",e.pingenOrgId,"PINGEN_ORG_ID"]]):Mn([["API key",e.postgridApiKey,"POSTGRID_API_KEY"]]);return n.length===0?void 0:`Letters are still switched on but the ${e.letterProvider==="pingen"?"Pingen":"PostGrid"} details ${Dn(n,t)} (${n.map(([s])=>s).join(", ")}) \u2014 turn letters off, or add the details.`}function Yt(e,t={}){let n=e.notifyChannel;if(n==="telegram"&&(!e.telegramBotToken?.trim()||!e.telegramChatId?.trim()))return`Alerts are still set to reach you on Telegram but the bot token and chat ID ${Dn([["bot token","TELEGRAM_BOT_TOKEN"],["chat ID","TELEGRAM_CHAT_ID"]],t)} \u2014 add them back, or choose another way to be alerted.`;if(n==="email"&&!e.notifyTo?.trim()&&!e.emailAddress?.trim())return"Alerts are still set to reach you by email but there's no address left to send them to \u2014 set one, or choose another way to be alerted.";if(n==="sms"&&!e.notifyTo?.trim()&&!e.testPhone?.trim())return"Alerts are still set to reach you by text but there's no number left to send them to \u2014 set one, or choose another way to be alerted."}import{readFile as ji,writeFile as ur}from"fs/promises";import{join as Ki}from"path";import{mkdir as ar,readFile as lr,access as cr}from"fs/promises";import{dirname as dr,join as Di}from"path";import{chmod as Ni,rename as or,unlink as rr,writeFile as $i}from"fs/promises";var Mi=new Set(["EPERM","EACCES","EBUSY"]);async function Ae(e,t,n){let i=`${e}.${process.pid}-${Date.now()}.tmp`;await $i(i,t);for(let s=1;;s++)try{await or(i,e),n!==void 0&&await Ni(e,n).catch(()=>{});return}catch(o){let r=o.code??"";if(Mi.has(r)&&s<5){await new Promise(d=>setTimeout(d,50*s));continue}if(await rr(i).catch(()=>{}),!Mi.has(r))throw o;await $i(e,t),n!==void 0&&await Ni(e,n).catch(()=>{});return}}var Ie=".klaudius",Fi=`${Ie}/manifest.json`,Wt=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json"]),Ui=new Set(["clients/README.md"]),qt=new Set(["package-lock.json"]);async function zt(e){let t=Di(e,Fi);try{await cr(t)}catch{return null}let n=await lr(t,"utf-8"),i=JSON.parse(n),s={};for(let[o,r]of Object.entries(i.files??{}))s[o.split("\\").join("/")]=r;return i.files=s,Array.isArray(i.ignored)?i.ignored=i.ignored.filter(o=>typeof o=="string").map(o=>o.split("\\").join("/")):delete i.ignored,i}async function Le(e,t){let n=Di(e,Fi);await ar(dr(n),{recursive:!0}),await Ae(n,JSON.stringify(t,null,2)+`
|
|
16
|
+
`)}function Hi(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}function Jt(e){return Ki(e,Ie,"ms-signin.json")}async function Gi(e){return ji(Ki(e,".ms-token.json"),"utf-8").then(t=>String(JSON.parse(t).account?.address??"")).then(t=>t.trim().toLowerCase()).catch(()=>"")}async function Qt(e,t){let n=t.trim().toLowerCase();if(n==="")return!1;let i=await Gi(e);if(i==="")return!1;if(i===n)return!0;let s=await ji(Jt(e),"utf-8").then(d=>JSON.parse(d)).catch(()=>null),o=String(s?.entered??"").trim().toLowerCase(),r=String(s?.token??"").trim().toLowerCase();return o!==""&&o===n&&r===i}async function Xt(e,t){let n={entered:t.trim(),token:await Gi(e)};await ur(Jt(e),`${JSON.stringify(n)}
|
|
17
|
+
`,"utf-8").catch(()=>{})}import{copyFile as vd,mkdir as Od,readdir as fr,stat as xd}from"fs/promises";import{dirname as Nd,join as Vi,relative as mr,sep as hr}from"path";import{fileURLToPath as Md}from"url";import{createHash as Bi}from"crypto";import{readFile as pr}from"fs/promises";async function fe(e){let t=await pr(e);return Bi("sha256").update(t).digest("hex")}function Fn(e){return Bi("sha256").update(e).digest("hex")}async function ze(e,t=e){let n=await fr(e,{withFileTypes:!0}),i=[];for(let s of n){let o=Vi(e,s.name);s.name===".klaudius"&&e===t||(s.isDirectory()?i.push(...await ze(o,t)):s.isFile()&&i.push(mr(t,o).split(hr).join("/")))}return i}async function Yi(e){let t=await ze(e),n={};for(let i of t)Wt.has(i)||(n[i]=await fe(Vi(e,i)));return n}import{copyFile as gr,mkdir as Wi,mkdtemp as yr,readdir as qi,rm as zi}from"fs/promises";import{tmpdir as kr}from"os";import{dirname as wr,join as Zt}from"path";import{Readable as Ar}from"stream";import*as Ji from"tar";var Er="https://klaudius.dev/api/template";function Pr(e){return Ar.fromWeb(e)}async function en(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Er,n="0.37.0",i;try{i=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(d){throw new Error(`Could not reach klaudius.dev to download the template: ${H(d)}`)}if(!i.ok){let d="";try{let c=await i.json();d=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${i.status}${d}`)}if(!i.body)throw new Error("Template download succeeded but response had no body");let s=i.headers.get("x-klaudius-tier"),o=await yr(Zt(kr(),"klaudius-template-")),r=0;try{try{await new Promise((p,u)=>{let g=Ji.extract({cwd:o,strict:!0});g.on("finish",p),g.on("error",u),Pr(i.body).on("error",u).pipe(g)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await Wi(e.destDir,{recursive:!0});let d=new Set(await qi(e.destDir)),c=await ze(o);try{for(let p of c){let u=Zt(e.destDir,p);await Wi(wr(u),{recursive:!0}),await gr(Zt(o,p),u),r++}}catch(p){let u=await qi(e.destDir).catch(()=>[]);for(let g of u)d.has(g)||await zi(Zt(e.destDir,g),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await zi(o,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:r,tier:s}}import{copyFile as Sr,mkdir as Qi,readFile as Un,rm as br,writeFile as _r}from"fs/promises";import{dirname as Tr,join as Ce}from"path";import{structuredPatch as Ir}from"diff";var bt=Ce(".klaudius","base"),Re=Ce(".klaudius","conflict-base"),Xi=".klaudius-snapshot-id";async function tn(e,t,n,i){let s=Ce(e,bt);await br(s,{recursive:!0,force:!0}),await Qi(s,{recursive:!0});for(let o of n){let r=Ce(s,o);await Qi(Tr(r),{recursive:!0}),await Sr(Ce(t,o),r)}i!==void 0&&await _r(Ce(s,Xi),i,"utf-8")}async function Zi(e){try{return(await Un(Ce(e,bt,Xi),"utf-8")).trim()}catch{return null}}async function es(e,t){try{return await Un(Ce(e,bt,t),"utf-8")}catch{return null}}async function ts(e,t){try{return await Un(Ce(e,Re,t),"utf-8")}catch{return null}}function ns(e,t,n,i){return!i||Ne(n)?null:e!==null&&!Ne(e)&&Fn(e)===i?e:t!==null&&!Ne(t)&&Fn(t)===i?t:null}function Ne(e){return e.includes("\0")||e.includes("\uFFFD")}function is(e,t,n=60){let i=Ir("base","new",e,t,"","",{context:2});if(i.hunks.length===0)return["Upstream content is identical to your base for this file."];let s=i.hunks.map(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),o=[`Upstream changed ${i.hunks.length} hunk(s) (new-version lines ${s}):`,"","```diff"],r=0,d=!1;for(let c of i.hunks){if(r>=n){d=!0;break}o.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),r+=1;let p=Math.max(n-r,0),u=c.lines.slice(0,p);if(o.push(...u),r+=u.length,u.length<c.lines.length){d=!0;break}}return o.push("```"),d&&o.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),o}var Cr="https://registry.npmjs.org/klaudius/latest";async function Rr(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Cr,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let s=await i.json();return typeof s.version=="string"?s.version:null}catch{return null}finally{clearTimeout(n)}}function vr(e,t){let n=o=>o.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),i=n(e),s=n(t);if(i.length<3||s.length<3)return!1;for(let o=0;o<3;o++){if(Number.isNaN(i[o])||Number.isNaN(s[o]))return!1;if(i[o]>s[o])return!0;if(i[o]<s[o])return!1}return!1}async function nn(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Rr();!n||!vr(n,t)||(a.blank(),a.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(a.detail("Your project content is fetched fresh either way, so you're not missing any"),a.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),a.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),a.blank())}import{createHash as Or}from"crypto";import{hostname as ss,userInfo as xr,platform as os,arch as rs}from"os";var Lr="https://klaudius.dev",Nr="/api/licenses/validate",$r="0.37.0";async function as(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),i=(process.env.KLAUDIUS_API_URL??Lr).replace(/\/$/,"")+Nr,s=_t(),o;try{o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:s,hostname:ss(),os:`${os()}-${rs()}`,cli_version:$r})})}catch(d){return{ok:!1,reason:`Could not reach the Klaudius license server (${H(d)}). Check your internet connection or try again later.`}}let r;try{r=await o.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${o.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${o.status}).`}}function _t(){let e=[ss(),xr().username,os(),rs()].join("|");return Or("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Mr}from"fs/promises";import{join as Dr}from"path";async function $e(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: ${H(n)}`}}}function ls(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function lt(e){let t;try{t=await Mr(Dr(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(i){return{ok:!1,message:`Could not read scripts/schema.sql: ${i.message}`}}let n=e.pat.replace(/\s+/g,"");try{let i=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(i.ok)return{ok:!0};let s=await i.text();return{ok:!1,message:Hr(i.status,s)}}catch(i){return{ok:!1,message:`Schema apply failed: ${H(i)}`}}}function Fr(e){let t=[...e.matchAll(/ALTER TABLE clients ADD COLUMN IF NOT EXISTS (\w+)/g)].map(i=>i[1]),n=[...e.matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/g)].map(i=>i[1]);return{clientsColumns:[...new Set(t)],tables:[...new Set(n)]}}function Ur(e,t){let n="";try{let s=JSON.parse(t);s&&typeof s.code=="string"&&(n=s.code)}catch{}return{missing:e===400&&n==="42703"||e===404&&(n==="PGRST205"||n==="42P01"),code:n}}async function sn(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{clientsColumns:i,tables:s}=Fr(e.sql),o=[];i.length>0&&o.push({path:`clients?select=${i.join(",")}&limit=0`,label:"clients columns"});for(let d of s)d!=="clients"&&o.push({path:`${d}?select=*&limit=0`,label:`${d} table`});let r=[];try{for(let d of o){let c=await fetch(`${t}/rest/v1/${d.path}`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(c.ok)continue;let p=Ur(c.status,await c.text());if(p.missing){r.push(d.label);continue}return{ok:!1,missing:r,unreachable:`HTTP ${c.status}${p.code?` ${p.code}`:""}`}}}catch(d){return{ok:!1,missing:r,unreachable:H(d)}}return{ok:r.length===0,missing:r}}function Hr(e,t){let n=t;try{let i=JSON.parse(t);i&&typeof i.message=="string"&&(n=i.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 jr(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 Kr(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&&jr(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 Me(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let i=await t.text().catch(()=>"");return{ok:!1,...Kr(t.status,i)}}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: ${H(t)}`}}}var cs="https://api.cloudflare.com/client/v4";function ds(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function De(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let s=await fetch(`${cs}/user/tokens/verify`,{headers:i});if(s.status===401||s.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} verifying the token. Try again or check cloudflarestatus.com.`};let o=await s.json(),r=o.result?.status;if(o.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${ds(o)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}try{let s=await fetch(`${cs}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:i});if(s.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(s.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(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let o=await s.json();return o.success===!1?{ok:!1,message:ds(o)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(o.result)?o.result.length:void 0}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}}var us="https://api.netlify.com/api/v1";async function Fe(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${us}/user`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} verifying the token. Try again or check netlifystatus.com.`}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${H(i)}`}}try{let i=await fetch(`${us}/accounts`,{headers:n});if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} listing your teams. Try again or check netlifystatus.com.`};let s=await i.json(),o=Array.isArray(s)?s:[];if(o.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let r=typeof o[0]?.slug=="string"?o[0].slug:void 0;return{ok:!0,accountCount:o.length,accountSlug:r}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${H(i)}`}}}function Gr(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,i=/caller does not have permission|billing/i.test(t)?"This usually means the key's Google Cloud project has no active billing account \u2014 Places needs billing set up even though Google's free monthly credit covers normal use. Check https://console.cloud.google.com/billing for the project this key belongs to. (Less often: the key's restrictions block the Places API \u2014 check Credentials.)":"Common causes: the key is wrong or deleted, billing is not enabled on its Cloud project, or the key's restrictions block the Places API. Check https://console.cloud.google.com/billing and the key's entry under Credentials.";return`${n} ${i}`}async function Ue(e){let t=Ai(e);if(t)return{ok:!1,message:t};let n=ke(e),i=n.value,s=o=>{let r=[o],d=Ei(e);return d&&r.push(d),n.repairs.length>0&&r.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),r.join(`
|
|
18
|
+
`)};try{let o=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":i,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(o.ok)return{ok:!0};if(o.status===429)return{ok:!0};let r={};try{r=await o.json()}catch{}let d=r.error?.message??"",c=r.error?.status??"";return o.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.)"}:o.status===401||o.status===403?{ok:!1,message:s(Gr(o.status,d))}:{ok:!1,message:s(`Google API returned HTTP ${o.status}${d?`: ${d}`:""}.`)}}catch(o){return{ok:!1,message:`Could not reach Google: ${H(o)}`}}}import Br from"nodemailer";import{ImapFlow as Vr}from"imapflow";function Yr(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function ps(e,t,n){let i=t.toLowerCase(),s=e.filter(Yr);if(s.some(d=>d.path.toLowerCase()===i))return;let o=i.startsWith("inbox")?void 0:[`inbox.${i}`,`inbox/${i}`],r=s.find(d=>d.specialUse===n)?.path??(o&&s.find(d=>o.includes(d.path.toLowerCase()))?.path);return{configured:t,detected:r||void 0}}function Hn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let i=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return i.includes("invalid credentials")||i.includes("authentication failed")||i.includes("auth failed")||i.includes("login failed")||i.includes("invalid login")?"auth":i.includes("etimedout")||i.includes("timeout")||i.includes("enotfound")||i.includes("getaddrinfo")||i.includes("econnrefused")||i.includes("econnreset")?"network":"other"}async function me(e){let t=Br.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(r){return{ok:!1,failedAt:"smtp",message:fs(r,"SMTP",e.usesAccountPassword,e.knownProvider),failureKind:Hn(r)}}finally{t.close()}let n=new Vr({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),i,s,o;try{if(await n.connect(),e.sentFolder||e.draftsFolder)try{let r=await n.list();e.sentFolder&&(i=ps(r,e.sentFolder,"\\Sent")),e.draftsFolder&&(s=ps(r,e.draftsFolder,"\\Drafts"))}catch{o=!0}await n.logout()}catch(r){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:fs(r,"IMAP",e.usesAccountPassword,e.knownProvider),failureKind:Hn(r)}}return{ok:!0,sentFolderIssue:i,draftsFolderIssue:s,foldersUnverified:o}}function fs(e,t,n,i){let s=e instanceof Error?e.message:String(e),o=s.toLowerCase();return Hn(e)==="auth"||o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
|
|
17
19
|
\u2022 The mailbox password is wrong or mistyped.
|
|
18
20
|
\u2022 The email address doesn't match this mailbox's login.
|
|
19
21
|
\u2022 The provider is blocking third-party apps \u2014 check that third-party
|
|
@@ -28,119 +30,122 @@ import{b as Me,c as Tt,d as ce,e as H,f as Wn,g as qn,h as _t,i as It,j as zn,k
|
|
|
28
30
|
\u2022 The address is an alias (e.g. a Google Workspace alias domain) \u2014 the
|
|
29
31
|
sign-in must use the account's primary address. Keep the alias as
|
|
30
32
|
EMAIL_ADDRESS and set EMAIL_LOGIN in .env to the primary address.
|
|
31
|
-
\u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}import*as
|
|
32
|
-
`+t;return
|
|
33
|
-
${e.stdout??""}`;return
|
|
34
|
-
`,"utf-8"),"added"}catch(o){return a.warn(`Couldn't write ${s} (${o instanceof Error?o.message:String(o)}). The parallel-run dispatch may occasionally ask for approval.`),"skipped"}}async function
|
|
35
|
-
`,"utf-8")}var
|
|
36
|
-
runs on. It sets the QA-pass default (and, on the smaller ChatGPT plans, the model).`}))):(a.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await
|
|
37
|
-
${
|
|
33
|
+
\u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}import*as on from"@clack/prompts";var Wr=[{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 ct(e,t,n){let i=!1;for(let s of Wr){let o=s.issue(e);if(o){if(a.blank(),o.detected){if(n.nonInteractive){t[s.key]=o.detected,i=!0,a.warn(`Your mailbox has no "${o.configured}" folder \u2014 it calls its ${s.label} folder "${o.detected}". Using that.`);continue}a.warn(`Your mailbox has no "${o.configured}" folder.`),a.detail(`It calls its ${s.label} folder "${o.detected}".`);let r=await on.confirm({message:`Use "${o.detected}" instead?`,initialValue:!0});if(on.isCancel(r))return n.onCancel?.(),i;r?(t[s.key]=o.detected,i=!0,a.success(`${s.envKey} set to "${o.detected}"`)):a.warn(`Keeping "${o.configured}". ${s.consequence}`);continue}a.warn(`Your mailbox has no "${o.configured}" folder. ${s.consequence}`),a.detail(`After setup, ask your AI agent to list the mailbox's folders and set ${s.envKey} in .env to the real name.`)}}return i}async function rn(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let i=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(i.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!i.ok)return{ok:!1,message:`Twilio API returned HTTP ${i.status}. Try again or check status.twilio.com.`};let s=await i.json();return s.status&&s.status!=="active"?{ok:!1,message:`Twilio account is in '${s.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:s.friendly_name}}catch(i){return{ok:!1,message:`Could not reach Twilio: ${H(i)}`}}}async function dt(e){return e.provider==="pingen"?qr(e):zr(e)}async function qr(e){if(!e.pingenClientId||!e.pingenClientSecret||!e.pingenOrgId)return{ok:!1,message:"Missing Pingen Client ID, Client Secret, or organisation id."};let t=e.pingenStaging?"https://identity-staging.pingen.com":"https://identity.pingen.com",n=e.pingenStaging?"https://api-staging.pingen.com":"https://api.pingen.com";try{let i=await fetch(`${t}/auth/access-tokens`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:e.pingenClientId,client_secret:e.pingenClientSecret,scope:"letter"})});if(!i.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${i.status}). Check the Client ID and Secret under your organisation's 'API Access' page \u2014 note that staging and production credentials are separate.`};let s=(await i.json()).access_token;if(!s)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let o=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${s}`}});return o.status===403||o.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"}:o.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${o.status}. Try again shortly.`}}catch(i){return{ok:!1,message:`Could not reach Pingen: ${H(i)}`}}}async function zr(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: ${H(t)}`}}}import{spawn as Jr}from"child_process";async function ms(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,i=await Qr(n);if(i.code===0)return{ok:!0};let s=i.stderr.toLowerCase();return s.includes("can't get application")||s.includes("isn't running")||s.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."}:s.includes("(-1728)")||s.includes("not found")||s.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.`}:s.includes("(-1719)")||s.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${i.stderr.trim()||`exit code ${i.code}`}`}}function Qr(e){return new Promise(t=>{let n=Jr("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),i="";n.stderr.on("data",s=>{i+=s.toString()}),n.on("close",s=>t({code:s??1,stderr:i})),n.on("error",s=>t({code:1,stderr:s.message}))})}import{spawn as an}from"child_process";import{existsSync as Xr}from"fs";import{homedir as Zr}from"os";function ea(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var ut=2,hs=2e3,ta=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function gs(e,t){let n=e+`
|
|
34
|
+
`+t;return ta.some(i=>i.test(n))}function ys(e){return new Promise(t=>setTimeout(t,e))}function na(e,t,n){return new Promise(i=>{let s=n.shell?an([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):an(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),o="",r="";s.stdout?.on("data",d=>{let c=d.toString();o+=c,process.stdout.write(c)}),s.stderr?.on("data",d=>{let c=d.toString();r+=c,process.stderr.write(c)}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",d=>i({code:1,stdout:o,stderr:r+d.message}))})}async function jn(e,t,n){let i={code:0,stdout:"",stderr:""};for(let s=0;s<=ut;s++){if(i=await na(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!gs(i.stderr,i.stdout))return i;s<ut&&(a.detail(`${n.label} failed with a transient network error \u2014 retrying (${s+2}/${ut+1})\u2026`),await ys(hs))}return i}function ia(e,t,n){return new Promise(i=>{let s=an(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",d=>{o+=d.toString()}),s.stderr?.on("data",d=>{r+=d.toString()}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",d=>i({code:1,stdout:o,stderr:r+d.message}))})}var sa=[{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 oa(e){let t=`${e.stderr??""}
|
|
35
|
+
${e.stdout??""}`;return sa.find(i=>i.pattern.test(t))?.hint}async function ra(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],s=(await Q())?.command??["python3"],o=async d=>{let c={code:0,stdout:"",stderr:""};for(let p=0;p<=ut;p++){if(c=await ia(s[0],[...s.slice(1),...d],{cwd:e}),c.code===0||!gs(c.stderr,c.stdout))return c;p<ut&&(a.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${ut+1})\u2026`),await ys(hs))}return c},r=await o([...n,"--break-system-packages",...t]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(a.detail("Older pip detected; retrying without --break-system-packages"),r=await o([...n,...t])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function ln(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=ea(),i=process.platform==="win32",s;if(i){let u=et([{label:"your Windows user folder",path:Zr()},{label:"the project folder",path:e}]);if(u.length>0){let g=await new Promise(w=>{let h=an("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),l="",E="";h.stdout?.on("data",T=>{l+=T.toString()}),h.stderr?.on("data",T=>{E+=T.toString()}),h.on("close",T=>w({code:T??1,stdout:l,stderr:E})),h.on("error",T=>w({code:1,stdout:l,stderr:T.message}))}),m=g.code===0?g.stdout.trim():void 0;if(!tt(m,Xr)){let{detail:w,action:h}=nt(u,"install");s=`${w}. ${h}`}}}let o=(u,g)=>{let m=oa(g);if(m){(t.hints??={})[u]=m;return}s&&(u==="npm"||u==="playwright"||u==="patchright")&&!Object.values(t.hints??{}).includes(s)&&((t.hints??={})[u]=s)};a.step("Running npm install (Next.js, Playwright JS, etc.)...");let r=await jn("npm",["install"],{cwd:e,label:"npm install",env:n,shell:i});t.npm=r.code===0?"ok":"failed",r.code!==0&&o("npm",r),a.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let d=await ra(e);t.pip=d.code===0?"ok":"failed",d.code!==0&&o("pip",d),a.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await jn("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:i});t.playwright=c.code===0?"ok":"failed",c.code!==0&&o("playwright",c),a.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await jn("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:i});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&o("patchright",p),t}import{copyFile as aa,access as la}from"fs/promises";import{dirname as ca,join as da}from"path";async function ks(){let e=await Ft("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 Kn(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await ks();if(e.state==="real")return{status:"ok",version:e.version};let t=await Q();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function ua(e){let[t,...n]=e.command,i=await Ft(t,[...n,"-c","import sys; print(sys.executable)"]),s=i.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(i.code!==0||!s)return{ok:!1,reason:"no-exe-path"};let o=da(ca(s),"python3.exe"),r=await la(o).then(()=>!0,()=>!1);if(!r){if(/[\\/]WindowsApps[\\/]/i.test(o))return{ok:!1,reason:"store-python",target:o};try{await aa(s,o)}catch{return{ok:!1,reason:"not-writable",target:o,manualCommand:`copy "${s}" "${o}"`}}}let d=await ks();return{ok:!0,target:o,created:!r,verified:d.state==="real",postState:d.state==="real"?void 0:d.state}}var pa="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 cn(){let e=await Kn();if(e.status!=="broken")return;let t=await ua(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.";a.success(n);return}if(t.ok&&t.postState==="stub"){a.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),a.detail(pa);return}if(t.ok){a.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."),a.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"){a.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"){a.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),a.detail(t.manualCommand??"");return}a.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 fa,spawnSync as ws}from"child_process";import{mkdtemp as ma,rm as ha,rmdir as ga,writeFile as ya,stat as Gn,unlink as ka,mkdir as wa}from"fs/promises";import{createServer as Aa}from"net";import{tmpdir as Ea}from"os";import{join as pt}from"path";function Pa(){return new Promise((e,t)=>{let n=Aa();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let i=n.address(),s=typeof i=="object"&&i?i.port:0;n.close(()=>e(s))})})}function dn(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?ws(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):ws("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function un(e){try{return await Sa(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Sa(e){let t=`klaudius-smoke-${process.pid}`,n=pt(".klaudius",`qa-smoke-${process.pid}.png`),i=pt(e,n),s,o,r=!1;try{s=await ma(pt(Ea(),"klaudius-qa-smoke-")),await ya(pt(s,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let d=await Pa();o=fa("python3",["-m","http.server",String(d),"--directory",s],{stdio:"ignore",shell:!1});let c=!1;o.on("error",()=>{c=!0}),o.on("exit",()=>{c=!0});let p=`http://127.0.0.1:${d}/`,u=!1;for(let E=0;E<24&&!c;E++)try{if((await fetch(p,{signal:AbortSignal.timeout(1e3)})).ok){u=!0;break}}catch{await new Promise(T=>setTimeout(T,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 g=pt(e,".klaudius"),m=await Gn(g).then(()=>!0,()=>!1);await wa(g,{recursive:!0}),r=!m;let w=dn(e,[`-s=${t}`,"open",p]);if(w.status!==0)return{ok:!1,stage:"browser",detail:((w.stderr??"")+(w.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 h=dn(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await Gn(i).catch(()=>null);if((!l||l.size===0)&&(h=dn(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await Gn(i).catch(()=>null)),!l||l.size===0){let E=((h.stderr??"")+(h.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${E?` (${E})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{dn(e,[`-s=${t}`,"close"]),o&&!o.killed&&o.kill(),await ka(i).catch(()=>{}),r&&await ga(pt(e,".klaudius")).catch(()=>{}),s&&await ha(s,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as As,readFile as ba,writeFile as Es}from"fs/promises";import{join as pn}from"path";var He="Bash(claude --bg --permission-mode auto *)";async function Ps(e){let t;try{t=await ba(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 je(e,t){let n=pn(e,".claude"),i=pn(n,"settings.local.json"),s=".claude/settings.local.json";try{await As(n,{recursive:!0});let o=await Ps(i);if(o===null)return a.warn(`${s} isn't valid JSON, so it was left as-is. Fix it and re-run to pre-approve the parallel-run dispatch.`),"skipped";let r=o.permissions&&typeof o.permissions=="object"&&!Array.isArray(o.permissions)?o.permissions:{},d=r.allow,c=Array.isArray(d)?d.filter(u=>typeof u=="string"):[];if(c.includes(t))return"present";c.push(t);let p={...o,permissions:{...r,allow:c}};return await Es(i,JSON.stringify(p,null,2)+`
|
|
36
|
+
`,"utf-8"),"added"}catch(o){return a.warn(`Couldn't write ${s} (${o instanceof Error?o.message:String(o)}). The parallel-run dispatch may occasionally ask for approval.`),"skipped"}}async function ft(e,t){let n=pn(e,".claude");await As(n,{recursive:!0});let i=pn(n,"settings.json"),s=await Ps(i)??{},o=s.enabledMcpjsonServers,r=Array.isArray(o)?o.filter(c=>typeof c=="string"):[];r.includes(t)||r.push(t);let d={...s,enabledMcpjsonServers:r};await Es(i,JSON.stringify(d,null,2)+`
|
|
37
|
+
`,"utf-8")}var bs="0.37.0",V=5,$=!1;function Vn(e){return X(e,Ie,"setup-pending")}function Ra(e){let t=process.env.KLAUDIUS_WHATSAPP_STATE_DIR||X(Ts(),".klaudius","whatsapp");return _a(X(t,e,"auth","creds.json"))}function ve(e){return`npx klaudius@latest init ${hn(mt(e))}`}function mt(e){if(process.platform==="win32")return e;let t=Ts();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function va(e){let t=[];try{let i=(await _s(e,{withFileTypes:!0})).filter(s=>s.isDirectory()&&!s.name.startsWith(".")).slice(0,200);for(let s of i){let o=X(e,s.name);if(!await qn(X(o,".env")))continue;let r=await qn(X(o,".klaudius","manifest.json"));if(t.push({path:o,finished:r}),t.length>=3)break}}catch{}return t}async function qn(e){try{return await Yn(e),!0}catch{return!1}}function hn(e){return/\s/.test(e)?`"${e}"`:e}function Ee(e,t,n){a.blank(),a.error(`${t} validation failed ${V} times in a row. Pausing setup so you don't get stuck in a loop.`),a.detail(`Last error: ${n}`),a.blank(),a.detail("Your credentials are saved in `.env`. Two ways forward:"),a.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),a.blank(),console.log(` ${A.cyan(ve(e))}`),a.blank(),a.detail(` (Your .env is at ${mt(X(e,".env"))} \u2014 open it in any text editor.)`),a.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),a.blank(),process.exit(1)}async function Is(e){$=!!e.answers;let t=e.target??".",n=Ia(t)?t:Ta(process.cwd(),t),i=Na(n);i&&(a.error("Klaudius can't be installed inside a protected system folder."),a.detail(`Path: ${n}`),a.detail(`Reason: ${i}`),a.blank(),a.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),a.blank(),process.platform==="win32"?(a.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${A.cyan("cd $HOME\\Documents")}`),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`)):(a.detail("For example:"),console.log(` ${A.cyan("cd ~/Documents")}`),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`)),a.blank(),process.exit(1)),process.platform==="win32"&&$a()&&(a.warn("You appear to be running in an elevated (Administrator) PowerShell."),a.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."),a.blank()),await nn("init",bs);let s=await Oa(n),o=s.kind==="scaffolded"&&!!e.answers&&await qn(Vn(n));if(s.kind==="scaffolded"&&!o){$&&_("folder","There's already a Klaudius project in this folder. Choose a new folder name, or open that project instead."),a.blank(),a.warn(`Found an existing Klaudius project at ${A.bold(n)}.`),a.detail("(Your .env and project files are in place.)"),a.blank(),s.nodeModulesMissing?(a.detail("It looks like a previous setup didn't finish installing dependencies."),a.detail("To pick up where it left off, run:"),a.blank(),n!==process.cwd()&&console.log(` ${A.cyan(`cd ${hn(t)}`)}`),console.log(` ${A.cyan("npx klaudius@latest install")} ${A.dim("# retries npm + pip + browsers; idempotent")}`),a.blank(),a.detail("Then verify with:"),a.blank(),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# checks Node / Python / installers / credentials")}`),a.blank()):(a.detail("Everything is scaffolded and dependencies look installed."),a.detail("Pick the action you wanted:"),a.blank(),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${A.cyan("npx klaudius@latest configure")} ${A.dim("# change a credential / API key")}`),console.log(` ${A.cyan("npx klaudius@latest update")} ${A.dim("# pull the latest skills, scripts, lessons")}`),a.blank()),a.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),a.blank();return}if(s.kind==="occupied"){$&&_("folder","This folder already has files in it. Choose an empty folder or a new name.");let y=t===".",f=await va(n);if(f.length>0){a.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),a.detail(`You're in: ${mt(n)}`),a.blank();for(let k of f)a.detail(k.finished?`Found a finished project at ${mt(k.path)}. To work in it:`:`Found an unfinished setup at ${mt(k.path)}. To pick up where it left off:`),a.blank(),k.finished?(console.log(` ${A.cyan(`cd ${mt(k.path)}`)}`),console.log(` ${A.cyan("claude")} ${A.dim("# open Claude Code in the project")}`)):console.log(` ${A.cyan(ve(k.path))} ${A.dim("# then pick Resume")}`),a.blank();process.exit(1)}a.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),a.detail(`Path: ${n}`),a.detail(`Contains: ${s.entries.slice(0,5).join(", ")}${s.entries.length>5?`, \u2026 (+${s.entries.length-5} more)`:""}`),a.blank(),y?(a.detail("Two ways forward:"),a.blank(),a.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`),a.blank(),a.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${A.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(a.detail(`The folder '${t}' already exists and isn't empty.`),a.detail("Either pick a different name:"),console.log(` ${A.cyan(`npx klaudius@latest init ${t}-2`)}`),a.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=null;e.answers&&(r=await Gt(e.answers),Kt(r),a.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let d=r??{},c={};if(r){let y=await Bn(X(n,".env"),"utf-8").catch(()=>null);y&&(c=J(y),r={...Object.fromEntries(Object.entries(c).filter(([k])=>!Oi.includes(k))),...r})}let p=e.license??r?.KLAUDIUS_LICENSE_KEY;$&&(!p||p.trim().length===0)&&_("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let u=await La(p),g=v.spinner();g.start("Validating license");let m=await as(u);m.ok||(g.stop(`License invalid: ${m.reason??"unknown"}`,2),a.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),$&&_("license",`${m.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)),g.stop(`License valid (${m.tier??"core"} tier)`);let w=await it();w.ok||(a.error(w.message??"Python version check failed."),a.blank(),a.detail(`Once you've installed Python 3.10+, re-run the same command: ${ve(n)}`),process.exit(1)),await cn();let h=we();h.ok||(a.error(h.message??"Node.js version check failed."),a.blank(),a.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${ve(n)}`),process.exit(1));let l,E=!1;if(r){let y=at(r);y||_("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=xi(y,d,c),a.success("Loaded setup answers (non-interactive mode)");let f=c.AI_AGENT==="codex"?"codex":"claude-code";if(o&&f!==(l.aiAgent??"claude-code")){let k=P=>P==="codex"?"Codex":"Claude Code";_("folder",`This folder was set up for ${k(f)}, so it can't carry on as ${k(l.aiAgent??"claude-code")}. Give the folder a different name to set up fresh, or switch back.`)}}else if(s.kind==="partial")if(await xa(n)==="resume"){let f=await Bn(s.envPath,"utf-8"),k=at(J(f));k?(a.success("Resuming with values from your existing .env"),a.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=k,E=!0,l.aiPlan||(l=await W(l,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
|
|
38
|
+
runs on. It sets the QA-pass default (and, on the smaller ChatGPT plans, the model).`}))):(a.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await W())}else{let f=await Bn(s.envPath,"utf-8"),k=at(J(f));l=await W(k??{})}else l=await W();l.licenseKey=u,await q(n,l),E||(a.success("Saved .env"),a.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),a.blank();for(let y=1;;y++){let f=v.spinner();f.start("Validating Supabase credentials");let k=await $e({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(k.ok){f.stop("Supabase credentials accepted");break}f.stop(k.message??"Supabase check failed",2),y>=V&&Ee(n,"Supabase",k.message??"Supabase check failed");let P=k.message??"Supabase check failed";a.blank(),$&&_("supabase",P),a.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${y+1} of ${V})`),a.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
39
|
+
${P}
|
|
38
40
|
|
|
39
41
|
Re-enter the URL, secret key, or PAT below. Press Enter on any
|
|
40
|
-
field to keep what's already there.`}),await
|
|
41
|
-
${
|
|
42
|
+
field to keep what's already there.`}),await q(n,l)}if(a.blank(),l.deployProvider==="cloudflare")for(let y=1;;y++){let f=v.spinner();f.start("Validating Cloudflare token + account");let k=await De({token:l.cloudflareApiToken??"",accountId:l.cloudflareAccountId??""});if(k.ok){f.stop(`Cloudflare credentials accepted (${k.projectCount??0} existing Pages project${k.projectCount===1?"":"s"})`);break}f.stop(k.message??"Cloudflare check failed",2),y>=V&&Ee(n,"Cloudflare",k.message??"Cloudflare check failed");let P=k.message??"Cloudflare check failed";a.blank(),$&&_("cloudflare",P),a.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${y+1} of ${V})`),a.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
|
|
43
|
+
${P}
|
|
42
44
|
|
|
43
45
|
Re-enter the API token or Account ID below. The token needs the
|
|
44
46
|
"Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
|
|
45
|
-
the current value.`}),await
|
|
46
|
-
${
|
|
47
|
+
the current value.`}),await q(n,l)}else if(l.deployProvider==="netlify")for(let y=1;;y++){let f=v.spinner();f.start("Validating Netlify token");let k=await Fe({token:l.netlifyAuthToken??""});if(k.ok){f.stop(k.accountSlug?`Netlify token accepted (team: ${k.accountSlug})`:"Netlify token accepted");break}f.stop(k.message??"Netlify check failed",2),y>=V&&Ee(n,"Netlify",k.message??"Netlify check failed");let P=k.message??"Netlify check failed";a.blank(),$&&_("netlify",P),a.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${y+1} of ${V})`),a.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"netlify",banner:`Netlify rejected the token:
|
|
48
|
+
${P}
|
|
47
49
|
|
|
48
50
|
Generate a new token at
|
|
49
51
|
https://app.netlify.com/user/applications#personal-access-tokens
|
|
50
|
-
and paste it below. Press Enter to keep the current value.`}),await
|
|
51
|
-
`);
|
|
52
|
-
${
|
|
52
|
+
and paste it below. Press Enter to keep the current value.`}),await q(n,l)}else if(l.deployProvider==="selfhost")for(let y=1;;y++){let f=Xe(l.selfhostDeployTarget??""),k=Ze(l.selfhostUrlTemplate??"");if(!f&&!k){a.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let P=[f&&`SELFHOST_DEPLOY_TARGET: ${f}`,k&&`SELFHOST_URL_TEMPLATE: ${k}`].filter(Boolean).join(`
|
|
53
|
+
`);y>=V&&Ee(n,"Self-host",P),a.blank(),$&&_("selfhost",P),a.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${y+1} of ${V})`),a.blank(),l=await W(l,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
|
|
54
|
+
${P}
|
|
53
55
|
|
|
54
|
-
Re-enter them below. Press Enter on a field to keep its current value.`}),await
|
|
56
|
+
Re-enter them below. Press Enter on a field to keep its current value.`}),await q(n,l)}else for(let y=1;;y++){let f=v.spinner();f.start("Validating Vercel token");let k=await Me(l.vercelToken??"");if(k.ok){f.stop(k.username?`Vercel token accepted (signed in as ${k.username})`:"Vercel token accepted");break}f.stop(k.message,2);let P=k.message,D=k.kind==="rejected"||k.kind==="scope",S=D?`${P} Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration).`:P;y>=V&&Ee(n,"Vercel",S),a.blank(),$&&_("vercel",S),a.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${y+1} of ${V})`),a.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"vercel",banner:D?`${P}
|
|
55
57
|
|
|
56
58
|
Create a new token at https://vercel.com/account/settings/tokens
|
|
57
59
|
(Scope: Full Account, Expiration: No Expiration) and paste it
|
|
58
|
-
below. Press Enter to keep the current value.`:`${
|
|
60
|
+
below. Press Enter to keep the current value.`:`${P}
|
|
59
61
|
|
|
60
62
|
Press Enter to keep the current value and try again, or paste a
|
|
61
|
-
different token.`}),await
|
|
62
|
-
${
|
|
63
|
+
different token.`}),await q(n,l)}a.blank();for(let y=1;;y++){let f=ke(l.googlePlacesApiKey??""),k=v.spinner();k.start("Validating Google Places API key");let P=await Ue(l.googlePlacesApiKey??"");if(P.ok){if(k.stop("Google Places API key accepted"),f.changed){if(f.repairs.length>0){a.blank(),a.warn("Corrected look-alike characters in your Google Places API key:");for(let S of f.repairs)a.detail(` ${S}`);a.detail("These come from keys that were transcribed rather than copied."),a.detail("Google accepted the corrected key, and .env now holds it.")}l.googlePlacesApiKey=f.value,await q(n,l)}break}k.stop(P.message??"Google Places check failed",2),y>=V&&Ee(n,"Google Places",P.message??"Google Places check failed");let D=P.message??"Google Places check failed";a.blank(),$&&_("google-places",D),a.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${y+1} of ${V})`),a.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"google-places",banner:`Google rejected the key:
|
|
64
|
+
${D}
|
|
63
65
|
|
|
64
66
|
Generate (or fix) the key at https://console.cloud.google.com
|
|
65
|
-
and paste it below. Press Enter to keep the current value.`}),await
|
|
67
|
+
and paste it below. Press Enter to keep the current value.`}),await q(n,l)}let T=!1;if($&&l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAuth!=="oauth-microsoft"){let y=[["email address",l.emailAddress],["password",l.emailPassword],["SMTP host",l.emailSmtpHost],["IMAP host",l.emailImapHost]].filter(([,P])=>!P).map(([P])=>P),f=[["SMTP port",l.emailSmtpPort],["IMAP port",l.emailImapPort]].filter(([,P])=>!P).map(([P])=>P),k=[...y.length>0?[`the ${y.join(", ")} ${y.length===1?"is":"are"} missing`]:[],...f.length>0?[`the ${f.join(" and ")} ${f.length===1?"isn't a number":"aren't numbers"}`]:[]];k.length>0&&_("email",`Email outreach is switched on, but ${k.join(", and ")}. Fill ${k.length===1&&y.length+f.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){a.blank();let y=0,f=!1,k;for(;!f;){y++;let P=v.spinner();P.start("Validating email credentials (SMTP + IMAP)");let D=l.emailProvider&&l.emailProvider!=="custom"?l.emailProvider:pe(l.emailSmtpHost),S=D?te[D]:void 0,L=await me({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:S?.usesAccountPassword,knownProvider:!!S,sentFolder:(l.emailSentFolder??"").trim()||"Sent",draftsFolder:(l.emailDraftsFolder??"").trim()||"Drafts"});if(L.ok){P.stop("Email credentials accepted (SMTP + IMAP)"),await ct(L,l,{nonInteractive:$,onCancel:()=>{v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
66
68
|
|
|
67
|
-
${
|
|
68
|
-
`),process.exit(0)}})&&await
|
|
69
|
+
${ve(n)}
|
|
70
|
+
`),process.exit(0)}})&&await q(n,l);break}P.stop(L.message??"Email check failed",2);let ie=`${D}\0${l.emailAddress}\0${l.emailPassword}`;if(S&&L.failureKind!=="network"&&k!==ie){k=ie;let Ve=Nt(D,l.emailSmtpHost,l.emailImapHost),ye,fi=0;if(Ve.length>0){a.blank(),a.warn(`That server rejected the login. ${S.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let de of Ve){let En=v.spinner();En.start(`Trying ${de.label} (${de.smtpHost})`);let Pn=await me({emailAddress:l.emailAddress,emailLogin:l.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:l.emailPassword,emailSmtpHost:de.smtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:de.imapHost,emailImapPort:l.emailImapPort});if(Pn.ok){En.stop(`${de.label}: your login works here (${de.smtpHost})`),ye=de;break}Pn.failureKind!=="network"&&fi++,En.stop(Pn.failureKind==="network"?`${de.label}: unreachable`:`${de.label}: rejected too`,2)}}if(ye){if(a.blank(),a.success("Found it \u2014 your password was right all along; the server was the only problem."),$){a.detail(`Non-interactive: using the working ${ye.label} servers automatically.`),l.emailSmtpHost=ye.smtpHost,l.emailImapHost=ye.imapHost,await q(n,l);continue}let de=await v.confirm({message:`Use the ${ye.label} servers (${ye.smtpHost} / ${ye.imapHost})?`,initialValue:!0});if(v.isCancel(de)&&(v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
69
71
|
|
|
70
|
-
${
|
|
71
|
-
`),process.exit(0)),
|
|
72
|
+
${ve(n)}
|
|
73
|
+
`),process.exit(0)),de){l.emailSmtpHost=ye.smtpHost,l.emailImapHost=ye.imapHost,await q(n,l);continue}}else Ve.length>0&&(a.blank(),fi===0?a.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."):S.noAltWorkedHint&&a.warn(S.noAltWorkedHint))}let be=L.message??"Email check failed";a.blank(),a.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),a.detail("You can skip it now and wire it up later from inside the project."),a.blank(),$&&_("email",be);let ae=await v.select({message:`What would you like to do? ${A.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:y>=3?"skip":y>=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(v.isCancel(ae)&&(v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
72
74
|
|
|
73
|
-
${
|
|
74
|
-
`),process.exit(0)),
|
|
75
|
-
${
|
|
75
|
+
${ve(n)}
|
|
76
|
+
`),process.exit(0)),ae==="skip"){l.outreachChannels=(l.outreachChannels??[]).filter(Ve=>Ve!=="email"),l.outreachPriority=(l.outreachPriority??[]).filter(Ve=>Ve!=="email"),l.outreachChannels.length===0&&(l.outreachEnabled=!1),await q(n,l),T=!0,a.success("Skipped email for now. Setup will continue."),l.outreachEnabled?a.detail("Outreach will use your other channel(s); email stays off until it's fixed."):a.detail("Automated outreach is off until email is fixed \u2014 everything else works."),f=!0;break}ae==="edit"&&(a.blank(),l=await W(l,{onlySection:"email",banner:`${L.failedAt==="imap"?"IMAP":"SMTP"} check failed:
|
|
77
|
+
${be}
|
|
76
78
|
|
|
77
79
|
Re-enter the email address, app password, or server details below.
|
|
78
80
|
Press Enter on any field to keep its current value.
|
|
79
81
|
|
|
80
82
|
Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
|
|
81
|
-
at the "Server settings" question.`}),await
|
|
82
|
-
${
|
|
83
|
+
at the "Server settings" question.`}),await q(n,l))}}if($&&l.outreachEnabled&&l.outreachChannels?.includes("sms")){let y=Bt(l);y&&_("sms",y)}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="twilio"&&l.twilioAccountSid&&l.twilioAuthToken){a.blank();for(let y=1;;y++){let f=v.spinner();f.start("Validating Twilio credentials");let k=await rn({accountSid:l.twilioAccountSid,authToken:l.twilioAuthToken});if(k.ok){f.stop(k.friendlyName?`Twilio credentials accepted (${k.friendlyName})`:"Twilio credentials accepted");break}f.stop(k.message??"Twilio check failed",2),y>=V&&Ee(n,"Twilio",k.message??"Twilio check failed");let P=k.message??"Twilio check failed";a.blank(),$&&_("sms",P),a.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${y+1} of ${V})`),a.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"sms",banner:`Twilio rejected the credentials:
|
|
84
|
+
${P}
|
|
83
85
|
|
|
84
86
|
Re-enter the Account SID or Auth Token below.
|
|
85
|
-
Press Enter on any field to keep its current value.`}),await
|
|
86
|
-
${
|
|
87
|
+
Press Enter on any field to keep its current value.`}),await q(n,l)}}if($&&l.outreachEnabled&&l.outreachChannels?.includes("letter")){let y=Vt(l);y&&_("letter",y)}if(l.outreachEnabled&&l.outreachChannels?.includes("letter")&&l.letterProvider){a.blank();for(let y=1;;y++){let f=v.spinner();f.start("Validating letter provider credentials");let k=await dt({provider:l.letterProvider,pingenClientId:l.pingenClientId,pingenClientSecret:l.pingenClientSecret,pingenOrgId:l.pingenOrgId,postgridApiKey:l.postgridApiKey});if(k.ok){f.stop(k.friendlyName?`Letter provider credentials accepted (${k.friendlyName})`:"Letter provider credentials accepted");break}f.stop(k.message??"Letter provider check failed",2),y>=V&&Ee(n,"Letter provider",k.message??"Letter provider check failed");let P=k.message??"Letter provider check failed";a.blank(),$&&_("letter",P),a.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${y+1} of ${V})`),a.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"letter",banner:`The letter provider rejected the credentials:
|
|
88
|
+
${P}
|
|
87
89
|
|
|
88
90
|
Re-enter them below.
|
|
89
|
-
Press Enter on any field to keep its current value.`}),await
|
|
91
|
+
Press Enter on any field to keep its current value.`}),await q(n,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="imessage"&&l.testPhone){a.blank();for(let y=1;;y++){let f=v.spinner();f.start("Validating iMessage setup (sending a test ping)");let k=await ms({testPhone:l.testPhone});if(k.ok){if(f.stop("iMessage dispatched (check your phone for the test ping)"),$){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 D=await v.confirm({message:"Did the test message actually arrive on your phone?",initialValue:!0});if(v.isCancel(D)&&(v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
90
92
|
|
|
91
|
-
${
|
|
92
|
-
`),process.exit(0)),
|
|
93
|
+
${ve(n)}
|
|
94
|
+
`),process.exit(0)),D)break;f.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),y>=V&&Ee(n,"iMessage","Test message dispatched but never delivered"),a.blank(),a.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."),a.blank(),l=await W(l,{onlySection:"sms",banner:`The test message was dispatched but never arrived on your phone.
|
|
93
95
|
Re-check the number below (international format with a leading +).
|
|
94
|
-
Press Enter on any field to keep its current value.`}),await
|
|
95
|
-
${
|
|
96
|
+
Press Enter on any field to keep its current value.`}),await q(n,l);continue}f.stop(k.message??"iMessage check failed",2),y>=V&&Ee(n,"iMessage",k.message??"iMessage check failed");let P=k.message??"iMessage check failed";a.blank(),$&&_("sms",P),a.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${y+1} of ${V})`),a.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"sms",banner:`iMessage check failed:
|
|
97
|
+
${P}
|
|
96
98
|
|
|
97
99
|
Either fix the underlying issue (sign in to Messages.app, configure
|
|
98
100
|
Text Message Forwarding) and press Enter through, or change SMS
|
|
99
|
-
provider to Twilio.`}),await
|
|
101
|
+
provider to Twilio.`}),await q(n,l)}}if($){let y=Yt(l);y&&_("notifications",y)}if((l.notifyChannel??"telegram")==="telegram"&&l.telegramBotToken&&l.telegramChatId){a.blank();let y=0,f=!1;for(;!f;){y++;let k=v.spinner();k.start("Validating Telegram bot + chat (sending a test ping)");let P=await $t({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(P.ok){k.stop(P.botHandle?`Telegram bot ${P.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),f=!0;break}k.stop(P.message??"Telegram check failed",2);let D=P.message??"Telegram check failed";a.blank(),a.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),a.blank(),$&&_("notifications",D);let S=await v.select({message:`What would you like to do? ${A.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:y>=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(v.isCancel(S)&&(v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
100
102
|
|
|
101
|
-
${
|
|
102
|
-
`),process.exit(0)),
|
|
103
|
-
${
|
|
103
|
+
${ve(n)}
|
|
104
|
+
`),process.exit(0)),S==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await q(n,l),a.success("Skipped Telegram. Setup will continue."),a.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`."),f=!0;break}if(S==="edit"&&(a.blank(),l=await W(l,{onlySection:"notifications",banner:`Telegram check failed:
|
|
105
|
+
${D}
|
|
104
106
|
|
|
105
107
|
Re-enter the bot token or chat_id below.
|
|
106
|
-
Press Enter on any field to keep its current value.`}),await
|
|
107
|
-
`,"utf-8")),await
|
|
108
|
+
Press Enter on any field to keep its current value.`}),await q(n,l),(l.notifyChannel??"telegram")!=="telegram"||!l.telegramBotToken||!l.telegramChatId)){a.success("Skipped Telegram. Setup will continue."),f=!0;break}}}if(a.blank(),o)a.detail("Picking up the setup that didn't finish in this folder \u2014 your files are already here.");else{let y=v.spinner();y.start("Downloading Klaudius template");let f;try{f=(await en({licenseKey:u,machineId:_t(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:n})).filesExtracted,y.stop(`Downloaded ${f} files into ${A.bold(n)}`)}catch(P){y.stop(P.message,2);let D=l.aiAgent==="codex"?".codex/config.toml":".mcp.json";a.detail(`Your .env / ${D} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await mn(X(n,"clients"),{recursive:!0});let k=await Yi(n);$&&(await mn(X(n,Ie),{recursive:!0}),await fn(Vn(n),`${new Date().toISOString()}
|
|
109
|
+
`,"utf-8")),await Le(n,Hi(bs,k)),a.success("Wrote .klaudius/manifest.json");try{await tn(n,n,Object.keys(k))}catch{}}let I=!1,O="",N="";if(e.skipSchema)a.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),a.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{a.blank();let y=v.spinner();y.start("Applying schema to Supabase");let f=await lt({projectRoot:n,pat:l.supabasePat,projectRef:l.supabaseProjectRef});f.ok?y.stop("Schema applied (or already present)"):(y.stop(f.message??"Schema apply failed",2),I=!0,O=f.message?.trim()||"the database refused the request",N=`https://supabase.com/dashboard/project/${l.supabaseProjectRef}/sql/new`)}let b=[],C={};if(e.skipInstall)a.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{a.blank(),a.heading("Installing dependencies");let y=await ln(n);if(a.detail(`npm: ${y.npm}, pip: ${y.pip}, playwright: ${y.playwright}, patchright: ${y.patchright}`),y.npm==="failed"&&b.push("npm"),y.pip==="failed"&&b.push("pip"),y.playwright==="failed"&&b.push("playwright"),y.patchright==="failed"&&b.push("patchright"),C=y.hints??{},y.npm!=="failed"&&y.playwright!=="failed"){a.step("Checking the QA screenshot chain (serving a test page and screenshotting it)\u2026");let f=await un(n);f.ok?a.success("QA screenshot chain verified (local page served and screenshotted)."):(a.warn(`QA screenshot chain check failed${f.stage?` (${f.stage})`:""}: ${f.detail??"unknown"}`),f.remediation&&a.detail(f.remediation))}}let M=l.outreachEnabled&&l.outreachPriority?.includes("whatsapp")&&(l.whatsappAccounts?.length??0)>0,G=!e.skipInstall&&!b.includes("npm"),U=(l.whatsappAccounts??[]).filter(y=>!(o&&Ra(y)));if(M&&G&&U.length>0){a.blank(),a.heading("Linking WhatsApp accounts"),console.log(A.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
|
|
108
110
|
phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
|
|
109
|
-
Link a Device, and point it at the QR shown in this terminal.`)),a.blank();for(let
|
|
111
|
+
Link a Device, and point it at the QR shown in this terminal.`)),a.blank();for(let y of U){console.log(A.cyan(`Pairing WhatsApp account '${y}'...`)),$||console.log(A.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${y})`));let f=Wn(process.execPath,["scripts/whatsapp.mjs","pair","--account",y],{cwd:n,stdio:"inherit"});f.status===0?a.detail(`Paired '${y}'.`):(console.log(A.yellow(`'${y}' did not pair (exit ${f.status??"signalled"}).`+($?"":" You can finish later via:"))),$||console.log(A.cyan(` npx klaudius@latest pair-whatsapp --label ${y}`))),a.blank()}}else if(M&&!G&&(a.blank(),console.log(A.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),!$)){console.log(A.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let y of l.whatsappAccounts)console.log(A.cyan(` npx klaudius@latest pair-whatsapp --label ${y}`))}let x=l.emailAuth==="oauth-microsoft"&&l.outreachEnabled&&l.outreachChannels?.includes("email"),R=!e.skipInstall&&!b.includes("pip"),Y=o&&await Qt(n,l.emailAddress??""),re=y=>{console.log(A.dim("Connect it any time from the project folder with:")),console.log(A.cyan(` ${y?y.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(A.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(x&&Y)a.blank(),a.detail("Your Outlook mailbox is already connected \u2014 leaving that sign-in alone.");else if(x&&R){a.blank(),a.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(A.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
|
|
110
112
|
password. Your browser will open to Microsoft's sign-in page \u2014
|
|
111
113
|
sign in as `+(l.emailAddress??"your outreach mailbox")+` and approve.
|
|
112
114
|
(No browser on this machine? It falls back to a short code you can
|
|
113
|
-
enter from any device.)`)),a.blank();let
|
|
114
|
-
|
|
115
|
-
`:"",k=l.aiAgent==="codex"?"codex":"claude",w=l.aiAgent==="codex"?"Codex":"Claude Code",b=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";S.length>0&&(console.log(g.dim(`Easiest fix \u2014 let ${w} finish it for you:`)),a.blank(),m&&process.stdout.write(m),console.log(` ${g.cyan(k)} ${g.dim(`# open ${w} in this folder`)}`),console.log(g.dim(" Then paste:")),console.log(g.cyan(` "Finish my Klaudius install \u2014 ${S.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),a.blank(),console.log(g.dim(` (Don't have ${w} yet? Install with: \`${b}\`)`)),a.blank(),console.log(g.dim("Or do it yourself:")),a.blank(),m&&process.stdout.write(m),console.log(` ${g.cyan("npx klaudius@latest install")} ${g.dim("# retry the failing installers")}`),console.log(` ${g.cyan("npx klaudius@latest doctor")} ${g.dim("# verify everything")}`),a.blank()),x&&(console.log(g.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${g.cyan(L)}`),console.log(g.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),a.blank()),S.includes("pip")&&!I.pip&&(console.log(g.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(g.dim(`Python 3.10+. Install a newer one from ${Zr()}`)),console.log(g.dim("and open a fresh Terminal before retrying.")),a.blank());let W=["npm","playwright","patchright"].filter(q=>S.includes(q)&&!I[q]);if(W.length>0){let q=W.length===1?"keeps":"keep";console.log(g.dim(`If ${W.join(" / ")} ${q} failing with network errors (ECONNRESET,`)),console.log(g.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(g.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),a.blank()}if(R&&(console.log(g.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${w}`)),console.log(g.dim("to finish setting it up \u2014 your email details are saved in .env.")),a.blank()),console.log(g.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),a.blank(),G){let q=[];x&&q.push(`Couldn't create the database tables: ${v.replace(/[:.\s]+$/,"")}. Check the database access token on the Database step.`);let Ue=S.filter(be=>be==="playwright"||be==="patchright"),ct=S.filter(be=>be!=="playwright"&&be!=="patchright");ct.length>0&&q.push(`Couldn't finish installing ${ct.join(", ")}. The install output says why.`),Ue.length>0&&q.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."),q.push("Then try again \u2014 setup carries on from here. If it keeps failing, email hello@klaudius.dev with the last few lines."),Q(x&&S.length===0?"supabase":"install",q.join(`
|
|
116
|
-
`))}return}if(await ts(Tn(n),{force:!0}),await ts(_n(n),{force:!0}),ea(l,n,e.target),R){let m=l.aiAgent==="codex"?"Codex":"Claude Code";console.log(g.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(g.dim(`Your details are saved in .env. To finish it, ask ${m}:`)),console.log(g.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(g.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(g.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(g.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(g.cyan(' and send a test email to my own address to confirm."')),l.outreachEnabled&&(l.outreachChannels??[]).length>0&&(a.blank(),console.log(g.yellow(`Note: your other channel(s) \u2014 ${(l.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),a.blank()}}async function J(e,t){await on(e,{recursive:!0}),await gt(X(e,".env"),Nt(t),"utf-8"),t.aiAgent==="codex"?(await on(X(e,".codex"),{recursive:!0}),await gt(X(e,".codex","config.toml"),Dt(t),"utf-8")):(await gt(X(e,".mcp.json"),Mt(t),"utf-8"),await sn(e,"supabase"),await tt(e,et))}async function qr(e){try{(await In(e)).isDirectory()||(a.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ss(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),s=n.every(c=>i.has(c)),o=n.includes(".env"),r=t.includes(".klaudius");if(s&&o&&!r)return{kind:"partial",envPath:X(e,".env")};if(r&&o){let c=!0;try{c=!(await In(X(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function zr(e){a.blank(),a.warn(`Found a partial setup at ${g.bold(e)}.`),a.detail(`A previous init wrote ${g.bold(".env")} but didn't finish scaffolding.`),a.blank();let t=await T.select({message:`How would you like to proceed? ${g.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 T.isCancel(t)&&(T.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Jr(e){if(e&&e.trim().length>0)return e;T.intro("Klaudius");let t=await T.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 T.isCancel(t)&&(T.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Qr(e){let t=Br(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let i of n)if(t.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function Xr(){if(process.platform!=="win32")return!1;try{return Cn("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Zr(){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 ea(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",s=e.aiAgent==="codex"?"Codex":"Claude Code";if(T.outro(g.green(g.bold("Project ready."))),e.aiPlan){let o=(e.qaPhase??je(e.aiPlan))==="off";console.log(`${g.bold("Your plan:")} ${Ke[e.aiPlan]}`),console.log(g.dim(o?` \u2192 QA pass off${He.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(g.dim(` Change it any time: ask ${s} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),a.blank()}if(console.log(g.bold("Next steps:")),a.blank(),t!==process.cwd()&&n){let o=`cd ${an(n)}`;console.log(` ${g.cyan(o)}${" ".repeat(Math.max(1,27-o.length))}${g.dim("# go into your project folder")}`)}console.log(` ${g.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${g.dim(`# opens ${s} in this project`)}`),a.blank(),console.log(g.bold(`Some starter prompts for ${s}:`)),a.blank(),console.log(` ${g.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${g.cyan(`I know I'm ready to start using Klaudius."`)}`),a.blank(),console.log(` ${g.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),a.blank(),console.log(` ${g.cyan('"Run the pipeline for one client."')}`),console.log(g.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.")),a.blank(),e.aiAgent!=="codex"&&(console.log(g.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(g.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),a.blank())}import{access as ta,readFile as na}from"fs/promises";import{join as Rn,resolve as ia}from"path";import de from"picocolors";async function ls(e){let t=e.target?ia(process.cwd(),e.target):process.cwd(),n=await as(Rn(t,".env")),i=await as(Rn(t,"package.json"));(!n||!i)&&(a.error("This doesn't look like a Klaudius project."),a.detail(`Path: ${t}`),n||a.detail("Missing: .env"),i||a.detail("Missing: package.json"),a.blank(),a.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),a.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let s="claude-code";try{te(await na(Rn(t,".env"),"utf-8")).AI_AGENT==="codex"&&(s="codex")}catch{}a.heading("Installing dependencies");let o=await Xt(t);a.blank(),a.detail(`npm: ${o.npm}, pip: ${o.pip}, playwright: ${o.playwright}, patchright: ${o.patchright}`);let r=[];if(o.npm==="failed"&&r.push("npm"),o.pip==="failed"&&r.push("pip"),o.playwright==="failed"&&r.push("playwright"),o.patchright==="failed"&&r.push("patchright"),r.length===0){a.blank(),console.log(de.green(de.bold("All dependencies installed."))),console.log(de.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),a.blank();return}a.blank(),console.log(de.yellow(de.bold(`${r.join(", ")} still failing.`))),a.blank();for(let[d,y]of Object.entries(o.hints??{}))console.log(de.yellow(`Likely cause of ${d} failure:`)),console.log(de.dim(` ${y}`)),a.blank();let c=s==="codex"?"codex":"claude",u=s==="codex"?"Codex":"Claude Code",p=s==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(de.dim("Options:")),console.log(de.dim(` \u2022 Open ${u} in this folder (\`${c}\`) and paste:`)),console.log(de.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(de.dim(` (Don't have ${u} yet? Install with: \`${p}\`)`)),console.log(de.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(de.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),a.blank(),process.exitCode=1}async function as(e){try{return await ta(e),!0}catch{return!1}}import{readFile as sa,writeFile as vn,access as oa}from"fs/promises";import{join as st}from"path";import*as ue from"@clack/prompts";import Ce from"picocolors";import{mkdir as ra}from"fs/promises";import{spawnSync as cs}from"child_process";async function ds(e){let t=e.projectRoot??process.cwd(),n=st(t,".env"),i=st(t,".mcp.json"),s=st(t,".codex","config.toml"),o=await xn(st(t,".klaudius","manifest.json")),r=await xn(n);!o&&!r&&(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ve();c.ok||(a.error(c.message??"Node.js version check failed."),a.blank(),a.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let u={};try{let h=await sa(n,"utf-8");u=te(h)}catch{a.warn("No .env found. Starting from an empty configuration.")}let p=fi(u);Object.keys(u).length>0&&(p.pipelineModes??=["classic"]),ue.intro("Reconfigure Klaudius"),a.detail("Press Enter on any prompt to keep its current value."),a.blank();let d=await z(p),y=p.aiAgent??"claude-code";if(d.aiAgent&&d.aiAgent!==y&&(a.error(`Switching AI coding agent (${y} \u2192 ${d.aiAgent}) isn't supported via configure.`),a.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),a.blank(),console.log(` ${Ce.cyan("npx klaudius@latest init <new-folder>")} ${Ce.dim("# pick the new agent in the wizard")}`),a.blank(),a.detail(".env is unchanged."),process.exit(1)),d.supabaseUrl!==u.SUPABASE_URL||d.supabaseServiceKey!==u.SUPABASE_SERVICE_KEY){a.heading("Re-validating Supabase credentials");let h=await We({url:d.supabaseUrl,serviceKey:d.supabaseServiceKey});h.ok||(a.error(h.message??"Supabase check failed"),a.warn("Aborting. .env not modified."),process.exit(1)),a.success("Supabase credentials accepted")}let f=la(d,u);if(f==="vercel"){let h=ue.spinner();h.start("Validating Vercel token");let l=await qe(d.vercelToken??"");l.ok?h.stop(l.username?`Vercel token accepted (signed in as ${l.username})`:"Vercel token accepted"):(h.stop(l.message,2),a.warn("Writing the token exactly as you entered it \u2014 not verified."),a.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(f==="cloudflare"){let h=ue.spinner();h.start("Validating Cloudflare token + account");let l=await ze({token:d.cloudflareApiToken??"",accountId:d.cloudflareAccountId??""});l.ok?h.stop("Cloudflare credentials accepted"):(h.stop(l.message??"Cloudflare check failed",2),a.warn("Writing the credentials exactly as you entered them \u2014 not verified."),a.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(f==="netlify"){let h=ue.spinner();h.start("Validating Netlify token");let l=await Je({token:d.netlifyAuthToken??""});l.ok?h.stop(l.accountSlug?`Netlify token accepted (team: ${l.accountSlug})`:"Netlify token accepted"):(h.stop(l.message??"Netlify check failed",2),a.warn("Writing the token exactly as you entered it \u2014 not verified."),a.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let A=Re(d.googlePlacesApiKey??"");if(A.changed&&d.googlePlacesApiKey){a.heading("Checking your Google Places API key");let h=await Qe(d.googlePlacesApiKey);if(h.ok){if(A.repairs.length>0){a.warn("Corrected look-alike characters in your Google Places API key:");for(let l of A.repairs)a.detail(` ${l}`);a.detail("These come from keys that were transcribed rather than copied.")}d.googlePlacesApiKey=A.value,a.success("Google accepted the key \u2014 writing the corrected value to .env")}else a.error(h.message??"Google rejected the Google Places API key"),a.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),a.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(aa(d,u)){let h=ue.spinner();h.start("Validating email credentials (SMTP + IMAP)");let l=d.emailProvider&&d.emailProvider!=="custom"?d.emailProvider:Me(d.emailSmtpHost),P=await _e({emailAddress:d.emailAddress,emailLogin:d.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:d.emailPassword,emailSmtpHost:d.emailSmtpHost,emailSmtpPort:d.emailSmtpPort,emailImapHost:d.emailImapHost,emailImapPort:d.emailImapPort,usesAccountPassword:l?ce[l].usesAccountPassword:void 0,knownProvider:!!l,sentFolder:(d.emailSentFolder??"").trim()||"Sent",draftsFolder:(d.emailDraftsFolder??"").trim()||"Drafts"});P.ok?(h.stop("Email credentials accepted (SMTP + IMAP)"),await zt(P,d,{nonInteractive:!1,onCancel:()=>a.detail("Left the folder names as they are.")})):(h.stop(P.message??"Email check failed",2),a.warn("Writing the email settings exactly as you entered them \u2014 not verified."),a.detail(P.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 vn(n,Nt(d),"utf-8"),a.success("Updated .env"),d.aiAgent==="codex"?(await ra(st(t,".codex"),{recursive:!0}),await vn(s,Dt(d),"utf-8"),a.success("Updated .codex/config.toml")):(await vn(i,Mt(d),"utf-8"),a.success("Updated .mcp.json"),await sn(t,"supabase"),await tt(t,et)),d.emailAuth==="oauth-microsoft"&&d.outreachEnabled&&d.outreachChannels?.includes("email")){let h=await se();if(!(h!==null&&cs(h.command[0],[...h.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(a.blank(),!h)a.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),a.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let P=await ue.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});ue.isCancel(P)||!P?a.detail(`Skipped. Connect it any time with: ${h.command.join(" ")} scripts/ms_oauth.py login`):cs(h.command[0],[...h.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?a.success("Outlook mailbox connected."):(a.warn("The Microsoft sign-in didn't complete."),a.detail(`Connect it any time with: ${h.command.join(" ")} scripts/ms_oauth.py login`))}}a.blank(),ue.outro(Ce.green("Configuration updated.")),await ca(t,o)}function aa(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(([s])=>s===void 0||s===""))return!1;let i=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([s,o])=>String(s)!==(t[o]??""))||i.some(([s,o])=>s!==void 0&&s!==(t[o]??""))}function la(e,t){let n=(i,s)=>(i??"")!==(t[s]??"");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 ca(e,t){let n=await xn(st(e,"node_modules"));a.blank(),t?n||(a.detail("Your project files are in place but dependencies aren't installed yet."),a.detail("To finish setup, run:"),a.blank(),console.log(` ${Ce.cyan("npx klaudius@latest install")} ${Ce.dim("# (re-)installs npm + pip + browsers; idempotent")}`),a.blank(),a.detail("Then verify with:"),a.blank(),console.log(` ${Ce.cyan("npx klaudius@latest doctor")} ${Ce.dim("# checks Node / Python / installers / credentials")}`),a.blank()):(a.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),a.detail("To finish setup, run:"),a.blank(),console.log(` ${Ce.cyan("npx klaudius@latest init")} ${Ce.dim("# pick Resume when prompted")}`),a.blank())}async function xn(e){try{return await oa(e),!0}catch{return!1}}import{copyFile as Un,mkdir as cn,readFile as At,rm as Ae,writeFile as dn,access as Hn}from"fs/promises";import{dirname as un,join as O}from"path";import{tmpdir as La}from"os";import*as Le from"@clack/prompts";import Et from"picocolors";import{execFile as Dn}from"child_process";import{createHash as da}from"crypto";import{access as ua,copyFile as ws,lstat as pa,mkdir as Ln,mkdtemp as ks,open as fa,readFile as oe,realpath as ha,rm as rt,stat as As,unlink as ma,writeFile as wt}from"fs/promises";import{tmpdir as Es}from"os";import{dirname as Fe,isAbsolute as On,join as F,relative as us,resolve as yt}from"path";var Nn={"Edit conflict":["keep-mine","take-new","check-merge","merge","auto-merge"],"Deleted locally":["restore","keep-deleted"],"Removed upstream":["keep-mine","delete"]},Mn=F(".klaudius","conflicts.md"),Fn=F(".klaudius","incoming"),ga=F(".klaudius","resolve.lock"),kt=F(".klaudius","merged"),ya=12e4,wa=3e4,ka=[["keepMine","keep-mine"],["takeNew","take-new"],["checkMerge","check-merge"],["merge","merge"],["autoMerge","auto-merge"],["restore","restore"],["keepDeleted","keep-deleted"],["delete","delete"]];function Ps(e,t){let n=ka.filter(([s])=>t[s]!==void 0&&t[s]!==!1),i=[t.checkMerge,t.merge].find(s=>typeof s=="string");return{path:e,action:n.length===1?n[0][1]:void 0,draft:i,finish:t.finish===!0}}function Aa(e){let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return`.klaudius/merged/draft${n>0?t.slice(n):""}`}function ps(e,t,n,i){if(/^(<<<<<<<|>>>>>>>)/m.test(t))return"still has conflict markers (<<<<<<< or >>>>>>>): finish the merge first";if(!e.toLowerCase().endsWith(".json")||n===null||i===null)return null;let s=r=>{try{return JSON.parse(r.replace(/^/,"")),null}catch(c){return c.message}};if(s(n)!==null||s(i)!==null)return null;let o=s(t);return o===null?null:`isn't valid JSON (${o})`}function $n(e){let t=[];for(let n=0;n<e.length;n++){let i=e[n];if(i==='"'){let s=n+1;for(;s<e.length&&e[s]!=='"';)s+=e[s]==="\\"?2:1;let o=s+1;for(;o<e.length&&/\s/.test(e[o]);)o++;let r=t[t.length-1];if(e[o]===":"&&r){let c=e.slice(n+1,s);if(r.has(c))return c;r.add(c)}n=s}else i==="{"?t.push(new Set):i==="["?t.push(null):(i==="}"||i==="]")&&t.pop()}return null}var Ea={".js":[process.execPath,["--check"]],".mjs":[process.execPath,["--check"]],".cjs":[process.execPath,["--check"]],".sh":["bash",["-n"]],".py":["python3",["-c","import ast, sys; ast.parse(open(sys.argv[1], 'rb').read(), sys.argv[1])"]]};async function fs(e,t,n,i,s){let o=e.slice(e.lastIndexOf("/")+1),r=o.lastIndexOf("."),c=r>0?o.slice(r).toLowerCase():"";if(c===".json"){let f=h=>{try{return JSON.parse(h.replace(/^/,"")),!0}catch{return!1}};if(!f(n)||!f(i)||$n(n)!==null||$n(i)!==null)return null;let A=$n(t.toString());return A===null?null:`gives the key "${A}" twice`}let u=c===".js"?await Pa(s)==="module"?".mjs":".cjs":c,p=Ea[u];if(!p)return null;let d={...process.env,NO_COLOR:"1",PYTHON_COLORS:"0"};delete d.FORCE_COLOR;let y;try{y=await ks(F(Es(),"klaudius-check-"))}catch{return null}try{let f=async(h,l)=>{let P=F(y,`${l}${u}`);await wt(P,h);let R=await ha(P).catch(()=>P);return new Promise(x=>Dn(p[0],[...p[1],P],{windowsHide:!0,timeout:1e4,env:d},(v,L,S)=>{if(!v||v.killed||v.signal||typeof v.code!="number")return x(null);let I=String(S).split(/\r?\n/).map(M=>M.split(R).join(e).split(P).join(e).trim()).filter(Boolean),N=I.find(M=>/^\w*Error\b|syntax error/i.test(M))??I[I.length-1]??v.message.split(`
|
|
117
|
-
`)
|
|
118
|
-
`),n=[],i=!1;t.forEach((o,r)=>{o.startsWith("```")?i=!i:!i&&o.startsWith("## ")&&n.push({path:o.slice(3).trim(),start:r})});let s=n.map((o,r)=>{let c=r+1<n.length?n[r+1].start:t.length,p=t.slice(o.start,c).find(d=>d.startsWith("**Type:**"))?.slice(9).trim();return{...o,end:c,type:p!==void 0&&p in Nn?p:null}});return{lines:t,sections:s}}function Sa(e,t,n){let i=[...e.lines.slice(0,t.start),...e.lines.slice(t.end)],s=i.findIndex(r=>r.startsWith("Updating from")),o=s>=0&&s+2<e.sections[0].start?i[s+2]:"";return o.trim()!==""&&!o.startsWith("Open ")&&!o.startsWith("---")&&(i[s+2]=`${n} ${n===1?"conflict is":"conflicts are"} still waiting for a decision; the others are settled.`),i.join(`
|
|
119
|
-
`)}function Ta(e){let t=e.match(/^Generated by .* on (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/m)?.[1];return`.klaudius/backup/resolve-${t?t.replace(/[:.]/g,"-"):"undated"}`}var ot=e=>ua(e).then(()=>!0,()=>!1);async function _a(e,t,n){let i=`${n}.bak`;for(let o=2;await ot(F(e,t,i));o++)i=`${n}.${o}.bak`;let s=F(e,t,i);return await Ln(Fe(s),{recursive:!0}),await ws(F(e,n),s),`${t}/${i}`}function Ia(e,t,n,i){let s=y=>{let f=new Map;for(let A of y.split(/\r\n|\r|\n/))A.trim()&&f.set(A,(f.get(A)??0)+1);return f},o=(y,f)=>y.get(f)??0,r=s(e),c=s(i),u=[["Your",s(t)],["The update's",s(n)]],p=y=>{let f=o(r,y),A=o(u[0][1],y)-f,h=o(u[1][1],y)-f,l=Math.max(0,f+A+h);return A>0&&h>0?{min:f+Math.max(A,h),max:l}:A<0&&h<0?{min:l,max:Math.max(0,f+Math.min(A,h))}:{min:l,max:l}},d=[];for(let[y,f]of u){let A=[...new Set([...f.keys(),...r.keys()])].filter(P=>o(f,P)!==o(r,P)),h=A.filter(P=>o(f,P)>o(r,P)&&o(c,P)<p(P).min),l=A.filter(P=>o(f,P)<o(r,P)&&o(c,P)>p(P).max);d.push(`${y} edits kept: ${A.length-h.length-l.length} of ${A.length}`);for(let P of h)d.push(` dropped: ${P.trim().slice(0,120)}`);for(let P of l)d.push(` still present: ${P.trim().slice(0,120)}`)}return d}function Ca(e,t,n){return new Promise(i=>{Dn("git",["merge-file","-p",e,t,n],{encoding:"buffer",maxBuffer:64*1024*1024,windowsHide:!0},(s,o)=>{if(!s)return i({merged:o});let r=s.code;if(typeof r=="number"&&r>0&&r<128)return i({overlaps:r});i({unavailable:s.message.split(`
|
|
120
|
-
`)[0]
|
|
121
|
-
`),o
|
|
122
|
-
`)){let
|
|
123
|
-
`))if(v.startsWith(`${l("<")} `))R="mine",x={mine:[],base:[],theirs:[]};else if(R&&v.startsWith(`${l("|")} `))R="base";else if(R&&v===l("="))R="theirs";else if(R&&v.startsWith(`${l(">")} `)){let L=j=>j.map(M=>M.trim()),S=L(x.mine),I=L(x.base),N=L(x.theirs);if(I.length>0&&S.length===I.length&&N.length===I.length)for(let j=0;j<I.length;j++){let[M,pe,C]=[S[j],I[j],N[j]];!M||!C||M===pe||C===pe||M===C||!Ra(M,C)||y(f,M)>y(h,M)&&y(f,C)>y(A,C)&&P.push(` kept both versions: ${M.slice(0,120)} / ${C.slice(0,120)}`)}R=null}else R&&x[R].push(v);return P}catch{return[]}finally{await rt(o,{recursive:!0,force:!0}).catch(()=>{})}}async function ms(e,t,n,i){let s=await oe(F(e,Te,t),"utf-8").catch(()=>null);if(s===null)return["No pre-edit base was staged for this file, so there is no line check. Say in plain words what the merge keeps from each side."];let o=await oe(F(e,i,`${t}.bak`),"utf-8").catch(()=>null)??await oe(F(e,t),"utf-8").catch(()=>""),r=await oe(F(e,Fn,t),"utf-8");return[s,o,r,n].some(Oe)?["Binary file: no line check."]:["Line check against the pre-edit base:",...Ia(s,o,r,n),...await va(s,o,r,n)]}function ln(e,t,n=0){for(let i of e)console.log(i);return console.log(`[klaudius-resolve] ${t}`),n}function D(e,t){return console.error(`${e} Nothing was changed.`),console.log(`[klaudius-resolve] refused${t===void 0?"":` remaining=${t}`}`),1}async function gs(e,t,n,i){let s=n?.match(/to \*\*([^*]+)\*\*/)?.[1]?.trim();(i||s||t.pendingConflicts!==void 0)&&(s&&(t.templateVersion=s),delete t.pendingConflicts,t.updatedAt=new Date().toISOString(),await xe(e,t));let o=c=>rt(F(e,c),{recursive:!0,force:!0,maxRetries:3}).then(()=>!0,()=>!1);if(!await o(Mn))return{complete:!1,lines:[".klaudius/conflicts.md couldn't be removed, so the update staging was kept. Close anything that has it open, then run the same command again."]};let r=!1;for(let c of[Fn,Te,kt])await o(c)||(r=!0);return{complete:!0,lines:[r?"Nothing is waiting for a decision. Some staging under .klaudius/ couldn't be removed; the next update clears it.":"Nothing is waiting for a decision. Update staging cleared."]}}var ys=e=>new Promise(t=>setTimeout(t,e));function xa(e,t){if(Date.now()-t>ya)return!0;let n=Number(e.trim());if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!1}catch(i){return i.code==="ESRCH"}}async function Oa(e,t){let n=F(e,ga),i=Date.now(),s=!1,o=0;for(;;)try{let r=await fa(n,"wx");await r.writeFile(String(process.pid)).finally(()=>r.close());break}catch(r){let c=r.code;if(c!=="EEXIST"&&c!=="EPERM")throw r;let u=await As(n).catch(()=>null);if(u===null){if(c==="EPERM"&&++o>5)throw r;await ys(50);continue}let p=await oe(n,"utf-8").catch(()=>"");if(!s&&xa(p,u.mtimeMs)){s=!0,await oe(n,"utf-8").catch(()=>"")===p&&await rt(n).catch(d=>{if(d.code!=="ENOENT")throw new Error(`.klaudius/resolve.lock was left by an earlier run and can't be removed (${d.message})`)});continue}if(Date.now()-i>wa)return null;await ys(100)}try{return await t()}finally{await rt(n,{force:!0}).catch(()=>{})}}async function bs(e){let t=e.projectRoot??process.cwd();return await ot(F(t,".klaudius","manifest.json"))?await Oa(t,()=>$a(t,e))??D("Another resolve is still running in this project; run this again once it has finished."):D("No .klaudius/manifest.json here: run this from the Klaudius project folder.")}async function $a(e,t){let n;try{n=await jt(e)}catch(C){return D(`.klaudius/manifest.json can't be read (${C.message}).`)}if(!n)return D("No .klaudius/manifest.json here: run this from the Klaudius project folder.");let i=await oe(F(e,Mn),"utf-8").catch(()=>null),s=i===null?null:ba(i);if(t.finish){if(t.path||t.action)return D("--finish takes no file or action.");let C=s?.sections.length??0;if(C>0)return D(`${C} ${C===1?"conflict is":"conflicts are"} still waiting in .klaudius/conflicts.md.`,C);let B=await gs(e,n,i,!1);return ln(B.lines,B.complete?"finished remaining=0":"remaining=0 incomplete",B.complete?0:1)}if(!t.path||!t.action)return D("Name one file and exactly one action.",s?.sections.length);if(!s)return D("No conflicts are staged (.klaudius/conflicts.md is missing).",0);let o=s.sections.length,r=t.path.split("\\").join("/");if(On(t.path)&&(r=us(e,t.path).split("\\").join("/")),r=r.replace(/^\.\//,""),r===""||On(r)||/^[a-zA-Z]:/.test(r)||r.split("/").includes(".."))return D(`${t.path} isn't a path inside this project.`,o);let c=s.sections.find(C=>C.path===r);if(!c)return D(`${r} isn't waiting in .klaudius/conflicts.md (waiting: ${s.sections.map(C=>C.path).join(", ")||"none"}).`,o);let u=F(e,r),p=F(e,Fn,r),d=await ot(u),y=await ot(p),f=c.type??(y?d?"Edit conflict":"Deleted locally":"Removed upstream"),A=t.action;if(!Nn[f].includes(A))return D(`${r} is a "${f}" conflict; its options are ${Nn[f].map(C=>`--${C}`).join(", ")}.`,o);if(f!=="Removed upstream"&&!y)return D(`The staged new version .klaudius/incoming/${r} is missing; run npx klaudius@latest update to stage it again.`,o);if(f==="Edit conflict"&&!d&&(A==="keep-mine"||A==="check-merge"||A==="merge"||A==="auto-merge"))return D(`${r} is no longer on disk, so there's no version of yours to ${A==="keep-mine"?"keep":"merge"}; choose --take-new.`,o);let h=Ta(i),l=null,P=[];if(A==="check-merge"||A==="merge"){if(!t.draft)return D(`--${A} needs the merged draft's path.`,o);if(l=yt(e,t.draft),process.platform==="linux"?l===yt(u):l.toLowerCase()===yt(u).toLowerCase())return D(`Write the merged version to its own draft file (${Aa(r)}), not over ${r}: the original is what gets backed up.`,o);let B=await oe(l,"utf-8").catch(()=>null);if(B===null)return D(`Can't read the draft ${t.draft}.`,o);let ie=await oe(p,"utf-8").catch(()=>null),Z=await oe(u,"utf-8").catch(()=>null),fe=ps(r,B,ie,Z)??(ie!==null&&Z!==null?await fs(r,B,Z,ie,Fe(u)):null);if(fe)return D(`The draft ${t.draft} ${fe}.`,o);if(P=await ms(e,r,B,h),A==="check-merge")return ln(P,`checked path=${r} remaining=${o}`)}let R=null;if(A==="auto-merge"){if(r.split("/").pop()===".gitignore")return D(".gitignore is only merged as a union (every line of the user's kept, the new patterns added, nothing removed), so it can't be merged automatically; merge it by hand.",o);let C=F(e,Te,r);if(!await ot(C))return D(`${r} has no pre-edit base, so it can't be merged automatically; merge it by hand.`,o);let B=F(e,h,`${r}.bak`),ie=await ot(B)?B:u,Z=await Ca(ie,C,p);if("overlaps"in Z)return D(`Your edits and the update's overlap in ${r} (${Z.overlaps} place${Z.overlaps===1?"":"s"}), so it can't be merged automatically; merge it by hand.`,o);if("unavailable"in Z)return D(`git merge-file couldn't run (${Z.unavailable}), so ${r} can't be merged automatically; merge it by hand.`,o);let fe=Z.merged.toString("utf-8"),E=await oe(p,"utf-8").catch(()=>null),$=await oe(ie,"utf-8").catch(()=>null),U=ps(r,fe,E,$)??(E!==null&&$!==null?await fs(r,Z.merged,$,E,Fe(u)):null);if(U)return D(`The automatic merge of ${r} ${U}; merge it by hand.`,o);P=await ms(e,r,fe,h);let le=P.filter(_=>/^\s+(dropped|still present|kept both versions):/.test(_)).map(_=>_.trim());if(le.length>0)return D(`The automatic merge of ${r} doesn't keep every edit (${le.join("; ")}); merge it by hand.`,o);R=Z.merged}if(A==="keep-deleted"&&d)return D(`${r} exists again, so it can't stay deleted; choose --restore, or move the file away first.`,o);let x=y?await ge(p):void 0,v=A==="take-new"||A==="restore"?x:A==="merge"?await ge(l):R?da("sha256").update(R).digest("hex"):void 0,L=d&&(A==="delete"||v!==void 0&&await ge(u)!==v),S=null;if(L)try{S=await _a(e,h,r)}catch(C){return D(`Couldn't save a backup copy of ${r} (${C.message}).`,o)}let I=[];switch(A){case"keep-mine":f==="Edit conflict"?(n.files[r]=x,I.push(`Kept your version of ${r}. Later updates treat it as your edit.`)):(delete n.files[r],I.push(`Kept ${r}. Klaudius no longer tracks it, so updates leave it alone.`));break;case"take-new":case"restore":await Ln(Fe(u),{recursive:!0}),await ws(p,u),n.files[r]=x,n.ignored&&(n.ignored=n.ignored.filter(C=>C!==r)),I.push(A==="take-new"?`Replaced ${r} with the new version.`:`Restored ${r} in its new version.`);break;case"merge":case"auto-merge":{let C=d?(await As(u)).mode&4095:void 0,B=R??await oe(l);await Ln(Fe(u),{recursive:!0}),d&&(await pa(u)).isSymbolicLink()?await wt(u,B):await pt(u,B,C),n.files[r]=x,I.push(`Wrote the merged version to ${r}.`,...P);break}case"keep-deleted":delete n.files[r],n.ignored=[...new Set([...n.ignored??[],r])],I.push(`${r} stays deleted; updates won't reinstall it.`);break;case"delete":d&&await rt(u,{force:!0}),delete n.files[r],I.push(`Deleted ${r}.`);break}S&&I.push(`Your previous version is saved at ${S}.`);let N=o-1,j=!0;if(N>0)n.pendingConflicts=N,n.updatedAt=new Date().toISOString(),await xe(e,n),await pt(F(e,Mn),Sa(s,c,N));else{let C=await gs(e,n,i,!0);I.push(...C.lines),j=C.complete}let M=l===null?"":us(yt(e,kt),l);j&&M&&!M.startsWith("..")&&!On(M)&&await ma(l).catch(()=>{});let pe=`path=${r} action=${A} remaining=${N}`;return j?ln(I,pe):ln(I,`${pe} incomplete`,1)}var Pt="0.35.0";async function _s(e){let t=e.projectRoot??process.cwd(),n=await jt(t);n||(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let E of Ut)delete n.files[E];let i,s=O(t,".env"),o,r;try{o=await At(s,"utf-8"),r=te(o)}catch{a.error("Couldn't read .env from this directory."),a.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=r.KLAUDIUS_LICENSE_KEY??"",i||(a.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),a.detail("This file is created by `npx klaudius@latest init`. If your project predates"),a.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),a.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=e.check?null:di(o,r,ci);c!==null&&(await dn(s,c,"utf-8"),a.detail("Backfilled new env keys")),await Vt("update",Pt),Le.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Pt}`),await Zt();let p=r.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&p==="claude-code"&&await tt(t,et)==="added"&&a.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let d=O(La(),`klaudius-update-${process.pid}-${Date.now()}`),y;try{a.heading("Downloading the latest Klaudius template");let E=await Gt({licenseKey:i,machineId:mt(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:d});a.success(`Fetched ${E.filesExtracted} canonical files`),y=d}catch(E){a.error(E.message),a.detail("Update aborted. Your project is unchanged."),await Ae(d,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let f=await Ma(y,t,n);if(e.check){let E=f.filter(_=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(_.state)),$=f.filter(_=>["conflict","locally-deleted","removed-modified"].includes(_.state)&&!(_.path===".gitignore"&&_.state==="conflict")),U="unknown";if(r.SUPABASE_URL&&r.SUPABASE_SERVICE_KEY){let _=await At(O(y,"scripts","schema.sql"),"utf-8").catch(()=>""),m=await Wt({url:r.SUPABASE_URL,serviceKey:r.SUPABASE_SERVICE_KEY,sql:_});m.unreachable?a.detail(`Database schema not checked (${m.unreachable}).`):m.ok?U="current":(U="stale",a.detail(`Database schema is behind (missing: ${m.missing.join(", ")}); update applies scripts/schema.sql.`))}let le=E.length>0||U==="stale";a.blank(),le?(E.length>0&&a.detail(`${ee(E.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),Le.outro(Et.yellow("An update is available."))):Le.outro(Et.green("Already up to date.")),console.log(`[klaudius-update-check] status=${le?"behind":"current"} pending=${E.length+(U==="stale"?1:0)} conflicts=${$.length} schema=${U}`),await Ae(d,{recursive:!0,force:!0}).catch(()=>{});return}let A=!1,h=f.find(E=>E.path===".gitignore"&&E.state==="conflict");if(h){let E=O(t,".gitignore"),$=await At(E,"utf-8"),U=await At(O(y,".gitignore"),"utf-8"),{merged:le,added:_}=Fa($,U);_.length>0&&await dn(E,le,"utf-8"),n.files[".gitignore"]=h.canonicalHash,h.state="gitignore-merged",A=!0,a.detail(_.length>0?`.gitignore auto-merged: kept all your lines, appended ${ee(_.length,"new canonical pattern")}: ${_.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let l=f.filter(E=>E.state==="new"),P=f.filter(E=>E.state==="clean-update"),R=f.filter(E=>E.state==="user-only"),x=f.filter(E=>E.state==="conflict"),v=f.filter(E=>E.state==="no-change"),L=f.filter(E=>E.state==="locally-deleted"),S=f.filter(E=>E.state==="removed-clean"),I=f.filter(E=>E.state==="removed-modified"),N=[...x,...L,...I],j=n.ignored?.length??0;a.blank(),a.heading("Change summary"),a.detail(`${ee(v.length,"file")} unchanged`),a.detail(`${ee(l.length,"new file")}`),a.detail(`${ee(P.length,"file")} updated cleanly (no local edits)`),a.detail(`${ee(R.length,"file")} you've edited (no upstream change \u2014 left alone)`),a.detail(`${ee(S.length,"file")} removed upstream (deleted cleanly)`);let M=x.filter(E=>E.reason==="untracked-local").length,pe=x.filter(E=>E.reason==="manifest-mismatch").length;a.detail(`${ee(x.filter(E=>!E.reason).length,"file")} with conflicts (you edited AND we have a new version)`),M>0&&a.detail(`${ee(M,"file")} of your own at a path the new version now ships (need your decision)`),pe>0&&a.detail(`${jn(pe)}, and we have a new version (need your decision)`),a.detail(`${ee(L.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`);let C=I.filter(E=>E.reason==="manifest-mismatch").length;if(a.detail(`${ee(I.length-C,"file")} removed upstream but edited locally (need your decision)`),C>0&&a.detail(`${jn(C)}, removed upstream (need your decision)`),j>0&&(a.detail(`${ee(j,"file")} kept deleted (previously resolved \u2014 skipped)`),j<=10))for(let E of n.ignored)a.detail(` kept deleted: ${E}`);let B=async()=>{let E=!1,$=U=>Ae(U,{recursive:!0,force:!0}).catch(()=>{E=!0});await $(O(t,".klaudius","incoming")),await $(O(t,Te)),await $(O(t,kt)),await $(O(t,".klaudius","conflicts.md")),E&&a.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/, .klaudius/merged/ and .klaudius/conflicts.md by hand)")};if(l.length===0&&P.length===0&&S.length===0&&N.length===0&&!A){await Ss(t,r,!1),await B(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Pt,await xe(t,n)),a.blank(),Le.outro(Et.green("Already up to date.")),await Ae(d,{recursive:!0,force:!0}).catch(()=>{});return}let ie=new Date().toISOString().replace(/[:.]/g,"-"),Z=`.klaudius/backup/update-${ie}`,fe=0;for(let E of[...P,...S]){if(E.localHash===void 0||E.localHash===E.canonicalHash)continue;let $=O(t,Z,`${E.path}.bak`);try{await cn(un($),{recursive:!0}),await Un(O(t,E.path),$)}catch(U){a.error(`Couldn't save a backup copy of ${E.path}: ${U.message}`),a.detail("Update stopped before replacing or removing any files (additions already made, such as new .env keys, are kept)."),await Ae(d,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}fe++}a.blank(),a.heading("Applying clean updates");for(let E of[...l,...P]){let $=O(y,E.path),U=O(t,E.path);await cn(un(U),{recursive:!0}),await Un($,U),n.files[E.path]=E.canonicalHash}l.length+P.length>0&&a.success(`Wrote ${ee(l.length+P.length,"file")}`),[...l,...P].some(E=>E.path==="package.json"||E.path==="package-lock.json")&&a.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let E of S){let $=O(t,E.path);await Ae($,{force:!0}),delete n.files[E.path]}if(S.length>0){a.success(`Deleted ${ee(S.length,"file")} removed upstream`);for(let E of S.slice(0,20))a.detail(` removed: ${E.path}`);S.length>20&&a.detail(` \u2026and ${S.length-20} more`)}if(fe>0&&a.detail(`Previous copies of the ${ee(fe,"file")} replaced or removed are in ${Z}/ (each saved as <name>.bak)`),await Ss(t,r,N.some(E=>E.path==="scripts/schema.sql")),N.length>0){a.blank(),a.heading(`${N.length} conflict(s) need resolution`);let E=O(t,".klaudius","incoming");try{await Ae(E,{recursive:!0,force:!0})}catch{}await Ae(O(t,kt),{recursive:!0,force:!0}).catch(()=>{});for(let _ of[...x,...L]){let m=O(y,_.path),k=O(E,_.path);await cn(un(k),{recursive:!0}),await Un(m,k)}let $=new Map,U=new Map;for(let _ of x){let m=await xi(t,_.path),k=await Oi(t,_.path),w=await At(O(y,_.path),"utf-8"),b=$i(m,k,w,_.manifestHash);_.reason==="untracked-local"?$.set(_.path,["_Klaudius doesn't track this file (it's your own, or one kept after an earlier version dropped it), and the new version ships one at the same path. No common base exists: compare your copy with `.klaudius/incoming/"+_.path+"` directly._"]):_.reason==="manifest-mismatch"?$.set(_.path,["_The manifest's entry for this file isn't the version Klaudius last installed (a hand-edited manifest, a conflict resolved outside `/resolve-conflicts`, or a folder restored from an older copy), so your copy was left in place. No verified base exists: compare it with `.klaudius/incoming/"+_.path+"` directly. If the file was never changed on purpose, taking the new version is safe._"]):b!==null?(U.set(_.path,b),$.set(_.path,Li(b,w))):m!==null&&(Oe(m)||Oe(w))?$.set(_.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+_.path+"` directly._"]):m===null?$.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._"]):$.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 le=O(t,Te);try{await Ae(le,{recursive:!0,force:!0})}catch{}for(let[_,m]of U){let k=O(le,_);await cn(un(k),{recursive:!0}),await dn(k,m,"utf-8")}await dn(O(t,".klaudius","conflicts.md"),Ua(N,n.templateVersion,Pt,$,U),"utf-8"),x.length+L.length>0&&a.detail("Staged canonical versions to .klaudius/incoming/"),U.size>0&&a.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),a.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Pt,n.baseSnapshot=ie,N.length===0?(delete n.pendingConflicts,await B()):n.pendingConflicts=N.length,await xe(t,n);try{await Bt(t,y,await De(y),ie)}catch{a.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(a.blank(),N.length===0)Le.outro(Et.green("Update complete."));else{let E=p==="codex"?"Codex":"Claude Code";Le.outro(Et.yellow(`${N.length} conflict(s) staged. Open ${E} in this project and ask:
|
|
124
|
-
|
|
115
|
+
enter from any device.)`)),a.blank();let y=await Q();if(y){let[f,...k]=y.command,P=Wn(f,[...k,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});P.status===0?(a.success("Outlook mailbox connected."),$&&await Xt(n,l.emailAddress??"")):(a.blank(),console.log(A.yellow(`The Microsoft sign-in didn't complete (exit ${P.status??"signalled"}). Setup continues without it.`)),re(y))}else console.log(A.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),re(null)}else x&&!R&&(a.blank(),console.log(A.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),$||(console.log(A.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(A.cyan(" python3 scripts/ms_oauth.py login"))));a.blank();let z=[...b,...I?["schema"]:[]];if(z.length>0){v.outro(A.yellow(A.bold(`Setup paused \u2014 ${z.join(", ")} failed.`))),console.log(A.dim("Your credentials and project files are all saved.")),a.blank();for(let[L,ie]of Object.entries(C))console.log(A.yellow(`Likely cause of ${L} failure:`)),console.log(A.dim(` ${ie}`)),a.blank();if($){let L=[];I&&(L.push(`Couldn't create the database tables: ${O.replace(/[:.\s]+$/,"")}. Check the database access token on the Database step.`),L.push(`If the token keeps being refused, open ${N}, paste in the contents of scripts/schema.sql from your project folder, and click Run.`));let ie=b.filter(ae=>ae==="playwright"||ae==="patchright"),be=b.filter(ae=>ae!=="playwright"&&ae!=="patchright");be.length>0&&L.push(`Couldn't finish installing ${be.join(", ")}. The install output says why.`),ie.length>0&&L.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."),T&&L.push("Email outreach was parked during setup \u2014 the mailbox credentials didn't pass their check. Your details are saved, so it can be picked up once the rest is through."),L.push("Then try again \u2014 setup carries on from here. If it keeps failing, email hello@klaudius.dev with the last few lines."),_(I&&b.length===0?"supabase":"install",L.join(`
|
|
116
|
+
`))}let y=n!==process.cwd()&&e.target?` ${A.cyan(`cd ${hn(e.target)}`)}
|
|
117
|
+
`:"",f=l.aiAgent==="codex"?"codex":"claude",k=l.aiAgent==="codex"?"Codex":"Claude Code",P=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";b.length>0&&(console.log(A.dim(`Easiest fix \u2014 let ${k} finish it for you:`)),a.blank(),y&&process.stdout.write(y),console.log(` ${A.cyan(f)} ${A.dim(`# open ${k} in this folder`)}`),console.log(A.dim(" Then paste:")),console.log(A.cyan(` "Finish my Klaudius install \u2014 ${b.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),a.blank(),console.log(A.dim(` (Don't have ${k} yet? Install with: \`${P}\`)`)),a.blank(),console.log(A.dim("Or do it yourself:")),a.blank(),y&&process.stdout.write(y),console.log(` ${A.cyan("npx klaudius@latest install")} ${A.dim("# retry the failing installers")}`),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# verify everything")}`),a.blank()),I&&(console.log(A.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${A.cyan(N)}`),console.log(A.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),a.blank()),b.includes("pip")&&!C.pip&&(console.log(A.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(A.dim(`Python 3.10+. Install a newer one from ${Ma()}`)),console.log(A.dim("and open a fresh Terminal before retrying.")),a.blank());let S=["npm","playwright","patchright"].filter(L=>b.includes(L)&&!C[L]);if(S.length>0){let L=S.length===1?"keeps":"keep";console.log(A.dim(`If ${S.join(" / ")} ${L} failing with network errors (ECONNRESET,`)),console.log(A.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(A.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),a.blank()}T&&(console.log(A.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${k}`)),console.log(A.dim("to finish setting it up \u2014 your email details are saved in .env.")),a.blank()),console.log(A.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),a.blank();return}if(await Ss(Vn(n),{force:!0}),await Ss(Jt(n),{force:!0}),Da(l,n,e.target),T){let y=l.aiAgent==="codex"?"Codex":"Claude Code";console.log(A.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(A.dim(`Your details are saved in .env. To finish it, ask ${y}:`)),console.log(A.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(A.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(A.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(A.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(A.cyan(' and send a test email to my own address to confirm."')),l.outreachEnabled&&(l.outreachChannels??[]).length>0&&(a.blank(),console.log(A.yellow(`Note: your other channel(s) \u2014 ${(l.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),a.blank()}}async function q(e,t){await mn(e,{recursive:!0}),await fn(X(e,".env"),st(t),"utf-8"),t.aiAgent==="codex"?(await mn(X(e,".codex"),{recursive:!0}),await fn(X(e,".codex","config.toml"),rt(t),"utf-8")):(await fn(X(e,".mcp.json"),ot(t),"utf-8"),await ft(e,"supabase"),await je(e,He))}async function Oa(e){try{(await Yn(e)).isDirectory()||($&&_("folder","There's already a file with that name. Choose a different folder name."),a.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await _s(e),n=t.filter(d=>!d.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),s=n.every(d=>i.has(d)),o=n.includes(".env"),r=t.includes(".klaudius");if(s&&o&&!r)return{kind:"partial",envPath:X(e,".env")};if(r&&o){let d=!0;try{d=!(await Yn(X(e,"node_modules"))).isDirectory()}catch{d=!0}return{kind:"scaffolded",nodeModulesMissing:d}}return{kind:"occupied",entries:n}}async function xa(e){a.blank(),a.warn(`Found a partial setup at ${A.bold(e)}.`),a.detail(`A previous init wrote ${A.bold(".env")} but didn't finish scaffolding.`),a.blank();let t=await v.select({message:`How would you like to proceed? ${A.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 v.isCancel(t)&&(v.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function La(e){if(e&&e.trim().length>0)return e;v.intro("Klaudius");let t=await v.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 v.isCancel(t)&&(v.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Na(e){let t=Ca(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let i of n)if(t.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function $a(){if(process.platform!=="win32")return!1;try{return Wn("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Ma(){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 Da(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",s=e.aiAgent==="codex"?"Codex":"Claude Code";if(v.outro(A.green(A.bold("Project ready."))),e.aiPlan){let o=(e.qaPhase??_e(e.aiPlan))==="off";console.log(`${A.bold("Your plan:")} ${We[e.aiPlan]}`),console.log(A.dim(o?` \u2192 QA pass off${Ye.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(A.dim(` Change it any time: ask ${s} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),a.blank()}if(console.log(A.bold("Next steps:")),a.blank(),t!==process.cwd()&&n){let o=`cd ${hn(n)}`;console.log(` ${A.cyan(o)}${" ".repeat(Math.max(1,27-o.length))}${A.dim("# go into your project folder")}`)}console.log(` ${A.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${A.dim(`# opens ${s} in this project`)}`),a.blank(),console.log(A.bold(`Some starter prompts for ${s}:`)),a.blank(),console.log(` ${A.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${A.cyan(`I know I'm ready to start using Klaudius."`)}`),a.blank(),$||(console.log(` ${A.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),a.blank()),console.log(` ${A.cyan('"Run the pipeline for one client."')}`),console.log(A.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.")),a.blank(),e.aiAgent!=="codex"&&(console.log(A.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(A.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),a.blank())}import{access as Fa,readFile as Ua}from"fs/promises";import{join as zn,resolve as Ha}from"path";import le from"picocolors";async function Rs(e){let t=e.target?Ha(process.cwd(),e.target):process.cwd(),n=await Cs(zn(t,".env")),i=await Cs(zn(t,"package.json"));(!n||!i)&&(a.error("This doesn't look like a Klaudius project."),a.detail(`Path: ${t}`),n||a.detail("Missing: .env"),i||a.detail("Missing: package.json"),a.blank(),a.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),a.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let s="claude-code";try{J(await Ua(zn(t,".env"),"utf-8")).AI_AGENT==="codex"&&(s="codex")}catch{}a.heading("Installing dependencies");let o=await ln(t);a.blank(),a.detail(`npm: ${o.npm}, pip: ${o.pip}, playwright: ${o.playwright}, patchright: ${o.patchright}`);let r=[];if(o.npm==="failed"&&r.push("npm"),o.pip==="failed"&&r.push("pip"),o.playwright==="failed"&&r.push("playwright"),o.patchright==="failed"&&r.push("patchright"),r.length===0){a.blank(),console.log(le.green(le.bold("All dependencies installed."))),console.log(le.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),a.blank();return}a.blank(),console.log(le.yellow(le.bold(`${r.join(", ")} still failing.`))),a.blank();for(let[u,g]of Object.entries(o.hints??{}))console.log(le.yellow(`Likely cause of ${u} failure:`)),console.log(le.dim(` ${g}`)),a.blank();let d=s==="codex"?"codex":"claude",c=s==="codex"?"Codex":"Claude Code",p=s==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(le.dim("Options:")),console.log(le.dim(` \u2022 Open ${c} in this folder (\`${d}\`) and paste:`)),console.log(le.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(le.dim(` (Don't have ${c} yet? Install with: \`${p}\`)`)),console.log(le.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(le.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),a.blank(),process.exitCode=1}async function Cs(e){try{return await Fa(e),!0}catch{return!1}}import{readFile as ol,writeFile as Jn,access as rl}from"fs/promises";import{join as gt}from"path";import*as ce from"@clack/prompts";import Oe from"picocolors";import{mkdir as Ns,copyFile as $s,readdir as Ka,readFile as Ms,rm as Fs}from"fs/promises";import{spawnSync as Ga}from"child_process";import{join as he}from"path";var xs=/^(#\s*)?([A-Za-z_][A-Za-z0-9_]*)=/,vs=/^#\s*[A-Za-z_][A-Za-z0-9_]*=\s*$/;function ja(e,t){let n=new Map,i=new Map,s=[];for(let o of e.split(`
|
|
118
|
+
`)){let r=o.replace(/\r$/,""),d=xs.exec(r.trim());if(d){let c=d[2];if(d[1]){!vs.test(r.trim())&&!t.has(r)&&s.push(r);continue}n.set(c,r),s.length>0&&(i.set(c,[...i.get(c)??[],...s]),s=[]);continue}r.trim().startsWith("#")&&(t.has(r)||vs.test(r.trim())||s.push(r))}return{lines:n,comments:i,trailing:s}}function Os(e){let t=e.trim();if(t.startsWith("#"))return;let n=t.indexOf("=");return n===-1?void 0:Ln(t.slice(n+1).trim())}function Ls(e,t,n){let i=e.split(`
|
|
119
|
+
`),s=ja(t,new Set(i)),o=[],r=new Set;for(let c of i){let u=xs.exec(c.trim())?.[2];if(u===void 0||r.has(u)){o.push(c);continue}r.add(u);for(let w of s.comments.get(u)??[])o.push(w);let g=s.lines.get(u),m=g!==void 0&&Os(g)!==Os(c);o.push(m&&!n.has(u)?g:c)}let d=[...s.trailing,...[...s.comments].filter(([c])=>!r.has(c)).flatMap(([,c])=>c)];return d.length>0&&(o[o.length-1]?.trim()!==""&&o.push(""),o.push(...d),o.push("")),o.join(`
|
|
120
|
+
`)}var ht=["supabase","vercel","cloudflare","netlify","selfhost","google-places","email","sms","letter","notifications"],Us={supabase:["SUPABASE_URL","SUPABASE_SERVICE_KEY","SUPABASE_ANON_KEY","SUPABASE_PAT","SUPABASE_PROJECT_REF"],vercel:["VERCEL_TOKEN","VERCEL_SCOPE"],cloudflare:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID"],netlify:["NETLIFY_AUTH_TOKEN","NETLIFY_ACCOUNT_SLUG"],selfhost:["SELFHOST_DEPLOY_TARGET","SELFHOST_URL_TEMPLATE"],"google-places":["GOOGLE_PLACES_API_KEY"],email:["EMAIL_PROVIDER","EMAIL_AUTH","EMAIL_ADDRESS","EMAIL_LOGIN","EMAIL_PASSWORD","EMAIL_FROM_NAME","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT","EMAIL_SENT_FOLDER","EMAIL_INBOX_FOLDER","EMAIL_DRAFTS_FOLDER"],sms:["SMS_PROVIDER","TEST_PHONE","TWILIO_ACCOUNT_SID","TWILIO_AUTH_TOKEN","TWILIO_PHONE_NUMBER"],letter:["LETTER_PROVIDER","PINGEN_CLIENT_ID","PINGEN_CLIENT_SECRET","PINGEN_ORG_ID","POSTGRID_API_KEY"],notifications:["NOTIFY_CHANNEL","NOTIFY_TO","TELEGRAM_BOT_TOKEN","TELEGRAM_CHAT_ID"]},Ds={email:"email",sms:"sms",letter:"letter"};function Ba(e,t){let n=new Set,i=(p,u)=>p==="LETTER_PROVIDER"&&u.trim()===Et?"":u,s=p=>p in e&&i(p,e[p]??"")!==i(p,t[p]??"");for(let p of ht)Us[p].some(s)&&n.add(p);if(s("DEPLOY_PROVIDER")){let p=(e.DEPLOY_PROVIDER??"").trim();p==="cloudflare"||p==="netlify"||p==="selfhost"?n.add(p):n.add("vercel")}let o=(p,u)=>(p[u]??"").split(",").map(g=>g.trim().toLowerCase()).filter(Boolean),r=(e.OUTREACH_ENABLED??"").toLowerCase()==="true",d=(t.OUTREACH_ENABLED??"").toLowerCase()==="true",c="OUTREACH_ENABLED"in e&&r&&!d;for(let p of["OUTREACH_CHANNELS","OUTREACH_PRIORITY"]){if(c){for(let g of o(p in e?e:t,p)){let m=Ds[g];m&&n.add(m)}continue}if(!(p in e))continue;let u=o(t,p);for(let g of o(e,p)){if(u.includes(g))continue;let m=Ds[g];m&&n.add(m)}}return ht.filter(p=>n.has(p))}async function Hs(e){let{projectRoot:t}=e,n=he(t,".env"),i=await Ms(n,"utf-8").catch(()=>null);i===null&&_("folder","There's no Klaudius install in this folder to reconfigure \u2014 it has no .env. Pick the folder your install is in, or set one up fresh.");let s=J(i),o=we();o.ok||_("install",o.message??"Node.js version check failed.");let r=await Gt(e.answers);Kt(r);let d="OUTREACH_CHANNELS"in r;d&&js(r.OUTREACH_CHANNELS,s.OUTREACH_CHANNELS)&&delete r.OUTREACH_CHANNELS;let c={...s,...r},p=at(c);p||Za(Qa(c));let u=s.AI_AGENT==="codex"?"codex":"claude-code",g=p.aiAgent??"claude-code";if(g!==u){let x=R=>R==="codex"?"Codex":"Claude Code";_("folder",`This install was set up for ${x(u)}, so it can't be reconfigured as ${x(g)}. Set up a new folder for the other assistant, or switch back. Nothing has been changed.`)}let m=Wa(p,r,s,c,d),w=Ba(r,s),l=nl(e.sections)??new Set(w),E=p.supabaseProjectRef!==(s.SUPABASE_PROJECT_REF??"");if(E&&l.add("supabase"),"SUPABASE_URL"in r||"SUPABASE_PROJECT_REF"in r){let x=qa(p.supabaseUrl??"");x&&x!==(p.supabaseProjectRef??"").trim().toLowerCase()&&_("supabase",`The database URL is for project "${x}", but the project reference says "${p.supabaseProjectRef}". They always name the same project, so one of the two is a typo. Nothing has been changed.`)}let{checked:T,rewritten:I}=await il(p,s,x=>l.has(x));for(let x of m)I.add(x);for(let x of Object.keys(r))I.add(x);for(let x of za(p,c))I.add(x);if(E){a.step("Setting up the tables in the new database");let x=await lt({projectRoot:t,pat:p.supabasePat,projectRef:p.supabaseProjectRef});x.ok||_("supabase",x.message??"The database wouldn't take the pipeline's tables."),a.success("Database tables in place")}let O=he(t,Ie,"backup"),N=he(Ie,"backup",`configure-${new Date().toISOString().replace(/[:.]/g,"-")}`),b=he(t,N,".env.bak");await Ns(he(t,N),{recursive:!0}),await $s(n,b),await Ya(O),await Ae(n,Ls(st(p),i,I)),a.success("Updated .env"),a.detail(`Previous .env saved as ${he(N,".env.bak")}`);let C=p.aiAgent==="codex"?he(t,".codex","config.toml"):he(t,".mcp.json"),M=await Ms(C,"utf-8").catch(()=>null);try{p.aiAgent==="codex"?(await Ns(he(t,".codex"),{recursive:!0}),await Ae(C,rt(p)),a.success("Updated .codex/config.toml")):(await Ae(C,ot(p)),a.success("Updated .mcp.json"))}catch(x){M===null?await Fs(C,{force:!0}).catch(()=>{}):await Ae(C,M).catch(()=>{});let R=await $s(b,n).then(()=>!0,()=>!1);throw a.warn(Ja(R,he(N,".env.bak"))),x}p.aiAgent!=="codex"&&(await ft(t,"supabase").catch(x=>{a.warn(`Couldn't pre-approve the database connection in .claude/settings.json (${x instanceof Error?x.message:String(x)}). Until that file can be written, the database connection may not be available to Claude Code. Your settings are saved.`)}),await je(t,He));let G=l.has("email")||"EMAIL_ADDRESS"in r||"EMAIL_AUTH"in r;await sl(t,p,G);let U=ht.filter(x=>T.has(x));console.log(`CONFIGURE-DONE sections=${w.join(",")} checked=${U.join(",")}`)}var Va=5;async function Ya(e){let t=(await Ka(e).catch(()=>[])).filter(n=>n.startsWith("configure-")).sort();for(let n of t.slice(0,Math.max(0,t.length-Va)))await Fs(he(e,n),{recursive:!0,force:!0}).catch(()=>{})}function Wa(e,t,n,i,s){let o=new Set;if("AI_PLAN"in t&&!("QA_PHASE"in t)&&(e.qaPhase=_e(e.aiPlan),o.add("QA_PHASE")),("PRICING"in t||"PRICING_MONTHLY"in t)&&!("PRICING_TERMS"in t)){Nn(e,i.PRICING,i.PRICING_MONTHLY);for(let m of["PRICING","PRICING_MONTHLY","PRICING_TERMS"])o.add(m)}let r=Te(n),d="EMAIL_PROVIDER"in t||!("EMAIL_SMTP_HOST"in t)?Te(i):Te({...i,EMAIL_PROVIDER:""});if(d&&d!=="custom"&&d!==r){let m=te[d];"EMAIL_PROVIDER"in t||(e.emailProvider=d,o.add("EMAIL_PROVIDER"));let w=[{smtpHost:m.smtpHost,imapHost:m.imapHost},...m.altHostSets??[]],h=T=>(t[T]??"").trim().toLowerCase(),l=w.find(T=>T.smtpHost===h("EMAIL_SMTP_HOST")||T.imapHost===h("EMAIL_IMAP_HOST"))??w[0],E=[["EMAIL_SMTP_HOST",()=>e.emailSmtpHost=l.smtpHost],["EMAIL_SMTP_PORT",()=>e.emailSmtpPort=m.smtpPort],["EMAIL_IMAP_HOST",()=>e.emailImapHost=l.imapHost],["EMAIL_IMAP_PORT",()=>e.emailImapPort=m.imapPort],...$n(d).map(([T,I,O])=>[T,()=>e[I]=O])];for(let[T,I]of E)T in t||(I(),o.add(T))}let c=m=>(m??"").split(",").map(w=>w.trim().toLowerCase()).filter(Boolean),p=s,u="OUTREACH_PRIORITY"in t,g=p?"OUTREACH_CHANNELS":"OUTREACH_PRIORITY";if(p!==u&&!js(i[g],n[g])){let m=c(i[g]),w=c(n[p?"OUTREACH_PRIORITY":"OUTREACH_CHANNELS"]),l=[...w.filter(E=>m.includes(E)),...m.filter(E=>!w.includes(E))];p?(e.outreachPriority=l,o.add("OUTREACH_PRIORITY")):(e.outreachChannels=l,o.add("OUTREACH_CHANNELS"))}return o}function js(e,t){let n=o=>[...new Set((o??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean))].sort(),i=n(e),s=n(t);return i.length===s.length&&i.every((o,r)=>o===s[r])}function qa(e){return e.trim().match(/^https:\/\/([a-z0-9]+)\.supabase\.co(?=[:/]|$)/i)?.[1]?.toLowerCase()}function za(e,t){return[["SUPABASE_SERVICE_KEY",e.supabaseServiceKey],["SUPABASE_PAT",e.supabasePat]].filter(([i,s])=>(t[i]??"")!==(s??"")).map(([i])=>i)}function Ja(e,t){return e?"Couldn't finish writing the settings \u2014 your previous .env has been put back.":`Couldn't finish writing the settings, and couldn't put your previous .env back either. Your previous settings are in ${t}.`}function Qa(e){let t=e.DEPLOY_PROVIDER?.trim()||"vercel";return["SUPABASE_URL","SUPABASE_SERVICE_KEY","SUPABASE_PAT","SUPABASE_PROJECT_REF",...t==="cloudflare"?["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID"]:t==="netlify"?["NETLIFY_AUTH_TOKEN"]:t==="selfhost"?["SELFHOST_DEPLOY_TARGET","SELFHOST_URL_TEMPLATE"]:["VERCEL_TOKEN"],"PRICING"].filter(i=>!(e[i]??"").trim())}var Xa={SUPABASE_URL:"the database URL",SUPABASE_SERVICE_KEY:"the database secret key",SUPABASE_PAT:"the database access token",SUPABASE_PROJECT_REF:"the database project reference",VERCEL_TOKEN:"the Vercel token",CLOUDFLARE_API_TOKEN:"the Cloudflare API token",CLOUDFLARE_ACCOUNT_ID:"the Cloudflare account ID",NETLIFY_AUTH_TOKEN:"the Netlify token",SELFHOST_DEPLOY_TARGET:"the server to deploy to",SELFHOST_URL_TEMPLATE:"the web address your sites are published at",PRICING:"the price you charge"};function Za(e){let t=e.map(s=>Xa[s]??s),n=t.length===0?"Some of this install's settings are missing, so there's nothing to change yet. Set the install up again from this folder.":`This install has no ${tl(t)} any more, so it can't be changed until that's back. Fill ${t.length===1?"it":"them"} in, and nothing else changes.`;switch(e[0]===void 0?void 0:el(e[0])){case"supabase":_("supabase",n);case"vercel":_("vercel",n);case"cloudflare":_("cloudflare",n);case"netlify":_("netlify",n);case"selfhost":_("selfhost",n);default:_("answers",n)}}function el(e){return ht.find(t=>Us[t].includes(e))}function tl(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function nl(e){if(e===void 0)return null;let t=e.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),n=new Set(ht),i=t.filter(s=>!n.has(s));return i.length>0&&_("answers",`Not a section that can be checked: ${i.join(", ")}. The sections are: ${ht.join(", ")}.`),new Set(t)}async function il(e,t,n){let i=new Set,s=new Set,o=e.outreachChannels??[],r=c=>!!e.outreachEnabled&&o.includes(c);if(n("supabase")&&e.supabaseUrl&&e.supabaseServiceKey){a.step("Checking the database credentials");let c=await $e({url:e.supabaseUrl,serviceKey:e.supabaseServiceKey});c.ok||_("supabase",c.message??"Supabase check failed"),i.add("supabase"),a.success("Database credentials accepted")}let d=e.deployProvider??"vercel";if(d==="vercel"&&n("vercel")&&e.vercelToken){a.step("Checking the Vercel token");let c=await Me(e.vercelToken);if(!c.ok){let p=c.kind==="rejected"||c.kind==="scope";_("vercel",p?`${c.message} Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration).`:c.message)}i.add("vercel"),a.success(c.username?`Vercel token accepted (signed in as ${c.username})`:"Vercel token accepted")}else if(d==="cloudflare"&&n("cloudflare")&&e.cloudflareApiToken&&e.cloudflareAccountId){a.step("Checking the Cloudflare token + account");let c=await De({token:e.cloudflareApiToken,accountId:e.cloudflareAccountId});c.ok||_("cloudflare",c.message??"Cloudflare check failed"),i.add("cloudflare"),a.success("Cloudflare credentials accepted")}else if(d==="netlify"&&n("netlify")&&e.netlifyAuthToken){a.step("Checking the Netlify token");let c=await Fe({token:e.netlifyAuthToken});c.ok||_("netlify",c.message??"Netlify check failed"),i.add("netlify"),a.success(c.accountSlug?`Netlify token accepted (team: ${c.accountSlug})`:"Netlify token accepted")}else if(d==="selfhost"&&n("selfhost")){let c=Xe(e.selfhostDeployTarget??""),p=Ze(e.selfhostUrlTemplate??"");(c||p)&&_("selfhost",[c&&`SELFHOST_DEPLOY_TARGET: ${c}`,p&&`SELFHOST_URL_TEMPLATE: ${p}`].filter(Boolean).join(`
|
|
121
|
+
`)),i.add("selfhost"),a.success("Self-host deploy settings accepted (SSH reachability is tested at your first deploy)")}if(n("google-places")&&e.googlePlacesApiKey){a.step("Checking the Google Places API key");let c=ke(e.googlePlacesApiKey),p=await Ue(e.googlePlacesApiKey);if(p.ok||_("google-places",p.message??"Google Places check failed"),c.changed){e.googlePlacesApiKey=c.value,s.add("GOOGLE_PLACES_API_KEY");for(let u of c.repairs)a.detail(`Corrected a look-alike character: ${u}`)}i.add("google-places"),a.success("Google Places API key accepted")}if(n("email")&&r("email")&&e.emailAuth!=="oauth-microsoft"){let c=[["email address",e.emailAddress],["password",e.emailPassword],["SMTP host",e.emailSmtpHost],["IMAP host",e.emailImapHost]].filter(([,w])=>!w).map(([w])=>w),p=[["SMTP port",e.emailSmtpPort],["IMAP port",e.emailImapPort]].filter(([,w])=>!w).map(([w])=>w),u=[...c.length>0?[`the ${c.join(", ")} ${c.length===1?"is":"are"} missing`]:[],...p.length>0?[`the ${p.join(" and ")} ${p.length===1?"isn't a number":"aren't numbers"}`]:[]];u.length>0&&_("email",`Email outreach is switched on, but ${u.join(", and ")}. Fill ${u.length===1&&c.length+p.length===1?"it":"them"} in, or turn email off.`),a.step("Checking the email credentials (SMTP + IMAP)");let g=e.emailProvider&&e.emailProvider!=="custom"?e.emailProvider:pe(e.emailSmtpHost),m=await me({emailAddress:e.emailAddress,emailLogin:e.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:e.emailPassword,emailSmtpHost:e.emailSmtpHost,emailSmtpPort:e.emailSmtpPort,emailImapHost:e.emailImapHost,emailImapPort:e.emailImapPort,usesAccountPassword:g?te[g].usesAccountPassword:void 0,knownProvider:!!g,sentFolder:(e.emailSentFolder??"").trim()||"Sent",draftsFolder:(e.emailDraftsFolder??"").trim()||"Drafts"});m.ok||_("email",m.message??"Email check failed"),i.add("email"),a.success("Email credentials accepted (SMTP + IMAP)"),await ct(m,e,{nonInteractive:!0})&&(s.add("EMAIL_SENT_FOLDER"),s.add("EMAIL_DRAFTS_FOLDER"))}if(n("sms")&&r("sms")){let c=Bt(e,t);if(c&&_("sms",c),e.smsProvider==="twilio"){a.step("Checking the Twilio credentials");let p=await rn({accountSid:e.twilioAccountSid,authToken:e.twilioAuthToken});p.ok||_("sms",p.message??"Twilio check failed"),i.add("sms"),a.success(p.friendlyName?`Twilio credentials accepted (${p.friendlyName})`:"Twilio credentials accepted")}}if(n("letter")&&r("letter")){let c=Vt(e,t);c&&_("letter",c),a.step("Checking the letter provider credentials");let p=await dt({provider:e.letterProvider,pingenClientId:e.pingenClientId,pingenClientSecret:e.pingenClientSecret,pingenOrgId:e.pingenOrgId,postgridApiKey:e.postgridApiKey});p.ok||_("letter",p.message??"Letter provider check failed"),i.add("letter"),a.success("Letter provider credentials accepted")}if(n("notifications")){let c=e.notifyChannel,p=Yt(e,t);if(p&&_("notifications",p),(c??"telegram")==="telegram"&&e.telegramBotToken&&e.telegramChatId){a.step("Checking the Telegram bot + chat (sending a test message)");let u=await $t({botToken:e.telegramBotToken,chatId:e.telegramChatId});u.ok||_("notifications",u.message??"Telegram check failed"),i.add("notifications"),a.success(u.botHandle?`Telegram bot ${u.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered")}}return{checked:i,rewritten:s}}async function sl(e,t,n){if(t.emailAuth!=="oauth-microsoft"||!n||await Qt(e,t.emailAddress??""))return;let i=await Q();if(!i){a.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in.");return}let[s,...o]=i.command;a.step("Connecting your Outlook / Microsoft 365 mailbox (one-time browser sign-in)"),Ga(s,[...o,"-u","scripts/ms_oauth.py","login"],{cwd:e,stdio:"inherit",timeout:39e5}).status===0?(await Xt(e,t.emailAddress??""),a.success("Outlook mailbox connected.")):a.warn("The Microsoft sign-in didn't complete. Your settings are saved.")}import{mkdir as al}from"fs/promises";import{spawnSync as Ks}from"child_process";async function Gs(e){let t=e.projectRoot??process.cwd();if(e.answers){await Hs({projectRoot:t,answers:e.answers,sections:e.sections});return}e.sections&&_("answers","The sections to check were given without the new settings to check them against, so there is nothing to reconfigure.");let n=gt(t,".env"),i=gt(t,".mcp.json"),s=gt(t,".codex","config.toml"),o=await Qn(gt(t,".klaudius","manifest.json")),r=await Qn(n);!o&&!r&&(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let d=we();d.ok||(a.error(d.message??"Node.js version check failed."),a.blank(),a.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 h=await ol(n,"utf-8");c=J(h)}catch{a.warn("No .env found. Starting from an empty configuration.")}let p=Li(c);Object.keys(c).length>0&&(p.pipelineModes??=["classic"]),ce.intro("Reconfigure Klaudius"),a.detail("Press Enter on any prompt to keep its current value."),a.blank();let u=await W(p),g=p.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==g&&(a.error(`Switching AI coding agent (${g} \u2192 ${u.aiAgent}) isn't supported via configure.`),a.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),a.blank(),console.log(` ${Oe.cyan("npx klaudius@latest init <new-folder>")} ${Oe.dim("# pick the new agent in the wizard")}`),a.blank(),a.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){a.heading("Re-validating Supabase credentials");let h=await $e({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});h.ok||(a.error(h.message??"Supabase check failed"),a.warn("Aborting. .env not modified."),process.exit(1)),a.success("Supabase credentials accepted")}let m=cl(u,c);if(m==="vercel"){let h=ce.spinner();h.start("Validating Vercel token");let l=await Me(u.vercelToken??"");l.ok?h.stop(l.username?`Vercel token accepted (signed in as ${l.username})`:"Vercel token accepted"):(h.stop(l.message,2),a.warn("Writing the token exactly as you entered it \u2014 not verified."),a.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(m==="cloudflare"){let h=ce.spinner();h.start("Validating Cloudflare token + account");let l=await De({token:u.cloudflareApiToken??"",accountId:u.cloudflareAccountId??""});l.ok?h.stop("Cloudflare credentials accepted"):(h.stop(l.message??"Cloudflare check failed",2),a.warn("Writing the credentials exactly as you entered them \u2014 not verified."),a.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(m==="netlify"){let h=ce.spinner();h.start("Validating Netlify token");let l=await Fe({token:u.netlifyAuthToken??""});l.ok?h.stop(l.accountSlug?`Netlify token accepted (team: ${l.accountSlug})`:"Netlify token accepted"):(h.stop(l.message??"Netlify check failed",2),a.warn("Writing the token exactly as you entered it \u2014 not verified."),a.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let w=ke(u.googlePlacesApiKey??"");if(w.changed&&u.googlePlacesApiKey){a.heading("Checking your Google Places API key");let h=await Ue(u.googlePlacesApiKey);if(h.ok){if(w.repairs.length>0){a.warn("Corrected look-alike characters in your Google Places API key:");for(let l of w.repairs)a.detail(` ${l}`);a.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=w.value,a.success("Google accepted the key \u2014 writing the corrected value to .env")}else a.error(h.message??"Google rejected the Google Places API key"),a.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),a.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(ll(u,c)){let h=ce.spinner();h.start("Validating email credentials (SMTP + IMAP)");let l=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:pe(u.emailSmtpHost),E=await me({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?te[l].usesAccountPassword:void 0,knownProvider:!!l,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});E.ok?(h.stop("Email credentials accepted (SMTP + IMAP)"),await ct(E,u,{nonInteractive:!1,onCancel:()=>a.detail("Left the folder names as they are.")})):(h.stop(E.message??"Email check failed",2),a.warn("Writing the email settings exactly as you entered them \u2014 not verified."),a.detail(E.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await Jn(n,st(u),"utf-8"),a.success("Updated .env"),u.aiAgent==="codex"?(await al(gt(t,".codex"),{recursive:!0}),await Jn(s,rt(u),"utf-8"),a.success("Updated .codex/config.toml")):(await Jn(i,ot(u),"utf-8"),a.success("Updated .mcp.json"),await ft(t,"supabase"),await je(t,He)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let h=await Q();if(!(h!==null&&Ks(h.command[0],[...h.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(a.blank(),!h)a.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),a.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let E=await ce.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});ce.isCancel(E)||!E?a.detail(`Skipped. Connect it any time with: ${h.command.join(" ")} scripts/ms_oauth.py login`):Ks(h.command[0],[...h.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?a.success("Outlook mailbox connected."):(a.warn("The Microsoft sign-in didn't complete."),a.detail(`Connect it any time with: ${h.command.join(" ")} scripts/ms_oauth.py login`))}}a.blank(),ce.outro(Oe.green("Configuration updated.")),await dl(t,o)}function ll(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(([s])=>s===void 0||s===""))return!1;let i=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([s,o])=>String(s)!==(t[o]??""))||i.some(([s,o])=>s!==void 0&&s!==(t[o]??""))}function cl(e,t){let n=(i,s)=>(i??"")!==(t[s]??"");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 dl(e,t){let n=await Qn(gt(e,"node_modules"));a.blank(),t?n||(a.detail("Your project files are in place but dependencies aren't installed yet."),a.detail("To finish setup, run:"),a.blank(),console.log(` ${Oe.cyan("npx klaudius@latest install")} ${Oe.dim("# (re-)installs npm + pip + browsers; idempotent")}`),a.blank(),a.detail("Then verify with:"),a.blank(),console.log(` ${Oe.cyan("npx klaudius@latest doctor")} ${Oe.dim("# checks Node / Python / installers / credentials")}`),a.blank()):(a.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),a.detail("To finish setup, run:"),a.blank(),console.log(` ${Oe.cyan("npx klaudius@latest init")} ${Oe.dim("# pick Resume when prompted")}`),a.blank())}async function Qn(e){try{return await rl(e),!0}catch{return!1}}import{copyFile as oi,mkdir as yn,readFile as Rt,rm as Pe,writeFile as kn,access as ri}from"fs/promises";import{dirname as wn,join as F}from"path";import{tmpdir as $l}from"os";import*as Ke from"@clack/prompts";import vt from"picocolors";import{execFile as ii}from"child_process";import{createHash as ul}from"crypto";import{access as pl,copyFile as Qs,lstat as fl,mkdir as ei,mkdtemp as Xs,open as ml,readFile as se,realpath as hl,rm as kt,stat as Zs,unlink as gl,writeFile as It}from"fs/promises";import{tmpdir as eo}from"os";import{dirname as Je,isAbsolute as Xn,join as K,relative as Bs,resolve as Tt}from"path";var ti={"Edit conflict":["keep-mine","take-new","check-merge","merge","auto-merge"],"Deleted locally":["restore","keep-deleted"],"Removed upstream":["keep-mine","delete"]},ni=K(".klaudius","conflicts.md"),si=K(".klaudius","incoming"),yl=K(".klaudius","resolve.lock"),Ct=K(".klaudius","merged"),kl=12e4,wl=3e4,Al=[["keepMine","keep-mine"],["takeNew","take-new"],["checkMerge","check-merge"],["merge","merge"],["autoMerge","auto-merge"],["restore","restore"],["keepDeleted","keep-deleted"],["delete","delete"]];function to(e,t){let n=Al.filter(([s])=>t[s]!==void 0&&t[s]!==!1),i=[t.checkMerge,t.merge].find(s=>typeof s=="string");return{path:e,action:n.length===1?n[0][1]:void 0,draft:i,finish:t.finish===!0}}function El(e){let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return`.klaudius/merged/draft${n>0?t.slice(n):""}`}function Vs(e,t,n,i){if(/^(<<<<<<<|>>>>>>>)/m.test(t))return"still has conflict markers (<<<<<<< or >>>>>>>): finish the merge first";if(!e.toLowerCase().endsWith(".json")||n===null||i===null)return null;let s=r=>{try{return JSON.parse(r.replace(/^/,"")),null}catch(d){return d.message}};if(s(n)!==null||s(i)!==null)return null;let o=s(t);return o===null?null:`isn't valid JSON (${o})`}function Zn(e){let t=[];for(let n=0;n<e.length;n++){let i=e[n];if(i==='"'){let s=n+1;for(;s<e.length&&e[s]!=='"';)s+=e[s]==="\\"?2:1;let o=s+1;for(;o<e.length&&/\s/.test(e[o]);)o++;let r=t[t.length-1];if(e[o]===":"&&r){let d=e.slice(n+1,s);if(r.has(d))return d;r.add(d)}n=s}else i==="{"?t.push(new Set):i==="["?t.push(null):(i==="}"||i==="]")&&t.pop()}return null}var Pl={".js":[process.execPath,["--check"]],".mjs":[process.execPath,["--check"]],".cjs":[process.execPath,["--check"]],".sh":["bash",["-n"]],".py":["python3",["-c","import ast, sys; ast.parse(open(sys.argv[1], 'rb').read(), sys.argv[1])"]]};async function Ys(e,t,n,i,s){let o=e.slice(e.lastIndexOf("/")+1),r=o.lastIndexOf("."),d=r>0?o.slice(r).toLowerCase():"";if(d===".json"){let m=h=>{try{return JSON.parse(h.replace(/^/,"")),!0}catch{return!1}};if(!m(n)||!m(i)||Zn(n)!==null||Zn(i)!==null)return null;let w=Zn(t.toString());return w===null?null:`gives the key "${w}" twice`}let c=d===".js"?await Sl(s)==="module"?".mjs":".cjs":d,p=Pl[c];if(!p)return null;let u={...process.env,NO_COLOR:"1",PYTHON_COLORS:"0"};delete u.FORCE_COLOR;let g;try{g=await Xs(K(eo(),"klaudius-check-"))}catch{return null}try{let m=async(h,l)=>{let E=K(g,`${l}${c}`);await It(E,h);let T=await hl(E).catch(()=>E);return new Promise(I=>ii(p[0],[...p[1],E],{windowsHide:!0,timeout:1e4,env:u},(O,N,b)=>{if(!O||O.killed||O.signal||typeof O.code!="number")return I(null);let C=String(b).split(/\r?\n/).map(U=>U.split(T).join(e).split(E).join(e).trim()).filter(Boolean),M=C.find(U=>/^\w*Error\b|syntax error/i.test(U))??C[C.length-1]??O.message.split(`
|
|
122
|
+
`)[0],G=C.find(U=>U.includes(e))?.match(/(?:line |:)(\d+)/)?.[1];I(G&&!/\bline \d+/.test(M)?`${M}, line ${G}`:M)}))};if(await m(n,"yours")!==null||await m(i,"new")!==null)return null;let w=await m(t,"merged");return w===null?null:`no longer parses (${w})`}catch{return null}finally{await kt(g,{recursive:!0,force:!0}).catch(()=>{})}}async function Sl(e){for(let t=Tt(e);;t=Je(t)){let n=await se(K(t,"package.json"),"utf-8").catch(()=>null);if(n!==null)try{return JSON.parse(n).type??"commonjs"}catch{return"commonjs"}if(Je(t)===t)return"commonjs"}}function bl(e){let t=e.split(`
|
|
123
|
+
`),n=[],i=!1;t.forEach((o,r)=>{o.startsWith("```")?i=!i:!i&&o.startsWith("## ")&&n.push({path:o.slice(3).trim(),start:r})});let s=n.map((o,r)=>{let d=r+1<n.length?n[r+1].start:t.length,p=t.slice(o.start,d).find(u=>u.startsWith("**Type:**"))?.slice(9).trim();return{...o,end:d,type:p!==void 0&&p in ti?p:null}});return{lines:t,sections:s}}function _l(e,t,n){let i=[...e.lines.slice(0,t.start),...e.lines.slice(t.end)],s=i.findIndex(r=>r.startsWith("Updating from")),o=s>=0&&s+2<e.sections[0].start?i[s+2]:"";return o.trim()!==""&&!o.startsWith("Open ")&&!o.startsWith("---")&&(i[s+2]=`${n} ${n===1?"conflict is":"conflicts are"} still waiting for a decision; the others are settled.`),i.join(`
|
|
124
|
+
`)}function Tl(e){let t=e.match(/^Generated by .* on (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/m)?.[1];return`.klaudius/backup/resolve-${t?t.replace(/[:.]/g,"-"):"undated"}`}var yt=e=>pl(e).then(()=>!0,()=>!1);async function Il(e,t,n){let i=`${n}.bak`;for(let o=2;await yt(K(e,t,i));o++)i=`${n}.${o}.bak`;let s=K(e,t,i);return await ei(Je(s),{recursive:!0}),await Qs(K(e,n),s),`${t}/${i}`}function Cl(e,t,n,i){let s=g=>{let m=new Map;for(let w of g.split(/\r\n|\r|\n/))w.trim()&&m.set(w,(m.get(w)??0)+1);return m},o=(g,m)=>g.get(m)??0,r=s(e),d=s(i),c=[["Your",s(t)],["The update's",s(n)]],p=g=>{let m=o(r,g),w=o(c[0][1],g)-m,h=o(c[1][1],g)-m,l=Math.max(0,m+w+h);return w>0&&h>0?{min:m+Math.max(w,h),max:l}:w<0&&h<0?{min:l,max:Math.max(0,m+Math.min(w,h))}:{min:l,max:l}},u=[];for(let[g,m]of c){let w=[...new Set([...m.keys(),...r.keys()])].filter(E=>o(m,E)!==o(r,E)),h=w.filter(E=>o(m,E)>o(r,E)&&o(d,E)<p(E).min),l=w.filter(E=>o(m,E)<o(r,E)&&o(d,E)>p(E).max);u.push(`${g} edits kept: ${w.length-h.length-l.length} of ${w.length}`);for(let E of h)u.push(` dropped: ${E.trim().slice(0,120)}`);for(let E of l)u.push(` still present: ${E.trim().slice(0,120)}`)}return u}function Rl(e,t,n){return new Promise(i=>{ii("git",["merge-file","-p",e,t,n],{encoding:"buffer",maxBuffer:64*1024*1024,windowsHide:!0},(s,o)=>{if(!s)return i({merged:o});let r=s.code;if(typeof r=="number"&&r>0&&r<128)return i({overlaps:r});i({unavailable:s.message.split(`
|
|
125
|
+
`)[0]})})})}var Ws=40;function vl(e,t){let n=d=>{let c=d.toLowerCase(),p=new Map;for(let u=0;u<c.length-1;u++)p.set(c.slice(u,u+2),(p.get(c.slice(u,u+2))??0)+1);return p},[i,s]=[n(e),n(t)],o=0,r=0;for(let[d,c]of i)o+=Math.min(c,s.get(d)??0),r+=c;for(let d of s.values())r+=d;return r>0&&2*o/r>=.5}async function Ol(e,t,n,i){let s=r=>r.replace(/\r\n?/g,`
|
|
126
|
+
`),o;try{o=await Xs(K(eo(),"klaudius-clash-"))}catch{return[]}try{let[r,d,c]=["mine","base","theirs"].map(O=>K(o,O));await It(r,s(t)),await It(d,s(e)),await It(c,s(n));let p=await new Promise(O=>ii("git",["merge-file","-p","--diff3",`--marker-size=${Ws}`,r,d,c],{encoding:"utf8",maxBuffer:64*1024*1024,windowsHide:!0},(N,b)=>{let C=N?.code;O(!N||typeof C=="number"&&C>0&&C<128?b:null)}));if(p===null)return[];let u=O=>{let N=new Map;for(let b of s(O).split(`
|
|
127
|
+
`)){let C=b.trim();C&&N.set(C,(N.get(C)??0)+1)}return N},g=(O,N)=>O.get(N)??0,[m,w,h]=[u(i),u(t),u(n)],l=O=>O.repeat(Ws),E=[],T=null,I={mine:[],base:[],theirs:[]};for(let O of p.split(`
|
|
128
|
+
`))if(O.startsWith(`${l("<")} `))T="mine",I={mine:[],base:[],theirs:[]};else if(T&&O.startsWith(`${l("|")} `))T="base";else if(T&&O===l("="))T="theirs";else if(T&&O.startsWith(`${l(">")} `)){let N=G=>G.map(U=>U.trim()),b=N(I.mine),C=N(I.base),M=N(I.theirs);if(C.length>0&&b.length===C.length&&M.length===C.length)for(let G=0;G<C.length;G++){let[U,x,R]=[b[G],C[G],M[G]];!U||!R||U===x||R===x||U===R||!vl(U,R)||g(m,U)>g(h,U)&&g(m,R)>g(w,R)&&E.push(` kept both versions: ${U.slice(0,120)} / ${R.slice(0,120)}`)}T=null}else T&&I[T].push(O);return E}catch{return[]}finally{await kt(o,{recursive:!0,force:!0}).catch(()=>{})}}async function qs(e,t,n,i){let s=await se(K(e,Re,t),"utf-8").catch(()=>null);if(s===null)return["No pre-edit base was staged for this file, so there is no line check. Say in plain words what the merge keeps from each side."];let o=await se(K(e,i,`${t}.bak`),"utf-8").catch(()=>null)??await se(K(e,t),"utf-8").catch(()=>""),r=await se(K(e,si,t),"utf-8");return[s,o,r,n].some(Ne)?["Binary file: no line check."]:["Line check against the pre-edit base:",...Cl(s,o,r,n),...await Ol(s,o,r,n)]}function gn(e,t,n=0){for(let i of e)console.log(i);return console.log(`[klaudius-resolve] ${t}`),n}function j(e,t){return console.error(`${e} Nothing was changed.`),console.log(`[klaudius-resolve] refused${t===void 0?"":` remaining=${t}`}`),1}async function zs(e,t,n,i){let s=n?.match(/to \*\*([^*]+)\*\*/)?.[1]?.trim();(i||s||t.pendingConflicts!==void 0)&&(s&&(t.templateVersion=s),delete t.pendingConflicts,t.updatedAt=new Date().toISOString(),await Le(e,t));let o=d=>kt(K(e,d),{recursive:!0,force:!0,maxRetries:3}).then(()=>!0,()=>!1);if(!await o(ni))return{complete:!1,lines:[".klaudius/conflicts.md couldn't be removed, so the update staging was kept. Close anything that has it open, then run the same command again."]};let r=!1;for(let d of[si,Re,Ct])await o(d)||(r=!0);return{complete:!0,lines:[r?"Nothing is waiting for a decision. Some staging under .klaudius/ couldn't be removed; the next update clears it.":"Nothing is waiting for a decision. Update staging cleared."]}}var Js=e=>new Promise(t=>setTimeout(t,e));function xl(e,t){if(Date.now()-t>kl)return!0;let n=Number(e.trim());if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!1}catch(i){return i.code==="ESRCH"}}async function Ll(e,t){let n=K(e,yl),i=Date.now(),s=!1,o=0;for(;;)try{let r=await ml(n,"wx");await r.writeFile(String(process.pid)).finally(()=>r.close());break}catch(r){let d=r.code;if(d!=="EEXIST"&&d!=="EPERM")throw r;let c=await Zs(n).catch(()=>null);if(c===null){if(d==="EPERM"&&++o>5)throw r;await Js(50);continue}let p=await se(n,"utf-8").catch(()=>"");if(!s&&xl(p,c.mtimeMs)){s=!0,await se(n,"utf-8").catch(()=>"")===p&&await kt(n).catch(u=>{if(u.code!=="ENOENT")throw new Error(`.klaudius/resolve.lock was left by an earlier run and can't be removed (${u.message})`)});continue}if(Date.now()-i>wl)return null;await Js(100)}try{return await t()}finally{await kt(n,{force:!0}).catch(()=>{})}}async function no(e){let t=e.projectRoot??process.cwd();return await yt(K(t,".klaudius","manifest.json"))?await Ll(t,()=>Nl(t,e))??j("Another resolve is still running in this project; run this again once it has finished."):j("No .klaudius/manifest.json here: run this from the Klaudius project folder.")}async function Nl(e,t){let n;try{n=await zt(e)}catch(R){return j(`.klaudius/manifest.json can't be read (${R.message}).`)}if(!n)return j("No .klaudius/manifest.json here: run this from the Klaudius project folder.");let i=await se(K(e,ni),"utf-8").catch(()=>null),s=i===null?null:bl(i);if(t.finish){if(t.path||t.action)return j("--finish takes no file or action.");let R=s?.sections.length??0;if(R>0)return j(`${R} ${R===1?"conflict is":"conflicts are"} still waiting in .klaudius/conflicts.md.`,R);let Y=await zs(e,n,i,!1);return gn(Y.lines,Y.complete?"finished remaining=0":"remaining=0 incomplete",Y.complete?0:1)}if(!t.path||!t.action)return j("Name one file and exactly one action.",s?.sections.length);if(!s)return j("No conflicts are staged (.klaudius/conflicts.md is missing).",0);let o=s.sections.length,r=t.path.split("\\").join("/");if(Xn(t.path)&&(r=Bs(e,t.path).split("\\").join("/")),r=r.replace(/^\.\//,""),r===""||Xn(r)||/^[a-zA-Z]:/.test(r)||r.split("/").includes(".."))return j(`${t.path} isn't a path inside this project.`,o);let d=s.sections.find(R=>R.path===r);if(!d)return j(`${r} isn't waiting in .klaudius/conflicts.md (waiting: ${s.sections.map(R=>R.path).join(", ")||"none"}).`,o);let c=K(e,r),p=K(e,si,r),u=await yt(c),g=await yt(p),m=d.type??(g?u?"Edit conflict":"Deleted locally":"Removed upstream"),w=t.action;if(!ti[m].includes(w))return j(`${r} is a "${m}" conflict; its options are ${ti[m].map(R=>`--${R}`).join(", ")}.`,o);if(m!=="Removed upstream"&&!g)return j(`The staged new version .klaudius/incoming/${r} is missing; run npx klaudius@latest update to stage it again.`,o);if(m==="Edit conflict"&&!u&&(w==="keep-mine"||w==="check-merge"||w==="merge"||w==="auto-merge"))return j(`${r} is no longer on disk, so there's no version of yours to ${w==="keep-mine"?"keep":"merge"}; choose --take-new.`,o);let h=Tl(i),l=null,E=[];if(w==="check-merge"||w==="merge"){if(!t.draft)return j(`--${w} needs the merged draft's path.`,o);if(l=Tt(e,t.draft),process.platform==="linux"?l===Tt(c):l.toLowerCase()===Tt(c).toLowerCase())return j(`Write the merged version to its own draft file (${El(r)}), not over ${r}: the original is what gets backed up.`,o);let Y=await se(l,"utf-8").catch(()=>null);if(Y===null)return j(`Can't read the draft ${t.draft}.`,o);let re=await se(p,"utf-8").catch(()=>null),z=await se(c,"utf-8").catch(()=>null),y=Vs(r,Y,re,z)??(re!==null&&z!==null?await Ys(r,Y,z,re,Je(c)):null);if(y)return j(`The draft ${t.draft} ${y}.`,o);if(E=await qs(e,r,Y,h),w==="check-merge")return gn(E,`checked path=${r} remaining=${o}`)}let T=null;if(w==="auto-merge"){if(r.split("/").pop()===".gitignore")return j(".gitignore is only merged as a union (every line of the user's kept, the new patterns added, nothing removed), so it can't be merged automatically; merge it by hand.",o);let R=K(e,Re,r);if(!await yt(R))return j(`${r} has no pre-edit base, so it can't be merged automatically; merge it by hand.`,o);let Y=K(e,h,`${r}.bak`),re=await yt(Y)?Y:c,z=await Rl(re,R,p);if("overlaps"in z)return j(`Your edits and the update's overlap in ${r} (${z.overlaps} place${z.overlaps===1?"":"s"}), so it can't be merged automatically; merge it by hand.`,o);if("unavailable"in z)return j(`git merge-file couldn't run (${z.unavailable}), so ${r} can't be merged automatically; merge it by hand.`,o);let y=z.merged.toString("utf-8"),f=await se(p,"utf-8").catch(()=>null),k=await se(re,"utf-8").catch(()=>null),P=Vs(r,y,f,k)??(f!==null&&k!==null?await Ys(r,z.merged,k,f,Je(c)):null);if(P)return j(`The automatic merge of ${r} ${P}; merge it by hand.`,o);E=await qs(e,r,y,h);let D=E.filter(S=>/^\s+(dropped|still present|kept both versions):/.test(S)).map(S=>S.trim());if(D.length>0)return j(`The automatic merge of ${r} doesn't keep every edit (${D.join("; ")}); merge it by hand.`,o);T=z.merged}if(w==="keep-deleted"&&u)return j(`${r} exists again, so it can't stay deleted; choose --restore, or move the file away first.`,o);let I=g?await fe(p):void 0,O=w==="take-new"||w==="restore"?I:w==="merge"?await fe(l):T?ul("sha256").update(T).digest("hex"):void 0,N=u&&(w==="delete"||O!==void 0&&await fe(c)!==O),b=null;if(N)try{b=await Il(e,h,r)}catch(R){return j(`Couldn't save a backup copy of ${r} (${R.message}).`,o)}let C=[];switch(w){case"keep-mine":m==="Edit conflict"?(n.files[r]=I,C.push(`Kept your version of ${r}. Later updates treat it as your edit.`)):(delete n.files[r],C.push(`Kept ${r}. Klaudius no longer tracks it, so updates leave it alone.`));break;case"take-new":case"restore":await ei(Je(c),{recursive:!0}),await Qs(p,c),n.files[r]=I,n.ignored&&(n.ignored=n.ignored.filter(R=>R!==r)),C.push(w==="take-new"?`Replaced ${r} with the new version.`:`Restored ${r} in its new version.`);break;case"merge":case"auto-merge":{let R=u?(await Zs(c)).mode&4095:void 0,Y=T??await se(l);await ei(Je(c),{recursive:!0}),u&&(await fl(c)).isSymbolicLink()?await It(c,Y):await Ae(c,Y,R),n.files[r]=I,C.push(`Wrote the merged version to ${r}.`,...E);break}case"keep-deleted":delete n.files[r],n.ignored=[...new Set([...n.ignored??[],r])],C.push(`${r} stays deleted; updates won't reinstall it.`);break;case"delete":u&&await kt(c,{force:!0}),delete n.files[r],C.push(`Deleted ${r}.`);break}b&&C.push(`Your previous version is saved at ${b}.`);let M=o-1,G=!0;if(M>0)n.pendingConflicts=M,n.updatedAt=new Date().toISOString(),await Le(e,n),await Ae(K(e,ni),_l(s,d,M));else{let R=await zs(e,n,i,!0);C.push(...R.lines),G=R.complete}let U=l===null?"":Bs(Tt(e,Ct),l);G&&U&&!U.startsWith("..")&&!Xn(U)&&await gl(l).catch(()=>{});let x=`path=${r} action=${w} remaining=${M}`;return G?gn(C,x):gn(C,`${x} incomplete`,1)}var Ot="0.37.0";async function oo(e){let t=e.projectRoot??process.cwd(),n=await zt(t);n||(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let f of Wt)delete n.files[f];let i,s=F(t,".env"),o,r;try{o=await Rt(s,"utf-8"),r=J(o)}catch{a.error("Couldn't read .env from this directory."),a.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=r.KLAUDIUS_LICENSE_KEY??"",i||(a.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),a.detail("This file is created by `npx klaudius@latest init`. If your project predates"),a.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),a.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let d=e.check?null:vi(o,r,Ri);d!==null&&(await kn(s,d,"utf-8"),a.detail("Backfilled new env keys")),await nn("update",Ot),Ke.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Ot}`),await cn();let p=r.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&p==="claude-code"&&await je(t,He)==="added"&&a.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=F($l(),`klaudius-update-${process.pid}-${Date.now()}`),g;try{a.heading("Downloading the latest Klaudius template");let f=await en({licenseKey:i,machineId:_t(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});a.success(`Fetched ${f.filesExtracted} canonical files`),g=u}catch(f){a.error(f.message),a.detail("Update aborted. Your project is unchanged."),await Pe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let m=await Dl(g,t,n);if(e.check){let f=m.filter(S=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(S.state)),k=m.filter(S=>["conflict","locally-deleted","removed-modified"].includes(S.state)&&!(S.path===".gitignore"&&S.state==="conflict")),P="unknown";if(r.SUPABASE_URL&&r.SUPABASE_SERVICE_KEY){let S=await Rt(F(g,"scripts","schema.sql"),"utf-8").catch(()=>""),L=await sn({url:r.SUPABASE_URL,serviceKey:r.SUPABASE_SERVICE_KEY,sql:S});L.unreachable?a.detail(`Database schema not checked (${L.unreachable}).`):L.ok?P="current":(P="stale",a.detail(`Database schema is behind (missing: ${L.missing.join(", ")}); update applies scripts/schema.sql.`))}let D=f.length>0||P==="stale";a.blank(),D?(f.length>0&&a.detail(`${Z(f.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),Ke.outro(vt.yellow("An update is available."))):Ke.outro(vt.green("Already up to date.")),console.log(`[klaudius-update-check] status=${D?"behind":"current"} pending=${f.length+(P==="stale"?1:0)} conflicts=${k.length} schema=${P}`),await Pe(u,{recursive:!0,force:!0}).catch(()=>{});return}let w=!1,h=m.find(f=>f.path===".gitignore"&&f.state==="conflict");if(h){let f=F(t,".gitignore"),k=await Rt(f,"utf-8"),P=await Rt(F(g,".gitignore"),"utf-8"),{merged:D,added:S}=Ul(k,P);S.length>0&&await kn(f,D,"utf-8"),n.files[".gitignore"]=h.canonicalHash,h.state="gitignore-merged",w=!0,a.detail(S.length>0?`.gitignore auto-merged: kept all your lines, appended ${Z(S.length,"new canonical pattern")}: ${S.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let l=m.filter(f=>f.state==="new"),E=m.filter(f=>f.state==="clean-update"),T=m.filter(f=>f.state==="user-only"),I=m.filter(f=>f.state==="conflict"),O=m.filter(f=>f.state==="no-change"),N=m.filter(f=>f.state==="locally-deleted"),b=m.filter(f=>f.state==="removed-clean"),C=m.filter(f=>f.state==="removed-modified"),M=[...I,...N,...C],G=n.ignored?.length??0;a.blank(),a.heading("Change summary"),a.detail(`${Z(O.length,"file")} unchanged`),a.detail(`${Z(l.length,"new file")}`),a.detail(`${Z(E.length,"file")} updated cleanly (no local edits)`),a.detail(`${Z(T.length,"file")} you've edited (no upstream change \u2014 left alone)`),a.detail(`${Z(b.length,"file")} removed upstream (deleted cleanly)`);let U=I.filter(f=>f.reason==="untracked-local").length,x=I.filter(f=>f.reason==="manifest-mismatch").length;a.detail(`${Z(I.filter(f=>!f.reason).length,"file")} with conflicts (you edited AND we have a new version)`),U>0&&a.detail(`${Z(U,"file")} of your own at a path the new version now ships (need your decision)`),x>0&&a.detail(`${ai(x)}, and we have a new version (need your decision)`),a.detail(`${Z(N.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`);let R=C.filter(f=>f.reason==="manifest-mismatch").length;if(a.detail(`${Z(C.length-R,"file")} removed upstream but edited locally (need your decision)`),R>0&&a.detail(`${ai(R)}, removed upstream (need your decision)`),G>0&&(a.detail(`${Z(G,"file")} kept deleted (previously resolved \u2014 skipped)`),G<=10))for(let f of n.ignored)a.detail(` kept deleted: ${f}`);let Y=async()=>{let f=!1,k=P=>Pe(P,{recursive:!0,force:!0}).catch(()=>{f=!0});await k(F(t,".klaudius","incoming")),await k(F(t,Re)),await k(F(t,Ct)),await k(F(t,".klaudius","conflicts.md")),f&&a.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/, .klaudius/merged/ and .klaudius/conflicts.md by hand)")};if(l.length===0&&E.length===0&&b.length===0&&M.length===0&&!w){await io(t,r,!1),await Y(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ot,await Le(t,n)),a.blank(),Ke.outro(vt.green("Already up to date.")),await Pe(u,{recursive:!0,force:!0}).catch(()=>{});return}let re=new Date().toISOString().replace(/[:.]/g,"-"),z=`.klaudius/backup/update-${re}`,y=0;for(let f of[...E,...b]){if(f.localHash===void 0||f.localHash===f.canonicalHash)continue;let k=F(t,z,`${f.path}.bak`);try{await yn(wn(k),{recursive:!0}),await oi(F(t,f.path),k)}catch(P){a.error(`Couldn't save a backup copy of ${f.path}: ${P.message}`),a.detail("Update stopped before replacing or removing any files (additions already made, such as new .env keys, are kept)."),await Pe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}y++}a.blank(),a.heading("Applying clean updates");for(let f of[...l,...E]){let k=F(g,f.path),P=F(t,f.path);await yn(wn(P),{recursive:!0}),await oi(k,P),n.files[f.path]=f.canonicalHash}l.length+E.length>0&&a.success(`Wrote ${Z(l.length+E.length,"file")}`),[...l,...E].some(f=>f.path==="package.json"||f.path==="package-lock.json")&&a.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let f of b){let k=F(t,f.path);await Pe(k,{force:!0}),delete n.files[f.path]}if(b.length>0){a.success(`Deleted ${Z(b.length,"file")} removed upstream`);for(let f of b.slice(0,20))a.detail(` removed: ${f.path}`);b.length>20&&a.detail(` \u2026and ${b.length-20} more`)}if(y>0&&a.detail(`Previous copies of the ${Z(y,"file")} replaced or removed are in ${z}/ (each saved as <name>.bak)`),await io(t,r,M.some(f=>f.path==="scripts/schema.sql")),M.length>0){a.blank(),a.heading(`${M.length} conflict(s) need resolution`);let f=F(t,".klaudius","incoming");try{await Pe(f,{recursive:!0,force:!0})}catch{}await Pe(F(t,Ct),{recursive:!0,force:!0}).catch(()=>{});for(let S of[...I,...N]){let L=F(g,S.path),ie=F(f,S.path);await yn(wn(ie),{recursive:!0}),await oi(L,ie)}let k=new Map,P=new Map;for(let S of I){let L=await es(t,S.path),ie=await ts(t,S.path),be=await Rt(F(g,S.path),"utf-8"),ae=ns(L,ie,be,S.manifestHash);S.reason==="untracked-local"?k.set(S.path,["_Klaudius doesn't track this file (it's your own, or one kept after an earlier version dropped it), and the new version ships one at the same path. No common base exists: compare your copy with `.klaudius/incoming/"+S.path+"` directly._"]):S.reason==="manifest-mismatch"?k.set(S.path,["_The manifest's entry for this file isn't the version Klaudius last installed (a hand-edited manifest, a conflict resolved outside `/resolve-conflicts`, or a folder restored from an older copy), so your copy was left in place. No verified base exists: compare it with `.klaudius/incoming/"+S.path+"` directly. If the file was never changed on purpose, taking the new version is safe._"]):ae!==null?(P.set(S.path,ae),k.set(S.path,is(ae,be))):L!==null&&(Ne(L)||Ne(be))?k.set(S.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+S.path+"` directly._"]):L===null?k.set(S.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._"]):k.set(S.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/"+S.path+"` directly._"])}let D=F(t,Re);try{await Pe(D,{recursive:!0,force:!0})}catch{}for(let[S,L]of P){let ie=F(D,S);await yn(wn(ie),{recursive:!0}),await kn(ie,L,"utf-8")}await kn(F(t,".klaudius","conflicts.md"),Hl(M,n.templateVersion,Ot,k,P),"utf-8"),I.length+N.length>0&&a.detail("Staged canonical versions to .klaudius/incoming/"),P.size>0&&a.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),a.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Ot,n.baseSnapshot=re,M.length===0?(delete n.pendingConflicts,await Y()):n.pendingConflicts=M.length,await Le(t,n);try{await tn(t,g,await ze(g),re)}catch{a.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(a.blank(),M.length===0)Ke.outro(vt.green("Update complete."));else{let f=p==="codex"?"Codex":"Claude Code";Ke.outro(vt.yellow(`${M.length} conflict(s) staged. Open ${f} in this project and ask:
|
|
129
|
+
"Run /resolve-conflicts"`))}await Pe(u,{recursive:!0,force:!0}).catch(()=>{})}async function io(e,t,n){let i=await Ml(e,t,n);return console.log(`[klaudius-update] schema=${i}`),i}async function Ml(e,t,n){let i=(t.SUPABASE_PAT??"").replace(/\s+/g,""),s=(t.SUPABASE_PROJECT_REF??"").trim();if(!i||!s)return a.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 o=await lt({projectRoot:e,pat:i,projectRef:s});return o.ok?(a.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"):(a.warn(o.message??"Database schema could not be applied"),a.detail(`Paste scripts/schema.sql into the SQL editor to apply it by hand (safe to re-run): ${ls(s)}`),"failed")}async function Dl(e,t,n){let i=await ze(e),s=new Set(i),o=new Map;for(let p of i)o.set(p,await fe(F(e,p)));let r=await Fl(t,n,o),d=new Set(n.ignored??[]),c=[];for(let p of i){if(d.has(p))continue;let u=o.get(p),g=n.files[p],m=F(t,p),w;try{await ri(m),w=await fe(m)}catch{let l=g!==void 0&&!Ui.has(p)&&!qt.has(p)?"locally-deleted":"new";c.push({path:p,state:l,canonicalHash:u,manifestHash:g});continue}let h=qt.has(p);u===g?w===g||h?c.push({path:p,state:"no-change",canonicalHash:u,localHash:w,manifestHash:g}):c.push({path:p,state:"user-only",canonicalHash:u,localHash:w,manifestHash:g}):w===u||h?c.push({path:p,state:"clean-update",canonicalHash:u,localHash:w,manifestHash:g}):g===void 0?c.push({path:p,state:"conflict",reason:"untracked-local",canonicalHash:u,localHash:w,manifestHash:g}):w!==g?c.push({path:p,state:"conflict",canonicalHash:u,localHash:w,manifestHash:g}):await r(p,g)?c.push({path:p,state:"conflict",reason:"manifest-mismatch",canonicalHash:u,localHash:w,manifestHash:g}):c.push({path:p,state:"clean-update",canonicalHash:u,localHash:w,manifestHash:g})}for(let p of Object.keys(n.files)){if(s.has(p))continue;let u=n.files[p],g=F(t,p),m;try{await ri(g),m=await fe(g)}catch{delete n.files[p];continue}qt.has(p)?c.push({path:p,state:"removed-clean",localHash:m,manifestHash:u}):m!==u?c.push({path:p,state:"removed-modified",localHash:m,manifestHash:u}):await r(p,u)?c.push({path:p,state:"removed-modified",reason:"manifest-mismatch",localHash:m,manifestHash:u}):c.push({path:p,state:"removed-clean",localHash:m,manifestHash:u})}return c}async function Fl(e,t,n){let i=F(e,bt),s=async p=>{try{return await fe(p)}catch{return null}},o=async(p,u,g)=>{let m=await s(F(i,p));return m===u||await s(F(e,Re,p))===u?!1:m!==null||g},r=await Zi(e),d=r!==null&&r===t.baseSnapshot,c=d;if(!d&&r===null&&t.baseSnapshot===void 0&&await ri(i).then(()=>!0,()=>!1)){c=!0;for(let[p,u]of Object.entries(t.files)){if(n.get(p)!==u)continue;let g=await s(F(i,p));if(g!==null&&g!==u){c=!1;break}}}return async(p,u)=>c&&await o(p,u,d)}function ai(e){return`${Z(e,"file")} Klaudius can't confirm ${e===1?"is":"are"} unedited`}function so(e){return e.reason==="manifest-mismatch"?"Hash the manifest records: ":"Hash at last install/update:"}function Z(e,t){return`${e} ${t}${e===1?"":"s"}`}function Ul(e,t){let n=e.includes(`\r
|
|
125
130
|
`)?`\r
|
|
126
131
|
`:`
|
|
127
|
-
`,i=e.split(/\r?\n/),s=new Set(i.map(
|
|
128
|
-
`)}import{existsSync as
|
|
129
|
-
`)),n.push(await
|
|
132
|
+
`,i=e.split(/\r?\n/),s=new Set(i.map(c=>c.trim()).filter(c=>c!=="")),o=[];for(let c of t.split(/\r?\n/)){let p=c.trim();p===""||p.startsWith("#")||s.has(p)||(o.push(p),s.add(p))}if(o.length===0)return{merged:e,added:o};let r=[...i];for(;r.length>0&&r[r.length-1].trim()==="";)r.pop();r.push("","# Added by `klaudius update` (new canonical ignore patterns)",...o);let d=[...new Set(i.map(c=>c.trim()).filter(c=>c.startsWith("!")))].filter(c=>!o.includes(c));return r.push(...d,""),{merged:r.join(n),added:o}}function Hl(e,t,n,i=new Map,s=new Map){let o=e.filter(m=>m.state==="conflict"&&!m.reason).length,r=e.filter(m=>m.reason==="untracked-local").length,d=e.filter(m=>m.reason==="manifest-mismatch").length,c=e.filter(m=>m.state==="locally-deleted").length,p=e.filter(m=>m.state==="removed-modified"&&!m.reason).length,u=[];u.push("# Update Conflicts"),u.push(""),u.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),u.push(`Updating from canonical version **${t}** to **${n}**.`),u.push("");let g=[];o>0&&g.push(`${o} file${o===1?"":"s"} ha${o===1?"s":"ve"} BOTH local edits AND upstream changes`),r>0&&g.push(`${r} file${r===1?"":"s"} of your own ${r===1?"sits":"sit"} at a path the new version now ships`),d>0&&g.push(`${ai(d)} and ${d===1?"has":"have"} upstream changes or removals`),c>0&&g.push(`${c} file${c===1?"":"s"} you deleted locally ${c===1?"is":"are"} still shipped by the canonical template`),p>0&&g.push(`${p} file${p===1?"":"s"} ${p===1?"was":"were"} removed upstream but edited locally`),u.push(g.join(", and ")+"."),u.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."),u.push(""),u.push("---"),u.push("");for(let m of e){if(u.push(`## ${m.path}`),u.push(""),m.state==="locally-deleted")u.push("**Type:** Deleted locally"),u.push(""),u.push("- You deleted this file after it was installed; the canonical template still ships it."),u.push(`- New canonical version staged at: \`.klaudius/incoming/${m.path}\``),u.push(`- Hash at last install/update: \`${(m.manifestHash??"(none)").slice(0,16)}\``),u.push(`- New canonical hash: \`${(m.canonicalHash??"(none)").slice(0,16)}\``),u.push(""),u.push("**Resolution options for the SKILL to walk through:**"),u.push(""),u.push("1. Restore \u2014 copy the canonical version back into place"),u.push("2. Keep deleted \u2014 never reinstall this file (recorded in the manifest's ignore list)");else if(m.state==="removed-modified")u.push("**Type:** Removed upstream"),u.push(""),u.push(`- Your local copy: \`${m.path}\``),u.push("- This file no longer exists in the canonical template."),u.push(m.reason==="manifest-mismatch"?"- The manifest's entry for this file isn't the version Klaudius last installed (a hand-edited manifest, a conflict resolved outside `/resolve-conflicts`, or a folder restored from an older copy), so your copy is treated as edited. If it was never changed on purpose, deleting it matches the new version.":"- You've modified it locally since install."),u.push(`- ${so(m)} \`${(m.manifestHash??"(none)").slice(0,16)}\``),u.push(`- Your local hash now: \`${(m.localHash??"(missing)").slice(0,16)}\``),u.push(""),u.push("**Resolution options for the SKILL to walk through:**"),u.push(""),u.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),u.push("2. Delete \u2014 remove the file from disk and from the manifest");else{u.push("**Type:** Edit conflict"),u.push(""),u.push(`- ${m.reason?"Your version":"Your version (with your local edits)"}: \`${m.path}\``),u.push(`- New canonical version: \`.klaudius/incoming/${m.path}\``),s.has(m.path)&&u.push(`- Pre-edit base (3-way merge ancestor): \`.klaudius/conflict-base/${m.path}\``),u.push(`- ${so(m)} \`${(m.manifestHash??"(none)").slice(0,16)}\``),u.push(`- Your local hash now: \`${(m.localHash??"(missing)").slice(0,16)}\``),u.push(`- New canonical hash: \`${(m.canonicalHash??"(none)").slice(0,16)}\``);let w=i.get(m.path);if(w&&w.length>0){let h=s.has(m.path);u.push(""),u.push(h?"**What upstream changed since your base:**":"**About this conflict:**"),u.push(""),u.push(...w),h&&(u.push(""),u.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._"))}u.push(""),u.push("**Resolution options for the SKILL to walk through:**"),u.push(""),u.push("1. Keep mine \u2014 discard the new canonical changes"),u.push("2. Take new \u2014 overwrite my edits with the new version"),u.push("3. Merge \u2014 review both side-by-side and produce a combined version")}u.push(""),u.push("---"),u.push("")}return u.join(`
|
|
133
|
+
`)}import{existsSync as Gl}from"fs";import{access as Bl,readFile as Ge,stat as Vl}from"fs/promises";import{homedir as lo}from"os";import{join as ee}from"path";import ne from"picocolors";import{spawn as ao,spawnSync as Yl}from"child_process";function jl(e){let t=e.trim();return t?/^pk_(live|test)_/.test(t)?"that's a PUBLISHABLE key (pk_\u2026) \u2014 it can't create payment links. Use a restricted key (rk_live_\u2026).":/^[a-z]{2,8}_(live|test)_[A-Za-z0-9]+$/.test(t)?null:"doesn't look like a Stripe secret or restricted key (expected rk_live_\u2026 / rk_test_\u2026).":"empty"}function Kl(e){return e===403}async function ro(e){let t=e.replace(/\s+/g,""),n=jl(t);if(n)return{ok:!1,kind:"rejected",message:n};try{let i=await fetch("https://api.stripe.com/v1/account",{headers:{Authorization:`Bearer ${t}`}});if(i.status===401)return{ok:!1,kind:"rejected",message:"Stripe rejected the key (HTTP 401) \u2014 it was revoked, or is from a different account."};if(Kl(i.status))return{ok:!0,livemode:/_live_/.test(t),restricted:/^rk/.test(t)};if(!i.ok)return{ok:!1,kind:"api",message:`Stripe returned HTTP ${i.status}`};let s=await i.json();return{ok:!0,livemode:s.livemode===!0,restricted:/^rk/.test(t),accountName:s.business_profile?.name??s.settings?.dashboard?.display_name??void 0}}catch(i){return{ok:!1,kind:"network",message:`Could not reach Stripe: ${H(i)}`}}}async function co(e){let t=e.projectRoot??process.cwd(),n=[];console.log(ne.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
134
|
+
`)),n.push(await zl());let i=await ec();i&&n.push(i),n.push(await Jl());let s=ee(t,".env"),o=ee(t,".klaudius","manifest.json"),r=ee(t,".mcp.json"),d=ee(t,".codex","config.toml"),c=await Be(s),p=await Be(o),u="claude-code";if(c)try{J(await Ge(s,"utf-8")).AI_AGENT==="codex"&&(u="codex")}catch{}if(u==="claude-code"){let h=await Be(ee(t,"AGENTS.md")),l=!await Be(ee(t,".claude"));h&&l&&(u="codex")}n.push({name:".env present",status:c?"ok":"fail",detail:c?s:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."});let g=!1;if(c){let h={};try{h=J(await Ge(s,"utf-8"))}catch{}let l=Pt(h.AI_PLAN),E=St(h.QA_PHASE)??_e(l);g=E==="off";let T=l&&Ye.has(l)&&u==="codex"?` \xB7 model pin ${_n}`:"";n.push({name:"Plan / QA pass",status:l?"ok":"warn",detail:l?`${We[l]} \xB7 QA pass ${E}${T}`:`plan not set \xB7 QA pass ${E}`,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 h=0,l="";if(p)try{let E=JSON.parse(await Ge(o,"utf-8"));h=typeof E.pendingConflicts=="number"?E.pendingConflicts:0,l=typeof E.templateVersion=="string"?E.templateVersion:""}catch{}n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?h>0?"warn":"ok":"fail",detail:p?h>0?`${l||"version unknown"} \u2014 ${h} conflict${h===1?"":"s"} from the last update still unresolved`:l?`${o} (template ${l})`:o:"missing",nextAction:p?h>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`."})}{let h=u==="codex"?d:r,l=await Ge(h,"utf-8").catch(()=>null),E=ee(Wl(),"config.toml"),T=u==="codex"?await Ge(E,"utf-8").catch(()=>null):null,I=ql(u,l,T),O=I==="ok"&&u==="codex"&&T!==null&&!li.test(l??"");n.push({name:`${u==="codex"?".codex/config.toml":".mcp.json"} \u2014 database connection`,status:I==="ok"?"ok":"warn",detail:O?`${E} \u2014 declared in your own Codex config rather than this folder's`:I==="ok"?h:I==="missing"?u==="codex"?`missing, and no "supabase" server in ${E} either`:"missing":I==="unreadable"?`${h} \u2014 can't be read as JSON`:u==="codex"?`${h} \u2014 no "supabase" server in it, nor in ${E}, so the agent has no database tools`:`${h} \u2014 no "supabase" server in it, so the agent has no database tools`,nextAction:I==="ok"?void 0:u==="codex"?"Run `npx klaudius@latest configure` to write it again, or ask Klaudius in the app to reconnect your database":"Run `npx klaudius@latest configure` to write it again, or press Reconnect it in the Klaudius app's Health check"})}if(n.push(await pc(u)),process.platform==="win32"){let h=await Ql(t);h&&n.push(h)}if(n.push(await Xl(t)),n.push(await Zl(t)),n.push(await tc(t,g)),n.push(await ic()),n.push(await nc(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 h=await Ge(s,"utf-8"),l=J(h);await sc(l,n,t)}console.log();for(let h of n){let l=h.status==="ok"?ne.green("\u2713"):h.status==="warn"?ne.yellow("\u26A0"):h.status==="skip"?ne.dim("\xB7"):ne.red("\u2717");console.log(` ${l} ${h.name}${h.detail?ne.dim(` \u2014 ${h.detail}`):""}`),h.nextAction&&console.log(` ${ne.dim("\u2192")} ${ne.cyan(h.nextAction)}`)}let m=n.filter(h=>h.status==="fail").length,w=n.filter(h=>h.status==="warn").length;console.log(),m===0&&w===0?console.log(ne.green(ne.bold("Everything checks out. You're good to go."))):m===0?console.log(ne.yellow(ne.bold(`${w} warning${w===1?"":"s"} \u2014 review above.`))):(console.log(ne.red(ne.bold(`${m} failed check${m===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}var li=/^[ \t]*\[[ \t]*mcp_servers[ \t]*\.[ \t]*"?supabase"?[ \t]*[.\]]/m;function Wl(){return process.env.CODEX_HOME?.trim()||ee(lo(),".codex")}function ql(e,t,n=null){if(e==="codex")return n!==null&&li.test(n)?"ok":t===null?"missing":li.test(t)?"ok":"no-supabase";if(t===null)return"missing";let i;try{i=JSON.parse(t)}catch{return"unreadable"}if(!i||typeof i!="object"||Array.isArray(i))return"unreadable";let s=i.mcpServers;if(!s||typeof s!="object"||Array.isArray(s))return"no-supabase";let o=s.supabase;return o&&typeof o=="object"&&!Array.isArray(o)?"ok":"no-supabase"}async function Be(e){try{return await Bl(e),!0}catch{return!1}}async function zl(){let e=await it();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 Jl(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let n=parseInt(t[1],10),i=parseInt(t[2],10);return n<22||n===22&&i<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function Ql(e){let t=et([{label:"your Windows user folder",path:lo()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",i=await ci("npm",["config","get","script-shell"],!0),s=i.code===0?i.stdout.trim():void 0;if(tt(s,Gl))return{name:n,status:"ok",detail:`${t[0].label} contains ${t[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=nt(t,"doctor"),d=t.some(c=>c.chars.includes("&"));return{name:n,status:d?"fail":"warn",detail:o,nextAction:r}}async function Xl(e){let t=ee(e,"node_modules");if(!await Be(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await Vl(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 Zl(e){let t=process.platform==="darwin"?ee(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?ee(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):ee(process.env.HOME??"",".cache","ms-playwright");return await Be(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 ec(){let e=await Kn();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 tc(e,t){if(!await Be(ee(e,"node_modules","@playwright","cli")))return{name:"QA screenshot chain",status:"skip",detail:"project dependencies not installed",nextAction:"Run `npx klaudius@latest install` first."};let i=await un(e);if(i.ok)return{name:"QA screenshot chain",status:"ok",detail:"served a page with python3 and screenshotted it"};let s=i.stage!=="python3-server"&&t;return{name:"QA screenshot chain",status:s?"warn":"fail",detail:`${i.stage?`${i.stage}: `:""}${i.detail??"failed"}`+(s?" (QA pass is off \u2014 this matters when you enable it, and for browser-based gathering)":""),nextAction:i.remediation}}async function nc(e){let t=ee(e,".klaudius","notify-failures.log");try{let n=(await Ge(t,"utf8")).trim();if(!n)return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"};let i=n.split(/\r?\n/);return{name:"Alert delivery",status:"warn",detail:`${i.length} failed send${i.length===1?"":"s"} recorded; latest: "${i[i.length-1]}"`,nextAction:"Check TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID in .env (rate limits also land here). Delete .klaudius/notify-failures.log once resolved."}}catch{return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"}}}async function ic(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
|
|
130
135
|
try:
|
|
131
136
|
${e.map(o=>` import ${o}`).join(`
|
|
132
137
|
`)}
|
|
133
138
|
except Exception as e:
|
|
134
139
|
print(str(e))
|
|
135
140
|
sys.exit(1)
|
|
136
|
-
`,n=await
|
|
137
|
-
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function
|
|
138
|
-
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:s}}return await Ee(re(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:s}}async function il(e,t){let n="Database schema up to date",i=(e.SUPABASE_URL??"").trim(),s=(e.SUPABASE_SERVICE_KEY??"").trim();if(!i||!s)return{name:n,status:"skip",detail:"Supabase credentials not set"};let o="";try{o=await at(re(t,"scripts","schema.sql"),"utf-8")}catch{return{name:n,status:"skip",detail:"scripts/schema.sql missing \u2014 run `npx klaudius@latest update`"}}let r=await Wt({url:i,serviceKey:s,sql:o});return r.unreachable?{name:n,status:"skip",detail:`Could not verify (${r.unreachable}) \u2014 see the Supabase rows above.`}:r.ok?{name:n,status:"ok",detail:"every table and column the pipeline expects is present"}:{name:n,status:"warn",detail:`missing: ${r.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 sl(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(p=>p.trim().toLowerCase()),i=(e.LETTER_PROVIDER??"").trim().toLowerCase(),s=n.includes("letter");if(!s&&(!i||i==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(s&&i!=="pingen"&&i!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!s)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${i} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let o=await Jt({provider:i,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!o.ok)return{name:t,status:"fail",detail:o.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let r=`${i} credentials accepted`+(o.friendlyName?` (${o.friendlyName})`:""),c=(e.SUPABASE_ANON_KEY??"").trim();if(!c)return{name:t,status:"warn",detail:r+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let u=Xn(c);if(u&&u!=="anon")return{name:t,status:"fail",detail:r+`, but SUPABASE_ANON_KEY holds a '${u}' key \u2014 shipping it in a claim page would expose the whole database`,nextAction:"Replace SUPABASE_ANON_KEY with the key whose role is 'anon' (Supabase dashboard \u2192 Settings \u2192 API keys)."};if(e.SUPABASE_URL)try{let p=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:c,Authorization:`Bearer ${c}`}});if(p.ok){let d=await p.json();if(Array.isArray(d)&&d.length>0)return{name:t,status:"fail",detail:r+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(i==="postgrid"){let p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(d=>!(e[d]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:r+`, but PostGrid needs your return address and .env is missing ${p.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:r}}async function ol(e,t){let n="Email credentials (SMTP + IMAP)",i=tl(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Rs(e))return i==="parked"?{name:"Email account (Microsoft sign-in)",status:"warn",detail:"Outlook mailbox saved in .env but email isn't an active outreach channel (skipped during setup?)",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."}:i==="incomplete"?{name:"Email account (Microsoft sign-in)",status:"fail",detail:"EMAIL_AUTH=oauth-microsoft but EMAIL_ADDRESS is missing from .env",nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}:nl(t);if(i==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(i==="incomplete"){let u=["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 ${u.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let s=ut(e),o=s&&s!=="custom"?s:Me(e.EMAIL_SMTP_HOST),r={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:o?ce[o].usesAccountPassword:void 0,knownProvider:!!o,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},c=await _e(r);if(c.ok){if(c.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 u=vs(c,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await se())?.command.join(" ")});return u?{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but ${u.detail}`,nextAction:u.nextAction}:{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(c.failureKind==="network")return{name:n,status:"fail",detail:c.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(o){let u=Tt(o,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(u.length>0){console.log(ne.dim(` (email login rejected \u2014 probing ${ce[o].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let y of u){let f=await _e({...r,emailSmtpHost:y.smtpHost,emailImapHost:y.imapHost});if(!f.ok&&f.failureKind!=="network"&&p++,f.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${y.label} (${y.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${y.smtpHost} and EMAIL_IMAP_HOST=${y.imapHost} in .env (or ask your AI agent to).`}}let d=(c.message??"login rejected").split(/\.\s|\n/)[0];return p===0?{name:n,status:"fail",detail:`${d} \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:`${d} \u2014 tried all ${ce[o].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:o==="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`.":o==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:c.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}function vs(e,t){let n=[],i=[],s=[];if(e.sentFolderIssue){let{configured:r,detected:c}=e.sentFolderIssue;n.push(`the server has no "${r}" folder \u2014 sent mail isn't being filed, so follow-ups can't see what was sent to whom`),c?i.push(`${t.sentKey}="${c}"`):s.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:r,detected:c}=e.draftsFolderIssue;n.push(`the server has no "${r}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),c?i.push(`${t.draftsKey}="${c}"`):s.push(t.draftsKey)}if(n.length===0)return;let o=[];if(i.length>0&&o.push(`Set ${i.join(" and ")} in .env (or ask your AI agent to).`),s.length>0){let r=t.python||"python3",c=t.account&&t.account!=="primary"?`${r} scripts/gmail.py folders --account ${t.account}`:`${r} scripts/gmail.py folders`;o.push(`Run \`${c}\` to list this mailbox's folder names, then set ${s.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:o.join(" ")}}async function rl(e){let t=[];for(let n of li(e)){let i=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:i,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:i,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:i,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:i,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let s=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_SENT_FOLDER`,o=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,r=Me(n.smtpHost),c=await _e({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,usesAccountPassword:r?ce[r].usesAccountPassword:void 0,knownProvider:!!r,sentFolder:(e[s]??"").trim()||"Sent",draftsFolder:(e[o]??"").trim()||"Drafts"});if(c.ok){let u=vs(c,{sentKey:s,draftsKey:o,account:n.label,python:(await se())?.command.join(" ")});u?t.push({name:i,status:"warn",detail:`authenticated (${n.smtpHost}), but ${u.detail}`,nextAction:u.nextAction}):t.push({name:i,status:"ok",detail:`authenticated (${n.smtpHost})`})}else t.push({name:i,status:"fail",detail:c.message,nextAction:c.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 al(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",i=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",s=await Kn(t,["--version"],process.platform==="win32");return s.code===0?{name:n,status:"ok",detail:(s.stdout||s.stderr).trim().split(`
|
|
139
|
-
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:i}}function
|
|
140
|
-
`));let o=
|
|
141
|
+
`,n=await Q();if(!n)return{name:"Python packages installed",status:"fail",detail:"no Python interpreter found (tried python3, python, py -3)",nextAction:"Fix the Python check above first \u2014 the packages live inside that interpreter."};let i=n.command,s=await ci(i[0],[...i.slice(1),"-c",t]);return s.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(s.stdout||s.stderr).trim().split(`
|
|
142
|
+
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function sc(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let r=await $e({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:r.ok?"ok":"fail",detail:r.ok?"connected":r.message,nextAction:r.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});let i=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(i==="selfhost"){let r=e.SELFHOST_DEPLOY_TARGET??"",d=e.SELFHOST_URL_TEMPLATE??"",c=[],p=Xe(r);p&&c.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let u=Ze(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 ${r} (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(i==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let r=await De({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:r.ok?"ok":"fail",detail:r.ok?`valid (${r.projectCount??0} Pages project${r.projectCount===1?"":"s"})`:r.message,nextAction:r.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Cloudflare."});else if(i==="netlify")if(e.NETLIFY_AUTH_TOKEN){let r=await Fe({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:r.ok?"ok":"fail",detail:r.ok?r.accountSlug?`valid (team: ${r.accountSlug})`:"valid":r.message,nextAction:r.ok?void 0:"Fix the token at https://app.netlify.com/user/applications#personal-access-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Netlify token",status:"fail",detail:"NETLIFY_AUTH_TOKEN missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Netlify."});else if(e.VERCEL_TOKEN){let r=await Me(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:r.ok?"ok":"fail",detail:r.ok?r.username??"valid":r.message,nextAction:r.ok?void 0:r.kind==="rejected"||r.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then `npx klaudius@latest configure`.":r.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 r=await Ue(e.GOOGLE_PLACES_API_KEY),d=ke(e.GOOGLE_PLACES_API_KEY);r.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:r.ok?"ok":"fail",detail:r.ok?"accepted":r.message,nextAction:r.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius@latest configure`."})}else t.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});t.push(await dc(e,n)),t.push(...await uc(e)),t.push(await ac(e,n)),e.STRIPE_SECRET_KEY&&t.push(await lc(e.STRIPE_SECRET_KEY)),t.push(await cc(e));let s=(e.NOTIFY_CHANNEL??"").toLowerCase(),o=s==="email"||s==="sms"||s==="none"||s==="off"?s:"telegram";if(o==="none"||o==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(o==="email"){let r=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:r&&e.EMAIL_ADDRESS?"ok":"fail",detail:r&&e.EMAIL_ADDRESS?`alerts go to ${r}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:r&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(o==="sms"){let r=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:r&&d?"ok":"fail",detail:r&&d?`alerts go to ${r} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:r?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:r&&d?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let r=await gi({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:r.ok?"ok":"fail",detail:r.ok?`bot ${r.botHandle??"ok"} (chat_id not tested)`:r.message,nextAction:r.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?t.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):t.push({name:"Notifications",status:"skip",detail:"not configured (optional)"})}function oc(e){let t=o=>!!o&&/^\d+$/.test(o.trim()),n=uo(e)?!!e.EMAIL_ADDRESS:!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),i=(e.OUTREACH_CHANNELS??"").split(",").map(o=>o.trim()),s=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&i.includes("email");return s&&n?"active":s?"incomplete":n?"parked":"unconfigured"}function uo(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function rc(e){let t="Email account (Microsoft sign-in)",n=await Q(),s=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[r,...d]=n.command,c=Yl(r,[...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(`
|
|
143
|
+
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:s}}return await Be(ee(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:s}}async function ac(e,t){let n="Database schema up to date",i=(e.SUPABASE_URL??"").trim(),s=(e.SUPABASE_SERVICE_KEY??"").trim();if(!i||!s)return{name:n,status:"skip",detail:"Supabase credentials not set"};let o="";try{o=await Ge(ee(t,"scripts","schema.sql"),"utf-8")}catch{return{name:n,status:"skip",detail:"scripts/schema.sql missing \u2014 run `npx klaudius@latest update`"}}let r=await sn({url:i,serviceKey:s,sql:o});return r.unreachable?{name:n,status:"skip",detail:`Could not verify (${r.unreachable}) \u2014 see the Supabase rows above.`}:r.ok?{name:n,status:"ok",detail:"every table and column the pipeline expects is present"}:{name:n,status:"warn",detail:`missing: ${r.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 lc(e){let t="Stripe key",n=await ro(e);if(!n.ok)return{name:t,status:"fail",detail:n.message,nextAction:n.kind==="network"?"Couldn't reach Stripe \u2014 check your connection, then re-run `npx klaudius@latest doctor`.":'Create a new restricted key at https://dashboard.stripe.com/apikeys, then tell your agent "connect Stripe" to store it.'};let i=!n.restricted;return{name:t,status:n.livemode&&!i?"ok":"warn",detail:`${n.accountName??"account"} \xB7 ${n.livemode?"live mode":"TEST mode \u2014 links made with this key can't take real payments"}${i?" \xB7 full secret key, which can do anything in the account":""}`,nextAction:i?'Create a restricted key at https://dashboard.stripe.com/apikeys with the permissions listed in .env.example, then tell your agent "connect Stripe".':n.livemode?void 0:`Swap in a live-mode key when you're ready to take real payments: tell your agent "connect Stripe".`}}async function cc(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(p=>p.trim().toLowerCase()),i=(e.LETTER_PROVIDER??"").trim().toLowerCase(),s=n.includes("letter");if(!s&&(!i||i==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(s&&i!=="pingen"&&i!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!s)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${i} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let o=await dt({provider:i,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!o.ok)return{name:t,status:"fail",detail:o.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let r=`${i} credentials accepted`+(o.friendlyName?` (${o.friendlyName})`:""),d=(e.SUPABASE_ANON_KEY??"").trim();if(!d)return{name:t,status:"warn",detail:r+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let c=ki(d);if(c&&c!=="anon")return{name:t,status:"fail",detail:r+`, 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:r+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(i==="postgrid"){let p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(u=>!(e[u]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:r+`, but PostGrid needs your return address and .env is missing ${p.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:r}}async function dc(e,t){let n="Email credentials (SMTP + IMAP)",i=oc(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(uo(e))return i==="parked"?{name:"Email account (Microsoft sign-in)",status:"warn",detail:"Outlook mailbox saved in .env but email isn't an active outreach channel (skipped during setup?)",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."}:i==="incomplete"?{name:"Email account (Microsoft sign-in)",status:"fail",detail:"EMAIL_AUTH=oauth-microsoft but EMAIL_ADDRESS is missing from .env",nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}:rc(t);if(i==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(i==="incomplete"){let 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 s=Te(e),o=s&&s!=="custom"?s:pe(e.EMAIL_SMTP_HOST),r={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:o?te[o].usesAccountPassword:void 0,knownProvider:!!o,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},d=await me(r);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=po(d,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await Q())?.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(o){let c=Nt(o,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(ne.dim(` (email login rejected \u2014 probing ${te[o].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let g of c){let m=await me({...r,emailSmtpHost:g.smtpHost,emailImapHost:g.imapHost});if(!m.ok&&m.failureKind!=="network"&&p++,m.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${g.label} (${g.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${g.smtpHost} and EMAIL_IMAP_HOST=${g.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 ${te[o].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:o==="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`.":o==="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 po(e,t){let n=[],i=[],s=[];if(e.sentFolderIssue){let{configured:r,detected:d}=e.sentFolderIssue;n.push(`the server has no "${r}" folder \u2014 sent mail isn't being filed, so follow-ups can't see what was sent to whom`),d?i.push(`${t.sentKey}="${d}"`):s.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:r,detected:d}=e.draftsFolderIssue;n.push(`the server has no "${r}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),d?i.push(`${t.draftsKey}="${d}"`):s.push(t.draftsKey)}if(n.length===0)return;let o=[];if(i.length>0&&o.push(`Set ${i.join(" and ")} in .env (or ask your AI agent to).`),s.length>0){let r=t.python||"python3",d=t.account&&t.account!=="primary"?`${r} scripts/gmail.py folders --account ${t.account}`:`${r} scripts/gmail.py folders`;o.push(`Run \`${d}\` to list this mailbox's folder names, then set ${s.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:o.join(" ")}}async function uc(e){let t=[];for(let n of Ci(e)){let i=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:i,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:i,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:i,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:i,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let s=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_SENT_FOLDER`,o=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,r=pe(n.smtpHost),d=await me({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,usesAccountPassword:r?te[r].usesAccountPassword:void 0,knownProvider:!!r,sentFolder:(e[s]??"").trim()||"Sent",draftsFolder:(e[o]??"").trim()||"Drafts"});if(d.ok){let c=po(d,{sentKey:s,draftsKey:o,account:n.label,python:(await Q())?.command.join(" ")});c?t.push({name:i,status:"warn",detail:`authenticated (${n.smtpHost}), but ${c.detail}`,nextAction:c.nextAction}):t.push({name:i,status:"ok",detail:`authenticated (${n.smtpHost})`})}else t.push({name:i,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 pc(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",i=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",s=await ci(t,["--version"],process.platform==="win32");return s.code===0?{name:n,status:"ok",detail:(s.stdout||s.stderr).trim().split(`
|
|
144
|
+
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:i}}function ci(e,t,n=!1){return new Promise(i=>{let s=n?ao([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ao(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",d=>{o+=d.toString()}),s.stderr?.on("data",d=>{r+=d.toString()}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",()=>i({code:1,stdout:o,stderr:r}))})}import{existsSync as fc}from"fs";import{spawnSync as mc}from"child_process";import{join as hc,resolve as gc}from"path";import oe from"picocolors";async function fo(e){let t=gc(e.projectRoot??process.cwd()),n=hc(t,"scripts","whatsapp.mjs");fc(n)||(console.error(oe.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(oe.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(oe.dim(`Looked for: ${n}`)),process.exit(1));let i=(e.label??"primary").trim(),s=i.replace(/[^A-Za-z0-9_-]/g,"");s||(console.error(oe.red(`Invalid label '${i}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),s!==i&&console.error(oe.yellow(`Note: cleaned label '${i}' \u2192 '${s}' (filename-safe characters only).`)),console.log(oe.cyan(`Pairing WhatsApp account '${s}'...`)),console.log(oe.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.
|
|
145
|
+
`));let o=mc(process.execPath,[n,"pair","--account",s],{cwd:t,stdio:"inherit"});if(o.status===0){console.log(oe.green(`Paired '${s}'.`)),console.log(oe.dim(`
|
|
141
146
|
If you haven't already, add '${s}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
142
147
|
WHATSAPP_ACCOUNTS=primary,${s}
|
|
143
|
-
(Skip this if '${s}' is already there or you set it via the init wizard.)`));return}o.error?console.error(
|
|
148
|
+
(Skip this if '${s}' is already there or you set it via the init wizard.)`));return}o.error?console.error(oe.red(`Pair failed: ${o.error.message}`)):(console.error(oe.red(`Pair did not complete (exit ${o.status??"signalled"}). Common causes:`)),console.error(oe.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(oe.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(oe.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${s}/daemon.log`))),process.exit(o.status??1)}import{spawnSync as wt,spawn as yc}from"child_process";import{existsSync as xt,mkdirSync as kc,readdirSync as wc,rmSync as yo,mkdtempSync as ko}from"fs";import{homedir as di,tmpdir as wo}from"os";import{join as ue}from"path";import Se from"picocolors";var Ac=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function mo(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Ao(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&Lt()&&Po();let t=Pc();if(t&&!e.reinstall&&!e.from){go(),console.log(Se.green("Opened the Klaudius app.")),ho();return}let n=await bc(e.from);console.log(Se.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?_c(n):Tc(n),go(),console.log(Se.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),ho()}function ho(){process.platform==="darwin"?console.log(Se.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(Se.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function An(){return ue(di(),"Applications","Klaudius.app")}function Eo(){return process.env.LOCALAPPDATA??ue(di(),"AppData","Local")}function Ec(){return ue(Eo(),"Klaudius")}function Lt(){let e=ue(Eo(),"Programs");try{for(let t of wc(e)){if(!/laudius/i.test(t))continue;let n=ue(e,t,"Klaudius.exe");if(xt(n))return n}}catch{}return null}function Pc(){return process.platform==="darwin"?xt(An()):Lt()!==null}async function Sc(){try{let{readFileSync:e}=await import("fs");return e(ue(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m)?.[2]?.trim()??null}catch{return null}}async function bc(e){if(e)return xt(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await Sc();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=`${Ac}?file=${encodeURIComponent(mo())}`,i=ue(ko(ue(wo(),"klaudius-app-")),mo());console.log(Se.cyan("Downloading the Klaudius app\u2026"));try{let s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.37.0"}});if(!s.ok){let d=`HTTP ${s.status}`;try{let c=await s.json();c.reason&&(d=c.reason)}catch{}throw new Error(d)}let o=Buffer.from(await s.arrayBuffer()),{writeFileSync:r}=await import("fs");return r(i,o),i}catch(s){console.error(`Couldn't download the app (${s.message}). If you're offline, try again later; otherwise email hello@klaudius.dev.`),process.exit(1)}}function _c(e){let t=ue(di(),"Applications");kc(t,{recursive:!0});let n=ko(ue(wo(),"klaudius-app-x-")),i=wt("ditto",["-xk",e,n],{stdio:"pipe"});i.status!==0&&(console.error(`Couldn't extract the app: ${i.stderr?.toString().trim()}`),process.exit(1));let s=ue(n,"Klaudius.app");xt(s)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),yo(An(),{recursive:!0,force:!0});let o=wt("mv",[s,An()],{stdio:"pipe"});o.status!==0&&(console.error(`Couldn't install to ~/Applications: ${o.stderr?.toString().trim()}`),process.exit(1))}function Tc(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=wt(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Ic(6e4)){let i=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,s=Lt();if(s&&So(s)){console.log(Se.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(Se.dim("Open it from the Start Menu if it doesn't appear shortly."));return}console.error(`Klaudius didn't finish installing (${i}).`),console.error("Check your Start Menu for Klaudius \u2014 it may still be finishing."),console.error("If it isn't there, email hello@klaudius.dev."),process.exit(1)}Po()}function Ic(e){let t=Date.now()+e;for(;;){let n=Lt();if(n)return n;if(Date.now()>=t)return null;Cc(500)}}function Cc(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Po(){let e=Ec();if(!xt(ue(e,"app","Klaudius.exe")))return;console.log(Se.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
|
|
144
149
|
$legacy = '${e.replace(/'/g,"''")}'
|
|
145
150
|
# Compare against the directory PLUS its separator, so a sibling folder whose
|
|
146
151
|
# name merely starts with the same text ("Klaudius Desktop") is never matched.
|
|
@@ -154,4 +159,4 @@ foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetF
|
|
|
154
159
|
Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
|
|
155
160
|
}
|
|
156
161
|
}
|
|
157
|
-
}`;
|
|
162
|
+
}`;wt("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{yo(e,{recursive:!0,force:!0})}catch{console.log(Se.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function go(){if(process.platform==="darwin"){wt("open",["-a",An()],{stdio:"pipe"});return}let e=Lt();if(!e||So(e))return;yc(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function So(e){let t=wt("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(i=>i.trim().toLowerCase()===n)}function bo(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 ui(e=0){await Promise.all([bo(process.stdout),bo(process.stderr)]),process.exit(e)}import{spawnSync as Rc}from"child_process";var pi="--use-system-ca";function _o(){let e=process.env.NODE_OPTIONS??"";if(e.includes(pi)||!we().ok)return;let n=e?`${e} ${pi}`:pi,i=Rc(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}_o();var Oc="0.37.0",ge=new vc;ge.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Oc);ge.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 Ti({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});ge.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 Is({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await ui(process.exitCode??0)}catch(n){console.error("init failed:",n.message),process.exit(1)}});ge.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 Rs({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});ge.command("configure").description("Re-run the setup wizard with current values pre-filled").option("--answers <file>","Non-interactive: read new answers from a JSON or dotenv-format file (same keys as .env) \u2014 a delta, holding only the settings that changed. Keys in the file replace what .env holds, a key present but empty clears it, and every key it leaves out is KEPT (unlike `init --answers`, where a setting the form owns reverts to its default when left out). Checks run before anything is written; on a failed check nothing is changed and it exits 2 with an INIT-BLOCKED line. On success it prints CONFIGURE-DONE sections=<changed> checked=<sections whose check ran>.").option("--sections <list>","Only with --answers: comma-separated sections whose credential checks should run (supabase, vercel, cloudflare, netlify, selfhost, google-places, email, sms, letter, notifications). Default: every section the answers file changes.").action(async e=>{try{await Gs({answers:e.answers,sections:e.sections}),await ui(process.exitCode??0)}catch(t){console.error("configure failed:",t.message),process.exit(1)}});ge.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 oo({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});ge.command("resolve").description("Record your decision on one conflict `update` staged (the /resolve-conflicts skill runs this for you)").argument("[file]","The conflicted file, as named in .klaudius/conflicts.md").allowExcessArguments(!1).option("--keep-mine","Keep your version").option("--take-new","Use the new version (yours is backed up first)").option("--check-merge <draft>","Show what a merged draft keeps from each side, changing nothing").option("--merge <draft>","Use a merged draft (yours is backed up first)").option("--auto-merge","Merge automatically when your edits and the update's don't overlap (yours is backed up first)").option("--restore","Bring back a file you deleted, in its new version").option("--keep-deleted","Keep a file you deleted out for good").option("--delete","Delete a file the new version dropped (backed up first)").option("--finish","Clear the update staging once nothing is waiting").action(async(e,t)=>{try{process.exitCode=await no(to(e,t))}catch(n){console.error("resolve failed:",n.message),process.exit(1)}});ge.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 co({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});ge.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 Ao({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});ge.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 fo({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ge.parse(process.argv);
|