klaudius 0.30.2 → 0.30.3
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,2 +1,2 @@
|
|
|
1
|
-
import{a as d,m as $,n as ne,p as k}from"./chunk-
|
|
1
|
+
import{a as d,m as $,n as ne,p as k}from"./chunk-F2UIJSEK.js";import{useEffect as Ue,useMemo as Ne,useRef as ee,useState as I}from"react";import{Box as h,Text as w,useApp as De,useInput as Ve}from"ink";import{Box as ie,Text as be}from"ink";import{jsx as se,jsxs as ve}from"react/jsx-runtime";var he={pending:"\u25CB",current:"\u25C9",done:"\u2713",skipped:"\xB7"},Be={pending:void 0,current:"cyan",done:"green",skipped:void 0};function ce({items:e}){return se(ie,{flexDirection:"column",width:28,flexShrink:0,children:e.map(r=>{let o=r.status==="skipped"||r.status==="pending";return se(ie,{children:ve(be,{color:Be[r.status],bold:r.status==="current",dimColor:o&&r.status!=="current",children:[he[r.status]," ",r.title]})},r.id)})})}import{useEffect as ye,useState as ae}from"react";import{Box as H,Text as N,useInput as we}from"ink";import ke from"ink-text-input";import{jsx as E,jsxs as X}from"react/jsx-runtime";function le({spec:e,masked:r,onSubmit:o,onBack:t}){let p=typeof e.initialValue=="string"?e.initialValue:"",s=r&&p.length>0,[c,x]=ae(s?"":p),[f,i]=ae(null);ye(()=>(d("TextPromptUI:mount",{masked:r,message:e.message.slice(0,60),initial:typeof e.initialValue=="string"?e.initialValue.slice(0,30):null}),()=>{d("TextPromptUI:unmount")}),[r,e.message,e.initialValue]),we((n,S)=>{d("TextPromptUI:useInput fired",{input:n,ctrl:S.ctrl,escape:S.escape,return:S.return}),S.escape&&t()});let P=n=>{d("TextPromptUI:handleSubmit",{raw:n.slice(0,30)});let S=n.length===0&&s?p:n;if(e.validate){let B=e.validate(S);if(B){d("TextPromptUI:validate failed",{err:B}),i(B);return}}i(null),o(S)};return X(H,{flexDirection:"column",children:[X(N,{children:[E(N,{color:"cyan",children:"?"})," ",e.message]}),X(H,{children:[E(N,{color:"green",children:"\u203A "}),E(ke,{value:c,onChange:x,onSubmit:P,placeholder:s?"type or paste a new value \u2014 or press Enter to keep the current one":e.placeholder,mask:r?"\u2022":void 0})]}),f&&E(H,{marginTop:0,children:E(N,{color:"red",children:f})})]})}import{useState as Ie}from"react";import{Box as G,Text as D,useInput as Ae}from"ink";import{jsx as V,jsxs as K}from"react/jsx-runtime";function pe({spec:e,onSubmit:r,onBack:o}){let t=e.options??[],p=typeof e.initialValue=="string"?Math.max(0,t.findIndex(x=>x.value===e.initialValue)):0,[s,c]=Ie(p===-1?0:p);return Ae((x,f)=>{if(f.escape)o();else if(f.upArrow)c(i=>(i-1+t.length)%t.length);else if(f.downArrow)c(i=>(i+1)%t.length);else if(f.return){let i=t[s];i&&r(i.value)}}),K(G,{flexDirection:"column",children:[K(D,{children:[V(D,{color:"cyan",children:"?"})," ",e.message]}),V(G,{flexDirection:"column",marginTop:0,children:t.map((x,f)=>{let i=f===s;return K(D,{color:i?"cyan":void 0,bold:i,children:[i?"\u25CF ":"\u25CB ",x.label]},x.value)})}),V(G,{marginTop:1,children:V(D,{dimColor:!0,children:"Use the \u2191 \u2193 arrow keys to choose, then press Enter"})})]})}import{useState as Re}from"react";import{Box as q,Text as A,useInput as Ce}from"ink";import{jsx as W,jsxs as z}from"react/jsx-runtime";function ue({spec:e,onSubmit:r,onBack:o}){let[t,p]=Re(typeof e.initialValue=="boolean"?e.initialValue:!0);return Ce((s,c)=>{c.escape?o():c.leftArrow||c.rightArrow?p(x=>!x):s==="y"||s==="Y"?p(!0):s==="n"||s==="N"?p(!1):c.return&&r(t)}),z(q,{flexDirection:"column",children:[z(A,{children:[W(A,{color:"cyan",children:"?"})," ",e.message]}),z(q,{marginTop:0,children:[z(A,{color:t?"cyan":void 0,bold:t,children:[t?"\u25CF ":"\u25CB ","Yes"]}),W(A,{children:" "}),z(A,{color:t?void 0:"cyan",bold:!t,children:[t?"\u25CB ":"\u25CF ","No"]})]}),W(q,{marginTop:1,children:W(A,{dimColor:!0,children:"Use the \u2190 \u2192 arrow keys (or y / n) to choose, then press Enter"})})]})}import{useState as me}from"react";import{Box as J,Text as O,useInput as Ee}from"ink";import{jsx as M,jsxs as Q}from"react/jsx-runtime";function de({spec:e,onSubmit:r,onBack:o}){let t=e.options??[],p=new Set(typeof e.initialValue=="string"?e.initialValue.split(",").map(i=>i.trim()).filter(Boolean):[]),[s,c]=me(0),[x,f]=me(p);return Ee((i,P)=>{if(P.escape)o();else if(P.upArrow)c(n=>(n-1+t.length)%t.length);else if(P.downArrow)c(n=>(n+1)%t.length);else if(i===" "){let n=t[s];n&&f(S=>{let B=new Set(S);return B.has(n.value)?B.delete(n.value):B.add(n.value),B})}else P.return&&r(t.map(n=>n.value).filter(n=>x.has(n)).join(","))}),Q(J,{flexDirection:"column",children:[Q(O,{children:[M(O,{color:"cyan",children:"?"})," ",e.message]}),M(J,{flexDirection:"column",marginTop:0,children:t.map((i,P)=>{let n=P===s,S=x.has(i.value);return Q(O,{color:n?"cyan":void 0,bold:n,children:[n?"\u203A ":" ",S?"\u25C9 ":"\u25EF ",i.label]},i.value)})}),M(J,{marginTop:1,children:M(O,{dimColor:!0,children:"\u2191 \u2193 to move, Space to tick/untick, Enter to confirm (ticking none is fine)"})})]})}import{Box as fe,Text as ge}from"ink";import{jsx as Z,jsxs as ze}from"react/jsx-runtime";function _({title:e,body:r}){let o=r.split(`
|
|
2
2
|
`);return ze(fe,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[Z(ge,{color:"cyan",bold:!0,children:e}),Z(fe,{flexDirection:"column",marginTop:0,children:o.map((t,p)=>Z(ge,{dimColor:!1,children:t.length===0?" ":t},p))})]})}import{jsx as l,jsxs as U}from"react/jsx-runtime";function yt({defaults:e,onComplete:r,onlySection:o,banner:t}){let{exit:p}=De(),s=ee({...e}),c=ee(new Map),[,x]=I(0),f=()=>x(u=>u+1),[i,P]=I(null),[n,S]=I(null),[B,te]=I([]),[F,re]=I(null),[oe,xe]=I(!1),[j,Se]=I({current:0,total:0}),R=()=>{let u=c.current;for(let g of k){let Y=g.isApplicable(s.current),a=u.get(g.id);Y?o&&g.id!==o?a!=="current"&&u.set(g.id,"done"):(a==="skipped"||!a)&&u.set(g.id,"pending"):u.set(g.id,"skipped")}};c.current.size===0&&R();let L=ee(!1);Ue(()=>{if(d("WizardApp:useEffect fired",{startedAlready:L.current}),L.current){d("WizardApp:useEffect returning early (startedRef true)");return}L.current=!0,d("WizardApp:orchestrator starting");let u=0,g=a=>{let v=++u;return d("orchestrator:promptFn called",{id:v,type:a.type,message:a.message.slice(0,60)}),re(null),new Promise((T,m)=>{S({id:v,spec:a,resolve:y=>{d("orchestrator:prompt resolved",{id:v,type:a.type,value:typeof y=="string"?y.slice(0,30):y}),T(y)},reject:y=>{d("orchestrator:prompt rejected",{id:v,reason:y.message}),m(y)}})})},Y=a=>{te(v=>[...v,a])};return(async()=>{try{let a=o?k.filter(m=>m.id===o):k,v=()=>a.filter(m=>m.isApplicable(s.current)).length,T=0;for(;T<a.length;){let m=a[T];if(!m.isApplicable(s.current)){c.current.set(m.id,"skipped"),T++,R(),f();continue}te([]);for(let b of k)b.id===m.id?c.current.set(b.id,"current"):c.current.get(b.id)==="current"&&c.current.set(b.id,"pending");P(m.id);let y=a.slice(0,T+1).filter(b=>b.isApplicable(s.current)).length;Se({current:y,total:v()}),f();try{let b=await m.execute(s.current,{prompt:g,info:Y});s.current={...s.current,...b},c.current.set(m.id,"done"),R(),T++}catch(b){if(b instanceof $){if(o&&m.clearOnSkip){for(let Te of m.clearOnSkip)s.current[Te]=void 0;c.current.set(m.id,"skipped"),R(),T++;continue}if(o)continue;c.current.set(m.id,"pending");let C=T-1;for(;C>=0&&!a[C].isApplicable(s.current);)C--;C<0||(T=C,c.current.set(a[T].id,"pending")),R(),f();continue}throw b}}d("orchestrator:all sections done, calling onComplete + exit"),xe(!0),S(null),P(null),f(),await new Promise(m=>setTimeout(m,200)),r(s.current),p()}catch(a){d("orchestrator:caught error",{name:a?.name,message:a?.message}),a instanceof ne&&(p(),process.exit(0));let v=a instanceof Error?a.message:String(a);re(`Setup error: ${v}`),f()}})(),()=>{d("WizardApp:useEffect cleanup ran (component unmounting)")}},[p,r]),Ve((u,g)=>{d("WizardApp:useInput fired",{input:u,ctrl:g.ctrl,escape:g.escape,return:g.return}),g.ctrl&&u==="c"&&(d("WizardApp:Ctrl+C \u2192 exiting"),p(),process.exit(0))});let Pe=Ne(()=>k.map(u=>({id:u.id,title:u.title,status:c.current.get(u.id)??"pending"})),[i,oe,F]);return U(h,{flexDirection:"column",paddingY:1,children:[U(h,{marginBottom:1,children:[l(w,{bold:!0,color:"cyan",children:"Klaudius setup"}),l(w,{dimColor:!0,children:" \xB7 "}),l(w,{dimColor:!0,children:j.total>0?`Step ${j.current} of ${j.total}`:"Loading\u2026"})]}),U(h,{children:[l(ce,{items:Pe}),U(h,{flexDirection:"column",flexGrow:1,marginLeft:2,children:[t&&U(h,{marginBottom:1,borderStyle:"round",borderColor:"red",paddingX:1,flexDirection:"column",children:[l(w,{color:"red",bold:!0,children:"\u26A0 Heads up"}),l(w,{children:t})]}),!o&&i!==null&&i!=="ai-agent"&&l(h,{marginBottom:1,children:l(w,{color:"green",children:"Nothing here is permanent, you can customize any of this later."})}),B.map((u,g)=>l(h,{marginBottom:1,children:l(_,{title:u.title,body:u.body})},g)),n?.spec.note&&l(h,{marginBottom:1,children:l(_,{title:n.spec.note.title,body:n.spec.note.body})}),n&&Oe(n),F&&l(h,{marginTop:1,children:l(w,{color:"red",children:F})}),oe&&l(h,{marginTop:1,children:l(w,{color:"green",bold:!0,children:"\u2713 Setup complete. Continuing\u2026"})})]})]}),l(h,{marginTop:1,children:l(w,{dimColor:!0,children:We(o,i)})})]})}function We(e,r){if(e){let o=k.find(t=>t.id===r);return o?.clearOnSkip&&o.clearOnSkip.length>0?"\u21B5 confirm esc skip this section ctrl-c cancel":"\u21B5 confirm ctrl-c cancel"}return"\u21B5 confirm esc back to previous section ctrl-c cancel"}function Oe(e){let r=t=>e.resolve(t),o=()=>e.reject(new $);switch(e.spec.type){case"text":case"password":return l(le,{spec:e.spec,masked:e.spec.type==="password",onSubmit:r,onBack:o},e.id);case"select":return l(pe,{spec:e.spec,onSubmit:r,onBack:o},e.id);case"multiselect":return l(de,{spec:e.spec,onSubmit:r,onBack:o},e.id);case"confirm":return l(ue,{spec:e.spec,onSubmit:r,onBack:o},e.id)}}export{yt as WizardApp};
|
package/dist/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as we,c as Ge,d as J,e as I,f as Jt,g as Xt,h as Be,i as Ve,j as le,k as Zt,l as en,o as tn,q as Ae,r as Ye,s as N}from"./chunk-
|
|
2
|
+
import{b as we,c as Ge,d as J,e as I,f as Jt,g as Xt,h as Be,i as Ve,j as le,k as Zt,l as en,o as tn,q as Ae,r as Ye,s as N}from"./chunk-F2UIJSEK.js";import{Command as Aa}from"commander";import{spawn as on}from"child_process";import{existsSync as Ds}from"fs";import{homedir as Hs}from"os";import O from"picocolors";import{win32 as Ss}from"path";var bs=["&","^","%","!"];function _s(e){return bs.filter(t=>e.includes(t))}function Ee(e){let t=[];for(let{label:n,path:s}of e){let o=_s(s);o.length>0&&t.push({label:n,path:s,chars:o})}return t}function Ts(e){let t=(e??"").trim().replace(/^["']|["']$/g,"");if(!t||t==="undefined"||t==="null")return null;let n=t.toLowerCase().split(/[\\/]/);if(n.length<2||n.includes("system32"))return null;let s=Ss.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(s)?t:null}function Pe(e,t){let n=Ts(e);return n===null?!1:t?t(n):!0}function Se(e,t){let n=e[0],s=[...new Set(e.flatMap(p=>p.chars))],o=s.map(p=>`"${p}"`).join(", "),a=s.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${o} in it ${a?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${a?"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 ce(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10),a=`${n}.${s}.${o}`;return n<22||n===22&&s<15?{ok:!1,version:a,major:n,minor:s,message:`Your installed Node.js is ${a}. 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:a,major:n,minor:s}}import{spawn as Is}from"child_process";import{existsSync as Cs}from"fs";import{homedir as Rs}from"os";import{delimiter as xs,join as We}from"path";var Os=new Set(["Restricted","AllSigned"]);function vs(e,t=Cs){for(let n of e.split(xs)){let s=n.replace(/"/g,"");if(!s)continue;let o=We(s,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let a of["npx.exe","npx.bat","npx.cmd"]){let r=We(s,a);if(t(r))return{path:r,isPs1:!1}}}return null}async function sn(){let e=vs(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await $s();if(!t)return{blocked:!1,shimPath:e.path};let n=We(Rs(),".local","node")+"\\";return{blocked:Os.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function $s(){let e=We(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await nn(e)??await nn("powershell.exe")}function nn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let s=Is(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",a=setTimeout(()=>{s.kill(),n(null)},8e3);s.stdout.on("data",r=>{o+=r.toString()}),s.stderr?.resume(),s.on("close",r=>{clearTimeout(a),n(r===0&&o.trim()?o.trim():null)}),s.on("error",()=>{clearTimeout(a),n(null)})})}import{spawn as Ls}from"child_process";var Le=3,ze=10,Ns=[["python3"],["python"],["py","-3"]];async function q(){for(let e of Ns){let t=await Qe(e[0],[...e.slice(1),"--version"]),n=(t.stdout+t.stderr).trim();if(/Python was not found/i.test(n)||t.code!==0)continue;let s=/Python\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(n);if(!s)continue;let o=parseInt(s[1],10),a=parseInt(s[2],10),r=s[3]?`${o}.${a}.${s[3]}`:`${o}.${a}`;return{command:[...e],version:r,major:o,minor:a}}return null}async function be(){let e=Ms(),t=await q();if(!t){let r=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${Le}.${ze}+ is not installed (or not on PATH). Install it from ${e}.`+r}}let{command:n,version:s,major:o,minor:a}=t;return o<Le||o===Le&&a<ze?{ok:!1,version:s,major:o,minor:a,command:n,message:`Your installed Python is ${s}. Klaudius needs Python ${Le}.${ze} or newer (the pipeline depends on packages that only ship wheels for ${Le}.${ze}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:s,major:o,minor:a,command:n}}function Ms(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Qe(e,t){return new Promise(n=>{let s=Ls(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",a="";s.stdout?.on("data",r=>{o+=r.toString()}),s.stderr?.on("data",r=>{a+=r.toString()}),s.on("close",r=>n({code:r??1,stdout:o,stderr:a})),s.on("error",()=>n({code:1,stdout:o,stderr:a}))})}var an=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function rn(e={}){console.log(O.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
3
|
`));let t=[];t.push(Us());let n=await be();if(t.push(Fs(n)),t.push(await js(n.command)),t.push(await Ks()),process.platform==="win32"){let o=await Gs();o&&t.push(o);let a=await Bs();a&&t.push(a)}t.push(await Vs());for(let o of t){let a=o.status==="ok"?O.green("\u2713"):o.status==="warn"?O.yellow("!"):O.red("\u2717");console.log(` ${a} ${o.name}${o.detail?O.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${O.dim("\u2192")} ${O.cyan(o.nextAction)}`)}console.log();let s=t.filter(o=>o.status==="fail");if(s.length===0){let o=t.filter(a=>a.status==="warn").length;Ys(o);return}console.log(O.red(O.bold(`${s.length} check${s.length===1?"":"s"} failed \u2014 fix the \u2192 items above, then re-run \`npx klaudius@latest preflight\`.`))),console.log(),console.log(O.dim(" AI assistant: install or upgrade whatever's marked \u2717 above for the")),console.log(O.dim(" user, then re-run `npx klaudius@latest preflight` until every check passes.")),console.log(),process.exitCode=1}function Us(){let e=ce();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 Fs(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 js(e){let t=e??["python3"],n=await qe(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 Ks(){let e=process.platform==="win32",t=await qe("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 qe("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 Gs(){let e=await sn();if(e.npxMissing)return null;let t="npx runs in PowerShell";if(!e.blocked){let n="resolves to a policy-immune shim";return e.shimPath&&(n=e.policy?`ExecutionPolicy ${e.policy} allows the npx.ps1 shim`:"npx.ps1 shim present but ExecutionPolicy unreadable \u2014 assuming it runs"),{name:t,status:"ok",detail:n}}return{name:t,status:"fail",detail:`ExecutionPolicy ${e.policy} blocks ${e.shimPath}, which PowerShell prefers over npx.cmd`,nextAction:e.ownInstall?`In PowerShell run: Remove-Item "$env:USERPROFILE\\.local\\node\\np*.ps1" \u2014 it deletes only the PowerShell shims from Klaudius's own Node install (npx falls back to npx.cmd). It prints nothing back; that means it worked. Then re-run this preflight.`:"In Windows PowerShell (the classic blue one, not PowerShell 7) run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned \u2014 printing nothing back means it worked; confirm with Get-ExecutionPolicy (should say RemoteSigned), then re-run this preflight. If it prints an error instead, your organisation manages this setting \u2014 ask IT."}}async function Bs(){let e=Ee([{label:"your Windows user folder",path:Hs()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await qe("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(Pe(s,Ds))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(c=>`"${c}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:a}=Se(e,"preflight"),r=e.some(c=>c.chars.includes("&"));return{name:t,status:r?"fail":"warn",detail:o,nextAction:a}}async function Vs(){try{return await fetch(an,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:an}}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 Ys(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 qe(e,t,n=!1){return new Promise(s=>{let o=n?on([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):on(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),a="",r="";o.stdout?.on("data",c=>{a+=c.toString()}),o.stderr?.on("data",c=>{r+=c.toString()}),o.on("close",c=>s({code:c??1,stdout:a,stderr:r})),o.on("error",()=>s({code:1,stdout:a,stderr:r}))})}import{mkdir as Mt,readdir as ts,readFile as Dt,stat as Ht,writeFile as Nt}from"fs/promises";import{spawnSync as Ut}from"child_process";import{homedir as mo}from"os";import{resolve as go,isAbsolute as yo,join as X,normalize as ko}from"path";import*as P from"@clack/prompts";import h from"picocolors";var Ws={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"},zs={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 ln(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let s=zs[(t??"").toUpperCase()];return s?`${s.pre??""}${n}${s.post??""}`:n}function It(e,t){if(!e)return e;let n=e.replace(/[\s().-]/g,"");if(/^\+\d{8,15}$/.test(n))return n;if(/^00\d{8,15}$/.test(n))return`+${n.slice(2)}`;let s=t?Ws[t.toUpperCase()]:void 0;return s==="1"&&/^1?\d{10}$/.test(n)?`+1${n.slice(-10)}`:s&&s!=="1"&&/^0\d{7,14}$/.test(n)?`+${s}${n.slice(1)}`:e}var Ct="claude-code",Rt="gpt-5.6-terra";function cn(e){if(e==="claude-code"||e==="codex")return e}var Qs=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function Je(e){let t=e?.trim().toLowerCase()??"";return Qs.includes(t)?t:void 0}function Xe(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 xt="vercel";function dn(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function un(e){if(e==="telegram"||e==="email"||e==="sms")return e}function pn(e){if(e==="password"||e==="oauth-microsoft")return e}function qs(e){if(e==="custom"||e!==void 0&&Object.hasOwn(J,e))return e}function Ze(e){let t=qs(e.EMAIL_PROVIDER);if(t)return t;let n=e.EMAIL_SMTP_HOST;if(n){for(let[s,o]of Object.entries(J))if(o.smtpHost===n)return s;return"custom"}}function fn(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let s of t.split(",")){let o=s.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(s=>{let o=/^[a-z0-9_]+$/.test(s)&&s!=="auto",a=c=>{let l=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${c}`];return l?.trim()?l.trim():void 0},r=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(c=>!a(c)).map(c=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${c}`);for(let c of["SMTP_PORT","IMAP_PORT"]){let l=a(c);l!==void 0&&!/^\d+$/.test(l)&&r.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${c}`)}return{label:s,valid:o,auth:(a("AUTH")??"password").toLowerCase(),address:a("ADDRESS"),missing:r,smtpHost:a("SMTP_HOST"),smtpPort:parseInt(a("SMTP_PORT")??"587",10),imapHost:a("IMAP_HOST"),imapPort:parseInt(a("IMAP_PORT")??"993",10),password:a("PASSWORD"),login:a("LOGIN")}})}function et(e){let t=[],n=c=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${c}`),t.push("# "+"=".repeat(60)),t.push("")},s=(c,l)=>{if(l==null||l===""){t.push(`# ${c}=`);return}let p=String(l);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(p)){let u=p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${c}="${u}"`)}else t.push(`${c}=${p}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),s("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),s("AI_AGENT",e.aiAgent??Ct),s("AI_PLAN",e.aiPlan),s("QA_PHASE",e.qaPhase??Ae(e.aiPlan)),n("Operating country and language"),s("OPERATOR_COUNTRY",e.country),s("OPERATOR_COUNTRY_CODE",e.countryCode),s("OPERATOR_LANGUAGE",e.language),s("OPERATOR_LANGUAGE_CODE",e.languageCode),n("Pipeline modes");let o=e.pipelineModes&&e.pipelineModes.length>0?e.pipelineModes:["classic"];s("PIPELINE_MODES",[...new Set(["classic",...o])].join(",")),n("Pricing"),s("PRICING",ln(e.pricing,e.countryCode)),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",ln(e.pricingMonthly,e.countryCode)),n("Automated outreach features"),s("OUTREACH_ENABLED",e.outreachEnabled?"true":"false"),s("OPERATOR_NAME",e.name),s("SIGNATURE",e.signature),s("OUTREACH_CHANNELS",e.outreachChannels?.join(",")),s("OUTREACH_PRIORITY",e.outreachPriority?.join(",")),n("Email outreach"),s("EMAIL_PROVIDER",e.emailProvider),s("EMAIL_AUTH",e.emailAuth??"password"),s("EMAIL_ADDRESS",e.emailAddress),s("EMAIL_PASSWORD",e.emailPassword),s("EMAIL_FROM_NAME",e.emailFromName),s("EMAIL_SMTP_HOST",e.emailSmtpHost),s("EMAIL_SMTP_PORT",e.emailSmtpPort),s("EMAIL_IMAP_HOST",e.emailImapHost),s("EMAIL_IMAP_PORT",e.emailImapPort),s("EMAIL_SENT_FOLDER",e.emailSentFolder),s("EMAIL_INBOX_FOLDER",e.emailInboxFolder),s("EMAIL_DRAFTS_FOLDER",e.emailDraftsFolder),n("SMS outreach"),s("SMS_PROVIDER",e.smsProvider),s("TEST_PHONE",It(e.testPhone,e.countryCode)),s("TWILIO_ACCOUNT_SID",e.twilioAccountSid),s("TWILIO_AUTH_TOKEN",e.twilioAuthToken),s("TWILIO_PHONE_NUMBER",e.twilioPhoneNumber),n("WhatsApp outreach"),s("WHATSAPP_ACCOUNTS",e.whatsappAccounts?.join(",")),n("Letter outreach"),s("LETTER_PROVIDER",e.letterProvider??"none"),s("PINGEN_CLIENT_ID",e.pingenClientId),s("PINGEN_CLIENT_SECRET",e.pingenClientSecret),s("PINGEN_ORG_ID",e.pingenOrgId),s("POSTGRID_API_KEY",e.postgridApiKey),n("Supabase (pipeline state)"),s("SUPABASE_URL",e.supabaseUrl),s("SUPABASE_SERVICE_KEY",e.supabaseServiceKey),s("SUPABASE_ANON_KEY",e.supabaseAnonKey),s("SUPABASE_PAT",e.supabasePat),s("SUPABASE_PROJECT_REF",e.supabaseProjectRef),n("Deployment"),s("DEPLOY_PROVIDER",e.deployProvider??xt),s("VERCEL_TOKEN",e.vercelToken),s("VERCEL_SCOPE",e.vercelScope??""),s("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),s("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),s("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),s("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),s("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),s("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),s("NOTIFY_CHANNEL",e.notifyChannel),s("NOTIFY_TO",e.notifyTo),s("TELEGRAM_BOT_TOKEN",e.telegramBotToken),s("TELEGRAM_CHAT_ID",e.telegramChatId);let a=new Set(t.map(c=>/^#?\s*([A-Z0-9_]+)=/.exec(c)?.[1]).filter(c=>!!c)),r=Object.entries(e.preservedEnv??{}).filter(([c])=>!a.has(c));if(r.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[c,l]of r)s(c,l)}return t.join(`
|
|
5
5
|
`)+`
|
|
@@ -11,8 +11,8 @@ import{b as we,c as Ge,d as J,e as I,f as Jt,g as Xt,h as Be,i as Ve,j as le,k a
|
|
|
11
11
|
`)+`
|
|
12
12
|
`}function Zs(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 K(e){let t={};for(let n of e.split(`
|
|
13
13
|
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let a=s.slice(0,o).trim(),r=Zs(s.slice(o+1).trim());t[a]=r}return t}function gn(e){let t=c=>{let l=e[c];if(!l)return;let p=parseInt(l,10);return isNaN(p)?void 0:p},n=e.SMS_PROVIDER,s=c=>c==="email"||c==="sms"||c==="whatsapp"||c==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(s),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(s),r=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:cn(e.AI_AGENT)??Ct,aiPlan:Je(e.AI_PLAN),qaPhase:Xe(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(c=>c.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailProvider:Ze(e),emailAuth:pn(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:It(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:dn(e.DEPLOY_PROVIDER)??xt,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:un(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function st(e){let t=_=>{let re=e[_];if(!re)return;let j=parseInt(re,10);return isNaN(j)?void 0:j},n=e.SUPABASE_URL,s=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,r=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",l=dn(e.DEPLOY_PROVIDER)??xt,p=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,k=e.CLOUDFLARE_ACCOUNT_ID,d=e.NETLIFY_AUTH_TOKEN,S=e.SELFHOST_DEPLOY_TARGET,y=e.SELFHOST_URL_TEMPLATE;if(!r||!n||!s||!o||!a||!(l==="cloudflare"?!!u&&!!k:l==="netlify"?!!d:l==="selfhost"?!!S&&!!y:!!p))return null;let b=e.SMS_PROVIDER,C=_=>_==="email"||_==="sms"||_==="whatsapp"||_==="letter",B=e.OUTREACH_CHANNELS?.split(",").map(_=>_.trim()).filter(C),ae=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:cn(e.AI_AGENT)??Ct,aiPlan:Je(e.AI_PLAN),qaPhase:Xe(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(_=>_.trim().toLowerCase()).filter(Boolean):void 0,pricing:r,pricingTerms:c,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:ae&&ae.length>0?ae:void 0,whatsappAccounts:R&&R.length>0?R:void 0,emailProvider:Ze(e),emailAuth:pn(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:b==="imessage"||b==="twilio"?b:void 0,testPhone:It(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:l,vercelToken:p,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:k||void 0,netlifyAuthToken:d||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:S||void 0,selfhostUrlTemplate:y||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:un(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Ja,mkdir as Xa,readdir as ri,stat as Za}from"fs/promises";import{dirname as tr,join as Sn,relative as li,sep as ci}from"path";import{fileURLToPath as sr}from"url";import{createHash as yn}from"crypto";import{readFile as ei}from"fs/promises";async function _e(e){let t=await ei(e);return yn("sha256").update(t).digest("hex")}function Ot(e){return yn("sha256").update(e).digest("hex")}import{mkdir as ti,readFile as ni,writeFile as si,access as ii}from"fs/promises";import{dirname as oi,join as kn}from"path";var ai=".klaudius",wn=`${ai}/manifest.json`,it=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml",".ms-token.json"]),An=new Set(["clients/README.md"]);async function En(e){let t=kn(e,wn);try{await ii(t)}catch{return null}let n=await ni(t,"utf-8"),s=JSON.parse(n),o={};for(let[a,r]of Object.entries(s.files??{}))o[a.split("\\").join("/")]=r;return s.files=o,Array.isArray(s.ignored)?s.ignored=s.ignored.filter(a=>typeof a=="string").map(a=>a.split("\\").join("/")):delete s.ignored,s}async function Ne(e,t){let n=kn(e,wn);await ti(oi(n),{recursive:!0}),await si(n,JSON.stringify(t,null,2)+`
|
|
14
|
-
`,"utf-8")}function Pn(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 ri(e,{withFileTypes:!0}),s=[];for(let o of n){let a=Sn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await ge(a,t)):o.isFile()&&s.push(li(t,a).split(ci).join("/")))}return s}async function bn(e){let t=await ge(e),n={};for(let s of t)it.has(s)||(n[s]=await _e(Sn(e,s)));return n}import{copyFile as di,mkdir as _n,mkdtemp as ui,readdir as Tn,rm as In}from"fs/promises";import{tmpdir as pi}from"os";import{dirname as fi,join as ot}from"path";import{Readable as hi}from"stream";import*as Cn from"tar";var mi="https://klaudius.dev/api/template";function gi(e){return hi.fromWeb(e)}async function at(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??mi,n="0.30.
|
|
15
|
-
`+de.bold(de.cyan(e))),detail:e=>console.log(de.dim(" "+e))};var Pi="https://registry.npmjs.org/klaudius/latest";async function Si(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Pi,{signal:t.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let o=await s.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function bi(e,t){let n=a=>a.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(s[a])||Number.isNaN(o[a]))return!1;if(s[a]>o[a])return!0;if(s[a]<o[a])return!1}return!1}async function ct(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Si();!n||!bi(n,t)||(i.blank(),i.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(i.detail("Your project content is fetched fresh either way, so you're not missing any"),i.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),i.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),i.blank())}import{createHash as _i}from"crypto";import{hostname as Nn,userInfo as Ti,platform as Mn,arch as Dn}from"os";var Ii="https://klaudius.dev",Ci="/api/licenses/validate",Ri="0.30.
|
|
14
|
+
`,"utf-8")}function Pn(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 ri(e,{withFileTypes:!0}),s=[];for(let o of n){let a=Sn(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await ge(a,t)):o.isFile()&&s.push(li(t,a).split(ci).join("/")))}return s}async function bn(e){let t=await ge(e),n={};for(let s of t)it.has(s)||(n[s]=await _e(Sn(e,s)));return n}import{copyFile as di,mkdir as _n,mkdtemp as ui,readdir as Tn,rm as In}from"fs/promises";import{tmpdir as pi}from"os";import{dirname as fi,join as ot}from"path";import{Readable as hi}from"stream";import*as Cn from"tar";var mi="https://klaudius.dev/api/template";function gi(e){return hi.fromWeb(e)}async function at(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??mi,n="0.30.3",s;try{s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${I(c)}`)}if(!s.ok){let c="";try{let l=await s.json();c=l.reason?` (${l.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${c}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),a=await ui(ot(pi(),"klaudius-template-")),r=0;try{try{await new Promise((p,u)=>{let k=Cn.extract({cwd:a,strict:!0});k.on("finish",p),k.on("error",u),gi(s.body).on("error",u).pipe(k)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await _n(e.destDir,{recursive:!0});let c=new Set(await Tn(e.destDir)),l=await ge(a);try{for(let p of l){let u=ot(e.destDir,p);await _n(fi(u),{recursive:!0}),await di(ot(a,p),u),r++}}catch(p){let u=await Tn(e.destDir).catch(()=>[]);for(let k of u)c.has(k)||await In(ot(e.destDir,k),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await In(a,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:r,tier:o}}import{copyFile as yi,mkdir as ki,readFile as Rn,rm as wi}from"fs/promises";import{dirname as Ai,join as ye}from"path";import{structuredPatch as Ei}from"diff";var xn=ye(".klaudius","base"),rt=ye(".klaudius","conflict-base");async function lt(e,t,n){let s=ye(e,xn);await wi(s,{recursive:!0,force:!0});for(let o of n){let a=ye(s,o);await ki(Ai(a),{recursive:!0}),await yi(ye(t,o),a)}}async function On(e,t){try{return await Rn(ye(e,xn,t),"utf-8")}catch{return null}}async function vn(e,t){try{return await Rn(ye(e,rt,t),"utf-8")}catch{return null}}function $n(e,t,n,s){return Te(n)?null:e!==null&&!Te(e)&&(!s||Ot(e)===s)?e:t!==null&&!Te(t)&&s&&Ot(t)===s?t:null}function Te(e){return e.includes("\0")||e.includes("\uFFFD")}function Ln(e,t,n=60){let s=Ei("base","new",e,t,"","",{context:2});if(s.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=s.hunks.map(l=>`${l.newStart}-${l.newStart+Math.max(l.newLines-1,0)}`).join(", "),a=[`Upstream changed ${s.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],r=0,c=!1;for(let l of s.hunks){if(r>=n){c=!0;break}a.push(`@@ -${l.oldStart},${l.oldLines} +${l.newStart},${l.newLines} @@`),r+=1;let p=Math.max(n-r,0),u=l.lines.slice(0,p);if(a.push(...u),r+=u.length,u.length<l.lines.length){c=!0;break}}return a.push("```"),c&&a.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),a}import de from"picocolors";var i={info:e=>console.log(de.cyan("\u2139"),e),success:e=>console.log(de.green("\u2713"),e),warn:e=>console.log(de.yellow("\u26A0"),e),error:e=>console.error(de.red("\u2717"),e),step:e=>console.log(de.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+de.bold(de.cyan(e))),detail:e=>console.log(de.dim(" "+e))};var Pi="https://registry.npmjs.org/klaudius/latest";async function Si(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Pi,{signal:t.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let o=await s.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function bi(e,t){let n=a=>a.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(s[a])||Number.isNaN(o[a]))return!1;if(s[a]>o[a])return!0;if(s[a]<o[a])return!1}return!1}async function ct(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Si();!n||!bi(n,t)||(i.blank(),i.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(i.detail("Your project content is fetched fresh either way, so you're not missing any"),i.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),i.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),i.blank())}import{createHash as _i}from"crypto";import{hostname as Nn,userInfo as Ti,platform as Mn,arch as Dn}from"os";var Ii="https://klaudius.dev",Ci="/api/licenses/validate",Ri="0.30.3";async function Hn(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),s=(process.env.KLAUDIUS_API_URL??Ii).replace(/\/$/,"")+Ci,o=Me(),a;try{a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Nn(),os:`${Mn()}-${Dn()}`,cli_version:Ri})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${I(c)}). Check your internet connection or try again later.`}}let r;try{r=await a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return r.ok?{ok:!0,tier:r.tier??"core"}:{ok:!1,reason:r.reason??`License rejected (HTTP ${a.status}).`}}function Me(){let e=[Nn(),Ti().username,Mn(),Dn()].join("|");return _i("sha256").update(e).digest("hex").slice(0,32)}import{readFile as xi}from"fs/promises";import{join as Oi}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: ${I(n)}`}}}async function Un(e){let t;try{t=await xi(Oi(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(s){return{ok:!1,message:`Could not read scripts/schema.sql: ${s.message}`}}let n=e.pat.replace(/\s+/g,"");try{let s=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(s.ok)return{ok:!0};let o=await s.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(i.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${s.status}): ${o.slice(0,300)}`}}catch(s){return{ok:!1,message:`Schema apply failed: ${s.message}`}}}async function dt(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${I(t)}`}}}var Fn="https://api.cloudflare.com/client/v4";function jn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ut(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${Fn}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await o.json(),r=a.result?.status;if(a.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${jn(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}try{let o=await fetch(`${Fn}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await o.json();return a.success===!1?{ok:!1,message:jn(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}}var Kn="https://api.netlify.com/api/v1";async function pt(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${Kn}/user`,{headers:n});if(s.status===401||s.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} verifying the token. Try again or check netlifystatus.com.`}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}try{let s=await fetch(`${Kn}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),a=Array.isArray(o)?o:[];if(a.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let r=typeof a[0]?.slug=="string"?a[0].slug:void 0;return{ok:!0,accountCount:a.length,accountSlug:r}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}}function vi(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,s=/caller does not have permission|billing/i.test(t)?"This usually means the key's Google Cloud project has no active billing account \u2014 Places needs billing set up even though Google's free monthly credit covers normal use. Check https://console.cloud.google.com/billing for the project this key belongs to. (Less often: the key's restrictions block the Places API \u2014 check Credentials.)":"Common causes: the key is wrong or deleted, billing is not enabled on its Cloud project, or the key's restrictions block the Places API. Check https://console.cloud.google.com/billing and the key's entry under Credentials.";return`${n} ${s}`}async function Ce(e){let t=Zt(e);if(t)return{ok:!1,message:t};let n=le(e),s=n.value,o=a=>{let r=[a],c=en(e);return c&&r.push(c),n.repairs.length>0&&r.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),r.join(`
|
|
16
16
|
`)};try{let a=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(a.ok)return{ok:!0};if(a.status===429)return{ok:!0};let r={};try{r=await a.json()}catch{}let c=r.error?.message??"",l=r.error?.status??"";return a.status===400&&(l==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(c))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:a.status===401||a.status===403?{ok:!1,message:o(vi(a.status,c))}:{ok:!1,message:o(`Google API returned HTTP ${a.status}${c?`: ${c}`:""}.`)}}catch(a){return{ok:!1,message:`Could not reach Google: ${I(a)}`}}}import $i from"nodemailer";import{ImapFlow as Li}from"imapflow";function Gn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let s=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return s.includes("invalid credentials")||s.includes("authentication failed")||s.includes("auth failed")||s.includes("login failed")||s.includes("invalid login")?"auth":s.includes("etimedout")||s.includes("timeout")||s.includes("enotfound")||s.includes("getaddrinfo")||s.includes("econnrefused")||s.includes("econnreset")?"network":"other"}async function ie(e){let t=$i.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(o){return{ok:!1,failedAt:"smtp",message:Bn(o,"SMTP",e.usesAccountPassword),failureKind:Gn(o)}}finally{t.close()}let n=new Li({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}),s;try{if(await n.connect(),e.draftsFolder)try{let o=await n.list(),a=e.draftsFolder.toLowerCase();if(!o.some(c=>c.path.toLowerCase()===a)){let c=o.find(l=>l.specialUse==="\\Drafts")?.path;s={configured:e.draftsFolder,detected:c}}}catch{}await n.logout()}catch(o){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:Bn(o,"IMAP",e.usesAccountPassword),failureKind:Gn(o)}}return{ok:!0,draftsFolderIssue:s}}function Bn(e,t,n){let s=e instanceof Error?e.message:String(e),o=s.toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
|
|
17
17
|
\u2022 The mailbox password is wrong or mistyped.
|
|
18
18
|
\u2022 The email address doesn't match this mailbox's login.
|
|
@@ -26,7 +26,7 @@ import{b as we,c as Ge,d as J,e as I,f as Jt,g as Xt,h as Be,i as Ve,j as le,k a
|
|
|
26
26
|
\u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}async function Vn(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let s=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(s.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!s.ok)return{ok:!1,message:`Twilio API returned HTTP ${s.status}. Try again or check status.twilio.com.`};let o=await s.json();return o.status&&o.status!=="active"?{ok:!1,message:`Twilio account is in '${o.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:o.friendly_name}}catch(s){return{ok:!1,message:`Could not reach Twilio: ${I(s)}`}}}async function ft(e){return e.provider==="pingen"?Ni(e):Mi(e)}async function Ni(e){if(!e.pingenClientId||!e.pingenClientSecret||!e.pingenOrgId)return{ok:!1,message:"Missing Pingen Client ID, Client Secret, or organisation id."};let t=e.pingenStaging?"https://identity-staging.pingen.com":"https://identity.pingen.com",n=e.pingenStaging?"https://api-staging.pingen.com":"https://api.pingen.com";try{let s=await fetch(`${t}/auth/access-tokens`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:e.pingenClientId,client_secret:e.pingenClientSecret,scope:"letter"})});if(!s.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${s.status}). Check the Client ID and Secret under your organisation's 'API Access' page \u2014 note that staging and production credentials are separate.`};let o=(await s.json()).access_token;if(!o)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let a=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${o}`}});return a.status===403||a.status===404?{ok:!1,message:"Pingen accepted the credentials but not the organisation id. Copy it from the dashboard URL: app.pingen.com/organisations/<id>/\u2026"}:a.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${a.status}. Try again shortly.`}}catch(s){return{ok:!1,message:`Could not reach Pingen: ${I(s)}`}}}async function Mi(e){if(!e.postgridApiKey)return{ok:!1,message:"Missing PostGrid API key."};try{let t=await fetch("https://api.postgrid.com/print-mail/v1/letters?limit=1",{headers:{"x-api-key":e.postgridApiKey}});return t.status===401||t.status===403?{ok:!1,message:"PostGrid rejected the API key (HTTP "+t.status+"). Copy it from the PostGrid dashboard \u2014 the live key starts with 'live_sk_'."}:t.ok?{ok:!0,friendlyName:e.postgridApiKey.startsWith("test_")?"test mode \u2014 letters will NOT print":void 0}:{ok:!1,message:`PostGrid API returned HTTP ${t.status}. Try again shortly.`}}catch(t){return{ok:!1,message:`Could not reach PostGrid: ${I(t)}`}}}import{spawn as Di}from"child_process";async function Yn(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,s=await Hi(n);if(s.code===0)return{ok:!0};let o=s.stderr.toLowerCase();return o.includes("can't get application")||o.includes("isn't running")||o.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:o.includes("(-1728)")||o.includes("not found")||o.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:o.includes("(-1719)")||o.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${s.stderr.trim()||`exit code ${s.code}`}`}}function Hi(e){return new Promise(t=>{let n=Di("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),s="";n.stderr.on("data",o=>{s+=o.toString()}),n.on("close",o=>t({code:o??1,stderr:s})),n.on("error",o=>t({code:1,stderr:o.message}))})}import{spawn as ht}from"child_process";import{existsSync as Ui}from"fs";import{homedir as Fi}from"os";function ji(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var Re=2,Wn=2e3,Ki=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function zn(e,t){let n=e+`
|
|
27
27
|
`+t;return Ki.some(s=>s.test(n))}function Qn(e){return new Promise(t=>setTimeout(t,e))}function Gi(e,t,n){return new Promise(s=>{let o=n.shell?ht([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):ht(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),a="",r="";o.stdout?.on("data",c=>{let l=c.toString();a+=l,process.stdout.write(l)}),o.stderr?.on("data",c=>{let l=c.toString();r+=l,process.stderr.write(l)}),o.on("close",c=>s({code:c??1,stdout:a,stderr:r})),o.on("error",c=>s({code:1,stdout:a,stderr:r+c.message}))})}async function vt(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=Re;o++){if(s=await Gi(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!zn(s.stderr,s.stdout))return s;o<Re&&(i.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${Re+1})\u2026`),await Qn(Wn))}return s}function Bi(e,t,n){return new Promise(s=>{let o=ht(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",r="";o.stdout?.on("data",c=>{a+=c.toString()}),o.stderr?.on("data",c=>{r+=c.toString()}),o.on("close",c=>s({code:c??1,stdout:a,stderr:r})),o.on("error",c=>s({code:1,stdout:a,stderr:r+c.message}))})}var Vi=[{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 Yi(e){let t=`${e.stderr??""}
|
|
28
28
|
${e.stdout??""}`;return Vi.find(s=>s.pattern.test(t))?.hint}async function Wi(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await q())?.command??["python3"],a=async c=>{let l={code:0,stdout:"",stderr:""};for(let p=0;p<=Re;p++){if(l=await Bi(o[0],[...o.slice(1),...c],{cwd:e}),l.code===0||!zn(l.stderr,l.stdout))return l;p<Re&&(i.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${Re+1})\u2026`),await Qn(Wn))}return l},r=await a([...n,"--break-system-packages",...t]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),r=await a([...n,...t])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function mt(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=ji(),s=process.platform==="win32",o;if(s){let u=Ee([{label:"your Windows user folder",path:Fi()},{label:"the project folder",path:e}]);if(u.length>0){let k=await new Promise(S=>{let y=ht("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),E="",b="";y.stdout?.on("data",C=>{E+=C.toString()}),y.stderr?.on("data",C=>{b+=C.toString()}),y.on("close",C=>S({code:C??1,stdout:E,stderr:b})),y.on("error",C=>S({code:1,stdout:E,stderr:C.message}))}),d=k.code===0?k.stdout.trim():void 0;if(!Pe(d,Ui)){let{detail:S,action:y}=Se(u,"install");o=`${S}. ${y}`}}}let a=(u,k)=>{let d=Yi(k);if(d){(t.hints??={})[u]=d;return}o&&(u==="npm"||u==="playwright"||u==="patchright")&&!Object.values(t.hints??{}).includes(o)&&((t.hints??={})[u]=o)};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let r=await vt("npm",["install"],{cwd:e,label:"npm install",env:n,shell:s});t.npm=r.code===0?"ok":"failed",r.code!==0&&a("npm",r),i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let c=await Wi(e);t.pip=c.code===0?"ok":"failed",c.code!==0&&a("pip",c),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let l=await vt("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:s});t.playwright=l.code===0?"ok":"failed",l.code!==0&&a("playwright",l),i.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await vt("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:s});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&a("patchright",p),t}import{copyFile as zi,access as Qi}from"fs/promises";import{dirname as qi,join as Ji}from"path";async function qn(){let e=await Qe("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 $t(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await qn();if(e.state==="real")return{status:"ok",version:e.version};let t=await q();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function Xi(e){let[t,...n]=e.command,s=await Qe(t,[...n,"-c","import sys; print(sys.executable)"]),o=s.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(s.code!==0||!o)return{ok:!1,reason:"no-exe-path"};let a=Ji(qi(o),"python3.exe"),r=await Qi(a).then(()=>!0,()=>!1);if(!r){if(/[\\/]WindowsApps[\\/]/i.test(a))return{ok:!1,reason:"store-python",target:a};try{await zi(o,a)}catch{return{ok:!1,reason:"not-writable",target:a,manualCommand:`copy "${o}" "${a}"`}}}let c=await qn();return{ok:!0,target:a,created:!r,verified:c.state==="real",postState:c.state==="real"?void 0:c.state}}var Zi="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 gt(){let e=await $t();if(e.status!=="broken")return;let t=await Xi(e.fallback);if(t.ok&&t.verified){let n=t.created?e.literal==="stub"?"Fixed a Windows quirk: `python3` was a Store placeholder; it now runs your real Python.":"Fixed a Windows quirk: created the missing `python3` command from your real Python.":"The `python3` command now works \u2014 it runs your real Python.";i.success(n);return}if(t.ok&&t.postState==="stub"){i.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),i.detail(Zi);return}if(t.ok){i.warn("A python3.exe is in place next to your Python, but that folder isn't on this machine's PATH, so commands can't find it."),i.detail('Re-installing Python from python.org with "Add python.exe to PATH" ticked resolves it \u2014 then open a fresh terminal.');return}if(t.reason==="store-python"){i.warn('This Python was installed from the Microsoft Store, which blocks creating the `python3` alias next to it. Installing Python from python.org (tick "Add python.exe to PATH") resolves it.');return}if(t.reason==="not-writable"){i.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),i.detail(t.manualCommand??"");return}i.warn("This machine's `python3` command isn't working, and the automatic fix could not complete. Re-installing Python from python.org (tick \"Add python.exe to PATH\") resolves it.")}import{spawn as eo,spawnSync as Jn}from"child_process";import{mkdtemp as to,rm as no,rmdir as so,writeFile as io,stat as Lt,unlink as oo,mkdir as ao}from"fs/promises";import{createServer as ro}from"net";import{tmpdir as lo}from"os";import{join as xe}from"path";function co(){return new Promise((e,t)=>{let n=ro();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let s=n.address(),o=typeof s=="object"&&s?s.port:0;n.close(()=>e(o))})})}function yt(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?Jn(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):Jn("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function kt(e){try{return await uo(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function uo(e){let t=`klaudius-smoke-${process.pid}`,n=xe(".klaudius",`qa-smoke-${process.pid}.png`),s=xe(e,n),o,a,r=!1;try{o=await to(xe(lo(),"klaudius-qa-smoke-")),await io(xe(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let c=await co();a=eo("python3",["-m","http.server",String(c),"--directory",o],{stdio:"ignore",shell:!1});let l=!1;a.on("error",()=>{l=!0}),a.on("exit",()=>{l=!0});let p=`http://127.0.0.1:${c}/`,u=!1;for(let b=0;b<24&&!l;b++)try{if((await fetch(p,{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 k=xe(e,".klaudius"),d=await Lt(k).then(()=>!0,()=>!1);await ao(k,{recursive:!0}),r=!d;let S=yt(e,[`-s=${t}`,"open",p]);if(S.status!==0)return{ok:!1,stage:"browser",detail:((S.stderr??"")+(S.stdout??"")).slice(-400).trim()||"playwright-cli could not open a browser",remediation:"Run `npx playwright install chromium` in this folder"+(process.platform==="linux"?", and under WSL also `npx playwright install-deps chromium` (missing system libraries are the usual cause there).":".")};let y=yt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await Lt(s).catch(()=>null);if((!E||E.size===0)&&(y=yt(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await Lt(s).catch(()=>null)),!E||E.size===0){let b=((y.stderr??"")+(y.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${b?` (${b})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{yt(e,[`-s=${t}`,"close"]),a&&!a.killed&&a.kill(),await oo(s).catch(()=>{}),r&&await so(xe(e,".klaudius")).catch(()=>{}),o&&await no(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as po,readFile as fo,writeFile as ho}from"fs/promises";import{join as Xn}from"path";async function wt(e,t){let n=Xn(e,".claude");await po(n,{recursive:!0});let s=Xn(n,"settings.json"),o={};try{let l=await fo(s,"utf-8"),p=JSON.parse(l);p&&typeof p=="object"&&!Array.isArray(p)&&(o=p)}catch{}let a=o.enabledMcpjsonServers,r=Array.isArray(a)?a.filter(l=>typeof l=="string"):[];r.includes(t)||r.push(t);let c={...o,enabledMcpjsonServers:r};await ho(s,JSON.stringify(c,null,2)+`
|
|
29
|
-
`,"utf-8")}var Zn="0.30.
|
|
29
|
+
`,"utf-8")}var Zn="0.30.3",v=5,H=!1;function U(e,t){i.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 wo(e){let t;try{t=await Dt(e,"utf-8")}catch{U("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let s=JSON.parse(n),o={};for(let[a,r]of Object.entries(s))r!=null&&(o[a]=typeof r=="string"?r:String(r));return o}catch(s){U("answers",`Answers file is not valid JSON: ${s.message}`)}return K(t)}function ue(e){return`npx klaudius@latest init ${At(Oe(e))}`}function Oe(e){if(process.platform==="win32")return e;let t=mo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Ao(e){let t=[];try{let s=(await ts(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let a=X(e,o.name);if(!await es(X(a,".env")))continue;let r=await es(X(a,".klaudius","manifest.json"));if(t.push({path:a,finished:r}),t.length>=3)break}}catch{}return t}async function es(e){try{return await Ht(e),!0}catch{return!1}}function At(e){return/\s/.test(e)?`"${e}"`:e}function ee(e,t,n){i.blank(),i.error(`${t} validation failed ${v} times in a row. Pausing setup so you don't get stuck in a loop.`),i.detail(`Last error: ${n}`),i.blank(),i.detail("Your credentials are saved in `.env`. Two ways forward:"),i.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),i.blank(),console.log(` ${h.cyan(ue(e))}`),i.blank(),i.detail(` (Your .env is at ${Oe(X(e,".env"))} \u2014 open it in any text editor.)`),i.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),i.blank(),process.exit(1)}async function ns(e){let t=e.target??".",n=yo(t)?t:go(process.cwd(),t),s=bo(n);s&&(i.error("Klaudius can't be installed inside a protected system folder."),i.detail(`Path: ${n}`),i.detail(`Reason: ${s}`),i.blank(),i.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),i.blank(),process.platform==="win32"?(i.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${h.cyan("cd $HOME\\Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)):(i.detail("For example:"),console.log(` ${h.cyan("cd ~/Documents")}`),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`)),i.blank(),process.exit(1)),process.platform==="win32"&&_o()&&(i.warn("You appear to be running in an elevated (Administrator) PowerShell."),i.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),i.blank()),await ct("init",Zn);let o=await Eo(n);if(o.kind==="scaffolded"){i.blank(),i.warn(`Found an existing Klaudius project at ${h.bold(n)}.`),i.detail("(Your .env and project files are in place.)"),i.blank(),o.nodeModulesMissing?(i.detail("It looks like a previous setup didn't finish installing dependencies."),i.detail("To pick up where it left off, run:"),i.blank(),n!==process.cwd()&&console.log(` ${h.cyan(`cd ${At(t)}`)}`),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retries npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Everything is scaffolded and dependencies look installed."),i.detail("Pick the action you wanted:"),i.blank(),console.log(` ${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")}`),i.blank()),i.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),i.blank();return}if(o.kind==="occupied"){let f=t===".",g=await Ao(n);if(g.length>0){i.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),i.detail(`You're in: ${Oe(n)}`),i.blank();for(let m of g)i.detail(m.finished?`Found a finished project at ${Oe(m.path)}. To work in it:`:`Found an unfinished setup at ${Oe(m.path)}. To pick up where it left off:`),i.blank(),m.finished?(console.log(` ${h.cyan(`cd ${Oe(m.path)}`)}`),console.log(` ${h.cyan("claude")} ${h.dim("# open Claude Code in the project")}`)):console.log(` ${h.cyan(ue(m.path))} ${h.dim("# then pick Resume")}`),i.blank();process.exit(1)}i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),i.blank(),f?(i.detail("Two ways forward:"),i.blank(),i.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${h.cyan("npx klaudius@latest init my-agency")}`),i.blank(),i.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")}`)):(i.detail(`The folder '${t}' already exists and isn't empty.`),i.detail("Either pick a different name:"),console.log(` ${h.cyan(`npx klaudius@latest init ${t}-2`)}`),i.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=null;e.answers&&(H=!0,a=await wo(e.answers),i.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let r=e.license??a?.KLAUDIUS_LICENSE_KEY;H&&(!r||r.trim().length===0)&&U("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let c=await So(r),l=P.spinner();l.start("Validating license");let p=await Hn(c);p.ok||(l.stop(`License invalid: ${p.reason??"unknown"}`,2),i.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),H&&U("license",`${p.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)),l.stop(`License valid (${p.tier??"core"} tier)`);let u=await be();u.ok||(i.error(u.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${ue(n)}`),process.exit(1)),await gt();let k=ce();k.ok||(i.error(k.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${ue(n)}`),process.exit(1));let d,S=!1;if(a){let f=st(a);f||U("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=f,i.success("Loaded setup answers (non-interactive mode)")}else if(o.kind==="partial")if(await Po(n)==="resume"){let g=await Dt(o.envPath,"utf-8"),m=st(K(g));m?(i.success("Resuming with values from your existing .env"),i.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),d=m,S=!0,d.aiPlan||(d=await N(d,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
|
|
30
30
|
runs on. It sets the QA-pass default (and the model on ChatGPT Plus).`}))):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),d=await N())}else{let g=await Dt(o.envPath,"utf-8"),m=st(K(g));d=await N(m??{})}else d=await N();d.licenseKey=c,await M(n,d),S||(i.success("Saved .env"),i.success(d.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let f=1;;f++){let g=P.spinner();g.start("Validating Supabase credentials");let m=await Ie({url:d.supabaseUrl,serviceKey:d.supabaseServiceKey});if(m.ok){g.stop("Supabase credentials accepted");break}g.stop(m.message??"Supabase check failed",2),f>=v&&ee(n,"Supabase",m.message??"Supabase check failed");let A=m.message??"Supabase check failed";i.blank(),H&&U("supabase",A),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${f+1} of ${v})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),d=await N(d,{onlySection:"supabase",banner:`Supabase rejected your credentials:
|
|
31
31
|
${A}
|
|
32
32
|
|
|
@@ -98,7 +98,7 @@ password. Your browser will open to Microsoft's sign-in page \u2014
|
|
|
98
98
|
sign in as `+(d.emailAddress??"your outreach mailbox")+` and approve.
|
|
99
99
|
(No browser on this machine? It falls back to a short code you can
|
|
100
100
|
enter from any device.)`)),i.blank();let f=await q();if(f){let[g,...m]=f.command,A=Ut(g,[...m,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});A.status===0?i.success("Outlook mailbox connected."):(i.blank(),console.log(h.yellow(`The Microsoft sign-in didn't complete (exit ${A.status??"signalled"}). Setup continues without it.`)),w(f))}else console.log(h.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),w(null)}else ke&&!$e&&(i.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")));i.blank();let x=[...R,...B?["schema"]:[]];if(x.length>0){P.outro(h.yellow(h.bold(`Setup paused \u2014 ${x.join(", ")} failed.`))),console.log(h.dim("Your credentials and project files are all saved.")),i.blank();for(let[D,Ke]of Object.entries(_))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${Ke}`)),i.blank();let f=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${At(e.target)}`)}
|
|
101
|
-
`:"",g=d.aiAgent==="codex"?"codex":"claude",m=d.aiAgent==="codex"?"Codex":"Claude Code",A=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:`)),i.blank(),f&&process.stdout.write(f),console.log(` ${h.cyan(g)} ${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."`)),i.blank(),console.log(h.dim(` (Don't have ${m} yet? Install with: \`${A}\`)`)),i.blank(),console.log(h.dim("Or do it yourself:")),i.blank(),f&&process.stdout.write(f),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")}`),i.blank()),B&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(ae)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.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 ${To()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),i.blank());let L=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if(L.length>0){let D=L.length===1?"keeps":"keep";console.log(h.dim(`If ${L.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`.")),i.blank()}y&&(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.")),i.blank()),console.log(h.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Io(d,n,e.target),y){let f=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 ${f}:`)),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&&(i.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.`))),i.blank()}}async function M(e,t){await Mt(e,{recursive:!0}),await Nt(X(e,".env"),et(t),"utf-8"),t.aiAgent==="codex"?(await Mt(X(e,".codex"),{recursive:!0}),await Nt(X(e,".codex","config.toml"),nt(t),"utf-8")):(await Nt(X(e,".mcp.json"),tt(t),"utf-8"),await wt(e,"supabase"))}async function Eo(e){try{(await Ht(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ts(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(c=>s.has(c)),a=n.includes(".env"),r=t.includes(".klaudius");if(o&&a&&!r)return{kind:"partial",envPath:X(e,".env")};if(r&&a){let c=!0;try{c=!(await Ht(X(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function Po(e){i.blank(),i.warn(`Found a partial setup at ${h.bold(e)}.`),i.detail(`A previous init wrote ${h.bold(".env")} but didn't finish scaffolding.`),i.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 So(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 bo(e){let t=ko(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let s of n)if(t.startsWith(s))return`Inside ${s.slice(0,-1)} (system-managed directory).`}}function _o(){if(process.platform!=="win32")return!1;try{return Ut("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function To(){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 Io(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(h.green(h.bold("Project ready."))),e.aiPlan){let a=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${Ye[e.aiPlan]}`),console.log(h.dim(a?` \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\`.`)),i.blank()}if(console.log(h.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let a=`cd ${At(n)}`;console.log(` ${h.cyan(a)}${" ".repeat(Math.max(1,27-a.length))}${h.dim("# go into your project folder")}`)}console.log(` ${h.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${h.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(h.bold(`Some starter prompts for ${o}:`)),i.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."`)}`),i.blank(),console.log(` ${h.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.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.")),i.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")),i.blank())}import{access as Co,readFile as Ro}from"fs/promises";import{join as Ft,resolve as xo}from"path";import V from"picocolors";async function is(e){let t=e.target?xo(process.cwd(),e.target):process.cwd(),n=await ss(Ft(t,".env")),s=await ss(Ft(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{K(await Ro(Ft(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let a=await mt(t);i.blank(),i.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let r=[];if(a.npm==="failed"&&r.push("npm"),a.pip==="failed"&&r.push("pip"),a.playwright==="failed"&&r.push("playwright"),a.patchright==="failed"&&r.push("patchright"),r.length===0){i.blank(),console.log(V.green(V.bold("All dependencies installed."))),console.log(V.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(V.yellow(V.bold(`${r.join(", ")} still failing.`))),i.blank();for(let[u,k]of Object.entries(a.hints??{}))console.log(V.yellow(`Likely cause of ${u} failure:`)),console.log(V.dim(` ${k}`)),i.blank();let c=o==="codex"?"codex":"claude",l=o==="codex"?"Codex":"Claude Code",p=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(V.dim("Options:")),console.log(V.dim(` \u2022 Open ${l} in this folder (\`${c}\`) and paste:`)),console.log(V.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(V.dim(` (Don't have ${l} yet? Install with: \`${p}\`)`)),console.log(V.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(V.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function ss(e){try{return await Co(e),!0}catch{return!1}}import{readFile as Oo,writeFile as jt,access as vo}from"fs/promises";import{join as ve}from"path";import*as te from"@clack/prompts";import oe from"picocolors";import{mkdir as $o}from"fs/promises";import{spawnSync as os}from"child_process";async function as(e){let t=e.projectRoot??process.cwd(),n=ve(t,".env"),s=ve(t,".mcp.json"),o=ve(t,".codex","config.toml"),a=await Kt(ve(t,".klaudius","manifest.json")),r=await Kt(n);!a&&!r&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ce();c.ok||(i.error(c.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let l={};try{let S=await Oo(n,"utf-8");l=K(S)}catch{i.warn("No .env found. Starting from an empty configuration.")}let p=gn(l);Object.keys(l).length>0&&(p.pipelineModes??=["classic"]),te.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await N(p),k=p.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==k&&(i.error(`Switching AI coding agent (${k} \u2192 ${u.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${oe.cyan("npx klaudius@latest init <new-folder>")} ${oe.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==l.SUPABASE_URL||u.supabaseServiceKey!==l.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let S=await Ie({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});S.ok||(i.error(S.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let d=le(u.googlePlacesApiKey??"");if(d.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let S=await Ce(u.googlePlacesApiKey);if(S.ok){if(d.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let y of d.repairs)i.detail(` ${y}`);i.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=d.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(S.message??"Google rejected the Google Places API key"),i.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),i.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Lo(u,l)){let S=te.spinner();S.start("Validating email credentials (SMTP + IMAP)");let y=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:we(u.emailSmtpHost),E=await ie({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:y?J[y].usesAccountPassword:void 0});E.ok?S.stop("Email credentials accepted (SMTP + IMAP)"):(S.stop(E.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(E.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await jt(n,et(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await $o(ve(t,".codex"),{recursive:!0}),await jt(o,nt(u),"utf-8"),i.success("Updated .codex/config.toml")):(await jt(s,tt(u),"utf-8"),i.success("Updated .mcp.json"),await wt(t,"supabase")),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let S=await q();if(!(S!==null&&os(S.command[0],[...S.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!S)i.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),i.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let E=await te.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});te.isCancel(E)||!E?i.detail(`Skipped. Connect it any time with: ${S.command.join(" ")} scripts/ms_oauth.py login`):os(S.command[0],[...S.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?i.success("Outlook mailbox connected."):(i.warn("The Microsoft sign-in didn't complete."),i.detail(`Connect it any time with: ${S.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),te.outro(oe.green("Configuration updated.")),await No(t,a)}function Lo(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([s])=>s===void 0||s==="")?!1:n.some(([s,o])=>String(s)!==(t[o]??""))}async function No(e,t){let n=await Kt(ve(e,"node_modules"));i.blank(),t?n||(i.detail("Your project files are in place but dependencies aren't installed yet."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${oe.cyan("npx klaudius@latest install")} ${oe.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${oe.cyan("npx klaudius@latest doctor")} ${oe.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${oe.cyan("npx klaudius@latest init")} ${oe.dim("# pick Resume when prompted")}`),i.blank())}async function Kt(e){try{return await vo(e),!0}catch{return!1}}import{copyFile as rs,mkdir as Gt,readFile as Et,rm as pe,writeFile as Pt,access as ls}from"fs/promises";import{dirname as Bt,join as $}from"path";import{tmpdir as Mo}from"os";import*as fe from"@clack/prompts";import De from"picocolors";var He="0.30.2";async function cs(e){let t=e.projectRoot??process.cwd(),n=await En(t);n||(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let w of it)delete n.files[w];let s,o=$(t,".env"),a,r;try{a=await Et(o,"utf-8"),r=K(a)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=r.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=e.check?null:mn(a,r,hn);c!==null&&(await Pt(o,c,"utf-8"),i.detail("Backfilled new env keys")),await ct("update",He),fe.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${He}`),await gt();let p=r.AI_AGENT==="codex"?"codex":"claude-code",u=$(Mo(),`klaudius-update-${process.pid}-${Date.now()}`),k;try{i.heading("Downloading the latest Klaudius template");let w=await at({licenseKey:s,machineId:Me(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});i.success(`Fetched ${w.filesExtracted} canonical files`),k=u}catch(w){i.error(w.message),i.detail("Update aborted. Your project is unchanged."),await pe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await Do(k,t,n);if(e.check){let w=d.filter(f=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(f.state)),x=d.filter(f=>["conflict","locally-deleted","removed-modified"].includes(f.state));i.blank(),w.length===0?fe.outro(De.green("Already up to date.")):(i.detail(`${Y(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),fe.outro(De.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${w.length===0?"current":"behind"} pending=${w.length} conflicts=${x.length}`),await pe(u,{recursive:!0,force:!0}).catch(()=>{});return}let S=!1,y=d.find(w=>w.path===".gitignore"&&w.state==="conflict");if(y){let w=$(t,".gitignore"),x=await Et(w,"utf-8"),f=await Et($(k,".gitignore"),"utf-8"),{merged:g,added:m}=Ho(x,f);m.length>0&&await Pt(w,g,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",S=!0,i.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${Y(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let E=d.filter(w=>w.state==="new"),b=d.filter(w=>w.state==="clean-update"),C=d.filter(w=>w.state==="user-only"),B=d.filter(w=>w.state==="conflict"),ae=d.filter(w=>w.state==="no-change"),R=d.filter(w=>w.state==="locally-deleted"),_=d.filter(w=>w.state==="removed-clean"),re=d.filter(w=>w.state==="removed-modified"),j=[...B,...R,...re],ke=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${Y(ae.length,"file")} unchanged`),i.detail(`${Y(E.length,"new file")}`),i.detail(`${Y(b.length,"file")} updated cleanly (no local edits)`),i.detail(`${Y(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${Y(_.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${Y(B.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${Y(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${Y(re.length,"file")} removed upstream but edited locally (need your decision)`),ke>0&&(i.detail(`${Y(ke,"file")} kept deleted (previously resolved \u2014 skipped)`),ke<=10))for(let w of n.ignored)i.detail(` kept deleted: ${w}`);let $e=async()=>{let w=!1,x=f=>pe(f,{recursive:!0,force:!0}).catch(()=>{w=!0});await x($(t,".klaudius","incoming")),await x($(t,rt)),await x($(t,".klaudius","conflicts.md")),w&&i.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(E.length===0&&b.length===0&&_.length===0&&j.length===0&&!S){await $e(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=He,await Ne(t,n)),i.blank(),fe.outro(De.green("Already up to date.")),await pe(u,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let w of[...E,...b]){let x=$(k,w.path),f=$(t,w.path);await Gt(Bt(f),{recursive:!0}),await rs(x,f),n.files[w.path]=w.canonicalHash}E.length+b.length>0&&i.success(`Wrote ${Y(E.length+b.length,"file")}`);for(let w of _){let x=$(t,w.path);await pe(x,{force:!0}),delete n.files[w.path]}if(_.length>0&&i.success(`Deleted ${Y(_.length,"file")} removed upstream`),j.length>0){i.blank(),i.heading(`${j.length} conflict(s) need resolution`);let w=$(t,".klaudius","incoming");try{await pe(w,{recursive:!0,force:!0})}catch{}for(let m of[...B,...R]){let A=$(k,m.path),T=$(w,m.path);await Gt(Bt(T),{recursive:!0}),await rs(A,T)}let x=new Map,f=new Map;for(let m of B){let A=await On(t,m.path),T=await vn(t,m.path),L=await Et($(k,m.path),"utf-8"),D=$n(A,T,L,m.manifestHash);D!==null?(f.set(m.path,D),x.set(m.path,Ln(D,L))):A!==null&&(Te(A)||Te(L))?x.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):A===null?x.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._"]):x.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 g=$(t,rt);try{await pe(g,{recursive:!0,force:!0})}catch{}for(let[m,A]of f){let T=$(g,m);await Gt(Bt(T),{recursive:!0}),await Pt(T,A,"utf-8")}await Pt($(t,".klaudius","conflicts.md"),Uo(j,n.templateVersion,He,x,f),"utf-8"),B.length+R.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),f.size>0&&i.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=He,j.length===0?(delete n.pendingConflicts,await $e()):n.pendingConflicts=j.length,await Ne(t,n);try{await lt(t,k,await ge(k))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),j.length===0)fe.outro(De.green("Update complete."));else{let w=p==="codex"?"Codex":"Claude Code";fe.outro(De.yellow(`${j.length} conflict(s) staged. Open ${w} in this project and ask:
|
|
101
|
+
`:"",g=d.aiAgent==="codex"?"codex":"claude",m=d.aiAgent==="codex"?"Codex":"Claude Code",A=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:`)),i.blank(),f&&process.stdout.write(f),console.log(` ${h.cyan(g)} ${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."`)),i.blank(),console.log(h.dim(` (Don't have ${m} yet? Install with: \`${A}\`)`)),i.blank(),console.log(h.dim("Or do it yourself:")),i.blank(),f&&process.stdout.write(f),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")}`),i.blank()),B&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(ae)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.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 ${To()}`)),console.log(h.dim("and open a fresh Terminal before retrying.")),i.blank());let L=["npm","playwright","patchright"].filter(D=>R.includes(D)&&!_[D]);if(L.length>0){let D=L.length===1?"keeps":"keep";console.log(h.dim(`If ${L.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`.")),i.blank()}y&&(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.")),i.blank()),console.log(h.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Io(d,n,e.target),y){let f=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 ${f}:`)),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&&(i.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.`))),i.blank()}}async function M(e,t){await Mt(e,{recursive:!0}),await Nt(X(e,".env"),et(t),"utf-8"),t.aiAgent==="codex"?(await Mt(X(e,".codex"),{recursive:!0}),await Nt(X(e,".codex","config.toml"),nt(t),"utf-8")):(await Nt(X(e,".mcp.json"),tt(t),"utf-8"),await wt(e,"supabase"))}async function Eo(e){try{(await Ht(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await ts(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(c=>s.has(c)),a=n.includes(".env"),r=t.includes(".klaudius");if(o&&a&&!r)return{kind:"partial",envPath:X(e,".env")};if(r&&a){let c=!0;try{c=!(await Ht(X(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function Po(e){i.blank(),i.warn(`Found a partial setup at ${h.bold(e)}.`),i.detail(`A previous init wrote ${h.bold(".env")} but didn't finish scaffolding.`),i.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 So(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 bo(e){let t=ko(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let s of n)if(t.startsWith(s))return`Inside ${s.slice(0,-1)} (system-managed directory).`}}function _o(){if(process.platform!=="win32")return!1;try{return Ut("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function To(){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 Io(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(P.outro(h.green(h.bold("Project ready."))),e.aiPlan){let a=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${Ye[e.aiPlan]}`),console.log(h.dim(a?` \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\`.`)),i.blank()}if(console.log(h.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let a=`cd ${At(n)}`;console.log(` ${h.cyan(a)}${" ".repeat(Math.max(1,27-a.length))}${h.dim("# go into your project folder")}`)}console.log(` ${h.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${h.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(h.bold(`Some starter prompts for ${o}:`)),i.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."`)}`),i.blank(),console.log(` ${h.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.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.")),i.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")),i.blank())}import{access as Co,readFile as Ro}from"fs/promises";import{join as Ft,resolve as xo}from"path";import V from"picocolors";async function is(e){let t=e.target?xo(process.cwd(),e.target):process.cwd(),n=await ss(Ft(t,".env")),s=await ss(Ft(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{K(await Ro(Ft(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let a=await mt(t);i.blank(),i.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let r=[];if(a.npm==="failed"&&r.push("npm"),a.pip==="failed"&&r.push("pip"),a.playwright==="failed"&&r.push("playwright"),a.patchright==="failed"&&r.push("patchright"),r.length===0){i.blank(),console.log(V.green(V.bold("All dependencies installed."))),console.log(V.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(V.yellow(V.bold(`${r.join(", ")} still failing.`))),i.blank();for(let[u,k]of Object.entries(a.hints??{}))console.log(V.yellow(`Likely cause of ${u} failure:`)),console.log(V.dim(` ${k}`)),i.blank();let c=o==="codex"?"codex":"claude",l=o==="codex"?"Codex":"Claude Code",p=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(V.dim("Options:")),console.log(V.dim(` \u2022 Open ${l} in this folder (\`${c}\`) and paste:`)),console.log(V.cyan(` "Finish my Klaudius install \u2014 ${r.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(V.dim(` (Don't have ${l} yet? Install with: \`${p}\`)`)),console.log(V.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(V.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function ss(e){try{return await Co(e),!0}catch{return!1}}import{readFile as Oo,writeFile as jt,access as vo}from"fs/promises";import{join as ve}from"path";import*as te from"@clack/prompts";import oe from"picocolors";import{mkdir as $o}from"fs/promises";import{spawnSync as os}from"child_process";async function as(e){let t=e.projectRoot??process.cwd(),n=ve(t,".env"),s=ve(t,".mcp.json"),o=ve(t,".codex","config.toml"),a=await Kt(ve(t,".klaudius","manifest.json")),r=await Kt(n);!a&&!r&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ce();c.ok||(i.error(c.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let l={};try{let S=await Oo(n,"utf-8");l=K(S)}catch{i.warn("No .env found. Starting from an empty configuration.")}let p=gn(l);Object.keys(l).length>0&&(p.pipelineModes??=["classic"]),te.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await N(p),k=p.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==k&&(i.error(`Switching AI coding agent (${k} \u2192 ${u.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${oe.cyan("npx klaudius@latest init <new-folder>")} ${oe.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==l.SUPABASE_URL||u.supabaseServiceKey!==l.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let S=await Ie({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});S.ok||(i.error(S.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let d=le(u.googlePlacesApiKey??"");if(d.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let S=await Ce(u.googlePlacesApiKey);if(S.ok){if(d.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let y of d.repairs)i.detail(` ${y}`);i.detail("These come from keys that were transcribed rather than copied.")}u.googlePlacesApiKey=d.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(S.message??"Google rejected the Google Places API key"),i.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),i.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Lo(u,l)){let S=te.spinner();S.start("Validating email credentials (SMTP + IMAP)");let y=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:we(u.emailSmtpHost),E=await ie({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:y?J[y].usesAccountPassword:void 0});E.ok?S.stop("Email credentials accepted (SMTP + IMAP)"):(S.stop(E.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(E.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await jt(n,et(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await $o(ve(t,".codex"),{recursive:!0}),await jt(o,nt(u),"utf-8"),i.success("Updated .codex/config.toml")):(await jt(s,tt(u),"utf-8"),i.success("Updated .mcp.json"),await wt(t,"supabase")),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let S=await q();if(!(S!==null&&os(S.command[0],[...S.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!S)i.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),i.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let E=await te.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});te.isCancel(E)||!E?i.detail(`Skipped. Connect it any time with: ${S.command.join(" ")} scripts/ms_oauth.py login`):os(S.command[0],[...S.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?i.success("Outlook mailbox connected."):(i.warn("The Microsoft sign-in didn't complete."),i.detail(`Connect it any time with: ${S.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),te.outro(oe.green("Configuration updated.")),await No(t,a)}function Lo(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([s])=>s===void 0||s==="")?!1:n.some(([s,o])=>String(s)!==(t[o]??""))}async function No(e,t){let n=await Kt(ve(e,"node_modules"));i.blank(),t?n||(i.detail("Your project files are in place but dependencies aren't installed yet."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${oe.cyan("npx klaudius@latest install")} ${oe.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${oe.cyan("npx klaudius@latest doctor")} ${oe.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${oe.cyan("npx klaudius@latest init")} ${oe.dim("# pick Resume when prompted")}`),i.blank())}async function Kt(e){try{return await vo(e),!0}catch{return!1}}import{copyFile as rs,mkdir as Gt,readFile as Et,rm as pe,writeFile as Pt,access as ls}from"fs/promises";import{dirname as Bt,join as $}from"path";import{tmpdir as Mo}from"os";import*as fe from"@clack/prompts";import De from"picocolors";var He="0.30.3";async function cs(e){let t=e.projectRoot??process.cwd(),n=await En(t);n||(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let w of it)delete n.files[w];let s,o=$(t,".env"),a,r;try{a=await Et(o,"utf-8"),r=K(a)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=r.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=e.check?null:mn(a,r,hn);c!==null&&(await Pt(o,c,"utf-8"),i.detail("Backfilled new env keys")),await ct("update",He),fe.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${He}`),await gt();let p=r.AI_AGENT==="codex"?"codex":"claude-code",u=$(Mo(),`klaudius-update-${process.pid}-${Date.now()}`),k;try{i.heading("Downloading the latest Klaudius template");let w=await at({licenseKey:s,machineId:Me(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});i.success(`Fetched ${w.filesExtracted} canonical files`),k=u}catch(w){i.error(w.message),i.detail("Update aborted. Your project is unchanged."),await pe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await Do(k,t,n);if(e.check){let w=d.filter(f=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(f.state)),x=d.filter(f=>["conflict","locally-deleted","removed-modified"].includes(f.state));i.blank(),w.length===0?fe.outro(De.green("Already up to date.")):(i.detail(`${Y(w.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),fe.outro(De.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${w.length===0?"current":"behind"} pending=${w.length} conflicts=${x.length}`),await pe(u,{recursive:!0,force:!0}).catch(()=>{});return}let S=!1,y=d.find(w=>w.path===".gitignore"&&w.state==="conflict");if(y){let w=$(t,".gitignore"),x=await Et(w,"utf-8"),f=await Et($(k,".gitignore"),"utf-8"),{merged:g,added:m}=Ho(x,f);m.length>0&&await Pt(w,g,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",S=!0,i.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${Y(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let E=d.filter(w=>w.state==="new"),b=d.filter(w=>w.state==="clean-update"),C=d.filter(w=>w.state==="user-only"),B=d.filter(w=>w.state==="conflict"),ae=d.filter(w=>w.state==="no-change"),R=d.filter(w=>w.state==="locally-deleted"),_=d.filter(w=>w.state==="removed-clean"),re=d.filter(w=>w.state==="removed-modified"),j=[...B,...R,...re],ke=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${Y(ae.length,"file")} unchanged`),i.detail(`${Y(E.length,"new file")}`),i.detail(`${Y(b.length,"file")} updated cleanly (no local edits)`),i.detail(`${Y(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${Y(_.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${Y(B.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${Y(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${Y(re.length,"file")} removed upstream but edited locally (need your decision)`),ke>0&&(i.detail(`${Y(ke,"file")} kept deleted (previously resolved \u2014 skipped)`),ke<=10))for(let w of n.ignored)i.detail(` kept deleted: ${w}`);let $e=async()=>{let w=!1,x=f=>pe(f,{recursive:!0,force:!0}).catch(()=>{w=!0});await x($(t,".klaudius","incoming")),await x($(t,rt)),await x($(t,".klaudius","conflicts.md")),w&&i.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/ and .klaudius/conflicts.md by hand)")};if(E.length===0&&b.length===0&&_.length===0&&j.length===0&&!S){await $e(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=He,await Ne(t,n)),i.blank(),fe.outro(De.green("Already up to date.")),await pe(u,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let w of[...E,...b]){let x=$(k,w.path),f=$(t,w.path);await Gt(Bt(f),{recursive:!0}),await rs(x,f),n.files[w.path]=w.canonicalHash}E.length+b.length>0&&i.success(`Wrote ${Y(E.length+b.length,"file")}`);for(let w of _){let x=$(t,w.path);await pe(x,{force:!0}),delete n.files[w.path]}if(_.length>0&&i.success(`Deleted ${Y(_.length,"file")} removed upstream`),j.length>0){i.blank(),i.heading(`${j.length} conflict(s) need resolution`);let w=$(t,".klaudius","incoming");try{await pe(w,{recursive:!0,force:!0})}catch{}for(let m of[...B,...R]){let A=$(k,m.path),T=$(w,m.path);await Gt(Bt(T),{recursive:!0}),await rs(A,T)}let x=new Map,f=new Map;for(let m of B){let A=await On(t,m.path),T=await vn(t,m.path),L=await Et($(k,m.path),"utf-8"),D=$n(A,T,L,m.manifestHash);D!==null?(f.set(m.path,D),x.set(m.path,Ln(D,L))):A!==null&&(Te(A)||Te(L))?x.set(m.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+m.path+"` directly._"]):A===null?x.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._"]):x.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 g=$(t,rt);try{await pe(g,{recursive:!0,force:!0})}catch{}for(let[m,A]of f){let T=$(g,m);await Gt(Bt(T),{recursive:!0}),await Pt(T,A,"utf-8")}await Pt($(t,".klaudius","conflicts.md"),Uo(j,n.templateVersion,He,x,f),"utf-8"),B.length+R.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),f.size>0&&i.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=He,j.length===0?(delete n.pendingConflicts,await $e()):n.pendingConflicts=j.length,await Ne(t,n);try{await lt(t,k,await ge(k))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),j.length===0)fe.outro(De.green("Update complete."));else{let w=p==="codex"?"Codex":"Claude Code";fe.outro(De.yellow(`${j.length} conflict(s) staged. Open ${w} in this project and ask:
|
|
102
102
|
"Run /resolve-conflicts"`))}await pe(u,{recursive:!0,force:!0}).catch(()=>{})}async function Do(e,t,n){let s=await ge(e),o=new Set(s),a=new Set(n.ignored??[]),r=[];for(let c of s){if(a.has(c))continue;let l=await _e($(e,c)),p=n.files[c],u=$(t,c),k;try{await ls(u),k=await _e(u)}catch{let d=p!==void 0&&!An.has(c)?"locally-deleted":"new";r.push({path:c,state:d,canonicalHash:l,manifestHash:p});continue}l===p?k===p?r.push({path:c,state:"no-change",canonicalHash:l,localHash:k,manifestHash:p}):r.push({path:c,state:"user-only",canonicalHash:l,localHash:k,manifestHash:p}):k===p?r.push({path:c,state:"clean-update",canonicalHash:l,localHash:k,manifestHash:p}):r.push({path:c,state:"conflict",canonicalHash:l,localHash:k,manifestHash:p})}for(let c of Object.keys(n.files)){if(o.has(c))continue;let l=n.files[c],p=$(t,c),u;try{await ls(p),u=await _e(p)}catch{delete n.files[c];continue}u===l?r.push({path:c,state:"removed-clean",localHash:u,manifestHash:l}):r.push({path:c,state:"removed-modified",localHash:u,manifestHash:l})}return r}function Y(e,t){return`${e} ${t}${e===1?"":"s"}`}function Ho(e,t){let n=e.includes(`\r
|
|
103
103
|
`)?`\r
|
|
104
104
|
`:`
|
|
@@ -118,11 +118,11 @@ except Exception as e:
|
|
|
118
118
|
`));let a=ca(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(a.status===0){console.log(G.green(`Paired '${o}'.`)),console.log(G.dim(`
|
|
119
119
|
If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
120
120
|
WHATSAPP_ACCOUNTS=primary,${o}
|
|
121
|
-
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}a.error?console.error(G.red(`Pair failed: ${a.error.message}`)):(console.error(G.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(G.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(G.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(G.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as Fe,spawn as pa}from"child_process";import{existsSync as je,mkdirSync as ys,rmSync as ks,mkdtempSync as ws}from"fs";import{homedir as Yt,tmpdir as As}from"os";import{join as z}from"path";import he from"picocolors";var fa=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function hs(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win.zip"}async function Es(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1));let t=ha();if(t&&!e.reinstall&&!e.from){gs(),console.log(he.green("Opened the Klaudius app.")),ms();return}let n=await ga(e.from);console.log(he.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?ya(n):ka(n),gs(),console.log(he.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),ms()}function ms(){process.platform==="darwin"?console.log(he.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(he.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function St(){return z(Yt(),"Applications","Klaudius.app")}function Wt(){return z(process.env.LOCALAPPDATA??z(Yt(),"AppData","Local"),"Klaudius")}function ha(){return process.platform==="darwin"?je(St()):je(z(Wt(),"app","Klaudius.exe"))}async function ma(){try{let{readFileSync:e}=await import("fs"),n=e(z(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function ga(e){if(e)return je(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await ma();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=`${fa}?file=${encodeURIComponent(hs())}`,s=z(ws(z(As(),"klaudius-app-")),hs());console.log(he.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.30.
|
|
121
|
+
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}a.error?console.error(G.red(`Pair failed: ${a.error.message}`)):(console.error(G.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(G.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(G.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(G.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as Fe,spawn as pa}from"child_process";import{existsSync as je,mkdirSync as ys,rmSync as ks,mkdtempSync as ws}from"fs";import{homedir as Yt,tmpdir as As}from"os";import{join as z}from"path";import he from"picocolors";var fa=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function hs(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win.zip"}async function Es(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1));let t=ha();if(t&&!e.reinstall&&!e.from){gs(),console.log(he.green("Opened the Klaudius app.")),ms();return}let n=await ga(e.from);console.log(he.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?ya(n):ka(n),gs(),console.log(he.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),ms()}function ms(){process.platform==="darwin"?console.log(he.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(he.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function St(){return z(Yt(),"Applications","Klaudius.app")}function Wt(){return z(process.env.LOCALAPPDATA??z(Yt(),"AppData","Local"),"Klaudius")}function ha(){return process.platform==="darwin"?je(St()):je(z(Wt(),"app","Klaudius.exe"))}async function ma(){try{let{readFileSync:e}=await import("fs"),n=e(z(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function ga(e){if(e)return je(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await ma();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=`${fa}?file=${encodeURIComponent(hs())}`,s=z(ws(z(As(),"klaudius-app-")),hs());console.log(he.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.30.3"}});if(!o.ok){let c=`HTTP ${o.status}`;try{let l=await o.json();l.reason&&(c=l.reason)}catch{}throw new Error(c)}let a=Buffer.from(await o.arrayBuffer()),{writeFileSync:r}=await import("fs");return r(s,a),s}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 ya(e){let t=z(Yt(),"Applications");ys(t,{recursive:!0});let n=ws(z(As(),"klaudius-app-x-")),s=Fe("ditto",["-xk",e,n],{stdio:"pipe"});s.status!==0&&(console.error(`Couldn't extract the app: ${s.stderr?.toString().trim()}`),process.exit(1));let o=z(n,"Klaudius.app");je(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),ks(St(),{recursive:!0,force:!0});let a=Fe("mv",[o,St()],{stdio:"pipe"});a.status!==0&&(console.error(`Couldn't install to ~/Applications: ${a.stderr?.toString().trim()}`),process.exit(1))}function ka(e){let t=Wt(),n=z(t,"app");ks(n,{recursive:!0,force:!0}),ys(n,{recursive:!0});let s=Fe("powershell.exe",["-NoProfile","-Command",`Expand-Archive -LiteralPath '${e}' -DestinationPath '${n}' -Force`],{stdio:"pipe"});s.status!==0&&(console.error(`Couldn't extract the app: ${s.stderr?.toString().trim()}`),process.exit(1));let o=z(n,"Klaudius.exe");je(o)||(console.error("Archive didn't contain Klaudius.exe \u2014 is this the right file?"),process.exit(1));let a=`
|
|
122
122
|
$W = New-Object -ComObject WScript.Shell
|
|
123
123
|
foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetFolderPath('Desktop'))) {
|
|
124
124
|
$S = $W.CreateShortcut((Join-Path $dir 'Klaudius.lnk'))
|
|
125
125
|
$S.TargetPath = '${o}'
|
|
126
126
|
$S.WorkingDirectory = '${n}'
|
|
127
127
|
$S.Save()
|
|
128
|
-
}`;Fe("powershell.exe",["-NoProfile","-Command",a],{stdio:"pipe"}).status!==0&&(console.log(he.yellow("App installed, but couldn't create shortcuts \u2014 launch it from:")),console.log(he.cyan(` ${o}`)))}function gs(){if(process.platform==="darwin")Fe("open",["-a",St()],{stdio:"pipe"});else{let e=z(Wt(),"app","Klaudius.exe");pa(e,[],{detached:!0,stdio:"ignore"}).unref()}}import{spawnSync as wa}from"child_process";var zt="--use-system-ca";function Ps(){let e=process.env.NODE_OPTIONS??"";if(e.includes(zt)||!ce().ok)return;let n=e?`${e} ${zt}`:zt,s=wa(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});s.signal&&(process.kill(process.pid,s.signal),process.exit(1)),process.exit(s.status??1)}Ps();var Ea="0.30.
|
|
128
|
+
}`;Fe("powershell.exe",["-NoProfile","-Command",a],{stdio:"pipe"}).status!==0&&(console.log(he.yellow("App installed, but couldn't create shortcuts \u2014 launch it from:")),console.log(he.cyan(` ${o}`)))}function gs(){if(process.platform==="darwin")Fe("open",["-a",St()],{stdio:"pipe"});else{let e=z(Wt(),"app","Klaudius.exe");pa(e,[],{detached:!0,stdio:"ignore"}).unref()}}import{spawnSync as wa}from"child_process";var zt="--use-system-ca";function Ps(){let e=process.env.NODE_OPTIONS??"";if(e.includes(zt)||!ce().ok)return;let n=e?`${e} ${zt}`:zt,s=wa(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});s.signal&&(process.kill(process.pid,s.signal),process.exit(1)),process.exit(s.status??1)}Ps();var Ea="0.30.3",se=new Aa;se.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Ea);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 rn({})}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 ns({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers})}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 is({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 as({})}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 cs({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 us({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 Es({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 fs({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 ge from"react";import{render as he}from"ink";var pe=new Set(["claude-pro","codex-plus"]);function U(e){return e&&pe.has(e)?"off":"on"}var ga={"claude-pro":"Claude Pro","claude-max-5x":"Claude Max 5x","claude-max-20x":"Claude Max 20x","claude-other":"Claude (Team, Enterprise or API key)","codex-plus":"ChatGPT Plus","codex-pro":"ChatGPT Pro","codex-other":"ChatGPT (Business, Enterprise or API key)"};async function ha(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:n}=await import("./WizardApp-
|
|
61
|
+
and doesn't expose your account login.`;import ge from"react";import{render as he}from"ink";var pe=new Set(["claude-pro","codex-plus"]);function U(e){return e&&pe.has(e)?"off":"on"}var ga={"claude-pro":"Claude Pro","claude-max-5x":"Claude Max 5x","claude-max-20x":"Claude Max 20x","claude-other":"Claude (Team, Enterprise or API key)","codex-plus":"ChatGPT Plus","codex-pro":"ChatGPT Pro","codex-other":"ChatGPT (Business, Enterprise or API key)"};async function ha(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:n}=await import("./WizardApp-NDPDI7JA.js"),t=null;C("runWizard:start",{onlySection:a.onlySection,hasDefaults:Object.keys(e).length>0}),L(),await new Promise(o=>setImmediate(o)),await new Promise(o=>setTimeout(o,0)),C("runWizard:event loop drained, mounting Ink");let i=he(ge.createElement(n,{defaults:e,onlySection:a.onlySection,banner:a.banner,onComplete:o=>{C("runWizard:onComplete called",{keys:Object.keys(o).length}),t=o}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,exitOnCtrlC:!1});if(C("runWizard:render returned, awaiting exit"),await i.waitUntilExit(),C("runWizard:waitUntilExit resolved",{resultIsNull:t===null}),!t)throw new Error(`Wizard exited without completing. Diagnostic log: ${K}
|
|
62
62
|
Please share that file so we can trace what happened.`);return t}function v(e){if(!(e instanceof Error))return String(e);let a=e.cause;if(!a||!(a instanceof Error))return e.message;let n=a.code,t=a.message;return n&&t&&t!==n?`${e.message} (${n}: ${t})`:n?`${e.message} (${n})`:t?`${e.message} (${t})`:e.message}async function G(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}`;return/webhook/i.test(s)?{ok:!1,reason:"webhook_set",message:"This bot has a webhook set, so getUpdates is unavailable. Auto-detect can't run; you'll need to paste the chat ID manually."}:{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: ${v(o)}`}}let n=a.result??[];if(n.length===0)return{ok:!1,reason:"no_messages",message:"No messages yet. Send your bot a regular text message in Telegram, then retry."};let t=n[n.length-1],i=t?.message?.chat?.id??t?.edited_message?.chat?.id??t?.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 me(e){try{let a=await fetch(`https://api.telegram.org/bot${encodeURIComponent(e.botToken)}/getMe`),n=await a.json();return n.ok?{ok:!0,botHandle:n.result?.username?`@${n.result.username}`:n.result?.first_name}:{ok:!1,failedAt:"token",message:`Telegram rejected the bot token: ${n.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: ${v(a)}`}}}async function fa(e){let a=await me({botToken:e.botToken});if(!a.ok)return a;let n=a.botHandle;try{let t=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 t.json();if(!i.ok){let o=i.description??`HTTP ${t.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:n,message:`Telegram delivered the bot token check but couldn't send to chat_id ${e.chatId}: ${o}.${s}`}}}catch(t){return{ok:!1,failedAt:"chat",botHandle:n,message:`Could not reach Telegram for chat_id check: ${v(t)}`}}return{ok:!0,botHandle:n}}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/rsync 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 rsync destination like user@host:/path";if(!/^[^\s:]+:\/?.+/.test(a))return"Should look like user@host:/path (an rsync-over-SSH destination)"}function _(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 ye=[{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"]}],fe=[{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 k(e){return e.trim().toLowerCase()}function z(e){if(!e)return;let a=k(e);for(let n of ye)if(k(n.country)===a||n.aliases?.some(t=>k(t)===a))return n}function B(e){if(!e)return;let a=k(e);for(let n of fe)if(k(n.language)===a||n.aliases?.some(t=>k(t)===a))return n}var be={\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":"_"},we=/[\u200B-\u200F\u202A-\u202E\u2060\uFEFF\u00AD]/g,Ce=/[\u0000-\u001F\u007F]/g;function x(e){let a=e.replace(we,"").replace(Ce,"").trim();return{value:a,changed:a!==e,repairs:[],unrepairable:[]}}function $(e){let n=x(e).value.normalize("NFKC").replace(/\s+/g,"");n.length>=2&&(n[0]==='"'&&n.at(-1)==='"'||n[0]==="'"&&n.at(-1)==="'")&&(n=n.slice(1,-1).trim());let t=[],i=[],o="";for(let s of n){let c=s.codePointAt(0);if(c<128){o+=s;continue}let p=be[s],r=o.length+1;p?(t.push(`position ${r}: '${s}' (${ve(c)}, U+${W(c)}) \u2192 '${p}'`),o+=p):(i.push({position:r,char:s,code:c}),o+=s)}return{value:o,changed:o!==e,repairs:t,unrepairable:i}}var ke=/^AIza[0-9A-Za-z_-]{35}$/;function Se(e){return ke.test(e)}function V(e){let a=$(e);if(a.value.length===0)return"Required \u2014 without this Klaudius can't find candidates.";if(a.unrepairable.length>0){let n=a.unrepairable[0];return`Character ${n.position} of this key is '${n.char}' (U+${W(n.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 ka(e){let a=$(e).value;if(!Se(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.`}function W(e){return e.toString(16).toUpperCase().padStart(4,"0")}function ve(e){return e>=1024&&e<=1279?"Cyrillic":e>=880&&e<=1023?"Greek":"non-Latin"}var j=class extends Error{constructor(){super("user pressed back"),this.name="BackSignal"}},q=class extends Error{constructor(){super("user cancelled"),this.name="CancelSignal"}},Pe="Include the country code with a + (e.g. +12025550123 for US, +447123456789 for UK)",Z=e=>/^\+\d{8,15}$/.test(e)?void 0:Pe,Y=e=>/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e)?void 0:"Enter a valid email",f=e=>a=>a.trim().length===0?`${e} is required`:void 0,Ae=/[\u2022\u2023\u2024\u2027\u00B7\u2219\u22C5\u25CF\u25CB\u25AA\u25AB\u204E\u2217\uFE61\u25E6\u2218]/,Ie="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).",O=e=>Ae.test(e)?Ie:void 0;function Te(e){if(/^eyJ/.test(e))try{let a=e.split(".")[1];if(!a)return;let n=JSON.parse(Buffer.from(a,"base64url").toString("utf8"));return typeof n.role=="string"?n.role:void 0}catch{return}}var E=e=>a=>O(a)??(a.trim().length===0?`${e} is required`:void 0),xe=e=>{let a=e.replace(/\s+/g,"");return a.length===0?"Personal access token is required":O(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.")},Ee="one-off, no monthly fees",J="per month";function P(e){if(!e)return!0;let a=e.trim();if(a==="")return!0;let n=a.replace(/[^\d.]/g,"");if(n==="")return/^\s*free\s*$/i.test(a);let t=parseFloat(n);return!isNaN(t)&&t===0}var Oe={id:"ai-agent",title:"AI coding agent",isApplicable:()=>!0,execute:async(e,{prompt:a,info:n})=>(n({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
|
|
|
@@ -81,10 +81,10 @@ you live.
|
|
|
81
81
|
Example: if you're based in Bulgaria but want to sell websites to UK
|
|
82
82
|
businesses, pick United Kingdom here.
|
|
83
83
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
84
|
+
This becomes your home market. You can add more countries any time
|
|
85
|
+
later \u2014 just tell Klaudius ("add Singapore as a market") and runs
|
|
86
|
+
will spread across all of them, with each client's site and outreach
|
|
87
|
+
in its own market's language.`});let t="__other__",i=[{value:"the United Kingdom",label:"United Kingdom"},{value:"the United States",label:"United States"},{value:"Italy",label:"Italy"},{value:"Spain",label:"Spain"},{value:"France",label:"France"},{value:"Germany",label:"Germany"},{value:"Ireland",label:"Ireland"},{value:"the Netherlands",label:"Netherlands"},{value:"Belgium",label:"Belgium"},{value:"Portugal",label:"Portugal"},{value:"Switzerland",label:"Switzerland"},{value:"Austria",label:"Austria"},{value:"Canada",label:"Canada"},{value:"Australia",label:"Australia"},{value:"New Zealand",label:"New Zealand"},{value:"Mexico",label:"Mexico"},{value:"Brazil",label:"Brazil"},{value:"Sweden",label:"Sweden"},{value:"Poland",label:"Poland"},{value:t,label:"Other (type it in)"}],o=e.country??"",s=i.some(l=>l.value===o),p=await a({type:"select",message:"Which country's businesses will Klaudius search for?",initialValue:s?o:o?t:"the United Kingdom",options:i}),r;p===t?r=await a({type:"text",message:"Type the country name (any common form is fine)",placeholder:"e.g. South Africa, Greece, Brazil",initialValue:s?"":o,validate:l=>l.trim().length===0?"Country is required":void 0,note:{title:"Free-form country",body:`We'll match what you type against our country lookup (covers all
|
|
88
88
|
ISO 3166 sovereign states + common territories like Hong Kong and
|
|
89
89
|
Puerto Rico). If we don't recognise the name, we'll ask you to type
|
|
90
90
|
the 2-letter ISO country code directly on the next prompt \u2014 the
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klaudius",
|
|
3
|
-
"version": "0.30.
|
|
3
|
+
"version": "0.30.3",
|
|
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": {
|