klaudius 0.37.5 → 0.38.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,168 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as Je,b as Ei,c as Pi,d as Te,e as Pt,f as pe,g as jt,h as te,i as H,j as Si,k as Kt,l as Qe,m as Xe,n as bi,o as _i,p as Ti,q as we,r as Ii,s as Ci}from"./chunk-S26ZZBGE.js";import{Command as Kc}from"commander";import{spawn as Oi}from"child_process";import{existsSync as qo}from"fs";import{homedir as zo}from"os";import B from"picocolors";import{win32 as No}from"path";var $o=["&","^","%","!"];function Mo(e){return $o.filter(t=>e.includes(t))}function Ze(e){let t=[];for(let{label:n,path:i}of e){let s=Mo(i);s.length>0&&t.push({label:n,path:i,chars:s})}return t}function Do(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=No.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(i)?t:null}function et(e,t){let n=Do(e);return n===null?!1:t?t(n):!0}function tt(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 Ae(){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 Fo}from"child_process";import{existsSync as Uo}from"fs";import{homedir as Ho}from"os";import{delimiter as jo,join as Gt}from"path";var Ko=new Set(["Restricted","AllSigned"]);function Go(e,t=Uo){for(let n of e.split(jo)){let i=n.replace(/"/g,"");if(!i)continue;let s=Gt(i,"npx.ps1");if(t(s))return{path:s,isPs1:!0};for(let o of["npx.exe","npx.bat","npx.cmd"]){let r=Gt(i,o);if(t(r))return{path:r,isPs1:!1}}}return null}async function vi(){let e=Go(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Bo();if(!t)return{blocked:!1,shimPath:e.path};let n=Gt(Ho(),".local","node")+"\\";return{blocked:Ko.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Bo(){let e=Gt(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await Ri(e)??await Ri("powershell.exe")}function Ri(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let i=Fo(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 Vo}from"child_process";var St=3,Bt=10,Yo=[["python3"],["python"],["py","-3"]];async function Q(){for(let e of Yo){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 nt(){let e=Wo(),t=await Q();if(!t){let r=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${St}.${Bt}+ is not installed (or not on PATH). Install it from ${e}.`+r}}let{command:n,version:i,major:s,minor:o}=t;return s<St||s===St&&o<Bt?{ok:!1,version:i,major:s,minor:o,command:n,message:`Your installed Python is ${i}. Klaudius needs Python ${St}.${Bt} or newer (the pipeline depends on packages that only ship wheels for ${St}.${Bt}+). 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 Wo(){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=Vo(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 xi=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function Li(e={}){console.log(B.bold(`Klaudius preflight \u2014 checking your machine\u2026
3
- `));let t=[];t.push(Jo());let n=await nt();if(t.push(Qo(n)),t.push(await Xo(n.command)),t.push(await Zo()),process.platform==="win32"){let s=await er();s&&t.push(s);let o=await tr();o&&t.push(o)}t.push(await nr());for(let s of t){let o=s.status==="ok"?B.green("\u2713"):s.status==="warn"?B.yellow("!"):B.red("\u2717");console.log(` ${o} ${s.name}${s.detail?B.dim(` \u2014 ${s.detail}`):""}`),s.nextAction&&console.log(` ${B.dim("\u2192")} ${B.cyan(s.nextAction)}`)}console.log();let i=t.filter(s=>s.status==="fail");if(i.length===0){let s=t.filter(o=>o.status==="warn").length;ir(s);return}console.log(B.red(B.bold(`${i.length} check${i.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(B.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(B.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Jo(){let e=Ae();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 Qo(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 Xo(e){let t=e??["python3"],n=await Yt(t[0],[...t.slice(1),"-m","pip","--version"]);return n.code===0?{name:"pip available",status:"ok",detail:(n.stdout||n.stderr).trim().split(`
4
- `)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function Zo(){let e=process.platform==="win32",t=await Yt("npm",["--version"],e);return t.code!==0?{name:"npm / npx available",status:"fail",detail:"npm not found",nextAction:"npm ships with Node.js \u2014 reinstall Node from https://nodejs.org/."}:(await Yt("npx",["--version"],e)).code!==0?{name:"npm / npx available",status:"fail",detail:`npm ${t.stdout.trim()} ok, npx missing`,nextAction:"npx ships with npm 5.2+ \u2014 reinstall Node from https://nodejs.org/."}:{name:"npm / npx available",status:"ok",detail:`npm ${t.stdout.trim()}`}}async function er(){let e=await vi();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 tr(){let e=Ze([{label:"your Windows user folder",path:zo()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await Yt("npm",["config","get","script-shell"],!0),i=n.code===0?n.stdout.trim():void 0;if(et(i,qo))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(d=>`"${d}"`).join(", ")}, but npm's script-shell (${i}) handles it`};let{detail:s,action:o}=tt(e,"preflight"),r=e.some(d=>d.chars.includes("&"));return{name:t,status:r?"fail":"warn",detail:s,nextAction:o}}async function nr(){try{return await fetch(xi,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:xi}}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 ir(e=0){e>0?console.log(B.green(B.bold("Your machine is ready."))+B.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(B.green(B.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(B.bold("NEXT STEP \u2014 this one is for you to run, not the AI assistant:")),console.log(" It's an interactive wizard (it asks for your license key and passwords),"),console.log(" so the assistant can't fill it in. Open a NEW terminal WINDOW and run:"),console.log(),console.log(` ${B.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(B.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(B.dim(" run it in a new terminal window.")),console.log()}function Yt(e,t,n=!1){return new Promise(i=>{let s=n?Oi([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Oi(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",d=>{o+=d.toString()}),s.stderr?.on("data",d=>{r+=d.toString()}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",()=>i({code:1,stdout:o,stderr:r}))})}import{mkdir as An,readdir as Ls,readFile as zn,rm as vs,stat as Xn,writeFile as wn}from"fs/promises";import{spawnSync as Zn}from"child_process";import{existsSync as Ma}from"fs";import{homedir as Ns}from"os";import{resolve as Da,isAbsolute as Fa,join as X,normalize as Ua}from"path";import*as v from"@clack/prompts";import A from"picocolors";import sr from"react";import{render as or}from"ink";async function W(e={},t={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius@latest init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:n}=await import("./WizardApp-VPIFRA7A.js"),i=null;Je("runWizard:start",{onlySection:t.onlySection,hasDefaults:Object.keys(e).length>0}),Pi(),await new Promise(o=>setImmediate(o)),await new Promise(o=>setTimeout(o,0)),Je("runWizard:event loop drained, mounting Ink");let s=or(sr.createElement(n,{defaults:e,onlySection:t.onlySection,banner:t.banner,onComplete:o=>{Je("runWizard:onComplete called",{keys:Object.keys(o).length}),i=o}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});Je("runWizard:render returned, awaiting exit");try{await s.waitUntilExit()}finally{process.stdin.pause(),process.stdin.ref()}if(Je("runWizard:waitUntilExit resolved",{resultIsNull:i===null}),!i)throw new Error(`Wizard exited without completing. Diagnostic log: ${Ei}
5
- Please share that file so we can trace what happened.`);return i}var rr={GB:"44",US:"1",CA:"1",AU:"61",NZ:"64",IE:"353",DE:"49",FR:"33",ES:"34",IT:"39",NL:"31",BE:"32",CH:"41",AT:"43",PT:"351",SE:"46",NO:"47",DK:"45",FI:"358",PL:"48",ZA:"27"};function Wt(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9.,  ]*$/.test(n))return n;let i=bi[(t??"").toUpperCase()];return i?`${i.pre??""}${n}${i.post??""}`:n}function Rn(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?rr[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 vn="claude-code",qt={AI_AGENT:["claude-code","codex"],AI_PLAN:["claude-pro","claude-max-5x","claude-max-20x","claude-team-standard","claude-team-premium","claude-other","codex-plus","codex-pro","codex-business","codex-business-premium","codex-other"],QA_PHASE:["on","off"],DEPLOY_PROVIDER:["vercel","cloudflare","netlify","selfhost"],EMAIL_AUTH:["password","oauth-microsoft"],SMS_PROVIDER:["twilio","imessage"],LETTER_PROVIDER:["pingen","postgrid","none"],NOTIFY_CHANNEL:["telegram","email","sms"]},We=(e,t)=>qt[e].includes(t??"");function On(e){return We("AI_AGENT",e)?e:void 0}function _t(e){let t=e?.trim().toLowerCase()??"";return We("AI_PLAN",t)?t:void 0}function Tt(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 xn="vercel";function Ln(e){return We("DEPLOY_PROVIDER",e)?e:void 0}function Nn(e){return We("NOTIFY_CHANNEL",e)?e:void 0}function $n(e){return We("EMAIL_AUTH",e)?e:void 0}function Mn(e){return We("SMS_PROVIDER",e)?e:void 0}var bt="none";function Dn(e){if(e!==bt)return We("LETTER_PROVIDER",e)?e:void 0}function Ni(e,t){switch(e){case"AI_AGENT":return On(t);case"AI_PLAN":return _t(t);case"QA_PHASE":return Tt(t);case"DEPLOY_PROVIDER":return Ln(t);case"EMAIL_AUTH":return $n(t);case"SMS_PROVIDER":return Mn(t);case"LETTER_PROVIDER":return t===bt?bt:Dn(t);case"NOTIFY_CHANNEL":return Nn(t)}}function ar(e){if(e==="custom"||e!==void 0&&Object.hasOwn(te,e))return e}function Ie(e){let t=ar(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n)return pe(n)??"custom"}function $i(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let i of t.split(",")){let s=i.trim().toLowerCase();s&&s!=="primary"&&!n.includes(s)&&n.push(s)}return n.map(i=>{let s=/^[a-z0-9_]+$/.test(i)&&i!=="auto",o=d=>{let c=e[`EMAIL_ACCOUNT_${i.toUpperCase()}_${d}`];return c?.trim()?c.trim():void 0},r=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(d=>!o(d)).map(d=>`EMAIL_ACCOUNT_${i.toUpperCase()}_${d}`);for(let d of["SMTP_PORT","IMAP_PORT"]){let c=o(d);c!==void 0&&!/^\d+$/.test(c)&&r.push(`EMAIL_ACCOUNT_${i.toUpperCase()}_${d}`)}return{label:i,valid:s,auth:(o("AUTH")??"password").toLowerCase(),address:o("ADDRESS"),missing:r,smtpHost:o("SMTP_HOST"),smtpPort:parseInt(o("SMTP_PORT")??"587",10),imapHost:o("IMAP_HOST"),imapPort:parseInt(o("IMAP_PORT")??"993",10),password:o("PASSWORD"),login:o("LOGIN")}})}function it(e){let t=[],n=d=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${d}`),t.push("# "+"=".repeat(60)),t.push("")},i=(d,c)=>{if(c==null||c===""){t.push(`# ${d}=`);return}let p=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(p)){let u=p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${d}="${u}"`)}else t.push(`${d}=${p}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),i("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),i("AI_AGENT",e.aiAgent??vn),i("AI_PLAN",e.aiPlan),i("QA_PHASE",e.qaPhase??Te(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",Wt(e.pricing,e.countryCode)),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",Wt(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",Rn(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??xn),i("VERCEL_TOKEN",e.vercelToken),i("VERCEL_SCOPE",e.vercelScope??""),i("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),i("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),i("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),i("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),i("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),i("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),i("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),i("NOTIFY_CHANNEL",e.notifyChannel),i("NOTIFY_TO",e.notifyTo),i("TELEGRAM_BOT_TOKEN",e.telegramBotToken),i("TELEGRAM_CHAT_ID",e.telegramChatId);let o=new Set(t.map(d=>/^#?\s*([A-Z0-9_]+)=/.exec(d)?.[1]).filter(d=>!!d)),r=Object.entries(e.preservedEnv??{}).filter(([d])=>!o.has(d));if(r.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[d,c]of r)i(d,c)}return t.join(`
6
- `)+`
7
- `}function st(e){let t={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(t,null,2)+`
8
- `}function ot(e){let t=e.supabaseProjectRef,n=lr(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.","","[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${t}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${n}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
9
- `)}function lr(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Mi=[{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 cr(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(`
10
- `)?"":`
11
- `,o=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let r of i)o.push(""),r.comment&&o.push(`# ${r.comment}`),o.push(cr(r.key,r.value));return e+s+o.join(`
12
- `)+`
13
- `}function Fn(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function J(e){let t={};for(let n of e.split(`
14
- `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.indexOf("=");if(s===-1)continue;let o=i.slice(0,s).trim(),r=Fn(i.slice(s+1).trim());t[o]=r}return t}var Fi=["VERCEL_TOKEN","CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","NETLIFY_AUTH_TOKEN","SELFHOST_DEPLOY_TARGET","SELFHOST_URL_TEMPLATE","EMAIL_PROVIDER","EMAIL_AUTH","EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT","SMS_PROVIDER","TEST_PHONE","TWILIO_ACCOUNT_SID","TWILIO_AUTH_TOKEN","TWILIO_PHONE_NUMBER","WHATSAPP_ACCOUNTS","LETTER_PROVIDER","PINGEN_CLIENT_ID","PINGEN_CLIENT_SECRET","PINGEN_ORG_ID","POSTGRID_API_KEY","NOTIFY_CHANNEL","TELEGRAM_BOT_TOKEN","TELEGRAM_CHAT_ID"];function Un(e,t,n){let i=Ti(Wt(t,e.countryCode)??"",Wt(n,e.countryCode)??"");e.pricing=i.pricing,e.pricingTerms=i.pricingTerms,e.pricingMonthly=i.pricingMonthly}function Hn(e){let t=e&&e!=="custom"?te[e]:void 0;return[["EMAIL_SENT_FOLDER","emailSentFolder",t?.sentFolder],["EMAIL_DRAFTS_FOLDER","emailDraftsFolder",t?.draftsFolder],["EMAIL_INBOX_FOLDER","emailInboxFolder",t?.inboxFolder]]}function Ui(e,t,n={}){let i={...e},s=r=>(t[r]??"").trim()!=="";!s("PRICING_TERMS")&&(s("PRICING")||s("PRICING_MONTHLY"))&&Un(i,t.PRICING,t.PRICING_MONTHLY),i.signature&&i.name&&i.signature.trim()===i.name.trim()&&(i.signature=void 0),s("EMAIL_FROM_NAME")||(i.emailFromName=i.name?.trim()&&i.emailAddress?.trim()?i.name.trim():void 0);let o=Ie(n)===i.emailProvider&&(n.EMAIL_ADDRESS??"").trim().toLowerCase()===(i.emailAddress??"").trim().toLowerCase();for(let[r,d,c]of Hn(i.emailProvider))s(r)||o&&(n[r]??"").trim()||(i[d]=c);return i}function Hi(e){let t=d=>{let c=e[d];if(!c)return;let p=parseInt(c,10);return isNaN(p)?void 0:p},n=e.SMS_PROVIDER,i=d=>d==="email"||d==="sms"||d==="whatsapp"||d==="letter",s=e.OUTREACH_CHANNELS?.split(",").map(d=>d.trim()).filter(i),o=e.OUTREACH_PRIORITY?.split(",").map(d=>d.trim()).filter(i),r=e.WHATSAPP_ACCOUNTS?.split(",").map(d=>d.trim()).filter(d=>d.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:On(e.AI_AGENT)??vn,aiPlan:_t(e.AI_PLAN),qaPhase:Tt(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(d=>d.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:s&&s.length>0?s:void 0,outreachPriority:o&&o.length>0?o:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailProvider:Ie(e),emailAuth:$n(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:Mn(n),testPhone:Rn(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,letterProvider:Dn(e.LETTER_PROVIDER),pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:Ln(e.DEPLOY_PROVIDER)??xn,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:Nn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function rt(e){let t=_=>{let C=e[_];if(!C)return;let M=parseInt(C,10);return isNaN(M)?void 0:M},n=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),s=e.SUPABASE_PAT?.replace(/\s+/g,""),o=e.SUPABASE_PROJECT_REF,r=e.PRICING,d=e.PRICING_TERMS||"one-off, no monthly fees",c=Ln(e.DEPLOY_PROVIDER)??xn,p=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,g=e.CLOUDFLARE_ACCOUNT_ID,m=e.NETLIFY_AUTH_TOKEN,w=e.SELFHOST_DEPLOY_TARGET,y=e.SELFHOST_URL_TEMPLATE;if(!r||!n||!i||!s||!o||!(c==="cloudflare"?!!u&&!!g:c==="netlify"?!!m:c==="selfhost"?!!w&&!!y:!!p))return null;let P=e.SMS_PROVIDER,T=_=>_==="email"||_==="sms"||_==="whatsapp"||_==="letter",I=e.OUTREACH_CHANNELS?.split(",").map(_=>_.trim()).filter(T),L=e.OUTREACH_PRIORITY?.split(",").map(_=>_.trim()).filter(T),$=e.WHATSAPP_ACCOUNTS?.split(",").map(_=>_.trim()).filter(_=>_.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:On(e.AI_AGENT)??vn,aiPlan:_t(e.AI_PLAN),qaPhase:Tt(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(_=>_.trim().toLowerCase()).filter(Boolean):void 0,pricing:r,pricingTerms:d,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:I&&I.length>0?I:void 0,outreachPriority:L&&L.length>0?L:void 0,whatsappAccounts:$&&$.length>0?$:void 0,emailProvider:Ie(e),emailAuth:$n(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:Mn(P),testPhone:Rn(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,letterProvider:Dn(e.LETTER_PROVIDER),pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,deployProvider:c,vercelToken:p,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:g||void 0,netlifyAuthToken:m||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:w||void 0,selfhostUrlTemplate:y||void 0,supabaseUrl:n,supabaseServiceKey:i,supabasePat:s,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:o,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:Nn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{readFile as dr}from"fs/promises";import Le from"picocolors";var a={info:e=>console.log(Le.cyan("\u2139"),e),success:e=>console.log(Le.green("\u2713"),e),warn:e=>console.log(Le.yellow("\u26A0"),e),error:e=>console.error(Le.red("\u2717"),e),step:e=>console.log(Le.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
15
- `+Le.bold(Le.cyan(e))),detail:e=>console.log(Le.dim(" "+e))};var ur="Fix this section's values and try again.";function S(e,t){a.blank();for(let n of pr(e,t))console.error(n);process.exit(2)}function pr(e,t){return[`INIT-BLOCKED section=${e}`,t,ur,"INIT-BLOCKED end"]}function zt(e){for(let t of Object.keys(qt)){if(!(t in e))continue;let n=e[t]??"";n.trim()!==""&&Ni(t,n)===void 0&&S("answers",`${t} is set to "${n}", which isn't one of the values it can take: ${qt[t].join(", ")}.`)}}async function Jt(e){let t;try{t=await dr(e,"utf-8")}catch{S("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){S("answers",`Answers file is not valid JSON: ${i.message}`)}return J(t)}function jn(e){return e.filter(([,t])=>!t?.trim()).map(([t,,n])=>[t,n])}function Kn(e,t){return e.some(([,n])=>(t[n]??"").trim()!=="")?"were cleared":"have never been set"}function Qt(e,t={}){if(!e.smsProvider)return"SMS is still switched on but no SMS provider is set \u2014 turn SMS off, or pick iMessage or Twilio.";if(e.smsProvider!=="twilio")return;let n=jn([["Account SID",e.twilioAccountSid,"TWILIO_ACCOUNT_SID"],["Auth Token",e.twilioAuthToken,"TWILIO_AUTH_TOKEN"],["sending number",e.twilioPhoneNumber,"TWILIO_PHONE_NUMBER"]]);return n.length>0?`SMS is still switched on but its Twilio details ${Kn(n,t)} (${n.map(([i])=>i).join(", ")}) \u2014 turn SMS off, or add the details.`:void 0}function Xt(e,t={}){if(!e.letterProvider)return"Letters are still switched on but no letter provider is set \u2014 turn letters off, or pick Pingen or PostGrid.";let n=e.letterProvider==="pingen"?jn([["Client ID",e.pingenClientId,"PINGEN_CLIENT_ID"],["Client Secret",e.pingenClientSecret,"PINGEN_CLIENT_SECRET"],["organisation id",e.pingenOrgId,"PINGEN_ORG_ID"]]):jn([["API key",e.postgridApiKey,"POSTGRID_API_KEY"]]);return n.length===0?void 0:`Letters are still switched on but the ${e.letterProvider==="pingen"?"Pingen":"PostGrid"} details ${Kn(n,t)} (${n.map(([s])=>s).join(", ")}) \u2014 turn letters off, or add the details.`}function Zt(e,t={}){let n=e.notifyChannel;if(n==="telegram"&&(!e.telegramBotToken?.trim()||!e.telegramChatId?.trim()))return`Alerts are still set to reach you on Telegram but the bot token and chat ID ${Kn([["bot token","TELEGRAM_BOT_TOKEN"],["chat ID","TELEGRAM_CHAT_ID"]],t)} \u2014 add them back, or choose another way to be alerted.`;if(n==="email"&&!e.notifyTo?.trim()&&!e.emailAddress?.trim())return"Alerts are still set to reach you by email but there's no address left to send them to \u2014 set one, or choose another way to be alerted.";if(n==="sms"&&!e.notifyTo?.trim()&&!e.testPhone?.trim())return"Alerts are still set to reach you by text but there's no number left to send them to \u2014 set one, or choose another way to be alerted."}import{readFile as qi,writeFile as wr}from"fs/promises";import{join as zi}from"path";import{mkdir as hr,readFile as gr,access as yr}from"fs/promises";import{dirname as kr,join as Bi}from"path";import{chmod as ji,rename as fr,unlink as mr,writeFile as Ki}from"fs/promises";var Gi=new Set(["EPERM","EACCES","EBUSY"]);async function Ee(e,t,n){let i=`${e}.${process.pid}-${Date.now()}.tmp`;await Ki(i,t);for(let s=1;;s++)try{await fr(i,e),n!==void 0&&await ji(e,n).catch(()=>{});return}catch(o){let r=o.code??"";if(Gi.has(r)&&s<5){await new Promise(d=>setTimeout(d,50*s));continue}if(await mr(i).catch(()=>{}),!Gi.has(r))throw o;await Ki(e,t),n!==void 0&&await ji(e,n).catch(()=>{});return}}var Ce=".klaudius",Vi=`${Ce}/manifest.json`,It=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json","prompts/lessons/find.md","prompts/lessons/gather.md","prompts/lessons/build.md","prompts/lessons/deploy.md","prompts/lessons/outreach.md"]),Yi=new Set(["clients/README.md"]),en=new Set(["package-lock.json"]);async function tn(e){let t=Bi(e,Vi);try{await yr(t)}catch{return null}let n=await gr(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 Ne(e,t){let n=Bi(e,Vi);await hr(kr(n),{recursive:!0}),await Ee(n,JSON.stringify(t,null,2)+`
16
- `)}function Wi(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}function nn(e){return zi(e,Ce,"ms-signin.json")}async function Ji(e){return qi(zi(e,".ms-token.json"),"utf-8").then(t=>String(JSON.parse(t).account?.address??"")).then(t=>t.trim().toLowerCase()).catch(()=>"")}async function sn(e,t){let n=t.trim().toLowerCase();if(n==="")return!1;let i=await Ji(e);if(i==="")return!1;if(i===n)return!0;let s=await qi(nn(e),"utf-8").then(d=>JSON.parse(d)).catch(()=>null),o=String(s?.entered??"").trim().toLowerCase(),r=String(s?.token??"").trim().toLowerCase();return o!==""&&o===n&&r===i}async function on(e,t){let n={entered:t.trim(),token:await Ji(e)};await wr(nn(e),`${JSON.stringify(n)}
17
- `,"utf-8").catch(()=>{})}import{copyFile as Kd,mkdir as Gd,readdir as Er,stat as Bd}from"fs/promises";import{dirname as Yd,join as Xi,relative as Pr,sep as Sr}from"path";import{fileURLToPath as qd}from"url";import{createHash as Qi}from"crypto";import{readFile as Ar}from"fs/promises";async function fe(e){let t=await Ar(e);return Qi("sha256").update(t).digest("hex")}function Gn(e){return Qi("sha256").update(e).digest("hex")}async function qe(e,t=e){let n=await Er(e,{withFileTypes:!0}),i=[];for(let s of n){let o=Xi(e,s.name);s.name===".klaudius"&&e===t||(s.isDirectory()?i.push(...await qe(o,t)):s.isFile()&&i.push(Pr(t,o).split(Sr).join("/")))}return i}async function Zi(e){let t=await qe(e),n={};for(let i of t)It.has(i)||(n[i]=await fe(Xi(e,i)));return n}import{copyFile as br,mkdir as es,mkdtemp as _r,readdir as ts,rm as ns}from"fs/promises";import{tmpdir as Tr}from"os";import{dirname as Ir,join as an}from"path";import{Readable as Cr}from"stream";import*as is from"tar";var Re="Couldn't reach Klaudius just now. Try again in a minute.";function rn(e,t){return e>=500||e===408||e===429?!0:!(typeof t=="object"&&t!==null&&typeof t.ok=="boolean")}var Rr="https://klaudius.dev/api/template";function vr(e){return Cr.fromWeb(e)}var at=class extends Error{unavailable=!0;detail;constructor(t){super(`${Re} (${t})`),this.detail=t}},Ct=class extends Error{outdated;reason;constructor(t,n){super(`Template download failed: HTTP ${t}${n?` (${n})`:""}`),this.outdated=t===426,this.reason=n}};async function ln(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Rr,n="0.37.5",i;try{i=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(d){throw new at(H(d))}if(!i.ok){let d=null;try{d=await i.json()}catch{}throw rn(i.status,d)?new at(`HTTP ${i.status}`):new Ct(i.status,d.reason??"")}if(!i.body)throw new Error("Template download succeeded but response had no body");let s=i.headers.get("x-klaudius-tier"),o=await _r(an(Tr(),"klaudius-template-")),r=0;try{try{await new Promise((p,u)=>{let g=is.extract({cwd:o,strict:!0});g.on("finish",p),g.on("error",u),vr(i.body).on("error",u).pipe(g)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await es(e.destDir,{recursive:!0});let d=new Set(await ts(e.destDir)),c=await qe(o);try{for(let p of c){let u=an(e.destDir,p);await es(Ir(u),{recursive:!0}),await br(an(o,p),u),r++}}catch(p){let u=await ts(e.destDir).catch(()=>[]);for(let g of u)d.has(g)||await ns(an(e.destDir,g),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await ns(o,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:r,tier:s}}import{copyFile as Or,mkdir as ss,readFile as Bn,rm as xr,writeFile as Lr}from"fs/promises";import{dirname as Nr,join as ve}from"path";import{structuredPatch as $r}from"diff";var Rt=ve(".klaudius","base"),Oe=ve(".klaudius","conflict-base"),os=".klaudius-snapshot-id";async function cn(e,t,n,i){let s=ve(e,Rt);await xr(s,{recursive:!0,force:!0}),await ss(s,{recursive:!0});for(let o of n){let r=ve(s,o);await ss(Nr(r),{recursive:!0}),await Or(ve(t,o),r)}i!==void 0&&await Lr(ve(s,os),i,"utf-8")}async function rs(e){try{return(await Bn(ve(e,Rt,os),"utf-8")).trim()}catch{return null}}async function as(e,t){try{return await Bn(ve(e,Rt,t),"utf-8")}catch{return null}}async function ls(e,t){try{return await Bn(ve(e,Oe,t),"utf-8")}catch{return null}}function cs(e,t,n,i){return!i||$e(n)?null:e!==null&&!$e(e)&&Gn(e)===i?e:t!==null&&!$e(t)&&Gn(t)===i?t:null}function $e(e){return e.includes("\0")||e.includes("\uFFFD")}function ds(e,t,n=60){let i=$r("base","new",e,t,"","",{context:2});if(i.hunks.length===0)return["Upstream content is identical to your base for this file."];let s=i.hunks.map(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),o=[`Upstream changed ${i.hunks.length} hunk(s) (new-version lines ${s}):`,"","```diff"],r=0,d=!1;for(let c of i.hunks){if(r>=n){d=!0;break}o.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),r+=1;let p=Math.max(n-r,0),u=c.lines.slice(0,p);if(o.push(...u),r+=u.length,u.length<c.lines.length){d=!0;break}}return o.push("```"),d&&o.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),o}var Mr="https://registry.npmjs.org/klaudius/latest";async function Dr(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Mr,{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 Fr(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 dn(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Dr();!n||!Fr(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 Ur}from"crypto";import{hostname as us,userInfo as Hr,platform as ps,arch as fs}from"os";var jr="https://klaudius.dev",Kr="/api/licenses/validate",Gr="0.37.5";async function ms(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??jr).replace(/\/$/,"")+Kr,s=vt(),o;try{o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:s,hostname:us(),os:`${ps()}-${fs()}`,cli_version:Gr})})}catch(c){return{ok:!1,unavailable:!0,reason:Re,detail:H(c)}}let r=null;try{r=await o.json()}catch{}if(rn(o.status,r))return{ok:!1,unavailable:!0,reason:Re,detail:`HTTP ${o.status}`};let d=r;return d.ok?{ok:!0,tier:d.tier??"core"}:{ok:!1,reason:d.reason??`License rejected (HTTP ${o.status}).`,...o.status===426?{outdated:!0}:{}}}function vt(){let e=[us(),Hr().username,ps(),fs()].join("|");return Ur("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Br}from"fs/promises";import{join as Vr}from"path";async function Me(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${H(n)}`}}}function Ot(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function lt(e){let t;try{t=await Br(Vr(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=qr(i.status,await i.text());return(i.status===401||i.status===403)&&e.url&&e.serviceKey?await Yr({url:e.url,serviceKey:e.serviceKey,projectRef:e.projectRef,sql:t,status:i.status,rejection:s}):{ok:!1,message:s}}catch(i){return{ok:!1,message:`Schema apply failed: ${H(i)}`}}}async function Yr(e){let t=e.projectRef.trim().toLowerCase();if(/^https?:\/\/([a-z0-9]+)\.supabase\.co(?=[:/]|$)/i.exec(e.url.trim())?.[1]?.toLowerCase()!==t)return{ok:!1,message:`${e.rejection} The tables couldn't be checked either: the database URL isn't this project's address (https://${t}.supabase.co).`};let i=hs(e.sql);if(i.tables.length===0&&Object.keys(i.columns).length===0)return{ok:!1,message:e.rejection};let s=await xt({url:e.url,serviceKey:e.serviceKey,sql:e.sql});return s.unreachable?{ok:!1,message:`${e.rejection} The tables already in the database couldn't be checked either (${s.unreachable}).`}:s.ok?{ok:!0,tokenRefused:e.status}:{ok:!1,message:`${e.rejection} Not in the database yet: ${s.missing.join(", ")}.`}}function ct(e){return e===401?"Your agent uses the same access token for some of its database work, and Supabase says it's invalid, expired or revoked: replace it when you can with a new one from https://supabase.com/dashboard/account/tokens.":"Your agent uses the same access token for some of its database work, so replace it when you can with a new one from https://supabase.com/dashboard/account/tokens, made in an account with access to this project, with full access (or at least Database and Migrations read-write and API Keys read on this project)."}function dt(e){return`Only tables and columns can be checked without the token. If you haven't just done it, open ${Ot(e)}, paste in the contents of scripts/schema.sql from your project folder, and click Run, so the rest of it is current too (safe to re-run).`}function hs(e){let t=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/--[^\n]*/g," "),n=o=>!o||o.toLowerCase()==="public",i=[];for(let o of t.matchAll(/CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+(?:(\w+)\.)?(\w+)/gi)){let r=o[2].toLowerCase();n(o[1])&&!i.includes(r)&&i.push(r)}let s=Object.create(null);for(let o of t.matchAll(/ALTER\s+TABLE\s+(IF\s+EXISTS\s+)?(?:ONLY\s+)?(?:(\w+)\.)?(\w+)\s+([^;]*)/gi)){if(o[1]||!n(o[2]))continue;let r=o[3].toLowerCase();for(let d of o[4].matchAll(/ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+(\w+)/gi)){let c=d[1].toLowerCase(),p=s[r]??(s[r]=[]);p.includes(c)||p.push(c)}}return{tables:i,columns:s}}function Wr(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 xt(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{tables:i,columns:s}=hs(e.sql),o=[];try{for(let r of new Set([...i,...Object.keys(s)])){let d=s[r]??[],c=await fetch(`${t}/rest/v1/${r}?select=${d.length>0?d.join(","):"*"}&limit=0`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(c.ok)continue;let p=Wr(c.status,await c.text());if(p.missing){o.push(c.status===404?`${r} table`:`${r} columns`);continue}return{ok:!1,missing:o,unreachable:`HTTP ${c.status}${p.code?` ${p.code}`:""}`}}}catch(r){return{ok:!1,missing:o,unreachable:H(r)}}return{ok:o.length===0,missing:o}}function qr(e,t){let n=t,i=!1;try{let o=JSON.parse(t);o&&typeof o.message=="string"&&(n=o.message,i=!0)}catch{}n=n.replace(/\s+/g," ").trim();let s=i&&n?`: "${zr(n,300)}"`:"";return e===401?`Supabase rejected the access token (HTTP 401${s}) \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?`Supabase refused the access token for this project (HTTP 403${s}). Create a new token at https://supabase.com/dashboard/account/tokens, signed in to an account with access to this project, with full access \u2014 or, if you choose its permissions, at least Database and Migrations read-write and API Keys read on this project \u2014 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.slice(0,300)}`}function zr(e,t){return e.length>t?`${e.slice(0,t-1).trimEnd()}\u2026`:e}function Jr(e){try{let t=JSON.parse(e);return t.error?.code==="not_found"?!0:/user not found/i.test(t.error?.message??"")}catch{return!1}}function Qr(e,t){return e===401||e===403?{kind:"rejected",message:`Vercel rejected the token (HTTP ${e}). It may be invalid, expired or revoked.`}:e===404&&Jr(t)?{kind:"scope",message:"Vercel rejected the token (HTTP 404). Its Scope doesn't include your account, for example it was limited to a single project."}:{kind:"api",message:`Vercel API returned HTTP ${e}. Try again or check status.vercel.com.`}}async function De(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,...Qr(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 gs="https://api.cloudflare.com/client/v4";function ys(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Fe(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let s=await fetch(`${gs}/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})`:""}. ${ys(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(`${gs}/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:ys(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 ks="https://api.netlify.com/api/v1";async function Ue(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${ks}/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(`${ks}/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 Xr(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 He(e){let t=Ii(e);if(t)return{ok:!1,message:t};let n=we(e),i=n.value,s=o=>{let r=[o],d=Ci(e);return d&&r.push(d),n.repairs.length>0&&r.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),r.join(`
18
- `)};try{let o=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":i,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(o.ok)return{ok:!0};if(o.status===429)return{ok:!0};let r={};try{r=await o.json()}catch{}let d=r.error?.message??"",c=r.error?.status??"";return o.status===400&&(c==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(d))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library/places.googleapis.com and press Enable for the project this key belongs to, then try again. (That page is 'Places API (New)' \u2014 the older 'Places API' is a different API and won't work.)"}:o.status===401||o.status===403?{ok:!1,message:s(Xr(o.status,d))}:{ok:!1,message:s(`Google API returned HTTP ${o.status}${d?`: ${d}`:""}.`)}}catch(o){return{ok:!1,message:`Could not reach Google: ${H(o)}`}}}import Zr from"nodemailer";import{ImapFlow as ea}from"imapflow";function ta(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function ws(e,t,n){let i=t.toLowerCase(),s=e.filter(ta);if(s.some(d=>d.path.toLowerCase()===i))return;let o=i.startsWith("inbox")?void 0:[`inbox.${i}`,`inbox/${i}`],r=s.find(d=>d.specialUse===n)?.path??(o&&s.find(d=>o.includes(d.path.toLowerCase()))?.path);return{configured:t,detected:r||void 0}}function Vn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let i=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return i.includes("invalid credentials")||i.includes("authentication failed")||i.includes("auth failed")||i.includes("login failed")||i.includes("invalid login")?"auth":i.includes("etimedout")||i.includes("timeout")||i.includes("enotfound")||i.includes("getaddrinfo")||i.includes("econnrefused")||i.includes("econnreset")?"network":"other"}async function me(e){let t=Zr.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:As(r,"SMTP",e.usesAccountPassword,e.knownProvider,e.errorHint),failureKind:Vn(r)}}finally{t.close()}let n=new ea({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=ws(r,e.sentFolder,"\\Sent")),e.draftsFolder&&(s=ws(r,e.draftsFolder,"\\Drafts"))}catch{o=!0}await n.logout()}catch(r){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:As(r,"IMAP",e.usesAccountPassword,e.knownProvider,e.errorHint),failureKind:Vn(r)}}return{ok:!0,sentFolderIssue:i,draftsFolderIssue:s,foldersUnverified:o}}function na(e){if(e?.form)return`Keep the alias as
19
- the email address and put the primary address in "Sign-in username".`;let t=e?.addressSetting??"EMAIL_ADDRESS",n=e?.loginSetting??"EMAIL_LOGIN";return`Keep the alias as
20
- ${t} and set ${n} in .env to the primary address.`}function ia(e){let t=e,i=(typeof t?.responseText=="string"&&t.responseText||typeof t?.response=="string"&&t.response||typeof t?.message=="string"&&t.message||"").replace(/^invalid login:\s*/i,"").replace(/https?:\/\/\S+/g,"").replace(/\bfor more information,? go to\b/gi,"").replace(/\b(AUTH\s+(?:PLAIN|LOGIN))\s+\S+/gi,"$1 \u2026").replace(/(?=[A-Za-z0-9+/]*\d)(?=[A-Za-z0-9+/]*[a-z])(?=[A-Za-z0-9+/]*[A-Z])[A-Za-z0-9+/]{16,}={0,2}/g,"\u2026").replace(/\n\s*\d{3}[ -]\d\.\d+\.\d+\s*/g," ").replace(/\s+/g," ").replace(/[\s.]+$/,"").trim();return!i||/^command failed$/i.test(i)?"":i.length>160?`${i.slice(0,157)}...`:i}function As(e,t,n,i,s){let o=e instanceof Error?e.message:String(e),r=o.toLowerCase();if(Vn(e)==="auth"||r.includes("invalid credentials")||r.includes("authentication failed")||r.includes("auth failed")||r.includes("login failed")){let d=ia(e),c=d?`${t} rejected the credentials (${d}).`:`${t} rejected the credentials.`;return!n&&/application-specific password required/i.test(d)?`${c}
21
- This mailbox refuses its normal account password here and wants an app
22
- password instead: a separate password the provider issues for apps,
23
- created in the account's security settings (2-step verification has to
24
- be on first). Create one and use it in place of the password.`:n?`${c} Most common causes:
25
- \u2022 The mailbox password is wrong or mistyped.
26
- \u2022 The email address doesn't match this mailbox's login.
27
- \u2022 The provider is blocking third-party apps \u2014 check that third-party
28
- access is enabled and 2FA is off in your provider's settings.`:i===!1?`${c} Most common causes:
29
- \u2022 The password is wrong or mistyped. Signing in to the mailbox's webmail
30
- with it is a quick way to check.
31
- \u2022 The email address isn't this mailbox's login name.
32
- \u2022 The server or port belongs to a different mailbox or provider.
33
- \u2022 The provider needs an app password here rather than the normal one.`:`${c} Most common causes:
34
- \u2022 The app password is wrong, expired, or for a different provider.
35
- \u2022 The email address doesn't match the account that issued the password.
36
- \u2022 The address is an alias (e.g. a Google Workspace alias domain) \u2014 the
37
- sign-in must use the account's primary address. ${na(s)}
38
- \u2022 2FA is required but no app-specific password was generated.`}return r.includes("etimedout")||r.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:r.includes("enotfound")||r.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${o}`}import*as un from"@clack/prompts";var sa=[{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 ut(e,t,n){let i=!1;for(let s of sa){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 un.confirm({message:`Use "${o.detected}" instead?`,initialValue:!0});if(un.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 pn(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 pt(e){return e.provider==="pingen"?oa(e):ra(e)}async function oa(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 ra(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 aa}from"child_process";async function Es(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 la(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 la(e){return new Promise(t=>{let n=aa("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 fn}from"child_process";import{existsSync as ca}from"fs";import{homedir as da}from"os";function ua(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var ft=2,Ps=2e3,pa=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Ss(e,t){let n=e+`
39
- `+t;return pa.some(i=>i.test(n))}function bs(e){return new Promise(t=>setTimeout(t,e))}function fa(e,t,n){return new Promise(i=>{let s=n.shell?fn([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):fn(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),o="",r="";s.stdout?.on("data",d=>{let c=d.toString();o+=c,process.stdout.write(c)}),s.stderr?.on("data",d=>{let c=d.toString();r+=c,process.stderr.write(c)}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",d=>i({code:1,stdout:o,stderr:r+d.message}))})}async function Yn(e,t,n){let i={code:0,stdout:"",stderr:""};for(let s=0;s<=ft;s++){if(i=await fa(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!Ss(i.stderr,i.stdout))return i;s<ft&&(a.detail(`${n.label} failed with a transient network error \u2014 retrying (${s+2}/${ft+1})\u2026`),await bs(Ps))}return i}function ma(e,t,n){return new Promise(i=>{let s=fn(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",d=>{o+=d.toString()}),s.stderr?.on("data",d=>{r+=d.toString()}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",d=>i({code:1,stdout:o,stderr:r+d.message}))})}var ha=[{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 ga(e){let t=`${e.stderr??""}
40
- ${e.stdout??""}`;return ha.find(i=>i.pattern.test(t))?.hint}async function ya(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],s=(await Q())?.command??["python3"],o=async d=>{let c={code:0,stdout:"",stderr:""};for(let p=0;p<=ft;p++){if(c=await ma(s[0],[...s.slice(1),...d],{cwd:e}),c.code===0||!Ss(c.stderr,c.stdout))return c;p<ft&&(a.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${ft+1})\u2026`),await bs(Ps))}return c},r=await o([...n,"--break-system-packages",...t]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(a.detail("Older pip detected; retrying without --break-system-packages"),r=await o([...n,...t])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function mn(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=ua(),i=process.platform==="win32",s;if(i){let u=Ze([{label:"your Windows user folder",path:da()},{label:"the project folder",path:e}]);if(u.length>0){let g=await new Promise(w=>{let y=fn("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),l="",P="";y.stdout?.on("data",T=>{l+=T.toString()}),y.stderr?.on("data",T=>{P+=T.toString()}),y.on("close",T=>w({code:T??1,stdout:l,stderr:P})),y.on("error",T=>w({code:1,stdout:l,stderr:T.message}))}),m=g.code===0?g.stdout.trim():void 0;if(!et(m,ca)){let{detail:w,action:y}=tt(u,"install");s=`${w}. ${y}`}}}let o=(u,g)=>{let m=ga(g);if(m){(t.hints??={})[u]=m;return}s&&(u==="npm"||u==="playwright"||u==="patchright")&&!Object.values(t.hints??{}).includes(s)&&((t.hints??={})[u]=s)};a.step("Running npm install (Next.js, Playwright JS, etc.)...");let r=await Yn("npm",["install"],{cwd:e,label:"npm install",env:n,shell:i});t.npm=r.code===0?"ok":"failed",r.code!==0&&o("npm",r),a.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let d=await ya(e);t.pip=d.code===0?"ok":"failed",d.code!==0&&o("pip",d),a.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Yn("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:i});t.playwright=c.code===0?"ok":"failed",c.code!==0&&o("playwright",c),a.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await Yn("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 ka,access as wa}from"fs/promises";import{dirname as Aa,join as Ea}from"path";async function _s(){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 Wn(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await _s();if(e.state==="real")return{status:"ok",version:e.version};let t=await Q();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function Pa(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=Ea(Aa(s),"python3.exe"),r=await wa(o).then(()=>!0,()=>!1);if(!r){if(/[\\/]WindowsApps[\\/]/i.test(o))return{ok:!1,reason:"store-python",target:o};try{await ka(s,o)}catch{return{ok:!1,reason:"not-writable",target:o,manualCommand:`copy "${s}" "${o}"`}}}let d=await _s();return{ok:!0,target:o,created:!r,verified:d.state==="real",postState:d.state==="real"?void 0:d.state}}var Sa="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 hn(){let e=await Wn();if(e.status!=="broken")return;let t=await Pa(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(Sa);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 ba,spawnSync as Ts}from"child_process";import{mkdtemp as _a,rm as Ta,rmdir as Ia,writeFile as Ca,stat as qn,unlink as Ra,mkdir as va}from"fs/promises";import{createServer as Oa}from"net";import{tmpdir as xa}from"os";import{join as mt}from"path";function La(){return new Promise((e,t)=>{let n=Oa();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 gn(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?Ts(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):Ts("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function yn(e){try{return await Na(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Na(e){let t=`klaudius-smoke-${process.pid}`,n=mt(".klaudius",`qa-smoke-${process.pid}.png`),i=mt(e,n),s,o,r=!1;try{s=await _a(mt(xa(),"klaudius-qa-smoke-")),await Ca(mt(s,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let d=await La();o=ba("python3",["-m","http.server",String(d),"--directory",s],{stdio:"ignore",shell:!1});let c=!1;o.on("error",()=>{c=!0}),o.on("exit",()=>{c=!0});let p=`http://127.0.0.1:${d}/`,u=!1;for(let P=0;P<24&&!c;P++)try{if((await fetch(p,{signal:AbortSignal.timeout(1e3)})).ok){u=!0;break}}catch{await new Promise(T=>setTimeout(T,500))}if(!u)return{ok:!1,stage:"python3-server",detail:"`python3 -m http.server` never came up on a free local port",remediation:process.platform==="win32"?"python3 on this machine isn't runnable (usually the Microsoft Store placeholder). Running `npx klaudius@latest update` fixes it automatically.":"Check `python3 --version` works in this terminal."};let g=mt(e,".klaudius"),m=await qn(g).then(()=>!0,()=>!1);await va(g,{recursive:!0}),r=!m;let w=gn(e,[`-s=${t}`,"open",p]);if(w.status!==0)return{ok:!1,stage:"browser",detail:((w.stderr??"")+(w.stdout??"")).slice(-400).trim()||"playwright-cli could not open a browser",remediation:"Run `npx playwright install chromium` in this folder"+(process.platform==="linux"?", and under WSL also `npx playwright install-deps chromium` (missing system libraries are the usual cause there).":".")};let y=gn(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await qn(i).catch(()=>null);if((!l||l.size===0)&&(y=gn(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await qn(i).catch(()=>null)),!l||l.size===0){let P=((y.stderr??"")+(y.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{gn(e,[`-s=${t}`,"close"]),o&&!o.killed&&o.kill(),await Ra(i).catch(()=>{}),r&&await Ia(mt(e,".klaudius")).catch(()=>{}),s&&await Ta(s,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as Is,readFile as $a,writeFile as Cs}from"fs/promises";import{join as kn}from"path";var je="Bash(claude --bg --permission-mode auto *)";async function Rs(e){let t;try{t=await $a(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 Ke(e,t){let n=kn(e,".claude"),i=kn(n,"settings.local.json"),s=".claude/settings.local.json";try{await Is(n,{recursive:!0});let o=await Rs(i);if(o===null)return a.warn(`${s} isn't valid JSON, so it was left as-is. Fix it and re-run to pre-approve the parallel-run dispatch.`),"skipped";let r=o.permissions&&typeof o.permissions=="object"&&!Array.isArray(o.permissions)?o.permissions:{},d=r.allow,c=Array.isArray(d)?d.filter(u=>typeof u=="string"):[];if(c.includes(t))return"present";c.push(t);let p={...o,permissions:{...r,allow:c}};return await Cs(i,JSON.stringify(p,null,2)+`
41
- `,"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 ht(e,t){let n=kn(e,".claude");await Is(n,{recursive:!0});let i=kn(n,"settings.json"),s=await Rs(i)??{},o=s.enabledMcpjsonServers,r=Array.isArray(o)?o.filter(c=>typeof c=="string"):[];r.includes(t)||r.push(t);let d={...s,enabledMcpjsonServers:r};await Cs(i,JSON.stringify(d,null,2)+`
42
- `,"utf-8")}var Jn="0.37.5",V=5,x=!1;function Qn(e){return X(e,Ce,"setup-pending")}function Ha(e){let t=process.env.KLAUDIUS_WHATSAPP_STATE_DIR||X(Ns(),".klaudius","whatsapp");return Ma(X(t,e,"auth","creds.json"))}var Os="Klaudius needs its latest update before setup can finish. Try again in a little while.";function xs(e){return`${e||"The license could not be validated."} If you believe this is in error, email hello@klaudius.dev with your purchase details.`}function he(e){return`npx klaudius@latest init ${En(gt(e))}`}function gt(e){if(process.platform==="win32")return e;let t=Ns();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function ja(e){let t=[];try{let i=(await Ls(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 ei(X(o,".env")))continue;let r=await ei(X(o,".klaudius","manifest.json"));if(t.push({path:o,finished:r}),t.length>=3)break}}catch{}return t}async function ei(e){try{return await Xn(e),!0}catch{return!1}}function En(e){return/\s/.test(e)?`"${e}"`:e}function Pe(e,t,n){a.blank(),a.error(`${t} validation failed ${V} times in a row. Pausing setup so you don't get stuck in a loop.`),a.detail(`Last error: ${n}`),a.blank(),a.detail("Your credentials are saved in `.env`. Two ways forward:"),a.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),a.blank(),console.log(` ${A.cyan(he(e))}`),a.blank(),a.detail(` (Your .env is at ${gt(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 $s(e){x=!!e.answers;let t=e.target??".",n=Fa(t)?t:Da(process.cwd(),t),i=Va(n);i&&(a.error("Klaudius can't be installed inside a protected system folder."),a.detail(`Path: ${n}`),a.detail(`Reason: ${i}`),a.blank(),a.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),a.blank(),process.platform==="win32"?(a.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${A.cyan("cd $HOME\\Documents")}`),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`)):(a.detail("For example:"),console.log(` ${A.cyan("cd ~/Documents")}`),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`)),a.blank(),process.exit(1)),process.platform==="win32"&&Ya()&&(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 dn("init",Jn);let s=await Ka(n),o=s.kind==="scaffolded"&&!!e.answers&&await ei(Qn(n));if(s.kind==="scaffolded"&&!o){x&&S("folder","There's already a Klaudius project in this folder. Choose a new folder name, or open that project instead."),a.blank(),a.warn(`Found an existing Klaudius project at ${A.bold(n)}.`),a.detail("(Your .env and project files are in place.)"),a.blank(),s.nodeModulesMissing?(a.detail("It looks like a previous setup didn't finish installing dependencies."),a.detail("To pick up where it left off, run:"),a.blank(),n!==process.cwd()&&console.log(` ${A.cyan(`cd ${En(t)}`)}`),console.log(` ${A.cyan("npx klaudius@latest install")} ${A.dim("# retries npm + pip + browsers; idempotent")}`),a.blank(),a.detail("Then verify with:"),a.blank(),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# checks Node / Python / installers / credentials")}`),a.blank()):(a.detail("Everything is scaffolded and dependencies look installed."),a.detail("Pick the action you wanted:"),a.blank(),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${A.cyan("npx klaudius@latest configure")} ${A.dim("# change a credential / API key")}`),console.log(` ${A.cyan("npx klaudius@latest update")} ${A.dim("# pull the latest skills, scripts and prompts")}`),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"){x&&S("folder","This folder already has files in it. Choose an empty folder or a new name.");let h=t===".",f=await ja(n);if(f.length>0){a.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),a.detail(`You're in: ${gt(n)}`),a.blank();for(let k of f)a.detail(k.finished?`Found a finished project at ${gt(k.path)}. To work in it:`:`Found an unfinished setup at ${gt(k.path)}. To pick up where it left off:`),a.blank(),k.finished?(console.log(` ${A.cyan(`cd ${gt(k.path)}`)}`),console.log(` ${A.cyan("claude")} ${A.dim("# open Claude Code in the project")}`)):console.log(` ${A.cyan(he(k.path))} ${A.dim("# then pick Resume")}`),a.blank();process.exit(1)}a.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),a.detail(`Path: ${n}`),a.detail(`Contains: ${s.entries.slice(0,5).join(", ")}${s.entries.length>5?`, \u2026 (+${s.entries.length-5} more)`:""}`),a.blank(),h?(a.detail("Two ways forward:"),a.blank(),a.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`),a.blank(),a.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${A.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(a.detail(`The folder '${t}' already exists and isn't empty.`),a.detail("Either pick a different name:"),console.log(` ${A.cyan(`npx klaudius@latest init ${t}-2`)}`),a.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=null;e.answers&&(r=await Jt(e.answers),zt(r),a.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let d=r??{},c={};if(r){let h=await zn(X(n,".env"),"utf-8").catch(()=>null);h&&(c=J(h),r={...Object.fromEntries(Object.entries(c).filter(([k])=>!Fi.includes(k))),...r})}let p=e.license??r?.KLAUDIUS_LICENSE_KEY;x&&(!p||p.trim().length===0)&&S("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let u=await Ba(p),g=v.spinner();g.start("Validating license");let m=await ms(u);!m.ok&&m.unavailable&&(g.stop(x?"Couldn't check the licence key":Re,2),m.detail&&a.detail(`Details: ${m.detail}`),x&&S("unavailable",Re),a.detail(`To try again, re-run the same command: ${he(n)}`),process.exit(1)),!m.ok&&m.outdated&&(g.stop(`This copy of Klaudius (${Jn}) is out of date, so it can't set up.`,2),x&&S("install",Os),a.detail(`Run the latest one instead: ${he(n)}`),process.exit(1)),m.ok||(g.stop(`License invalid: ${m.reason??"unknown"}`,2),a.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),x&&S("license",xs(m.reason)),process.exit(1)),g.stop(`License valid (${m.tier??"core"} tier)`);let w=await nt();w.ok||(a.error(w.message??"Python version check failed."),a.blank(),a.detail(`Once you've installed Python 3.10+, re-run the same command: ${he(n)}`),process.exit(1)),await hn();let y=Ae();y.ok||(a.error(y.message??"Node.js version check failed."),a.blank(),a.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${he(n)}`),process.exit(1));let l,P=!1;if(r){let h=rt(r);h||S("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=Ui(h,d,c),a.success("Loaded setup answers (non-interactive mode)");let f=c.AI_AGENT==="codex"?"codex":"claude-code";if(o&&f!==(l.aiAgent??"claude-code")){let k=E=>E==="codex"?"Codex":"Claude Code";S("folder",`This folder was set up for ${k(f)}, so it can't carry on as ${k(l.aiAgent??"claude-code")}. Give the folder a different name to set up fresh, or switch back.`)}}else if(s.kind==="partial")if(await Ga(n)==="resume"){let f=await zn(s.envPath,"utf-8"),k=rt(J(f));k?(a.success("Resuming with values from your existing .env"),a.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=k,P=!0,l.aiPlan||(l=await W(l,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
43
- runs on. It sets the QA-pass default (and, on the smaller ChatGPT plans, the model).`}))):(a.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await W())}else{let f=await zn(s.envPath,"utf-8"),k=rt(J(f));l=await W(k??{})}else l=await W();l.licenseKey=u,await q(n,l),P||(a.success("Saved .env"),a.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),a.blank();for(let h=1;;h++){let f=v.spinner();f.start("Validating Supabase credentials");let k=await Me({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(k.ok){f.stop("Supabase credentials accepted");break}f.stop(k.message??"Supabase check failed",2),h>=V&&Pe(n,"Supabase",k.message??"Supabase check failed");let E=k.message??"Supabase check failed";a.blank(),x&&S("supabase",E),a.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${h+1} of ${V})`),a.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
44
- ${E}
45
-
46
- Re-enter the URL, secret key, or PAT below. Press Enter on any
47
- field to keep what's already there.`}),await q(n,l)}if(a.blank(),l.deployProvider==="cloudflare")for(let h=1;;h++){let f=v.spinner();f.start("Validating Cloudflare token + account");let k=await Fe({token:l.cloudflareApiToken??"",accountId:l.cloudflareAccountId??""});if(k.ok){f.stop(`Cloudflare credentials accepted (${k.projectCount??0} existing Pages project${k.projectCount===1?"":"s"})`);break}f.stop(k.message??"Cloudflare check failed",2),h>=V&&Pe(n,"Cloudflare",k.message??"Cloudflare check failed");let E=k.message??"Cloudflare check failed";a.blank(),x&&S("cloudflare",E),a.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${h+1} of ${V})`),a.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
48
- ${E}
49
-
50
- Re-enter the API token or Account ID below. The token needs the
51
- "Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
52
- the current value.`}),await q(n,l)}else if(l.deployProvider==="netlify")for(let h=1;;h++){let f=v.spinner();f.start("Validating Netlify token");let k=await Ue({token:l.netlifyAuthToken??""});if(k.ok){f.stop(k.accountSlug?`Netlify token accepted (team: ${k.accountSlug})`:"Netlify token accepted");break}f.stop(k.message??"Netlify check failed",2),h>=V&&Pe(n,"Netlify",k.message??"Netlify check failed");let E=k.message??"Netlify check failed";a.blank(),x&&S("netlify",E),a.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${h+1} of ${V})`),a.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"netlify",banner:`Netlify rejected the token:
53
- ${E}
54
-
55
- Generate a new token at
56
- https://app.netlify.com/user/applications#personal-access-tokens
57
- and paste it below. Press Enter to keep the current value.`}),await q(n,l)}else if(l.deployProvider==="selfhost")for(let h=1;;h++){let f=Qe(l.selfhostDeployTarget??""),k=Xe(l.selfhostUrlTemplate??"");if(!f&&!k){a.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let E=[f&&`SELFHOST_DEPLOY_TARGET: ${f}`,k&&`SELFHOST_URL_TEMPLATE: ${k}`].filter(Boolean).join(`
58
- `);h>=V&&Pe(n,"Self-host",E),a.blank(),x&&S("selfhost",E),a.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${h+1} of ${V})`),a.blank(),l=await W(l,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
59
- ${E}
60
-
61
- Re-enter them below. Press Enter on a field to keep its current value.`}),await q(n,l)}else for(let h=1;;h++){let f=v.spinner();f.start("Validating Vercel token");let k=await De(l.vercelToken??"");if(k.ok){f.stop(k.username?`Vercel token accepted (signed in as ${k.username})`:"Vercel token accepted");break}f.stop(k.message,2);let E=k.message,D=k.kind==="rejected"||k.kind==="scope",b=D?`${E} Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration).`:E;h>=V&&Pe(n,"Vercel",b),a.blank(),x&&S("vercel",b),a.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${h+1} of ${V})`),a.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"vercel",banner:D?`${E}
62
-
63
- Create a new token at https://vercel.com/account/settings/tokens
64
- (Scope: Full Account, Expiration: No Expiration) and paste it
65
- below. Press Enter to keep the current value.`:`${E}
66
-
67
- Press Enter to keep the current value and try again, or paste a
68
- different token.`}),await q(n,l)}a.blank();for(let h=1;;h++){let f=we(l.googlePlacesApiKey??""),k=v.spinner();k.start("Validating Google Places API key");let E=await He(l.googlePlacesApiKey??"");if(E.ok){if(k.stop("Google Places API key accepted"),f.changed){if(f.repairs.length>0){a.blank(),a.warn("Corrected look-alike characters in your Google Places API key:");for(let b of f.repairs)a.detail(` ${b}`);a.detail("These come from keys that were transcribed rather than copied."),a.detail("Google accepted the corrected key, and .env now holds it.")}l.googlePlacesApiKey=f.value,await q(n,l)}break}k.stop(E.message??"Google Places check failed",2),h>=V&&Pe(n,"Google Places",E.message??"Google Places check failed");let D=E.message??"Google Places check failed";a.blank(),x&&S("google-places",D),a.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${h+1} of ${V})`),a.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"google-places",banner:`Google rejected the key:
69
- ${D}
70
-
71
- Generate (or fix) the key at https://console.cloud.google.com
72
- and paste it below. Press Enter to keep the current value.`}),await q(n,l)}let T=!1;if(x&&l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAuth!=="oauth-microsoft"){let h=[["email address",l.emailAddress],["password",l.emailPassword],["SMTP host",l.emailSmtpHost],["IMAP host",l.emailImapHost]].filter(([,E])=>!E).map(([E])=>E),f=[["SMTP port",l.emailSmtpPort],["IMAP port",l.emailImapPort]].filter(([,E])=>!E).map(([E])=>E),k=[...h.length>0?[`the ${h.join(", ")} ${h.length===1?"is":"are"} missing`]:[],...f.length>0?[`the ${f.join(" and ")} ${f.length===1?"isn't a number":"aren't numbers"}`]:[]];k.length>0&&S("email",`Email outreach is switched on, but ${k.join(", and ")}. Fill ${k.length===1&&h.length+f.length===1?"it":"them"} in, or turn email off.`)}if(l.outreachEnabled&&l.outreachChannels?.includes("email")&&l.emailAddress&&l.emailPassword&&l.emailSmtpHost&&l.emailSmtpPort&&l.emailImapHost&&l.emailImapPort){a.blank();let h=0,f=!1,k;for(;!f;){h++;let E=v.spinner();E.start("Validating email credentials (SMTP + IMAP)");let D=l.emailProvider&&l.emailProvider!=="custom"?l.emailProvider:pe(l.emailSmtpHost),b=D?te[D]:void 0,N=await me({emailAddress:l.emailAddress,emailLogin:l.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:l.emailPassword,emailSmtpHost:l.emailSmtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:l.emailImapHost,emailImapPort:l.emailImapPort,usesAccountPassword:b?.usesAccountPassword,knownProvider:!!b,errorHint:{form:x},sentFolder:(l.emailSentFolder??"").trim()||"Sent",draftsFolder:(l.emailDraftsFolder??"").trim()||"Drafts"});if(N.ok){E.stop("Email credentials accepted (SMTP + IMAP)"),await ut(N,l,{nonInteractive:x,onCancel:()=>{v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
73
-
74
- ${he(n)}
75
- `),process.exit(0)}})&&await q(n,l);break}E.stop(N.message??"Email check failed",2);let ie=`${D}\0${l.emailAddress}\0${l.emailPassword}`;if(b&&N.failureKind!=="network"&&k!==ie){k=ie;let Ye=jt(D,l.emailSmtpHost,l.emailImapHost),ke,Ai=0;if(Ye.length>0){a.blank(),a.warn(`That server rejected the login. ${b.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let de of Ye){let In=v.spinner();In.start(`Trying ${de.label} (${de.smtpHost})`);let Cn=await me({emailAddress:l.emailAddress,emailLogin:l.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:l.emailPassword,emailSmtpHost:de.smtpHost,emailSmtpPort:l.emailSmtpPort,emailImapHost:de.imapHost,emailImapPort:l.emailImapPort,errorHint:{form:x}});if(Cn.ok){In.stop(`${de.label}: your login works here (${de.smtpHost})`),ke=de;break}Cn.failureKind!=="network"&&Ai++,In.stop(Cn.failureKind==="network"?`${de.label}: unreachable`:`${de.label}: rejected too`,2)}}if(ke){if(a.blank(),a.success("Found it \u2014 your password was right all along; the server was the only problem."),x){a.detail(`Non-interactive: using the working ${ke.label} servers automatically.`),l.emailSmtpHost=ke.smtpHost,l.emailImapHost=ke.imapHost,await q(n,l);continue}let de=await v.confirm({message:`Use the ${ke.label} servers (${ke.smtpHost} / ${ke.imapHost})?`,initialValue:!0});if(v.isCancel(de)&&(v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
76
-
77
- ${he(n)}
78
- `),process.exit(0)),de){l.emailSmtpHost=ke.smtpHost,l.emailImapHost=ke.imapHost,await q(n,l);continue}}else Ye.length>0&&(a.blank(),Ai===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."):b.noAltWorkedHint&&a.warn(b.noAltWorkedHint))}let _e=N.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(),x&&S("email",_e);let ae=await v.select({message:`What would you like to do? ${A.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:h>=3?"skip":h>=2?"edit":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my email details and retry"},{value:"skip",label:"Skip email for now (finish setup; wire email up later)"}]});if(v.isCancel(ae)&&(v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
79
-
80
- ${he(n)}
81
- `),process.exit(0)),ae==="skip"){l.outreachChannels=(l.outreachChannels??[]).filter(Ye=>Ye!=="email"),l.outreachPriority=(l.outreachPriority??[]).filter(Ye=>Ye!=="email"),l.outreachChannels.length===0&&(l.outreachEnabled=!1),await q(n,l),T=!0,a.success("Skipped email for now. Setup will continue."),l.outreachEnabled?a.detail("Outreach will use your other channel(s); email stays off until it's fixed."):a.detail("Automated outreach is off until email is fixed \u2014 everything else works."),f=!0;break}ae==="edit"&&(a.blank(),l=await W(l,{onlySection:"email",banner:`${N.failedAt==="imap"?"IMAP":"SMTP"} check failed:
82
- ${_e}
83
-
84
- Re-enter the email address, app password, or server details below.
85
- Press Enter on any field to keep its current value.
86
-
87
- Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
88
- at the "Server settings" question.`}),await q(n,l))}}if(x&&l.outreachEnabled&&l.outreachChannels?.includes("sms")){let h=Qt(l);h&&S("sms",h)}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="twilio"&&l.twilioAccountSid&&l.twilioAuthToken){a.blank();for(let h=1;;h++){let f=v.spinner();f.start("Validating Twilio credentials");let k=await pn({accountSid:l.twilioAccountSid,authToken:l.twilioAuthToken});if(k.ok){f.stop(k.friendlyName?`Twilio credentials accepted (${k.friendlyName})`:"Twilio credentials accepted");break}f.stop(k.message??"Twilio check failed",2),h>=V&&Pe(n,"Twilio",k.message??"Twilio check failed");let E=k.message??"Twilio check failed";a.blank(),x&&S("sms",E),a.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${h+1} of ${V})`),a.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"sms",banner:`Twilio rejected the credentials:
89
- ${E}
90
-
91
- Re-enter the Account SID or Auth Token below.
92
- Press Enter on any field to keep its current value.`}),await q(n,l)}}if(x&&l.outreachEnabled&&l.outreachChannels?.includes("letter")){let h=Xt(l);h&&S("letter",h)}if(l.outreachEnabled&&l.outreachChannels?.includes("letter")&&l.letterProvider){a.blank();for(let h=1;;h++){let f=v.spinner();f.start("Validating letter provider credentials");let k=await pt({provider:l.letterProvider,pingenClientId:l.pingenClientId,pingenClientSecret:l.pingenClientSecret,pingenOrgId:l.pingenOrgId,postgridApiKey:l.postgridApiKey});if(k.ok){f.stop(k.friendlyName?`Letter provider credentials accepted (${k.friendlyName})`:"Letter provider credentials accepted");break}f.stop(k.message??"Letter provider check failed",2),h>=V&&Pe(n,"Letter provider",k.message??"Letter provider check failed");let E=k.message??"Letter provider check failed";a.blank(),x&&S("letter",E),a.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${h+1} of ${V})`),a.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"letter",banner:`The letter provider rejected the credentials:
93
- ${E}
94
-
95
- Re-enter them below.
96
- Press Enter on any field to keep its current value.`}),await q(n,l)}}if(l.outreachEnabled&&l.outreachChannels?.includes("sms")&&l.smsProvider==="imessage"&&l.testPhone){a.blank();for(let h=1;;h++){let f=v.spinner();f.start("Validating iMessage setup (sending a test ping)");let k=await Es({testPhone:l.testPhone});if(k.ok){if(f.stop("iMessage dispatched (check your phone for the test ping)"),x){console.error("NOTE: iMessage dispatch succeeded but DELIVERY is unverified in non-interactive mode. Check the test message arrived on your phone; if not, open Messages on this Mac, confirm it's signed in with your Apple ID, and enable Settings \u2192 Messages \u2192 Text Message Forwarding on your iPhone.");break}let D=await v.confirm({message:"Did the test message actually arrive on your phone?",initialValue:!0});if(v.isCancel(D)&&(v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
97
-
98
- ${he(n)}
99
- `),process.exit(0)),D)break;f.stop("Dispatched but not delivered \u2014 Messages.app can't reach that number",2),h>=V&&Pe(n,"iMessage","Test message dispatched but never delivered"),a.blank(),a.warn("Messages accepted the send but it didn't arrive. Usual fixes: make sure TEST_PHONE is in international format (+44\u2026 not 07\u2026); open Messages on this Mac and confirm it's signed in with your Apple ID; and on your iPhone enable Settings \u2192 Messages \u2192 Text Message Forwarding for this Mac. Fix, then retry."),a.blank(),l=await W(l,{onlySection:"sms",banner:`The test message was dispatched but never arrived on your phone.
100
- Re-check the number below (international format with a leading +).
101
- Press Enter on any field to keep its current value.`}),await q(n,l);continue}f.stop(k.message??"iMessage check failed",2),h>=V&&Pe(n,"iMessage",k.message??"iMessage check failed");let E=k.message??"iMessage check failed";a.blank(),x&&S("sms",E),a.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${h+1} of ${V})`),a.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"sms",banner:`iMessage check failed:
102
- ${E}
103
-
104
- Either fix the underlying issue (sign in to Messages.app, configure
105
- Text Message Forwarding) and press Enter through, or change SMS
106
- provider to Twilio.`}),await q(n,l)}}if(x){let h=Zt(l);h&&S("notifications",h)}if((l.notifyChannel??"telegram")==="telegram"&&l.telegramBotToken&&l.telegramChatId){a.blank();let h=0,f=!1;for(;!f;){h++;let k=v.spinner();k.start("Validating Telegram bot + chat (sending a test ping)");let E=await Kt({botToken:l.telegramBotToken,chatId:l.telegramChatId});if(E.ok){k.stop(E.botHandle?`Telegram bot ${E.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),f=!0;break}k.stop(E.message??"Telegram check failed",2);let D=E.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(),x&&S("notifications",D);let b=await v.select({message:`What would you like to do? ${A.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:h>=2?"skip":"retry",options:[{value:"retry",label:"Retry the check (good if it was a momentary network blip)"},{value:"edit",label:"Edit my bot token / chat ID and retry"},{value:"skip",label:"Skip Telegram for now (I'll add it later by editing .env)"}]});if(v.isCancel(b)&&(v.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
107
-
108
- ${he(n)}
109
- `),process.exit(0)),b==="skip"){l.telegramBotToken=void 0,l.telegramChatId=void 0,await q(n,l),a.success("Skipped Telegram. Setup will continue."),a.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),f=!0;break}if(b==="edit"&&(a.blank(),l=await W(l,{onlySection:"notifications",banner:`Telegram check failed:
110
- ${D}
111
-
112
- Re-enter the bot token or chat_id below.
113
- Press Enter on any field to keep its current value.`}),await q(n,l),(l.notifyChannel??"telegram")!=="telegram"||!l.telegramBotToken||!l.telegramChatId)){a.success("Skipped Telegram. Setup will continue."),f=!0;break}}}if(a.blank(),o)a.detail("Picking up the setup that didn't finish in this folder \u2014 your files are already here.");else{let h=v.spinner();h.start("Downloading Klaudius template");let f;try{f=(await ln({licenseKey:u,machineId:vt(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:l.aiAgent,destDir:n})).filesExtracted,h.stop(`Downloaded ${f} files into ${A.bold(n)}`)}catch(E){x&&E instanceof at&&(h.stop("Couldn't download Klaudius",2),a.detail(`Details: ${E.detail}`),S("unavailable",Re)),x&&E instanceof Ct&&(h.stop(E.message,2),S(E.outdated?"install":"license",E.outdated?Os:xs(E.reason))),h.stop(E.message,2);let D=l.aiAgent==="codex"?".codex/config.toml":".mcp.json";a.detail(`Your .env / ${D} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await An(X(n,"clients"),{recursive:!0});let k=await Zi(n);x&&(await An(X(n,Ce),{recursive:!0}),await wn(Qn(n),`${new Date().toISOString()}
114
- `,"utf-8")),await Ne(n,Wi(Jn,k)),a.success("Wrote .klaudius/manifest.json");try{await cn(n,n,Object.keys(k))}catch{}}let I=!1,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 h=v.spinner();h.start("Applying schema to Supabase");let f=await lt({projectRoot:n,pat:l.supabasePat,projectRef:l.supabaseProjectRef,url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(f.ok&&f.tokenRefused){let k=f.tokenRefused;h.stop("Tables already in place"),a.warn(`Supabase refused the access token (HTTP ${k}), but every table and column is already in the database, so setup carries on.`),a.detail(ct(k)),a.detail(dt(l.supabaseProjectRef))}else f.ok?h.stop("Schema applied (or already present)"):(h.stop(f.message??"Schema apply failed",2),I=!0,L=f.message?.trim()||"the database refused the request",$=`https://supabase.com/dashboard/project/${l.supabaseProjectRef}/sql/new`)}let _=[],C={};if(e.skipInstall)a.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{a.blank(),a.heading("Installing dependencies");let h=await mn(n);if(a.detail(`npm: ${h.npm}, pip: ${h.pip}, playwright: ${h.playwright}, patchright: ${h.patchright}`),h.npm==="failed"&&_.push("npm"),h.pip==="failed"&&_.push("pip"),h.playwright==="failed"&&_.push("playwright"),h.patchright==="failed"&&_.push("patchright"),C=h.hints??{},h.npm!=="failed"&&h.playwright!=="failed"){a.step("Checking the QA screenshot chain (serving a test page and screenshotting it)\u2026");let f=await yn(n);f.ok?a.success("QA screenshot chain verified (local page served and screenshotted)."):(a.warn(`QA screenshot chain check failed${f.stage?` (${f.stage})`:""}: ${f.detail??"unknown"}`),f.remediation&&a.detail(f.remediation))}}let M=l.outreachEnabled&&l.outreachPriority?.includes("whatsapp")&&(l.whatsappAccounts?.length??0)>0,G=!e.skipInstall&&!_.includes("npm"),U=(l.whatsappAccounts??[]).filter(h=>!(o&&Ha(h)));if(M&&G&&U.length>0){a.blank(),a.heading("Linking WhatsApp accounts"),console.log(A.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
115
- phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
116
- Link a Device, and point it at the QR shown in this terminal.`)),a.blank();for(let h of U){console.log(A.cyan(`Pairing WhatsApp account '${h}'...`)),x||console.log(A.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${h})`));let f=Zn(process.execPath,["scripts/whatsapp.mjs","pair","--account",h],{cwd:n,stdio:"inherit"});f.status===0?a.detail(`Paired '${h}'.`):(console.log(A.yellow(`'${h}' did not pair (exit ${f.status??"signalled"}).`+(x?"":" You can finish later via:"))),x||console.log(A.cyan(` npx klaudius@latest pair-whatsapp --label ${h}`))),a.blank()}}else if(M&&!G&&(a.blank(),console.log(A.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),!x)){console.log(A.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let h of l.whatsappAccounts)console.log(A.cyan(` npx klaudius@latest pair-whatsapp --label ${h}`))}let O=l.emailAuth==="oauth-microsoft"&&l.outreachEnabled&&l.outreachChannels?.includes("email"),R=!e.skipInstall&&!_.includes("pip"),Y=o&&await sn(n,l.emailAddress??""),re=h=>{console.log(A.dim("Connect it any time from the project folder with:")),console.log(A.cyan(` ${h?h.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(A.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(O&&Y)a.blank(),a.detail("Your Outlook mailbox is already connected \u2014 leaving that sign-in alone.");else if(O&&R){a.blank(),a.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(A.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
117
- password. Your browser will open to Microsoft's sign-in page \u2014
118
- sign in as `+(l.emailAddress??"your outreach mailbox")+` and approve.
119
- (No browser on this machine? It falls back to a short code you can
120
- enter from any device.)`)),a.blank();let h=await Q();if(h){let[f,...k]=h.command,E=Zn(f,[...k,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});E.status===0?(a.success("Outlook mailbox connected."),x&&await on(n,l.emailAddress??"")):(a.blank(),console.log(A.yellow(`The Microsoft sign-in didn't complete (exit ${E.status??"signalled"}). Setup continues without it.`)),re(h))}else console.log(A.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),re(null)}else O&&!R&&(a.blank(),console.log(A.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),x||(console.log(A.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(A.cyan(" python3 scripts/ms_oauth.py login"))));a.blank();let z=[..._,...I?["schema"]:[]];if(z.length>0){v.outro(A.yellow(A.bold(`Setup paused \u2014 ${z.join(", ")} failed.`))),console.log(A.dim("Your credentials and project files are all saved.")),a.blank();for(let[N,ie]of Object.entries(C))console.log(A.yellow(`Likely cause of ${N} failure:`)),console.log(A.dim(` ${ie}`)),a.blank();if(x){let N=[];I&&(N.push(`Couldn't create the database tables: ${L.replace(/[:.\s]+$/,"")}. Check the database access token on the Database step.`),N.push(`If the token keeps being refused, open ${$}, paste in the contents of scripts/schema.sql from your project folder, and click Run.`));let ie=_.filter(ae=>ae==="playwright"||ae==="patchright"),_e=_.filter(ae=>ae!=="playwright"&&ae!=="patchright");_e.length>0&&N.push(`Couldn't finish installing ${_e.join(", ")}. The install output says why.`),ie.length>0&&N.push("Couldn't download the browsers Klaudius uses to gather business details, check the sites it builds and make invoices. The install output says why. If your network blocks large downloads, a different network, such as a phone hotspot, often gets past it."),T&&N.push("Email outreach was parked during setup \u2014 the mailbox credentials didn't pass their check. Your details are saved, so it can be picked up once the rest is through."),N.push("Then try again \u2014 setup carries on from here. If it keeps failing, email hello@klaudius.dev with the last few lines."),S(I&&_.length===0?"supabase":"install",N.join(`
121
- `))}let h=n!==process.cwd()&&e.target?` ${A.cyan(`cd ${En(e.target)}`)}
122
- `:"",f=l.aiAgent==="codex"?"codex":"claude",k=l.aiAgent==="codex"?"Codex":"Claude Code",E=l.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";_.length>0&&(console.log(A.dim(`Easiest fix \u2014 let ${k} finish it for you:`)),a.blank(),h&&process.stdout.write(h),console.log(` ${A.cyan(f)} ${A.dim(`# open ${k} in this folder`)}`),console.log(A.dim(" Then paste:")),console.log(A.cyan(` "Finish my Klaudius install \u2014 ${_.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),a.blank(),console.log(A.dim(` (Don't have ${k} yet? Install with: \`${E}\`)`)),a.blank(),console.log(A.dim("Or do it yourself:")),a.blank(),h&&process.stdout.write(h),console.log(` ${A.cyan("npx klaudius@latest install")} ${A.dim("# retry the failing installers")}`),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# verify everything")}`),a.blank()),I&&(console.log(A.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${A.cyan($)}`),console.log(A.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),a.blank()),_.includes("pip")&&!C.pip&&(console.log(A.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(A.dim(`Python 3.10+. Install a newer one from ${Wa()}`)),console.log(A.dim("and open a fresh Terminal before retrying.")),a.blank());let b=["npm","playwright","patchright"].filter(N=>_.includes(N)&&!C[N]);if(b.length>0){let N=b.length===1?"keeps":"keep";console.log(A.dim(`If ${b.join(" / ")} ${N} failing with network errors (ECONNRESET,`)),console.log(A.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(A.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),a.blank()}T&&(console.log(A.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${k}`)),console.log(A.dim("to finish setting it up \u2014 your email details are saved in .env.")),a.blank()),console.log(A.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),a.blank();return}if(await vs(Qn(n),{force:!0}),await vs(nn(n),{force:!0}),qa(l,n,e.target),T){let h=l.aiAgent==="codex"?"Codex":"Claude Code";console.log(A.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(A.dim(`Your details are saved in .env. To finish it, ask ${h}:`)),console.log(A.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(A.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(A.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(A.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(A.cyan(' and send a test email to my own address to confirm."')),l.outreachEnabled&&(l.outreachChannels??[]).length>0&&(a.blank(),console.log(A.yellow(`Note: your other channel(s) \u2014 ${(l.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),a.blank()}}async function q(e,t){await An(e,{recursive:!0}),await wn(X(e,".env"),it(t),"utf-8"),t.aiAgent==="codex"?(await An(X(e,".codex"),{recursive:!0}),await wn(X(e,".codex","config.toml"),ot(t),"utf-8")):(await wn(X(e,".mcp.json"),st(t),"utf-8"),await ht(e,"supabase"),await Ke(e,je))}async function Ka(e){try{(await Xn(e)).isDirectory()||(x&&S("folder","There's already a file with that name. Choose a different folder name."),a.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Ls(e),n=t.filter(d=>!d.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),s=n.every(d=>i.has(d)),o=n.includes(".env"),r=t.includes(".klaudius");if(s&&o&&!r)return{kind:"partial",envPath:X(e,".env")};if(r&&o){let d=!0;try{d=!(await Xn(X(e,"node_modules"))).isDirectory()}catch{d=!0}return{kind:"scaffolded",nodeModulesMissing:d}}return{kind:"occupied",entries:n}}async function Ga(e){a.blank(),a.warn(`Found a partial setup at ${A.bold(e)}.`),a.detail(`A previous init wrote ${A.bold(".env")} but didn't finish scaffolding.`),a.blank();let t=await v.select({message:`How would you like to proceed? ${A.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return v.isCancel(t)&&(v.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Ba(e){if(e&&e.trim().length>0)return e;v.intro("Klaudius");let t=await v.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return v.isCancel(t)&&(v.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Va(e){let t=Ua(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 Ya(){if(process.platform!=="win32")return!1;try{return Zn("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Wa(){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 qa(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",s=e.aiAgent==="codex"?"Codex":"Claude Code";if(v.outro(A.green(A.bold("Project ready."))),e.aiPlan){let o=(e.qaPhase??Te(e.aiPlan))==="off";console.log(`${A.bold("Your plan:")} ${Pt[e.aiPlan]}`),console.log(A.dim(o?" \u2192 QA pass off, so each run fits your usage window.":" \u2192 full pipeline, including the independent QA pass after every build.")),console.log(A.dim(` Change it any time: ask ${s} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),a.blank()}if(console.log(A.bold("Next steps:")),a.blank(),t!==process.cwd()&&n){let o=`cd ${En(n)}`;console.log(` ${A.cyan(o)}${" ".repeat(Math.max(1,27-o.length))}${A.dim("# go into your project folder")}`)}console.log(` ${A.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${A.dim(`# opens ${s} in this project`)}`),a.blank(),console.log(A.bold(`Some starter prompts for ${s}:`)),a.blank(),console.log(` ${A.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${A.cyan(`I know I'm ready to start using Klaudius."`)}`),a.blank(),x||(console.log(` ${A.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),a.blank()),console.log(` ${A.cyan('"Run the pipeline for one client."')}`),console.log(A.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),a.blank(),e.aiAgent!=="codex"&&(console.log(A.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(A.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),a.blank())}import{access as za,readFile as Ja}from"fs/promises";import{join as ti,resolve as Qa}from"path";import le from"picocolors";async function Ds(e){let t=e.target?Qa(process.cwd(),e.target):process.cwd(),n=await Ms(ti(t,".env")),i=await Ms(ti(t,"package.json"));(!n||!i)&&(a.error("This doesn't look like a Klaudius project."),a.detail(`Path: ${t}`),n||a.detail("Missing: .env"),i||a.detail("Missing: package.json"),a.blank(),a.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),a.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let s="claude-code";try{J(await Ja(ti(t,".env"),"utf-8")).AI_AGENT==="codex"&&(s="codex")}catch{}a.heading("Installing dependencies");let o=await mn(t);a.blank(),a.detail(`npm: ${o.npm}, pip: ${o.pip}, playwright: ${o.playwright}, patchright: ${o.patchright}`);let r=[];if(o.npm==="failed"&&r.push("npm"),o.pip==="failed"&&r.push("pip"),o.playwright==="failed"&&r.push("playwright"),o.patchright==="failed"&&r.push("patchright"),r.length===0){a.blank(),console.log(le.green(le.bold("All dependencies installed."))),console.log(le.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),a.blank();return}a.blank(),console.log(le.yellow(le.bold(`${r.join(", ")} still failing.`))),a.blank();for(let[u,g]of Object.entries(o.hints??{}))console.log(le.yellow(`Likely cause of ${u} failure:`)),console.log(le.dim(` ${g}`)),a.blank();let d=s==="codex"?"codex":"claude",c=s==="codex"?"Codex":"Claude Code",p=s==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(le.dim("Options:")),console.log(le.dim(` \u2022 Open ${c} in this folder (\`${d}\`) and paste:`)),console.log(le.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(le.dim(` (Don't have ${c} yet? Install with: \`${p}\`)`)),console.log(le.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(le.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),a.blank(),process.exitCode=1}async function Ms(e){try{return await za(e),!0}catch{return!1}}import{readFile as gl,writeFile as ni,access as yl}from"fs/promises";import{join as kt}from"path";import*as ce from"@clack/prompts";import xe from"picocolors";import{mkdir as Ks,copyFile as Gs,readdir as Za,readFile as Bs,rm as Ys}from"fs/promises";import{spawnSync as el}from"child_process";import{join as ge}from"path";var Hs=/^(#\s*)?([A-Za-z_][A-Za-z0-9_]*)=/,Fs=/^#\s*[A-Za-z_][A-Za-z0-9_]*=\s*$/;function Xa(e,t){let n=new Map,i=new Map,s=[];for(let o of e.split(`
123
- `)){let r=o.replace(/\r$/,""),d=Hs.exec(r.trim());if(d){let c=d[2];if(d[1]){!Fs.test(r.trim())&&!t.has(r)&&s.push(r);continue}n.set(c,r),s.length>0&&(i.set(c,[...i.get(c)??[],...s]),s=[]);continue}r.trim().startsWith("#")&&(t.has(r)||Fs.test(r.trim())||s.push(r))}return{lines:n,comments:i,trailing:s}}function Us(e){let t=e.trim();if(t.startsWith("#"))return;let n=t.indexOf("=");return n===-1?void 0:Fn(t.slice(n+1).trim())}function js(e,t,n){let i=e.split(`
124
- `),s=Xa(t,new Set(i)),o=[],r=new Set;for(let c of i){let u=Hs.exec(c.trim())?.[2];if(u===void 0||r.has(u)){o.push(c);continue}r.add(u);for(let w of s.comments.get(u)??[])o.push(w);let g=s.lines.get(u),m=g!==void 0&&Us(g)!==Us(c);o.push(m&&!n.has(u)?g:c)}let d=[...s.trailing,...[...s.comments].filter(([c])=>!r.has(c)).flatMap(([,c])=>c)];return d.length>0&&(o[o.length-1]?.trim()!==""&&o.push(""),o.push(...d),o.push("")),o.join(`
125
- `)}var yt=["supabase","vercel","cloudflare","netlify","selfhost","google-places","email","sms","letter","notifications"],Ws={supabase:["SUPABASE_URL","SUPABASE_SERVICE_KEY","SUPABASE_ANON_KEY","SUPABASE_PAT","SUPABASE_PROJECT_REF"],vercel:["VERCEL_TOKEN","VERCEL_SCOPE"],cloudflare:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID"],netlify:["NETLIFY_AUTH_TOKEN","NETLIFY_ACCOUNT_SLUG"],selfhost:["SELFHOST_DEPLOY_TARGET","SELFHOST_URL_TEMPLATE"],"google-places":["GOOGLE_PLACES_API_KEY"],email:["EMAIL_PROVIDER","EMAIL_AUTH","EMAIL_ADDRESS","EMAIL_LOGIN","EMAIL_PASSWORD","EMAIL_FROM_NAME","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT","EMAIL_SENT_FOLDER","EMAIL_INBOX_FOLDER","EMAIL_DRAFTS_FOLDER"],sms:["SMS_PROVIDER","TEST_PHONE","TWILIO_ACCOUNT_SID","TWILIO_AUTH_TOKEN","TWILIO_PHONE_NUMBER"],letter:["LETTER_PROVIDER","PINGEN_CLIENT_ID","PINGEN_CLIENT_SECRET","PINGEN_ORG_ID","POSTGRID_API_KEY"],notifications:["NOTIFY_CHANNEL","NOTIFY_TO","TELEGRAM_BOT_TOKEN","TELEGRAM_CHAT_ID"]},Vs={email:"email",sms:"sms",letter:"letter"};function tl(e,t){let n=new Set,i=(p,u)=>p==="LETTER_PROVIDER"&&u.trim()===bt?"":u,s=p=>p in e&&i(p,e[p]??"")!==i(p,t[p]??"");for(let p of yt)Ws[p].some(s)&&n.add(p);if(s("DEPLOY_PROVIDER")){let p=(e.DEPLOY_PROVIDER??"").trim();p==="cloudflare"||p==="netlify"||p==="selfhost"?n.add(p):n.add("vercel")}let o=(p,u)=>(p[u]??"").split(",").map(g=>g.trim().toLowerCase()).filter(Boolean),r=(e.OUTREACH_ENABLED??"").toLowerCase()==="true",d=(t.OUTREACH_ENABLED??"").toLowerCase()==="true",c="OUTREACH_ENABLED"in e&&r&&!d;for(let p of["OUTREACH_CHANNELS","OUTREACH_PRIORITY"]){if(c){for(let g of o(p in e?e:t,p)){let m=Vs[g];m&&n.add(m)}continue}if(!(p in e))continue;let u=o(t,p);for(let g of o(e,p)){if(u.includes(g))continue;let m=Vs[g];m&&n.add(m)}}return yt.filter(p=>n.has(p))}async function qs(e){let{projectRoot:t}=e,n=ge(t,".env"),i=await Bs(n,"utf-8").catch(()=>null);i===null&&S("folder","There's no Klaudius install in this folder to reconfigure \u2014 it has no .env. Pick the folder your install is in, or set one up fresh.");let s=J(i),o=Ae();o.ok||S("install",o.message??"Node.js version check failed.");let r=await Jt(e.answers);zt(r);let d="OUTREACH_CHANNELS"in r;d&&zs(r.OUTREACH_CHANNELS,s.OUTREACH_CHANNELS)&&delete r.OUTREACH_CHANNELS;let c={...s,...r},p=rt(c);p||dl(ll(c));let u=s.AI_AGENT==="codex"?"codex":"claude-code",g=p.aiAgent??"claude-code";if(g!==u){let O=R=>R==="codex"?"Codex":"Claude Code";S("folder",`This install was set up for ${O(u)}, so it can't be reconfigured as ${O(g)}. Set up a new folder for the other assistant, or switch back. Nothing has been changed.`)}let m=sl(p,r,s,c,d),w=tl(r,s),l=fl(e.sections)??new Set(w),P=p.supabaseProjectRef!==(s.SUPABASE_PROJECT_REF??"");if(P&&l.add("supabase"),"SUPABASE_URL"in r||"SUPABASE_PROJECT_REF"in r){let O=ol(p.supabaseUrl??"");O&&O!==(p.supabaseProjectRef??"").trim().toLowerCase()&&S("supabase",`The database URL is for project "${O}", but the project reference says "${p.supabaseProjectRef}". They always name the same project, so one of the two is a typo. Nothing has been changed.`)}let{checked:T,rewritten:I}=await ml(p,s,O=>l.has(O));for(let O of m)I.add(O);for(let O of Object.keys(r))I.add(O);for(let O of rl(p,c))I.add(O);if(P){a.step("Setting up the tables in the new database");let O=await lt({projectRoot:t,pat:p.supabasePat,projectRef:p.supabaseProjectRef,url:p.supabaseUrl,serviceKey:p.supabaseServiceKey});O.ok||S("supabase",`${O.message??"The database wouldn't take the pipeline's tables."}
126
- If the token keeps being refused, open ${Ot(p.supabaseProjectRef)}, paste in the contents of scripts/schema.sql from your project folder, and click Run. Then try again.`),a.success("Database tables in place"),O.tokenRefused&&(a.warn(`Supabase refused the access token (HTTP ${O.tokenRefused}), but the tables were already in the new database.`),a.detail(ct(O.tokenRefused)),a.detail(dt(p.supabaseProjectRef)))}let L=ge(t,Ce,"backup"),$=ge(Ce,"backup",`configure-${new Date().toISOString().replace(/[:.]/g,"-")}`),_=ge(t,$,".env.bak");await Ks(ge(t,$),{recursive:!0}),await Gs(n,_),await il(L),await Ee(n,js(it(p),i,I)),a.success("Updated .env"),a.detail(`Previous .env saved as ${ge($,".env.bak")}`);let C=p.aiAgent==="codex"?ge(t,".codex","config.toml"):ge(t,".mcp.json"),M=await Bs(C,"utf-8").catch(()=>null);try{p.aiAgent==="codex"?(await Ks(ge(t,".codex"),{recursive:!0}),await Ee(C,ot(p)),a.success("Updated .codex/config.toml")):(await Ee(C,st(p)),a.success("Updated .mcp.json"))}catch(O){M===null?await Ys(C,{force:!0}).catch(()=>{}):await Ee(C,M).catch(()=>{});let R=await Gs(_,n).then(()=>!0,()=>!1);throw a.warn(al(R,ge($,".env.bak"))),O}p.aiAgent!=="codex"&&(await ht(t,"supabase").catch(O=>{a.warn(`Couldn't pre-approve the database connection in .claude/settings.json (${O instanceof Error?O.message:String(O)}). Until that file can be written, the database connection may not be available to Claude Code. Your settings are saved.`)}),await Ke(t,je));let G=l.has("email")||"EMAIL_ADDRESS"in r||"EMAIL_AUTH"in r;await hl(t,p,G);let U=yt.filter(O=>T.has(O));console.log(`CONFIGURE-DONE sections=${w.join(",")} checked=${U.join(",")}`)}var nl=5;async function il(e){let t=(await Za(e).catch(()=>[])).filter(n=>n.startsWith("configure-")).sort();for(let n of t.slice(0,Math.max(0,t.length-nl)))await Ys(ge(e,n),{recursive:!0,force:!0}).catch(()=>{})}function sl(e,t,n,i,s){let o=new Set;if("AI_PLAN"in t&&!("QA_PHASE"in t)&&(e.qaPhase=Te(e.aiPlan),o.add("QA_PHASE")),("PRICING"in t||"PRICING_MONTHLY"in t)&&!("PRICING_TERMS"in t)){Un(e,i.PRICING,i.PRICING_MONTHLY);for(let m of["PRICING","PRICING_MONTHLY","PRICING_TERMS"])o.add(m)}let r=Ie(n),d="EMAIL_PROVIDER"in t||!("EMAIL_SMTP_HOST"in t)?Ie(i):Ie({...i,EMAIL_PROVIDER:""});if(d&&d!=="custom"&&d!==r){let m=te[d];"EMAIL_PROVIDER"in t||(e.emailProvider=d,o.add("EMAIL_PROVIDER"));let w=[{smtpHost:m.smtpHost,imapHost:m.imapHost},...m.altHostSets??[]],y=T=>(t[T]??"").trim().toLowerCase(),l=w.find(T=>T.smtpHost===y("EMAIL_SMTP_HOST")||T.imapHost===y("EMAIL_IMAP_HOST"))??w[0],P=[["EMAIL_SMTP_HOST",()=>e.emailSmtpHost=l.smtpHost],["EMAIL_SMTP_PORT",()=>e.emailSmtpPort=m.smtpPort],["EMAIL_IMAP_HOST",()=>e.emailImapHost=l.imapHost],["EMAIL_IMAP_PORT",()=>e.emailImapPort=m.imapPort],...Hn(d).map(([T,I,L])=>[T,()=>e[I]=L])];for(let[T,I]of P)T in t||(I(),o.add(T))}let c=m=>(m??"").split(",").map(w=>w.trim().toLowerCase()).filter(Boolean),p=s,u="OUTREACH_PRIORITY"in t,g=p?"OUTREACH_CHANNELS":"OUTREACH_PRIORITY";if(p!==u&&!zs(i[g],n[g])){let m=c(i[g]),w=c(n[p?"OUTREACH_PRIORITY":"OUTREACH_CHANNELS"]),l=[...w.filter(P=>m.includes(P)),...m.filter(P=>!w.includes(P))];p?(e.outreachPriority=l,o.add("OUTREACH_PRIORITY")):(e.outreachChannels=l,o.add("OUTREACH_CHANNELS"))}return o}function zs(e,t){let n=o=>[...new Set((o??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean))].sort(),i=n(e),s=n(t);return i.length===s.length&&i.every((o,r)=>o===s[r])}function ol(e){return e.trim().match(/^https:\/\/([a-z0-9]+)\.supabase\.co(?=[:/]|$)/i)?.[1]?.toLowerCase()}function rl(e,t){return[["SUPABASE_SERVICE_KEY",e.supabaseServiceKey],["SUPABASE_PAT",e.supabasePat]].filter(([i,s])=>(t[i]??"")!==(s??"")).map(([i])=>i)}function al(e,t){return e?"Couldn't finish writing the settings \u2014 your previous .env has been put back.":`Couldn't finish writing the settings, and couldn't put your previous .env back either. Your previous settings are in ${t}.`}function ll(e){let t=e.DEPLOY_PROVIDER?.trim()||"vercel";return["SUPABASE_URL","SUPABASE_SERVICE_KEY","SUPABASE_PAT","SUPABASE_PROJECT_REF",...t==="cloudflare"?["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID"]:t==="netlify"?["NETLIFY_AUTH_TOKEN"]:t==="selfhost"?["SELFHOST_DEPLOY_TARGET","SELFHOST_URL_TEMPLATE"]:["VERCEL_TOKEN"],"PRICING"].filter(i=>!(e[i]??"").trim())}var cl={SUPABASE_URL:"the database URL",SUPABASE_SERVICE_KEY:"the database secret key",SUPABASE_PAT:"the database access token",SUPABASE_PROJECT_REF:"the database project reference",VERCEL_TOKEN:"the Vercel token",CLOUDFLARE_API_TOKEN:"the Cloudflare API token",CLOUDFLARE_ACCOUNT_ID:"the Cloudflare account ID",NETLIFY_AUTH_TOKEN:"the Netlify token",SELFHOST_DEPLOY_TARGET:"the server to deploy to",SELFHOST_URL_TEMPLATE:"the web address your sites are published at",PRICING:"the price you charge"};function dl(e){let t=e.map(s=>cl[s]??s),n=t.length===0?"Some of this install's settings are missing, so there's nothing to change yet. Set the install up again from this folder.":`This install has no ${pl(t)} any more, so it can't be changed until that's back. Fill ${t.length===1?"it":"them"} in, and nothing else changes.`;switch(e[0]===void 0?void 0:ul(e[0])){case"supabase":S("supabase",n);case"vercel":S("vercel",n);case"cloudflare":S("cloudflare",n);case"netlify":S("netlify",n);case"selfhost":S("selfhost",n);default:S("answers",n)}}function ul(e){return yt.find(t=>Ws[t].includes(e))}function pl(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function fl(e){if(e===void 0)return null;let t=e.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),n=new Set(yt),i=t.filter(s=>!n.has(s));return i.length>0&&S("answers",`Not a section that can be checked: ${i.join(", ")}. The sections are: ${yt.join(", ")}.`),new Set(t)}async function ml(e,t,n){let i=new Set,s=new Set,o=e.outreachChannels??[],r=c=>!!e.outreachEnabled&&o.includes(c);if(n("supabase")&&e.supabaseUrl&&e.supabaseServiceKey){a.step("Checking the database credentials");let c=await Me({url:e.supabaseUrl,serviceKey:e.supabaseServiceKey});c.ok||S("supabase",c.message??"Supabase check failed"),i.add("supabase"),a.success("Database credentials accepted")}let d=e.deployProvider??"vercel";if(d==="vercel"&&n("vercel")&&e.vercelToken){a.step("Checking the Vercel token");let c=await De(e.vercelToken);if(!c.ok){let p=c.kind==="rejected"||c.kind==="scope";S("vercel",p?`${c.message} Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration).`:c.message)}i.add("vercel"),a.success(c.username?`Vercel token accepted (signed in as ${c.username})`:"Vercel token accepted")}else if(d==="cloudflare"&&n("cloudflare")&&e.cloudflareApiToken&&e.cloudflareAccountId){a.step("Checking the Cloudflare token + account");let c=await Fe({token:e.cloudflareApiToken,accountId:e.cloudflareAccountId});c.ok||S("cloudflare",c.message??"Cloudflare check failed"),i.add("cloudflare"),a.success("Cloudflare credentials accepted")}else if(d==="netlify"&&n("netlify")&&e.netlifyAuthToken){a.step("Checking the Netlify token");let c=await Ue({token:e.netlifyAuthToken});c.ok||S("netlify",c.message??"Netlify check failed"),i.add("netlify"),a.success(c.accountSlug?`Netlify token accepted (team: ${c.accountSlug})`:"Netlify token accepted")}else if(d==="selfhost"&&n("selfhost")){let c=Qe(e.selfhostDeployTarget??""),p=Xe(e.selfhostUrlTemplate??"");(c||p)&&S("selfhost",[c&&`SELFHOST_DEPLOY_TARGET: ${c}`,p&&`SELFHOST_URL_TEMPLATE: ${p}`].filter(Boolean).join(`
127
- `)),i.add("selfhost"),a.success("Self-host deploy settings accepted (SSH reachability is tested at your first deploy)")}if(n("google-places")&&e.googlePlacesApiKey){a.step("Checking the Google Places API key");let c=we(e.googlePlacesApiKey),p=await He(e.googlePlacesApiKey);if(p.ok||S("google-places",p.message??"Google Places check failed"),c.changed){e.googlePlacesApiKey=c.value,s.add("GOOGLE_PLACES_API_KEY");for(let u of c.repairs)a.detail(`Corrected a look-alike character: ${u}`)}i.add("google-places"),a.success("Google Places API key accepted")}if(n("email")&&r("email")&&e.emailAuth!=="oauth-microsoft"){let c=[["email address",e.emailAddress],["password",e.emailPassword],["SMTP host",e.emailSmtpHost],["IMAP host",e.emailImapHost]].filter(([,w])=>!w).map(([w])=>w),p=[["SMTP port",e.emailSmtpPort],["IMAP port",e.emailImapPort]].filter(([,w])=>!w).map(([w])=>w),u=[...c.length>0?[`the ${c.join(", ")} ${c.length===1?"is":"are"} missing`]:[],...p.length>0?[`the ${p.join(" and ")} ${p.length===1?"isn't a number":"aren't numbers"}`]:[]];u.length>0&&S("email",`Email outreach is switched on, but ${u.join(", and ")}. Fill ${u.length===1&&c.length+p.length===1?"it":"them"} in, or turn email off.`),a.step("Checking the email credentials (SMTP + IMAP)");let g=e.emailProvider&&e.emailProvider!=="custom"?e.emailProvider:pe(e.emailSmtpHost),m=await me({emailAddress:e.emailAddress,emailLogin:e.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:e.emailPassword,emailSmtpHost:e.emailSmtpHost,emailSmtpPort:e.emailSmtpPort,emailImapHost:e.emailImapHost,emailImapPort:e.emailImapPort,usesAccountPassword:g?te[g].usesAccountPassword:void 0,knownProvider:!!g,errorHint:{form:!0},sentFolder:(e.emailSentFolder??"").trim()||"Sent",draftsFolder:(e.emailDraftsFolder??"").trim()||"Drafts"});m.ok||S("email",m.message??"Email check failed"),i.add("email"),a.success("Email credentials accepted (SMTP + IMAP)"),await ut(m,e,{nonInteractive:!0})&&(s.add("EMAIL_SENT_FOLDER"),s.add("EMAIL_DRAFTS_FOLDER"))}if(n("sms")&&r("sms")){let c=Qt(e,t);if(c&&S("sms",c),e.smsProvider==="twilio"){a.step("Checking the Twilio credentials");let p=await pn({accountSid:e.twilioAccountSid,authToken:e.twilioAuthToken});p.ok||S("sms",p.message??"Twilio check failed"),i.add("sms"),a.success(p.friendlyName?`Twilio credentials accepted (${p.friendlyName})`:"Twilio credentials accepted")}}if(n("letter")&&r("letter")){let c=Xt(e,t);c&&S("letter",c),a.step("Checking the letter provider credentials");let p=await pt({provider:e.letterProvider,pingenClientId:e.pingenClientId,pingenClientSecret:e.pingenClientSecret,pingenOrgId:e.pingenOrgId,postgridApiKey:e.postgridApiKey});p.ok||S("letter",p.message??"Letter provider check failed"),i.add("letter"),a.success("Letter provider credentials accepted")}if(n("notifications")){let c=e.notifyChannel,p=Zt(e,t);if(p&&S("notifications",p),(c??"telegram")==="telegram"&&e.telegramBotToken&&e.telegramChatId){a.step("Checking the Telegram bot + chat (sending a test message)");let u=await Kt({botToken:e.telegramBotToken,chatId:e.telegramChatId});u.ok||S("notifications",u.message??"Telegram check failed"),i.add("notifications"),a.success(u.botHandle?`Telegram bot ${u.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered")}}return{checked:i,rewritten:s}}async function hl(e,t,n){if(t.emailAuth!=="oauth-microsoft"||!n||await sn(e,t.emailAddress??""))return;let i=await Q();if(!i){a.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in.");return}let[s,...o]=i.command;a.step("Connecting your Outlook / Microsoft 365 mailbox (one-time browser sign-in)"),el(s,[...o,"-u","scripts/ms_oauth.py","login"],{cwd:e,stdio:"inherit",timeout:39e5}).status===0?(await on(e,t.emailAddress??""),a.success("Outlook mailbox connected.")):a.warn("The Microsoft sign-in didn't complete. Your settings are saved.")}import{mkdir as kl}from"fs/promises";import{spawnSync as Js}from"child_process";async function Qs(e){let t=e.projectRoot??process.cwd();if(e.answers){await qs({projectRoot:t,answers:e.answers,sections:e.sections});return}e.sections&&S("answers","The sections to check were given without the new settings to check them against, so there is nothing to reconfigure.");let n=kt(t,".env"),i=kt(t,".mcp.json"),s=kt(t,".codex","config.toml"),o=await ii(kt(t,".klaudius","manifest.json")),r=await ii(n);!o&&!r&&(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let d=Ae();d.ok||(a.error(d.message??"Node.js version check failed."),a.blank(),a.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let c={};try{let y=await gl(n,"utf-8");c=J(y)}catch{a.warn("No .env found. Starting from an empty configuration.")}let p=Hi(c);Object.keys(c).length>0&&(p.pipelineModes??=["classic"]),ce.intro("Reconfigure Klaudius"),a.detail("Press Enter on any prompt to keep its current value."),a.blank();let u=await W(p),g=p.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==g&&(a.error(`Switching AI coding agent (${g} \u2192 ${u.aiAgent}) isn't supported via configure.`),a.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),a.blank(),console.log(` ${xe.cyan("npx klaudius@latest init <new-folder>")} ${xe.dim("# pick the new agent in the wizard")}`),a.blank(),a.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){a.heading("Re-validating Supabase credentials");let y=await Me({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});y.ok||(a.error(y.message??"Supabase check failed"),a.warn("Aborting. .env not modified."),process.exit(1)),a.success("Supabase credentials accepted")}let m=Al(u,c);if(m==="vercel"){let y=ce.spinner();y.start("Validating Vercel token");let l=await De(u.vercelToken??"");l.ok?y.stop(l.username?`Vercel token accepted (signed in as ${l.username})`:"Vercel token accepted"):(y.stop(l.message,2),a.warn("Writing the token exactly as you entered it \u2014 not verified."),a.detail(l.kind==="rejected"||l.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then re-run `npx klaudius@latest configure`.":l.kind==="network"?"Couldn't reach Vercel \u2014 check your connection, then run `npx klaudius@latest doctor`.":"Vercel's API returned an error \u2014 try again shortly (status.vercel.com), then run `npx klaudius@latest doctor`."))}else if(m==="cloudflare"){let y=ce.spinner();y.start("Validating Cloudflare token + account");let l=await Fe({token:u.cloudflareApiToken??"",accountId:u.cloudflareAccountId??""});l.ok?y.stop("Cloudflare credentials accepted"):(y.stop(l.message??"Cloudflare check failed",2),a.warn("Writing the credentials exactly as you entered them \u2014 not verified."),a.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(m==="netlify"){let y=ce.spinner();y.start("Validating Netlify token");let l=await Ue({token:u.netlifyAuthToken??""});l.ok?y.stop(l.accountSlug?`Netlify token accepted (team: ${l.accountSlug})`:"Netlify token accepted"):(y.stop(l.message??"Netlify check failed",2),a.warn("Writing the token exactly as you entered it \u2014 not verified."),a.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let w=we(u.googlePlacesApiKey??"");if(w.changed&&u.googlePlacesApiKey){a.heading("Checking your Google Places API key");let y=await He(u.googlePlacesApiKey);if(y.ok){if(w.repairs.length>0){a.warn("Corrected look-alike characters in your Google Places API key:");for(let l of w.repairs)a.detail(` ${l}`);a.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=w.value,a.success("Google accepted the key \u2014 writing the corrected value to .env")}else a.error(y.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(wl(u,c)){let y=ce.spinner();y.start("Validating email credentials (SMTP + IMAP)");let l=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:pe(u.emailSmtpHost),P=await me({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:l?te[l].usesAccountPassword:void 0,knownProvider:!!l,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});P.ok?(y.stop("Email credentials accepted (SMTP + IMAP)"),await ut(P,u,{nonInteractive:!1,onCancel:()=>a.detail("Left the folder names as they are.")})):(y.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 ni(n,it(u),"utf-8"),a.success("Updated .env"),u.aiAgent==="codex"?(await kl(kt(t,".codex"),{recursive:!0}),await ni(s,ot(u),"utf-8"),a.success("Updated .codex/config.toml")):(await ni(i,st(u),"utf-8"),a.success("Updated .mcp.json"),await ht(t,"supabase"),await Ke(t,je)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let y=await Q();if(!(y!==null&&Js(y.command[0],[...y.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(a.blank(),!y)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 ce.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});ce.isCancel(P)||!P?a.detail(`Skipped. Connect it any time with: ${y.command.join(" ")} scripts/ms_oauth.py login`):Js(y.command[0],[...y.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: ${y.command.join(" ")} scripts/ms_oauth.py login`))}}a.blank(),ce.outro(xe.green("Configuration updated.")),await El(t,o)}function wl(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 Al(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 El(e,t){let n=await ii(kt(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(` ${xe.cyan("npx klaudius@latest install")} ${xe.dim("# (re-)installs npm + pip + browsers; idempotent")}`),a.blank(),a.detail("Then verify with:"),a.blank(),console.log(` ${xe.cyan("npx klaudius@latest doctor")} ${xe.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(` ${xe.cyan("npx klaudius@latest init")} ${xe.dim("# pick Resume when prompted")}`),a.blank())}async function ii(e){try{return await yl(e),!0}catch{return!1}}import{copyFile as ui,mkdir as Sn,readFile as Mt,rm as Se,writeFile as bn,access as pi}from"fs/promises";import{dirname as _n,join as F}from"path";import{tmpdir as Yl}from"os";import*as Ge from"@clack/prompts";import Dt from"picocolors";import{execFile as ci}from"child_process";import{createHash as Pl}from"crypto";import{access as Sl,copyFile as oo,lstat as bl,mkdir as ri,mkdtemp as ro,open as _l,readFile as se,realpath as Tl,rm as At,stat as ao,unlink as Il,writeFile as Nt}from"fs/promises";import{tmpdir as lo}from"os";import{dirname as ze,isAbsolute as si,join as K,relative as Xs,resolve as Lt}from"path";var ai={"Edit conflict":["keep-mine","take-new","check-merge","merge","auto-merge"],"Deleted locally":["restore","keep-deleted"],"Removed upstream":["keep-mine","delete"]},li=K(".klaudius","conflicts.md"),di=K(".klaudius","incoming"),Cl=K(".klaudius","resolve.lock"),$t=K(".klaudius","merged"),Rl=12e4,vl=3e4,Ol=[["keepMine","keep-mine"],["takeNew","take-new"],["checkMerge","check-merge"],["merge","merge"],["autoMerge","auto-merge"],["restore","restore"],["keepDeleted","keep-deleted"],["delete","delete"]];function co(e,t){let n=Ol.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 xl(e){let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return`.klaudius/merged/draft${n>0?t.slice(n):""}`}function Zs(e,t,n,i){if(/^(<<<<<<<|>>>>>>>)/m.test(t))return"still has conflict markers (<<<<<<< or >>>>>>>): finish the merge first";if(!e.toLowerCase().endsWith(".json")||n===null||i===null)return null;let s=r=>{try{return JSON.parse(r.replace(/^/,"")),null}catch(d){return d.message}};if(s(n)!==null||s(i)!==null)return null;let o=s(t);return o===null?null:`isn't valid JSON (${o})`}function oi(e){let t=[];for(let n=0;n<e.length;n++){let i=e[n];if(i==='"'){let s=n+1;for(;s<e.length&&e[s]!=='"';)s+=e[s]==="\\"?2:1;let o=s+1;for(;o<e.length&&/\s/.test(e[o]);)o++;let r=t[t.length-1];if(e[o]===":"&&r){let d=e.slice(n+1,s);if(r.has(d))return d;r.add(d)}n=s}else i==="{"?t.push(new Set):i==="["?t.push(null):(i==="}"||i==="]")&&t.pop()}return null}var Ll={".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 eo(e,t,n,i,s){let o=e.slice(e.lastIndexOf("/")+1),r=o.lastIndexOf("."),d=r>0?o.slice(r).toLowerCase():"";if(d===".json"){let m=y=>{try{return JSON.parse(y.replace(/^/,"")),!0}catch{return!1}};if(!m(n)||!m(i)||oi(n)!==null||oi(i)!==null)return null;let w=oi(t.toString());return w===null?null:`gives the key "${w}" twice`}let c=d===".js"?await Nl(s)==="module"?".mjs":".cjs":d,p=Ll[c];if(!p)return null;let u={...process.env,NO_COLOR:"1",PYTHON_COLORS:"0"};delete u.FORCE_COLOR;let g;try{g=await ro(K(lo(),"klaudius-check-"))}catch{return null}try{let m=async(y,l)=>{let P=K(g,`${l}${c}`);await Nt(P,y);let T=await Tl(P).catch(()=>P);return new Promise(I=>ci(p[0],[...p[1],P],{windowsHide:!0,timeout:1e4,env:u},(L,$,_)=>{if(!L||L.killed||L.signal||typeof L.code!="number")return I(null);let C=String(_).split(/\r?\n/).map(U=>U.split(T).join(e).split(P).join(e).trim()).filter(Boolean),M=C.find(U=>/^\w*Error\b|syntax error/i.test(U))??C[C.length-1]??L.message.split(`
128
- `)[0],G=C.find(U=>U.includes(e))?.match(/(?:line |:)(\d+)/)?.[1];I(G&&!/\bline \d+/.test(M)?`${M}, line ${G}`:M)}))};if(await m(n,"yours")!==null||await m(i,"new")!==null)return null;let w=await m(t,"merged");return w===null?null:`no longer parses (${w})`}catch{return null}finally{await At(g,{recursive:!0,force:!0}).catch(()=>{})}}async function Nl(e){for(let t=Lt(e);;t=ze(t)){let n=await se(K(t,"package.json"),"utf-8").catch(()=>null);if(n!==null)try{return JSON.parse(n).type??"commonjs"}catch{return"commonjs"}if(ze(t)===t)return"commonjs"}}function $l(e){let t=e.split(`
129
- `),n=[],i=!1;t.forEach((o,r)=>{o.startsWith("```")?i=!i:!i&&o.startsWith("## ")&&n.push({path:o.slice(3).trim(),start:r})});let s=n.map((o,r)=>{let d=r+1<n.length?n[r+1].start:t.length,p=t.slice(o.start,d).find(u=>u.startsWith("**Type:**"))?.slice(9).trim();return{...o,end:d,type:p!==void 0&&p in ai?p:null}});return{lines:t,sections:s}}function Ml(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(`
130
- `)}function Dl(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 wt=e=>Sl(e).then(()=>!0,()=>!1);async function Fl(e,t,n){let i=`${n}.bak`;for(let o=2;await wt(K(e,t,i));o++)i=`${n}.${o}.bak`;let s=K(e,t,i);return await ri(ze(s),{recursive:!0}),await oo(K(e,n),s),`${t}/${i}`}function Ul(e,t,n,i){let s=g=>{let m=new Map;for(let w of g.split(/\r\n|\r|\n/))w.trim()&&m.set(w,(m.get(w)??0)+1);return m},o=(g,m)=>g.get(m)??0,r=s(e),d=s(i),c=[["Your",s(t)],["The update's",s(n)]],p=g=>{let m=o(r,g),w=o(c[0][1],g)-m,y=o(c[1][1],g)-m,l=Math.max(0,m+w+y);return w>0&&y>0?{min:m+Math.max(w,y),max:l}:w<0&&y<0?{min:l,max:Math.max(0,m+Math.min(w,y))}:{min:l,max:l}},u=[];for(let[g,m]of c){let w=[...new Set([...m.keys(),...r.keys()])].filter(P=>o(m,P)!==o(r,P)),y=w.filter(P=>o(m,P)>o(r,P)&&o(d,P)<p(P).min),l=w.filter(P=>o(m,P)<o(r,P)&&o(d,P)>p(P).max);u.push(`${g} edits kept: ${w.length-y.length-l.length} of ${w.length}`);for(let P of y)u.push(` dropped: ${P.trim().slice(0,120)}`);for(let P of l)u.push(` still present: ${P.trim().slice(0,120)}`)}return u}function Hl(e,t,n){return new Promise(i=>{ci("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(`
131
- `)[0]})})})}var to=40;function jl(e,t){let n=d=>{let c=d.toLowerCase(),p=new Map;for(let u=0;u<c.length-1;u++)p.set(c.slice(u,u+2),(p.get(c.slice(u,u+2))??0)+1);return p},[i,s]=[n(e),n(t)],o=0,r=0;for(let[d,c]of i)o+=Math.min(c,s.get(d)??0),r+=c;for(let d of s.values())r+=d;return r>0&&2*o/r>=.5}async function Kl(e,t,n,i){let s=r=>r.replace(/\r\n?/g,`
132
- `),o;try{o=await ro(K(lo(),"klaudius-clash-"))}catch{return[]}try{let[r,d,c]=["mine","base","theirs"].map(L=>K(o,L));await Nt(r,s(t)),await Nt(d,s(e)),await Nt(c,s(n));let p=await new Promise(L=>ci("git",["merge-file","-p","--diff3",`--marker-size=${to}`,r,d,c],{encoding:"utf8",maxBuffer:64*1024*1024,windowsHide:!0},($,_)=>{let C=$?.code;L(!$||typeof C=="number"&&C>0&&C<128?_:null)}));if(p===null)return[];let u=L=>{let $=new Map;for(let _ of s(L).split(`
133
- `)){let C=_.trim();C&&$.set(C,($.get(C)??0)+1)}return $},g=(L,$)=>L.get($)??0,[m,w,y]=[u(i),u(t),u(n)],l=L=>L.repeat(to),P=[],T=null,I={mine:[],base:[],theirs:[]};for(let L of p.split(`
134
- `))if(L.startsWith(`${l("<")} `))T="mine",I={mine:[],base:[],theirs:[]};else if(T&&L.startsWith(`${l("|")} `))T="base";else if(T&&L===l("="))T="theirs";else if(T&&L.startsWith(`${l(">")} `)){let $=G=>G.map(U=>U.trim()),_=$(I.mine),C=$(I.base),M=$(I.theirs);if(C.length>0&&_.length===C.length&&M.length===C.length)for(let G=0;G<C.length;G++){let[U,O,R]=[_[G],C[G],M[G]];!U||!R||U===O||R===O||U===R||!jl(U,R)||g(m,U)>g(y,U)&&g(m,R)>g(w,R)&&P.push(` kept both versions: ${U.slice(0,120)} / ${R.slice(0,120)}`)}T=null}else T&&I[T].push(L);return P}catch{return[]}finally{await At(o,{recursive:!0,force:!0}).catch(()=>{})}}async function no(e,t,n,i){let s=await se(K(e,Oe,t),"utf-8").catch(()=>null);if(s===null)return["No pre-edit base was staged for this file, so there is no line check. Say in plain words what the merge keeps from each side."];let o=await se(K(e,i,`${t}.bak`),"utf-8").catch(()=>null)??await se(K(e,t),"utf-8").catch(()=>""),r=await se(K(e,di,t),"utf-8");return[s,o,r,n].some($e)?["Binary file: no line check."]:["Line check against the pre-edit base:",...Ul(s,o,r,n),...await Kl(s,o,r,n)]}function Pn(e,t,n=0){for(let i of e)console.log(i);return console.log(`[klaudius-resolve] ${t}`),n}function j(e,t){return console.error(`${e} Nothing was changed.`),console.log(`[klaudius-resolve] refused${t===void 0?"":` remaining=${t}`}`),1}async function io(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 Ne(e,t));let o=d=>At(K(e,d),{recursive:!0,force:!0,maxRetries:3}).then(()=>!0,()=>!1);if(!await o(li))return{complete:!1,lines:[".klaudius/conflicts.md couldn't be removed, so the update staging was kept. Close anything that has it open, then run the same command again."]};let r=!1;for(let d of[di,Oe,$t])await o(d)||(r=!0);return{complete:!0,lines:[r?"Nothing is waiting for a decision. Some staging under .klaudius/ couldn't be removed; the next update clears it.":"Nothing is waiting for a decision. Update staging cleared."]}}var so=e=>new Promise(t=>setTimeout(t,e));function Gl(e,t){if(Date.now()-t>Rl)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 Bl(e,t){let n=K(e,Cl),i=Date.now(),s=!1,o=0;for(;;)try{let r=await _l(n,"wx");await r.writeFile(String(process.pid)).finally(()=>r.close());break}catch(r){let d=r.code;if(d!=="EEXIST"&&d!=="EPERM")throw r;let c=await ao(n).catch(()=>null);if(c===null){if(d==="EPERM"&&++o>5)throw r;await so(50);continue}let p=await se(n,"utf-8").catch(()=>"");if(!s&&Gl(p,c.mtimeMs)){s=!0,await se(n,"utf-8").catch(()=>"")===p&&await At(n).catch(u=>{if(u.code!=="ENOENT")throw new Error(`.klaudius/resolve.lock was left by an earlier run and can't be removed (${u.message})`)});continue}if(Date.now()-i>vl)return null;await so(100)}try{return await t()}finally{await At(n,{force:!0}).catch(()=>{})}}async function uo(e){let t=e.projectRoot??process.cwd();return await wt(K(t,".klaudius","manifest.json"))?await Bl(t,()=>Vl(t,e))??j("Another resolve is still running in this project; run this again once it has finished."):j("No .klaudius/manifest.json here: run this from the Klaudius project folder.")}async function Vl(e,t){let n;try{n=await tn(e)}catch(R){return j(`.klaudius/manifest.json can't be read (${R.message}).`)}if(!n)return j("No .klaudius/manifest.json here: run this from the Klaudius project folder.");let i=await se(K(e,li),"utf-8").catch(()=>null),s=i===null?null:$l(i);if(t.finish){if(t.path||t.action)return j("--finish takes no file or action.");let R=s?.sections.length??0;if(R>0)return j(`${R} ${R===1?"conflict is":"conflicts are"} still waiting in .klaudius/conflicts.md.`,R);let Y=await io(e,n,i,!1);return Pn(Y.lines,Y.complete?"finished remaining=0":"remaining=0 incomplete",Y.complete?0:1)}if(!t.path||!t.action)return j("Name one file and exactly one action.",s?.sections.length);if(!s)return j("No conflicts are staged (.klaudius/conflicts.md is missing).",0);let o=s.sections.length,r=t.path.split("\\").join("/");if(si(t.path)&&(r=Xs(e,t.path).split("\\").join("/")),r=r.replace(/^\.\//,""),r===""||si(r)||/^[a-zA-Z]:/.test(r)||r.split("/").includes(".."))return j(`${t.path} isn't a path inside this project.`,o);let d=s.sections.find(R=>R.path===r);if(!d)return j(`${r} isn't waiting in .klaudius/conflicts.md (waiting: ${s.sections.map(R=>R.path).join(", ")||"none"}).`,o);let c=K(e,r),p=K(e,di,r),u=await wt(c),g=await wt(p),m=d.type??(g?u?"Edit conflict":"Deleted locally":"Removed upstream"),w=t.action;if(!ai[m].includes(w))return j(`${r} is a "${m}" conflict; its options are ${ai[m].map(R=>`--${R}`).join(", ")}.`,o);if(m!=="Removed upstream"&&!g)return j(`The staged new version .klaudius/incoming/${r} is missing; run npx klaudius@latest update to stage it again.`,o);if(m==="Edit conflict"&&!u&&(w==="keep-mine"||w==="check-merge"||w==="merge"||w==="auto-merge"))return j(`${r} is no longer on disk, so there's no version of yours to ${w==="keep-mine"?"keep":"merge"}; choose --take-new.`,o);let y=Dl(i),l=null,P=[];if(w==="check-merge"||w==="merge"){if(!t.draft)return j(`--${w} needs the merged draft's path.`,o);if(l=Lt(e,t.draft),process.platform==="linux"?l===Lt(c):l.toLowerCase()===Lt(c).toLowerCase())return j(`Write the merged version to its own draft file (${xl(r)}), not over ${r}: the original is what gets backed up.`,o);let Y=await se(l,"utf-8").catch(()=>null);if(Y===null)return j(`Can't read the draft ${t.draft}.`,o);let re=await se(p,"utf-8").catch(()=>null),z=await se(c,"utf-8").catch(()=>null),h=Zs(r,Y,re,z)??(re!==null&&z!==null?await eo(r,Y,z,re,ze(c)):null);if(h)return j(`The draft ${t.draft} ${h}.`,o);if(P=await no(e,r,Y,y),w==="check-merge")return Pn(P,`checked path=${r} remaining=${o}`)}let T=null;if(w==="auto-merge"){if(r.split("/").pop()===".gitignore")return j(".gitignore is only merged as a union (every line of the user's kept, the new patterns added, nothing removed), so it can't be merged automatically; merge it by hand.",o);let R=K(e,Oe,r);if(!await wt(R))return j(`${r} has no pre-edit base, so it can't be merged automatically; merge it by hand.`,o);let Y=K(e,y,`${r}.bak`),re=await wt(Y)?Y:c,z=await Hl(re,R,p);if("overlaps"in z)return j(`Your edits and the update's overlap in ${r} (${z.overlaps} place${z.overlaps===1?"":"s"}), so it can't be merged automatically; merge it by hand.`,o);if("unavailable"in z)return j(`git merge-file couldn't run (${z.unavailable}), so ${r} can't be merged automatically; merge it by hand.`,o);let h=z.merged.toString("utf-8"),f=await se(p,"utf-8").catch(()=>null),k=await se(re,"utf-8").catch(()=>null),E=Zs(r,h,f,k)??(f!==null&&k!==null?await eo(r,z.merged,k,f,ze(c)):null);if(E)return j(`The automatic merge of ${r} ${E}; merge it by hand.`,o);P=await no(e,r,h,y);let D=P.filter(b=>/^\s+(dropped|still present|kept both versions):/.test(b)).map(b=>b.trim());if(D.length>0)return j(`The automatic merge of ${r} doesn't keep every edit (${D.join("; ")}); merge it by hand.`,o);T=z.merged}if(w==="keep-deleted"&&u)return j(`${r} exists again, so it can't stay deleted; choose --restore, or move the file away first.`,o);let I=g?await fe(p):void 0,L=w==="take-new"||w==="restore"?I:w==="merge"?await fe(l):T?Pl("sha256").update(T).digest("hex"):void 0,$=u&&(w==="delete"||L!==void 0&&await fe(c)!==L),_=null;if($)try{_=await Fl(e,y,r)}catch(R){return j(`Couldn't save a backup copy of ${r} (${R.message}).`,o)}let C=[];switch(w){case"keep-mine":m==="Edit conflict"?(n.files[r]=I,C.push(`Kept your version of ${r}. Later updates treat it as your edit.`)):(delete n.files[r],C.push(`Kept ${r}. Klaudius no longer tracks it, so updates leave it alone.`));break;case"take-new":case"restore":await ri(ze(c),{recursive:!0}),await oo(p,c),n.files[r]=I,n.ignored&&(n.ignored=n.ignored.filter(R=>R!==r)),C.push(w==="take-new"?`Replaced ${r} with the new version.`:`Restored ${r} in its new version.`);break;case"merge":case"auto-merge":{let R=u?(await ao(c)).mode&4095:void 0,Y=T??await se(l);await ri(ze(c),{recursive:!0}),u&&(await bl(c)).isSymbolicLink()?await Nt(c,Y):await Ee(c,Y,R),n.files[r]=I,C.push(`Wrote the merged version to ${r}.`,...P);break}case"keep-deleted":delete n.files[r],n.ignored=[...new Set([...n.ignored??[],r])],C.push(`${r} stays deleted; updates won't reinstall it.`);break;case"delete":u&&await At(c,{force:!0}),delete n.files[r],C.push(`Deleted ${r}.`);break}_&&C.push(`Your previous version is saved at ${_}.`);let M=o-1,G=!0;if(M>0)n.pendingConflicts=M,n.updatedAt=new Date().toISOString(),await Ne(e,n),await Ee(K(e,li),Ml(s,d,M));else{let R=await io(e,n,i,!0);C.push(...R.lines),G=R.complete}let U=l===null?"":Xs(Lt(e,$t),l);G&&U&&!U.startsWith("..")&&!si(U)&&await Il(l).catch(()=>{});let O=`path=${r} action=${w} remaining=${M}`;return G?Pn(C,O):Pn(C,`${O} incomplete`,1)}var Ft="0.37.5";async function mo(e){let t=e.projectRoot??process.cwd(),n=await tn(t);n||(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let f of It)delete n.files[f];let i,s=F(t,".env"),o,r;try{o=await Mt(s,"utf-8"),r=J(o)}catch{a.error("Couldn't read .env from this directory."),a.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=r.KLAUDIUS_LICENSE_KEY??"",i||(a.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),a.detail("This file is created by `npx klaudius@latest init`. If your project predates"),a.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),a.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let d=e.check?null:Di(o,r,Mi);d!==null&&(await bn(s,d,"utf-8"),a.detail("Backfilled new env keys")),await dn("update",Ft),Ge.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Ft}`),await hn();let p=r.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&p==="claude-code"&&await Ke(t,je)==="added"&&a.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=F(Yl(),`klaudius-update-${process.pid}-${Date.now()}`),g;try{a.heading("Downloading the latest Klaudius template");let f=await ln({licenseKey:i,machineId:vt(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});a.success(`Fetched ${f.filesExtracted} canonical files`),g=u}catch(f){a.error(f.message),a.detail("Update aborted. Your project is unchanged."),await Se(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let m=await ql(g,t,n);if(e.check){let f=m.filter(b=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(b.state)),k=m.filter(b=>["conflict","locally-deleted","removed-modified"].includes(b.state)&&!(b.path===".gitignore"&&b.state==="conflict")),E="unknown";if(r.SUPABASE_URL&&r.SUPABASE_SERVICE_KEY){let b=await Mt(F(g,"scripts","schema.sql"),"utf-8").catch(()=>""),N=await xt({url:r.SUPABASE_URL,serviceKey:r.SUPABASE_SERVICE_KEY,sql:b});N.unreachable?a.detail(`Database schema not checked (${N.unreachable}).`):N.ok?E="current":(E="stale",a.detail(`Database schema is behind (missing: ${N.missing.join(", ")}); update applies scripts/schema.sql.`))}let D=f.length>0||E==="stale";a.blank(),D?(f.length>0&&a.detail(`${Z(f.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),Ge.outro(Dt.yellow("An update is available."))):Ge.outro(Dt.green("Already up to date.")),console.log(`[klaudius-update-check] status=${D?"behind":"current"} pending=${f.length+(E==="stale"?1:0)} conflicts=${k.length} schema=${E}`),await Se(u,{recursive:!0,force:!0}).catch(()=>{});return}let w=!1,y=m.find(f=>f.path===".gitignore"&&f.state==="conflict");if(y){let f=F(t,".gitignore"),k=await Mt(f,"utf-8"),E=await Mt(F(g,".gitignore"),"utf-8"),{merged:D,added:b}=Jl(k,E);b.length>0&&await bn(f,D,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",w=!0,a.detail(b.length>0?`.gitignore auto-merged: kept all your lines, appended ${Z(b.length,"new canonical pattern")}: ${b.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let l=m.filter(f=>f.state==="new"),P=m.filter(f=>f.state==="clean-update"),T=m.filter(f=>f.state==="user-only"),I=m.filter(f=>f.state==="conflict"),L=m.filter(f=>f.state==="no-change"),$=m.filter(f=>f.state==="locally-deleted"),_=m.filter(f=>f.state==="removed-clean"),C=m.filter(f=>f.state==="removed-modified"),M=[...I,...$,...C],G=n.ignored?.length??0;a.blank(),a.heading("Change summary"),a.detail(`${Z(L.length,"file")} unchanged`),a.detail(`${Z(l.length,"new file")}`),a.detail(`${Z(P.length,"file")} updated cleanly (no local edits)`),a.detail(`${Z(T.length,"file")} you've edited (no upstream change \u2014 left alone)`),a.detail(`${Z(_.length,"file")} removed upstream (deleted cleanly)`);let U=I.filter(f=>f.reason==="untracked-local").length,O=I.filter(f=>f.reason==="manifest-mismatch").length;a.detail(`${Z(I.filter(f=>!f.reason).length,"file")} with conflicts (you edited AND we have a new version)`),U>0&&a.detail(`${Z(U,"file")} of your own at a path the new version now ships (need your decision)`),O>0&&a.detail(`${fi(O)}, and we have a new version (need your decision)`),a.detail(`${Z($.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`);let R=C.filter(f=>f.reason==="manifest-mismatch").length;if(a.detail(`${Z(C.length-R,"file")} removed upstream but edited locally (need your decision)`),R>0&&a.detail(`${fi(R)}, removed upstream (need your decision)`),G>0&&(a.detail(`${Z(G,"file")} kept deleted (previously resolved \u2014 skipped)`),G<=10))for(let f of n.ignored)a.detail(` kept deleted: ${f}`);let Y=async()=>{let f=!1,k=E=>Se(E,{recursive:!0,force:!0}).catch(()=>{f=!0});await k(F(t,".klaudius","incoming")),await k(F(t,Oe)),await k(F(t,$t)),await k(F(t,".klaudius","conflicts.md")),f&&a.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/, .klaudius/merged/ and .klaudius/conflicts.md by hand)")};if(l.length===0&&P.length===0&&_.length===0&&M.length===0&&!w){await po(t,r,!1),await Y(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ft,await Ne(t,n)),a.blank(),Ge.outro(Dt.green("Already up to date.")),await Se(u,{recursive:!0,force:!0}).catch(()=>{});return}let re=new Date().toISOString().replace(/[:.]/g,"-"),z=`.klaudius/backup/update-${re}`,h=0;for(let f of[...P,..._]){if(f.localHash===void 0||f.localHash===f.canonicalHash)continue;let k=F(t,z,`${f.path}.bak`);try{await Sn(_n(k),{recursive:!0}),await ui(F(t,f.path),k)}catch(E){a.error(`Couldn't save a backup copy of ${f.path}: ${E.message}`),a.detail("Update stopped before replacing or removing any files (additions already made, such as new .env keys, are kept)."),await Se(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}h++}a.blank(),a.heading("Applying clean updates");for(let f of[...l,...P]){let k=F(g,f.path),E=F(t,f.path);await Sn(_n(E),{recursive:!0}),await ui(k,E),n.files[f.path]=f.canonicalHash}l.length+P.length>0&&a.success(`Wrote ${Z(l.length+P.length,"file")}`),[...l,...P].some(f=>f.path==="package.json"||f.path==="package-lock.json")&&a.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let f of _){let k=F(t,f.path);await Se(k,{force:!0}),delete n.files[f.path]}if(_.length>0){a.success(`Deleted ${Z(_.length,"file")} removed upstream`);for(let f of _.slice(0,20))a.detail(` removed: ${f.path}`);_.length>20&&a.detail(` \u2026and ${_.length-20} more`)}if(h>0&&a.detail(`Previous copies of the ${Z(h,"file")} replaced or removed are in ${z}/ (each saved as <name>.bak)`),await po(t,r,M.some(f=>f.path==="scripts/schema.sql")),M.length>0){a.blank(),a.heading(`${M.length} conflict(s) need resolution`);let f=F(t,".klaudius","incoming");try{await Se(f,{recursive:!0,force:!0})}catch{}await Se(F(t,$t),{recursive:!0,force:!0}).catch(()=>{});for(let b of[...I,...$]){let N=F(g,b.path),ie=F(f,b.path);await Sn(_n(ie),{recursive:!0}),await ui(N,ie)}let k=new Map,E=new Map;for(let b of I){let N=await as(t,b.path),ie=await ls(t,b.path),_e=await Mt(F(g,b.path),"utf-8"),ae=cs(N,ie,_e,b.manifestHash);b.reason==="untracked-local"?k.set(b.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/"+b.path+"` directly._"]):b.reason==="manifest-mismatch"?k.set(b.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/"+b.path+"` directly. If the file was never changed on purpose, taking the new version is safe._"]):ae!==null?(E.set(b.path,ae),k.set(b.path,ds(ae,_e))):N!==null&&($e(N)||$e(_e))?k.set(b.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+b.path+"` directly._"]):N===null?k.set(b.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):k.set(b.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/"+b.path+"` directly._"])}let D=F(t,Oe);try{await Se(D,{recursive:!0,force:!0})}catch{}for(let[b,N]of E){let ie=F(D,b);await Sn(_n(ie),{recursive:!0}),await bn(ie,N,"utf-8")}await bn(F(t,".klaudius","conflicts.md"),Ql(M,n.templateVersion,Ft,k,E),"utf-8"),I.length+$.length>0&&a.detail("Staged canonical versions to .klaudius/incoming/"),E.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=Ft,n.baseSnapshot=re,M.length===0?(delete n.pendingConflicts,await Y()):n.pendingConflicts=M.length,await Ne(t,n);try{await cn(t,g,await qe(g),re)}catch{a.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(a.blank(),M.length===0)Ge.outro(Dt.green("Update complete."));else{let f=p==="codex"?"Codex":"Claude Code";Ge.outro(Dt.yellow(`${M.length} conflict(s) staged. Open ${f} in this project and ask:
135
- "Run /resolve-conflicts"`))}await Se(u,{recursive:!0,force:!0}).catch(()=>{})}async function po(e,t,n){let i=await Wl(e,t,n);return console.log(`[klaudius-update] schema=${i}`),i}async function Wl(e,t,n){let i=(t.SUPABASE_PAT??"").replace(/\s+/g,""),s=(t.SUPABASE_PROJECT_REF??"").trim();if(!i||!s)return a.detail("Database schema not checked: SUPABASE_PAT / SUPABASE_PROJECT_REF aren't in .env. Run `npx klaudius@latest configure` to add them, or paste scripts/schema.sql into your Supabase SQL editor (safe to re-run)."),"skipped";let o=await lt({projectRoot:e,pat:i,projectRef:s,url:t.SUPABASE_URL,serviceKey:t.SUPABASE_SERVICE_KEY});return o.ok&&o.tokenRefused?(a.warn(`Supabase refused the access token (HTTP ${o.tokenRefused}), so scripts/schema.sql wasn't re-applied; every table and column in it is already in the database.`),n&&a.detail("scripts/schema.sql is in conflict, so the check used your current copy \u2014 resolve its conflict, then run update again."),a.detail(ct(o.tokenRefused)),a.detail(dt(s)),"present"):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): ${Ot(s)}`),"failed")}async function ql(e,t,n){let i=await qe(e),s=new Set(i),o=new Map;for(let p of i)o.set(p,await fe(F(e,p)));let r=await zl(t,n,o),d=new Set(n.ignored??[]),c=[];for(let p of i){if(d.has(p)||It.has(p))continue;let u=o.get(p),g=n.files[p],m=F(t,p),w;try{await pi(m),w=await fe(m)}catch{let l=g!==void 0&&!Yi.has(p)&&!en.has(p)?"locally-deleted":"new";c.push({path:p,state:l,canonicalHash:u,manifestHash:g});continue}let y=en.has(p);u===g?w===g||y?c.push({path:p,state:"no-change",canonicalHash:u,localHash:w,manifestHash:g}):c.push({path:p,state:"user-only",canonicalHash:u,localHash:w,manifestHash:g}):w===u||y?c.push({path:p,state:"clean-update",canonicalHash:u,localHash:w,manifestHash:g}):g===void 0?c.push({path:p,state:"conflict",reason:"untracked-local",canonicalHash:u,localHash:w,manifestHash:g}):w!==g?c.push({path:p,state:"conflict",canonicalHash:u,localHash:w,manifestHash:g}):await r(p,g)?c.push({path:p,state:"conflict",reason:"manifest-mismatch",canonicalHash:u,localHash:w,manifestHash:g}):c.push({path:p,state:"clean-update",canonicalHash:u,localHash:w,manifestHash:g})}for(let p of Object.keys(n.files)){if(s.has(p))continue;let u=n.files[p],g=F(t,p),m;try{await pi(g),m=await fe(g)}catch{delete n.files[p];continue}en.has(p)?c.push({path:p,state:"removed-clean",localHash:m,manifestHash:u}):m!==u?c.push({path:p,state:"removed-modified",localHash:m,manifestHash:u}):await r(p,u)?c.push({path:p,state:"removed-modified",reason:"manifest-mismatch",localHash:m,manifestHash:u}):c.push({path:p,state:"removed-clean",localHash:m,manifestHash:u})}return c}async function zl(e,t,n){let i=F(e,Rt),s=async p=>{try{return await fe(p)}catch{return null}},o=async(p,u,g)=>{let m=await s(F(i,p));return m===u||await s(F(e,Oe,p))===u?!1:m!==null||g},r=await rs(e),d=r!==null&&r===t.baseSnapshot,c=d;if(!d&&r===null&&t.baseSnapshot===void 0&&await pi(i).then(()=>!0,()=>!1)){c=!0;for(let[p,u]of Object.entries(t.files)){if(n.get(p)!==u)continue;let g=await s(F(i,p));if(g!==null&&g!==u){c=!1;break}}}return async(p,u)=>c&&await o(p,u,d)}function fi(e){return`${Z(e,"file")} Klaudius can't confirm ${e===1?"is":"are"} unedited`}function fo(e){return e.reason==="manifest-mismatch"?"Hash the manifest records: ":"Hash at last install/update:"}function Z(e,t){return`${e} ${t}${e===1?"":"s"}`}function Jl(e,t){let n=e.includes(`\r
136
- `)?`\r
137
- `:`
138
- `,i=e.split(/\r?\n/),s=new Set(i.map(c=>c.trim()).filter(c=>c!=="")),o=[];for(let c of t.split(/\r?\n/)){let p=c.trim();p===""||p.startsWith("#")||s.has(p)||(o.push(p),s.add(p))}if(o.length===0)return{merged:e,added:o};let r=[...i];for(;r.length>0&&r[r.length-1].trim()==="";)r.pop();r.push("","# Added by `klaudius update` (new canonical ignore patterns)",...o);let d=[...new Set(i.map(c=>c.trim()).filter(c=>c.startsWith("!")))].filter(c=>!o.includes(c));return r.push(...d,""),{merged:r.join(n),added:o}}function Ql(e,t,n,i=new Map,s=new Map){let o=e.filter(m=>m.state==="conflict"&&!m.reason).length,r=e.filter(m=>m.reason==="untracked-local").length,d=e.filter(m=>m.reason==="manifest-mismatch").length,c=e.filter(m=>m.state==="locally-deleted").length,p=e.filter(m=>m.state==="removed-modified"&&!m.reason).length,u=[];u.push("# Update Conflicts"),u.push(""),u.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),u.push(`Updating from canonical version **${t}** to **${n}**.`),u.push("");let g=[];o>0&&g.push(`${o} file${o===1?"":"s"} ha${o===1?"s":"ve"} BOTH local edits AND upstream changes`),r>0&&g.push(`${r} file${r===1?"":"s"} of your own ${r===1?"sits":"sit"} at a path the new version now ships`),d>0&&g.push(`${fi(d)} and ${d===1?"has":"have"} upstream changes or removals`),c>0&&g.push(`${c} file${c===1?"":"s"} you deleted locally ${c===1?"is":"are"} still shipped by the canonical template`),p>0&&g.push(`${p} file${p===1?"":"s"} ${p===1?"was":"were"} removed upstream but edited locally`),u.push(g.join(", and ")+"."),u.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),u.push(""),u.push("---"),u.push("");for(let m of e){if(u.push(`## ${m.path}`),u.push(""),m.state==="locally-deleted")u.push("**Type:** Deleted locally"),u.push(""),u.push("- You deleted this file after it was installed; the canonical template still ships it."),u.push(`- New canonical version staged at: \`.klaudius/incoming/${m.path}\``),u.push(`- Hash at last install/update: \`${(m.manifestHash??"(none)").slice(0,16)}\``),u.push(`- New canonical hash: \`${(m.canonicalHash??"(none)").slice(0,16)}\``),u.push(""),u.push("**Resolution options for the SKILL to walk through:**"),u.push(""),u.push("1. Restore \u2014 copy the canonical version back into place"),u.push("2. Keep deleted \u2014 never reinstall this file (recorded in the manifest's ignore list)");else if(m.state==="removed-modified")u.push("**Type:** Removed upstream"),u.push(""),u.push(`- Your local copy: \`${m.path}\``),u.push("- This file no longer exists in the canonical template."),u.push(m.reason==="manifest-mismatch"?"- The manifest's entry for this file isn't the version Klaudius last installed (a hand-edited manifest, a conflict resolved outside `/resolve-conflicts`, or a folder restored from an older copy), so your copy is treated as edited. If it was never changed on purpose, deleting it matches the new version.":"- You've modified it locally since install."),u.push(`- ${fo(m)} \`${(m.manifestHash??"(none)").slice(0,16)}\``),u.push(`- Your local hash now: \`${(m.localHash??"(missing)").slice(0,16)}\``),u.push(""),u.push("**Resolution options for the SKILL to walk through:**"),u.push(""),u.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),u.push("2. Delete \u2014 remove the file from disk and from the manifest");else{u.push("**Type:** Edit conflict"),u.push(""),u.push(`- ${m.reason?"Your version":"Your version (with your local edits)"}: \`${m.path}\``),u.push(`- New canonical version: \`.klaudius/incoming/${m.path}\``),s.has(m.path)&&u.push(`- Pre-edit base (3-way merge ancestor): \`.klaudius/conflict-base/${m.path}\``),u.push(`- ${fo(m)} \`${(m.manifestHash??"(none)").slice(0,16)}\``),u.push(`- Your local hash now: \`${(m.localHash??"(missing)").slice(0,16)}\``),u.push(`- New canonical hash: \`${(m.canonicalHash??"(none)").slice(0,16)}\``);let w=i.get(m.path);if(w&&w.length>0){let y=s.has(m.path);u.push(""),u.push(y?"**What upstream changed since your base:**":"**About this conflict:**"),u.push(""),u.push(...w),y&&(u.push(""),u.push("_If your local edits don't touch the hunks above, merging is mechanical: take the canonical version and re-apply your edits (or apply the hunks to your copy). If they overlap, compare both versions properly before choosing._"))}u.push(""),u.push("**Resolution options for the SKILL to walk through:**"),u.push(""),u.push("1. Keep mine \u2014 discard the new canonical changes"),u.push("2. Take new \u2014 overwrite my edits with the new version"),u.push("3. Merge \u2014 review both side-by-side and produce a combined version")}u.push(""),u.push("---"),u.push("")}return u.join(`
139
- `)}import{existsSync as ec}from"fs";import{access as tc,readFile as Be,stat as nc}from"fs/promises";import{homedir as yo}from"os";import{join as ee}from"path";import ne from"picocolors";import{spawn as go,spawnSync as ic}from"child_process";function Xl(e){let t=e.trim();return t?/^pk_(live|test)_/.test(t)?"that's a PUBLISHABLE key (pk_\u2026) \u2014 it can't create payment links. Use a restricted key (rk_live_\u2026).":/^[a-z]{2,8}_(live|test)_[A-Za-z0-9]+$/.test(t)?null:"doesn't look like a Stripe secret or restricted key (expected rk_live_\u2026 / rk_test_\u2026).":"empty"}function Zl(e){return e===403}async function ho(e){let t=e.replace(/\s+/g,""),n=Xl(t);if(n)return{ok:!1,kind:"rejected",message:n};try{let i=await fetch("https://api.stripe.com/v1/account",{headers:{Authorization:`Bearer ${t}`}});if(i.status===401)return{ok:!1,kind:"rejected",message:"Stripe rejected the key (HTTP 401) \u2014 it was revoked, or is from a different account."};if(Zl(i.status))return{ok:!0,livemode:/_live_/.test(t),restricted:/^rk/.test(t)};if(!i.ok)return{ok:!1,kind:"api",message:`Stripe returned HTTP ${i.status}`};let s=await i.json();return{ok:!0,livemode:s.livemode===!0,restricted:/^rk/.test(t),accountName:s.business_profile?.name??s.settings?.dashboard?.display_name??void 0}}catch(i){return{ok:!1,kind:"network",message:`Could not reach Stripe: ${H(i)}`}}}async function ko(e){let t=e.projectRoot??process.cwd(),n=[];console.log(ne.bold(`Klaudius doctor \u2014 checking your project\u2026
140
- `)),n.push(await rc());let i=await uc();i&&n.push(i),n.push(await ac());let s=ee(t,".env"),o=ee(t,".klaudius","manifest.json"),r=ee(t,".mcp.json"),d=ee(t,".codex","config.toml"),c=await Ve(s),p=await Ve(o),u="claude-code";if(c)try{J(await Be(s,"utf-8")).AI_AGENT==="codex"&&(u="codex")}catch{}if(u==="claude-code"){let y=await Ve(ee(t,"AGENTS.md")),l=!await Ve(ee(t,".claude"));y&&l&&(u="codex")}n.push({name:".env present",status:c?"ok":"fail",detail:c?s:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."});let g=!1;if(c){let y={};try{y=J(await Be(s,"utf-8"))}catch{}let l=_t(y.AI_PLAN),P=Tt(y.QA_PHASE)??Te(l);g=P==="off",n.push({name:"Plan / QA pass",status:l?"ok":"warn",detail:l?`${Pt[l]} \xB7 QA pass ${P}`:`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 y=0,l="";if(p)try{let P=JSON.parse(await Be(o,"utf-8"));y=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?y>0?"warn":"ok":"fail",detail:p?y>0?`${l||"version unknown"} \u2014 ${y} conflict${y===1?"":"s"} from the last update still unresolved`:l?`${o} (template ${l})`:o:"missing",nextAction:p?y>0?'Open your agent in this folder and say "resolve the conflicts" \u2014 until then some files are still on the previous version.':void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."})}{let y=u==="codex"?d:r,l=await Be(y,"utf-8").catch(()=>null),P=ee(sc(),"config.toml"),T=u==="codex"?await Be(P,"utf-8").catch(()=>null):null,I=oc(u,l,T),L=I==="ok"&&u==="codex"&&T!==null&&!mi.test(l??"");n.push({name:`${u==="codex"?".codex/config.toml":".mcp.json"} \u2014 database connection`,status:I==="ok"?"ok":"warn",detail:L?`${P} \u2014 declared in your own Codex config rather than this folder's`:I==="ok"?y:I==="missing"?u==="codex"?`missing, and no "supabase" server in ${P} either`:"missing":I==="unreadable"?`${y} \u2014 can't be read as JSON`:u==="codex"?`${y} \u2014 no "supabase" server in it, nor in ${P}, so the agent has no database tools`:`${y} \u2014 no "supabase" server in it, so the agent has no database tools`,nextAction:I==="ok"?void 0:u==="codex"?"Run `npx klaudius@latest configure` to write it again, or ask Klaudius in the app to reconnect your database":"Run `npx klaudius@latest configure` to write it again, or press Reconnect it in the Klaudius app's Health check"})}if(n.push(await Sc(u)),process.platform==="win32"){let y=await lc(t);y&&n.push(y)}if(n.push(await cc(t)),n.push(await dc(t)),n.push(await pc(t,g)),n.push(await mc()),n.push(await fc(t)),!c)n.push({name:"Credential validations",status:"skip",detail:".env missing"});else if(e.offline)n.push({name:"Credential validations",status:"skip",detail:"--offline set"});else{let y=await Be(s,"utf-8"),l=J(y);await hc(l,n,t)}console.log();for(let y of n){let l=y.status==="ok"?ne.green("\u2713"):y.status==="warn"?ne.yellow("\u26A0"):y.status==="skip"?ne.dim("\xB7"):ne.red("\u2717");console.log(` ${l} ${y.name}${y.detail?ne.dim(` \u2014 ${y.detail}`):""}`),y.nextAction&&console.log(` ${ne.dim("\u2192")} ${ne.cyan(y.nextAction)}`)}let m=n.filter(y=>y.status==="fail").length,w=n.filter(y=>y.status==="warn").length;console.log(),m===0&&w===0?console.log(ne.green(ne.bold("Everything checks out. You're good to go."))):m===0?console.log(ne.yellow(ne.bold(`${w} warning${w===1?"":"s"} \u2014 review above.`))):(console.log(ne.red(ne.bold(`${m} failed check${m===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}var mi=/^[ \t]*\[[ \t]*mcp_servers[ \t]*\.[ \t]*"?supabase"?[ \t]*[.\]]/m;function sc(){return process.env.CODEX_HOME?.trim()||ee(yo(),".codex")}function oc(e,t,n=null){if(e==="codex")return n!==null&&mi.test(n)?"ok":t===null?"missing":mi.test(t)?"ok":"no-supabase";if(t===null)return"missing";let i;try{i=JSON.parse(t)}catch{return"unreadable"}if(!i||typeof i!="object"||Array.isArray(i))return"unreadable";let s=i.mcpServers;if(!s||typeof s!="object"||Array.isArray(s))return"no-supabase";let o=s.supabase;return o&&typeof o=="object"&&!Array.isArray(o)?"ok":"no-supabase"}async function Ve(e){try{return await tc(e),!0}catch{return!1}}async function rc(){let e=await nt();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 ac(){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 lc(e){let t=Ze([{label:"your Windows user folder",path:yo()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",i=await gi("npm",["config","get","script-shell"],!0),s=i.code===0?i.stdout.trim():void 0;if(et(s,ec))return{name:n,status:"ok",detail:`${t[0].label} contains ${t[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=tt(t,"doctor"),d=t.some(c=>c.chars.includes("&"));return{name:n,status:d?"fail":"warn",detail:o,nextAction:r}}async function cc(e){let t=ee(e,"node_modules");if(!await Ve(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await nc(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 dc(e){let t=process.platform==="darwin"?ee(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?ee(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):ee(process.env.HOME??"",".cache","ms-playwright");return await Ve(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 uc(){let e=await Wn();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 pc(e,t){if(!await Ve(ee(e,"node_modules","@playwright","cli")))return{name:"QA screenshot chain",status:"skip",detail:"project dependencies not installed",nextAction:"Run `npx klaudius@latest install` first."};let i=await yn(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 fc(e){let t=ee(e,".klaudius","notify-failures.log");try{let n=(await Be(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 mc(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
141
- try:
142
- ${e.map(o=>` import ${o}`).join(`
143
- `)}
144
- except Exception as e:
145
- print(str(e))
146
- sys.exit(1)
147
- `,n=await Q();if(!n)return{name:"Python packages installed",status:"fail",detail:"no Python interpreter found (tried python3, python, py -3)",nextAction:"Fix the Python check above first \u2014 the packages live inside that interpreter."};let i=n.command,s=await gi(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(`
148
- `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function hc(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let r=await Me({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:r.ok?"ok":"fail",detail:r.ok?"connected":r.message,nextAction:r.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});let i=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(i==="selfhost"){let r=e.SELFHOST_DEPLOY_TARGET??"",d=e.SELFHOST_URL_TEMPLATE??"",c=[],p=Qe(r);p&&c.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let u=Xe(d);u&&c.push(`SELFHOST_URL_TEMPLATE: ${u}`),t.push({name:"Self-host deploy config",status:c.length===0?"ok":"fail",detail:c.length===0?`target ${r} (SSH reachability tested at first deploy)`:c.join("; "),nextAction:c.length===0?void 0:"Run `npx klaudius@latest configure` and fix the self-host deployment answers."})}else if(i==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let r=await Fe({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 Ue({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 De(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 He(e.GOOGLE_PLACES_API_KEY),d=we(e.GOOGLE_PLACES_API_KEY);r.ok&&d.changed?t.push({name:"Google Places API key",status:"fail",detail:"The key works, but the copy stored in .env is not the key we had to send \u2014 "+(d.repairs.length>0?`it contains look-alike characters (${d.repairs.join("; ")}). `:"it contains invisible or stray characters. ")+"The pipeline's scripts read .env directly and will fail on it.",nextAction:"Run `npx klaudius@latest configure` and press Enter through the prompts \u2014 it rewrites .env with the corrected key."}):t.push({name:"Google Places API key",status:r.ok?"ok":"fail",detail:r.ok?"accepted":r.message,nextAction:r.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius@latest configure`."})}else t.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});t.push(await Ec(e,n)),t.push(...await Pc(e)),t.push(await kc(e,n)),e.STRIPE_SECRET_KEY&&t.push(await wc(e.STRIPE_SECRET_KEY)),t.push(await Ac(e));let s=(e.NOTIFY_CHANNEL??"").toLowerCase(),o=s==="email"||s==="sms"||s==="none"||s==="off"?s:"telegram";if(o==="none"||o==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(o==="email"){let r=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:r&&e.EMAIL_ADDRESS?"ok":"fail",detail:r&&e.EMAIL_ADDRESS?`alerts go to ${r}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:r&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(o==="sms"){let r=e.NOTIFY_TO||e.TEST_PHONE,d=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:r&&d?"ok":"fail",detail:r&&d?`alerts go to ${r} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:r?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:r&&d?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let r=await Si({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 gc(e){let t=o=>!!o&&/^\d+$/.test(o.trim()),n=wo(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 wo(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function yc(e){let t="Email account (Microsoft sign-in)",n=await Q(),s=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[r,...d]=n.command,c=ic(r,[...d,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),p=`${c.stdout??""}${c.stderr??""}`.trim();if(c.status===0){let u=/signed in as (\S+)/.exec(p)?.[1];return{name:t,status:"ok",detail:u?`signed in as ${u} (token refresh works)`:"signed in (token refresh works)"}}return{name:t,status:"fail",detail:p.split(`
149
- `)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:s}}return await Ve(ee(e,".ms-token.json"))?{name:t,status:"warn",detail:"token cache present, but no Python found to verify it"}:{name:t,status:"fail",detail:"no Microsoft sign-in found (.ms-token.json missing)",nextAction:s}}async function kc(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 Be(ee(t,"scripts","schema.sql"),"utf-8")}catch{return{name:n,status:"skip",detail:"scripts/schema.sql missing \u2014 run `npx klaudius@latest update`"}}let r=await xt({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 wc(e){let t="Stripe key",n=await ho(e);if(!n.ok)return{name:t,status:"fail",detail:n.message,nextAction:n.kind==="network"?"Couldn't reach Stripe \u2014 check your connection, then re-run `npx klaudius@latest doctor`.":'Create a new restricted key at https://dashboard.stripe.com/apikeys, then tell your agent "connect Stripe" to store it.'};let i=!n.restricted;return{name:t,status:n.livemode&&!i?"ok":"warn",detail:`${n.accountName??"account"} \xB7 ${n.livemode?"live mode":"TEST mode \u2014 links made with this key can't take real payments"}${i?" \xB7 full secret key, which can do anything in the account":""}`,nextAction:i?'Create a restricted key at https://dashboard.stripe.com/apikeys with the permissions listed in .env.example, then tell your agent "connect Stripe".':n.livemode?void 0:`Swap in a live-mode key when you're ready to take real payments: tell your agent "connect Stripe".`}}async function Ac(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 pt({provider:i,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!o.ok)return{name:t,status:"fail",detail:o.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let r=`${i} credentials accepted`+(o.friendlyName?` (${o.friendlyName})`:""),d=(e.SUPABASE_ANON_KEY??"").trim();if(!d)return{name:t,status:"warn",detail:r+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let c=_i(d);if(c&&c!=="anon")return{name:t,status:"fail",detail:r+`, but SUPABASE_ANON_KEY holds a '${c}' key \u2014 shipping it in a claim page would expose the whole database`,nextAction:"Replace SUPABASE_ANON_KEY with the key whose role is 'anon' (Supabase dashboard \u2192 Settings \u2192 API keys)."};if(e.SUPABASE_URL)try{let p=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:d,Authorization:`Bearer ${d}`}});if(p.ok){let u=await p.json();if(Array.isArray(u)&&u.length>0)return{name:t,status:"fail",detail:r+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(i==="postgrid"){let p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(u=>!(e[u]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:r+`, but PostGrid needs your return address and .env is missing ${p.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:r}}async function Ec(e,t){let n="Email credentials (SMTP + IMAP)",i=gc(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(wo(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."}:yc(t);if(i==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(i==="incomplete"){let c=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(p=>p.endsWith("_PORT")?!e[p]||!/^\d+$/.test(e[p].trim()):!e[p]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${c.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let s=Ie(e),o=s&&s!=="custom"?s:pe(e.EMAIL_SMTP_HOST),r={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:o?te[o].usesAccountPassword:void 0,knownProvider:!!o,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},d=await me(r);if(d.ok){if(d.foldersUnverified)return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the mailbox's folder list could not be read, so the Sent and Drafts folder names are unverified`,nextAction:"Re-run doctor; if it persists, check the mailbox's folder names by hand."};let c=Ao(d,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await Q())?.command.join(" ")});return c?{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but ${c.detail}`,nextAction:c.nextAction}:{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(d.failureKind==="network")return{name:n,status:"fail",detail:d.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(o){let c=jt(o,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(ne.dim(` (email login rejected \u2014 probing ${te[o].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let g of c){let m=await me({...r,emailSmtpHost:g.smtpHost,emailImapHost:g.imapHost});if(!m.ok&&m.failureKind!=="network"&&p++,m.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${g.label} (${g.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${g.smtpHost} and EMAIL_IMAP_HOST=${g.imapHost} in .env (or ask your AI agent to).`}}let u=(d.message??"login rejected").split(/\.\s|\n/)[0];return p===0?{name:n,status:"fail",detail:`${u} \u2014 and none of the alternate servers were reachable either; this looks like a network problem`,nextAction:"Check your connection and re-run doctor before touching the password."}:{name:n,status:"fail",detail:`${u} \u2014 tried all ${te[o].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:o==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":o==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:d.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}function Ao(e,t){let n=[],i=[],s=[];if(e.sentFolderIssue){let{configured:r,detected:d}=e.sentFolderIssue;n.push(`the server has no "${r}" folder \u2014 sent mail isn't being filed, so follow-ups can't see what was sent to whom`),d?i.push(`${t.sentKey}="${d}"`):s.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:r,detected:d}=e.draftsFolderIssue;n.push(`the server has no "${r}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),d?i.push(`${t.draftsKey}="${d}"`):s.push(t.draftsKey)}if(n.length===0)return;let o=[];if(i.length>0&&o.push(`Set ${i.join(" and ")} in .env (or ask your AI agent to).`),s.length>0){let r=t.python||"python3",d=t.account&&t.account!=="primary"?`${r} scripts/gmail.py folders --account ${t.account}`:`${r} scripts/gmail.py folders`;o.push(`Run \`${d}\` to list this mailbox's folder names, then set ${s.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:o.join(" ")}}async function Pc(e){let t=[];for(let n of $i(e)){let i=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:i,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:i,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:i,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:i,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let s=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_SENT_FOLDER`,o=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,r=pe(n.smtpHost),d=await me({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,usesAccountPassword:r?te[r].usesAccountPassword:void 0,knownProvider:!!r,errorHint:{addressSetting:`EMAIL_ACCOUNT_${n.label.toUpperCase()}_ADDRESS`,loginSetting:`EMAIL_ACCOUNT_${n.label.toUpperCase()}_LOGIN`},sentFolder:(e[s]??"").trim()||"Sent",draftsFolder:(e[o]??"").trim()||"Drafts"});if(d.ok){let c=Ao(d,{sentKey:s,draftsKey:o,account:n.label,python:(await Q())?.command.join(" ")});c?t.push({name:i,status:"warn",detail:`authenticated (${n.smtpHost}), but ${c.detail}`,nextAction:c.nextAction}):t.push({name:i,status:"ok",detail:`authenticated (${n.smtpHost})`})}else t.push({name:i,status:"fail",detail:d.message,nextAction:d.failureKind==="network"?"Looks like a network/host problem \u2014 check this mailbox's SMTP/IMAP hosts in .env.":"Check this mailbox's password and hosts in .env (regional providers often need a different server)."})}return t}async function Sc(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 gi(t,["--version"],process.platform==="win32");if(s.code===0){let o=(s.stdout||s.stderr).trim().split(`
150
- `)[0]??"";return e==="codex"&&bc(o)?{name:n,status:"warn",detail:`${o} \u2014 older than ${hi}`,nextAction:`Update the Codex your terminal runs (\`npm install -g @openai/codex@latest\`, or however you installed it): from ${hi}, Codex starts on GPT-6.1 Sol; older versions can start on GPT-6 Astra, which uses up your limits about five times as fast.`}:{name:n,status:"ok",detail:o}}return{name:n,status:"warn",detail:"not found",nextAction:i}}var hi="0.159.1";function bc(e){let t=e.match(/(\d+)\.(\d+)\.(\d+)(-\S+)?/);if(!t)return!1;let n=t.slice(1,4).map(Number),i=hi.split(".").map(Number);for(let s=0;s<3;s++)if(n[s]!==i[s])return n[s]<i[s];return t[4]!==void 0}function gi(e,t,n=!1){return new Promise(i=>{let s=n?go([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):go(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",d=>{o+=d.toString()}),s.stderr?.on("data",d=>{r+=d.toString()}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",()=>i({code:1,stdout:o,stderr:r}))})}import{existsSync as _c}from"fs";import{spawnSync as Tc}from"child_process";import{join as Ic,resolve as Cc}from"path";import oe from"picocolors";async function Eo(e){let t=Cc(e.projectRoot??process.cwd()),n=Ic(t,"scripts","whatsapp.mjs");_c(n)||(console.error(oe.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(oe.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(oe.dim(`Looked for: ${n}`)),process.exit(1));let i=(e.label??"primary").trim(),s=i.replace(/[^A-Za-z0-9_-]/g,"");s||(console.error(oe.red(`Invalid label '${i}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),s!==i&&console.error(oe.yellow(`Note: cleaned label '${i}' \u2192 '${s}' (filename-safe characters only).`)),console.log(oe.cyan(`Pairing WhatsApp account '${s}'...`)),console.log(oe.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
151
- `));let o=Tc(process.execPath,[n,"pair","--account",s],{cwd:t,stdio:"inherit"});if(o.status===0){console.log(oe.green(`Paired '${s}'.`)),console.log(oe.dim(`
152
- If you haven't already, add '${s}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
153
- WHATSAPP_ACCOUNTS=primary,${s}
154
- (Skip this if '${s}' is already there or you set it via the init wizard.)`));return}o.error?console.error(oe.red(`Pair failed: ${o.error.message}`)):(console.error(oe.red(`Pair did not complete (exit ${o.status??"signalled"}). Common causes:`)),console.error(oe.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(oe.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(oe.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${s}/daemon.log`))),process.exit(o.status??1)}import{spawnSync as Et,spawn as Rc}from"child_process";import{existsSync as Ut,mkdirSync as vc,readdirSync as Oc,rmSync as _o,mkdtempSync as To}from"fs";import{homedir as yi,tmpdir as Io}from"os";import{join as ue}from"path";import be from"picocolors";var xc=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function Po(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Co(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&Ht()&&vo();let t=Nc();if(t&&!e.reinstall&&!e.from){bo(),console.log(be.green("Opened the Klaudius app.")),So();return}let n=await Mc(e.from);console.log(be.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Dc(n):Fc(n),bo(),console.log(be.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),So()}function So(){process.platform==="darwin"?console.log(be.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(be.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function Tn(){return ue(yi(),"Applications","Klaudius.app")}function Ro(){return process.env.LOCALAPPDATA??ue(yi(),"AppData","Local")}function Lc(){return ue(Ro(),"Klaudius")}function Ht(){let e=ue(Ro(),"Programs");try{for(let t of Oc(e)){if(!/laudius/i.test(t))continue;let n=ue(e,t,"Klaudius.exe");if(Ut(n))return n}}catch{}return null}function Nc(){return process.platform==="darwin"?Ut(Tn()):Ht()!==null}async function $c(){try{let{readFileSync:e}=await import("fs");return e(ue(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m)?.[2]?.trim()??null}catch{return null}}async function Mc(e){if(e)return Ut(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await $c();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=`${xc}?file=${encodeURIComponent(Po())}`,i=ue(To(ue(Io(),"klaudius-app-")),Po());console.log(be.cyan("Downloading the Klaudius app\u2026"));try{let s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.37.5"}});if(!s.ok){let d=`HTTP ${s.status}`;try{let c=await s.json();c.reason&&(d=c.reason)}catch{}throw new Error(d)}let o=Buffer.from(await s.arrayBuffer()),{writeFileSync:r}=await import("fs");return r(i,o),i}catch(s){console.error(`Couldn't download the app (${s.message}). If you're offline, try again later; otherwise email hello@klaudius.dev.`),process.exit(1)}}function Dc(e){let t=ue(yi(),"Applications");vc(t,{recursive:!0});let n=To(ue(Io(),"klaudius-app-x-")),i=Et("ditto",["-xk",e,n],{stdio:"pipe"});i.status!==0&&(console.error(`Couldn't extract the app: ${i.stderr?.toString().trim()}`),process.exit(1));let s=ue(n,"Klaudius.app");Ut(s)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),_o(Tn(),{recursive:!0,force:!0});let o=Et("mv",[s,Tn()],{stdio:"pipe"});o.status!==0&&(console.error(`Couldn't install to ~/Applications: ${o.stderr?.toString().trim()}`),process.exit(1))}function Fc(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=Et(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Uc(6e4)){let i=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,s=Ht();if(s&&Oo(s)){console.log(be.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(be.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)}vo()}function Uc(e){let t=Date.now()+e;for(;;){let n=Ht();if(n)return n;if(Date.now()>=t)return null;Hc(500)}}function Hc(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function vo(){let e=Lc();if(!Ut(ue(e,"app","Klaudius.exe")))return;console.log(be.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
155
- $legacy = '${e.replace(/'/g,"''")}'
156
- # Compare against the directory PLUS its separator, so a sibling folder whose
157
- # name merely starts with the same text ("Klaudius Desktop") is never matched.
158
- $legacyPrefix = $legacy.TrimEnd('\\') + '\\'
159
- $W = New-Object -ComObject WScript.Shell
160
- foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetFolderPath('Desktop'))) {
161
- $lnk = Join-Path $dir 'Klaudius.lnk'
162
- if (Test-Path -LiteralPath $lnk) {
163
- $target = $W.CreateShortcut($lnk).TargetPath
164
- if ($target -and $target.StartsWith($legacyPrefix, [StringComparison]::OrdinalIgnoreCase)) {
165
- Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
166
- }
167
- }
168
- }`;Et("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{_o(e,{recursive:!0,force:!0})}catch{console.log(be.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function bo(){if(process.platform==="darwin"){Et("open",["-a",Tn()],{stdio:"pipe"});return}let e=Ht();if(!e||Oo(e))return;Rc(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function Oo(e){let t=Et("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 xo(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 ki(e=0){await Promise.all([xo(process.stdout),xo(process.stderr)]),process.exit(e)}import{spawnSync as jc}from"child_process";var wi="--use-system-ca";function Lo(){let e=process.env.NODE_OPTIONS??"";if(e.includes(wi)||!Ae().ok)return;let n=e?`${e} ${wi}`:wi,i=jc(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)}Lo();var Gc="0.37.5",ye=new Kc;ye.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Gc);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 Li({})}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 $s({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await ki(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 Ds({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").option("--answers <file>","Non-interactive: read new answers from a JSON or dotenv-format file (same keys as .env) \u2014 a delta, holding only the settings that changed. Keys in the file replace what .env holds, a key present but empty clears it, and every key it leaves out is KEPT (unlike `init --answers`, where a setting the form owns reverts to its default when left out). Checks run before anything is written; on a failed check nothing is changed and it exits 2 with an INIT-BLOCKED line. On success it prints CONFIGURE-DONE sections=<changed> checked=<sections whose check ran>.").option("--sections <list>","Only with --answers: comma-separated sections whose credential checks should run (supabase, vercel, cloudflare, netlify, selfhost, google-places, email, sms, letter, notifications). Default: every section the answers file changes.").action(async e=>{try{await Qs({answers:e.answers,sections:e.sections}),await ki(process.exitCode??0)}catch(t){console.error("configure failed:",t.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 mo({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 uo(co(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 ko({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 Co({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 Eo({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ye.parse(process.argv);
2
+ import{statSync as s}from"fs";import{isAbsolute as c}from"path";var o="KLAUDIUS_PROJECT_DIR";function n(t,i){let r=t[o];return r===void 0||r===""?{dir:null}:i.isAbsolute(r)?i.isDirectory(r)?{dir:r}:{error:`${o} names "${r}", which is not a folder.`}:{error:`${o} must name the project folder by its full path, not "${r}".`}}var e=n(process.env,{isAbsolute:c,isDirectory:t=>{try{return s(t).isDirectory()}catch{return!1}}});"error"in e&&(console.error(e.error),process.exit(2));e.dir!==null&&process.chdir(e.dir);await import("./main-6O2VUPQT.js");