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