klaudius 0.32.3 → 0.32.4
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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as m,m as q,n as J,p as R}from"./chunk-
|
|
1
|
+
import{a as m,m as q,n as J,p as R}from"./chunk-N7WRVWZQ.js";import{useEffect as Oe,useMemo as Me,useRef as ie,useState as E}from"react";import{Box as B,Text as k,useApp as Fe,useInput as Ye}from"ink";import{Box as ce,Text as we}from"ink";import{jsx as le,jsxs as Ae}from"react/jsx-runtime";var ke={pending:"\u25CB",current:"\u25C9",done:"\u2713",skipped:"\xB7"},Ie={pending:void 0,current:"cyan",done:"green",skipped:void 0};function pe({items:e}){return le(ce,{flexDirection:"column",width:28,flexShrink:0,children:e.map(r=>{let o=r.status==="skipped"||r.status==="pending";return le(ce,{children:Ae(we,{color:Ie[r.status],bold:r.status==="current",dimColor:o&&r.status!=="current",children:[ke[r.status]," ",r.title]})},r.id)})})}import{useEffect as Re,useState as ue}from"react";import{Box as Q,Text as Y,useInput as Ee}from"ink";import Ce from"ink-text-input";import{jsx as D,jsxs as Z}from"react/jsx-runtime";function de({spec:e,masked:r,onSubmit:o,onBack:t}){let u=typeof e.initialValue=="string"?e.initialValue:"",n=r&&u.length>0,[i,b]=ue(n?"":u),[g,c]=ue(null);Re(()=>(m("TextPromptUI:mount",{masked:r,message:e.message.slice(0,60),initial:typeof e.initialValue=="string"?e.initialValue.slice(0,30):null}),()=>{m("TextPromptUI:unmount")}),[r,e.message,e.initialValue]),Ee((d,x)=>{m("TextPromptUI:useInput fired",{input:d,ctrl:x.ctrl,escape:x.escape,return:x.return}),x.escape&&t()});let A=d=>{m("TextPromptUI:handleSubmit",{raw:d.slice(0,30)});let x=d.length===0&&n?u:d;if(e.validate){let l=e.validate(x);if(l){m("TextPromptUI:validate failed",{err:l}),c(l);return}}c(null),o(x)};return Z(Q,{flexDirection:"column",children:[Z(Y,{children:[D(Y,{color:"cyan",children:"?"})," ",e.message]}),Z(Q,{children:[D(Y,{color:"green",children:"\u203A "}),D(Ce,{value:i,onChange:b,onSubmit:A,placeholder:n?"type or paste a new value \u2014 or press Enter to keep the current one":e.placeholder,mask:r?"\u2022":void 0})]}),g&&D(Q,{marginTop:0,children:D(Y,{color:"red",children:g})})]})}import{useState as ze}from"react";import{Box as _,Text as $,useInput as Ue}from"ink";import{jsx as j,jsxs as ee}from"react/jsx-runtime";function me({spec:e,onSubmit:r,onBack:o}){let t=e.options??[],u=typeof e.initialValue=="string"?Math.max(0,t.findIndex(b=>b.value===e.initialValue)):0,[n,i]=ze(u===-1?0:u);return Ue((b,g)=>{if(g.escape)o();else if(g.upArrow)i(c=>(c-1+t.length)%t.length);else if(g.downArrow)i(c=>(c+1)%t.length);else if(g.return){let c=t[n];c&&r(c.value)}}),ee(_,{flexDirection:"column",children:[ee($,{children:[j($,{color:"cyan",children:"?"})," ",e.message]}),j(_,{flexDirection:"column",marginTop:0,children:t.map((b,g)=>{let c=g===n;return ee($,{color:c?"cyan":void 0,bold:c,children:[c?"\u25CF ":"\u25CB ",b.label]},b.value)})}),j(_,{marginTop:1,children:j($,{dimColor:!0,children:"Use the \u2191 \u2193 arrow keys to choose, then press Enter"})})]})}import{useState as Ne}from"react";import{Box as te,Text as z,useInput as De}from"ink";import{jsx as L,jsxs as V}from"react/jsx-runtime";function fe({spec:e,onSubmit:r,onBack:o}){let[t,u]=Ne(typeof e.initialValue=="boolean"?e.initialValue:!0);return De((n,i)=>{i.escape?o():i.leftArrow||i.rightArrow?u(b=>!b):n==="y"||n==="Y"?u(!0):n==="n"||n==="N"?u(!1):i.return&&r(t)}),V(te,{flexDirection:"column",children:[V(z,{children:[L(z,{color:"cyan",children:"?"})," ",e.message]}),V(te,{marginTop:0,children:[V(z,{color:t?"cyan":void 0,bold:t,children:[t?"\u25CF ":"\u25CB ","Yes"]}),L(z,{children:" "}),V(z,{color:t?void 0:"cyan",bold:!t,children:[t?"\u25CB ":"\u25CF ","No"]})]}),L(te,{marginTop:1,children:L(z,{dimColor:!0,children:"Use the \u2190 \u2192 arrow keys (or y / n) to choose, then press Enter"})})]})}import{useState as re}from"react";import{Box as H,Text as W,useInput as Ve}from"ink";import{jsx as O,jsxs as X}from"react/jsx-runtime";function ge({spec:e,onSubmit:r,onBack:o}){let t=e.options??[],u=new Set(typeof e.initialValue=="string"?e.initialValue.split(",").map(d=>d.trim()).filter(Boolean):[]),[n,i]=re(0),[b,g]=re(u),[c,A]=re(null);return Ve((d,x)=>{if(x.escape)o();else if(x.upArrow)i(l=>(l-1+t.length)%t.length);else if(x.downArrow)i(l=>(l+1)%t.length);else if(d===" "){let l=t[n];l&&(A(null),g(y=>{let T=new Set(y);return T.has(l.value)?T.delete(l.value):T.add(l.value),T}))}else if(x.return){let l=t.map(T=>T.value).filter(T=>b.has(T)).join(","),y=e.validate?.(l);if(y){A(y);return}r(l)}}),X(H,{flexDirection:"column",children:[X(W,{children:[O(W,{color:"cyan",children:"?"})," ",e.message]}),O(H,{flexDirection:"column",marginTop:0,children:t.map((d,x)=>{let l=x===n,y=b.has(d.value);return X(W,{color:l?"cyan":void 0,bold:l,children:[l?"\u203A ":" ",y?"\u25C9 ":"\u25EF ",d.label]},d.value)})}),c&&O(H,{marginTop:0,children:O(W,{color:"red",children:c})}),O(H,{marginTop:1,children:X(W,{dimColor:!0,children:["\u2191 \u2193 to move, Space to tick/untick, Enter to confirm",e.validate?" (tick at least one)":" (ticking none is fine)"]})})]})}import{Box as xe,Text as Se}from"ink";import{jsx as oe,jsxs as We}from"react/jsx-runtime";function ne({title:e,body:r}){let o=r.split(`
|
|
2
2
|
`);return We(xe,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[oe(Se,{color:"cyan",bold:!0,children:e}),oe(xe,{flexDirection:"column",marginTop:0,children:o.map((t,u)=>oe(Se,{dimColor:!1,children:t.length===0?" ":t},u))})]})}import{jsx as a,jsxs as M}from"react/jsx-runtime";function Rt({defaults:e,onComplete:r,onlySection:o,banner:t}){let{exit:u}=Fe(),n=ie({...e}),i=ie(new Map),[,b]=E(0),g=()=>b(f=>f+1),[c,A]=E(null),[d,x]=E(null),[l,y]=E([]),[T,se]=E(null),[ae,he]=E(!1),[G,be]=E({current:0,total:0}),U=()=>{let f=i.current;for(let S of R){let C=S.isApplicable(n.current),I=f.get(S.id);C?o&&S.id!==o?I!=="current"&&f.set(S.id,"done"):(I==="skipped"||!I)&&f.set(S.id,"pending"):f.set(S.id,"skipped")}};i.current.size===0&&U();let K=ie(!1);Oe(()=>{if(m("WizardApp:useEffect fired",{startedAlready:K.current}),K.current){m("WizardApp:useEffect returning early (startedRef true)");return}K.current=!0,m("WizardApp:orchestrator starting");let f=0,S=0,C=null,I=null,F=0,Pe=p=>{let v=++f;return m("orchestrator:promptFn called",{id:v,type:p.type,message:p.message.slice(0,60)}),se(null),new Promise((P,s)=>{x({id:v,spec:p,resolve:w=>{m("orchestrator:prompt resolved",{id:v,type:p.type,value:typeof w=="string"?w.slice(0,30):w}),S++,P(w)},reject:w=>{m("orchestrator:prompt rejected",{id:v,reason:w.message}),s(w)}})})},Be=p=>{y(v=>[...v,p])};return(async()=>{try{let p=o?R.filter(s=>s.id===o):R,v=()=>p.filter(s=>s.isApplicable(n.current)).length,P=0;for(;P<p.length;){let s=p[P];if(!s.isApplicable(n.current)){i.current.set(s.id,"skipped"),P++,U(),g();continue}y(C?[{title:"Something went wrong in this step",body:`${C}
|
|
3
3
|
|
|
4
4
|
Your answers in the earlier steps are kept. Try this step again below.`+(F>=2?`
|
package/dist/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as we,c as qe,d as X,e as x,f as on,g as rn,h as Qe,i as Je,j as de,k as an,l as ln,o as cn,q as Ae,r as Xe,s as N}from"./chunk-
|
|
2
|
+
import{b as we,c as qe,d as X,e as x,f as on,g as rn,h as Qe,i as Je,j as de,k as an,l as ln,o as cn,q as Ae,r as Xe,s as N}from"./chunk-N7WRVWZQ.js";import{Command as Kr}from"commander";import{spawn as pn}from"child_process";import{existsSync as Ji}from"fs";import{homedir as Xi}from"os";import O from"picocolors";import{win32 as Di}from"path";var Fi=["&","^","%","!"];function Hi(e){return Fi.filter(t=>e.includes(t))}function Ee(e){let t=[];for(let{label:n,path:i}of e){let o=Hi(i);o.length>0&&t.push({label:n,path:i,chars:o})}return t}function Ui(e){let t=(e??"").trim().replace(/^["']|["']$/g,"");if(!t||t==="undefined"||t==="null")return null;let n=t.toLowerCase().split(/[\\/]/);if(n.length<2||n.includes("system32"))return null;let i=Di.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(i)?t:null}function Pe(e,t){let n=Ui(e);return n===null?!1:t?t(n):!0}function Se(e,t){let n=e[0],i=[...new Set(e.flatMap(f=>f.chars))],o=i.map(f=>`"${f}"`).join(", "),r=i.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 ue(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),i=parseInt(t[2],10),o=parseInt(t[3],10),r=`${n}.${i}.${o}`;return n<22||n===22&&i<15?{ok:!1,version:r,major:n,minor:i,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:i}}import{spawn as ji}from"child_process";import{existsSync as Ki}from"fs";import{homedir as Gi}from"os";import{delimiter as Vi,join as Ze}from"path";var Bi=new Set(["Restricted","AllSigned"]);function Yi(e,t=Ki){for(let n of e.split(Vi)){let i=n.replace(/"/g,"");if(!i)continue;let o=Ze(i,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let a=Ze(i,r);if(t(a))return{path:a,isPs1:!1}}}return null}async function un(){let e=Yi(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Wi();if(!t)return{blocked:!1,shimPath:e.path};let n=Ze(Gi(),".local","node")+"\\";return{blocked:Bi.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Wi(){let e=Ze(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await dn(e)??await dn("powershell.exe")}function dn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let i=ji(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",r=setTimeout(()=>{i.kill(),n(null)},8e3);i.stdout.on("data",a=>{o+=a.toString()}),i.stderr?.resume(),i.on("close",a=>{clearTimeout(r),n(a===0&&o.trim()?o.trim():null)}),i.on("error",()=>{clearTimeout(r),n(null)})})}import{spawn as zi}from"child_process";var Ue=3,et=10,qi=[["python3"],["python"],["py","-3"]];async function K(){for(let e of qi){let t=await tt(e[0],[...e.slice(1),"--version"]),n=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(n)||t.code!==0)continue;let i=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!i)continue;let o=parseInt(i[1],10),r=parseInt(i[2],10),a=i[3]?`${o}.${r}.${i[3]}`:`${o}.${r}`;return{command:[...e],version:a,major:o,minor:r}}return null}async function be(){let e=Qi(),t=await K();if(!t){let a=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${Ue}.${et}+ is not installed (or not on PATH). Install it from ${e}.`+a}}let{command:n,version:i,major:o,minor:r}=t;return o<Ue||o===Ue&&r<et?{ok:!1,version:i,major:o,minor:r,command:n,message:`Your installed Python is ${i}. Klaudius needs Python ${Ue}.${et} or newer (the pipeline depends on packages that only ship wheels for ${Ue}.${et}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:i,major:o,minor:r,command:n}}function Qi(){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 tt(e,t){return new Promise(n=>{let i=zi(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";i.stdout?.on("data",a=>{o+=a.toString()}),i.stderr?.on("data",a=>{r+=a.toString()}),i.on("close",a=>n({code:a??1,stdout:o,stderr:r})),i.on("error",()=>n({code:1,stdout:o,stderr:r}))})}var fn=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function hn(e={}){console.log(O.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
3
|
`));let t=[];t.push(Zi());let n=await be();if(t.push(es(n)),t.push(await ts(n.command)),t.push(await ns()),process.platform==="win32"){let o=await is();o&&t.push(o);let r=await ss();r&&t.push(r)}t.push(await os());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 i=t.filter(o=>o.status==="fail");if(i.length===0){let o=t.filter(r=>r.status==="warn").length;rs(o);return}console.log(O.red(O.bold(`${i.length} check${i.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(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 Zi(){let e=ue();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal window before re-running."}}function es(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 ts(e){let t=e??["python3"],n=await nt(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
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 ns(){let e=process.platform==="win32",t=await nt("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 nt("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 is(){let e=await un();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 ss(){let e=Ee([{label:"your Windows user folder",path:Xi()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await nt("npm",["config","get","script-shell"],!0),i=n.code===0?n.stdout.trim():void 0;if(Pe(i,Ji))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(l=>`"${l}"`).join(", ")}, but npm's script-shell (${i}) handles it`};let{detail:o,action:r}=Se(e,"preflight"),a=e.some(l=>l.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function os(){try{return await fetch(fn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:fn}}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 rs(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 WINDOW 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 window.")),console.log()}function nt(e,t,n=!1){return new Promise(i=>{let o=n?pn([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):pn(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>i({code:l??1,stdout:r,stderr:a})),o.on("error",()=>i({code:1,stdout:r,stderr:a}))})}import{mkdir as Gt,readdir as ui,readFile as Vt,stat as Bt,writeFile as Kt}from"fs/promises";import{spawnSync as Yt}from"child_process";import{homedir as vo}from"os";import{resolve as Oo,isAbsolute as Lo,join as Z,normalize as $o}from"path";import*as P from"@clack/prompts";import h from"picocolors";var as={GB:"44",US:"1",CA:"1",AU:"61",NZ:"64",IE:"353",DE:"49",FR:"33",ES:"34",IT:"39",NL:"31",BE:"32",CH:"41",AT:"43",PT:"351",SE:"46",NO:"47",DK:"45",FI:"358",PL:"48",ZA:"27"},ls={US:{pre:"$"},CA:{pre:"$"},AU:{pre:"$"},NZ:{pre:"$"},GB:{pre:"\xA3"},IE:{pre:"\u20AC"},DE:{pre:"\u20AC"},FR:{pre:"\u20AC"},ES:{pre:"\u20AC"},IT:{pre:"\u20AC"},NL:{pre:"\u20AC"},BE:{pre:"\u20AC"},AT:{pre:"\u20AC"},PT:{pre:"\u20AC"},FI:{pre:"\u20AC"},CH:{pre:"CHF "},SE:{post:" kr"},NO:{post:" kr"},DK:{post:" kr"},PL:{post:" z\u0142"},ZA:{pre:"R"}};function mn(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let i=ls[(t??"").toUpperCase()];return i?`${i.pre??""}${n}${i.post??""}`:n}function $t(e,t){if(!e)return e;let n=e.replace(/[\s().-]/g,"");if(/^\+\d{8,15}$/.test(n))return n;if(/^00\d{8,15}$/.test(n))return`+${n.slice(2)}`;let i=t?as[t.toUpperCase()]:void 0;return i==="1"&&/^1?\d{10}$/.test(n)?`+1${n.slice(-10)}`:i&&i!=="1"&&/^0\d{7,14}$/.test(n)?`+${i}${n.slice(1)}`:e}var Nt="claude-code",Mt="gpt-5.6-terra";function gn(e){if(e==="claude-code"||e==="codex")return e}var cs=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function it(e){let t=e?.trim().toLowerCase()??"";return cs.includes(t)?t:void 0}function st(e){let t=e?.trim().toLowerCase();if(t==="on"||t==="true"||t==="yes"||t==="1")return"on";if(t==="off"||t==="false"||t==="no"||t==="0")return"off"}var Dt="vercel";function yn(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function kn(e){if(e==="telegram"||e==="email"||e==="sms")return e}function wn(e){if(e==="password"||e==="oauth-microsoft")return e}function ds(e){if(e==="custom"||e!==void 0&&Object.hasOwn(X,e))return e}function ot(e){let t=ds(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[i,o]of Object.entries(X))if(o.smtpHost===n)return i;return"custom"}}function An(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let i of t.split(",")){let o=i.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(i=>{let o=/^[a-z0-9_]+$/.test(i)&&i!=="auto",r=l=>{let c=e[`EMAIL_ACCOUNT_${i.toUpperCase()}_${l}`];return c?.trim()?c.trim():void 0},a=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(l=>!r(l)).map(l=>`EMAIL_ACCOUNT_${i.toUpperCase()}_${l}`);for(let l of["SMTP_PORT","IMAP_PORT"]){let c=r(l);c!==void 0&&!/^\d+$/.test(c)&&a.push(`EMAIL_ACCOUNT_${i.toUpperCase()}_${l}`)}return{label:i,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:a,smtpHost:r("SMTP_HOST"),smtpPort:parseInt(r("SMTP_PORT")??"587",10),imapHost:r("IMAP_HOST"),imapPort:parseInt(r("IMAP_PORT")??"993",10),password:r("PASSWORD"),login:r("LOGIN")}})}function rt(e){let t=[],n=l=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${l}`),t.push("# "+"=".repeat(60)),t.push("")},i=(l,c)=>{if(c==null||c===""){t.push(`# ${l}=`);return}let f=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(f)){let u=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${l}="${u}"`)}else t.push(`${l}=${f}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),i("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),i("AI_AGENT",e.aiAgent??Nt),i("AI_PLAN",e.aiPlan),i("QA_PHASE",e.qaPhase??Ae(e.aiPlan)),n("Operating country and language"),i("OPERATOR_COUNTRY",e.country),i("OPERATOR_COUNTRY_CODE",e.countryCode),i("OPERATOR_LANGUAGE",e.language),i("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let o=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];i("PIPELINE_MODES",[...new Set(o)].join(",")),n("Pricing"),i("PRICING",mn(e.pricing,e.countryCode)),i("PRICING_TERMS",e.pricingTerms),i("PRICING_MONTHLY",mn(e.pricingMonthly,e.countryCode)),n("Automated outreach features"),i("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),i("OPERATOR_NAME",e.name),i("SIGNATURE",e.signature),i("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),i("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),i("EMAIL_PROVIDER",e.emailProvider),i("EMAIL_AUTH",e.emailAuth??"password"),i("EMAIL_ADDRESS",e.emailAddress),i("EMAIL_PASSWORD",e.emailPassword),i("EMAIL_FROM_NAME",e.emailFromName),i("EMAIL_SMTP_HOST",e.emailSmtpHost),i("EMAIL_SMTP_PORT",e.emailSmtpPort),i("EMAIL_IMAP_HOST",e.emailImapHost),i("EMAIL_IMAP_PORT",e.emailImapPort),i("EMAIL_SENT_FOLDER",e.emailSentFolder),i("EMAIL_INBOX_FOLDER",e.emailInboxFolder),i("EMAIL_DRAFTS_FOLDER",e.emailDraftsFolder),n("SMS outreach"),i("SMS_PROVIDER",e.smsProvider),i("TEST_PHONE",$t(e.testPhone,e.countryCode)),i("TWILIO_ACCOUNT_SID",e.twilioAccountSid),i("TWILIO_AUTH_TOKEN",e.twilioAuthToken),i("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),i("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Letter outreach"),i("LETTER_PROVIDER",e.letterProvider??"none"),i("PINGEN_CLIENT_ID",e.pingenClientId),i("PINGEN_CLIENT_SECRET",e.pingenClientSecret),i("PINGEN_ORG_ID",e.pingenOrgId),i("POSTGRID_API_KEY",e.postgridApiKey),n("Supabase (pipeline state)"),i("SUPABASE_URL",e.supabaseUrl),i("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),i("SUPABASE_ANON_KEY",e.supabaseAnonKey),i("SUPABASE_PAT",e.supabasePat),i("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),i("DEPLOY_PROVIDER",e.deployProvider??Dt),i("VERCEL_TOKEN",e.vercelToken),i("VERCEL_SCOPE",e.vercelScope??""),i("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),i("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),i("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),i("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),i("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),i("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),i("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),i("NOTIFY_CHANNEL",e.notifyChannel),i("NOTIFY_TO",e.notifyTo),i("TELEGRAM_BOT_TOKEN",e.telegramBotToken),i("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(l=>/^#?\s*([A-Z0-9_]+)=/.exec(l)?.[1]).filter(l=>!!l)),a=Object.entries(e.preservedEnv??{}).filter(([l])=>!r.has(l));if(a.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[l,c]of a)i(l,c)}return t.join(`
|
|
5
5
|
`)+`
|
|
@@ -11,8 +11,8 @@ import{b as we,c as qe,d as X,e as x,f as on,g as rn,h as Qe,i as Je,j as de,k a
|
|
|
11
11
|
`)+`
|
|
12
12
|
`}function fs(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 G(e){let t={};for(let n of e.split(`
|
|
13
13
|
`)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o===-1)continue;let r=i.slice(0,o).trim(),a=fs(i.slice(o+1).trim());t[r]=a}return t}function Sn(e){let t=l=>{let c=e[l];if(!c)return;let f=parseInt(c,10);return isNaN(f)?void 0:f},n=e.SMS_PROVIDER,i=l=>l==="email"||l==="sms"||l==="whatsapp"||l==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(l=>l.trim()).filter(i),r=e.OUTREACH_PRIORITY?.split(",").map(l=>l.trim()).filter(i),a=e.WHATSAPP_ACCOUNTS?.split(",").map(l=>l.trim()).filter(l=>l.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:gn(e.AI_AGENT)??Nt,aiPlan:it(e.AI_PLAN),qaPhase:st(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:r&&r.length>0?r:void 0,whatsappAccounts:a&&a.length>0?a:void 0,emailProvider:ot(e),emailAuth:wn(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:$t(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:yn(e.DEPLOY_PROVIDER)??Dt,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:kn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function ct(e){let t=_=>{let ce=e[_];if(!ce)return;let j=parseInt(ce,10);return isNaN(j)?void 0:j},n=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),r=e.SUPABASE_PROJECT_REF,a=e.PRICING,l=e.PRICING_TERMS||"one-off, no monthly fees",c=yn(e.DEPLOY_PROVIDER)??Dt,f=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,A=e.CLOUDFLARE_ACCOUNT_ID,d=e.NETLIFY_AUTH_TOKEN,b=e.SELFHOST_DEPLOY_TARGET,g=e.SELFHOST_URL_TEMPLATE;if(!a||!n||!i||!o||!r||!(c==="cloudflare"?!!u&&!!A:c==="netlify"?!!d:c==="selfhost"?!!b&&!!g:!!f))return null;let S=e.SMS_PROVIDER,C=_=>_==="email"||_==="sms"||_==="whatsapp"||_==="letter",B=e.OUTREACH_CHANNELS?.split(",").map(_=>_.trim()).filter(C),le=e.OUTREACH_PRIORITY?.split(",").map(_=>_.trim()).filter(C),R=e.WHATSAPP_ACCOUNTS?.split(",").map(_=>_.trim()).filter(_=>_.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:gn(e.AI_AGENT)??Nt,aiPlan:it(e.AI_PLAN),qaPhase:st(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(_=>_.trim().toLowerCase()).filter(Boolean):void 0,pricing:a,pricingTerms:l,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:B&&B.length>0?B:void 0,outreachPriority:le&&le.length>0?le:void 0,whatsappAccounts:R&&R.length>0?R:void 0,emailProvider:ot(e),emailAuth:wn(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:S==="imessage"||S==="twilio"?S:void 0,testPhone:$t(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,deployProvider:c,vercelToken:f,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:A||void 0,netlifyAuthToken:d||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:b||void 0,selfhostUrlTemplate:g||void 0,supabaseUrl:n,supabaseServiceKey:i,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:kn(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 Es,stat as Ea}from"fs/promises";import{dirname as Sa,join as Rn,relative as Ps,sep as Ss}from"path";import{fileURLToPath as _a}from"url";import{createHash as bn}from"crypto";import{readFile as hs}from"fs/promises";async function _e(e){let t=await hs(e);return bn("sha256").update(t).digest("hex")}function Ft(e){return bn("sha256").update(e).digest("hex")}import{mkdir as ms,readFile as gs,writeFile as ys,access as ks}from"fs/promises";import{dirname as ws,join as _n}from"path";var As=".klaudius",Tn=`${As}/manifest.json`,dt=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json"]),In=new Set(["clients/README.md"]),ut=new Set(["package-lock.json"]);async function Cn(e){let t=_n(e,Tn);try{await ks(t)}catch{return null}let n=await gs(t,"utf-8"),i=JSON.parse(n),o={};for(let[r,a]of Object.entries(i.files??{}))o[r.split("\\").join("/")]=a;return i.files=o,Array.isArray(i.ignored)?i.ignored=i.ignored.filter(r=>typeof r=="string").map(r=>r.split("\\").join("/")):delete i.ignored,i}async function je(e,t){let n=_n(e,Tn);await ms(ws(n),{recursive:!0}),await ys(n,JSON.stringify(t,null,2)+`
|
|
14
|
-
`,"utf-8")}function xn(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function ge(e,t=e){let n=await Es(e,{withFileTypes:!0}),i=[];for(let o of n){let r=Rn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?i.push(...await ge(r,t)):o.isFile()&&i.push(Ps(t,r).split(Ss).join("/")))}return i}async function vn(e){let t=await ge(e),n={};for(let i of t)dt.has(i)||(n[i]=await _e(Rn(e,i)));return n}import{copyFile as bs,mkdir as On,mkdtemp as _s,readdir as Ln,rm as $n}from"fs/promises";import{tmpdir as Ts}from"os";import{dirname as Is,join as pt}from"path";import{Readable as Cs}from"stream";import*as Nn from"tar";var xs="https://klaudius.dev/api/template";function Rs(e){return Cs.fromWeb(e)}async function ft(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??xs,n="0.32.
|
|
15
|
-
`+pe.bold(pe.cyan(e))),detail:e=>console.log(pe.dim(" "+e))};var Ms="https://registry.npmjs.org/klaudius/latest";async function Ds(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Ms,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let o=await i.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function Fs(e,t){let n=r=>r.split("-")[0].split(".").map(a=>Number.parseInt(a,10)),i=n(e),o=n(t);if(i.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(i[r])||Number.isNaN(o[r]))return!1;if(i[r]>o[r])return!0;if(i[r]<o[r])return!1}return!1}async function gt(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Ds();!n||!Fs(n,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(s.detail("Your project content is fetched fresh either way, so you're not missing any"),s.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),s.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),s.blank())}import{createHash as Hs}from"crypto";import{hostname as Kn,userInfo as Us,platform as Gn,arch as Vn}from"os";var js="https://klaudius.dev",Ks="/api/licenses/validate",Gs="0.32.
|
|
14
|
+
`,"utf-8")}function xn(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function ge(e,t=e){let n=await Es(e,{withFileTypes:!0}),i=[];for(let o of n){let r=Rn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?i.push(...await ge(r,t)):o.isFile()&&i.push(Ps(t,r).split(Ss).join("/")))}return i}async function vn(e){let t=await ge(e),n={};for(let i of t)dt.has(i)||(n[i]=await _e(Rn(e,i)));return n}import{copyFile as bs,mkdir as On,mkdtemp as _s,readdir as Ln,rm as $n}from"fs/promises";import{tmpdir as Ts}from"os";import{dirname as Is,join as pt}from"path";import{Readable as Cs}from"stream";import*as Nn from"tar";var xs="https://klaudius.dev/api/template";function Rs(e){return Cs.fromWeb(e)}async function ft(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??xs,n="0.32.4",i;try{i=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(l){throw new Error(`Could not reach klaudius.dev to download the template: ${x(l)}`)}if(!i.ok){let l="";try{let c=await i.json();l=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${i.status}${l}`)}if(!i.body)throw new Error("Template download succeeded but response had no body");let o=i.headers.get("x-klaudius-tier"),r=await _s(pt(Ts(),"klaudius-template-")),a=0;try{try{await new Promise((f,u)=>{let A=Nn.extract({cwd:r,strict:!0});A.on("finish",f),A.on("error",u),Rs(i.body).on("error",u).pipe(A)})}catch(f){throw new Error(`Failed to extract template archive: ${f.message}`)}await On(e.destDir,{recursive:!0});let l=new Set(await Ln(e.destDir)),c=await ge(r);try{for(let f of c){let u=pt(e.destDir,f);await On(Is(u),{recursive:!0}),await bs(pt(r,f),u),a++}}catch(f){let u=await Ln(e.destDir).catch(()=>[]);for(let A of u)l.has(A)||await $n(pt(e.destDir,A),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${f.message}`)}}finally{await $n(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:a,tier:o}}import{copyFile as vs,mkdir as Os,readFile as Mn,rm as Ls}from"fs/promises";import{dirname as $s,join as ye}from"path";import{structuredPatch as Ns}from"diff";var Dn=ye(".klaudius","base"),ht=ye(".klaudius","conflict-base");async function mt(e,t,n){let i=ye(e,Dn);await Ls(i,{recursive:!0,force:!0});for(let o of n){let r=ye(i,o);await Os($s(r),{recursive:!0}),await vs(ye(t,o),r)}}async function Fn(e,t){try{return await Mn(ye(e,Dn,t),"utf-8")}catch{return null}}async function Hn(e,t){try{return await Mn(ye(e,ht,t),"utf-8")}catch{return null}}function Un(e,t,n,i){return Te(n)?null:e!==null&&!Te(e)&&(!i||Ft(e)===i)?e:t!==null&&!Te(t)&&i&&Ft(t)===i?t:null}function Te(e){return e.includes("\0")||e.includes("\uFFFD")}function jn(e,t,n=60){let i=Ns("base","new",e,t,"","",{context:2});if(i.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=i.hunks.map(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),r=[`Upstream changed ${i.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],a=0,l=!1;for(let c of i.hunks){if(a>=n){l=!0;break}r.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),a+=1;let f=Math.max(n-a,0),u=c.lines.slice(0,f);if(r.push(...u),a+=u.length,u.length<c.lines.length){l=!0;break}}return r.push("```"),l&&r.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),r}import pe from"picocolors";var s={info:e=>console.log(pe.cyan("\u2139"),e),success:e=>console.log(pe.green("\u2713"),e),warn:e=>console.log(pe.yellow("\u26A0"),e),error:e=>console.error(pe.red("\u2717"),e),step:e=>console.log(pe.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+pe.bold(pe.cyan(e))),detail:e=>console.log(pe.dim(" "+e))};var Ms="https://registry.npmjs.org/klaudius/latest";async function Ds(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Ms,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let o=await i.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function Fs(e,t){let n=r=>r.split("-")[0].split(".").map(a=>Number.parseInt(a,10)),i=n(e),o=n(t);if(i.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(i[r])||Number.isNaN(o[r]))return!1;if(i[r]>o[r])return!0;if(i[r]<o[r])return!1}return!1}async function gt(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Ds();!n||!Fs(n,t)||(s.blank(),s.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(s.detail("Your project content is fetched fresh either way, so you're not missing any"),s.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),s.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),s.blank())}import{createHash as Hs}from"crypto";import{hostname as Kn,userInfo as Us,platform as Gn,arch as Vn}from"os";var js="https://klaudius.dev",Ks="/api/licenses/validate",Gs="0.32.4";async function Bn(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),i=(process.env.KLAUDIUS_API_URL??js).replace(/\/$/,"")+Ks,o=Ke(),r;try{r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Kn(),os:`${Gn()}-${Vn()}`,cli_version:Gs})})}catch(l){return{ok:!1,reason:`Could not reach the Klaudius license server (${x(l)}). Check your internet connection or try again later.`}}let a;try{a=await r.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${r.status}).`}}return a.ok?{ok:!0,tier:a.tier??"core"}:{ok:!1,reason:a.reason??`License rejected (HTTP ${r.status}).`}}function Ke(){let e=[Kn(),Us().username,Gn(),Vn()].join("|");return Hs("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Vs}from"fs/promises";import{join as Bs}from"path";async function Ie(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: ${x(n)}`}}}async function Yn(e){let t;try{t=await Vs(Bs(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(i){return{ok:!1,message:`Could not read scripts/schema.sql: ${i.message}`}}let n=e.pat.replace(/\s+/g,"");try{let i=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(i.ok)return{ok:!0};let o=await i.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(s.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${i.status}): ${o.slice(0,300)}`}}catch(i){return{ok:!1,message:`Schema apply failed: ${i.message}`}}}function Ys(e){try{let t=JSON.parse(e);return t.error?.code==="not_found"?!0:/user not found/i.test(t.error?.message??"")}catch{return!1}}function Ws(e,t){return e===401||e===403?{kind:"rejected",message:`Vercel rejected the token (HTTP ${e}). It may be invalid, expired or revoked.`}:e===404&&Ys(t)?{kind:"scope",message:"Vercel rejected the token (HTTP 404). Its Scope doesn't include your account, for example it was limited to a single project."}:{kind:"api",message:`Vercel API returned HTTP ${e}. Try again or check status.vercel.com.`}}async function Ce(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let i=await t.text().catch(()=>"");return{ok:!1,...Ws(t.status,i)}}let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,kind:"network",message:`Could not reach Vercel: ${x(t)}`}}}var Wn="https://api.cloudflare.com/client/v4";function zn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function xe(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${Wn}/user/tokens/verify`,{headers:i});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let r=await o.json(),a=r.result?.status;if(r.success===!1||a&&a!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${a?` (status: ${a})`:""}. ${zn(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${x(o)}`}}try{let o=await fetch(`${Wn}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:i});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:zn(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: ${x(o)}`}}}var qn="https://api.netlify.com/api/v1";async function Re(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${qn}/user`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} verifying the token. Try again or check netlifystatus.com.`}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${x(i)}`}}try{let i=await fetch(`${qn}/accounts`,{headers:n});if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} listing your teams. Try again or check netlifystatus.com.`};let o=await i.json(),r=Array.isArray(o)?o:[];if(r.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let a=typeof r[0]?.slug=="string"?r[0].slug:void 0;return{ok:!0,accountCount:r.length,accountSlug:a}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${x(i)}`}}}function zs(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,i=/caller does not have permission|billing/i.test(t)?"This usually means the key's Google Cloud project has no active billing account \u2014 Places needs billing set up even though Google's free monthly credit covers normal use. Check https://console.cloud.google.com/billing for the project this key belongs to. (Less often: the key's restrictions block the Places API \u2014 check Credentials.)":"Common causes: the key is wrong or deleted, billing is not enabled on its Cloud project, or the key's restrictions block the Places API. Check https://console.cloud.google.com/billing and the key's entry under Credentials.";return`${n} ${i}`}async function ve(e){let t=an(e);if(t)return{ok:!1,message:t};let n=de(e),i=n.value,o=r=>{let a=[r],l=ln(e);return l&&a.push(l),n.repairs.length>0&&a.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),a.join(`
|
|
16
16
|
`)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":i,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let a={};try{a=await r.json()}catch{}let l=a.error?.message??"",c=a.error?.status??"";return r.status===400&&(c==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(l))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library/places.googleapis.com and press Enable for the project this key belongs to, then try again. (That page is 'Places API (New)' \u2014 the older 'Places API' is a different API and won't work.)"}:r.status===401||r.status===403?{ok:!1,message:o(zs(r.status,l))}:{ok:!1,message:o(`Google API returned HTTP ${r.status}${l?`: ${l}`:""}.`)}}catch(r){return{ok:!1,message:`Could not reach Google: ${x(r)}`}}}import qs from"nodemailer";import{ImapFlow as Qs}from"imapflow";function Js(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function Qn(e,t,n){let i=t.toLowerCase(),o=e.filter(Js);if(o.some(l=>l.path.toLowerCase()===i))return;let r=i.startsWith("inbox")?void 0:[`inbox.${i}`,`inbox/${i}`],a=o.find(l=>l.specialUse===n)?.path??(r&&o.find(l=>r.includes(l.path.toLowerCase()))?.path);return{configured:t,detected:a||void 0}}function Jn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let i=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return i.includes("invalid credentials")||i.includes("authentication failed")||i.includes("auth failed")||i.includes("login failed")||i.includes("invalid login")?"auth":i.includes("etimedout")||i.includes("timeout")||i.includes("enotfound")||i.includes("getaddrinfo")||i.includes("econnrefused")||i.includes("econnreset")?"network":"other"}async function oe(e){let t=qs.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(a){return{ok:!1,failedAt:"smtp",message:Xn(a,"SMTP",e.usesAccountPassword),failureKind:Jn(a)}}finally{t.close()}let n=new Qs({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),i,o,r;try{if(await n.connect(),e.sentFolder||e.draftsFolder)try{let a=await n.list();e.sentFolder&&(i=Qn(a,e.sentFolder,"\\Sent")),e.draftsFolder&&(o=Qn(a,e.draftsFolder,"\\Drafts"))}catch{r=!0}await n.logout()}catch(a){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Xn(a,"IMAP",e.usesAccountPassword),failureKind:Jn(a)}}return{ok:!0,sentFolderIssue:i,draftsFolderIssue:o,foldersUnverified:r}}function Xn(e,t,n){let i=e instanceof Error?e.message:String(e),o=i.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.
|
|
@@ -27,7 +27,7 @@ import{b as we,c as qe,d as X,e as x,f as on,g as rn,h as Qe,i as Je,j as de,k a
|
|
|
27
27
|
`+t;return ro.some(i=>i.test(n))}function ii(e){return new Promise(t=>setTimeout(t,e))}function ao(e,t,n){return new Promise(i=>{let o=n.shell?At([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):At(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),r="",a="";o.stdout?.on("data",l=>{let c=l.toString();r+=c,process.stdout.write(c)}),o.stderr?.on("data",l=>{let c=l.toString();a+=c,process.stderr.write(c)}),o.on("close",l=>i({code:l??1,stdout:r,stderr:a})),o.on("error",l=>i({code:1,stdout:r,stderr:a+l.message}))})}async function Ht(e,t,n){let i={code:0,stdout:"",stderr:""};for(let o=0;o<=Oe;o++){if(i=await ao(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!ni(i.stderr,i.stdout))return i;o<Oe&&(s.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${Oe+1})\u2026`),await ii(ti))}return i}function lo(e,t,n){return new Promise(i=>{let o=At(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>i({code:l??1,stdout:r,stderr:a})),o.on("error",l=>i({code:1,stdout:r,stderr:a+l.message}))})}var co=[{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 uo(e){let t=`${e.stderr??""}
|
|
28
28
|
${e.stdout??""}`;return co.find(i=>i.pattern.test(t))?.hint}async function po(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await K())?.command??["python3"],r=async l=>{let c={code:0,stdout:"",stderr:""};for(let f=0;f<=Oe;f++){if(c=await lo(o[0],[...o.slice(1),...l],{cwd:e}),c.code===0||!ni(c.stderr,c.stdout))return c;f<Oe&&(s.detail(`pip install hit a transient network error \u2014 retrying (${f+2}/${Oe+1})\u2026`),await ii(ti))}return c},a=await r([...n,"--break-system-packages",...t]);return a.code!==0&&/no such option:.*break-system-packages/i.test(a.stderr)&&(s.detail("Older pip detected; retrying without --break-system-packages"),a=await r([...n,...t])),a.code!==0&&(a.stderr.trim()&&process.stderr.write(a.stderr),a.stdout.trim()&&process.stdout.write(a.stdout)),a}async function Et(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=oo(),i=process.platform==="win32",o;if(i){let u=Ee([{label:"your Windows user folder",path:so()},{label:"the project folder",path:e}]);if(u.length>0){let A=await new Promise(b=>{let g=At("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),k="",S="";g.stdout?.on("data",C=>{k+=C.toString()}),g.stderr?.on("data",C=>{S+=C.toString()}),g.on("close",C=>b({code:C??1,stdout:k,stderr:S})),g.on("error",C=>b({code:1,stdout:k,stderr:C.message}))}),d=A.code===0?A.stdout.trim():void 0;if(!Pe(d,io)){let{detail:b,action:g}=Se(u,"install");o=`${b}. ${g}`}}}let r=(u,A)=>{let d=uo(A);if(d){(t.hints??={})[u]=d;return}o&&(u==="npm"||u==="playwright"||u==="patchright")&&!Object.values(t.hints??{}).includes(o)&&((t.hints??={})[u]=o)};s.step("Running npm install (Next.js, Playwright JS, etc.)...");let a=await Ht("npm",["install"],{cwd:e,label:"npm install",env:n,shell:i});t.npm=a.code===0?"ok":"failed",a.code!==0&&r("npm",a),s.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await po(e);t.pip=l.code===0?"ok":"failed",l.code!==0&&r("pip",l),s.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Ht("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:i});t.playwright=c.code===0?"ok":"failed",c.code!==0&&r("playwright",c),s.step("Installing Patchright browser (chromium ~200MB; one-time)...");let f=await Ht("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:i});return t.patchright=f.code===0?"ok":"failed",f.code!==0&&r("patchright",f),t}import{copyFile as fo,access as ho}from"fs/promises";import{dirname as mo,join as go}from"path";async function si(){let e=await tt("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 Ut(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await si();if(e.state==="real")return{status:"ok",version:e.version};let t=await K();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function yo(e){let[t,...n]=e.command,i=await tt(t,[...n,"-c","import sys; print(sys.executable)"]),o=i.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(i.code!==0||!o)return{ok:!1,reason:"no-exe-path"};let r=go(mo(o),"python3.exe"),a=await ho(r).then(()=>!0,()=>!1);if(!a){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await fo(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let l=await si();return{ok:!0,target:r,created:!a,verified:l.state==="real",postState:l.state==="real"?void 0:l.state}}var ko="A real python3.exe now exists, but the Microsoft Store placeholder still shadows it. Turn OFF both `python.exe` and `python3.exe` under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases, then open a fresh terminal.";async function Pt(){let e=await Ut();if(e.status!=="broken")return;let t=await yo(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.";s.success(n);return}if(t.ok&&t.postState==="stub"){s.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),s.detail(ko);return}if(t.ok){s.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."),s.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"){s.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"){s.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),s.detail(t.manualCommand??"");return}s.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 wo,spawnSync as oi}from"child_process";import{mkdtemp as Ao,rm as Eo,rmdir as Po,writeFile as So,stat as jt,unlink as bo,mkdir as _o}from"fs/promises";import{createServer as To}from"net";import{tmpdir as Io}from"os";import{join as Le}from"path";function Co(){return new Promise((e,t)=>{let n=To();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let i=n.address(),o=typeof i=="object"&&i?i.port:0;n.close(()=>e(o))})})}function St(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?oi(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):oi("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function bt(e){try{return await xo(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function xo(e){let t=`klaudius-smoke-${process.pid}`,n=Le(".klaudius",`qa-smoke-${process.pid}.png`),i=Le(e,n),o,r,a=!1;try{o=await Ao(Le(Io(),"klaudius-qa-smoke-")),await So(Le(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let l=await Co();r=wo("python3",["-m","http.server",String(l),"--directory",o],{stdio:"ignore",shell:!1});let c=!1;r.on("error",()=>{c=!0}),r.on("exit",()=>{c=!0});let f=`http://127.0.0.1:${l}/`,u=!1;for(let S=0;S<24&&!c;S++)try{if((await fetch(f,{signal:AbortSignal.timeout(1e3)})).ok){u=!0;break}}catch{await new Promise(C=>setTimeout(C,500))}if(!u)return{ok:!1,stage:"python3-server",detail:"`python3 -m http.server` never came up on a free local port",remediation:process.platform==="win32"?"python3 on this machine isn't runnable (usually the Microsoft Store placeholder). Running `npx klaudius@latest update` fixes it automatically.":"Check `python3 --version` works in this terminal."};let A=Le(e,".klaudius"),d=await jt(A).then(()=>!0,()=>!1);await _o(A,{recursive:!0}),a=!d;let b=St(e,[`-s=${t}`,"open",f]);if(b.status!==0)return{ok:!1,stage:"browser",detail:((b.stderr??"")+(b.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=St(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await jt(i).catch(()=>null);if((!k||k.size===0)&&(g=St(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),k=await jt(i).catch(()=>null)),!k||k.size===0){let S=((g.stderr??"")+(g.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${S?` (${S})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{St(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await bo(i).catch(()=>{}),a&&await Po(Le(e,".klaudius")).catch(()=>{}),o&&await Eo(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as ri,readFile as Ro,writeFile as ai}from"fs/promises";import{join as _t}from"path";var $e="Bash(claude --bg --permission-mode auto *)";async function li(e){let t;try{t=await Ro(e,"utf-8")}catch{return{}}try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return null}async function Ne(e,t){let n=_t(e,".claude"),i=_t(n,"settings.local.json"),o=".claude/settings.local.json";try{await ri(n,{recursive:!0});let r=await li(i);if(r===null)return s.warn(`${o} isn't valid JSON, so it was left as-is. Fix it and re-run to pre-approve the parallel-run dispatch.`),"skipped";let a=r.permissions&&typeof r.permissions=="object"&&!Array.isArray(r.permissions)?r.permissions:{},l=a.allow,c=Array.isArray(l)?l.filter(u=>typeof u=="string"):[];if(c.includes(t))return"present";c.push(t);let f={...r,permissions:{...a,allow:c}};return await ai(i,JSON.stringify(f,null,2)+`
|
|
29
29
|
`,"utf-8"),"added"}catch(r){return s.warn(`Couldn't write ${o} (${r instanceof Error?r.message:String(r)}). The parallel-run dispatch may occasionally ask for approval.`),"skipped"}}async function Tt(e,t){let n=_t(e,".claude");await ri(n,{recursive:!0});let i=_t(n,"settings.json"),o=await li(i)??{},r=o.enabledMcpjsonServers,a=Array.isArray(r)?r.filter(c=>typeof c=="string"):[];a.includes(t)||a.push(t);let l={...o,enabledMcpjsonServers:a};await ai(i,JSON.stringify(l,null,2)+`
|
|
30
|
-
`,"utf-8")}var ci="0.32.
|
|
30
|
+
`,"utf-8")}var ci="0.32.4",L=5,F=!1;function H(e,t){s.blank(),console.error(`INIT-BLOCKED section=${e}`),console.error(t),console.error("Fix this section's values in the answers file and re-run the same init command. Progress so far is saved in .env."),process.exit(2)}async function No(e){let t;try{t=await Vt(e,"utf-8")}catch{H("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let i=JSON.parse(n),o={};for(let[r,a]of Object.entries(i))a!=null&&(o[r]=typeof a=="string"?a:String(a));return o}catch(i){H("answers",`Answers file is not valid JSON: ${i.message}`)}return G(t)}function re(e){return`npx klaudius@latest init ${It(Me(e))}`}function Me(e){if(process.platform==="win32")return e;let t=vo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Mo(e){let t=[];try{let i=(await ui(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of i){let r=Z(e,o.name);if(!await di(Z(r,".env")))continue;let a=await di(Z(r,".klaudius","manifest.json"));if(t.push({path:r,finished:a}),t.length>=3)break}}catch{}return t}async function di(e){try{return await Bt(e),!0}catch{return!1}}function It(e){return/\s/.test(e)?`"${e}"`:e}function te(e,t,n){s.blank(),s.error(`${t} validation failed ${L} times in a row. Pausing setup so you don't get stuck in a loop.`),s.detail(`Last error: ${n}`),s.blank(),s.detail("Your credentials are saved in `.env`. Two ways forward:"),s.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),s.blank(),console.log(` ${h.cyan(re(e))}`),s.blank(),s.detail(` (Your .env is at ${Me(Z(e,".env"))} \u2014 open it in any text editor.)`),s.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),s.blank(),process.exit(1)}async function pi(e){let t=e.target??".",n=Lo(t)?t:Oo(process.cwd(),t),i=Uo(n);i&&(s.error("Klaudius can't be installed inside a protected system folder."),s.detail(`Path: ${n}`),s.detail(`Reason: ${i}`),s.blank(),s.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),s.blank(),process.platform==="win32"?(s.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${h.cyan("cd $HOME\\Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)):(s.detail("For example:"),console.log(` ${h.cyan("cd ~/Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)),s.blank(),process.exit(1)),process.platform==="win32"&&jo()&&(s.warn("You appear to be running in an elevated (Administrator) PowerShell."),s.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."),s.blank()),await gt("init",ci);let o=await Do(n);if(o.kind==="scaffolded"){s.blank(),s.warn(`Found an existing Klaudius project at ${h.bold(n)}.`),s.detail("(Your .env and project files are in place.)"),s.blank(),o.nodeModulesMissing?(s.detail("It looks like a previous setup didn't finish installing dependencies."),s.detail("To pick up where it left off, run:"),s.blank(),n!==process.cwd()&&console.log(` ${h.cyan(`cd ${It(t)}`)}`),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retries npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Everything is scaffolded and dependencies look installed."),s.detail("Pick the action you wanted:"),s.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${h.cyan("npx klaudius@latest configure")} ${h.dim("# change a credential / API key")}`),console.log(` ${h.cyan("npx klaudius@latest update")} ${h.dim("# pull the latest skills, scripts, lessons")}`),s.blank()),s.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),s.blank();return}if(o.kind==="occupied"){let p=t===".",y=await Mo(n);if(y.length>0){s.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),s.detail(`You're in: ${Me(n)}`),s.blank();for(let m of y)s.detail(m.finished?`Found a finished project at ${Me(m.path)}. To work in it:`:`Found an unfinished setup at ${Me(m.path)}. To pick up where it left off:`),s.blank(),m.finished?(console.log(` ${h.cyan(`cd ${Me(m.path)}`)}`),console.log(` ${h.cyan("claude")} ${h.dim("# open Claude Code in the project")}`)):console.log(` ${h.cyan(re(m.path))} ${h.dim("# then pick Resume")}`),s.blank();process.exit(1)}s.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),s.detail(`Path: ${n}`),s.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),s.blank(),p?(s.detail("Two ways forward:"),s.blank(),s.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`),s.blank(),s.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${h.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(s.detail(`The folder '${t}' already exists and isn't empty.`),s.detail("Either pick a different name:"),console.log(` ${h.cyan(`npx klaudius@latest init ${t}-2`)}`),s.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=null;e.answers&&(F=!0,r=await No(e.answers),s.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let a=e.license??r?.KLAUDIUS_LICENSE_KEY;F&&(!a||a.trim().length===0)&&H("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let l=await Ho(a),c=P.spinner();c.start("Validating license");let f=await Bn(l);f.ok||(c.stop(`License invalid: ${f.reason??"unknown"}`,2),s.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),F&&H("license",`${f.reason??"The license could not be validated."} If you believe this is in error, email hello@klaudius.dev with your purchase details.`),process.exit(1)),c.stop(`License valid (${f.tier??"core"} tier)`);let u=await be();u.ok||(s.error(u.message??"Python version check failed."),s.blank(),s.detail(`Once you've installed Python 3.10+, re-run the same command: ${re(n)}`),process.exit(1)),await Pt();let A=ue();A.ok||(s.error(A.message??"Node.js version check failed."),s.blank(),s.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${re(n)}`),process.exit(1));let d,b=!1;if(r){let p=ct(r);p||H("answers","The answers file is missing required fields. Required: PRICING, SUPABASE_URL, SUPABASE_SERVICE_KEY, SUPABASE_PAT, SUPABASE_PROJECT_REF, plus the credentials for your DEPLOY_PROVIDER (VERCEL_TOKEN, or CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, or NETLIFY_AUTH_TOKEN, or SELFHOST_DEPLOY_TARGET + SELFHOST_URL_TEMPLATE). Keys match a working .env."),d=p,s.success("Loaded setup answers (non-interactive mode)")}else if(o.kind==="partial")if(await Fo(n)==="resume"){let y=await Vt(o.envPath,"utf-8"),m=ct(G(y));m?(s.success("Resuming with values from your existing .env"),s.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),d=m,b=!0,d.aiPlan||(d=await N(d,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
|
|
31
31
|
runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(s.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),d=await N())}else{let y=await Vt(o.envPath,"utf-8"),m=ct(G(y));d=await N(m??{})}else d=await N();d.licenseKey=l,await M(n,d),b||(s.success("Saved .env"),s.success(d.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),s.blank();for(let p=1;;p++){let y=P.spinner();y.start("Validating Supabase credentials");let m=await Ie({url:d.supabaseUrl,serviceKey:d.supabaseServiceKey});if(m.ok){y.stop("Supabase credentials accepted");break}y.stop(m.message??"Supabase check failed",2),p>=L&&te(n,"Supabase",m.message??"Supabase check failed");let E=m.message??"Supabase check failed";s.blank(),F&&H("supabase",E),s.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${p+1} of ${L})`),s.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),s.blank(),d=await N(d,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
32
32
|
${E}
|
|
33
33
|
|
|
@@ -105,7 +105,7 @@ password. Your browser will open to Microsoft's sign-in page \u2014
|
|
|
105
105
|
sign in as `+(d.emailAddress??"your outreach mailbox")+` and approve.
|
|
106
106
|
(No browser on this machine? It falls back to a short code you can
|
|
107
107
|
enter from any device.)`)),s.blank();let p=await K();if(p){let[y,...m]=p.command,E=Yt(y,[...m,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});E.status===0?s.success("Outlook mailbox connected."):(s.blank(),console.log(h.yellow(`The Microsoft sign-in didn't complete (exit ${E.status??"signalled"}). Setup continues without it.`)),w(p))}else console.log(h.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),w(null)}else ke&&!He&&(s.blank(),console.log(h.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(h.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(h.cyan(" python3 scripts/ms_oauth.py login")));s.blank();let v=[...R,...B?["schema"]:[]];if(v.length>0){P.outro(h.yellow(h.bold(`Setup paused \u2014 ${v.join(", ")} failed.`))),console.log(h.dim("Your credentials and project files are all saved.")),s.blank();for(let[D,ze]of Object.entries(_))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${ze}`)),s.blank();let p=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${It(e.target)}`)}
|
|
108
|
-
`:"",y=d.aiAgent==="codex"?"codex":"claude",m=d.aiAgent==="codex"?"Codex":"Claude Code",E=d.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";R.length>0&&(console.log(h.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),s.blank(),p&&process.stdout.write(p),console.log(` ${h.cyan(y)} ${h.dim(`# open ${m} in this folder`)}`),console.log(h.dim(" Then paste:")),console.log(h.cyan(` "Finish my Klaudius install \u2014 ${R.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(h.dim(` (Don't have ${m} yet? Install with: \`${E}\`)`)),s.blank(),console.log(h.dim("Or do it yourself:")),s.blank(),p&&process.stdout.write(p),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retry the failing installers")}`),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify everything")}`),s.blank()),B&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(le)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),R.includes("pip")&&!_.pip&&(console.log(h.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(h.dim(`Python 3.10+. Install a newer one from ${Ko()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),s.blank());let I=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if(I.length>0){let D=I.length===1?"keeps":"keep";console.log(h.dim(`If ${I.join(" / ")} ${D} failing with network errors (ECONNRESET,`)),console.log(h.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(h.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}g&&(console.log(h.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${m}`)),console.log(h.dim("to finish setting it up \u2014 your email details are saved in .env.")),s.blank()),console.log(h.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}if(Go(d,n,e.target),g){let p=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(h.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(h.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(h.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(h.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(h.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(h.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(h.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(s.blank(),console.log(h.yellow(`Note: your other channel(s) \u2014 ${(d.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),s.blank()}}async function M(e,t){await Gt(e,{recursive:!0}),await Kt(Z(e,".env"),rt(t),"utf-8"),t.aiAgent==="codex"?(await Gt(Z(e,".codex"),{recursive:!0}),await Kt(Z(e,".codex","config.toml"),lt(t),"utf-8")):(await Kt(Z(e,".mcp.json"),at(t),"utf-8"),await Tt(e,"supabase"),await Ne(e,$e))}async function Do(e){try{(await Bt(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ui(e),n=t.filter(l=>!l.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(l=>i.has(l)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:Z(e,".env")};if(a&&r){let l=!0;try{l=!(await Bt(Z(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Fo(e){s.blank(),s.warn(`Found a partial setup at ${h.bold(e)}.`),s.detail(`A previous init wrote ${h.bold(".env")} but didn't finish scaffolding.`),s.blank();let t=await P.select({message:`How would you like to proceed? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return P.isCancel(t)&&(P.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Ho(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 Uo(e){let t=$o(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let i of n)if(t.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function jo(){if(process.platform!=="win32")return!1;try{return Yt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Ko(){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 Go(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(h.green(h.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${Xe[e.aiPlan]}`),console.log(h.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(h.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),s.blank()}if(console.log(h.bold("Next steps:")),s.blank(),t!==process.cwd()&&n){let r=`cd ${It(n)}`;console.log(` ${h.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${h.dim("# go into your project folder")}`)}console.log(` ${h.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${h.dim(`# opens ${o} in this project`)}`),s.blank(),console.log(h.bold(`Some starter prompts for ${o}:`)),s.blank(),console.log(` ${h.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${h.cyan(`I know I'm ready to start using Klaudius."`)}`),s.blank(),console.log(` ${h.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),s.blank(),console.log(` ${h.cyan('"Run the pipeline for one client."')}`),console.log(h.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),s.blank(),e.aiAgent!=="codex"&&(console.log(h.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(h.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),s.blank())}import{access as Vo,readFile as Bo}from"fs/promises";import{join as Wt,resolve as Yo}from"path";import Y from"picocolors";async function hi(e){let t=e.target?Yo(process.cwd(),e.target):process.cwd(),n=await fi(Wt(t,".env")),i=await fi(Wt(t,"package.json"));(!n||!i)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),n||s.detail("Missing: .env"),i||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{G(await Bo(Wt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}s.heading("Installing dependencies");let r=await Et(t);s.blank(),s.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let a=[];if(r.npm==="failed"&&a.push("npm"),r.pip==="failed"&&a.push("pip"),r.playwright==="failed"&&a.push("playwright"),r.patchright==="failed"&&a.push("patchright"),a.length===0){s.blank(),console.log(Y.green(Y.bold("All dependencies installed."))),console.log(Y.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(Y.yellow(Y.bold(`${a.join(", ")} still failing.`))),s.blank();for(let[u,A]of Object.entries(r.hints??{}))console.log(Y.yellow(`Likely cause of ${u} failure:`)),console.log(Y.dim(` ${A}`)),s.blank();let l=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",f=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(Y.dim("Options:")),console.log(Y.dim(` \u2022 Open ${c} in this folder (\`${l}\`) and paste:`)),console.log(Y.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(Y.dim(` (Don't have ${c} yet? Install with: \`${f}\`)`)),console.log(Y.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(Y.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function fi(e){try{return await Vo(e),!0}catch{return!1}}import{readFile as Wo,writeFile as zt,access as zo}from"fs/promises";import{join as De}from"path";import*as W from"@clack/prompts";import ae from"picocolors";import{mkdir as qo}from"fs/promises";import{spawnSync as mi}from"child_process";async function gi(e){let t=e.projectRoot??process.cwd(),n=De(t,".env"),i=De(t,".mcp.json"),o=De(t,".codex","config.toml"),r=await qt(De(t,".klaudius","manifest.json")),a=await qt(n);!r&&!a&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let l=ue();l.ok||(s.error(l.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let c={};try{let g=await Wo(n,"utf-8");c=G(g)}catch{s.warn("No .env found. Starting from an empty configuration.")}let f=Sn(c);Object.keys(c).length>0&&(f.pipelineModes??=["classic"]),W.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let u=await N(f),A=f.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==A&&(s.error(`Switching AI coding agent (${A} \u2192 ${u.aiAgent}) isn't supported via configure.`),s.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest init <new-folder>")} ${ae.dim("# pick the new agent in the wizard")}`),s.blank(),s.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let g=await Ie({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});g.ok||(s.error(g.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let d=Jo(u,c);if(d==="vercel"){let g=W.spinner();g.start("Validating Vercel token");let k=await Ce(u.vercelToken??"");k.ok?g.stop(k.username?`Vercel token accepted (signed in as ${k.username})`:"Vercel token accepted"):(g.stop(k.message,2),s.warn("Writing the token exactly as you entered it \u2014 not verified."),s.detail(k.kind==="rejected"||k.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then re-run `npx klaudius@latest configure`.":k.kind==="network"?"Couldn't reach Vercel \u2014 check your connection, then run `npx klaudius@latest doctor`.":"Vercel's API returned an error \u2014 try again shortly (status.vercel.com), then run `npx klaudius@latest doctor`."))}else if(d==="cloudflare"){let g=W.spinner();g.start("Validating Cloudflare token + account");let k=await xe({token:u.cloudflareApiToken??"",accountId:u.cloudflareAccountId??""});k.ok?g.stop("Cloudflare credentials accepted"):(g.stop(k.message??"Cloudflare check failed",2),s.warn("Writing the credentials exactly as you entered them \u2014 not verified."),s.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(d==="netlify"){let g=W.spinner();g.start("Validating Netlify token");let k=await Re({token:u.netlifyAuthToken??""});k.ok?g.stop(k.accountSlug?`Netlify token accepted (team: ${k.accountSlug})`:"Netlify token accepted"):(g.stop(k.message??"Netlify check failed",2),s.warn("Writing the token exactly as you entered it \u2014 not verified."),s.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let b=de(u.googlePlacesApiKey??"");if(b.changed&&u.googlePlacesApiKey){s.heading("Checking your Google Places API key");let g=await ve(u.googlePlacesApiKey);if(g.ok){if(b.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let k of b.repairs)s.detail(` ${k}`);s.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=b.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(g.message??"Google rejected the Google Places API key"),s.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),s.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Qo(u,c)){let g=W.spinner();g.start("Validating email credentials (SMTP + IMAP)");let k=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:we(u.emailSmtpHost),S=await oe({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:k?X[k].usesAccountPassword:void 0,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});S.ok?(g.stop("Email credentials accepted (SMTP + IMAP)"),await kt(S,u,{nonInteractive:!1,onCancel:()=>s.detail("Left the folder names as they are.")})):(g.stop(S.message??"Email check failed",2),s.warn("Writing the email settings exactly as you entered them \u2014 not verified."),s.detail(S.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await zt(n,rt(u),"utf-8"),s.success("Updated .env"),u.aiAgent==="codex"?(await qo(De(t,".codex"),{recursive:!0}),await zt(o,lt(u),"utf-8"),s.success("Updated .codex/config.toml")):(await zt(i,at(u),"utf-8"),s.success("Updated .mcp.json"),await Tt(t,"supabase"),await Ne(t,$e)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let g=await K();if(!(g!==null&&mi(g.command[0],[...g.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(s.blank(),!g)s.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),s.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let S=await W.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});W.isCancel(S)||!S?s.detail(`Skipped. Connect it any time with: ${g.command.join(" ")} scripts/ms_oauth.py login`):mi(g.command[0],[...g.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?s.success("Outlook mailbox connected."):(s.warn("The Microsoft sign-in didn't complete."),s.detail(`Connect it any time with: ${g.command.join(" ")} scripts/ms_oauth.py login`))}}s.blank(),W.outro(ae.green("Configuration updated.")),await Xo(t,r)}function Qo(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];if(n.some(([o])=>o===void 0||o===""))return!1;let i=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([o,r])=>String(o)!==(t[r]??""))||i.some(([o,r])=>o!==void 0&&o!==(t[r]??""))}function Jo(e,t){let n=(i,o)=>(i??"")!==(t[o]??"");switch(e.deployProvider??"vercel"){case"vercel":return e.vercelToken&&n(e.vercelToken,"VERCEL_TOKEN")?"vercel":null;case"cloudflare":return e.cloudflareApiToken&&e.cloudflareAccountId&&(n(e.cloudflareApiToken,"CLOUDFLARE_API_TOKEN")||n(e.cloudflareAccountId,"CLOUDFLARE_ACCOUNT_ID"))?"cloudflare":null;case"netlify":return e.netlifyAuthToken&&n(e.netlifyAuthToken,"NETLIFY_AUTH_TOKEN")?"netlify":null;default:return null}}async function Xo(e,t){let n=await qt(De(e,"node_modules"));s.blank(),t?n||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest install")} ${ae.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest doctor")} ${ae.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest init")} ${ae.dim("# pick Resume when prompted")}`),s.blank())}async function qt(e){try{return await zo(e),!0}catch{return!1}}import{copyFile as yi,mkdir as Qt,readFile as Ct,rm as fe,writeFile as xt,access as ki}from"fs/promises";import{dirname as Jt,join as $}from"path";import{tmpdir as Zo}from"os";import*as he from"@clack/prompts";import Ge from"picocolors";var Ve="0.32.3";async function wi(e){let t=e.projectRoot??process.cwd(),n=await Cn(t);n||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let w of dt)delete n.files[w];let i,o=$(t,".env"),r,a;try{r=await Ct(o,"utf-8"),a=G(r)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=a.KLAUDIUS_LICENSE_KEY??"",i||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius@latest init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let l=e.check?null:Pn(r,a,En);l!==null&&(await xt(o,l,"utf-8"),s.detail("Backfilled new env keys")),await gt("update",Ve),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Ve}`),await Pt();let f=a.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&f==="claude-code"&&await Ne(t,$e)==="added"&&s.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=$(Zo(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{s.heading("Downloading the latest Klaudius template");let w=await ft({licenseKey:i,machineId:Ke(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:f,destDir:u});s.success(`Fetched ${w.filesExtracted} canonical files`),A=u}catch(w){s.error(w.message),s.detail("Update aborted. Your project is unchanged."),await fe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await er(A,t,n);if(e.check){let w=d.filter(p=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(p.state)),v=d.filter(p=>["conflict","locally-deleted","removed-modified"].includes(p.state));s.blank(),w.length===0?he.outro(Ge.green("Already up to date.")):(s.detail(`${z(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(Ge.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${w.length===0?"current":"behind"} pending=${w.length} conflicts=${v.length}`),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}let b=!1,g=d.find(w=>w.path===".gitignore"&&w.state==="conflict");if(g){let w=$(t,".gitignore"),v=await Ct(w,"utf-8"),p=await Ct($(A,".gitignore"),"utf-8"),{merged:y,added:m}=tr(v,p);m.length>0&&await xt(w,y,"utf-8"),n.files[".gitignore"]=g.canonicalHash,g.state="gitignore-merged",b=!0,s.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${z(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let k=d.filter(w=>w.state==="new"),S=d.filter(w=>w.state==="clean-update"),C=d.filter(w=>w.state==="user-only"),B=d.filter(w=>w.state==="conflict"),le=d.filter(w=>w.state==="no-change"),R=d.filter(w=>w.state==="locally-deleted"),_=d.filter(w=>w.state==="removed-clean"),ce=d.filter(w=>w.state==="removed-modified"),j=[...B,...R,...ce],ke=n.ignored?.length??0;if(s.blank(),s.heading("Change summary"),s.detail(`${z(le.length,"file")} unchanged`),s.detail(`${z(k.length,"new file")}`),s.detail(`${z(S.length,"file")} updated cleanly (no local edits)`),s.detail(`${z(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${z(_.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${z(B.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${z(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),s.detail(`${z(ce.length,"file")} removed upstream but edited locally (need your decision)`),ke>0&&(s.detail(`${z(ke,"file")} kept deleted (previously resolved \u2014 skipped)`),ke<=10))for(let w of n.ignored)s.detail(` kept deleted: ${w}`);let He=async()=>{let w=!1,v=p=>fe(p,{recursive:!0,force:!0}).catch(()=>{w=!0});await v($(t,".klaudius","incoming")),await v($(t,ht)),await v($(t,".klaudius","conflicts.md")),w&&s.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(k.length===0&&S.length===0&&_.length===0&&j.length===0&&!b){await He(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ve,await je(t,n)),s.blank(),he.outro(Ge.green("Already up to date.")),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let w of[...k,...S]){let v=$(A,w.path),p=$(t,w.path);await Qt(Jt(p),{recursive:!0}),await yi(v,p),n.files[w.path]=w.canonicalHash}k.length+S.length>0&&s.success(`Wrote ${z(k.length+S.length,"file")}`),[...k,...S].some(w=>w.path==="package.json"||w.path==="package-lock.json")&&s.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let w of _){let v=$(t,w.path);await fe(v,{force:!0}),delete n.files[w.path]}if(_.length>0&&s.success(`Deleted ${z(_.length,"file")} removed upstream`),j.length>0){s.blank(),s.heading(`${j.length} conflict(s) need resolution`);let w=$(t,".klaudius","incoming");try{await fe(w,{recursive:!0,force:!0})}catch{}for(let m of[...B,...R]){let E=$(A,m.path),T=$(w,m.path);await Qt(Jt(T),{recursive:!0}),await yi(E,T)}let v=new Map,p=new Map;for(let m of B){let E=await Fn(t,m.path),T=await Hn(t,m.path),I=await Ct($(A,m.path),"utf-8"),D=Un(E,T,I,m.manifestHash);D!==null?(p.set(m.path,D),v.set(m.path,jn(D,I))):E!==null&&(Te(E)||Te(I))?v.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):E===null?v.set(m.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):v.set(m.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/"+m.path+"` directly._"])}let y=$(t,ht);try{await fe(y,{recursive:!0,force:!0})}catch{}for(let[m,E]of p){let T=$(y,m);await Qt(Jt(T),{recursive:!0}),await xt(T,E,"utf-8")}await xt($(t,".klaudius","conflicts.md"),nr(j,n.templateVersion,Ve,v,p),"utf-8"),B.length+R.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),p.size>0&&s.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Ve,j.length===0?(delete n.pendingConflicts,await He()):n.pendingConflicts=j.length,await je(t,n);try{await mt(t,A,await ge(A))}catch{s.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(s.blank(),j.length===0)he.outro(Ge.green("Update complete."));else{let w=f==="codex"?"Codex":"Claude Code";he.outro(Ge.yellow(`${j.length} conflict(s) staged. Open ${w} in this project and ask:
|
|
108
|
+
`:"",y=d.aiAgent==="codex"?"codex":"claude",m=d.aiAgent==="codex"?"Codex":"Claude Code",E=d.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";R.length>0&&(console.log(h.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),s.blank(),p&&process.stdout.write(p),console.log(` ${h.cyan(y)} ${h.dim(`# open ${m} in this folder`)}`),console.log(h.dim(" Then paste:")),console.log(h.cyan(` "Finish my Klaudius install \u2014 ${R.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),s.blank(),console.log(h.dim(` (Don't have ${m} yet? Install with: \`${E}\`)`)),s.blank(),console.log(h.dim("Or do it yourself:")),s.blank(),p&&process.stdout.write(p),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retry the failing installers")}`),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify everything")}`),s.blank()),B&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(le)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),s.blank()),R.includes("pip")&&!_.pip&&(console.log(h.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(h.dim(`Python 3.10+. Install a newer one from ${Ko()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),s.blank());let I=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if(I.length>0){let D=I.length===1?"keeps":"keep";console.log(h.dim(`If ${I.join(" / ")} ${D} failing with network errors (ECONNRESET,`)),console.log(h.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(h.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),s.blank()}g&&(console.log(h.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${m}`)),console.log(h.dim("to finish setting it up \u2014 your email details are saved in .env.")),s.blank()),console.log(h.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),s.blank();return}if(Go(d,n,e.target),g){let p=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(h.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(h.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(h.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(h.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(h.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(h.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(h.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(s.blank(),console.log(h.yellow(`Note: your other channel(s) \u2014 ${(d.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),s.blank()}}async function M(e,t){await Gt(e,{recursive:!0}),await Kt(Z(e,".env"),rt(t),"utf-8"),t.aiAgent==="codex"?(await Gt(Z(e,".codex"),{recursive:!0}),await Kt(Z(e,".codex","config.toml"),lt(t),"utf-8")):(await Kt(Z(e,".mcp.json"),at(t),"utf-8"),await Tt(e,"supabase"),await Ne(e,$e))}async function Do(e){try{(await Bt(e)).isDirectory()||(s.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ui(e),n=t.filter(l=>!l.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let i=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(l=>i.has(l)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:Z(e,".env")};if(a&&r){let l=!0;try{l=!(await Bt(Z(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Fo(e){s.blank(),s.warn(`Found a partial setup at ${h.bold(e)}.`),s.detail(`A previous init wrote ${h.bold(".env")} but didn't finish scaffolding.`),s.blank();let t=await P.select({message:`How would you like to proceed? ${h.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return P.isCancel(t)&&(P.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function Ho(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 Uo(e){let t=$o(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let i of n)if(t.startsWith(i))return`Inside ${i.slice(0,-1)} (system-managed directory).`}}function jo(){if(process.platform!=="win32")return!1;try{return Yt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Ko(){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 Go(e,t,n){let i=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(h.green(h.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${Xe[e.aiPlan]}`),console.log(h.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(h.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),s.blank()}if(console.log(h.bold("Next steps:")),s.blank(),t!==process.cwd()&&n){let r=`cd ${It(n)}`;console.log(` ${h.cyan(r)}${" ".repeat(Math.max(1,27-r.length))}${h.dim("# go into your project folder")}`)}console.log(` ${h.cyan(i)}${" ".repeat(Math.max(1,27-i.length))}${h.dim(`# opens ${o} in this project`)}`),s.blank(),console.log(h.bold(`Some starter prompts for ${o}:`)),s.blank(),console.log(` ${h.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${h.cyan(`I know I'm ready to start using Klaudius."`)}`),s.blank(),console.log(` ${h.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),s.blank(),console.log(` ${h.cyan('"Run the pipeline for one client."')}`),console.log(h.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),s.blank(),e.aiAgent!=="codex"&&(console.log(h.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(h.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),s.blank())}import{access as Vo,readFile as Bo}from"fs/promises";import{join as Wt,resolve as Yo}from"path";import Y from"picocolors";async function hi(e){let t=e.target?Yo(process.cwd(),e.target):process.cwd(),n=await fi(Wt(t,".env")),i=await fi(Wt(t,"package.json"));(!n||!i)&&(s.error("This doesn't look like a Klaudius project."),s.detail(`Path: ${t}`),n||s.detail("Missing: .env"),i||s.detail("Missing: package.json"),s.blank(),s.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),s.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{G(await Bo(Wt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}s.heading("Installing dependencies");let r=await Et(t);s.blank(),s.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let a=[];if(r.npm==="failed"&&a.push("npm"),r.pip==="failed"&&a.push("pip"),r.playwright==="failed"&&a.push("playwright"),r.patchright==="failed"&&a.push("patchright"),a.length===0){s.blank(),console.log(Y.green(Y.bold("All dependencies installed."))),console.log(Y.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),s.blank();return}s.blank(),console.log(Y.yellow(Y.bold(`${a.join(", ")} still failing.`))),s.blank();for(let[u,A]of Object.entries(r.hints??{}))console.log(Y.yellow(`Likely cause of ${u} failure:`)),console.log(Y.dim(` ${A}`)),s.blank();let l=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",f=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(Y.dim("Options:")),console.log(Y.dim(` \u2022 Open ${c} in this folder (\`${l}\`) and paste:`)),console.log(Y.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(Y.dim(` (Don't have ${c} yet? Install with: \`${f}\`)`)),console.log(Y.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(Y.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),s.blank(),process.exitCode=1}async function fi(e){try{return await Vo(e),!0}catch{return!1}}import{readFile as Wo,writeFile as zt,access as zo}from"fs/promises";import{join as De}from"path";import*as W from"@clack/prompts";import ae from"picocolors";import{mkdir as qo}from"fs/promises";import{spawnSync as mi}from"child_process";async function gi(e){let t=e.projectRoot??process.cwd(),n=De(t,".env"),i=De(t,".mcp.json"),o=De(t,".codex","config.toml"),r=await qt(De(t,".klaudius","manifest.json")),a=await qt(n);!r&&!a&&(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let l=ue();l.ok||(s.error(l.message??"Node.js version check failed."),s.blank(),s.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let c={};try{let g=await Wo(n,"utf-8");c=G(g)}catch{s.warn("No .env found. Starting from an empty configuration.")}let f=Sn(c);Object.keys(c).length>0&&(f.pipelineModes??=["classic"]),W.intro("Reconfigure Klaudius"),s.detail("Press Enter on any prompt to keep its current value."),s.blank();let u=await N(f),A=f.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==A&&(s.error(`Switching AI coding agent (${A} \u2192 ${u.aiAgent}) isn't supported via configure.`),s.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest init <new-folder>")} ${ae.dim("# pick the new agent in the wizard")}`),s.blank(),s.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){s.heading("Re-validating Supabase credentials");let g=await Ie({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});g.ok||(s.error(g.message??"Supabase check failed"),s.warn("Aborting. .env not modified."),process.exit(1)),s.success("Supabase credentials accepted")}let d=Jo(u,c);if(d==="vercel"){let g=W.spinner();g.start("Validating Vercel token");let k=await Ce(u.vercelToken??"");k.ok?g.stop(k.username?`Vercel token accepted (signed in as ${k.username})`:"Vercel token accepted"):(g.stop(k.message,2),s.warn("Writing the token exactly as you entered it \u2014 not verified."),s.detail(k.kind==="rejected"||k.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then re-run `npx klaudius@latest configure`.":k.kind==="network"?"Couldn't reach Vercel \u2014 check your connection, then run `npx klaudius@latest doctor`.":"Vercel's API returned an error \u2014 try again shortly (status.vercel.com), then run `npx klaudius@latest doctor`."))}else if(d==="cloudflare"){let g=W.spinner();g.start("Validating Cloudflare token + account");let k=await xe({token:u.cloudflareApiToken??"",accountId:u.cloudflareAccountId??""});k.ok?g.stop("Cloudflare credentials accepted"):(g.stop(k.message??"Cloudflare check failed",2),s.warn("Writing the credentials exactly as you entered them \u2014 not verified."),s.detail("Run `npx klaudius@latest doctor` once you've fixed them."))}else if(d==="netlify"){let g=W.spinner();g.start("Validating Netlify token");let k=await Re({token:u.netlifyAuthToken??""});k.ok?g.stop(k.accountSlug?`Netlify token accepted (team: ${k.accountSlug})`:"Netlify token accepted"):(g.stop(k.message??"Netlify check failed",2),s.warn("Writing the token exactly as you entered it \u2014 not verified."),s.detail("Run `npx klaudius@latest doctor` once you've fixed it."))}let b=de(u.googlePlacesApiKey??"");if(b.changed&&u.googlePlacesApiKey){s.heading("Checking your Google Places API key");let g=await ve(u.googlePlacesApiKey);if(g.ok){if(b.repairs.length>0){s.warn("Corrected look-alike characters in your Google Places API key:");for(let k of b.repairs)s.detail(` ${k}`);s.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=b.value,s.success("Google accepted the key \u2014 writing the corrected value to .env")}else s.error(g.message??"Google rejected the Google Places API key"),s.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),s.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Qo(u,c)){let g=W.spinner();g.start("Validating email credentials (SMTP + IMAP)");let k=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:we(u.emailSmtpHost),S=await oe({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:k?X[k].usesAccountPassword:void 0,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});S.ok?(g.stop("Email credentials accepted (SMTP + IMAP)"),await kt(S,u,{nonInteractive:!1,onCancel:()=>s.detail("Left the folder names as they are.")})):(g.stop(S.message??"Email check failed",2),s.warn("Writing the email settings exactly as you entered them \u2014 not verified."),s.detail(S.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await zt(n,rt(u),"utf-8"),s.success("Updated .env"),u.aiAgent==="codex"?(await qo(De(t,".codex"),{recursive:!0}),await zt(o,lt(u),"utf-8"),s.success("Updated .codex/config.toml")):(await zt(i,at(u),"utf-8"),s.success("Updated .mcp.json"),await Tt(t,"supabase"),await Ne(t,$e)),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let g=await K();if(!(g!==null&&mi(g.command[0],[...g.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(s.blank(),!g)s.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),s.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let S=await W.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});W.isCancel(S)||!S?s.detail(`Skipped. Connect it any time with: ${g.command.join(" ")} scripts/ms_oauth.py login`):mi(g.command[0],[...g.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?s.success("Outlook mailbox connected."):(s.warn("The Microsoft sign-in didn't complete."),s.detail(`Connect it any time with: ${g.command.join(" ")} scripts/ms_oauth.py login`))}}s.blank(),W.outro(ae.green("Configuration updated.")),await Xo(t,r)}function Qo(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];if(n.some(([o])=>o===void 0||o===""))return!1;let i=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([o,r])=>String(o)!==(t[r]??""))||i.some(([o,r])=>o!==void 0&&o!==(t[r]??""))}function Jo(e,t){let n=(i,o)=>(i??"")!==(t[o]??"");switch(e.deployProvider??"vercel"){case"vercel":return e.vercelToken&&n(e.vercelToken,"VERCEL_TOKEN")?"vercel":null;case"cloudflare":return e.cloudflareApiToken&&e.cloudflareAccountId&&(n(e.cloudflareApiToken,"CLOUDFLARE_API_TOKEN")||n(e.cloudflareAccountId,"CLOUDFLARE_ACCOUNT_ID"))?"cloudflare":null;case"netlify":return e.netlifyAuthToken&&n(e.netlifyAuthToken,"NETLIFY_AUTH_TOKEN")?"netlify":null;default:return null}}async function Xo(e,t){let n=await qt(De(e,"node_modules"));s.blank(),t?n||(s.detail("Your project files are in place but dependencies aren't installed yet."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest install")} ${ae.dim("# (re-)installs npm + pip + browsers; idempotent")}`),s.blank(),s.detail("Then verify with:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest doctor")} ${ae.dim("# checks Node / Python / installers / credentials")}`),s.blank()):(s.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),s.detail("To finish setup, run:"),s.blank(),console.log(` ${ae.cyan("npx klaudius@latest init")} ${ae.dim("# pick Resume when prompted")}`),s.blank())}async function qt(e){try{return await zo(e),!0}catch{return!1}}import{copyFile as yi,mkdir as Qt,readFile as Ct,rm as fe,writeFile as xt,access as ki}from"fs/promises";import{dirname as Jt,join as $}from"path";import{tmpdir as Zo}from"os";import*as he from"@clack/prompts";import Ge from"picocolors";var Ve="0.32.4";async function wi(e){let t=e.projectRoot??process.cwd(),n=await Cn(t);n||(s.error("This doesn't look like a Klaudius project."),s.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let w of dt)delete n.files[w];let i,o=$(t,".env"),r,a;try{r=await Ct(o,"utf-8"),a=G(r)}catch{s.error("Couldn't read .env from this directory."),s.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=a.KLAUDIUS_LICENSE_KEY??"",i||(s.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),s.detail("This file is created by `npx klaudius@latest init`. If your project predates"),s.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),s.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let l=e.check?null:Pn(r,a,En);l!==null&&(await xt(o,l,"utf-8"),s.detail("Backfilled new env keys")),await gt("update",Ve),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Ve}`),await Pt();let f=a.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&f==="claude-code"&&await Ne(t,$e)==="added"&&s.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=$(Zo(),`klaudius-update-${process.pid}-${Date.now()}`),A;try{s.heading("Downloading the latest Klaudius template");let w=await ft({licenseKey:i,machineId:Ke(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:f,destDir:u});s.success(`Fetched ${w.filesExtracted} canonical files`),A=u}catch(w){s.error(w.message),s.detail("Update aborted. Your project is unchanged."),await fe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await er(A,t,n);if(e.check){let w=d.filter(p=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(p.state)),v=d.filter(p=>["conflict","locally-deleted","removed-modified"].includes(p.state));s.blank(),w.length===0?he.outro(Ge.green("Already up to date.")):(s.detail(`${z(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(Ge.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${w.length===0?"current":"behind"} pending=${w.length} conflicts=${v.length}`),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}let b=!1,g=d.find(w=>w.path===".gitignore"&&w.state==="conflict");if(g){let w=$(t,".gitignore"),v=await Ct(w,"utf-8"),p=await Ct($(A,".gitignore"),"utf-8"),{merged:y,added:m}=tr(v,p);m.length>0&&await xt(w,y,"utf-8"),n.files[".gitignore"]=g.canonicalHash,g.state="gitignore-merged",b=!0,s.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${z(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let k=d.filter(w=>w.state==="new"),S=d.filter(w=>w.state==="clean-update"),C=d.filter(w=>w.state==="user-only"),B=d.filter(w=>w.state==="conflict"),le=d.filter(w=>w.state==="no-change"),R=d.filter(w=>w.state==="locally-deleted"),_=d.filter(w=>w.state==="removed-clean"),ce=d.filter(w=>w.state==="removed-modified"),j=[...B,...R,...ce],ke=n.ignored?.length??0;if(s.blank(),s.heading("Change summary"),s.detail(`${z(le.length,"file")} unchanged`),s.detail(`${z(k.length,"new file")}`),s.detail(`${z(S.length,"file")} updated cleanly (no local edits)`),s.detail(`${z(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),s.detail(`${z(_.length,"file")} removed upstream (deleted cleanly)`),s.detail(`${z(B.length,"file")} with conflicts (you edited AND we have a new version)`),s.detail(`${z(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),s.detail(`${z(ce.length,"file")} removed upstream but edited locally (need your decision)`),ke>0&&(s.detail(`${z(ke,"file")} kept deleted (previously resolved \u2014 skipped)`),ke<=10))for(let w of n.ignored)s.detail(` kept deleted: ${w}`);let He=async()=>{let w=!1,v=p=>fe(p,{recursive:!0,force:!0}).catch(()=>{w=!0});await v($(t,".klaudius","incoming")),await v($(t,ht)),await v($(t,".klaudius","conflicts.md")),w&&s.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(k.length===0&&S.length===0&&_.length===0&&j.length===0&&!b){await He(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ve,await je(t,n)),s.blank(),he.outro(Ge.green("Already up to date.")),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}s.blank(),s.heading("Applying clean updates");for(let w of[...k,...S]){let v=$(A,w.path),p=$(t,w.path);await Qt(Jt(p),{recursive:!0}),await yi(v,p),n.files[w.path]=w.canonicalHash}k.length+S.length>0&&s.success(`Wrote ${z(k.length+S.length,"file")}`),[...k,...S].some(w=>w.path==="package.json"||w.path==="package-lock.json")&&s.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let w of _){let v=$(t,w.path);await fe(v,{force:!0}),delete n.files[w.path]}if(_.length>0&&s.success(`Deleted ${z(_.length,"file")} removed upstream`),j.length>0){s.blank(),s.heading(`${j.length} conflict(s) need resolution`);let w=$(t,".klaudius","incoming");try{await fe(w,{recursive:!0,force:!0})}catch{}for(let m of[...B,...R]){let E=$(A,m.path),T=$(w,m.path);await Qt(Jt(T),{recursive:!0}),await yi(E,T)}let v=new Map,p=new Map;for(let m of B){let E=await Fn(t,m.path),T=await Hn(t,m.path),I=await Ct($(A,m.path),"utf-8"),D=Un(E,T,I,m.manifestHash);D!==null?(p.set(m.path,D),v.set(m.path,jn(D,I))):E!==null&&(Te(E)||Te(I))?v.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):E===null?v.set(m.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):v.set(m.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/"+m.path+"` directly._"])}let y=$(t,ht);try{await fe(y,{recursive:!0,force:!0})}catch{}for(let[m,E]of p){let T=$(y,m);await Qt(Jt(T),{recursive:!0}),await xt(T,E,"utf-8")}await xt($(t,".klaudius","conflicts.md"),nr(j,n.templateVersion,Ve,v,p),"utf-8"),B.length+R.length>0&&s.detail("Staged canonical versions to .klaudius/incoming/"),p.size>0&&s.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),s.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Ve,j.length===0?(delete n.pendingConflicts,await He()):n.pendingConflicts=j.length,await je(t,n);try{await mt(t,A,await ge(A))}catch{s.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(s.blank(),j.length===0)he.outro(Ge.green("Update complete."));else{let w=f==="codex"?"Codex":"Claude Code";he.outro(Ge.yellow(`${j.length} conflict(s) staged. Open ${w} in this project and ask:
|
|
109
109
|
"Run /resolve-conflicts"`))}await fe(u,{recursive:!0,force:!0}).catch(()=>{})}async function er(e,t,n){let i=await ge(e),o=new Set(i),r=new Set(n.ignored??[]),a=[];for(let l of i){if(r.has(l))continue;let c=await _e($(e,l)),f=n.files[l],u=$(t,l),A;try{await ki(u),A=await _e(u)}catch{let b=f!==void 0&&!In.has(l)&&!ut.has(l)?"locally-deleted":"new";a.push({path:l,state:b,canonicalHash:c,manifestHash:f});continue}let d=ut.has(l);c===f?A===f||d?a.push({path:l,state:"no-change",canonicalHash:c,localHash:A,manifestHash:f}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:A,manifestHash:f}):A===f||d?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:A,manifestHash:f}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:A,manifestHash:f})}for(let l of Object.keys(n.files)){if(o.has(l))continue;let c=n.files[l],f=$(t,l),u;try{await ki(f),u=await _e(f)}catch{delete n.files[l];continue}u===c||ut.has(l)?a.push({path:l,state:"removed-clean",localHash:u,manifestHash:c}):a.push({path:l,state:"removed-modified",localHash:u,manifestHash:c})}return a}function z(e,t){return`${e} ${t}${e===1?"":"s"}`}function tr(e,t){let n=e.includes(`\r
|
|
110
110
|
`)?`\r
|
|
111
111
|
`:`
|
|
@@ -125,7 +125,7 @@ except Exception as e:
|
|
|
125
125
|
`));let r=Tr(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(V.green(`Paired '${o}'.`)),console.log(V.dim(`
|
|
126
126
|
If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
127
127
|
WHATSAPP_ACCOUNTS=primary,${o}
|
|
128
|
-
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(V.red(`Pair failed: ${r.error.message}`)):(console.error(V.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(V.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(V.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(V.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as Fe,spawn as xr}from"child_process";import{existsSync as Ye,mkdirSync as Rr,readdirSync as vr,rmSync as Ci,mkdtempSync as xi}from"fs";import{homedir as Zt,tmpdir as Ri}from"os";import{join as J}from"path";import ie from"picocolors";var Or=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function _i(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function vi(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&We()&&Li();let t=$r();if(t&&!e.reinstall&&!e.from){Ii(),console.log(ie.green("Opened the Klaudius app.")),Ti();return}let n=await Mr(e.from);console.log(ie.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Dr(n):Fr(n),Ii(),console.log(ie.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),Ti()}function Ti(){process.platform==="darwin"?console.log(ie.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(ie.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function Rt(){return J(Zt(),"Applications","Klaudius.app")}function Oi(){return process.env.LOCALAPPDATA??J(Zt(),"AppData","Local")}function Lr(){return J(Oi(),"Klaudius")}function We(){let e=J(Oi(),"Programs");try{for(let t of vr(e)){if(!/laudius/i.test(t))continue;let n=J(e,t,"Klaudius.exe");if(Ye(n))return n}}catch{}return null}function $r(){return process.platform==="darwin"?Ye(Rt()):We()!==null}async function Nr(){try{let{readFileSync:e}=await import("fs"),n=e(J(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function Mr(e){if(e)return Ye(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await Nr();t||(console.error("Couldn't find your license key."),console.error("Run this from inside your Klaudius folder (the one `npx klaudius init` created)."),process.exit(1));let n=`${Or}?file=${encodeURIComponent(_i())}`,i=J(xi(J(Ri(),"klaudius-app-")),_i());console.log(ie.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.32.
|
|
128
|
+
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(V.red(`Pair failed: ${r.error.message}`)):(console.error(V.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(V.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(V.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(V.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as Fe,spawn as xr}from"child_process";import{existsSync as Ye,mkdirSync as Rr,readdirSync as vr,rmSync as Ci,mkdtempSync as xi}from"fs";import{homedir as Zt,tmpdir as Ri}from"os";import{join as J}from"path";import ie from"picocolors";var Or=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function _i(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function vi(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&We()&&Li();let t=$r();if(t&&!e.reinstall&&!e.from){Ii(),console.log(ie.green("Opened the Klaudius app.")),Ti();return}let n=await Mr(e.from);console.log(ie.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Dr(n):Fr(n),Ii(),console.log(ie.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),Ti()}function Ti(){process.platform==="darwin"?console.log(ie.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(ie.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function Rt(){return J(Zt(),"Applications","Klaudius.app")}function Oi(){return process.env.LOCALAPPDATA??J(Zt(),"AppData","Local")}function Lr(){return J(Oi(),"Klaudius")}function We(){let e=J(Oi(),"Programs");try{for(let t of vr(e)){if(!/laudius/i.test(t))continue;let n=J(e,t,"Klaudius.exe");if(Ye(n))return n}}catch{}return null}function $r(){return process.platform==="darwin"?Ye(Rt()):We()!==null}async function Nr(){try{let{readFileSync:e}=await import("fs"),n=e(J(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function Mr(e){if(e)return Ye(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await Nr();t||(console.error("Couldn't find your license key."),console.error("Run this from inside your Klaudius folder (the one `npx klaudius init` created)."),process.exit(1));let n=`${Or}?file=${encodeURIComponent(_i())}`,i=J(xi(J(Ri(),"klaudius-app-")),_i());console.log(ie.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.32.4"}});if(!o.ok){let l=`HTTP ${o.status}`;try{let c=await o.json();c.reason&&(l=c.reason)}catch{}throw new Error(l)}let r=Buffer.from(await o.arrayBuffer()),{writeFileSync:a}=await import("fs");return a(i,r),i}catch(o){console.error(`Couldn't download the app (${o.message}). If you're offline, try again later; otherwise email hello@klaudius.dev.`),process.exit(1)}}function Dr(e){let t=J(Zt(),"Applications");Rr(t,{recursive:!0});let n=xi(J(Ri(),"klaudius-app-x-")),i=Fe("ditto",["-xk",e,n],{stdio:"pipe"});i.status!==0&&(console.error(`Couldn't extract the app: ${i.stderr?.toString().trim()}`),process.exit(1));let o=J(n,"Klaudius.app");Ye(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),Ci(Rt(),{recursive:!0,force:!0});let r=Fe("mv",[o,Rt()],{stdio:"pipe"});r.status!==0&&(console.error(`Couldn't install to ~/Applications: ${r.stderr?.toString().trim()}`),process.exit(1))}function Fr(e){/\.exe$/i.test(e)||(console.error("Expected the Klaudius installer (.exe). A zip can't be installed here \u2014 an unzipped copy can never update itself."),process.exit(1));let t=Fe(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Hr(6e4)){let i=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,o=We();if(o&&$i(o)){console.log(ie.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(ie.dim("Open it from the Start Menu if it doesn't appear shortly."));return}console.error(`Klaudius didn't finish installing (${i}).`),console.error("Check your Start Menu for Klaudius \u2014 it may still be finishing."),console.error("If it isn't there, email hello@klaudius.dev."),process.exit(1)}Li()}function Hr(e){let t=Date.now()+e;for(;;){let n=We();if(n)return n;if(Date.now()>=t)return null;Ur(500)}}function Ur(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Li(){let e=Lr();if(!Ye(J(e,"app","Klaudius.exe")))return;console.log(ie.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
|
|
129
129
|
$legacy = '${e.replace(/'/g,"''")}'
|
|
130
130
|
# Compare against the directory PLUS its separator, so a sibling folder whose
|
|
131
131
|
# name merely starts with the same text ("Klaudius Desktop") is never matched.
|
|
@@ -139,4 +139,4 @@ foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetF
|
|
|
139
139
|
Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
|
|
140
140
|
}
|
|
141
141
|
}
|
|
142
|
-
}`;Fe("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Ci(e,{recursive:!0,force:!0})}catch{console.log(ie.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function Ii(){if(process.platform==="darwin"){Fe("open",["-a",Rt()],{stdio:"pipe"});return}let e=We();if(!e||$i(e))return;xr(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function $i(e){let t=Fe("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(i=>i.trim().toLowerCase()===n)}function Ni(e){return new Promise(t=>{if(e.destroyed||e.writableEnded||!e.writable){t();return}let n=()=>t();e.once("error",n);try{e.write("",n)}catch{n()}})}async function en(e=0){await Promise.all([Ni(process.stdout),Ni(process.stderr)]),process.exit(e)}import{spawnSync as jr}from"child_process";var tn="--use-system-ca";function Mi(){let e=process.env.NODE_OPTIONS??"";if(e.includes(tn)||!ue().ok)return;let n=e?`${e} ${tn}`:tn,i=jr(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}Mi();var Gr="0.32.
|
|
142
|
+
}`;Fe("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Ci(e,{recursive:!0,force:!0})}catch{console.log(ie.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function Ii(){if(process.platform==="darwin"){Fe("open",["-a",Rt()],{stdio:"pipe"});return}let e=We();if(!e||$i(e))return;xr(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function $i(e){let t=Fe("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(i=>i.trim().toLowerCase()===n)}function Ni(e){return new Promise(t=>{if(e.destroyed||e.writableEnded||!e.writable){t();return}let n=()=>t();e.once("error",n);try{e.write("",n)}catch{n()}})}async function en(e=0){await Promise.all([Ni(process.stdout),Ni(process.stderr)]),process.exit(e)}import{spawnSync as jr}from"child_process";var tn="--use-system-ca";function Mi(){let e=process.env.NODE_OPTIONS??"";if(e.includes(tn)||!ue().ok)return;let n=e?`${e} ${tn}`:tn,i=jr(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}Mi();var Gr="0.32.4",se=new Kr;se.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Gr);se.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 hn({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});se.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").option("--answers <file>","Non-interactive setup: read answers from a JSON or dotenv-format file (same keys as .env). On a failed check, exits with code 2 and an INIT-BLOCKED line instead of reopening the wizard.").action(async(e,t)=>{try{await pi({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await en(process.exitCode??0)}catch(n){console.error("init failed:",n.message),process.exit(1)}});se.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 hi({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});se.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await gi({}),await en(process.exitCode??0)}catch(e){console.error("configure failed:",e.message),process.exit(1)}});se.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").option("--check","Report whether an update is available without changing anything").action(async e=>{try{await wi({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});se.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 Ei({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});se.command("app").description("Install (first run) and open the Klaudius desktop app").option("--from <archive>","Install from a local app archive (testing)").option("--reinstall","Reinstall even if already installed").action(async e=>{try{await vi({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});se.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 bi({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});se.parse(process.argv);
|
|
@@ -58,7 +58,7 @@ login, so the server isn't the problem. In Titan webmail, check:
|
|
|
58
58
|
many providers require a generated app-specific password, while some
|
|
59
59
|
(e.g. IONOS, Titan) just use your normal mailbox password. If your
|
|
60
60
|
provider offers app passwords, prefer one \u2014 it's revocable on its own
|
|
61
|
-
and doesn't expose your account login.`;import pe from"react";import{render as me}from"ink";var ye=new Set(["claude-pro","codex-plus"]);function U(e){return e&&ye.has(e)?"off":"on"}var ma={"claude-pro":"Claude Pro","claude-max-5x":"Claude Max 5x","claude-max-20x":"Claude Max 20x","claude-other":"Claude (Team
|
|
61
|
+
and doesn't expose your account login.`;import pe from"react";import{render as me}from"ink";var ye=new Set(["claude-pro","codex-plus"]);function U(e){return e&&ye.has(e)?"off":"on"}var ma={"claude-pro":"Claude Pro","claude-max-5x":"Claude Max 5x","claude-max-20x":"Claude Max 20x","claude-other":"Claude (Team or Enterprise)","codex-plus":"ChatGPT Plus","codex-pro":"ChatGPT Pro","codex-other":"ChatGPT (Business or Enterprise)"};async function ya(e={},a={}){if(!process.stdin.isTTY)throw new Error("Klaudius's interactive wizard requires a terminal (TTY). Run `npx klaudius@latest init` directly from your terminal \u2014 not through a pipe, file redirect, or non-interactive shell context.");let{WizardApp:t}=await import("./WizardApp-XO6AZMMM.js"),n=null;k("runWizard:start",{onlySection:a.onlySection,hasDefaults:Object.keys(e).length>0}),R(),await new Promise(o=>setImmediate(o)),await new Promise(o=>setTimeout(o,0)),k("runWizard:event loop drained, mounting Ink");let i=me(pe.createElement(t,{defaults:e,onlySection:a.onlySection,banner:a.banner,onComplete:o=>{k("runWizard:onComplete called",{keys:Object.keys(o).length}),n=o}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});k("runWizard:render returned, awaiting exit");try{await i.waitUntilExit()}finally{process.stdin.pause(),process.stdin.ref()}if(k("runWizard:waitUntilExit resolved",{resultIsNull:n===null}),!n)throw new Error(`Wizard exited without completing. Diagnostic log: ${L}
|
|
62
62
|
Please share that file so we can trace what happened.`);return n}function P(e){if(!(e instanceof Error))return String(e);let a=e.cause;if(!a||!(a instanceof Error))return e.message;let t=a.code,n=a.message;return t&&n&&n!==t?`${e.message} (${t}: ${n})`:t?`${e.message} (${t})`:n?`${e.message} (${n})`:e.message}async function B(e){let a;try{let o=await fetch(`https://api.telegram.org/bot${encodeURIComponent(e.botToken)}/getUpdates`);if(a=await o.json(),!a.ok){let s=a.description??`HTTP ${o.status}`;if(/webhook/i.test(s))return{ok:!1,reason:"webhook_set",message:"This bot has a webhook set: another app already receives its messages, so Telegram won't show them to Klaudius."};if(/terminated by other getUpdates/i.test(s))return{ok:!1,reason:"conflict",message:`Telegram says another app is already polling this bot: ${s}.`};let r=a.error_code??o.status;return r===429||r>=500?{ok:!1,reason:"busy",message:`Telegram couldn't answer just now: ${s}.`}:{ok:!1,reason:"bad_token",message:`Telegram rejected the bot token: ${s}. Double-check the token from @BotFather.`}}}catch(o){return{ok:!1,reason:"network",message:`Could not reach Telegram: ${P(o)}`}}let t=a.result??[];if(t.length===0)return{ok:!1,reason:"no_messages",message:"No messages yet. Send your bot a regular text message in Telegram, then retry."};let n=t[t.length-1],i=n?.message?.chat?.id??n?.edited_message?.chat?.id??n?.channel_post?.chat?.id;return i===void 0?{ok:!1,reason:"no_messages",message:"Got an update from Telegram but couldn't find a chat ID in it. Send another text message and retry."}:{ok:!0,chatId:String(i)}}async function fe(e){try{let a=await fetch(`https://api.telegram.org/bot${encodeURIComponent(e.botToken)}/getMe`),t=await a.json();return t.ok?{ok:!0,botHandle:t.result?.username?`@${t.result.username}`:t.result?.first_name}:{ok:!1,failedAt:"token",message:`Telegram rejected the bot token: ${t.description??`HTTP ${a.status}`}. Generate a new token by messaging @BotFather \u2192 /mytoken or /newbot.`}}catch(a){return{ok:!1,failedAt:"token",message:`Could not reach Telegram: ${P(a)}`}}}async function ka(e){let a=await fe({botToken:e.botToken});if(!a.ok)return a;let t=a.botHandle;try{let n=await fetch(`https://api.telegram.org/bot${encodeURIComponent(e.botToken)}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:e.chatId,text:"\u2713 Klaudius connected. You'll get a notification here whenever outreach lands or a candidate replies. (You can ignore this setup message.)",disable_notification:!0})}),i=await n.json();if(!i.ok){let o=i.description??`HTTP ${n.status}`,s="";return/chat not found/i.test(o)?s=" The chat_id is wrong, or the bot hasn't been added to that chat yet. If it's a group, you must add the bot to the group first; then send /start to it.":(/bot was blocked/i.test(o)||/forbidden/i.test(o))&&(s=" The bot has been blocked by the chat, or never received a /start. Open Telegram, find your bot, and send /start to wake it up."),{ok:!1,failedAt:"chat",botHandle:t,message:`Telegram delivered the bot token check but couldn't send to chat_id ${e.chatId}: ${o}.${s}`}}}catch(n){return{ok:!1,failedAt:"chat",botHandle:t,message:`Could not reach Telegram for chat_id check: ${P(n)}`}}return{ok:!0,botHandle:t}}function D(e){let a=e.trim();if(a.length===0)return"Required \u2014 without this Klaudius can't deploy generated sites";if(a.startsWith("http://")||a.startsWith("https://"))return"This is the SSH destination, not a URL \u2014 e.g. deploy@yourvps:/var/www/klaudius-sites";if(/^[A-Za-z]:[\\/]/.test(a))return"That's a local Windows path \u2014 the target must be a remote SSH destination like user@host:/path";if(!/^[^\s:]+:\/?.+/.test(a))return"Should look like user@host:/path (an SSH destination)"}function z(e){let a=e.trim();if(a.length===0)return"Required \u2014 outreach links every pitch to the live site URL";if(!/^https?:\/\//.test(a))return"Must start with https:// (or http://)";if(!a.includes("{slug}"))return"Must contain {slug} \u2014 it's replaced with each client's slug";if(!(a.replace(/^https?:\/\//,"").split("/")[0]??"").includes("{slug}"))return"{slug} must be in the hostname (e.g. https://{slug}.sites.example.com) \u2014 a path like /sites/{slug} breaks static-export asset links"}var be=[{country:"the United Kingdom",code:"GB",language:"English",langCode:"en",aliases:["uk","united kingdom","great britain","britain","england","scotland","wales","northern ireland"]},{country:"Ireland",code:"IE",language:"English",langCode:"en"},{country:"France",code:"FR",language:"French",langCode:"fr"},{country:"Germany",code:"DE",language:"German",langCode:"de",aliases:["deutschland"]},{country:"Austria",code:"AT",language:"German",langCode:"de",aliases:["\xF6sterreich","osterreich"]},{country:"Switzerland",code:"CH",language:"German",langCode:"de",aliases:["schweiz","suisse","svizzera"]},{country:"Liechtenstein",code:"LI",language:"German",langCode:"de"},{country:"Luxembourg",code:"LU",language:"French",langCode:"fr",aliases:["l\xEBtzebuerg"]},{country:"the Netherlands",code:"NL",language:"Dutch",langCode:"nl",aliases:["netherlands","holland","nederland"]},{country:"Belgium",code:"BE",language:"Dutch",langCode:"nl",aliases:["belgi\xEB","belgique"]},{country:"Monaco",code:"MC",language:"French",langCode:"fr"},{country:"Andorra",code:"AD",language:"Catalan",langCode:"ca"},{country:"Italy",code:"IT",language:"Italian",langCode:"it",aliases:["italia"]},{country:"Spain",code:"ES",language:"Spanish",langCode:"es",aliases:["espa\xF1a","espana"]},{country:"Portugal",code:"PT",language:"Portuguese",langCode:"pt"},{country:"Malta",code:"MT",language:"English",langCode:"en"},{country:"San Marino",code:"SM",language:"Italian",langCode:"it"},{country:"Vatican City",code:"VA",language:"Italian",langCode:"it",aliases:["the vatican","holy see"]},{country:"Sweden",code:"SE",language:"Swedish",langCode:"sv",aliases:["sverige"]},{country:"Norway",code:"NO",language:"Norwegian",langCode:"no",aliases:["norge"]},{country:"Denmark",code:"DK",language:"Danish",langCode:"da",aliases:["danmark"]},{country:"Finland",code:"FI",language:"Finnish",langCode:"fi",aliases:["suomi"]},{country:"Iceland",code:"IS",language:"Icelandic",langCode:"is",aliases:["\xEDsland"]},{country:"Poland",code:"PL",language:"Polish",langCode:"pl",aliases:["polska"]},{country:"Czech Republic",code:"CZ",language:"Czech",langCode:"cs",aliases:["czechia","\u010Desko"]},{country:"Slovakia",code:"SK",language:"Slovak",langCode:"sk",aliases:["slovensko"]},{country:"Hungary",code:"HU",language:"Hungarian",langCode:"hu",aliases:["magyarorsz\xE1g"]},{country:"Slovenia",code:"SI",language:"Slovenian",langCode:"sl",aliases:["slovenija"]},{country:"Croatia",code:"HR",language:"Croatian",langCode:"hr",aliases:["hrvatska"]},{country:"Bosnia and Herzegovina",code:"BA",language:"Bosnian",langCode:"bs",aliases:["bosnia"]},{country:"Serbia",code:"RS",language:"Serbian",langCode:"sr",aliases:["srbija"]},{country:"Montenegro",code:"ME",language:"Montenegrin",langCode:"sr",aliases:["crna gora"]},{country:"Kosovo",code:"XK",language:"Albanian",langCode:"sq"},{country:"North Macedonia",code:"MK",language:"Macedonian",langCode:"mk",aliases:["macedonia"]},{country:"Albania",code:"AL",language:"Albanian",langCode:"sq",aliases:["shqip\xEBria"]},{country:"Bulgaria",code:"BG",language:"Bulgarian",langCode:"bg"},{country:"Romania",code:"RO",language:"Romanian",langCode:"ro",aliases:["rom\xE2nia"]},{country:"Moldova",code:"MD",language:"Romanian",langCode:"ro"},{country:"Greece",code:"GR",language:"Greek",langCode:"el",aliases:["\u03B5\u03BB\u03BB\u03AC\u03B4\u03B1"]},{country:"Cyprus",code:"CY",language:"Greek",langCode:"el"},{country:"Russia",code:"RU",language:"Russian",langCode:"ru",aliases:["\u0440\u043E\u0441\u0441\u0438\u044F"]},{country:"Ukraine",code:"UA",language:"Ukrainian",langCode:"uk",aliases:["\u0443\u043A\u0440\u0430\u0457\u043D\u0430"]},{country:"Belarus",code:"BY",language:"Belarusian",langCode:"be"},{country:"Estonia",code:"EE",language:"Estonian",langCode:"et",aliases:["eesti"]},{country:"Latvia",code:"LV",language:"Latvian",langCode:"lv",aliases:["latvija"]},{country:"Lithuania",code:"LT",language:"Lithuanian",langCode:"lt",aliases:["lietuva"]},{country:"Turkey",code:"TR",language:"Turkish",langCode:"tr",aliases:["t\xFCrkiye","turkiye"]},{country:"Armenia",code:"AM",language:"Armenian",langCode:"hy"},{country:"Azerbaijan",code:"AZ",language:"Azerbaijani",langCode:"az",aliases:["az\u0259rbaycan"]},{country:"Georgia",code:"GE",language:"Georgian",langCode:"ka",aliases:["\u10E1\u10D0\u10E5\u10D0\u10E0\u10D7\u10D5\u10D4\u10DA\u10DD"]},{country:"Israel",code:"IL",language:"Hebrew",langCode:"he"},{country:"Palestine",code:"PS",language:"Arabic",langCode:"ar"},{country:"Lebanon",code:"LB",language:"Arabic",langCode:"ar"},{country:"Syria",code:"SY",language:"Arabic",langCode:"ar"},{country:"Jordan",code:"JO",language:"Arabic",langCode:"ar"},{country:"Iraq",code:"IQ",language:"Arabic",langCode:"ar"},{country:"Iran",code:"IR",language:"Persian",langCode:"fa",aliases:["islamic republic of iran"]},{country:"Saudi Arabia",code:"SA",language:"Arabic",langCode:"ar"},{country:"Yemen",code:"YE",language:"Arabic",langCode:"ar"},{country:"Oman",code:"OM",language:"Arabic",langCode:"ar"},{country:"the United Arab Emirates",code:"AE",language:"English",langCode:"en",aliases:["uae","united arab emirates","dubai","abu dhabi"]},{country:"Qatar",code:"QA",language:"Arabic",langCode:"ar"},{country:"Bahrain",code:"BH",language:"Arabic",langCode:"ar"},{country:"Kuwait",code:"KW",language:"Arabic",langCode:"ar"},{country:"Kazakhstan",code:"KZ",language:"Kazakh",langCode:"kk"},{country:"Uzbekistan",code:"UZ",language:"Uzbek",langCode:"uz"},{country:"Kyrgyzstan",code:"KG",language:"Kyrgyz",langCode:"ky"},{country:"Turkmenistan",code:"TM",language:"Turkmen",langCode:"tk"},{country:"Tajikistan",code:"TJ",language:"Tajik",langCode:"tg"},{country:"Afghanistan",code:"AF",language:"Persian",langCode:"fa"},{country:"India",code:"IN",language:"English",langCode:"en"},{country:"Pakistan",code:"PK",language:"English",langCode:"en"},{country:"Bangladesh",code:"BD",language:"Bengali",langCode:"bn"},{country:"Sri Lanka",code:"LK",language:"English",langCode:"en"},{country:"Nepal",code:"NP",language:"Nepali",langCode:"ne"},{country:"Bhutan",code:"BT",language:"English",langCode:"en"},{country:"the Maldives",code:"MV",language:"English",langCode:"en",aliases:["maldives"]},{country:"China",code:"CN",language:"Chinese",langCode:"zh",aliases:["\u4E2D\u56FD","people's republic of china","prc"]},{country:"Hong Kong",code:"HK",language:"English",langCode:"en",aliases:["hk"]},{country:"Macao",code:"MO",language:"Chinese",langCode:"zh",aliases:["macau"]},{country:"Taiwan",code:"TW",language:"Chinese",langCode:"zh",aliases:["\u53F0\u7063","republic of china"]},{country:"Japan",code:"JP",language:"Japanese",langCode:"ja",aliases:["\u65E5\u672C"]},{country:"South Korea",code:"KR",language:"Korean",langCode:"ko",aliases:["korea","republic of korea"]},{country:"North Korea",code:"KP",language:"Korean",langCode:"ko",aliases:["dprk"]},{country:"Mongolia",code:"MN",language:"Mongolian",langCode:"mn"},{country:"Thailand",code:"TH",language:"Thai",langCode:"th"},{country:"Vietnam",code:"VN",language:"Vietnamese",langCode:"vi",aliases:["viet nam"]},{country:"Cambodia",code:"KH",language:"Khmer",langCode:"km"},{country:"Laos",code:"LA",language:"Lao",langCode:"lo"},{country:"Myanmar",code:"MM",language:"Burmese",langCode:"my",aliases:["burma"]},{country:"Malaysia",code:"MY",language:"Malay",langCode:"ms"},{country:"Singapore",code:"SG",language:"English",langCode:"en"},{country:"Brunei",code:"BN",language:"Malay",langCode:"ms",aliases:["brunei darussalam"]},{country:"Indonesia",code:"ID",language:"Indonesian",langCode:"id"},{country:"the Philippines",code:"PH",language:"English",langCode:"en",aliases:["philippines"]},{country:"Timor-Leste",code:"TL",language:"Portuguese",langCode:"pt",aliases:["east timor"]},{country:"the United States",code:"US",language:"English",langCode:"en",aliases:["us","usa","united states","united states of america","america","states"]},{country:"Canada",code:"CA",language:"English",langCode:"en"},{country:"Mexico",code:"MX",language:"Spanish",langCode:"es",aliases:["m\xE9xico"]},{country:"Guatemala",code:"GT",language:"Spanish",langCode:"es"},{country:"Belize",code:"BZ",language:"English",langCode:"en"},{country:"El Salvador",code:"SV",language:"Spanish",langCode:"es"},{country:"Honduras",code:"HN",language:"Spanish",langCode:"es"},{country:"Nicaragua",code:"NI",language:"Spanish",langCode:"es"},{country:"Costa Rica",code:"CR",language:"Spanish",langCode:"es"},{country:"Panama",code:"PA",language:"Spanish",langCode:"es",aliases:["panam\xE1"]},{country:"Cuba",code:"CU",language:"Spanish",langCode:"es"},{country:"the Dominican Republic",code:"DO",language:"Spanish",langCode:"es",aliases:["dominican republic"]},{country:"Haiti",code:"HT",language:"French",langCode:"fr"},{country:"Jamaica",code:"JM",language:"English",langCode:"en"},{country:"the Bahamas",code:"BS",language:"English",langCode:"en",aliases:["bahamas"]},{country:"Trinidad and Tobago",code:"TT",language:"English",langCode:"en"},{country:"Barbados",code:"BB",language:"English",langCode:"en"},{country:"Saint Lucia",code:"LC",language:"English",langCode:"en"},{country:"Saint Vincent and the Grenadines",code:"VC",language:"English",langCode:"en"},{country:"Grenada",code:"GD",language:"English",langCode:"en"},{country:"Dominica",code:"DM",language:"English",langCode:"en"},{country:"Saint Kitts and Nevis",code:"KN",language:"English",langCode:"en"},{country:"Antigua and Barbuda",code:"AG",language:"English",langCode:"en"},{country:"Puerto Rico",code:"PR",language:"Spanish",langCode:"es"},{country:"Brazil",code:"BR",language:"Portuguese",langCode:"pt",aliases:["brasil"]},{country:"Argentina",code:"AR",language:"Spanish",langCode:"es"},{country:"Colombia",code:"CO",language:"Spanish",langCode:"es"},{country:"Chile",code:"CL",language:"Spanish",langCode:"es"},{country:"Peru",code:"PE",language:"Spanish",langCode:"es",aliases:["per\xFA"]},{country:"Venezuela",code:"VE",language:"Spanish",langCode:"es"},{country:"Ecuador",code:"EC",language:"Spanish",langCode:"es"},{country:"Bolivia",code:"BO",language:"Spanish",langCode:"es"},{country:"Paraguay",code:"PY",language:"Spanish",langCode:"es"},{country:"Uruguay",code:"UY",language:"Spanish",langCode:"es"},{country:"Guyana",code:"GY",language:"English",langCode:"en"},{country:"Suriname",code:"SR",language:"Dutch",langCode:"nl"},{country:"Australia",code:"AU",language:"English",langCode:"en",aliases:["aus","oz"]},{country:"New Zealand",code:"NZ",language:"English",langCode:"en",aliases:["nz","aotearoa"]},{country:"Fiji",code:"FJ",language:"English",langCode:"en"},{country:"Papua New Guinea",code:"PG",language:"English",langCode:"en",aliases:["png"]},{country:"Samoa",code:"WS",language:"English",langCode:"en"},{country:"Tonga",code:"TO",language:"English",langCode:"en"},{country:"Vanuatu",code:"VU",language:"English",langCode:"en"},{country:"Solomon Islands",code:"SB",language:"English",langCode:"en"},{country:"Kiribati",code:"KI",language:"English",langCode:"en"},{country:"Tuvalu",code:"TV",language:"English",langCode:"en"},{country:"Nauru",code:"NR",language:"English",langCode:"en"},{country:"Palau",code:"PW",language:"English",langCode:"en"},{country:"the Marshall Islands",code:"MH",language:"English",langCode:"en",aliases:["marshall islands"]},{country:"Micronesia",code:"FM",language:"English",langCode:"en",aliases:["federated states of micronesia"]},{country:"Egypt",code:"EG",language:"Arabic",langCode:"ar"},{country:"Libya",code:"LY",language:"Arabic",langCode:"ar"},{country:"Tunisia",code:"TN",language:"Arabic",langCode:"ar"},{country:"Algeria",code:"DZ",language:"Arabic",langCode:"ar"},{country:"Morocco",code:"MA",language:"Arabic",langCode:"ar",aliases:["maroc"]},{country:"Sudan",code:"SD",language:"Arabic",langCode:"ar"},{country:"South Sudan",code:"SS",language:"English",langCode:"en"},{country:"Mauritania",code:"MR",language:"Arabic",langCode:"ar"},{country:"Nigeria",code:"NG",language:"English",langCode:"en"},{country:"Ghana",code:"GH",language:"English",langCode:"en"},{country:"Senegal",code:"SN",language:"French",langCode:"fr",aliases:["s\xE9n\xE9gal"]},{country:"C\xF4te d'Ivoire",code:"CI",language:"French",langCode:"fr",aliases:["ivory coast"]},{country:"Mali",code:"ML",language:"French",langCode:"fr"},{country:"Burkina Faso",code:"BF",language:"French",langCode:"fr"},{country:"Niger",code:"NE",language:"French",langCode:"fr"},{country:"Guinea",code:"GN",language:"French",langCode:"fr",aliases:["guin\xE9e"]},{country:"Guinea-Bissau",code:"GW",language:"Portuguese",langCode:"pt"},{country:"Sierra Leone",code:"SL",language:"English",langCode:"en"},{country:"Liberia",code:"LR",language:"English",langCode:"en"},{country:"the Gambia",code:"GM",language:"English",langCode:"en",aliases:["gambia"]},{country:"Cabo Verde",code:"CV",language:"Portuguese",langCode:"pt",aliases:["cape verde"]},{country:"Togo",code:"TG",language:"French",langCode:"fr"},{country:"Benin",code:"BJ",language:"French",langCode:"fr",aliases:["b\xE9nin"]},{country:"Cameroon",code:"CM",language:"French",langCode:"fr",aliases:["cameroun"]},{country:"the Central African Republic",code:"CF",language:"French",langCode:"fr",aliases:["central african republic","car"]},{country:"Chad",code:"TD",language:"French",langCode:"fr",aliases:["tchad"]},{country:"Equatorial Guinea",code:"GQ",language:"Spanish",langCode:"es"},{country:"Gabon",code:"GA",language:"French",langCode:"fr"},{country:"the Republic of the Congo",code:"CG",language:"French",langCode:"fr",aliases:["congo","republic of the congo","congo-brazzaville"]},{country:"the Democratic Republic of the Congo",code:"CD",language:"French",langCode:"fr",aliases:["dr congo","drc","democratic republic of the congo","congo-kinshasa","zaire"]},{country:"S\xE3o Tom\xE9 and Pr\xEDncipe",code:"ST",language:"Portuguese",langCode:"pt",aliases:["sao tome and principe","sao tome"]},{country:"Ethiopia",code:"ET",language:"Amharic",langCode:"am"},{country:"Eritrea",code:"ER",language:"Tigrinya",langCode:"ti"},{country:"Djibouti",code:"DJ",language:"French",langCode:"fr"},{country:"Somalia",code:"SO",language:"Somali",langCode:"so"},{country:"Kenya",code:"KE",language:"English",langCode:"en"},{country:"Uganda",code:"UG",language:"English",langCode:"en"},{country:"Tanzania",code:"TZ",language:"English",langCode:"en",aliases:["united republic of tanzania"]},{country:"Rwanda",code:"RW",language:"English",langCode:"en"},{country:"Burundi",code:"BI",language:"French",langCode:"fr"},{country:"Madagascar",code:"MG",language:"French",langCode:"fr"},{country:"Mauritius",code:"MU",language:"English",langCode:"en"},{country:"the Seychelles",code:"SC",language:"English",langCode:"en",aliases:["seychelles"]},{country:"Comoros",code:"KM",language:"French",langCode:"fr"},{country:"South Africa",code:"ZA",language:"English",langCode:"en",aliases:["sa"]},{country:"Namibia",code:"NA",language:"English",langCode:"en"},{country:"Botswana",code:"BW",language:"English",langCode:"en"},{country:"Zimbabwe",code:"ZW",language:"English",langCode:"en"},{country:"Zambia",code:"ZM",language:"English",langCode:"en"},{country:"Malawi",code:"MW",language:"English",langCode:"en"},{country:"Mozambique",code:"MZ",language:"Portuguese",langCode:"pt",aliases:["mo\xE7ambique"]},{country:"Angola",code:"AO",language:"Portuguese",langCode:"pt"},{country:"Lesotho",code:"LS",language:"English",langCode:"en"},{country:"Eswatini",code:"SZ",language:"English",langCode:"en",aliases:["swaziland"]}],we=[{language:"English",code:"en"},{language:"Italian",code:"it",aliases:["italiano"]},{language:"Spanish",code:"es",aliases:["espa\xF1ol","espanol","castellano"]},{language:"French",code:"fr",aliases:["fran\xE7ais","francais"]},{language:"German",code:"de",aliases:["deutsch"]},{language:"Portuguese",code:"pt",aliases:["portugu\xEAs","portugues"]},{language:"Dutch",code:"nl",aliases:["nederlands","flemish"]},{language:"Swedish",code:"sv",aliases:["svenska"]},{language:"Norwegian",code:"no",aliases:["norsk"]},{language:"Danish",code:"da",aliases:["dansk"]},{language:"Icelandic",code:"is",aliases:["\xEDslenska"]},{language:"Catalan",code:"ca",aliases:["catal\xE0"]},{language:"Romanian",code:"ro",aliases:["rom\xE2n\u0103","romana"]},{language:"Polish",code:"pl",aliases:["polski"]},{language:"Czech",code:"cs",aliases:["\u010De\u0161tina","cestina"]},{language:"Slovak",code:"sk",aliases:["sloven\u010Dina"]},{language:"Slovenian",code:"sl",aliases:["sloven\u0161\u010Dina"]},{language:"Croatian",code:"hr",aliases:["hrvatski"]},{language:"Bosnian",code:"bs",aliases:["bosanski"]},{language:"Serbian",code:"sr",aliases:["\u0441\u0440\u043F\u0441\u043A\u0438"]},{language:"Montenegrin",code:"sr",aliases:["crnogorski"]},{language:"Macedonian",code:"mk",aliases:["\u043C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438"]},{language:"Bulgarian",code:"bg",aliases:["\u0431\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438"]},{language:"Russian",code:"ru",aliases:["\u0440\u0443\u0441\u0441\u043A\u0438\u0439"]},{language:"Ukrainian",code:"uk",aliases:["\u0443\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430"]},{language:"Belarusian",code:"be",aliases:["\u0431\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F"]},{language:"Latvian",code:"lv",aliases:["latvie\u0161u"]},{language:"Lithuanian",code:"lt",aliases:["lietuvi\u0173"]},{language:"Greek",code:"el",aliases:["\u03B5\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC","ellinik\xE1"]},{language:"Albanian",code:"sq",aliases:["shqip"]},{language:"Armenian",code:"hy",aliases:["\u0570\u0561\u0575\u0565\u0580\u0565\u0576"]},{language:"Persian",code:"fa",aliases:["farsi","dari","\u0641\u0627\u0631\u0633\u06CC"]},{language:"Hindi",code:"hi",aliases:["\u0939\u093F\u0928\u094D\u0926\u0940"]},{language:"Urdu",code:"ur",aliases:["\u0627\u0631\u062F\u0648"]},{language:"Bengali",code:"bn",aliases:["bangla","\u09AC\u09BE\u0982\u09B2\u09BE"]},{language:"Nepali",code:"ne",aliases:["\u0928\u0947\u092A\u093E\u0932\u0940"]},{language:"Sinhala",code:"si",aliases:["\u0DC3\u0DD2\u0D82\u0DC4\u0DBD","sinhalese"]},{language:"Finnish",code:"fi",aliases:["suomi"]},{language:"Estonian",code:"et",aliases:["eesti"]},{language:"Hungarian",code:"hu",aliases:["magyar"]},{language:"Turkish",code:"tr",aliases:["t\xFCrk\xE7e","turkce"]},{language:"Azerbaijani",code:"az",aliases:["az\u0259rbaycan dili","azeri"]},{language:"Kazakh",code:"kk",aliases:["\u049B\u0430\u0437\u0430\u049B \u0442\u0456\u043B\u0456"]},{language:"Uzbek",code:"uz",aliases:["o'zbek"]},{language:"Kyrgyz",code:"ky",aliases:["\u043A\u044B\u0440\u0433\u044B\u0437\u0447\u0430"]},{language:"Turkmen",code:"tk",aliases:["t\xFCrkmen\xE7e"]},{language:"Arabic",code:"ar",aliases:["\u0627\u0644\u0639\u0631\u0628\u064A\u0629"]},{language:"Hebrew",code:"he",aliases:["\u05E2\u05D1\u05E8\u05D9\u05EA","ivrit"]},{language:"Amharic",code:"am",aliases:["\u12A0\u121B\u122D\u129B"]},{language:"Tigrinya",code:"ti",aliases:["\u1275\u130D\u122D\u129B"]},{language:"Chinese",code:"zh",aliases:["mandarin","\u4E2D\u6587","\u6C49\u8BED","putonghua"]},{language:"Japanese",code:"ja",aliases:["\u65E5\u672C\u8A9E","nihongo"]},{language:"Korean",code:"ko",aliases:["\uD55C\uAD6D\uC5B4"]},{language:"Thai",code:"th",aliases:["\u0E44\u0E17\u0E22"]},{language:"Vietnamese",code:"vi",aliases:["ti\u1EBFng vi\u1EC7t"]},{language:"Khmer",code:"km",aliases:["\u1781\u17D2\u1798\u17C2\u179A","cambodian"]},{language:"Lao",code:"lo",aliases:["\u0EA5\u0EB2\u0EA7"]},{language:"Burmese",code:"my",aliases:["\u1019\u103C\u1014\u103A\u1019\u102C","myanmar"]},{language:"Dzongkha",code:"dz",aliases:["\u0F62\u0FAB\u0F7C\u0F44\u0F0B\u0F41"]},{language:"Mongolian",code:"mn",aliases:["\u043C\u043E\u043D\u0433\u043E\u043B"]},{language:"Georgian",code:"ka",aliases:["\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8"]},{language:"Tajik",code:"tg",aliases:["\u0442\u043E\u04B7\u0438\u043A\u04E3"]},{language:"Malay",code:"ms",aliases:["bahasa malaysia","bahasa melayu"]},{language:"Indonesian",code:"id",aliases:["bahasa indonesia"]},{language:"Filipino",code:"fil",aliases:["tagalog","pilipino"]},{language:"Swahili",code:"sw",aliases:["kiswahili"]},{language:"Somali",code:"so",aliases:["af soomaali"]},{language:"Yoruba",code:"yo",aliases:["yor\xF9b\xE1"]},{language:"Hausa",code:"ha",aliases:["harshen hausa"]},{language:"Zulu",code:"zu",aliases:["isizulu"]},{language:"Afrikaans",code:"af"}];function C(e){return e.trim().toLowerCase()}function $(e){if(!e)return;let a=C(e);for(let t of be)if(C(t.country)===a||t.aliases?.some(n=>C(n)===a))return t}function V(e){if(!e)return;let a=C(e);for(let t of we)if(C(t.language)===a||t.aliases?.some(n=>C(n)===a))return t}var ke={\u0410:"A",\u0430:"a",\u0412:"B",\u0432:"b",\u0415:"E",\u0435:"e",\u041A:"K",\u043A:"k",\u041C:"M",\u043C:"m",\u041D:"H",\u043D:"h",\u041E:"O",\u043E:"o",\u0420:"P",\u0440:"p",\u0421:"C",\u0441:"c",\u0422:"T",\u0442:"t",\u0423:"Y",\u0443:"y",\u0425:"X",\u0445:"x",\u0406:"I",\u0456:"i",\u0405:"S",\u0455:"s",\u0408:"J",\u0458:"j",\u0417:"3",\u0437:"3",\u0427:"4",\u0431:"6",\u0391:"A",\u03B1:"a",\u0392:"B",\u03B2:"b",\u0395:"E",\u03B5:"e",\u0396:"Z",\u0397:"H",\u0399:"I",\u03B9:"i",\u039A:"K",\u03BA:"k",\u039C:"M",\u039D:"N",\u039F:"O",\u03BF:"o",\u03A1:"P",\u03C1:"p",\u03A4:"T",\u03C4:"t",\u03A5:"Y",\u03A7:"X",\u03C7:"x",\u03BD:"v","\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\uFF3F":"_"},Ce=/[\u200B-\u200F\u202A-\u202E\u2060\uFEFF\u00AD]/g,Se=/[\u0000-\u001F\u007F]/g;function x(e){let a=e.replace(Ce,"").replace(Se,"").trim();return{value:a,changed:a!==e,repairs:[],unrepairable:[]}}function S(e){let t=x(e).value.normalize("NFKC").replace(/\s+/g,"");t.length>=2&&(t[0]==='"'&&t.at(-1)==='"'||t[0]==="'"&&t.at(-1)==="'")&&(t=t.slice(1,-1).trim());let n=[],i=[],o="";for(let s of t){let r=s.codePointAt(0);if(r<128){o+=s;continue}let m=ke[s],u=o.length+1;m?(n.push(`position ${u}: '${s}' (${Te(r)}, U+${O(r)}) \u2192 '${m}'`),o+=m):(i.push({position:u,char:s,code:r}),o+=s)}return{value:o,changed:o!==e,repairs:n,unrepairable:i}}var ve=/^AIza[0-9A-Za-z_-]{35}$/;function Pe(e){return ve.test(e)}function W(e){let a=S(e);if(a.value.length===0)return"Required \u2014 without this Klaudius can't find candidates.";if(a.unrepairable.length>0){let t=a.unrepairable[0];return`Character ${t.position} of this key is '${t.char}' (U+${O(t.code)}), which isn't a character a Google key can contain. Copy the key with the copy button next to it in the Cloud Console \u2014 reading it off a screenshot or retyping it introduces look-alike characters.`}}function Pa(e){let a=S(e).value;if(!Pe(a))return a.startsWith("AIza")?a.length!==39?`A Google API key is normally 39 characters \u2014 this one is ${a.length}. `+(a.length>39?"It looks like two keys ran together, so paste just the one key.":"It looks truncated, so copy it again with the copy button next to it in the Cloud Console."):"This key contains characters a Google key normally doesn't. Re-copy it with the copy button in the Cloud Console.":`A Google API key normally starts with "AIza" \u2014 this one starts with "${a.slice(0,4)}". Check you copied the API key itself (Cloud Console \u2192 Credentials), not a project ID or client ID.`}var Ae=/^\d+:[A-Za-z0-9_-]{35}$/;function j(e){let a=S(e);if(a.value.length===0)return"Required \u2014 paste the token @BotFather sent you.";if(a.unrepairable.length>0){let t=a.unrepairable[0];return`Character ${t.position} of this token is '${t.char}' (U+${O(t.code)}), which a bot token can't contain. Copy the token from @BotFather's message rather than retyping it.`}}function q(e){if(!Ae.test(S(e).value))return"That doesn't look like a bot token, which is a number, a colon, then 35 letters and digits (like 1234567890:AAEhBP\u2026). Copy just the token from @BotFather's message, not the words around it."}function O(e){return e.toString(16).toUpperCase().padStart(4,"0")}function Te(e){return e>=1024&&e<=1279?"Cyrillic":e>=880&&e<=1023?"Greek":"non-Latin"}var Z=class extends Error{constructor(){super("user pressed back"),this.name="BackSignal"}},Y=class extends Error{constructor(){super("user cancelled"),this.name="CancelSignal"}},Ie="Include the country code with a + (e.g. +12025550123 for US, +447123456789 for UK)",J=e=>/^\+\d{8,15}$/.test(e)?void 0:Ie,Q=e=>/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e)?void 0:"Enter a valid email",b=e=>a=>a.trim().length===0?`${e} is required`:void 0,Ee=/[\u2022\u2023\u2024\u2027\u00B7\u2219\u22C5\u25CF\u25CB\u25AA\u25AB\u204E\u2217\uFE61\u25E6\u2218]/,xe="That looks like the masked \u2022\u2022\u2022\u2022\u2022 value your screen shows, not the token itself. Click the reveal/copy icon next to it and paste the real value (letters and numbers).",N=e=>Ee.test(e)?xe:void 0;function Oe(e){if(/^eyJ/.test(e))try{let a=e.split(".")[1];if(!a)return;let t=JSON.parse(Buffer.from(a,"base64url").toString("utf8"));return typeof t.role=="string"?t.role:void 0}catch{return}}var M=e=>a=>N(a)??(a.trim().length===0?`${e} is required`:void 0),Me=e=>{let a=e.replace(/\s+/g,"");return a.length===0?"Personal access token is required":N(a)??(/^sbp_[A-Za-z0-9._~+\/=-]{20,}$/.test(a)?void 0:"Doesn't look like a valid token \u2014 it should be 'sbp_' followed by letters and numbers.")},Ne="one-off, no monthly fees",X="per month";function A(e){if(!e)return!0;let a=e.trim();if(a==="")return!0;let t=a.replace(/[^\d.]/g,"");if(t==="")return/^\s*free\s*$/i.test(a);let n=parseFloat(t);return!isNaN(n)&&n===0}var He={id:"ai-agent",title:"AI coding agent",isApplicable:()=>!0,execute:async(e,{prompt:a,info:t})=>(t({title:"Which AI coding agent do you use?",body:`Klaudius works with two AI coding agents in your terminal \u2014 Claude Code
|
|
63
63
|
(Anthropic) or Codex (OpenAI). Pick whichever you already pay for.
|
|
64
64
|
|
|
@@ -73,7 +73,7 @@ the plan's usage window. Pro and above: full pipeline, QA pass included.
|
|
|
73
73
|
Max and above: full pipeline, QA pass included.
|
|
74
74
|
|
|
75
75
|
`)+`Not locked in \u2014 ask ${i} to turn the QA pass on or off any
|
|
76
|
-
time, or re-run configure if you change plan.`});let s=n?[{value:"codex-plus",label:"ChatGPT Plus (QA pass off, Terra model)"},{value:"codex-pro",label:"ChatGPT Pro (full pipeline)"},{value:"codex-other",label:"Other \u2014 Business
|
|
76
|
+
time, or re-run configure if you change plan.`});let s=n?[{value:"codex-plus",label:"ChatGPT Plus (QA pass off, Terra model)"},{value:"codex-pro",label:"ChatGPT Pro (full pipeline)"},{value:"codex-other",label:"Other \u2014 Business or Enterprise (full pipeline)"}]:[{value:"claude-pro",label:"Claude Pro (QA pass off)"},{value:"claude-max-5x",label:"Claude Max 5x (full pipeline)"},{value:"claude-max-20x",label:"Claude Max 20x (full pipeline)"},{value:"claude-other",label:"Other \u2014 Team or Enterprise (full pipeline)"}],r=s.some(g=>g.value===e.aiPlan)?e.aiPlan:void 0,m=!n&&!r?_():void 0,u=await a({type:"select",message:`Which ${o} plan will ${i} run on?`,initialValue:r??m??s[0].value,options:s}),c=u===e.aiPlan&&e.qaPhase!==void 0?e.qaPhase:U(u);return{aiPlan:u,qaPhase:c}}},Fe={id:"location",title:"Location & language",isApplicable:()=>!0,execute:async(e,{prompt:a,info:t})=>{t({title:"Which country are you finding businesses in?",body:`Klaudius searches for businesses in this country, writes outreach in
|
|
77
77
|
this country's language, and builds sites in this country's language.
|
|
78
78
|
This is the country your customers are in \u2014 not necessarily where
|
|
79
79
|
you live.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.32.
|
|
3
|
+
"version": "0.32.4",
|
|
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": {
|