klaudius 0.28.0 → 0.29.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +56 -56
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,113 +1,113 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as fe,c as
|
|
3
|
-
`));let t=[];t.push(
|
|
4
|
-
`)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function
|
|
2
|
+
import{b as fe,c as Le,d as Y,e as C,f as Ht,g as Ut,h as Me,i as De,j as se,k as Ft,l as jt,o as Kt,q as he,r as He,s as $}from"./chunk-6DXNBDYF.js";import{Command as Ko}from"commander";import{spawn as Vt}from"child_process";import{existsSync as gs}from"fs";import{homedir as ys}from"os";import O from"picocolors";import{win32 as ns}from"path";var ss=["&","^","%","!"];function is(e){return ss.filter(t=>e.includes(t))}function me(e){let t=[];for(let{label:n,path:s}of e){let o=is(s);o.length>0&&t.push({label:n,path:s,chars:o})}return t}function os(e){let t=(e??"").trim().replace(/^["']|["']$/g,"");if(!t||t==="undefined"||t==="null")return null;let n=t.toLowerCase().split(/[\\/]/);if(n.length<2||n.includes("system32"))return null;let s=ns.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(s)?t:null}function ge(e,t){let n=os(e);return n===null?!1:t?t(n):!0}function ye(e,t){let n=e[0],s=[...new Set(e.flatMap(p=>p.chars))],o=s.map(p=>`"${p}"`).join(", "),r=s.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${o} in it ${r?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${r?"will":"may"} fail here with a misleading demand to install Visual Studio \u2014 Visual Studio is NOT needed and installing it will not fix this. Instead point npm's build steps at a shell that parses these paths correctly: PowerShell 7 (pwsh) or Git Bash, whichever is installed \u2014 npm config set script-shell "<full path to pwsh.exe or bash.exe>" (applies to all npm projects on this machine) \u2014 ${t==="preflight"?'then re-run this preflight \u2014 the "Install path safe for npm builds" check passes once script-shell is set.':t==="doctor"?"then re-run doctor \u2014 this check passes once script-shell is set.":'then re-run `npx klaudius@latest install`; `npx klaudius@latest doctor` confirms the fix (its "Install path safe for npm builds" check passes once script-shell is set).'} Windows PowerShell 5.1 ("powershell") will NOT work: it can't run the "||" in packages' install scripts. If neither shell is installed, PowerShell 7 is a small download: winget install Microsoft.PowerShell. If only the PROJECT folder is affected (not the user folder), moving the project to a plain path like C:\\klaudius also fixes it, or scope the npm setting to just this project by adding --location=project (run inside the project folder).`}}function ie(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10),r=`${n}.${s}.${o}`;return n<22||n===22&&s<15?{ok:!1,version:r,major:n,minor:s,message:`Your installed Node.js is ${r}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:r,major:n,minor:s}}import{spawn as as}from"child_process";import{existsSync as rs}from"fs";import{homedir as ls}from"os";import{delimiter as cs,join as Ue}from"path";var ds=new Set(["Restricted","AllSigned"]);function us(e,t=rs){for(let n of e.split(cs)){let s=n.replace(/"/g,"");if(!s)continue;let o=Ue(s,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let l=Ue(s,r);if(t(l))return{path:l,isPs1:!1}}}return null}async function Bt(){let e=us(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await ps();if(!t)return{blocked:!1,shimPath:e.path};let n=Ue(ls(),".local","node")+"\\";return{blocked:ds.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function ps(){let e=Ue(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await Gt(e)??await Gt("powershell.exe")}function Gt(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let s=as(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",r=setTimeout(()=>{s.kill(),n(null)},8e3);s.stdout.on("data",l=>{o+=l.toString()}),s.stderr?.resume(),s.on("close",l=>{clearTimeout(r),n(l===0&&o.trim()?o.trim():null)}),s.on("error",()=>{clearTimeout(r),n(null)})})}import{spawn as fs}from"child_process";var xe=3,Fe=10,hs=[["python3"],["python"],["py","-3"]];async function G(){for(let e of hs){let t=await je(e[0],[...e.slice(1),"--version"]),n=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(n)||t.code!==0)continue;let s=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!s)continue;let o=parseInt(s[1],10),r=parseInt(s[2],10),l=s[3]?`${o}.${r}.${s[3]}`:`${o}.${r}`;return{command:[...e],version:l,major:o,minor:r}}return null}async function ke(){let e=ms(),t=await G();if(!t){let l=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 ${xe}.${Fe}+ is not installed (or not on PATH). Install it from ${e}.`+l}}let{command:n,version:s,major:o,minor:r}=t;return o<xe||o===xe&&r<Fe?{ok:!1,version:s,major:o,minor:r,command:n,message:`Your installed Python is ${s}. Klaudius needs Python ${xe}.${Fe} or newer (the pipeline depends on packages that only ship wheels for ${xe}.${Fe}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:s,major:o,minor:r,command:n}}function ms(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function je(e,t){return new Promise(n=>{let s=fs(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",l=>{o+=l.toString()}),s.stderr?.on("data",l=>{r+=l.toString()}),s.on("close",l=>n({code:l??1,stdout:o,stderr:r})),s.on("error",()=>n({code:1,stdout:o,stderr:r}))})}var Yt=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function Wt(e={}){console.log(O.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
|
+
`));let t=[];t.push(ks());let n=await ke();if(t.push(ws(n)),t.push(await As(n.command)),t.push(await Ps()),process.platform==="win32"){let o=await Es();o&&t.push(o);let r=await bs();r&&t.push(r)}t.push(await Ss());for(let o of t){let r=o.status==="ok"?O.green("\u2713"):o.status==="warn"?O.yellow("!"):O.red("\u2717");console.log(` ${r} ${o.name}${o.detail?O.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${O.dim("\u2192")} ${O.cyan(o.nextAction)}`)}console.log();let s=t.filter(o=>o.status==="fail");if(s.length===0){let o=t.filter(r=>r.status==="warn").length;Ts(o);return}console.log(O.red(O.bold(`${s.length} check${s.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(O.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(O.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function ks(){let e=ie();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal before re-running."}}function ws(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 As(e){let t=e??["python3"],n=await Ke(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 Ps(){let e=process.platform==="win32",t=await Ke("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 Ke("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 Es(){let e=await Bt();if(e.npxMissing)return null;let t="npx runs in PowerShell";if(!e.blocked){let n="resolves to a policy-immune shim";return e.shimPath&&(n=e.policy?`ExecutionPolicy ${e.policy} allows the npx.ps1 shim`:"npx.ps1 shim present but ExecutionPolicy unreadable \u2014 assuming it runs"),{name:t,status:"ok",detail:n}}return{name:t,status:"fail",detail:`ExecutionPolicy ${e.policy} blocks ${e.shimPath}, which PowerShell prefers over npx.cmd`,nextAction:e.ownInstall?`In PowerShell run: Remove-Item "$env:USERPROFILE\\.local\\node\\np*.ps1" \u2014 it deletes only the PowerShell shims from Klaudius's own Node install (npx falls back to npx.cmd). It prints nothing back; that means it worked. Then re-run this preflight.`:"In Windows PowerShell (the classic blue one, not PowerShell 7) run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned \u2014 printing nothing back means it worked; confirm with Get-ExecutionPolicy (should say RemoteSigned), then re-run this preflight. If it prints an error instead, your organisation manages this setting \u2014 ask IT."}}async function bs(){let e=me([{label:"your Windows user folder",path:ys()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await Ke("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(ge(s,gs))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(d=>`"${d}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=ye(e,"preflight"),l=e.some(d=>d.chars.includes("&"));return{name:t,status:l?"fail":"warn",detail:o,nextAction:r}}async function Ss(){try{return await fetch(Yt,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:Yt}}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 Ts(e=0){e>0?console.log(O.green(O.bold("Your machine is ready."))+O.yellow(` (${e} warning${e===1?"":"s"} above \u2014 worth a look, but nothing is blocked.)`)):console.log(O.green(O.bold("All checks passed \u2014 your machine is ready."))),console.log(),console.log(O.bold("NEXT STEP \u2014 this one is for you to run, not the AI assistant:")),console.log(" It's an interactive wizard (it asks for your license key and passwords),"),console.log(" so the assistant can't fill it in. Open a NEW terminal tab and run:"),console.log(),console.log(` ${O.cyan("npx klaudius@latest init my-agency")}`),console.log(),console.log(O.dim(" AI assistant: stop here. Do not run init yourself \u2014 tell the user to")),console.log(O.dim(" run it in a new terminal.")),console.log()}function Ke(e,t,n=!1){return new Promise(s=>{let o=n?Vt([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Vt(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",l="";o.stdout?.on("data",d=>{r+=d.toString()}),o.stderr?.on("data",d=>{l+=d.toString()}),o.on("close",d=>s({code:d??1,stdout:r,stderr:l})),o.on("error",()=>s({code:1,stdout:r,stderr:l}))})}import{mkdir as _t,readdir as Kn,readFile as Un,stat as It,writeFile as Tt}from"fs/promises";import{spawnSync as Ct}from"child_process";import{homedir as Bi}from"os";import{resolve as Vi,isAbsolute as Yi,join as W,normalize as Wi}from"path";import*as P from"@clack/prompts";import f from"picocolors";var yt="claude-code",kt="gpt-5.6-terra";function Qt(e){if(e==="claude-code"||e==="codex")return e}var _s=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function Ge(e){let t=e?.trim().toLowerCase()??"";return _s.includes(t)?t:void 0}function Be(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 wt="vercel";function qt(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function zt(e){if(e==="telegram"||e==="email"||e==="sms")return e}function Jt(e){if(e==="password"||e==="oauth-microsoft")return e}function Is(e){if(e==="custom"||e!==void 0&&Object.hasOwn(Y,e))return e}function Ve(e){let t=Is(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[s,o]of Object.entries(Y))if(o.smtpHost===n)return s;return"custom"}}function Xt(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let s of t.split(",")){let o=s.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(s=>{let o=/^[a-z0-9_]+$/.test(s)&&s!=="auto",r=d=>{let c=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${d}`];return c?.trim()?c.trim():void 0},l=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(d=>!r(d)).map(d=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${d}`);for(let d of["SMTP_PORT","IMAP_PORT"]){let c=r(d);c!==void 0&&!/^\d+$/.test(c)&&l.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${d}`)}return{label:s,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:l,smtpHost:r("SMTP_HOST"),smtpPort:parseInt(r("SMTP_PORT")??"587",10),imapHost:r("IMAP_HOST"),imapPort:parseInt(r("IMAP_PORT")??"993",10),password:r("PASSWORD")}})}function Ye(e){let t=[],n=d=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${d}`),t.push("# "+"=".repeat(60)),t.push("")},s=(d,c)=>{if(c==null||c===""){t.push(`# ${d}=`);return}let p=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(p)){let a=p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${d}="${a}"`)}else t.push(`${d}=${p}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),s("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),s("AI_AGENT",e.aiAgent??yt),s("AI_PLAN",e.aiPlan),s("QA_PHASE",e.qaPhase??he(e.aiPlan)),n("Operating country and language"),s("OPERATOR_COUNTRY",e.country),s("OPERATOR_COUNTRY_CODE",e.countryCode),s("OPERATOR_LANGUAGE",e.language),s("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let o=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];s("PIPELINE_MODES",[...new Set(["classic",...o])].join(",")),n("Pricing"),s("PRICING",e.pricing),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",e.pricingMonthly),n("Automated outreach features"),s("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),s("OPERATOR_NAME",e.name),s("SIGNATURE",e.signature),s("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),s("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),s("EMAIL_PROVIDER",e.emailProvider),s("EMAIL_AUTH",e.emailAuth??"password"),s("EMAIL_ADDRESS",e.emailAddress),s("EMAIL_PASSWORD",e.emailPassword),s("EMAIL_FROM_NAME",e.emailFromName),s("EMAIL_SMTP_HOST",e.emailSmtpHost),s("EMAIL_SMTP_PORT",e.emailSmtpPort),s("EMAIL_IMAP_HOST",e.emailImapHost),s("EMAIL_IMAP_PORT",e.emailImapPort),s("EMAIL_SENT_FOLDER",e.emailSentFolder),s("EMAIL_INBOX_FOLDER",e.emailInboxFolder),s("EMAIL_DRAFTS_FOLDER",e.emailDraftsFolder),n("SMS outreach"),s("SMS_PROVIDER",e.smsProvider),s("TEST_PHONE",e.testPhone),s("TWILIO_ACCOUNT_SID",e.twilioAccountSid),s("TWILIO_AUTH_TOKEN",e.twilioAuthToken),s("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),s("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Letter outreach"),s("LETTER_PROVIDER",e.letterProvider??"none"),s("PINGEN_CLIENT_ID",e.pingenClientId),s("PINGEN_CLIENT_SECRET",e.pingenClientSecret),s("PINGEN_ORG_ID",e.pingenOrgId),s("POSTGRID_API_KEY",e.postgridApiKey),n("Supabase (pipeline state)"),s("SUPABASE_URL",e.supabaseUrl),s("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),s("SUPABASE_ANON_KEY",e.supabaseAnonKey),s("SUPABASE_PAT",e.supabasePat),s("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),s("DEPLOY_PROVIDER",e.deployProvider??wt),s("VERCEL_TOKEN",e.vercelToken),s("VERCEL_SCOPE",e.vercelScope??""),s("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),s("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),s("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),s("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),s("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),s("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),s("NOTIFY_CHANNEL",e.notifyChannel),s("NOTIFY_TO",e.notifyTo),s("TELEGRAM_BOT_TOKEN",e.telegramBotToken),s("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(d=>/^#?\s*([A-Z0-9_]+)=/.exec(d)?.[1]).filter(d=>!!d)),l=Object.entries(e.preservedEnv??{}).filter(([d])=>!r.has(d));if(l.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[d,c]of l)s(d,c)}return t.join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`}function
|
|
7
|
-
`}function
|
|
8
|
-
`)}function
|
|
6
|
+
`}function We(e){let t={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(t,null,2)+`
|
|
7
|
+
`}function Qe(e){let t=e.supabaseProjectRef,n=Cs(e.supabasePat);return["# Codex MCP config \u2014 generated by `npx klaudius init` / `configure`.","# Edit freely. NEVER commit this file \u2014 .gitignore already excludes it.","# See `.codex/config.toml.example` for the documented format.","",...e.aiPlan==="codex-plus"?["# Set by the wizard for ChatGPT Plus. Change or delete to use Codex's default.",`model = "${kt}"`,""]:[],"[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${t}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${n}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
|
|
8
|
+
`)}function Cs(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Zt=[{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. Pre-modes installs targeted no-website businesses only ('classic') \u2014 this records that explicitly. Add 'rescue' (businesses whose existing website is verifiably dead or bad) and/or 'booking' (businesses whose Google-listed website is a booking-platform page) \u2014 e.g. 'classic,rescue,booking' \u2014 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 Rs(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function en(e,t,n){let s=n.filter(l=>!(l.key in t));if(s.length===0)return null;let o=e.endsWith(`
|
|
9
9
|
`)?"":`
|
|
10
|
-
`,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let l of s)r.push(""),l.comment&&r.push(`# ${l.comment}`),r.push(
|
|
10
|
+
`,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let l of s)r.push(""),l.comment&&r.push(`# ${l.comment}`),r.push(Rs(l.key,l.value));return e+o+r.join(`
|
|
11
11
|
`)+`
|
|
12
|
-
`}function
|
|
13
|
-
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),l=
|
|
14
|
-
`,"utf-8")}function
|
|
15
|
-
`+oe.bold(oe.cyan(e))),detail:e=>console.log(oe.dim(" "+e))};var
|
|
16
|
-
`)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let l={};try{l=await r.json()}catch{}let
|
|
12
|
+
`}function xs(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 U(e){let t={};for(let n of e.split(`
|
|
13
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),l=xs(s.slice(o+1).trim());t[r]=l}return t}function tn(e){let t=d=>{let c=e[d];if(!c)return;let p=parseInt(c,10);return isNaN(p)?void 0:p},n=e.SMS_PROVIDER,s=d=>d==="email"||d==="sms"||d==="whatsapp"||d==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(d=>d.trim()).filter(s),r=e.OUTREACH_PRIORITY?.split(",").map(d=>d.trim()).filter(s),l=e.WHATSAPP_ACCOUNTS?.split(",").map(d=>d.trim()).filter(d=>d.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Qt(e.AI_AGENT)??yt,aiPlan:Ge(e.AI_PLAN),qaPhase:Be(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(d=>d.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:r&&r.length>0?r:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailProvider:Ve(e),emailAuth:Jt(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:n==="imessage"||n==="twilio"?n:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:qt(e.DEPLOY_PROVIDER)??wt,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:zt(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function At(e){let t=T=>{let te=e[T];if(!te)return;let D=parseInt(te,10);return isNaN(D)?void 0:D},n=e.SUPABASE_URL,s=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),r=e.SUPABASE_PROJECT_REF,l=e.PRICING,d=e.PRICING_TERMS||"one-off, no monthly fees",c=qt(e.DEPLOY_PROVIDER)??wt,p=e.VERCEL_TOKEN,a=e.CLOUDFLARE_API_TOKEN,y=e.CLOUDFLARE_ACCOUNT_ID,E=e.NETLIFY_AUTH_TOKEN,w=e.SELFHOST_DEPLOY_TARGET,g=e.SELFHOST_URL_TEMPLATE;if(!l||!n||!s||!o||!r||!(c==="cloudflare"?!!a&&!!y:c==="netlify"?!!E:c==="selfhost"?!!w&&!!g:!!p))return null;let b=e.SMS_PROVIDER,R=T=>T==="email"||T==="sms"||T==="whatsapp"||T==="letter",I=e.OUTREACH_CHANNELS?.split(",").map(T=>T.trim()).filter(R),Q=e.OUTREACH_PRIORITY?.split(",").map(T=>T.trim()).filter(R),V=e.WHATSAPP_ACCOUNTS?.split(",").map(T=>T.trim()).filter(T=>T.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Qt(e.AI_AGENT)??yt,aiPlan:Ge(e.AI_PLAN),qaPhase:Be(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(T=>T.trim().toLowerCase()).filter(Boolean):void 0,pricing:l,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:Q&&Q.length>0?Q:void 0,whatsappAccounts:V&&V.length>0?V:void 0,emailProvider:Ve(e),emailAuth:Jt(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:b==="imessage"||b==="twilio"?b:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,deployProvider:c,vercelToken:p,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:a||void 0,cloudflareAccountId:y||void 0,netlifyAuthToken:E||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:w||void 0,selfhostUrlTemplate:g||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:zt(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as wa,mkdir as Aa,readdir as Hs,stat as Pa}from"fs/promises";import{dirname as ba,join as cn,relative as Us,sep as Fs}from"path";import{fileURLToPath as Ta}from"url";import{createHash as nn}from"crypto";import{readFile as Os}from"fs/promises";async function we(e){let t=await Os(e);return nn("sha256").update(t).digest("hex")}function Pt(e){return nn("sha256").update(e).digest("hex")}import{mkdir as vs,readFile as Ns,writeFile as $s,access as Ls}from"fs/promises";import{dirname as Ms,join as sn}from"path";var Ds=".klaudius",on=`${Ds}/manifest.json`,qe=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml",".ms-token.json"]),an=new Set(["clients/README.md"]);async function rn(e){let t=sn(e,on);try{await Ls(t)}catch{return null}let n=await Ns(t,"utf-8"),s=JSON.parse(n),o={};for(let[r,l]of Object.entries(s.files??{}))o[r.split("\\").join("/")]=l;return s.files=o,Array.isArray(s.ignored)?s.ignored=s.ignored.filter(r=>typeof r=="string").map(r=>r.split("\\").join("/")):delete s.ignored,s}async function Oe(e,t){let n=sn(e,on);await vs(Ms(n),{recursive:!0}),await $s(n,JSON.stringify(t,null,2)+`
|
|
14
|
+
`,"utf-8")}function ln(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function le(e,t=e){let n=await Hs(e,{withFileTypes:!0}),s=[];for(let o of n){let r=cn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await le(r,t)):o.isFile()&&s.push(Us(t,r).split(Fs).join("/")))}return s}async function dn(e){let t=await le(e),n={};for(let s of t)qe.has(s)||(n[s]=await we(cn(e,s)));return n}import{copyFile as js,mkdir as un,mkdtemp as Ks,readdir as pn,rm as fn}from"fs/promises";import{tmpdir as Gs}from"os";import{dirname as Bs,join as ze}from"path";import{Readable as Vs}from"stream";import*as hn from"tar";var Ys="https://klaudius.dev/api/template";function Ws(e){return Vs.fromWeb(e)}async function Je(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Ys,n="0.29.1",s;try{s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(d){throw new Error(`Could not reach klaudius.dev to download the template: ${C(d)}`)}if(!s.ok){let d="";try{let c=await s.json();d=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${d}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),r=await Ks(ze(Gs(),"klaudius-template-")),l=0;try{try{await new Promise((p,a)=>{let y=hn.extract({cwd:r,strict:!0});y.on("finish",p),y.on("error",a),Ws(s.body).on("error",a).pipe(y)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await un(e.destDir,{recursive:!0});let d=new Set(await pn(e.destDir)),c=await le(r);try{for(let p of c){let a=ze(e.destDir,p);await un(Bs(a),{recursive:!0}),await js(ze(r,p),a),l++}}catch(p){let a=await pn(e.destDir).catch(()=>[]);for(let y of a)d.has(y)||await fn(ze(e.destDir,y),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await fn(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:o}}import{copyFile as Qs,mkdir as qs,readFile as mn,rm as zs}from"fs/promises";import{dirname as Js,join as ce}from"path";import{structuredPatch as Xs}from"diff";var gn=ce(".klaudius","base"),Xe=ce(".klaudius","conflict-base");async function Ze(e,t,n){let s=ce(e,gn);await zs(s,{recursive:!0,force:!0});for(let o of n){let r=ce(s,o);await qs(Js(r),{recursive:!0}),await Qs(ce(t,o),r)}}async function yn(e,t){try{return await mn(ce(e,gn,t),"utf-8")}catch{return null}}async function kn(e,t){try{return await mn(ce(e,Xe,t),"utf-8")}catch{return null}}function wn(e,t,n,s){return Ae(n)?null:e!==null&&!Ae(e)&&(!s||Pt(e)===s)?e:t!==null&&!Ae(t)&&s&&Pt(t)===s?t:null}function Ae(e){return e.includes("\0")||e.includes("\uFFFD")}function An(e,t,n=60){let s=Xs("base","new",e,t,"","",{context:2});if(s.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=s.hunks.map(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),r=[`Upstream changed ${s.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],l=0,d=!1;for(let c of s.hunks){if(l>=n){d=!0;break}r.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),l+=1;let p=Math.max(n-l,0),a=c.lines.slice(0,p);if(r.push(...a),l+=a.length,a.length<c.lines.length){d=!0;break}}return r.push("```"),d&&r.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),r}import oe from"picocolors";var i={info:e=>console.log(oe.cyan("\u2139"),e),success:e=>console.log(oe.green("\u2713"),e),warn:e=>console.log(oe.yellow("\u26A0"),e),error:e=>console.error(oe.red("\u2717"),e),step:e=>console.log(oe.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+oe.bold(oe.cyan(e))),detail:e=>console.log(oe.dim(" "+e))};var Zs="https://registry.npmjs.org/klaudius/latest";async function ei(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Zs,{signal:t.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let o=await s.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function ti(e,t){let n=r=>r.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(s[r])||Number.isNaN(o[r]))return!1;if(s[r]>o[r])return!0;if(s[r]<o[r])return!1}return!1}async function et(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await ei();!n||!ti(n,t)||(i.blank(),i.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(i.detail("Your project content is fetched fresh either way, so you're not missing any"),i.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),i.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),i.blank())}import{createHash as ni}from"crypto";import{hostname as Pn,userInfo as si,platform as En,arch as bn}from"os";var ii="https://klaudius.dev",oi="/api/licenses/validate",ai="0.29.1";async function Sn(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),s=(process.env.KLAUDIUS_API_URL??ii).replace(/\/$/,"")+oi,o=ve(),r;try{r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Pn(),os:`${En()}-${bn()}`,cli_version:ai})})}catch(d){return{ok:!1,reason:`Could not reach the Klaudius license server (${C(d)}). Check your internet connection or try again later.`}}let l;try{l=await r.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${r.status}).`}}return l.ok?{ok:!0,tier:l.tier??"core"}:{ok:!1,reason:l.reason??`License rejected (HTTP ${r.status}).`}}function ve(){let e=[Pn(),si().username,En(),bn()].join("|");return ni("sha256").update(e).digest("hex").slice(0,32)}import{readFile as ri}from"fs/promises";import{join as li}from"path";async function Pe(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: ${C(n)}`}}}async function Tn(e){let t;try{t=await ri(li(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(s){return{ok:!1,message:`Could not read scripts/schema.sql: ${s.message}`}}let n=e.pat.replace(/\s+/g,"");try{let s=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(s.ok)return{ok:!0};let o=await s.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(i.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${s.status}): ${o.slice(0,300)}`}}catch(s){return{ok:!1,message:`Schema apply failed: ${s.message}`}}}async function tt(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${C(t)}`}}}var _n="https://api.cloudflare.com/client/v4";function In(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function nt(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${_n}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let r=await o.json(),l=r.result?.status;if(r.success===!1||l&&l!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${l?` (status: ${l})`:""}. ${In(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${C(o)}`}}try{let o=await fetch(`${_n}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let r=await o.json();return r.success===!1?{ok:!1,message:In(r)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(r.result)?r.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${C(o)}`}}}var Cn="https://api.netlify.com/api/v1";async function st(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${Cn}/user`,{headers:n});if(s.status===401||s.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} verifying the token. Try again or check netlifystatus.com.`}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${C(s)}`}}try{let s=await fetch(`${Cn}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),r=Array.isArray(o)?o:[];if(r.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let l=typeof r[0]?.slug=="string"?r[0].slug:void 0;return{ok:!0,accountCount:r.length,accountSlug:l}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${C(s)}`}}}async function Ee(e){let t=Ft(e);if(t)return{ok:!1,message:t};let n=se(e),s=n.value,o=r=>{let l=[r],d=jt(e);return d&&l.push(d),n.repairs.length>0&&l.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.`),l.join(`
|
|
16
|
+
`)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let l={};try{l=await r.json()}catch{}let d=l.error?.message??"",c=l.error?.status??"";return r.status===400&&(c==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(d))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:r.status===401||r.status===403?{ok:!1,message:o(d||`Google rejected the key (HTTP ${r.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`)}:{ok:!1,message:o(`Google API returned HTTP ${r.status}${d?`: ${d}`:""}.`)}}catch(r){return{ok:!1,message:`Could not reach Google: ${C(r)}`}}}import ci from"nodemailer";import{ImapFlow as di}from"imapflow";function Rn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let s=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return s.includes("invalid credentials")||s.includes("authentication failed")||s.includes("auth failed")||s.includes("login failed")||s.includes("invalid login")?"auth":s.includes("etimedout")||s.includes("timeout")||s.includes("enotfound")||s.includes("getaddrinfo")||s.includes("econnrefused")||s.includes("econnreset")?"network":"other"}async function J(e){let t=ci.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(o){return{ok:!1,failedAt:"smtp",message:xn(o,"SMTP",e.usesAccountPassword),failureKind:Rn(o)}}finally{t.close()}let n=new di({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),s;try{if(await n.connect(),e.draftsFolder)try{let o=await n.list(),r=e.draftsFolder.toLowerCase();if(!o.some(d=>d.path.toLowerCase()===r)){let d=o.find(c=>c.specialUse==="\\Drafts")?.path;s={configured:e.draftsFolder,detected:d}}}catch{}await n.logout()}catch(o){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:xn(o,"IMAP",e.usesAccountPassword),failureKind:Rn(o)}}return{ok:!0,draftsFolderIssue:s}}function xn(e,t,n){let s=e instanceof Error?e.message:String(e),o=s.toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
|
|
17
17
|
\u2022 The mailbox password is wrong or mistyped.
|
|
18
18
|
\u2022 The email address doesn't match this mailbox's login.
|
|
19
19
|
\u2022 The provider is blocking third-party apps \u2014 check that third-party
|
|
20
20
|
access is enabled and 2FA is off in your provider's settings.`:`${t} rejected the credentials. Most common causes:
|
|
21
21
|
\u2022 The app password is wrong, expired, or for a different provider.
|
|
22
22
|
\u2022 The email address doesn't match the account that issued the password.
|
|
23
|
-
\u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}async function
|
|
24
|
-
`+t;return
|
|
25
|
-
${e.stdout??""}`;return
|
|
26
|
-
`,"utf-8")}var
|
|
27
|
-
runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),a=await
|
|
28
|
-
${
|
|
23
|
+
\u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}async function On(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let s=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(s.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!s.ok)return{ok:!1,message:`Twilio API returned HTTP ${s.status}. Try again or check status.twilio.com.`};let o=await s.json();return o.status&&o.status!=="active"?{ok:!1,message:`Twilio account is in '${o.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:o.friendly_name}}catch(s){return{ok:!1,message:`Could not reach Twilio: ${C(s)}`}}}async function it(e){return e.provider==="pingen"?ui(e):pi(e)}async function ui(e){if(!e.pingenClientId||!e.pingenClientSecret||!e.pingenOrgId)return{ok:!1,message:"Missing Pingen Client ID, Client Secret, or organisation id."};let t=e.pingenStaging?"https://identity-staging.pingen.com":"https://identity.pingen.com",n=e.pingenStaging?"https://api-staging.pingen.com":"https://api.pingen.com";try{let s=await fetch(`${t}/auth/access-tokens`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:e.pingenClientId,client_secret:e.pingenClientSecret,scope:"letter"})});if(!s.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${s.status}). Check the Client ID and Secret under your organisation's 'API Access' page \u2014 note that staging and production credentials are separate.`};let o=(await s.json()).access_token;if(!o)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let r=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${o}`}});return r.status===403||r.status===404?{ok:!1,message:"Pingen accepted the credentials but not the organisation id. Copy it from the dashboard URL: app.pingen.com/organisations/<id>/\u2026"}:r.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${r.status}. Try again shortly.`}}catch(s){return{ok:!1,message:`Could not reach Pingen: ${C(s)}`}}}async function pi(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: ${C(t)}`}}}import{spawn as fi}from"child_process";async function vn(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,s=await hi(n);if(s.code===0)return{ok:!0};let o=s.stderr.toLowerCase();return o.includes("can't get application")||o.includes("isn't running")||o.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:o.includes("(-1728)")||o.includes("not found")||o.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:o.includes("(-1719)")||o.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${s.stderr.trim()||`exit code ${s.code}`}`}}function hi(e){return new Promise(t=>{let n=fi("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),s="";n.stderr.on("data",o=>{s+=o.toString()}),n.on("close",o=>t({code:o??1,stderr:s})),n.on("error",o=>t({code:1,stderr:o.message}))})}import{spawn as ot}from"child_process";import{existsSync as mi}from"fs";import{homedir as gi}from"os";function yi(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var be=2,Nn=2e3,ki=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function $n(e,t){let n=e+`
|
|
24
|
+
`+t;return ki.some(s=>s.test(n))}function Ln(e){return new Promise(t=>setTimeout(t,e))}function wi(e,t,n){return new Promise(s=>{let o=n.shell?ot([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):ot(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),r="",l="";o.stdout?.on("data",d=>{let c=d.toString();r+=c,process.stdout.write(c)}),o.stderr?.on("data",d=>{let c=d.toString();l+=c,process.stderr.write(c)}),o.on("close",d=>s({code:d??1,stdout:r,stderr:l})),o.on("error",d=>s({code:1,stdout:r,stderr:l+d.message}))})}async function Et(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=be;o++){if(s=await wi(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!$n(s.stderr,s.stdout))return s;o<be&&(i.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${be+1})\u2026`),await Ln(Nn))}return s}function Ai(e,t,n){return new Promise(s=>{let o=ot(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),r="",l="";o.stdout?.on("data",d=>{r+=d.toString()}),o.stderr?.on("data",d=>{l+=d.toString()}),o.on("close",d=>s({code:d??1,stdout:r,stderr:l})),o.on("error",d=>s({code:1,stdout:r,stderr:l+d.message}))})}var Pi=[{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 Ei(e){let t=`${e.stderr??""}
|
|
25
|
+
${e.stdout??""}`;return Pi.find(s=>s.pattern.test(t))?.hint}async function bi(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await G())?.command??["python3"],r=async d=>{let c={code:0,stdout:"",stderr:""};for(let p=0;p<=be;p++){if(c=await Ai(o[0],[...o.slice(1),...d],{cwd:e}),c.code===0||!$n(c.stderr,c.stdout))return c;p<be&&(i.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${be+1})\u2026`),await Ln(Nn))}return c},l=await r([...n,"--break-system-packages",...t]);return l.code!==0&&/no such option:.*break-system-packages/i.test(l.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),l=await r([...n,...t])),l.code!==0&&(l.stderr.trim()&&process.stderr.write(l.stderr),l.stdout.trim()&&process.stdout.write(l.stdout)),l}async function at(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=yi(),s=process.platform==="win32",o;if(s){let a=me([{label:"your Windows user folder",path:gi()},{label:"the project folder",path:e}]);if(a.length>0){let y=await new Promise(w=>{let g=ot("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),k="",b="";g.stdout?.on("data",R=>{k+=R.toString()}),g.stderr?.on("data",R=>{b+=R.toString()}),g.on("close",R=>w({code:R??1,stdout:k,stderr:b})),g.on("error",R=>w({code:1,stdout:k,stderr:R.message}))}),E=y.code===0?y.stdout.trim():void 0;if(!ge(E,mi)){let{detail:w,action:g}=ye(a,"install");o=`${w}. ${g}`}}}let r=(a,y)=>{let E=Ei(y);if(E){(t.hints??={})[a]=E;return}o&&(a==="npm"||a==="playwright"||a==="patchright")&&!Object.values(t.hints??{}).includes(o)&&((t.hints??={})[a]=o)};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let l=await Et("npm",["install"],{cwd:e,label:"npm install",env:n,shell:s});t.npm=l.code===0?"ok":"failed",l.code!==0&&r("npm",l),i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let d=await bi(e);t.pip=d.code===0?"ok":"failed",d.code!==0&&r("pip",d),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Et("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:s});t.playwright=c.code===0?"ok":"failed",c.code!==0&&r("playwright",c),i.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await Et("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:s});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&r("patchright",p),t}import{copyFile as Si,access as Ti}from"fs/promises";import{dirname as _i,join as Ii}from"path";async function Mn(){let e=await je("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 bt(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await Mn();if(e.state==="real")return{status:"ok",version:e.version};let t=await G();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function Ci(e){let[t,...n]=e.command,s=await je(t,[...n,"-c","import sys; print(sys.executable)"]),o=s.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(s.code!==0||!o)return{ok:!1,reason:"no-exe-path"};let r=Ii(_i(o),"python3.exe"),l=await Ti(r).then(()=>!0,()=>!1);if(!l){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await Si(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let d=await Mn();return{ok:!0,target:r,created:!l,verified:d.state==="real",postState:d.state==="real"?void 0:d.state}}var Ri="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 rt(){let e=await bt();if(e.status!=="broken")return;let t=await Ci(e.fallback);if(t.ok&&t.verified){let n=t.created?e.literal==="stub"?"Fixed a Windows quirk: `python3` was a Store placeholder; it now runs your real Python.":"Fixed a Windows quirk: created the missing `python3` command from your real Python.":"The `python3` command now works \u2014 it runs your real Python.";i.success(n);return}if(t.ok&&t.postState==="stub"){i.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),i.detail(Ri);return}if(t.ok){i.warn("A python3.exe is in place next to your Python, but that folder isn't on this machine's PATH, so commands can't find it."),i.detail('Re-installing Python from python.org with "Add python.exe to PATH" ticked resolves it \u2014 then open a fresh terminal.');return}if(t.reason==="store-python"){i.warn('This Python was installed from the Microsoft Store, which blocks creating the `python3` alias next to it. Installing Python from python.org (tick "Add python.exe to PATH") resolves it.');return}if(t.reason==="not-writable"){i.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),i.detail(t.manualCommand??"");return}i.warn("This machine's `python3` command isn't working, and the automatic fix could not complete. Re-installing Python from python.org (tick \"Add python.exe to PATH\") resolves it.")}import{spawn as xi,spawnSync as Dn}from"child_process";import{mkdtemp as Oi,rm as vi,rmdir as Ni,writeFile as $i,stat as St,unlink as Li,mkdir as Mi}from"fs/promises";import{createServer as Di}from"net";import{tmpdir as Hi}from"os";import{join as Se}from"path";function Ui(){return new Promise((e,t)=>{let n=Di();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let s=n.address(),o=typeof s=="object"&&s?s.port:0;n.close(()=>e(o))})})}function lt(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?Dn(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):Dn("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function ct(e){try{return await Fi(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Fi(e){let t=`klaudius-smoke-${process.pid}`,n=Se(".klaudius",`qa-smoke-${process.pid}.png`),s=Se(e,n),o,r,l=!1;try{o=await Oi(Se(Hi(),"klaudius-qa-smoke-")),await $i(Se(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let d=await Ui();r=xi("python3",["-m","http.server",String(d),"--directory",o],{stdio:"ignore",shell:!1});let c=!1;r.on("error",()=>{c=!0}),r.on("exit",()=>{c=!0});let p=`http://127.0.0.1:${d}/`,a=!1;for(let b=0;b<24&&!c;b++)try{if((await fetch(p,{signal:AbortSignal.timeout(1e3)})).ok){a=!0;break}}catch{await new Promise(R=>setTimeout(R,500))}if(!a)return{ok:!1,stage:"python3-server",detail:"`python3 -m http.server` never came up on a free local port",remediation:process.platform==="win32"?"python3 on this machine isn't runnable (usually the Microsoft Store placeholder). Running `npx klaudius@latest update` fixes it automatically.":"Check `python3 --version` works in this terminal."};let y=Se(e,".klaudius"),E=await St(y).then(()=>!0,()=>!1);await Mi(y,{recursive:!0}),l=!E;let w=lt(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 g=lt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await St(s).catch(()=>null);if((!k||k.size===0)&&(g=lt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await St(s).catch(()=>null)),!k||k.size===0){let b=((g.stderr??"")+(g.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${b?` (${b})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{lt(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await Li(s).catch(()=>{}),l&&await Ni(Se(e,".klaudius")).catch(()=>{}),o&&await vi(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as ji,readFile as Ki,writeFile as Gi}from"fs/promises";import{join as Hn}from"path";async function dt(e,t){let n=Hn(e,".claude");await ji(n,{recursive:!0});let s=Hn(n,"settings.json"),o={};try{let c=await Ki(s,"utf-8"),p=JSON.parse(c);p&&typeof p=="object"&&!Array.isArray(p)&&(o=p)}catch{}let r=o.enabledMcpjsonServers,l=Array.isArray(r)?r.filter(c=>typeof c=="string"):[];l.includes(t)||l.push(t);let d={...o,enabledMcpjsonServers:l};await Gi(s,JSON.stringify(d,null,2)+`
|
|
26
|
+
`,"utf-8")}var Fn="0.29.1",N=5;function de(e){return`npx klaudius@latest init ${ut(Te(e))}`}function Te(e){if(process.platform==="win32")return e;let t=Bi();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Qi(e){let t=[];try{let s=(await Kn(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let r=W(e,o.name);if(!await jn(W(r,".env")))continue;let l=await jn(W(r,".klaudius","manifest.json"));if(t.push({path:r,finished:l}),t.length>=3)break}}catch{}return t}async function jn(e){try{return await It(e),!0}catch{return!1}}function ut(e){return/\s/.test(e)?`"${e}"`:e}function X(e,t,n){i.blank(),i.error(`${t} validation failed ${N} times in a row. Pausing setup so you don't get stuck in a loop.`),i.detail(`Last error: ${n}`),i.blank(),i.detail("Your credentials are saved in `.env`. Two ways forward:"),i.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),i.blank(),console.log(` ${f.cyan(de(e))}`),i.blank(),i.detail(` (Your .env is at ${Te(W(e,".env"))} \u2014 open it in any text editor.)`),i.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),i.blank(),process.exit(1)}async function Gn(e){let t=e.target??".",n=Yi(t)?t:Vi(process.cwd(),t),s=Xi(n);s&&(i.error("Klaudius can't be installed inside a protected system folder."),i.detail(`Path: ${n}`),i.detail(`Reason: ${s}`),i.blank(),i.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),i.blank(),process.platform==="win32"?(i.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${f.cyan("cd $HOME\\Documents")}`),console.log(` ${f.cyan("npx klaudius@latest init my-agency")}`)):(i.detail("For example:"),console.log(` ${f.cyan("cd ~/Documents")}`),console.log(` ${f.cyan("npx klaudius@latest init my-agency")}`)),i.blank(),process.exit(1)),process.platform==="win32"&&Zi()&&(i.warn("You appear to be running in an elevated (Administrator) PowerShell."),i.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),i.blank()),await et("init",Fn);let o=await qi(n);if(o.kind==="scaffolded"){i.blank(),i.warn(`Found an existing Klaudius project at ${f.bold(n)}.`),i.detail("(Your .env and project files are in place.)"),i.blank(),o.nodeModulesMissing?(i.detail("It looks like a previous setup didn't finish installing dependencies."),i.detail("To pick up where it left off, run:"),i.blank(),n!==process.cwd()&&console.log(` ${f.cyan(`cd ${ut(t)}`)}`),console.log(` ${f.cyan("npx klaudius@latest install")} ${f.dim("# retries npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${f.cyan("npx klaudius@latest doctor")} ${f.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Everything is scaffolded and dependencies look installed."),i.detail("Pick the action you wanted:"),i.blank(),console.log(` ${f.cyan("npx klaudius@latest doctor")} ${f.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${f.cyan("npx klaudius@latest configure")} ${f.dim("# change a credential / API key")}`),console.log(` ${f.cyan("npx klaudius@latest update")} ${f.dim("# pull the latest skills, scripts, lessons")}`),i.blank()),i.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),i.blank();return}if(o.kind==="occupied"){let u=t===".",m=await Qi(n);if(m.length>0){i.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),i.detail(`You're in: ${Te(n)}`),i.blank();for(let h of m)i.detail(h.finished?`Found a finished project at ${Te(h.path)}. To work in it:`:`Found an unfinished setup at ${Te(h.path)}. To pick up where it left off:`),i.blank(),h.finished?(console.log(` ${f.cyan(`cd ${Te(h.path)}`)}`),console.log(` ${f.cyan("claude")} ${f.dim("# open Claude Code in the project")}`)):console.log(` ${f.cyan(de(h.path))} ${f.dim("# then pick Resume")}`),i.blank();process.exit(1)}i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),i.blank(),u?(i.detail("Two ways forward:"),i.blank(),i.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${f.cyan("npx klaudius@latest init my-agency")}`),i.blank(),i.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${f.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(i.detail(`The folder '${t}' already exists and isn't empty.`),i.detail("Either pick a different name:"),console.log(` ${f.cyan(`npx klaudius@latest init ${t}-2`)}`),i.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=await Ji(e.license),l=P.spinner();l.start("Validating license");let d=await Sn(r);d.ok||(l.stop(`License invalid: ${d.reason??"unknown"}`,2),i.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),l.stop(`License valid (${d.tier??"core"} tier)`);let c=await ke();c.ok||(i.error(c.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${de(n)}`),process.exit(1)),await rt();let p=ie();p.ok||(i.error(p.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${de(n)}`),process.exit(1));let a,y=!1;if(o.kind==="partial")if(await zi(n)==="resume"){let m=await Un(o.envPath,"utf-8"),h=At(U(m));h?(i.success("Resuming with values from your existing .env"),i.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),a=h,y=!0,a.aiPlan||(a=await $(a,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
|
|
27
|
+
runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),a=await $())}else{let m=await Un(o.envPath,"utf-8"),h=At(U(m));a=await $(h??{})}else a=await $();a.licenseKey=r,await L(n,a),y||(i.success("Saved .env"),i.success(a.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let u=1;;u++){let m=P.spinner();m.start("Validating Supabase credentials");let h=await Pe({url:a.supabaseUrl,serviceKey:a.supabaseServiceKey});if(h.ok){m.stop("Supabase credentials accepted");break}m.stop(h.message??"Supabase check failed",2),u>=N&&X(n,"Supabase",h.message??"Supabase check failed");let A=h.message??"Supabase check failed";i.blank(),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${u+1} of ${N})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await $(a,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
28
|
+
${A}
|
|
29
29
|
|
|
30
30
|
Re-enter the URL, secret key, or PAT below. Press Enter on any
|
|
31
|
-
field to keep what's already there.`}),await L(n,a)}if(i.blank(),a.deployProvider==="cloudflare")for(let u=1;;u++){let m=
|
|
32
|
-
${
|
|
31
|
+
field to keep what's already there.`}),await L(n,a)}if(i.blank(),a.deployProvider==="cloudflare")for(let u=1;;u++){let m=P.spinner();m.start("Validating Cloudflare token + account");let h=await nt({token:a.cloudflareApiToken??"",accountId:a.cloudflareAccountId??""});if(h.ok){m.stop(`Cloudflare credentials accepted (${h.projectCount??0} existing Pages project${h.projectCount===1?"":"s"})`);break}m.stop(h.message??"Cloudflare check failed",2),u>=N&&X(n,"Cloudflare",h.message??"Cloudflare check failed");let A=h.message??"Cloudflare check failed";i.blank(),i.warn(`Bouncing you back into the Cloudflare section so you can fix it in place. (attempt ${u+1} of ${N})`),i.detail("(Press Enter on a field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await $(a,{onlySection:"cloudflare",banner:`Cloudflare rejected the credentials:
|
|
32
|
+
${A}
|
|
33
33
|
|
|
34
34
|
Re-enter the API token or Account ID below. The token needs the
|
|
35
35
|
"Account \u2192 Cloudflare Pages \u2192 Edit" permission. Press Enter to keep
|
|
36
|
-
the current value.`}),await L(n,a)}else if(a.deployProvider==="netlify")for(let u=1;;u++){let m=
|
|
37
|
-
${
|
|
36
|
+
the current value.`}),await L(n,a)}else if(a.deployProvider==="netlify")for(let u=1;;u++){let m=P.spinner();m.start("Validating Netlify token");let h=await st({token:a.netlifyAuthToken??""});if(h.ok){m.stop(h.accountSlug?`Netlify token accepted (team: ${h.accountSlug})`:"Netlify token accepted");break}m.stop(h.message??"Netlify check failed",2),u>=N&&X(n,"Netlify",h.message??"Netlify check failed");let A=h.message??"Netlify check failed";i.blank(),i.warn(`Bouncing you back into the Netlify section so you can fix it in place. (attempt ${u+1} of ${N})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await $(a,{onlySection:"netlify",banner:`Netlify rejected the token:
|
|
37
|
+
${A}
|
|
38
38
|
|
|
39
39
|
Generate a new token at
|
|
40
40
|
https://app.netlify.com/user/applications#personal-access-tokens
|
|
41
|
-
and paste it below. Press Enter to keep the current value.`}),await L(n,a)}else if(a.deployProvider==="selfhost")for(let u=1;;u++){let m=
|
|
42
|
-
`);u>=
|
|
43
|
-
${
|
|
41
|
+
and paste it below. Press Enter to keep the current value.`}),await L(n,a)}else if(a.deployProvider==="selfhost")for(let u=1;;u++){let m=Me(a.selfhostDeployTarget??""),h=De(a.selfhostUrlTemplate??"");if(!m&&!h){i.success("Self-host deploy configured (SSH reachability is tested at your first deploy)");break}let A=[m&&`SELFHOST_DEPLOY_TARGET: ${m}`,h&&`SELFHOST_URL_TEMPLATE: ${h}`].filter(Boolean).join(`
|
|
42
|
+
`);u>=N&&X(n,"Self-host",A),i.blank(),i.warn(`Bouncing you back into the self-host section so you can fix it in place. (attempt ${u+1} of ${N})`),i.blank(),a=await $(a,{onlySection:"selfhost",banner:`The self-host deploy settings look wrong:
|
|
43
|
+
${A}
|
|
44
44
|
|
|
45
|
-
Re-enter them below. Press Enter on a field to keep its current value.`}),await L(n,a)}else for(let u=1;;u++){let m=
|
|
46
|
-
${
|
|
45
|
+
Re-enter them below. Press Enter on a field to keep its current value.`}),await L(n,a)}else for(let u=1;;u++){let m=P.spinner();m.start("Validating Vercel token");let h=await tt(a.vercelToken??"");if(h.ok){m.stop(h.username?`Vercel token accepted (signed in as ${h.username})`:"Vercel token accepted");break}m.stop(h.message??"Vercel check failed",2),u>=N&&X(n,"Vercel",h.message??"Vercel check failed");let A=h.message??"Vercel check failed";i.blank(),i.warn(`Bouncing you back into the Vercel section so you can fix it in place. (attempt ${u+1} of ${N})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await $(a,{onlySection:"vercel",banner:`Vercel rejected the token:
|
|
46
|
+
${A}
|
|
47
47
|
|
|
48
48
|
Generate a new token at https://vercel.com/account/tokens and
|
|
49
|
-
paste it below. Press Enter to keep the current value.`}),await L(n,a)}i.blank();for(let u=1;;u++){let m=se(a.googlePlacesApiKey??""),h=
|
|
50
|
-
${
|
|
49
|
+
paste it below. Press Enter to keep the current value.`}),await L(n,a)}i.blank();for(let u=1;;u++){let m=se(a.googlePlacesApiKey??""),h=P.spinner();h.start("Validating Google Places API key");let A=await Ee(a.googlePlacesApiKey??"");if(A.ok){if(h.stop("Google Places API key accepted"),m.changed){if(m.repairs.length>0){i.blank(),i.warn("Corrected look-alike characters in your Google Places API key:");for(let _ of m.repairs)i.detail(` ${_}`);i.detail("These come from keys that were transcribed rather than copied."),i.detail("Google accepted the corrected key, and .env now holds it.")}a.googlePlacesApiKey=m.value,await L(n,a)}break}h.stop(A.message??"Google Places check failed",2),u>=N&&X(n,"Google Places",A.message??"Google Places check failed");let S=A.message??"Google Places check failed";i.blank(),i.warn(`Bouncing you back into the Google Places section so you can fix it in place. (attempt ${u+1} of ${N})`),i.detail("(Press Enter on the field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await $(a,{onlySection:"google-places",banner:`Google rejected the key:
|
|
50
|
+
${S}
|
|
51
51
|
|
|
52
52
|
Generate (or fix) the key at https://console.cloud.google.com
|
|
53
|
-
and paste it below. Press Enter to keep the current value.`}),await L(n,a)}let
|
|
53
|
+
and paste it below. Press Enter to keep the current value.`}),await L(n,a)}let E=!1;if(a.outreachEnabled&&a.outreachChannels?.includes("email")&&a.emailAddress&&a.emailPassword&&a.emailSmtpHost&&a.emailSmtpPort&&a.emailImapHost&&a.emailImapPort){i.blank();let u=0,m=!1,h;for(;!m;){u++;let A=P.spinner();A.start("Validating email credentials (SMTP + IMAP)");let S=a.emailProvider&&a.emailProvider!=="custom"?a.emailProvider:fe(a.emailSmtpHost),_=S?Y[S]:void 0,x=await J({emailAddress:a.emailAddress,emailPassword:a.emailPassword,emailSmtpHost:a.emailSmtpHost,emailSmtpPort:a.emailSmtpPort,emailImapHost:a.emailImapHost,emailImapPort:a.emailImapPort,usesAccountPassword:_?.usesAccountPassword});if(x.ok){A.stop("Email credentials accepted (SMTP + IMAP)");break}A.stop(x.message??"Email check failed",2);let ne=`${S}\0${a.emailAddress}\0${a.emailPassword}`;if(_&&x.failureKind!=="network"&&h!==ne){h=ne;let ae=Le(S,a.emailSmtpHost,a.emailImapHost),re,Dt=0;if(ae.length>0){i.blank(),i.warn(`That server rejected the login. ${_.label} runs several regional servers \u2014 trying the others with the same credentials...`);for(let K of ae){let mt=P.spinner();mt.start(`Trying ${K.label} (${K.smtpHost})`);let gt=await J({emailAddress:a.emailAddress,emailPassword:a.emailPassword,emailSmtpHost:K.smtpHost,emailSmtpPort:a.emailSmtpPort,emailImapHost:K.imapHost,emailImapPort:a.emailImapPort});if(gt.ok){mt.stop(`${K.label}: your login works here (${K.smtpHost})`),re=K;break}gt.failureKind!=="network"&&Dt++,mt.stop(gt.failureKind==="network"?`${K.label}: unreachable`:`${K.label}: rejected too`,2)}}if(re){i.blank(),i.success("Found it \u2014 your password was right all along; the server was the only problem.");let K=await P.confirm({message:`Use the ${re.label} servers (${re.smtpHost} / ${re.imapHost})?`,initialValue:!0});if(P.isCancel(K)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
54
54
|
|
|
55
55
|
${de(n)}
|
|
56
|
-
`),process.exit(0)),
|
|
56
|
+
`),process.exit(0)),K){a.emailSmtpHost=re.smtpHost,a.emailImapHost=re.imapHost,await L(n,a);continue}}else ae.length>0&&(i.blank(),Dt===0?i.warn("Couldn't reach any of the alternate servers \u2014 this looks like a network problem, not a credential problem. Check your connection and retry."):_.noAltWorkedHint&&i.warn(_.noAltWorkedHint))}let Re=x.message??"Email check failed";i.blank(),i.warn("Email isn't required to finish setup \u2014 the rest of Klaudius (finding businesses, building, deploying) works without it."),i.detail("You can skip it now and wire it up later from inside the project."),i.blank();let ht=await P.select({message:`What would you like to do? ${f.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:u>=3?"skip":u>=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(P.isCancel(ht)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
57
57
|
|
|
58
58
|
${de(n)}
|
|
59
|
-
`),process.exit(0)),
|
|
60
|
-
${
|
|
59
|
+
`),process.exit(0)),ht==="skip"){a.outreachChannels=(a.outreachChannels??[]).filter(ae=>ae!=="email"),a.outreachPriority=(a.outreachPriority??[]).filter(ae=>ae!=="email"),a.outreachChannels.length===0&&(a.outreachEnabled=!1),await L(n,a),E=!0,i.success("Skipped email for now. Setup will continue."),a.outreachEnabled?i.detail("Outreach will use your other channel(s); email stays off until it's fixed."):i.detail("Automated outreach is off until email is fixed \u2014 everything else works."),m=!0;break}ht==="edit"&&(i.blank(),a=await $(a,{onlySection:"email",banner:`${x.failedAt==="imap"?"IMAP":"SMTP"} check failed:
|
|
60
|
+
${Re}
|
|
61
61
|
|
|
62
62
|
Re-enter the email address, app password, or server details below.
|
|
63
63
|
Press Enter on any field to keep its current value.
|
|
64
64
|
|
|
65
65
|
Tip: to change the SMTP/IMAP servers, pick "Enter servers manually"
|
|
66
|
-
at the "Server settings" question.`}),await L(n,a))}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="twilio"&&a.twilioAccountSid&&a.twilioAuthToken){i.blank();for(let u=1;;u++){let m=
|
|
67
|
-
${
|
|
66
|
+
at the "Server settings" question.`}),await L(n,a))}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="twilio"&&a.twilioAccountSid&&a.twilioAuthToken){i.blank();for(let u=1;;u++){let m=P.spinner();m.start("Validating Twilio credentials");let h=await On({accountSid:a.twilioAccountSid,authToken:a.twilioAuthToken});if(h.ok){m.stop(h.friendlyName?`Twilio credentials accepted (${h.friendlyName})`:"Twilio credentials accepted");break}m.stop(h.message??"Twilio check failed",2),u>=N&&X(n,"Twilio",h.message??"Twilio check failed");let A=h.message??"Twilio check failed";i.blank(),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${N})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await $(a,{onlySection:"sms",banner:`Twilio rejected the credentials:
|
|
67
|
+
${A}
|
|
68
68
|
|
|
69
69
|
Re-enter the Account SID or Auth Token below.
|
|
70
|
-
Press Enter on any field to keep its current value.`}),await L(n,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("letter")&&a.letterProvider){i.blank();for(let u=1;;u++){let m=
|
|
71
|
-
${
|
|
70
|
+
Press Enter on any field to keep its current value.`}),await L(n,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("letter")&&a.letterProvider){i.blank();for(let u=1;;u++){let m=P.spinner();m.start("Validating letter provider credentials");let h=await it({provider:a.letterProvider,pingenClientId:a.pingenClientId,pingenClientSecret:a.pingenClientSecret,pingenOrgId:a.pingenOrgId,postgridApiKey:a.postgridApiKey});if(h.ok){m.stop(h.friendlyName?`Letter provider credentials accepted (${h.friendlyName})`:"Letter provider credentials accepted");break}m.stop(h.message??"Letter provider check failed",2),u>=N&&X(n,"Letter provider",h.message??"Letter provider check failed");let A=h.message??"Letter provider check failed";i.blank(),i.warn(`Bouncing you back into the letter section so you can fix it in place. (attempt ${u+1} of ${N})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await $(a,{onlySection:"letter",banner:`The letter provider rejected the credentials:
|
|
71
|
+
${A}
|
|
72
72
|
|
|
73
73
|
Re-enter them below.
|
|
74
|
-
Press Enter on any field to keep its current value.`}),await L(n,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="imessage"&&a.testPhone){i.blank();for(let u=1;;u++){let m=
|
|
75
|
-
${
|
|
74
|
+
Press Enter on any field to keep its current value.`}),await L(n,a)}}if(a.outreachEnabled&&a.outreachChannels?.includes("sms")&&a.smsProvider==="imessage"&&a.testPhone){i.blank();for(let u=1;;u++){let m=P.spinner();m.start("Validating iMessage setup (sending a test ping)");let h=await vn({testPhone:a.testPhone});if(h.ok){m.stop("iMessage dispatched (check your phone for the test ping)");break}m.stop(h.message??"iMessage check failed",2),u>=N&&X(n,"iMessage",h.message??"iMessage check failed");let A=h.message??"iMessage check failed";i.blank(),i.warn(`Bouncing you back into the SMS section so you can fix it in place. (attempt ${u+1} of ${N})`),i.detail("(Press Enter on any field to keep its current value. Ctrl+C to exit.)"),i.blank(),a=await $(a,{onlySection:"sms",banner:`iMessage check failed:
|
|
75
|
+
${A}
|
|
76
76
|
|
|
77
77
|
Either fix the underlying issue (sign in to Messages.app, configure
|
|
78
78
|
Text Message Forwarding) and press Enter through, or change SMS
|
|
79
|
-
provider to Twilio.`}),await L(n,a)}}if((a.notifyChannel??"telegram")==="telegram"&&a.telegramBotToken&&a.telegramChatId){i.blank();let u=0,m=!1;for(;!m;){u++;let h=
|
|
79
|
+
provider to Twilio.`}),await L(n,a)}}if((a.notifyChannel??"telegram")==="telegram"&&a.telegramBotToken&&a.telegramChatId){i.blank();let u=0,m=!1;for(;!m;){u++;let h=P.spinner();h.start("Validating Telegram bot + chat (sending a test ping)");let A=await Ut({botToken:a.telegramBotToken,chatId:a.telegramChatId});if(A.ok){h.stop(A.botHandle?`Telegram bot ${A.botHandle} accepted, test message delivered`:"Telegram credentials accepted, test message delivered"),m=!0;break}h.stop(A.message??"Telegram check failed",2);let S=A.message??"Telegram check failed";i.blank(),i.warn("Telegram is optional \u2014 you can skip it now and wire it up later by editing `.env`."),i.blank();let _=await P.select({message:`What would you like to do? ${f.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:u>=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(P.isCancel(_)&&(P.cancel(`Setup cancelled. Your .env is saved \u2014 resume with:
|
|
80
80
|
|
|
81
81
|
${de(n)}
|
|
82
|
-
`),process.exit(0)),
|
|
83
|
-
${
|
|
82
|
+
`),process.exit(0)),_==="skip"){a.telegramBotToken=void 0,a.telegramChatId=void 0,await L(n,a),i.success("Skipped Telegram. Setup will continue."),i.detail("Wire it up later by pasting your bot token and chat ID into the TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID lines of `.env`."),m=!0;break}if(_==="edit"&&(i.blank(),a=await $(a,{onlySection:"notifications",banner:`Telegram check failed:
|
|
83
|
+
${S}
|
|
84
84
|
|
|
85
85
|
Re-enter the bot token or chat_id below.
|
|
86
|
-
Press Enter on any field to keep its current value.`}),await L(n,a),(a.notifyChannel??"telegram")!=="telegram"||!a.telegramBotToken||!a.telegramChatId)){i.success("Skipped Telegram. Setup will continue."),m=!0;break}}}i.blank();let
|
|
86
|
+
Press Enter on any field to keep its current value.`}),await L(n,a),(a.notifyChannel??"telegram")!=="telegram"||!a.telegramBotToken||!a.telegramChatId)){i.success("Skipped Telegram. Setup will continue."),m=!0;break}}}i.blank();let w=P.spinner();w.start("Downloading Klaudius template");let g;try{g=(await Je({licenseKey:r,machineId:ve(),hostname:process.platform==="win32"?process.env.COMPUTERNAME:void 0,os:`${process.platform}-${process.arch}`,agent:a.aiAgent,destDir:n})).filesExtracted,w.stop(`Downloaded ${g} files into ${f.bold(n)}`)}catch(u){w.stop(u.message,2);let m=a.aiAgent==="codex"?".codex/config.toml":".mcp.json";i.detail(`Your .env / ${m} are saved. Re-run init once the issue is resolved to retry the download.`),process.exit(1)}await _t(W(n,"clients"),{recursive:!0});let k=await dn(n);await Oe(n,ln(Fn,k)),i.success("Wrote .klaudius/manifest.json");try{await Ze(n,n,Object.keys(k))}catch{}let b=!1,R="";if(e.skipSchema)i.warn("--skip-schema set; not applying scripts/schema.sql to your Supabase project."),i.detail(`Apply manually later via the SQL editor: ${a.supabaseUrl.replace("https://","https://supabase.com/dashboard/project/"+a.supabaseProjectRef+"/sql/new").replace(a.supabaseProjectRef+".supabase.co","")}`);else{i.blank();let u=P.spinner();u.start("Applying schema to Supabase");let m=await Tn({projectRoot:n,pat:a.supabasePat,projectRef:a.supabaseProjectRef});m.ok?u.stop("Schema applied (or already present)"):(u.stop(m.message??"Schema apply failed",2),b=!0,R=`https://supabase.com/dashboard/project/${a.supabaseProjectRef}/sql/new`)}let I=[],Q={};if(e.skipInstall)i.warn("--skip-install set; you'll need to run npm install + pip install + playwright/patchright install yourself.");else{i.blank(),i.heading("Installing dependencies");let u=await at(n);if(i.detail(`npm: ${u.npm}, pip: ${u.pip}, playwright: ${u.playwright}, patchright: ${u.patchright}`),u.npm==="failed"&&I.push("npm"),u.pip==="failed"&&I.push("pip"),u.playwright==="failed"&&I.push("playwright"),u.patchright==="failed"&&I.push("patchright"),Q=u.hints??{},u.npm!=="failed"&&u.playwright!=="failed"){i.step("Checking the QA screenshot chain (serving a test page and screenshotting it)\u2026");let m=await ct(n);m.ok?i.success("QA screenshot chain verified (local page served and screenshotted)."):(i.warn(`QA screenshot chain check failed${m.stage?` (${m.stage})`:""}: ${m.detail??"unknown"}`),m.remediation&&i.detail(m.remediation))}}let V=a.outreachEnabled&&a.outreachPriority?.includes("whatsapp")&&(a.whatsappAccounts?.length??0)>0,T=!e.skipInstall&&!I.includes("npm");if(V&&T){i.blank(),i.heading("Linking WhatsApp accounts"),console.log(f.dim(`You'll be prompted to scan one QR per linked number. Open WhatsApp on the
|
|
87
87
|
phone whose number you want to link, then Settings \u2192 Linked Devices \u2192
|
|
88
|
-
Link a Device, and point it at the QR shown in this terminal.`)),i.blank();for(let u of a.whatsappAccounts){console.log(f.cyan(`Pairing WhatsApp account '${u}'...`)),console.log(f.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${u})`));let m=
|
|
88
|
+
Link a Device, and point it at the QR shown in this terminal.`)),i.blank();for(let u of a.whatsappAccounts){console.log(f.cyan(`Pairing WhatsApp account '${u}'...`)),console.log(f.dim(`(Ctrl-C abandons init but your .env is already saved \u2014 finish later via: npx klaudius@latest pair-whatsapp --label ${u})`));let m=Ct(process.execPath,["scripts/whatsapp.mjs","pair","--account",u],{cwd:n,stdio:"inherit"});m.status===0?i.detail(`Paired '${u}'.`):(console.log(f.yellow(`'${u}' did not pair (exit ${m.status??"signalled"}). You can finish later via:`)),console.log(f.cyan(` npx klaudius@latest pair-whatsapp --label ${u}`))),i.blank()}}else if(V&&!T){i.blank(),console.log(f.yellow("Skipping WhatsApp pairing \u2014 baileys isn't installed yet (npm install failed earlier or was skipped).")),console.log(f.dim("Once `npx klaudius@latest install` completes successfully, pair via:"));for(let u of a.whatsappAccounts)console.log(f.cyan(` npx klaudius@latest pair-whatsapp --label ${u}`))}let te=a.emailAuth==="oauth-microsoft"&&a.outreachEnabled&&a.outreachChannels?.includes("email"),D=!e.skipInstall&&!I.includes("pip"),pe=u=>{console.log(f.dim("Connect it any time from the project folder with:")),console.log(f.cyan(` ${u?u.command.join(" "):"python3"} scripts/ms_oauth.py login`)),console.log(f.dim(" (on a remote/browser-less machine, add: --device-code)"))};if(te&&D){i.blank(),i.heading("Connecting your Outlook / Microsoft 365 mailbox"),console.log(f.dim(`Microsoft mailboxes connect with a one-time browser sign-in instead of a
|
|
89
89
|
password. Your browser will open to Microsoft's sign-in page \u2014
|
|
90
90
|
sign in as `+(a.emailAddress??"your outreach mailbox")+` and approve.
|
|
91
91
|
(No browser on this machine? It falls back to a short code you can
|
|
92
|
-
enter from any device.)`)),i.blank();let u=await
|
|
93
|
-
`:"",m=a.aiAgent==="codex"?"codex":"claude",h=a.aiAgent==="codex"?"Codex":"Claude Code",w=a.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";T.length>0&&(console.log(f.dim(`Easiest fix \u2014 let ${h} finish it for you:`)),i.blank(),u&&process.stdout.write(u),console.log(` ${f.cyan(m)} ${f.dim(`# open ${h} in this folder`)}`),console.log(f.dim(" Then paste:")),console.log(f.cyan(` "Finish my Klaudius install \u2014 ${T.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(f.dim(` (Don't have ${h} yet? Install with: \`${w}\`)`)),i.blank(),console.log(f.dim("Or do it yourself:")),i.blank(),u&&process.stdout.write(u),console.log(` ${f.cyan("npx klaudius@latest install")} ${f.dim("# retry the failing installers")}`),console.log(` ${f.cyan("npx klaudius@latest doctor")} ${f.dim("# verify everything")}`),i.blank()),v&&(console.log(f.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${f.cyan($)}`),console.log(f.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),T.includes("pip")&&!W.pip&&(console.log(f.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(f.dim(`Python 3.10+. Install a newer one from ${Ri()}`)),console.log(f.dim("and open a fresh Terminal before retrying.")),i.blank());let b=["npm","playwright","patchright"].filter(C=>T.includes(C)&&!W[C]);if(b.length>0){let C=b.length===1?"keeps":"keep";console.log(f.dim(`If ${b.join(" / ")} ${C} failing with network errors (ECONNRESET,`)),console.log(f.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(f.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}g&&(console.log(f.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${h}`)),console.log(f.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(f.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Oi(a,n,e.target),g){let u=a.aiAgent==="codex"?"Codex":"Claude Code";console.log(f.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(f.dim(`Your details are saved in .env. To finish it, ask ${u}:`)),console.log(f.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(f.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(f.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(f.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(f.cyan(' and send a test email to my own address to confirm."')),a.outreachEnabled&&(a.outreachChannels??[]).length>0&&(i.blank(),console.log(f.yellow(`Note: your other channel(s) \u2014 ${(a.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),i.blank()}}async function L(e,t){await kt(e,{recursive:!0}),await yt(V(e,".env"),Fe(t),"utf-8"),t.aiAgent==="codex"?(await kt(V(e,".codex"),{recursive:!0}),await yt(V(e,".codex","config.toml"),Ge(t),"utf-8")):(await yt(V(e,".mcp.json"),Ke(t),"utf-8"),await st(e,"supabase"))}async function bi(e){try{(await wt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await vn(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(c=>s.has(c)),r=n.includes(".env"),l=t.includes(".klaudius");if(o&&r&&!l)return{kind:"partial",envPath:V(e,".env")};if(l&&r){let c=!0;try{c=!(await wt(V(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function _i(e){i.blank(),i.warn(`Found a partial setup at ${f.bold(e)}.`),i.detail(`A previous init wrote ${f.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await A.select({message:`How would you like to proceed? ${f.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 A.isCancel(t)&&(A.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Ti(e){if(e&&e.trim().length>0)return e;A.intro("Klaudius");let t=await A.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 A.isCancel(t)&&(A.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Ii(e){let t=Pi(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let s of n)if(t.startsWith(s))return`Inside ${s.slice(0,-1)} (system-managed directory).`}}function Ci(){if(process.platform!=="win32")return!1;try{return At("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Ri(){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 Oi(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(A.outro(f.green(f.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??he(e.aiPlan))==="off";console.log(`${f.bold("Your plan:")} ${Le[e.aiPlan]}`),console.log(f.dim(r?` \u2192 QA pass off${e.aiPlan==="codex-plus"&&e.aiAgent==="codex"?", model pinned to Terra":""}, so each run fits your usage window.`:" \u2192 full pipeline, including the independent QA pass after every build.")),console.log(f.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),i.blank()}if(console.log(f.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let r=`cd ${it(n)}`;console.log(` ${f.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${f.dim("# go into your project folder")}`)}console.log(` ${f.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${f.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(f.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${f.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${f.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${f.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${f.cyan('"Run the pipeline for one client."')}`),console.log(f.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),i.blank(),e.aiAgent!=="codex"&&(console.log(f.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(f.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as xi,readFile as Ni}from"fs/promises";import{join as Et,resolve as vi}from"path";import j from"picocolors";async function Mn(e){let t=e.target?vi(process.cwd(),e.target):process.cwd(),n=await $n(Et(t,".env")),s=await $n(Et(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{U(await Ni(Et(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await nt(t);i.blank(),i.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let l=[];if(r.npm==="failed"&&l.push("npm"),r.pip==="failed"&&l.push("pip"),r.playwright==="failed"&&l.push("playwright"),r.patchright==="failed"&&l.push("patchright"),l.length===0){i.blank(),console.log(j.green(j.bold("All dependencies installed."))),console.log(j.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(j.yellow(j.bold(`${l.join(", ")} still failing.`))),i.blank();for(let[a,y]of Object.entries(r.hints??{}))console.log(j.yellow(`Likely cause of ${a} failure:`)),console.log(j.dim(` ${y}`)),i.blank();let c=o==="codex"?"codex":"claude",d=o==="codex"?"Codex":"Claude Code",p=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(j.dim("Options:")),console.log(j.dim(` \u2022 Open ${d} in this folder (\`${c}\`) and paste:`)),console.log(j.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(j.dim(` (Don't have ${d} yet? Install with: \`${p}\`)`)),console.log(j.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(j.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function $n(e){try{return await xi(e),!0}catch{return!1}}import{readFile as Li,writeFile as Pt,access as $i}from"fs/promises";import{join as _e}from"path";import*as q from"@clack/prompts";import J from"picocolors";import{mkdir as Mi}from"fs/promises";import{spawnSync as Dn}from"child_process";async function Hn(e){let t=e.projectRoot??process.cwd(),n=_e(t,".env"),s=_e(t,".mcp.json"),o=_e(t,".codex","config.toml"),r=await St(_e(t,".klaudius","manifest.json")),l=await St(n);!r&&!l&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ie();c.ok||(i.error(c.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let d={};try{let k=await Li(n,"utf-8");d=U(k)}catch{i.warn("No .env found. Starting from an empty configuration.")}let p=zt(d);Object.keys(d).length>0&&(p.pipelineModes??=["classic"]),q.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let a=await N(p),y=p.aiAgent??"claude-code";if(a.aiAgent&&a.aiAgent!==y&&(i.error(`Switching AI coding agent (${y} \u2192 ${a.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${J.cyan("npx klaudius@latest init <new-folder>")} ${J.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),a.supabaseUrl!==d.SUPABASE_URL||a.supabaseServiceKey!==d.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let k=await Ee({url:a.supabaseUrl,serviceKey:a.supabaseServiceKey});k.ok||(i.error(k.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let g=se(a.googlePlacesApiKey??"");if(g.changed&&a.googlePlacesApiKey){i.heading("Checking your Google Places API key");let k=await Pe(a.googlePlacesApiKey);if(k.ok){if(g.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let P of g.repairs)i.detail(` ${P}`);i.detail("These come from keys that were transcribed rather than copied.")}a.googlePlacesApiKey=g.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(k.message??"Google rejected the Google Places API key"),i.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),i.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Di(a,d)){let k=q.spinner();k.start("Validating email credentials (SMTP + IMAP)");let P=a.emailProvider&&a.emailProvider!=="custom"?a.emailProvider:fe(a.emailSmtpHost),_=await Q({emailAddress:a.emailAddress,emailPassword:a.emailPassword,emailSmtpHost:a.emailSmtpHost,emailSmtpPort:a.emailSmtpPort,emailImapHost:a.emailImapHost,emailImapPort:a.emailImapPort,usesAccountPassword:P?B[P].usesAccountPassword:void 0});_.ok?k.stop("Email credentials accepted (SMTP + IMAP)"):(k.stop(_.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(_.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 Pt(n,Fe(a),"utf-8"),i.success("Updated .env"),a.aiAgent==="codex"?(await Mi(_e(t,".codex"),{recursive:!0}),await Pt(o,Ge(a),"utf-8"),i.success("Updated .codex/config.toml")):(await Pt(s,Ke(a),"utf-8"),i.success("Updated .mcp.json"),await st(t,"supabase")),a.emailAuth==="oauth-microsoft"&&a.outreachEnabled&&a.outreachChannels?.includes("email")){let k=await z();if(!(k!==null&&Dn(k.command[0],[...k.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!k)i.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),i.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let _=await q.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});q.isCancel(_)||!_?i.detail(`Skipped. Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`):Dn(k.command[0],[...k.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?i.success("Outlook mailbox connected."):(i.warn("The Microsoft sign-in didn't complete."),i.detail(`Connect it any time with: ${k.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),q.outro(J.green("Configuration updated.")),await Hi(t,r)}function Di(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([s])=>s===void 0||s==="")?!1:n.some(([s,o])=>String(s)!==(t[o]??""))}async function Hi(e,t){let n=await St(_e(e,"node_modules"));i.blank(),t?n||(i.detail("Your project files are in place but dependencies aren't installed yet."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${J.cyan("npx klaudius@latest install")} ${J.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${J.cyan("npx klaudius@latest doctor")} ${J.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${J.cyan("npx klaudius@latest init")} ${J.dim("# pick Resume when prompted")}`),i.blank())}async function St(e){try{return await $i(e),!0}catch{return!1}}import{copyFile as Un,mkdir as bt,readFile as ot,rm as ue,writeFile as at,access as jn}from"fs/promises";import{dirname as _t,join as O}from"path";import{tmpdir as Ui}from"os";import*as Te from"@clack/prompts";import Tt from"picocolors";var rt="0.28.0";async function Fn(e){let t=e.projectRoot??process.cwd(),n=await Zt(t);n||(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let u of Be)delete n.files[u];let s,o=O(t,".env"),r,l;try{r=await ot(o,"utf-8"),l=U(r)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=l.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=Wt(r,l,Yt);c!==null&&(await at(o,c,"utf-8"),i.detail("Backfilled new env keys")),await Qe("update",rt),Te.intro(`Update from ${n.templateVersion} \u2192 ${rt}`);let p=l.AI_AGENT==="codex"?"codex":"claude-code",a=O(Ui(),`klaudius-update-${process.pid}-${Date.now()}`),y;try{i.heading("Downloading the latest Klaudius template");let u=await We({licenseKey:s,machineId:Oe(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:a});i.success(`Fetched ${u.filesExtracted} canonical files`),y=a}catch(u){i.error(u.message),i.detail("Update aborted. Your project is unchanged."),await ue(a,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let g=await ji(y,t,n),k=!1,P=g.find(u=>u.path===".gitignore"&&u.state==="conflict");if(P){let u=O(t,".gitignore"),m=await ot(u,"utf-8"),h=await ot(O(y,".gitignore"),"utf-8"),{merged:w,added:E}=Fi(m,h);E.length>0&&await at(u,w,"utf-8"),n.files[".gitignore"]=P.canonicalHash,P.state="gitignore-merged",k=!0,i.detail(E.length>0?`.gitignore auto-merged: kept all your lines, appended ${K(E.length,"new canonical pattern")}: ${E.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let _=g.filter(u=>u.state==="new"),v=g.filter(u=>u.state==="clean-update"),$=g.filter(u=>u.state==="user-only"),T=g.filter(u=>u.state==="conflict"),W=g.filter(u=>u.state==="no-change"),G=g.filter(u=>u.state==="locally-deleted"),S=g.filter(u=>u.state==="removed-clean"),te=g.filter(u=>u.state==="removed-modified"),H=[...T,...G,...te],pe=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${K(W.length,"file")} unchanged`),i.detail(`${K(_.length,"new file")}`),i.detail(`${K(v.length,"file")} updated cleanly (no local edits)`),i.detail(`${K($.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${K(S.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${K(T.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${K(G.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${K(te.length,"file")} removed upstream but edited locally (need your decision)`),pe>0&&(i.detail(`${K(pe,"file")} kept deleted (previously resolved \u2014 skipped)`),pe<=10))for(let u of n.ignored)i.detail(` kept deleted: ${u}`);let Ie=async()=>{let u=!1,m=h=>ue(h,{recursive:!0,force:!0}).catch(()=>{u=!0});await m(O(t,".klaudius","incoming")),await m(O(t,ze)),await m(O(t,".klaudius","conflicts.md")),u&&i.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(_.length===0&&v.length===0&&S.length===0&&H.length===0&&!k){await Ie(),i.blank(),Te.outro(Tt.green("Already up to date.")),await ue(a,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let u of[..._,...v]){let m=O(y,u.path),h=O(t,u.path);await bt(_t(h),{recursive:!0}),await Un(m,h),n.files[u.path]=u.canonicalHash}_.length+v.length>0&&i.success(`Wrote ${K(_.length+v.length,"file")}`);for(let u of S){let m=O(t,u.path);await ue(m,{force:!0}),delete n.files[u.path]}if(S.length>0&&i.success(`Deleted ${K(S.length,"file")} removed upstream`),H.length>0){i.blank(),i.heading(`${H.length} conflict(s) need resolution`);let u=O(t,".klaudius","incoming");try{await ue(u,{recursive:!0,force:!0})}catch{}for(let E of[...T,...G]){let b=O(y,E.path),C=O(u,E.path);await bt(_t(C),{recursive:!0}),await Un(b,C)}let m=new Map,h=new Map;for(let E of T){let b=await dn(t,E.path),C=await un(t,E.path),ne=await ot(O(y,E.path),"utf-8"),Ce=pn(b,C,ne,E.manifestHash);Ce!==null?(h.set(E.path,Ce),m.set(E.path,fn(Ce,ne))):b!==null&&(Ae(b)||Ae(ne))?m.set(E.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+E.path+"` directly._"]):b===null?m.set(E.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._"]):m.set(E.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/"+E.path+"` directly._"])}let w=O(t,ze);try{await ue(w,{recursive:!0,force:!0})}catch{}for(let[E,b]of h){let C=O(w,E);await bt(_t(C),{recursive:!0}),await at(C,b,"utf-8")}await at(O(t,".klaudius","conflicts.md"),Ki(H,n.templateVersion,rt,m,h),"utf-8"),T.length+G.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),h.size>0&&i.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),H.length===0&&(n.templateVersion=rt,await Ie()),await Ve(t,n);try{await qe(t,y,await le(y))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),H.length===0)Te.outro(Tt.green("Update complete."));else{let u=p==="codex"?"Codex":"Claude Code";Te.outro(Tt.yellow(`${H.length} conflict(s) staged. Open ${u} in this project and ask:
|
|
94
|
-
"Run /resolve-conflicts"`))}await ue(a,{recursive:!0,force:!0}).catch(()=>{})}async function
|
|
92
|
+
enter from any device.)`)),i.blank();let u=await G();if(u){let[m,...h]=u.command,A=Ct(m,[...h,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});A.status===0?i.success("Outlook mailbox connected."):(i.blank(),console.log(f.yellow(`The Microsoft sign-in didn't complete (exit ${A.status??"signalled"}). Setup continues without it.`)),pe(u))}else console.log(f.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),pe(null)}else te&&!D&&(i.blank(),console.log(f.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(f.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(f.cyan(" python3 scripts/ms_oauth.py login")));i.blank();let Ce=[...I,...b?["schema"]:[]];if(Ce.length>0){P.outro(f.yellow(f.bold(`Setup paused \u2014 ${Ce.join(", ")} failed.`))),console.log(f.dim("Your credentials and project files are all saved.")),i.blank();for(let[x,ne]of Object.entries(Q))console.log(f.yellow(`Likely cause of ${x} failure:`)),console.log(f.dim(` ${ne}`)),i.blank();let u=n!==process.cwd()&&e.target?` ${f.cyan(`cd ${ut(e.target)}`)}
|
|
93
|
+
`:"",m=a.aiAgent==="codex"?"codex":"claude",h=a.aiAgent==="codex"?"Codex":"Claude Code",A=a.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";I.length>0&&(console.log(f.dim(`Easiest fix \u2014 let ${h} finish it for you:`)),i.blank(),u&&process.stdout.write(u),console.log(` ${f.cyan(m)} ${f.dim(`# open ${h} in this folder`)}`),console.log(f.dim(" Then paste:")),console.log(f.cyan(` "Finish my Klaudius install \u2014 ${I.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(f.dim(` (Don't have ${h} yet? Install with: \`${A}\`)`)),i.blank(),console.log(f.dim("Or do it yourself:")),i.blank(),u&&process.stdout.write(u),console.log(` ${f.cyan("npx klaudius@latest install")} ${f.dim("# retry the failing installers")}`),console.log(` ${f.cyan("npx klaudius@latest doctor")} ${f.dim("# verify everything")}`),i.blank()),b&&(console.log(f.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${f.cyan(R)}`),console.log(f.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),I.includes("pip")&&!Q.pip&&(console.log(f.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(f.dim(`Python 3.10+. Install a newer one from ${eo()}`)),console.log(f.dim("and open a fresh Terminal before retrying.")),i.blank());let _=["npm","playwright","patchright"].filter(x=>I.includes(x)&&!Q[x]);if(_.length>0){let x=_.length===1?"keeps":"keep";console.log(f.dim(`If ${_.join(" / ")} ${x} failing with network errors (ECONNRESET,`)),console.log(f.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(f.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}E&&(console.log(f.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${h}`)),console.log(f.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(f.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(to(a,n,e.target),E){let u=a.aiAgent==="codex"?"Codex":"Claude Code";console.log(f.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(f.dim(`Your details are saved in .env. To finish it, ask ${u}:`)),console.log(f.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(f.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(f.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(f.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(f.cyan(' and send a test email to my own address to confirm."')),a.outreachEnabled&&(a.outreachChannels??[]).length>0&&(i.blank(),console.log(f.yellow(`Note: your other channel(s) \u2014 ${(a.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),i.blank()}}async function L(e,t){await _t(e,{recursive:!0}),await Tt(W(e,".env"),Ye(t),"utf-8"),t.aiAgent==="codex"?(await _t(W(e,".codex"),{recursive:!0}),await Tt(W(e,".codex","config.toml"),Qe(t),"utf-8")):(await Tt(W(e,".mcp.json"),We(t),"utf-8"),await dt(e,"supabase"))}async function qi(e){try{(await It(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await Kn(e),n=t.filter(d=>!d.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(d=>s.has(d)),r=n.includes(".env"),l=t.includes(".klaudius");if(o&&r&&!l)return{kind:"partial",envPath:W(e,".env")};if(l&&r){let d=!0;try{d=!(await It(W(e,"node_modules"))).isDirectory()}catch{d=!0}return{kind:"scaffolded",nodeModulesMissing:d}}return{kind:"occupied",entries:n}}async function zi(e){i.blank(),i.warn(`Found a partial setup at ${f.bold(e)}.`),i.detail(`A previous init wrote ${f.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await P.select({message:`How would you like to proceed? ${f.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return P.isCancel(t)&&(P.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Ji(e){if(e&&e.trim().length>0)return e;P.intro("Klaudius");let t=await P.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return P.isCancel(t)&&(P.cancel("Setup cancelled. No files written."),process.exit(0)),t}function Xi(e){let t=Wi(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let s of n)if(t.startsWith(s))return`Inside ${s.slice(0,-1)} (system-managed directory).`}}function Zi(){if(process.platform!=="win32")return!1;try{return Ct("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function eo(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function to(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(f.green(f.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??he(e.aiPlan))==="off";console.log(`${f.bold("Your plan:")} ${He[e.aiPlan]}`),console.log(f.dim(r?` \u2192 QA pass off${e.aiPlan==="codex-plus"&&e.aiAgent==="codex"?", model pinned to Terra":""}, so each run fits your usage window.`:" \u2192 full pipeline, including the independent QA pass after every build.")),console.log(f.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),i.blank()}if(console.log(f.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let r=`cd ${ut(n)}`;console.log(` ${f.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${f.dim("# go into your project folder")}`)}console.log(` ${f.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${f.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(f.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${f.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${f.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${f.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${f.cyan('"Run the pipeline for one client."')}`),console.log(f.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),i.blank(),e.aiAgent!=="codex"&&(console.log(f.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(f.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as no,readFile as so}from"fs/promises";import{join as Rt,resolve as io}from"path";import F from"picocolors";async function Vn(e){let t=e.target?io(process.cwd(),e.target):process.cwd(),n=await Bn(Rt(t,".env")),s=await Bn(Rt(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{U(await so(Rt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await at(t);i.blank(),i.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let l=[];if(r.npm==="failed"&&l.push("npm"),r.pip==="failed"&&l.push("pip"),r.playwright==="failed"&&l.push("playwright"),r.patchright==="failed"&&l.push("patchright"),l.length===0){i.blank(),console.log(F.green(F.bold("All dependencies installed."))),console.log(F.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(F.yellow(F.bold(`${l.join(", ")} still failing.`))),i.blank();for(let[a,y]of Object.entries(r.hints??{}))console.log(F.yellow(`Likely cause of ${a} failure:`)),console.log(F.dim(` ${y}`)),i.blank();let d=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",p=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(F.dim("Options:")),console.log(F.dim(` \u2022 Open ${c} in this folder (\`${d}\`) and paste:`)),console.log(F.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(F.dim(` (Don't have ${c} yet? Install with: \`${p}\`)`)),console.log(F.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(F.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function Bn(e){try{return await no(e),!0}catch{return!1}}import{readFile as oo,writeFile as xt,access as ao}from"fs/promises";import{join as _e}from"path";import*as q from"@clack/prompts";import Z from"picocolors";import{mkdir as ro}from"fs/promises";import{spawnSync as Yn}from"child_process";async function Wn(e){let t=e.projectRoot??process.cwd(),n=_e(t,".env"),s=_e(t,".mcp.json"),o=_e(t,".codex","config.toml"),r=await Ot(_e(t,".klaudius","manifest.json")),l=await Ot(n);!r&&!l&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let d=ie();d.ok||(i.error(d.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let c={};try{let w=await oo(n,"utf-8");c=U(w)}catch{i.warn("No .env found. Starting from an empty configuration.")}let p=tn(c);Object.keys(c).length>0&&(p.pipelineModes??=["classic"]),q.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let a=await $(p),y=p.aiAgent??"claude-code";if(a.aiAgent&&a.aiAgent!==y&&(i.error(`Switching AI coding agent (${y} \u2192 ${a.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${Z.cyan("npx klaudius@latest init <new-folder>")} ${Z.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),a.supabaseUrl!==c.SUPABASE_URL||a.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let w=await Pe({url:a.supabaseUrl,serviceKey:a.supabaseServiceKey});w.ok||(i.error(w.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let E=se(a.googlePlacesApiKey??"");if(E.changed&&a.googlePlacesApiKey){i.heading("Checking your Google Places API key");let w=await Ee(a.googlePlacesApiKey);if(w.ok){if(E.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let g of E.repairs)i.detail(` ${g}`);i.detail("These come from keys that were transcribed rather than copied.")}a.googlePlacesApiKey=E.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(w.message??"Google rejected the Google Places API key"),i.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),i.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(lo(a,c)){let w=q.spinner();w.start("Validating email credentials (SMTP + IMAP)");let g=a.emailProvider&&a.emailProvider!=="custom"?a.emailProvider:fe(a.emailSmtpHost),k=await J({emailAddress:a.emailAddress,emailPassword:a.emailPassword,emailSmtpHost:a.emailSmtpHost,emailSmtpPort:a.emailSmtpPort,emailImapHost:a.emailImapHost,emailImapPort:a.emailImapPort,usesAccountPassword:g?Y[g].usesAccountPassword:void 0});k.ok?w.stop("Email credentials accepted (SMTP + IMAP)"):(w.stop(k.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(k.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 xt(n,Ye(a),"utf-8"),i.success("Updated .env"),a.aiAgent==="codex"?(await ro(_e(t,".codex"),{recursive:!0}),await xt(o,Qe(a),"utf-8"),i.success("Updated .codex/config.toml")):(await xt(s,We(a),"utf-8"),i.success("Updated .mcp.json"),await dt(t,"supabase")),a.emailAuth==="oauth-microsoft"&&a.outreachEnabled&&a.outreachChannels?.includes("email")){let w=await G();if(!(w!==null&&Yn(w.command[0],[...w.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!w)i.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),i.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let k=await q.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});q.isCancel(k)||!k?i.detail(`Skipped. Connect it any time with: ${w.command.join(" ")} scripts/ms_oauth.py login`):Yn(w.command[0],[...w.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?i.success("Outlook mailbox connected."):(i.warn("The Microsoft sign-in didn't complete."),i.detail(`Connect it any time with: ${w.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),q.outro(Z.green("Configuration updated.")),await co(t,r)}function lo(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([s])=>s===void 0||s==="")?!1:n.some(([s,o])=>String(s)!==(t[o]??""))}async function co(e,t){let n=await Ot(_e(e,"node_modules"));i.blank(),t?n||(i.detail("Your project files are in place but dependencies aren't installed yet."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${Z.cyan("npx klaudius@latest install")} ${Z.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${Z.cyan("npx klaudius@latest doctor")} ${Z.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${Z.cyan("npx klaudius@latest init")} ${Z.dim("# pick Resume when prompted")}`),i.blank())}async function Ot(e){try{return await ao(e),!0}catch{return!1}}import{copyFile as Qn,mkdir as vt,readFile as pt,rm as ue,writeFile as ft,access as qn}from"fs/promises";import{dirname as Nt,join as v}from"path";import{tmpdir as uo}from"os";import*as Ie from"@clack/prompts";import $t from"picocolors";var Ne="0.29.1";async function zn(e){let t=e.projectRoot??process.cwd(),n=await rn(t);n||(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let u of qe)delete n.files[u];let s,o=v(t,".env"),r,l;try{r=await pt(o,"utf-8"),l=U(r)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=l.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let d=en(r,l,Zt);d!==null&&(await ft(o,d,"utf-8"),i.detail("Backfilled new env keys")),await et("update",Ne),Ie.intro(`Update from ${n.templateVersion} \u2192 ${Ne}`),await rt();let p=l.AI_AGENT==="codex"?"codex":"claude-code",a=v(uo(),`klaudius-update-${process.pid}-${Date.now()}`),y;try{i.heading("Downloading the latest Klaudius template");let u=await Je({licenseKey:s,machineId:ve(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:a});i.success(`Fetched ${u.filesExtracted} canonical files`),y=a}catch(u){i.error(u.message),i.detail("Update aborted. Your project is unchanged."),await ue(a,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let E=await po(y,t,n),w=!1,g=E.find(u=>u.path===".gitignore"&&u.state==="conflict");if(g){let u=v(t,".gitignore"),m=await pt(u,"utf-8"),h=await pt(v(y,".gitignore"),"utf-8"),{merged:A,added:S}=fo(m,h);S.length>0&&await ft(u,A,"utf-8"),n.files[".gitignore"]=g.canonicalHash,g.state="gitignore-merged",w=!0,i.detail(S.length>0?`.gitignore auto-merged: kept all your lines, appended ${B(S.length,"new canonical pattern")}: ${S.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let k=E.filter(u=>u.state==="new"),b=E.filter(u=>u.state==="clean-update"),R=E.filter(u=>u.state==="user-only"),I=E.filter(u=>u.state==="conflict"),Q=E.filter(u=>u.state==="no-change"),V=E.filter(u=>u.state==="locally-deleted"),T=E.filter(u=>u.state==="removed-clean"),te=E.filter(u=>u.state==="removed-modified"),D=[...I,...V,...te],pe=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${B(Q.length,"file")} unchanged`),i.detail(`${B(k.length,"new file")}`),i.detail(`${B(b.length,"file")} updated cleanly (no local edits)`),i.detail(`${B(R.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${B(T.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${B(I.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${B(V.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${B(te.length,"file")} removed upstream but edited locally (need your decision)`),pe>0&&(i.detail(`${B(pe,"file")} kept deleted (previously resolved \u2014 skipped)`),pe<=10))for(let u of n.ignored)i.detail(` kept deleted: ${u}`);let Ce=async()=>{let u=!1,m=h=>ue(h,{recursive:!0,force:!0}).catch(()=>{u=!0});await m(v(t,".klaudius","incoming")),await m(v(t,Xe)),await m(v(t,".klaudius","conflicts.md")),u&&i.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(k.length===0&&b.length===0&&T.length===0&&D.length===0&&!w){await Ce(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ne,await Oe(t,n)),i.blank(),Ie.outro($t.green("Already up to date.")),await ue(a,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let u of[...k,...b]){let m=v(y,u.path),h=v(t,u.path);await vt(Nt(h),{recursive:!0}),await Qn(m,h),n.files[u.path]=u.canonicalHash}k.length+b.length>0&&i.success(`Wrote ${B(k.length+b.length,"file")}`);for(let u of T){let m=v(t,u.path);await ue(m,{force:!0}),delete n.files[u.path]}if(T.length>0&&i.success(`Deleted ${B(T.length,"file")} removed upstream`),D.length>0){i.blank(),i.heading(`${D.length} conflict(s) need resolution`);let u=v(t,".klaudius","incoming");try{await ue(u,{recursive:!0,force:!0})}catch{}for(let S of[...I,...V]){let _=v(y,S.path),x=v(u,S.path);await vt(Nt(x),{recursive:!0}),await Qn(_,x)}let m=new Map,h=new Map;for(let S of I){let _=await yn(t,S.path),x=await kn(t,S.path),ne=await pt(v(y,S.path),"utf-8"),Re=wn(_,x,ne,S.manifestHash);Re!==null?(h.set(S.path,Re),m.set(S.path,An(Re,ne))):_!==null&&(Ae(_)||Ae(ne))?m.set(S.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+S.path+"` directly._"]):_===null?m.set(S.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):m.set(S.path,["_The base snapshot is newer than the version your edits diverged from (an earlier update's conflicts were left unresolved), so a precise upstream diff isn't available for this file \u2014 compare against `.klaudius/incoming/"+S.path+"` directly._"])}let A=v(t,Xe);try{await ue(A,{recursive:!0,force:!0})}catch{}for(let[S,_]of h){let x=v(A,S);await vt(Nt(x),{recursive:!0}),await ft(x,_,"utf-8")}await ft(v(t,".klaudius","conflicts.md"),ho(D,n.templateVersion,Ne,m,h),"utf-8"),I.length+V.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),h.size>0&&i.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Ne,D.length===0?(delete n.pendingConflicts,await Ce()):n.pendingConflicts=D.length,await Oe(t,n);try{await Ze(t,y,await le(y))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),D.length===0)Ie.outro($t.green("Update complete."));else{let u=p==="codex"?"Codex":"Claude Code";Ie.outro($t.yellow(`${D.length} conflict(s) staged. Open ${u} in this project and ask:
|
|
94
|
+
"Run /resolve-conflicts"`))}await ue(a,{recursive:!0,force:!0}).catch(()=>{})}async function po(e,t,n){let s=await le(e),o=new Set(s),r=new Set(n.ignored??[]),l=[];for(let d of s){if(r.has(d))continue;let c=await we(v(e,d)),p=n.files[d],a=v(t,d),y;try{await qn(a),y=await we(a)}catch{let E=p!==void 0&&!an.has(d)?"locally-deleted":"new";l.push({path:d,state:E,canonicalHash:c,manifestHash:p});continue}c===p?y===p?l.push({path:d,state:"no-change",canonicalHash:c,localHash:y,manifestHash:p}):l.push({path:d,state:"user-only",canonicalHash:c,localHash:y,manifestHash:p}):y===p?l.push({path:d,state:"clean-update",canonicalHash:c,localHash:y,manifestHash:p}):l.push({path:d,state:"conflict",canonicalHash:c,localHash:y,manifestHash:p})}for(let d of Object.keys(n.files)){if(o.has(d))continue;let c=n.files[d],p=v(t,d),a;try{await qn(p),a=await we(p)}catch{delete n.files[d];continue}a===c?l.push({path:d,state:"removed-clean",localHash:a,manifestHash:c}):l.push({path:d,state:"removed-modified",localHash:a,manifestHash:c})}return l}function B(e,t){return`${e} ${t}${e===1?"":"s"}`}function fo(e,t){let n=e.includes(`\r
|
|
95
95
|
`)?`\r
|
|
96
96
|
`:`
|
|
97
|
-
`,s=e.split(/\r?\n/),o=new Set(s.map(
|
|
98
|
-
`)}import{existsSync as
|
|
99
|
-
`)),n.push(await
|
|
97
|
+
`,s=e.split(/\r?\n/),o=new Set(s.map(c=>c.trim()).filter(c=>c!=="")),r=[];for(let c of t.split(/\r?\n/)){let p=c.trim();p===""||p.startsWith("#")||o.has(p)||(r.push(p),o.add(p))}if(r.length===0)return{merged:e,added:r};let l=[...s];for(;l.length>0&&l[l.length-1].trim()==="";)l.pop();l.push("","# Added by `klaudius update` (new canonical ignore patterns)",...r);let d=[...new Set(s.map(c=>c.trim()).filter(c=>c.startsWith("!")))].filter(c=>!r.includes(c));return l.push(...d,""),{merged:l.join(n),added:r}}function ho(e,t,n,s=new Map,o=new Map){let r=e.filter(a=>a.state==="conflict").length,l=e.filter(a=>a.state==="locally-deleted").length,d=e.filter(a=>a.state==="removed-modified").length,c=[];c.push("# Update Conflicts"),c.push(""),c.push(`Generated by \`npx klaudius@latest update\` on ${new Date().toISOString()}.`),c.push(`Updating from canonical version **${t}** to **${n}**.`),c.push("");let p=[];r>0&&p.push(`${r} file${r===1?"":"s"} ha${r===1?"s":"ve"} BOTH local edits AND upstream changes`),l>0&&p.push(`${l} file${l===1?"":"s"} you deleted locally ${l===1?"is":"are"} still shipped by the canonical template`),d>0&&p.push(`${d} file${d===1?"":"s"} ${d===1?"was":"were"} removed upstream but edited locally`),c.push(p.join(", and ")+"."),c.push("Open Claude Code in this project and run `/resolve-conflicts` \u2014 that skill walks through each conflict interactively, helping you decide what to keep, take, merge, or delete."),c.push(""),c.push("---"),c.push("");for(let a of e){if(c.push(`## ${a.path}`),c.push(""),a.state==="locally-deleted")c.push("**Type:** Deleted locally"),c.push(""),c.push("- You deleted this file after it was installed; the canonical template still ships it."),c.push(`- New canonical version staged at: \`.klaudius/incoming/${a.path}\``),c.push(`- Hash at last install/update: \`${(a.manifestHash??"(none)").slice(0,16)}\``),c.push(`- New canonical hash: \`${(a.canonicalHash??"(none)").slice(0,16)}\``),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Restore \u2014 copy the canonical version back into place"),c.push("2. Keep deleted \u2014 never reinstall this file (recorded in the manifest's ignore list)");else if(a.state==="removed-modified")c.push("**Type:** Removed upstream"),c.push(""),c.push(`- Your local copy: \`${a.path}\``),c.push("- This file no longer exists in the canonical template."),c.push("- You've modified it locally since install."),c.push(`- Hash at last install/update: \`${(a.manifestHash??"(none)").slice(0,16)}\``),c.push(`- Your local hash now: \`${(a.localHash??"(missing)").slice(0,16)}\``),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Keep mine \u2014 leave the file in place; stop tracking it in the manifest"),c.push("2. Delete \u2014 remove the file from disk and from the manifest");else{c.push("**Type:** Edit conflict"),c.push(""),c.push(`- Your version (with your local edits): \`${a.path}\``),c.push(`- New canonical version: \`.klaudius/incoming/${a.path}\``),o.has(a.path)&&c.push(`- Pre-edit base (3-way merge ancestor): \`.klaudius/conflict-base/${a.path}\``),c.push(`- Hash at last install/update: \`${(a.manifestHash??"(none)").slice(0,16)}\``),c.push(`- Your local hash now: \`${(a.localHash??"(missing)").slice(0,16)}\``),c.push(`- New canonical hash: \`${(a.canonicalHash??"(none)").slice(0,16)}\``);let y=s.get(a.path);y&&y.length>0&&(c.push(""),c.push("**What upstream changed since your base:**"),c.push(""),c.push(...y),c.push(""),c.push("_If your local edits don't touch the hunks above, merging is mechanical: take the canonical version and re-apply your edits (or apply the hunks to your copy). If they overlap, compare both versions properly before choosing._")),c.push(""),c.push("**Resolution options for the SKILL to walk through:**"),c.push(""),c.push("1. Keep mine \u2014 discard the new canonical changes"),c.push("2. Take canonical \u2014 overwrite my edits with the new version"),c.push("3. Merge \u2014 review both side-by-side and produce a combined version")}c.push(""),c.push("---"),c.push("")}return c.join(`
|
|
98
|
+
`)}import{existsSync as mo}from"fs";import{access as go,readFile as $e,stat as yo}from"fs/promises";import{homedir as ko}from"os";import{join as j}from"path";import M from"picocolors";import{spawn as Jn,spawnSync as wo}from"child_process";async function Xn(e){let t=e.projectRoot??process.cwd(),n=[];console.log(M.bold(`Klaudius doctor \u2014 checking your project\u2026
|
|
99
|
+
`)),n.push(await Ao());let s=await To();s&&n.push(s),n.push(await Po());let o=j(t,".env"),r=j(t,".klaudius","manifest.json"),l=j(t,".mcp.json"),d=j(t,".codex","config.toml"),c=await z(o),p=await z(r),a="claude-code";if(c)try{U(await $e(o,"utf-8")).AI_AGENT==="codex"&&(a="codex")}catch{}if(a==="claude-code"){let g=await z(j(t,"AGENTS.md")),k=!await z(j(t,".claude"));g&&k&&(a="codex")}n.push({name:".env present",status:c?"ok":"fail",detail:c?o:"missing",nextAction:c?void 0:"Run `npx klaudius@latest init` in this folder."});let y=!1;if(c){let g={};try{g=U(await $e(o,"utf-8"))}catch{}let k=Ge(g.AI_PLAN),b=Be(g.QA_PHASE)??he(k);y=b==="off";let R=k==="codex-plus"&&a==="codex"?` \xB7 model pin ${kt}`:"";n.push({name:"Plan / QA pass",status:k?"ok":"warn",detail:k?`${He[k]} \xB7 QA pass ${b}${R}`:`plan not set \xB7 QA pass ${b}`,nextAction:k?void 0:"Run `npx klaudius@latest configure` and pick your plan \u2014 on Claude Pro / ChatGPT Plus it turns the QA pass off so each run fits your usage window."})}{let g=0,k="";if(p)try{let b=JSON.parse(await $e(r,"utf-8"));g=typeof b.pendingConflicts=="number"?b.pendingConflicts:0,k=typeof b.templateVersion=="string"?b.templateVersion:""}catch{}n.push({name:"Template scaffolded (.klaudius/manifest.json)",status:p?g>0?"warn":"ok":"fail",detail:p?g>0?`${k||"version unknown"} \u2014 ${g} conflict${g===1?"":"s"} from the last update still unresolved`:k?`${r} (template ${k})`:r:"missing",nextAction:p?g>0?'Open your agent in this folder and say "resolve the conflicts" \u2014 until then some files are still on the previous version.':void 0:c?"Init didn't finish \u2014 run `npx klaudius@latest init` and pick Resume.":"Run `npx klaudius@latest init`."})}if(a==="codex"){let g=await z(d);n.push({name:".codex/config.toml present",status:g?"ok":"warn",detail:g?d:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}else{let g=await z(l);n.push({name:".mcp.json present",status:g?"ok":"warn",detail:g?l:"missing",nextAction:g?void 0:"Run `npx klaudius@latest configure` to regenerate."})}if(n.push(await Mo(a)),process.platform==="win32"){let g=await Eo(t);g&&n.push(g)}if(n.push(await bo(t)),n.push(await So(t)),n.push(await _o(t,y)),n.push(await Co()),n.push(await Io(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 g=await $e(o,"utf-8"),k=U(g);await Ro(k,n,t)}console.log();for(let g of n){let k=g.status==="ok"?M.green("\u2713"):g.status==="warn"?M.yellow("\u26A0"):g.status==="skip"?M.dim("\xB7"):M.red("\u2717");console.log(` ${k} ${g.name}${g.detail?M.dim(` \u2014 ${g.detail}`):""}`),g.nextAction&&console.log(` ${M.dim("\u2192")} ${M.cyan(g.nextAction)}`)}let E=n.filter(g=>g.status==="fail").length,w=n.filter(g=>g.status==="warn").length;console.log(),E===0&&w===0?console.log(M.green(M.bold("Everything checks out. You're good to go."))):E===0?console.log(M.yellow(M.bold(`${w} warning${w===1?"":"s"} \u2014 review above.`))):(console.log(M.red(M.bold(`${E} failed check${E===1?"":"s"} \u2014 see the \u2192 next actions above.`))),process.exitCode=1),console.log()}async function z(e){try{return await go(e),!0}catch{return!1}}async function Ao(){let e=await ke();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 Po(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)return{name:"Node \u2265 22.15",status:"warn",detail:e};let n=parseInt(t[1],10),s=parseInt(t[2],10);return n<22||n===22&&s<15?{name:"Node \u2265 22.15",status:"fail",detail:e,nextAction:"Upgrade Node.js to 22.15+ from https://nodejs.org/"}:{name:"Node \u2265 22.15",status:"ok",detail:e}}async function Eo(e){let t=me([{label:"your Windows user folder",path:ko()},{label:"the project folder",path:e}]);if(t.length===0)return null;let n="Install path safe for npm builds",s=await Lt("npm",["config","get","script-shell"],!0),o=s.code===0?s.stdout.trim():void 0;if(ge(o,mo))return{name:n,status:"ok",detail:`${t[0].label} contains ${t[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${o}) handles it`};let{detail:r,action:l}=ye(t,"doctor"),d=t.some(c=>c.chars.includes("&"));return{name:n,status:d?"fail":"warn",detail:r,nextAction:l}}async function bo(e){let t=j(e,"node_modules");if(!await z(t))return{name:"node_modules installed",status:"fail",detail:"missing",nextAction:"Run `npx klaudius@latest install` in this folder."};try{if(!(await yo(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 So(e){let t=process.platform==="darwin"?j(process.env.HOME??"","Library","Caches","ms-playwright"):process.platform==="win32"?j(process.env.USERPROFILE??"","AppData","Local","ms-playwright"):j(process.env.HOME??"",".cache","ms-playwright");return await z(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 To(){let e=await bt();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 _o(e,t){if(!await z(j(e,"node_modules","@playwright","cli")))return{name:"QA screenshot chain",status:"skip",detail:"project dependencies not installed",nextAction:"Run `npx klaudius@latest install` first."};let s=await ct(e);if(s.ok)return{name:"QA screenshot chain",status:"ok",detail:"served a page with python3 and screenshotted it"};let o=s.stage!=="python3-server"&&t;return{name:"QA screenshot chain",status:o?"warn":"fail",detail:`${s.stage?`${s.stage}: `:""}${s.detail??"failed"}`+(o?" (QA pass is off \u2014 this matters when you enable it, and for browser-based gathering)":""),nextAction:s.remediation}}async function Io(e){let t=j(e,".klaudius","notify-failures.log");try{let n=(await $e(t,"utf8")).trim();if(!n)return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"};let s=n.split(/\r?\n/);return{name:"Alert delivery",status:"warn",detail:`${s.length} failed send${s.length===1?"":"s"} recorded; latest: "${s[s.length-1]}"`,nextAction:"Check TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID in .env (rate limits also land here). Delete .klaudius/notify-failures.log once resolved."}}catch{return{name:"Alert delivery",status:"ok",detail:"no failed sends recorded"}}}async function Co(){let e=["supabase","dotenv","requests","httpx","PIL"],t=`import sys
|
|
100
100
|
try:
|
|
101
101
|
${e.map(r=>` import ${r}`).join(`
|
|
102
102
|
`)}
|
|
103
103
|
except Exception as e:
|
|
104
104
|
print(str(e))
|
|
105
105
|
sys.exit(1)
|
|
106
|
-
`,n=await
|
|
107
|
-
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function
|
|
108
|
-
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await Z(Y(e,".ms-token.json"))?{name:t,status:"warn",detail:"token cache present, but no Python found to verify it"}:{name:t,status:"fail",detail:"no Microsoft sign-in found (.ms-token.json missing)",nextAction:o}}async function so(e){let t="Database schema up to date",n=(e.SUPABASE_URL??"").trim().replace(/\/+$/,""),s=(e.SUPABASE_SERVICE_KEY??"").trim();if(!n||!s)return{name:t,status:"skip",detail:"Supabase credentials not set"};try{let o=await fetch(`${n}/rest/v1/clients?select=postal_address&limit=1`,{headers:{apikey:s,Authorization:`Bearer ${s}`}});if(o.ok)return{name:t,status:"ok",detail:"clients.postal_address present"};let r=await o.text();return o.status===400&&/postal_address/.test(r)?(e.OUTREACH_CHANNELS??"").split(",").some(c=>c.trim().toLowerCase()==="letter")?{name:t,status:"warn",detail:"clients.postal_address is missing \u2014 this database was provisioned before the letter channel. Captures still work (values are stored under extra), but the letter channel reads the real column.",nextAction:"Run once in the Supabase SQL editor: ALTER TABLE clients ADD COLUMN IF NOT EXISTS postal_address JSONB;"}:{name:t,status:"skip",detail:"clients.postal_address absent \u2014 only needed by the letter channel, which isn't enabled"}:{name:t,status:"skip",detail:`Could not verify (HTTP ${o.status}) \u2014 see the Supabase rows above.`}}catch{return{name:t,status:"skip",detail:"Supabase unreachable \u2014 skipped schema check"}}}async function io(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(p=>p.trim().toLowerCase()),s=(e.LETTER_PROVIDER??"").trim().toLowerCase(),o=n.includes("letter");if(!o&&(!s||s==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(o&&s!=="pingen"&&s!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!o)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${s} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let r=await et({provider:s,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!r.ok)return{name:t,status:"fail",detail:r.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let l=`${s} credentials accepted`+(r.friendlyName?` (${r.friendlyName})`:""),c=(e.SUPABASE_ANON_KEY??"").trim();if(!c)return{name:t,status:"warn",detail:l+", 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 d=$t(c);if(d&&d!=="anon")return{name:t,status:"fail",detail:l+`, but SUPABASE_ANON_KEY holds a '${d}' key \u2014 shipping it in a claim page would expose the whole database`,nextAction:"Replace SUPABASE_ANON_KEY with the key whose role is 'anon' (Supabase dashboard \u2192 Settings \u2192 API keys)."};if(e.SUPABASE_URL)try{let p=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:c,Authorization:`Bearer ${c}`}});if(p.ok){let a=await p.json();if(Array.isArray(a)&&a.length>0)return{name:t,status:"fail",detail:l+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(s==="postgrid"){let p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(a=>!(e[a]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:l+`, 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:l}}async function oo(e,t){let n="Email credentials (SMTP + IMAP)",s=to(e);if(s==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Bn(e))return s==="parked"?{name:"Email account (Microsoft sign-in)",status:"warn",detail:"Outlook mailbox saved in .env but email isn't an active outreach channel (skipped during setup?)",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."}:s==="incomplete"?{name:"Email account (Microsoft sign-in)",status:"fail",detail:"EMAIL_AUTH=oauth-microsoft but EMAIL_ADDRESS is missing from .env",nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}:no(t);if(s==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(s==="incomplete"){let d=["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 ${d.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=je(e),r=o&&o!=="custom"?o:fe(e.EMAIL_SMTP_HOST),l={emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:r?B[r].usesAccountPassword:void 0,draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},c=await Q(l);if(c.ok){if(c.draftsFolderIssue){let{configured:d,detected:p}=c.draftsFolderIssue;return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the server has no "${d}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`,nextAction:p?`Set EMAIL_DRAFTS_FOLDER="${p}" in .env (or ask your AI agent to).`:"Set EMAIL_DRAFTS_FOLDER in .env to this mailbox's drafts folder name."}}return{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(c.failureKind==="network")return{name:n,status:"fail",detail:c.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(r){let d=xe(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(d.length>0){console.log(M.dim(` (email login rejected \u2014 probing ${B[r].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let y of d){let g=await Q({...l,emailSmtpHost:y.smtpHost,emailImapHost:y.imapHost});if(!g.ok&&g.failureKind!=="network"&&p++,g.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${y.label} (${y.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${y.smtpHost} and EMAIL_IMAP_HOST=${y.imapHost} in .env (or ask your AI agent to).`}}let a=(c.message??"login rejected").split(/\.\s|\n/)[0];return p===0?{name:n,status:"fail",detail:`${a} \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:`${a} \u2014 tried all ${B[r].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:r==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":r==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:c.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}async function ao(e){let t=[];for(let n of Vt(e)){let s=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:s,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:s,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:s,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:s,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let o=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,r=await Q({emailAddress:n.address,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,draftsFolder:(e[o]??"").trim()||"Drafts"});if(r.ok)if(r.draftsFolderIssue){let{configured:l,detected:c}=r.draftsFolderIssue;t.push({name:s,status:"warn",detail:`authenticated (${n.smtpHost}), but the server has no "${l}" folder \u2014 saving drafts from this mailbox would fail`,nextAction:c?`Set ${o}="${c}" in .env (or ask your AI agent to).`:`Set ${o} in .env to this mailbox's drafts folder name.`})}else t.push({name:s,status:"ok",detail:`authenticated (${n.smtpHost})`});else t.push({name:s,status:"fail",detail:r.message,nextAction:r.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 ro(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",s=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",o=await Ct(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
|
|
109
|
-
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:s}}function
|
|
110
|
-
`));let r=
|
|
106
|
+
`,n=await G();if(!n)return{name:"Python packages installed",status:"fail",detail:"no Python interpreter found (tried python3, python, py -3)",nextAction:"Fix the Python check above first \u2014 the packages live inside that interpreter."};let s=n.command,o=await Lt(s[0],[...s.slice(1),"-c",t]);return o.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(o.stdout||o.stderr).trim().split(`
|
|
107
|
+
`).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function Ro(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let l=await Pe({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:l.ok?"ok":"fail",detail:l.ok?"connected":l.message,nextAction:l.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});let s=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(s==="selfhost"){let l=e.SELFHOST_DEPLOY_TARGET??"",d=e.SELFHOST_URL_TEMPLATE??"",c=[],p=Me(l);p&&c.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let a=De(d);a&&c.push(`SELFHOST_URL_TEMPLATE: ${a}`),t.push({name:"Self-host deploy config",status:c.length===0?"ok":"fail",detail:c.length===0?`target ${l} (SSH reachability tested at first deploy)`:c.join("; "),nextAction:c.length===0?void 0:"Run `npx klaudius@latest configure` and fix the self-host deployment answers."})}else if(s==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let l=await nt({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:l.ok?"ok":"fail",detail:l.ok?`valid (${l.projectCount??0} Pages project${l.projectCount===1?"":"s"})`:l.message,nextAction:l.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Cloudflare."});else if(s==="netlify")if(e.NETLIFY_AUTH_TOKEN){let l=await st({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:l.ok?"ok":"fail",detail:l.ok?l.accountSlug?`valid (team: ${l.accountSlug})`:"valid":l.message,nextAction:l.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 l=await tt(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:l.ok?"ok":"fail",detail:l.ok?l.username??"valid":l.message,nextAction:l.ok?void 0:"Generate a new token at https://vercel.com/account/tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let l=await Ee(e.GOOGLE_PLACES_API_KEY),d=se(e.GOOGLE_PLACES_API_KEY);l.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:l.ok?"ok":"fail",detail:l.ok?"accepted":l.message,nextAction:l.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 $o(e,n)),t.push(...await Lo(e)),t.push(await vo(e)),t.push(await No(e));let o=(e.NOTIFY_CHANNEL??"").toLowerCase(),r=o==="email"||o==="sms"||o==="none"||o==="off"?o:"telegram";if(r==="none"||r==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(r==="email"){let l=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:l&&e.EMAIL_ADDRESS?"ok":"fail",detail:l&&e.EMAIL_ADDRESS?`alerts go to ${l}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:l&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(r==="sms"){let l=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:l&&d?"ok":"fail",detail:l&&d?`alerts go to ${l} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:l?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:l&&d?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let l=await Ht({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:l.ok?"ok":"fail",detail:l.ok?`bot ${l.botHandle??"ok"} (chat_id not tested)`:l.message,nextAction:l.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 xo(e){let t=r=>!!r&&/^\d+$/.test(r.trim()),n=Zn(e)?!!e.EMAIL_ADDRESS:!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),s=(e.OUTREACH_CHANNELS??"").split(",").map(r=>r.trim()),o=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&s.includes("email");return o&&n?"active":o?"incomplete":n?"parked":"unconfigured"}function Zn(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function Oo(e){let t="Email account (Microsoft sign-in)",n=await G(),o=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[l,...d]=n.command,c=wo(l,[...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 a=/signed in as (\S+)/.exec(p)?.[1];return{name:t,status:"ok",detail:a?`signed in as ${a} (token refresh works)`:"signed in (token refresh works)"}}return{name:t,status:"fail",detail:p.split(`
|
|
108
|
+
`)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:o}}return await z(j(e,".ms-token.json"))?{name:t,status:"warn",detail:"token cache present, but no Python found to verify it"}:{name:t,status:"fail",detail:"no Microsoft sign-in found (.ms-token.json missing)",nextAction:o}}async function vo(e){let t="Database schema up to date",n=(e.SUPABASE_URL??"").trim().replace(/\/+$/,""),s=(e.SUPABASE_SERVICE_KEY??"").trim();if(!n||!s)return{name:t,status:"skip",detail:"Supabase credentials not set"};try{let o=await fetch(`${n}/rest/v1/clients?select=postal_address&limit=1`,{headers:{apikey:s,Authorization:`Bearer ${s}`}});if(o.ok)return{name:t,status:"ok",detail:"clients.postal_address present"};let r=await o.text();return o.status===400&&/postal_address/.test(r)?(e.OUTREACH_CHANNELS??"").split(",").some(d=>d.trim().toLowerCase()==="letter")?{name:t,status:"warn",detail:"clients.postal_address is missing \u2014 this database was provisioned before the letter channel. Captures still work (values are stored under extra), but the letter channel reads the real column.",nextAction:"Run once in the Supabase SQL editor: ALTER TABLE clients ADD COLUMN IF NOT EXISTS postal_address JSONB;"}:{name:t,status:"skip",detail:"clients.postal_address absent \u2014 only needed by the letter channel, which isn't enabled"}:{name:t,status:"skip",detail:`Could not verify (HTTP ${o.status}) \u2014 see the Supabase rows above.`}}catch{return{name:t,status:"skip",detail:"Supabase unreachable \u2014 skipped schema check"}}}async function No(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(p=>p.trim().toLowerCase()),s=(e.LETTER_PROVIDER??"").trim().toLowerCase(),o=n.includes("letter");if(!o&&(!s||s==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(o&&s!=="pingen"&&s!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!o)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${s} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let r=await it({provider:s,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!r.ok)return{name:t,status:"fail",detail:r.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let l=`${s} credentials accepted`+(r.friendlyName?` (${r.friendlyName})`:""),d=(e.SUPABASE_ANON_KEY??"").trim();if(!d)return{name:t,status:"warn",detail:l+", 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=Kt(d);if(c&&c!=="anon")return{name:t,status:"fail",detail:l+`, 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 a=await p.json();if(Array.isArray(a)&&a.length>0)return{name:t,status:"fail",detail:l+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(s==="postgrid"){let p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(a=>!(e[a]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:l+`, 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:l}}async function $o(e,t){let n="Email credentials (SMTP + IMAP)",s=xo(e);if(s==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(Zn(e))return s==="parked"?{name:"Email account (Microsoft sign-in)",status:"warn",detail:"Outlook mailbox saved in .env but email isn't an active outreach channel (skipped during setup?)",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."}:s==="incomplete"?{name:"Email account (Microsoft sign-in)",status:"fail",detail:"EMAIL_AUTH=oauth-microsoft but EMAIL_ADDRESS is missing from .env",nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}:Oo(t);if(s==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(s==="incomplete"){let c=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(p=>p.endsWith("_PORT")?!e[p]||!/^\d+$/.test(e[p].trim()):!e[p]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${c.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let o=Ve(e),r=o&&o!=="custom"?o:fe(e.EMAIL_SMTP_HOST),l={emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:r?Y[r].usesAccountPassword:void 0,draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},d=await J(l);if(d.ok){if(d.draftsFolderIssue){let{configured:c,detected:p}=d.draftsFolderIssue;return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the server has no "${c}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`,nextAction:p?`Set EMAIL_DRAFTS_FOLDER="${p}" in .env (or ask your AI agent to).`:"Set EMAIL_DRAFTS_FOLDER in .env to this mailbox's drafts folder name."}}return{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(d.failureKind==="network")return{name:n,status:"fail",detail:d.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(r){let c=Le(r,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(M.dim(` (email login rejected \u2014 probing ${Y[r].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let y of c){let E=await J({...l,emailSmtpHost:y.smtpHost,emailImapHost:y.imapHost});if(!E.ok&&E.failureKind!=="network"&&p++,E.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${y.label} (${y.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${y.smtpHost} and EMAIL_IMAP_HOST=${y.imapHost} in .env (or ask your AI agent to).`}}let a=(d.message??"login rejected").split(/\.\s|\n/)[0];return p===0?{name:n,status:"fail",detail:`${a} \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:`${a} \u2014 tried all ${Y[r].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:r==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":r==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:d.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}async function Lo(e){let t=[];for(let n of Xt(e)){let s=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:s,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:s,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:s,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:s,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let o=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,r=await J({emailAddress:n.address,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,draftsFolder:(e[o]??"").trim()||"Drafts"});if(r.ok)if(r.draftsFolderIssue){let{configured:l,detected:d}=r.draftsFolderIssue;t.push({name:s,status:"warn",detail:`authenticated (${n.smtpHost}), but the server has no "${l}" folder \u2014 saving drafts from this mailbox would fail`,nextAction:d?`Set ${o}="${d}" in .env (or ask your AI agent to).`:`Set ${o} in .env to this mailbox's drafts folder name.`})}else t.push({name:s,status:"ok",detail:`authenticated (${n.smtpHost})`});else t.push({name:s,status:"fail",detail:r.message,nextAction:r.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 Mo(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",s=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",o=await Lt(t,["--version"],process.platform==="win32");return o.code===0?{name:n,status:"ok",detail:(o.stdout||o.stderr).trim().split(`
|
|
109
|
+
`)[0]}:{name:n,status:"warn",detail:"not found",nextAction:s}}function Lt(e,t,n=!1){return new Promise(s=>{let o=n?Jn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):Jn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",l="";o.stdout?.on("data",d=>{r+=d.toString()}),o.stderr?.on("data",d=>{l+=d.toString()}),o.on("close",d=>s({code:d??1,stdout:r,stderr:l})),o.on("error",()=>s({code:1,stdout:r,stderr:l}))})}import{existsSync as Do}from"fs";import{spawnSync as Ho}from"child_process";import{join as Uo,resolve as Fo}from"path";import H from"picocolors";async function es(e){let t=Fo(e.projectRoot??process.cwd()),n=Uo(t,"scripts","whatsapp.mjs");Do(n)||(console.error(H.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(H.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(H.dim(`Looked for: ${n}`)),process.exit(1));let s=(e.label??"primary").trim(),o=s.replace(/[^A-Za-z0-9_-]/g,"");o||(console.error(H.red(`Invalid label '${s}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),o!==s&&console.error(H.yellow(`Note: cleaned label '${s}' \u2192 '${o}' (filename-safe characters only).`)),console.log(H.cyan(`Pairing WhatsApp account '${o}'...`)),console.log(H.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.
|
|
110
|
+
`));let r=Ho(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(H.green(`Paired '${o}'.`)),console.log(H.dim(`
|
|
111
111
|
If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
112
112
|
WHATSAPP_ACCOUNTS=primary,${o}
|
|
113
|
-
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(
|
|
113
|
+
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(H.red(`Pair failed: ${r.error.message}`)):(console.error(H.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(H.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(H.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(H.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as jo}from"child_process";var Mt="--use-system-ca";function ts(){let e=process.env.NODE_OPTIONS??"";if(e.includes(Mt)||!ie().ok)return;let n=e?`${e} ${Mt}`:Mt,s=jo(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});s.signal&&(process.kill(process.pid,s.signal),process.exit(1)),process.exit(s.status??1)}ts();var Go="0.29.1",ee=new Ko;ee.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Go);ee.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 Wt({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});ee.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").action(async(e,t)=>{try{await Gn({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});ee.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 Vn({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});ee.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await Wn({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});ee.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await zn({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});ee.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 Xn({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});ee.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 es({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ee.parse(process.argv);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.29.1",
|
|
4
4
|
"description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code or Codex (find, build, deploy, outreach end-to-end).",
|
|
5
5
|
"homepage": "https://klaudius.dev",
|
|
6
6
|
"bugs": {
|